dsh-sensenova-pool 1.1.0 → 1.3.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
@@ -3,6 +3,32 @@
3
3
  本文件记录本插件的所有重要变更,格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
4
4
  版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
5
5
 
6
+ ## [1.3.0] - 2026-11-27
7
+
8
+ ### 新增
9
+
10
+ - **生图与 `/v1/*` 通用接口透传**:本地回环接口不再只处理 `/v1/chat/completions`,现已支持将 `sensenova-u1.5-lite` 等生图模型使用的 `/v1/images/generations`、`/v1/images/edits`、`/v1/images/variations` 及其他合法 `/v1/*` 端点透传至上游。
11
+ - **原样请求体与多格式兼容**:透传路径直接转发原始字节与 `Content-Type`,同时兼容商汤 JSON(`images/image_url`、`watermark`、`prompt_extend` 等)与 `multipart/form-data` 二进制表单上传,不经对话请求体清洗。
12
+ - **完整复用多 Key 轮换池**:透传请求同样自动替换真实上游 Key,遇 `429` / `5xx` 自动换 Key 重发,全池限流继续对外屏蔽为 `503 + Retry-After`。
13
+ - **生图独立超时保护**:`/v1/images/*` 默认单次上游请求超时至少为 180 秒(支持 `imageRequestTimeoutMs` 覆盖),避免高分辨率出图被对话默认 60 秒超时误杀。
14
+ - **路径安全边界校验**:严格校验拼接后的上游 URL 同源且不越出基准路径,拦截 `..`、`%2e%2e`、`//` 等路径遍历与非 `/v1/` 路由。
15
+
16
+ ## [1.2.0] - 2026-11-20
17
+
18
+ ### 修复
19
+
20
+ - **中国站 / 国际站双站隔离**:设置页 Tab 只切换管理视图,不再修改共享实例上游。两站同时工作,可同时进行对话和处理外部请求。
21
+ - 分别注册 `sensenova-pool`(商汤日日新 · 中国站)与 `sensenova-pool-intl`(商汤日日新 · 国际站),会话 provider 决定请求归属,不受当前 Tab 影响。
22
+ - 两站分别维护 Key 池、模型目录、隐藏模型、上下文窗口 / 最大输出覆盖、本地外部接口及其 API Key、冷却 / 失效 / RPM 状态;切换 Tab 不重置或串用另一站状态。
23
+ - 旧配置中的自定义 `baseUrl` 只作用于配置 `endpoint` 所属站,另一站仍使用自己的官方地址,避免向错误上游发送 Key。
24
+
25
+ ### 迁移与兼容性
26
+
27
+ - 旧共享凭据仅迁移到旧记录 `endpoint` 所属站;旧记录缺少该字段时按旧配置 `endpoint` 判断,缺省中国站。旧 Key、隐藏模型、窗口设置和外部密钥不复制到另一站,另一站从空 Key 池和默认模型设置开始。
28
+ - 两站迁移后使用各自独立凭据记录;保留旧记录供回退,不删除或覆盖旧记录。
29
+ - **旧国际站会话必须重新选择国际站 provider**(`sensenova-pool-intl`)及对应模型:旧 `sensenova-pool` 现在固定属于中国站,切换设置 Tab 不会修改会话 provider。
30
+ - 修复 [#6](https://github.com/Phoeky/dsh-sensenova-pool/issues/6) 反馈的跨站模型选择混乱,感谢 @zuosus 提供反馈。
31
+
6
32
  ## [1.1.0] - 2026-11-19
7
33
 
8
34
  ### 新增
package/README.md CHANGED
@@ -21,6 +21,8 @@
21
21
 
22
22
  ---
23
23
 
24
+ > **1.2.0**:中国站和国际站现已完全隔离,各自拥有 Key 池与模型分组。旧国际站会话升级后请重新选择「商汤日日新 · 国际站」。
25
+
24
26
  ## 功能
25
27
 
26
28
  ### 🔑 多 Key 轮换池
@@ -47,31 +49,33 @@
47
49
 
48
50
  截图里的 `2/3 成功,1 次限流` 是真实发生的记录:这把 Key 触发过 1 次 429,被池子内部消化掉,上层没有收到过任何 429。
49
51
 
50
- ### 🌏 可选端点:中国站 / 国际站
52
+ ### 🌏 双站隔离:中国站 / 国际站(未发布)
51
53
 
52
- 商汤有**两个独立的 API 站**,模型、套餐、额度、key 都各自独立:
54
+ 中国站与国际站是**两个同时工作的独立实例**,不再共用一个可切换上游的池子:
53
55
 
54
- | 端点 | 地址 | 适用 |
55
- |---|---|---|
56
- | 中国站(默认) | `https://token.sensenova.cn/v1` | 在商汤国内平台申请的 key |
57
- | 国际站 | `https://token.sensenova.ai/v1` | 在国际站申请的 key |
56
+ | 站点 | 上游地址 | provider | 模型选择器显示 |
57
+ |---|---|---|---|
58
+ | 中国站 | `https://token.sensenova.cn/v1` | `sensenova-pool` | 商汤日日新 · 中国站 |
59
+ | 国际站 | `https://token.sensenova.ai/v1` | `sensenova-pool-intl` | 商汤日日新 · 国际站 |
60
+
61
+ 设置页的「中国站 / 国际站」Tab **只切换管理视图**,不会切换请求上游,不会停用另一站,也不会清掉另一站的状态。两站可以同时对话、同时服务外部客户端。
62
+
63
+ - **Key 池独立**:Key 只加入当前管理站;删除、清空、探活均不影响另一站。
64
+ - **模型目录、隐藏模型与窗口独立**:包括同名模型,各站分别刷新目录、保存可见性及上下文窗口 / 最大输出覆盖。
65
+ - **外部接口与密钥独立**:各站有自己的本地接口地址和 API Key,外部客户端须成对使用对应站的地址与密钥。
66
+ - **冷却、失效与 RPM 状态独立**:Tab 切换不重置健康状态;默认每把 Key 的本地 RPM 中国站为 2、国际站为 3。
67
+
68
+ > ⚠️ 两站 Key **互不通用**,请分别在对应 Tab 添加。国际站 Key 发到中国站(反之亦然)可能返回 401 / 403;Tab 不会替你把已有 Key 移到另一站。
58
69
 
59
- 在设置卡片最上方点一下就能切换,**无需重启 DSH**;所选端点会随 key 一起存进凭据库,
60
- 重启后仍然记得。切换会连带做四件事,缺一件状态就会自相矛盾:
70
+ #### 从旧版升级
61
71
 
62
- 1. **上游地址** —— 之后所有请求打到新站;
63
- 2. **模型目录** —— 换回该站的内置基线,再自动用新 key 刷新(中国站独有 `deepseek-*` / `glm-*`,
64
- 国际站是 5 个 `sensenova-*` 模型,含 2 个生图模型,全部列出);
65
- 3. **限流额度** —— 两个站的 RPM 分开算(本地预限流默认中国站 2、国际站 3);
66
- 4. **key 健康状态** —— 冷却/失效是针对旧站记下的,切过去时一律清掉,不带着旧标记进新站。
72
+ 旧共享凭据只迁移到**旧 `endpoint` 所属站**(旧记录没有该字段时按旧配置 `endpoint` 判断,缺省中国站),另一站 Key 池和自定义模型设置为空(模型目录从该站内置基线开始),不会复制旧 Key。原有隐藏模型、窗口覆盖和外部密钥也只由所属站继承。迁移后两站分别保存独立凭据;**保留旧记录供回退**,不删除或覆盖它。
67
73
 
68
- > ⚠️ 两个站的 key **互不通用**:拿国际站的 key 打中国站会得到 `401 Forbidden`。插件不会
69
- > 自动猜你在哪个站(猜错会把本来好用的 key 标成失效),所以端点必须自己选对 ——
70
- > 如果切过去后所有 key 都显示「已失效」,先检查是不是选错了站。
74
+ 旧版国际站会话仍可能保存 `sensenova-pool`,该 provider 现在固定指向中国站。**继续旧国际站会话前,必须重新选择「商汤日日新 · 国际站」(`sensenova-pool-intl`)及对应模型**;仅切设置 Tab 不会修改会话 provider。
71
75
 
72
76
  ### 🧠 一次接入全部模型
73
77
 
74
- 装好插件后,模型选择器里自动出现「商汤日日新(Key 轮换池)」分组,包含以下模型:
78
+ 装好插件后,模型选择器里分别出现「商汤日日新 · 中国站」和「商汤日日新 · 国际站」分组。中国站内置以下模型;国际站目录见下文常见问题:
75
79
 
76
80
  | 模型 | 上下文 | 最大输出 | 图片输入 |
77
81
  |---|---|---|---|
@@ -107,7 +111,7 @@ Key 存在 DSH 的凭据库里,不写进任何配置文件。填入即生效
107
111
 
108
112
  ### 🔌 提供对外的 OpenAI 兼容接口
109
113
 
110
- 插件在 127.0.0.1 上起一个 OpenAI 兼容服务。设置页显示接口地址和 API Key,复制后填进其他 Agent 或客户端即可使用;请求共用同一个 Key 池,遇到限流同样自动换 Key。
114
+ 插件为两站分别在 127.0.0.1 上提供独立 OpenAI 兼容服务。当前 Tab 显示该站接口地址和 API Key,复制后填进其他 Agent 或客户端即可使用;请求只共用该站的 Key 池,遇到限流同样自动换 Key。以下地址仅为中国站示例,请以各 Tab 实际显示为准。
111
115
 
112
116
  ```bash
113
117
  curl http://127.0.0.1:51234/v1/chat/completions \
@@ -179,9 +183,9 @@ pnpm --dir "$DSH_PROFILE_DIR" add "link:$PWD"
179
183
 
180
184
  ## 使用
181
185
 
182
- ### 1. 填入 Key
186
+ ### 1. 选择管理站并填入 Key
183
187
 
184
- 打开 **设置 → dsh-sensenova-pool**(或插件页里本插件的卡片),在弹出的卡片里粘贴一把或多把商汤 Key:
188
+ 打开 **设置 → dsh-sensenova-pool**(或插件页里本插件的卡片),先选中国站或国际站 Tab,再粘贴该站申请的一把或多把商汤 Key:
185
189
 
186
190
  ```
187
191
  sk-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
@@ -191,14 +195,13 @@ sk-cccccccccccccccccccccccccccccc
191
195
 
192
196
  点「**添加 Key**」。支持多种分隔方式,重复和无效项会被自动过滤。
193
197
 
194
- ### 2. 先确认端点
198
+ ### 2. 确认管理视图与上游地址
195
199
 
196
- 卡片最上方的「上游端点」区显示当前打的是哪个站 —— 中国站还是国际站。点另一个按钮即可切换,
197
- 下方会显示切换后的实际上游地址。**key 只在自己申请的那个站有效**,选错站会看到 401。
200
+ 当前 Tab 显示该站的实际上游地址。Tab 只决定你正在管理哪一站;两站仍同时工作。**Key 只在自己申请的那个站有效**,请不要将它加入另一站。
198
201
 
199
202
  ### 3. 选择模型
200
203
 
201
- 新建会话,在模型选择器里选「**商汤日日新(Key 轮换池)**」下的任意模型,然后正常对话即可。
204
+ 新建会话,在模型选择器里选「**商汤日日新 · 中国站**」或「**商汤日日新 · 国际站**」下的对应模型,然后正常对话即可。会话 provider 决定请求所属站,与设置页当前 Tab 无关。旧国际站会话须重新选择国际站 provider。
202
205
 
203
206
  ### 4. 需要时调整
204
207
 
@@ -213,11 +216,11 @@ sk-cccccccccccccccccccccccccccccc
213
216
 
214
217
  ### 5. 接入其他服务
215
218
 
216
- 设置页「本地接口」区给出两样东西:
219
+ 设置页当前站的「本地接口」区给出两样东西;另一站有独立地址和密钥,不可混用:
217
220
 
218
221
  | 字段 | 示例 | 说明 |
219
222
  |---|---|---|
220
- | 接口地址 | `http://127.0.0.1:51234/v1` | OpenAI 兼容,`/chat/completions`、`/models` 都支持,流式/非流式都行 |
223
+ | 接口地址 | `http://127.0.0.1:51234/v1` | OpenAI 兼容,支持 `/chat/completions`、`/models` 及 `/images/generations`、`/images/edits` 等 `/v1/*` 接口透传,均走多 Key 轮换 |
221
224
  | API Key | `sk-dsh-…` | 填进 `Authorization: Bearer` 即可 |
222
225
 
223
226
  任何 OpenAI 客户端都可以直接用它,例如:
@@ -244,33 +247,28 @@ print(client.chat.completions.create(
244
247
  - id: llm-sensenova-pool
245
248
  name: dsh-sensenova-pool
246
249
  config:
247
- endpoint: cn # cn = 中国站,intl = 国际站;默认 cn。也可在设置卡片里切换
250
+ endpoint: cn # 旧配置兼容:旧记录归属及自定义 baseUrl 所属站;不再切换运行实例
248
251
  rpmLimit: 2 # 每把 Key 的本地 RPM 预限流上限;0 = 关闭,-1(默认)= 按端点取值
249
252
  maxAttempts: 6 # 单个请求最多尝试几把 Key
250
253
  maxConcurrency: 1 # 每把 Key 的并发上限;1 = 串行(推荐)
251
254
  acquireTimeoutMs: 180000
252
255
  requestTimeoutMs: 60000
253
- # baseUrl: https://token.sensenova.cn/v1 # 仅当所有请求要走自建网关时才填;填了就不随端点切换
256
+ # baseUrl: https://token.sensenova.cn/v1 # 仅覆盖 endpoint 指定的站;另一站仍用官方地址
254
257
  ```
255
258
 
256
- `endpoint` 只决定**默认**端点:一旦在设置卡片里切过,以卡片里的选择(存在凭据库)为准,
257
- 这样「重启后还记得你在哪个站」不需要改配置文件。`rpmLimit` 留默认值时按端点取
258
- (中国站 2、国际站 3),显式写数字则两个端点都用这个值。
259
+ `endpoint` 保留用于旧凭据归属兼容(旧记录自身的 `endpoint` 字段优先)以及指定自定义 `baseUrl` 所属站,**不控制两站启停或 Tab**。两站始终各自使用固定上游;`baseUrl` 只覆盖配置 `endpoint` 所属站,另一站仍走官方地址,避免错误复用地址而泄漏 Key。`rpmLimit` 留默认值时按站取值(中国站 2、国际站 3),显式写数字则两站使用同一上限数值,但各自的计数与冷却独立。
259
260
 
260
261
  `rpmLimit` 的中国站默认值 2 基于实测(真实上限约 3 RPM)。**调大它不会提高吞吐,只会更容易被限流** —— 想提高吞吐应该增加 Key,而不是加压。
261
262
 
262
- **两个站的 Key 能混着用吗?** 不能。key 只在发卡的那个站有效,池子只打「当前选中的端点」,
263
- 所以换站后要换用该站的 key(切站不会删除现有的 key,切回来它们还在)。
263
+ **两个站的 Key 能混着用吗?** 不能。Key 只在发卡站有效。请在各站 Tab 分别添加;切换 Tab 不搬移、不删除 Key,也不改变另一站的请求。
264
264
 
265
265
  ---
266
266
 
267
267
  ## 常见问题
268
268
 
269
- **切到国际站后所有 key 都显示「已失效」?**
269
+ **国际站 Key 显示「已失效」?**
270
270
 
271
- 基本就是**选错站了**:国际站的 key 打中国站会返回 `401 Forbidden`,反之亦然。切回正确的站即可
272
- (切站时会清掉冷却/失效标记,所以切回来那些 key 会立刻恢复可用)。如果确认站选对了仍然 401,
273
- 那才是 key 本身的问题。
271
+ 先确认 Key 是否在国际站申请、是否添加到了国际站 Tab。两站 Key 互不通用;Tab 切换不会清除失效或冷却标记。若误加到另一站,请移除后在正确站添加;归属正确仍返回 401 / 403 时,再检查 Key 或套餐权限。
274
272
 
275
273
  **国际站里怎么没有 `deepseek-v4-flash` / `glm-5.2`?**
276
274
 
@@ -456,7 +454,7 @@ Paste one or more SenseNova API keys in one place and use every SenseNova model
456
454
  - **Never leaks a 429 upward** — when every key is exhausted the plugin reports `503 + Retry-After` so DSH backs off on its own
457
455
  - **All models, zero config** — a built-in catalogue works offline and refreshes from `/v1/models` once a valid key is present, so new models need no plugin upgrade
458
456
  - **Keys are masked** — only `sk-example...0001` style masks are ever displayed
459
- - **Two endpoints** — pick the China site (`token.sensenova.cn`) or the international site (`token.sensenova.ai`) from the settings card; switching also swaps the model list and the rate-limit budget, and the choice survives restarts
457
+ - **双站隔离(未发布)** — 中国站 / 国际站 Tab 只切管理视图,两站同时工作;provider 分别为 `sensenova-pool` / `sensenova-pool-intl`,显示「商汤日日新 · 中国站 / 国际站」。各站 Key 池、模型目录、隐藏模型、窗口覆盖、本地接口 / 密钥与冷却 / RPM 状态完全独立。旧凭据仅迁移到旧 `endpoint` 所属站,另一站为空,旧记录保留回退;旧国际站会话须重新选择国际站 provider。
460
458
 
461
459
  ### Install
462
460
 
package/lib/client.js CHANGED
@@ -37,7 +37,10 @@ window.__ModuleLoader__.load({
37
37
 
38
38
  const BUNDLE_NAME = 'dsh-sensenova-pool';
39
39
  const NS = 'dsh-sensenova-pool';
40
- const BASE = '/plugins/dsh-sensenova-pool';
40
+ const SITES = [
41
+ { id: 'cn', base: '/plugins/dsh-sensenova-pool', label: 'siteCn' },
42
+ { id: 'intl', base: '/plugins/dsh-sensenova-pool/intl', label: 'siteIntl' },
43
+ ];
41
44
 
42
45
  /** 写入类操作必须带的证明头(回环 Host 校验不足以证明调用方被授过权)。 */
43
46
  const ADMIN_HEADER = 'x-sensenova-pool-admin';
@@ -246,13 +249,36 @@ window.__ModuleLoader__.load({
246
249
 
247
250
  // ------------------------------------------------------------------ 卡片
248
251
 
252
+ /** Tab 只控制可见性;两张卡常驻,异步状态与未保存草稿始终归各站所有。 */
253
+ function SiteTabs({ t, variant }) {
254
+ const [site, setSite] = React.useState('cn');
255
+ return h('div', { style: rootStyle }, [
256
+ variant === 'section' ? h('h2', { key: 'title', style: pageTitleStyle }, t('nav')) : null,
257
+ h('p', { key: 'hint', style: hintStyle }, t('sitesHint')),
258
+ h('div', { key: 'tabs', role: 'tablist', 'aria-label': t('sitesTitle'), style: { display: 'flex', gap: 8 } },
259
+ SITES.map((option) => h('button', {
260
+ key: option.id,
261
+ type: 'button',
262
+ role: 'tab',
263
+ 'aria-selected': site === option.id,
264
+ style: site === option.id ? buttonPrimaryStyle : buttonStyle,
265
+ onClick: () => setSite(option.id),
266
+ }, t(option.label)))),
267
+ ...SITES.map((option) => h('div', {
268
+ key: option.id,
269
+ role: 'tabpanel',
270
+ 'aria-label': t(option.label),
271
+ hidden: site !== option.id,
272
+ }, h(KeyCard, { key: option.id, t, base: option.base }))),
273
+ ]);
274
+ }
275
+
249
276
  /**
250
- * 管理卡片:上游端点 + 对外接口 + Key 池 + 模型可见性。
251
- *
277
+ * 单站管理卡片:只读上游地址 + 对外接口 + Key 池 + 模型可见性。
252
278
  * @param props.t 文案读取器(宿主 locale 绑定)。
253
- * @param props.variant 'section' 时渲染页面标题(设置分区里需要),'card' 时不渲染。
279
+ * @param props.base 固定站点的管理路由前缀,组件生命周期内不变。
254
280
  */
255
- function KeyCard({ t, variant }) {
281
+ function KeyCard({ t, base }) {
256
282
  const [draft, setDraft] = React.useState('');
257
283
  const [busy, setBusy] = React.useState(false);
258
284
  const [notice, setNotice] = React.useState(undefined);
@@ -262,7 +288,7 @@ window.__ModuleLoader__.load({
262
288
  const [catalog, setCatalog] = React.useState(undefined);
263
289
  const [models, setModels] = React.useState([]);
264
290
  const [endpoint, setEndpoint] = React.useState(undefined);
265
- // 上游端点(中国站 / 国际站):{ current, upstream, pinned, rpmLimit, options[] }
291
+ // 仅展示此固定实例的上游地址,不提供切换操作。
266
292
  const [upstream, setUpstream] = React.useState(undefined);
267
293
  const [adminKey, setAdminKey] = React.useState(undefined);
268
294
  const [tested, setTested] = React.useState({});
@@ -274,7 +300,7 @@ window.__ModuleLoader__.load({
274
300
 
275
301
  const load = React.useCallback(async () => {
276
302
  try {
277
- const status = await getJson(`${BASE}/status`);
303
+ const status = await getJson(`${base}/status`);
278
304
  if (status && Array.isArray(status.keys)) setKeys(status.keys);
279
305
  if (status) {
280
306
  setSummary(status.summary);
@@ -288,7 +314,7 @@ window.__ModuleLoader__.load({
288
314
  } catch (cause) {
289
315
  setError(cause instanceof Error ? cause.message : String(cause));
290
316
  }
291
- }, []);
317
+ }, [base]);
292
318
 
293
319
  React.useEffect(() => {
294
320
  load();
@@ -314,7 +340,7 @@ window.__ModuleLoader__.load({
314
340
 
315
341
  const addKeys = () =>
316
342
  run('add', async () => {
317
- const value = await postJson(`${BASE}/keys`, { action: 'add', keys: draft }, adminKey);
343
+ const value = await postJson(`${base}/keys`, { action: 'add', keys: draft }, adminKey);
318
344
  setDraft('');
319
345
  const parts = [t('added', { added: String(value.added) })];
320
346
  if (value.duplicate > 0) parts.push(t('duplicate', { duplicate: String(value.duplicate) }));
@@ -323,42 +349,32 @@ window.__ModuleLoader__.load({
323
349
 
324
350
  const removeKey = (id) =>
325
351
  run('remove', async () => {
326
- await postJson(`${BASE}/keys`, { action: 'remove', id }, adminKey);
352
+ await postJson(`${base}/keys`, { action: 'remove', id }, adminKey);
327
353
  return t('removed');
328
354
  });
329
355
 
330
356
  const clearKeys = () =>
331
357
  run('clear', async () => {
332
- await postJson(`${BASE}/keys`, { action: 'clear' }, adminKey);
358
+ await postJson(`${base}/keys`, { action: 'clear' }, adminKey);
333
359
  return t('cleared');
334
360
  });
335
361
 
336
362
  const refreshCatalog = () =>
337
363
  run('refresh', async () => {
338
- const value = await postJson(`${BASE}/keys`, { action: 'refresh-catalog' }, adminKey);
364
+ const value = await postJson(`${base}/keys`, { action: 'refresh-catalog' }, adminKey);
339
365
  return t('catalogRefreshed', { count: String(value?.catalog?.count ?? 0) });
340
366
  });
341
367
 
342
368
  const testKey = (id) =>
343
369
  run('test', async () => {
344
- const value = await postJson(`${BASE}/test`, { id }, adminKey);
370
+ const value = await postJson(`${base}/test`, { id }, adminKey);
345
371
  setTested((previous) => ({ ...previous, [id]: value }));
346
372
  return value.ok ? t('testOk', { ms: String(value.latencyMs) }) : t('testFail', { message: String(value.message).slice(0, 80) });
347
373
  });
348
374
 
349
- // 切换上游端点。key 在两个站之间不通用,所以这里不做任何自动探测 —— 换站后
350
- // 新站上没有的 key 会如实显示「已失效」,用户据此判断是不是选错了站。
351
- const selectEndpoint = (id) =>
352
- run('endpoint', async () => {
353
- const value = await postJson(`${BASE}/keys`, { action: 'set-endpoint', id }, adminKey);
354
- if (value && value.upstreamEndpoint) setUpstream(value.upstreamEndpoint);
355
- const chosen = (value?.upstreamEndpoint?.options || []).find((option) => option.active);
356
- return t('endpointSwitched', { label: chosen ? chosen.label : id });
357
- });
358
-
359
375
  const toggleModel = (id, enabled) =>
360
376
  run('model', async () => {
361
- await postJson(`${BASE}/keys`, { action: 'set-model', id, enabled }, adminKey);
377
+ await postJson(`${base}/keys`, { action: 'set-model', id, enabled }, adminKey);
362
378
  return enabled ? t('modelShown', { id }) : t('modelHidden', { id });
363
379
  });
364
380
 
@@ -385,7 +401,7 @@ window.__ModuleLoader__.load({
385
401
 
386
402
  const submitLimits = (model) =>
387
403
  run('limits', async () => {
388
- await postJson(`${BASE}/keys`, limitsPayload(model, limitWindow, limitOutput), adminKey);
404
+ await postJson(`${base}/keys`, limitsPayload(model, limitWindow, limitOutput), adminKey);
389
405
  closeLimits();
390
406
  return t('limitsSaved', { id: model.id });
391
407
  });
@@ -393,7 +409,7 @@ window.__ModuleLoader__.load({
393
409
  const resetLimits = (model) =>
394
410
  run('limits', async () => {
395
411
  // 两个字段传空 = 恢复默认(服务端会归一成「不存覆盖」)。
396
- await postJson(`${BASE}/keys`, limitsPayload(model, '', ''), adminKey);
412
+ await postJson(`${base}/keys`, limitsPayload(model, '', ''), adminKey);
397
413
  closeLimits();
398
414
  return t('limitsReset', { id: model.id });
399
415
  });
@@ -410,41 +426,10 @@ window.__ModuleLoader__.load({
410
426
  const endpointReady = endpoint !== undefined && typeof endpoint.baseUrl === 'string' && endpoint.baseUrl !== '';
411
427
 
412
428
  return h('div', { style: rootStyle }, [
413
- variant === 'section' ? h('h2', { key: 'title', style: pageTitleStyle }, t('nav')) : null,
414
429
  h('p', { key: 'hint', style: hintStyle }, t('hint')),
415
430
 
416
- // ---- 上游端点:中国站 / 国际站 -------------------------------------
417
- //
418
- // 两个站的 key 互不通用,所以这是一个「你得自己选对」的开关,而不是自动
419
- // 探测。放在最上面:填 key 之前就该先确认打的是哪个站。
420
- upstream && Array.isArray(upstream.options) && upstream.options.length > 0
421
- ? h('div', { key: 'endpoint-pick', style: { ...blockStyle, paddingTop: 0, borderTop: 'none' } }, [
422
- h('h3', { key: 'title', style: blockTitleStyle }, t('epTitle')),
423
- h('p', { key: 'hint', style: hintStyle }, t('epHint')),
424
- h(
425
- 'div',
426
- { key: 'options', style: { display: 'flex', flexWrap: 'wrap', gap: 8 } },
427
- upstream.options.map((option) =>
428
- h(
429
- 'button',
430
- {
431
- key: option.id,
432
- type: 'button',
433
- // 选中项用主按钮样式;其余是普通按钮。
434
- style: option.active ? buttonPrimaryStyle : buttonStyle,
435
- disabled: busy || option.active === true,
436
- title: option.baseUrl,
437
- onClick: () => selectEndpoint(option.id),
438
- },
439
- option.active ? `✓ ${option.label}` : option.label,
440
- ),
441
- ),
442
- ),
443
- h('p', { key: 'addr', style: { ...codeStyle, margin: 0 } }, `${t('epUpstream')}:${upstream.upstream || '—'}`),
444
- upstream.pinned
445
- ? h('p', { key: 'pinned', style: { ...hintStyle, color: 'var(--dsw-alias-label-warning, #bf8700)' } }, t('epPinned'))
446
- : null,
447
- ])
431
+ upstream
432
+ ? h('p', { key: 'upstream', style: { ...codeStyle, margin: 0 } }, `${t('epUpstream')}:${upstream.upstream || '—'}`)
448
433
  : null,
449
434
 
450
435
  summary
@@ -720,11 +705,11 @@ window.__ModuleLoader__.load({
720
705
  copy: 'Copy',
721
706
  copied: 'Copied',
722
707
  copyFailed: 'Copy failed — select the text and copy manually.',
723
- epTitle: 'Endpoint',
724
- epHint: 'The China site and the international site are separate services: a key only works on the site that issued it. Switching swaps the upstream URL, the model list and the rate-limit budget.',
708
+ sitesTitle: 'Site management',
709
+ siteCn: 'China',
710
+ siteIntl: 'International',
711
+ sitesHint: 'China and international run simultaneously with independent Key pools. Tabs only change the management card shown; they do not switch upstreams. Keys only work on the site that issued them.',
725
712
  epUpstream: 'Upstream',
726
- epPinned: 'baseUrl is fixed in the plugin config — switching only changes the model list and the rate-limit budget, not the address.',
727
- endpointSwitched: 'Switched to {label}',
728
713
  keysTitle: 'Key pool',
729
714
  modelsTitle: 'Models in the picker',
730
715
  modelsHint: '{count} of {total} models are shown. Context window and max output are editable per model — clear a field to restore the default.',
@@ -780,11 +765,11 @@ window.__ModuleLoader__.load({
780
765
  copy: '复制',
781
766
  copied: '已复制',
782
767
  copyFailed: '复制失败,请手动选中文本复制。',
783
- epTitle: '上游端点',
784
- epHint: '中国站与国际站是两个独立的服务,key 只在发卡的那个站有效。切换会同时换掉上游地址、模型列表与限流额度。',
768
+ sitesTitle: '站点管理',
769
+ siteCn: '中国站',
770
+ siteIntl: '国际站',
771
+ sitesHint: '中国站与国际站同时可用,Key 池独立。Tab 仅切换当前显示的管理卡片,不是切换上游;Key 只在发卡站点有效。',
785
772
  epUpstream: '上游地址',
786
- epPinned: '插件配置里写死了 baseUrl —— 切换只换模型列表与限流额度,不改请求地址。',
787
- endpointSwitched: '已切换到{label}',
788
773
  keysTitle: 'Key 池',
789
774
  modelsTitle: '下拉中的模型',
790
775
  modelsHint: '共 {total} 个模型,当前展示 {count} 个。窗口与最大输出可逐模型修改(清空输入框即恢复默认)。',
@@ -852,7 +837,7 @@ window.__ModuleLoader__.load({
852
837
  locale: NS,
853
838
  inject: () => ({ t }),
854
839
  },
855
- ({ t: seat }) => h(KeyCard, { t: seat, variant: 'section' }),
840
+ ({ t: seat }) => h(SiteTabs, { t: seat, variant: 'section' }),
856
841
  ),
857
842
  ),
858
843
  );
@@ -869,7 +854,7 @@ window.__ModuleLoader__.load({
869
854
  locale: NS,
870
855
  inject: () => ({ t }),
871
856
  },
872
- ({ view, t: seat }) => (view === 'summary' ? seat('hint') : h(KeyCard, { t: seat, variant: 'card' })),
857
+ ({ view, t: seat }) => (view === 'summary' ? seat('sitesHint') : h(SiteTabs, { t: seat, variant: 'card' })),
873
858
  ),
874
859
  ),
875
860
  );
@@ -888,7 +873,7 @@ window.__ModuleLoader__.load({
888
873
  locale: NS,
889
874
  inject: () => ({ t }),
890
875
  },
891
- ({ t: seat }) => h(KeyCard, { t: seat, variant: 'card' }),
876
+ ({ t: seat }) => h(SiteTabs, { t: seat, variant: 'card' }),
892
877
  ),
893
878
  ),
894
879
  );
package/lib/index.d.ts CHANGED
@@ -45,5 +45,6 @@ type PluginConfig = {
45
45
  rpmLimit: number;
46
46
  maxConcurrency: number;
47
47
  };
48
+ /** 两站各自创建完整运行实例;Tab 不参与请求路由。 */
48
49
  export declare function apply(ctx: any, config: PluginConfig): void;
49
50
  export { PROVIDER_ID, PROVIDER_NAME, SETTINGS_NS, maskKey, keyIdOf };
package/lib/index.js CHANGED
@@ -21,7 +21,7 @@ import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
21
21
  import { createProvider } from '@earendil-works/pi-ai';
22
22
  import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completions.lazy';
23
23
  import z from '@deepseek-ai/schemastery';
24
- import { DEFAULT_ENDPOINT_ID, ENDPOINTS, builtinModelsFor, endpointFor, isEndpointId, thinkingLevelMapFor, } from './catalog.js';
24
+ import { DEFAULT_ENDPOINT_ID, ENDPOINTS, builtinModelsFor, endpointFor, thinkingLevelMapFor, } from './catalog.js';
25
25
  import { KeyPool, keyIdOf, maskKey } from './keypool.js';
26
26
  import { ModelCatalog, createShim } from './shim.js';
27
27
  import { registerKeyRoutes, registerSettingsSection, } from './routes.js';
@@ -85,12 +85,12 @@ export const Config = z.object({
85
85
  .string()
86
86
  .default(DEFAULT_ENDPOINT_ID)
87
87
  .description('上游端点:cn = 中国站(token.sensenova.cn),intl = 国际站(token.sensenova.ai)。' +
88
- '两个站的 key 互不通用;也可以在设置卡片里切换,切换结果会持久化。' +
88
+ '两站同时运行;该字段仅用于旧记录迁移和旧自定义地址归属。' +
89
89
  '写错的值不会被拒绝,而是回落到 cn(不让一个拼写问题把插件卡在加载阶段)。'),
90
90
  baseUrl: z
91
91
  .string()
92
92
  .default('')
93
- .description('覆盖端点地址(填空表示用所选端点的默认地址)。仅在所有请求要走自建网关 / 代理时使用。'),
93
+ .description('覆盖 endpoint 指定站点的地址(留空使用官方地址);另一站保持官方地址,避免跨站发送 Key。'),
94
94
  maxAttempts: z.number().default(6).description('单个请求最多尝试几把 key'),
95
95
  acquireTimeoutMs: z.number().default(180_000).description('等待可用 key 的总预算(毫秒)'),
96
96
  requestTimeoutMs: z.number().default(60_000).description('单次上游请求超时(毫秒)'),
@@ -131,14 +131,16 @@ const INERT_AUTH = {
131
131
  },
132
132
  },
133
133
  };
134
+ /** 两站各自创建完整运行实例;Tab 不参与请求路由。 */
134
135
  export function apply(ctx, config) {
135
- /**
136
- * 配置文件里的端点(缺省 = 中国站,保证老用户升级后行为不变)。
137
- *
138
- * 运行期真正生效的端点是 `currentEndpoint`:它以凭据记录里的选择为准(用户在
139
- * 设置卡片里切过),没有记录时回落到这里。
140
- */
141
- const configEndpoint = endpointFor(config?.endpoint);
136
+ for (const site of ['cn', 'intl'])
137
+ applySite(ctx, config, site);
138
+ }
139
+ function applySite(ctx, config, site) {
140
+ const PROVIDER_ID = site === 'cn' ? 'sensenova-pool' : 'sensenova-pool-intl';
141
+ const PROVIDER_NAME = site === 'cn' ? '商汤日日新 · 中国站' : '商汤日日新 · 国际站';
142
+ // 每站实例有固定身份;旧 config.endpoint 只用于迁移归属。
143
+ const configEndpoint = endpointFor(site);
142
144
  /**
143
145
  * config 里显式写的 `rpmLimit`(≥0 才算显式);-1(默认)表示「按端点取默认值」。
144
146
  */
@@ -155,24 +157,23 @@ export function apply(ctx, config) {
155
157
  warn: (message) => ctx.logger?.warn?.(`sensenova-pool: ${message}`),
156
158
  error: (message) => ctx.logger?.error?.(`sensenova-pool: ${message}`),
157
159
  };
158
- /** 当前生效的端点。启动时取 config,装载凭据记录后可能被记录里的选择覆盖。 */
159
- let currentEndpoint = configEndpoint;
160
+ /** 本实例的固定站点,凭据重载或 Tab 操作均不改变它。 */
161
+ const currentEndpoint = configEndpoint;
160
162
  /**
161
- * 用户显式指定了 `baseUrl` 时不随端点切换(自建网关 / 代理的场景)。
162
- *
163
- * 这时「端点」只影响**内置基线与显示**,请求一律走用户给的地址。
163
+ * 兼容旧自定义网关:仅 config.endpoint 对应站点使用自定义地址,另一站使用官方地址。
164
164
  */
165
165
  const baseUrlPinned = resolved.baseUrl.length > 0;
166
166
  /** 所选端点对应的上游根地址。 */
167
167
  function upstreamFor(endpoint) {
168
- return baseUrlPinned ? resolved.baseUrl : endpoint.baseUrl;
168
+ // 旧版自定义地址只用于其配置所属站,禁止另一站也复用它而泄漏 Key。
169
+ return baseUrlPinned && site === endpointFor(config?.endpoint).id ? resolved.baseUrl : endpoint.baseUrl;
169
170
  }
170
171
  /** 该端点下每把 key 的本地 RPM 上限(0 表示不限流)。 */
171
172
  function rpmLimitFor(endpoint) {
172
173
  return explicitRpmLimit ?? defaultRpmLimitFor(endpoint.id);
173
174
  }
174
175
  const catalog = new ModelCatalog();
175
- // 回环服务按**端点**而不是地址区分:即使 baseUrl 被固定,切换端点也要换目录基线。
176
+ // 每个实例只装载本站基线;自定义网关不改变站点身份。
176
177
  catalog.reset(currentEndpoint.id);
177
178
  const pool = new KeyPool([], {
178
179
  rpmLimit: (() => {
@@ -220,6 +221,7 @@ export function apply(ctx, config) {
220
221
  let externalKey = '';
221
222
  /** 凭据库里是否**已有**本插件的记录(决定首次装载后要不要立刻补写)。 */
222
223
  let recordExisted = false;
224
+ let migrationPending = false;
223
225
  /** 最近的轮换事件,供状态页展示「刚才发生了什么」。 */
224
226
  const recentRotations = [];
225
227
  const shim = createShim({
@@ -256,8 +258,8 @@ export function apply(ctx, config) {
256
258
  upstreamEndpoint: () => ({
257
259
  current: currentEndpoint.id,
258
260
  upstream: shim.upstream(),
259
- /** baseUrl 被 config 固定时,界面要提示「切端点只换目录/额度,不改地址」。 */
260
- pinned: baseUrlPinned,
261
+ // 是否为本站配置了自定义上游。
262
+ pinned: baseUrlPinned && site === endpointFor(config?.endpoint).id,
261
263
  rpmLimit: rpmLimitFor(currentEndpoint),
262
264
  options: ENDPOINTS.map((option) => ({
263
265
  id: option.id,
@@ -298,7 +300,8 @@ export function apply(ctx, config) {
298
300
  * 一套持久化路径不值得。grant 的 payload 是**逐字保留**的,多几个字段完全安全。
299
301
  */
300
302
  const RECORD_SCOPE = 'dsh-sensenova-pool';
301
- const RECORD_ID = `${RECORD_SCOPE}/keys`;
303
+ const RECORD_ID = `${RECORD_SCOPE}/keys-${site}`;
304
+ const LEGACY_RECORD_ID = `${RECORD_SCOPE}/keys`;
302
305
  /**
303
306
  * 写入前等待首次权威装载的上限(毫秒)。
304
307
  *
@@ -349,6 +352,7 @@ export function apply(ctx, config) {
349
352
  * 权威装载之前写入(启动还没完,用户就点了「添加 Key」),池子里只有刚加的那把,
350
353
  * 磁盘上原有的 key 会被静默抹掉。
351
354
  */
355
+ let authoritativeLoaded = false;
352
356
  let notifyKeysLoaded;
353
357
  const firstAuthoritativeLoad = new Promise((resolve) => {
354
358
  notifyKeysLoaded = resolve;
@@ -378,29 +382,22 @@ export function apply(ctx, config) {
378
382
  }
379
383
  }
380
384
  }
385
+ if (migrationPending) {
386
+ // 先清标记,避免 modifyRecord 的变更事件重入时重复迁移。
387
+ migrationPending = false;
388
+ try {
389
+ await persistRecord();
390
+ }
391
+ catch (error) {
392
+ migrationPending = true;
393
+ logger.warn('旧版状态迁移暂未落盘,保留旧记录以便下次重试');
394
+ }
395
+ }
396
+ authoritativeLoaded = true;
381
397
  notifyKeysLoaded?.();
382
398
  }
383
399
  return added;
384
400
  }
385
- /**
386
- * 应用一个"未来可能换端点"的选择(启动装载时用)。
387
- *
388
- * 与运行期的 {@link applyEndpoint} 同源,但这里不落盘、不刷新目录 —— 调用方
389
- * (启动装载)随后会自己触发目录刷新,重复调用只会白白多打一次上游。
390
- */
391
- function adoptEndpoint(id) {
392
- if (id === currentEndpoint.id)
393
- return false;
394
- currentEndpoint = endpointFor(id);
395
- catalog.reset(currentEndpoint.id);
396
- shim.setUpstream(upstreamFor(currentEndpoint));
397
- pool.setRpmLimit((() => {
398
- const limit = rpmLimitFor(currentEndpoint);
399
- return limit > 0 ? limit : null;
400
- })());
401
- pool.resetHealth();
402
- return true;
403
- }
404
401
  /** 生成一把形如商汤 key 的对外密钥(只被本地 shim 校验,不发给上游)。 */
405
402
  function newExternalKey() {
406
403
  return `sk-dsh-${randomBytes(24).toString('hex')}`;
@@ -414,14 +411,28 @@ export function apply(ctx, config) {
414
411
  let record;
415
412
  try {
416
413
  record = await credentials.readRecord(RECORD_ID);
414
+ if (record === undefined || record === null) {
415
+ // 旧共享记录仅由原选中站继承;另一站不得复制旧 Key。
416
+ // 保留旧记录,便于回退。独立记录存在后不再重复迁移。
417
+ const legacy = await credentials.readRecord(LEGACY_RECORD_ID);
418
+ const legacySite = endpointFor(legacy?.payload?.endpoint ?? config?.endpoint).id;
419
+ if (legacy && legacySite === site) {
420
+ record = legacy;
421
+ migrationPending = true;
422
+ }
423
+ }
417
424
  }
418
425
  catch (error) {
419
- logger.warn(`读取 key 记录失败:${error instanceof Error ? error.message : String(error)}`);
420
- return 0;
426
+ throw new Error(`读取 key 记录失败:${error instanceof Error ? error.message : String(error)}`);
421
427
  }
422
428
  const payload = record?.payload ?? {};
423
429
  recordExisted = record !== undefined && record !== null;
424
430
  const keys = Array.isArray(payload.keys) ? payload.keys : [];
431
+ const authoritativeKeys = new Set(keys.filter((key) => typeof key === 'string').map((key) => key.trim()));
432
+ for (const existing of pool.keys()) {
433
+ if (!authoritativeKeys.has(existing))
434
+ pool.removeKey(existing);
435
+ }
425
436
  let added = 0;
426
437
  for (const raw of keys) {
427
438
  if (typeof raw === 'string' && pool.addKey(raw))
@@ -458,10 +469,7 @@ export function apply(ctx, config) {
458
469
  externalKey = payload.externalKey;
459
470
  shim.setToken(externalKey);
460
471
  }
461
- // 端点:记录里的选择优先于 config(用户在设置卡片里切过之后,重启也必须记住)。
462
- // 记录里没有该字段 = 从未切过,保持 config 的端点,老用户行为不变。
463
- if (isEndpointId(payload.endpoint))
464
- adoptEndpoint(payload.endpoint);
472
+ // 本实例的站点固定,不采纳记录里的切站请求。
465
473
  if (added > 0)
466
474
  logger.info(`已装载 ${added} 把 key`);
467
475
  return added;
@@ -717,10 +725,9 @@ export function apply(ctx, config) {
717
725
  return;
718
726
  void loadKeysAndNotify()
719
727
  .then((added) => {
720
- if (added > 0) {
721
- refreshCatalog();
728
+ refreshCatalog();
729
+ if (added > 0)
722
730
  void fetchCatalogFromUpstream();
723
- }
724
731
  })
725
732
  .catch((error) => {
726
733
  logger.warn(`记录变更后重载失败:${error instanceof Error ? error.message : String(error)}`);
@@ -738,7 +745,7 @@ export function apply(ctx, config) {
738
745
  async function fetchCatalogFromUpstream() {
739
746
  if (pool.size === 0)
740
747
  return;
741
- // 现取上游地址与基线:两次请求之间用户可能已经切换了端点。
748
+ // 目录和上游固定属于本站,另一站的刷新不会覆盖本实例。
742
749
  const endpoint = currentEndpoint;
743
750
  const url = `${shim.upstream().replace(/\/+$/, '')}/models`;
744
751
  const attempted = new Set();
@@ -758,9 +765,6 @@ export function apply(ctx, config) {
758
765
  });
759
766
  if (response.ok) {
760
767
  const payload = await response.json();
761
- // 请求在途时端点被切走:这份响应对新端点没有意义,丢弃。
762
- if (currentEndpoint.id !== endpoint.id)
763
- return;
764
768
  const count = catalog.apply(payload, builtinModelsFor(endpoint.id));
765
769
  pool.reportSuccess(entry);
766
770
  if (count > 0) {
@@ -840,46 +844,20 @@ export function apply(ctx, config) {
840
844
  logger.warn(`模型窗口设置落盘失败(本次会话已生效):${error instanceof Error ? error.message : String(error)}`);
841
845
  }
842
846
  };
843
- /**
844
- * 切换上游端点(中国站 ⇄ 国际站)。
845
- *
846
- * 这是「换一个站继续用」而不是「改个地址」:两个站的 key、模型、限流额度都
847
- * 不同,所以四件事必须一起做,缺一件都会让状态变得自相矛盾:
848
- *
849
- * 1. **上游地址** —— 之后所有请求打到新站;
850
- * 2. **模型目录** —— 退回新站的内置基线(旧站的模型列表在新站上多数是 404);
851
- * 3. **RPM 额度** —— 新站有自己的额度(中国站实测约 3 RPM,国际站另计);
852
- * 4. **key 健康状态** —— 冷却/失效是针对旧站记下的,带过去会让切站后几分钟
853
- * 内一把 key 都用不了。
854
- *
855
- * 落盘顺序:先写凭据记录再刷新模型选择器 —— 刷新会让 DSH 立刻重读模型,
856
- * 若此时记录还没写成功,用户会看到「切换了但重启又回到原来那个站」。
857
- * 落盘失败不回滚:内存里已经切过去了,会话可用性优先,下次写入会一并带上。
858
- */
847
+ /** 保留旧接口但禁止修改固定站点的上游,避免旧客户端串站。 */
859
848
  const handleEndpointChanged = async (id) => {
860
- if (!isEndpointId(id))
861
- throw new Error(`未知端点:${id}`);
862
- if (id === currentEndpoint.id)
863
- return;
864
- adoptEndpoint(id);
865
- logger.info(`已切换上游端点到「${currentEndpoint.label}」(${shim.upstream()})`);
866
- try {
867
- await saveKeys();
868
- }
869
- catch (error) {
870
- logger.warn(`端点选择落盘失败(本次会话已生效):${error instanceof Error ? error.message : String(error)}`);
871
- }
872
- refreshCatalog();
873
- void fetchCatalogFromUpstream();
849
+ if (id !== site)
850
+ throw new Error('站点已隔离,请在设置页切换 Tab,不支持切换实例上游');
874
851
  };
875
852
  // 设置页:填 key(用户明确要求只在设置页填)。
876
853
  try {
877
- registerSettingsSection(ctx, {
878
- namespace: SETTINGS_NS,
879
- config,
880
- pool,
881
- onKeysChanged: handleKeysChanged,
882
- });
854
+ if (site === 'cn')
855
+ registerSettingsSection(ctx, {
856
+ namespace: SETTINGS_NS,
857
+ config,
858
+ pool,
859
+ onKeysChanged: handleKeysChanged,
860
+ });
883
861
  }
884
862
  catch (error) {
885
863
  logger.warn(`设置页注册失败(不影响模型可用):${error instanceof Error ? error.message : String(error)}`);
@@ -894,6 +872,13 @@ export function apply(ctx, config) {
894
872
  onModelsChanged: handleModelsChanged,
895
873
  onModelLimitsChanged: handleModelLimitsChanged,
896
874
  onEndpointChanged: handleEndpointChanged,
875
+ prepareWrite: async () => {
876
+ if (credentialsRegistered()) {
877
+ await Promise.race([firstAuthoritativeLoad, delay(SAVE_LOAD_WAIT_MS)]);
878
+ if (!authoritativeLoaded)
879
+ throw new Error('凭据尚未成功装载,请稍后重试或检查凭据服务');
880
+ }
881
+ },
897
882
  reload: async () => {
898
883
  // 手动重载:走同一套「装载并宣告」逻辑,因此在启动早期点它也不会把
899
884
  // 「还没读到」误当成「真的没有 key」而清空权威装载信号。
@@ -901,7 +886,7 @@ export function apply(ctx, config) {
901
886
  refreshCatalog();
902
887
  },
903
888
  fetchCatalog: fetchCatalogFromUpstream,
904
- });
889
+ }, site === 'cn' ? undefined : '/plugins/dsh-sensenova-pool/intl');
905
890
  }
906
891
  catch (error) {
907
892
  logger.warn(`Web 路由注册失败:${error instanceof Error ? error.message : String(error)}`);
package/lib/routes.d.ts CHANGED
@@ -97,6 +97,8 @@ export interface RouteDeps {
97
97
  status: StatusProvider;
98
98
  pool: KeyPool;
99
99
  logger: Logger;
100
+ /** 首次装载完成前不修改池子,避免把磁盘旧 Key 覆盖掉。 */
101
+ prepareWrite?(): Promise<void>;
100
102
  /** key 列表发生变更后回调(持久化 + 刷新目录)。 */
101
103
  onKeysChanged(): Promise<void>;
102
104
  /** 模型可见性发生变更后回调(收到完整的「被隐藏」列表)。 */
@@ -128,7 +130,7 @@ export declare const ROUTE_BASE = "/plugins/dsh-sensenova-pool";
128
130
  */
129
131
  export declare function parseKeyInput(input: unknown): string[];
130
132
  /** 在可选的 webServer 服务上挂载 key 管理路由。 */
131
- export declare function registerKeyRoutes(ctx: any, deps: RouteDeps): void;
133
+ export declare function registerKeyRoutes(ctx: any, deps: RouteDeps, routeBase?: string): void;
132
134
  export interface SettingsSectionDeps {
133
135
  namespace: string;
134
136
  config: unknown;
package/lib/routes.js CHANGED
@@ -132,7 +132,7 @@ export function parseKeyInput(input) {
132
132
  }
133
133
  // ------------------------------------------------------------------ 路由
134
134
  /** 在可选的 webServer 服务上挂载 key 管理路由。 */
135
- export function registerKeyRoutes(ctx, deps) {
135
+ export function registerKeyRoutes(ctx, deps, routeBase = ROUTE_BASE) {
136
136
  /**
137
137
  * 每进程随机的写入令牌。
138
138
  *
@@ -175,7 +175,7 @@ export function registerKeyRoutes(ctx, deps) {
175
175
  return false;
176
176
  };
177
177
  // ---- 状态:池健康度、目录来源、最近轮换 ----------------------------
178
- register(`${ROUTE_BASE}/status`, async (req, res) => {
178
+ register(`${routeBase}/status`, async (req, res) => {
179
179
  if (req.method !== 'GET') {
180
180
  sendJson(res, 405, { error: 'method not allowed' });
181
181
  return;
@@ -198,7 +198,7 @@ export function registerKeyRoutes(ctx, deps) {
198
198
  });
199
199
  }, 'status route');
200
200
  // ---- 列出 key(永远脱敏) ------------------------------------------
201
- register(`${ROUTE_BASE}/keys`, async (req, res) => {
201
+ register(`${routeBase}/keys`, async (req, res) => {
202
202
  if (req.method === 'GET') {
203
203
  sendJson(res, 200, { keys: deps.status.pool() });
204
204
  return;
@@ -207,6 +207,7 @@ export function registerKeyRoutes(ctx, deps) {
207
207
  if (!requireAdmin(req, res))
208
208
  return;
209
209
  const body = await readJsonBody(req);
210
+ await deps.prepareWrite?.();
210
211
  const action = typeof body?.action === 'string' ? body.action : 'add';
211
212
  if (action === 'add') {
212
213
  const parsed = parseKeyInput(body?.keys ?? body?.key);
@@ -362,7 +363,7 @@ export function registerKeyRoutes(ctx, deps) {
362
363
  sendJson(res, 405, { error: 'method not allowed' });
363
364
  }, 'keys route');
364
365
  // ---- 单把 key 探活:真实打一次极小请求,立刻告诉用户好不好使 --------
365
- register(`${ROUTE_BASE}/test`, async (req, res) => {
366
+ register(`${routeBase}/test`, async (req, res) => {
366
367
  if (req.method !== 'POST') {
367
368
  sendJson(res, 405, { error: 'method not allowed' });
368
369
  return;
package/lib/shim.d.ts CHANGED
@@ -73,6 +73,13 @@ export interface ShimOptions {
73
73
  * 一眼就能定位。默认关闭(体积大且可能含用户内容),由 e2e / 排障时显式打开。
74
74
  */
75
75
  debugRequestOn400?: boolean;
76
+ /**
77
+ * 图像接口(`/v1/images/*`)单次上游请求超时(毫秒)。
78
+ *
79
+ * 生图/图生图(如 `sensenova-u1.5-lite`)是非流式长耗时请求,默认至少 180 秒,
80
+ * 避免高分辨率出图在对话默认的 60 秒被误判超时并重复重试。
81
+ */
82
+ imageRequestTimeoutMs?: number;
76
83
  }
77
84
  export interface Shim {
78
85
  ready: Promise<void>;
package/lib/shim.js CHANGED
@@ -117,12 +117,15 @@ export function createShim(options) {
117
117
  writeError(res, 401, 'unauthorized', 'missing or invalid Authorization bearer');
118
118
  return;
119
119
  }
120
- const url = (req.url ?? '/').split('?')[0];
121
- if (req.method === 'GET' && (url === '/healthz' || url === '/healthz/')) {
120
+ const rawUrl = req.url ?? '/';
121
+ const queryIndex = rawUrl.indexOf('?');
122
+ const pathname = queryIndex >= 0 ? rawUrl.slice(0, queryIndex) : rawUrl;
123
+ const search = queryIndex >= 0 ? rawUrl.slice(queryIndex) : '';
124
+ if (req.method === 'GET' && (pathname === '/healthz' || pathname === '/healthz/')) {
122
125
  writeJson(res, 200, { ok: true, ...pool.summary() });
123
126
  return;
124
127
  }
125
- if (req.method === 'GET' && (url === '/v1/models' || url === '/v1/models/')) {
128
+ if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/v1/models/')) {
126
129
  writeJson(res, 200, {
127
130
  object: 'list',
128
131
  data: catalog.current().map((model) => ({
@@ -134,11 +137,20 @@ export function createShim(options) {
134
137
  });
135
138
  return;
136
139
  }
137
- if (req.method === 'POST' && (url === '/v1/chat/completions' || url === '/v1/chat/completions/')) {
140
+ if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/v1/chat/completions/')) {
138
141
  await chatCompletions(req, res);
139
142
  return;
140
143
  }
141
- writeError(res, 404, 'not_found', `no such route: ${req.method} ${url}`);
144
+ // 其他 /v1/* 端点(如生图模型 sensenova-u1.5-lite 的 /v1/images/generations、
145
+ // /v1/images/edits 等):保持原始请求体与 Content-Type 原样透传并走 key 轮换池。
146
+ if (pathname.startsWith('/v1/') && isAllowedPassthroughMethod(req.method)) {
147
+ const target = resolveUpstreamPassthroughUrl(upstreamBaseUrl, pathname, search);
148
+ if (target !== null) {
149
+ await passthrough(req, res, target.url, target.subpath);
150
+ return;
151
+ }
152
+ }
153
+ writeError(res, 404, 'not_found', `no such route: ${req.method} ${pathname}`);
142
154
  }
143
155
  catch (error) {
144
156
  const message = error instanceof Error ? error.message : String(error);
@@ -250,6 +262,90 @@ export function createShim(options) {
250
262
  });
251
263
  stream.pipe(res);
252
264
  }
265
+ /**
266
+ * 透传非 chat 的 `/v1/*` 请求(生图 / 图生图等)到上游,并复用 key 轮换池。
267
+ *
268
+ * 不解析、不改写原始请求体(同时兼容 JSON 与 multipart/form-data),
269
+ * 读入 Buffer 后可在 429 / 5xx 切换下一把 key 时安全重发。
270
+ */
271
+ async function passthrough(req, res, upstreamUrl, subpath) {
272
+ const method = (req.method ?? 'GET').toUpperCase();
273
+ const hasBody = method !== 'GET' && method !== 'HEAD';
274
+ const rawBody = hasBody ? await readBody(req) : undefined;
275
+ const isImageRoute = subpath === '/images' || subpath.startsWith('/images/');
276
+ const effectiveRotation = isImageRoute
277
+ ? {
278
+ ...rotation,
279
+ requestTimeoutMs: options.imageRequestTimeoutMs ??
280
+ Math.max(rotation.requestTimeoutMs, DEFAULT_IMAGE_REQUEST_TIMEOUT_MS),
281
+ }
282
+ : rotation;
283
+ const controller = new AbortController();
284
+ res.on('close', () => {
285
+ if (!res.writableEnded)
286
+ controller.abort();
287
+ });
288
+ const result = await requestWithRotation(pool, effectiveRotation, (apiKey, signal) => fetch(upstreamUrl, {
289
+ method,
290
+ headers: buildPassthroughHeaders(req, apiKey),
291
+ body: rawBody !== undefined && rawBody.length > 0 ? new Uint8Array(rawBody) : undefined,
292
+ signal,
293
+ }), {
294
+ onAttemptFailed: (log) => {
295
+ options.logger?.warn(`sensenova-pool: key ${log.keyId} ${log.kind} (${log.status}) — ${log.message}`);
296
+ options.onAttemptFailed?.(log);
297
+ },
298
+ signal: controller.signal,
299
+ });
300
+ if (!result.ok) {
301
+ if (controller.signal.aborted) {
302
+ if (!res.headersSent)
303
+ res.statusCode = 499;
304
+ res.end();
305
+ return;
306
+ }
307
+ if (options.debugRequestOn400 && result.error.status === 400) {
308
+ const preview = formatDebugBodyPreview(req.headers['content-type'], rawBody);
309
+ options.logger?.warn(`sensenova-pool: 上游 400(${result.error.message}),透传 ${method} ${subpath} 请求体:${preview}`);
310
+ }
311
+ writeError(res, outwardStatus(result.error), result.error.kind, summarizeFailure(result.error.message, result.attempts), result.error.kind === 'rate_limit' ? retryAfterSeconds(pool) : undefined);
312
+ return;
313
+ }
314
+ const upstream = result.response;
315
+ const contentType = upstream.headers.get('content-type');
316
+ if (contentType?.toLowerCase().includes('text/event-stream') && upstream.body) {
317
+ res.writeHead(upstream.status, {
318
+ 'content-type': contentType,
319
+ 'cache-control': 'no-cache',
320
+ connection: 'keep-alive',
321
+ 'x-accel-buffering': 'no',
322
+ 'x-sensenova-pool-key': result.keyId,
323
+ 'x-sensenova-pool-attempts': String(result.attempts),
324
+ });
325
+ const stream = Readable.fromWeb(upstream.body);
326
+ stream.on('error', (error) => {
327
+ options.logger?.warn(`sensenova-pool: upstream stream failed mid-flight: ${error.message}`);
328
+ if (res.writable)
329
+ res.end();
330
+ });
331
+ stream.pipe(res);
332
+ return;
333
+ }
334
+ const outHeaders = {
335
+ 'x-sensenova-pool-key': result.keyId,
336
+ 'x-sensenova-pool-attempts': String(result.attempts),
337
+ };
338
+ if (contentType)
339
+ outHeaders['content-type'] = contentType;
340
+ if (method === 'HEAD' || upstream.status === 204) {
341
+ res.writeHead(upstream.status, outHeaders);
342
+ res.end();
343
+ return;
344
+ }
345
+ const payload = Buffer.from(await upstream.arrayBuffer());
346
+ res.writeHead(upstream.status, outHeaders);
347
+ res.end(payload);
348
+ }
253
349
  return {
254
350
  ready,
255
351
  baseUrl,
@@ -387,4 +483,91 @@ function writeError(res, status, code, message, retryAfterSec) {
387
483
  res.writeHead(status, headers);
388
484
  res.end(payload);
389
485
  }
486
+ const DEFAULT_IMAGE_REQUEST_TIMEOUT_MS = 180_000;
487
+ const ALLOWED_PASSTHROUGH_METHODS = new Set(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']);
488
+ const PASSTHROUGH_REQUEST_HEADERS = [
489
+ 'content-type',
490
+ 'accept',
491
+ 'openai-beta',
492
+ 'anthropic-version',
493
+ 'anthropic-beta',
494
+ 'x-request-id',
495
+ ];
496
+ function isAllowedPassthroughMethod(method) {
497
+ return typeof method === 'string' && ALLOWED_PASSTHROUGH_METHODS.has(method.toUpperCase());
498
+ }
499
+ /**
500
+ * 将本地 `/v1/...` 路径安全拼接到当前上游根地址,防御路径遍历与跨主机逃逸。
501
+ */
502
+ function resolveUpstreamPassthroughUrl(upstreamBaseUrl, pathname, search) {
503
+ if (!pathname.startsWith('/v1/'))
504
+ return null;
505
+ const rawSubpath = pathname.slice(3); // 保留开头的 "/"
506
+ const subpath = rawSubpath.replace(/\/+$/, '');
507
+ if (subpath.length <= 1)
508
+ return null;
509
+ if (/[\u0000-\u001f\u007f\\]/.test(subpath))
510
+ return null;
511
+ if (subpath.includes('//'))
512
+ return null;
513
+ for (const segment of subpath.slice(1).split('/')) {
514
+ if (!segment || segment === '.' || segment === '..')
515
+ return null;
516
+ let decoded;
517
+ try {
518
+ decoded = decodeURIComponent(segment);
519
+ }
520
+ catch {
521
+ return null;
522
+ }
523
+ if (decoded === '.' ||
524
+ decoded === '..' ||
525
+ decoded.includes('/') ||
526
+ decoded.includes('\\') ||
527
+ decoded.includes('\u0000')) {
528
+ return null;
529
+ }
530
+ }
531
+ const baseTrimmed = upstreamBaseUrl.replace(/\/+$/, '');
532
+ const candidate = `${baseTrimmed}${subpath}${search}`;
533
+ try {
534
+ const baseParsed = new URL(baseTrimmed);
535
+ const targetParsed = new URL(candidate);
536
+ if (targetParsed.origin !== baseParsed.origin)
537
+ return null;
538
+ const basePath = baseParsed.pathname.replace(/\/+$/, '');
539
+ if (basePath.length > 0 && targetParsed.pathname !== basePath && !targetParsed.pathname.startsWith(`${basePath}/`)) {
540
+ return null;
541
+ }
542
+ }
543
+ catch {
544
+ return null;
545
+ }
546
+ return { url: candidate, subpath };
547
+ }
548
+ function buildPassthroughHeaders(req, apiKey) {
549
+ const headers = {
550
+ authorization: `Bearer ${apiKey}`,
551
+ };
552
+ for (const name of PASSTHROUGH_REQUEST_HEADERS) {
553
+ const value = req.headers[name];
554
+ if (typeof value === 'string' && value.length > 0) {
555
+ headers[name] = value;
556
+ }
557
+ else if (Array.isArray(value) && value.length > 0) {
558
+ headers[name] = value.join(', ');
559
+ }
560
+ }
561
+ return headers;
562
+ }
563
+ function formatDebugBodyPreview(contentType, rawBody) {
564
+ if (!rawBody || rawBody.length === 0)
565
+ return '(empty)';
566
+ const ct = Array.isArray(contentType) ? contentType.join(', ') : (contentType ?? '');
567
+ if (/\bjson\b/i.test(ct) || /^text\//i.test(ct)) {
568
+ const text = rawBody.toString('utf8');
569
+ return text.length > 2000 ? `${text.slice(0, 2000)}…(共 ${rawBody.length} 字节)` : text;
570
+ }
571
+ return `<${ct || 'binary'}, ${rawBody.length} bytes>`;
572
+ }
390
573
  export { DEFAULT_BASE_URL };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-sensenova-pool",
3
3
  "displayName": "DSH SenseNova Key Pool",
4
4
  "description": "商汤日日新(SenseNova)多 Key 轮换池 — 填入多把 Key 即可零配置接入 DeepSeek Harness,遇 429 限流自动切换下一把 Key。",
5
- "version": "1.1.0",
5
+ "version": "1.3.0",
6
6
  "author": "Phoeky",
7
7
  "keywords": [
8
8
  "dsh-plugin",