dsh-sensenova-pool 1.0.0 → 1.2.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/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,6 +288,8 @@ 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);
291
+ // 仅展示此固定实例的上游地址,不提供切换操作。
292
+ const [upstream, setUpstream] = React.useState(undefined);
265
293
  const [adminKey, setAdminKey] = React.useState(undefined);
266
294
  const [tested, setTested] = React.useState({});
267
295
  const [copied, setCopied] = React.useState('');
@@ -272,20 +300,21 @@ window.__ModuleLoader__.load({
272
300
 
273
301
  const load = React.useCallback(async () => {
274
302
  try {
275
- const status = await getJson(`${BASE}/status`);
303
+ const status = await getJson(`${base}/status`);
276
304
  if (status && Array.isArray(status.keys)) setKeys(status.keys);
277
305
  if (status) {
278
306
  setSummary(status.summary);
279
307
  setCatalog(status.catalog);
280
308
  if (Array.isArray(status.models)) setModels(status.models);
281
309
  if (status.endpoint) setEndpoint(status.endpoint);
310
+ if (status.upstreamEndpoint) setUpstream(status.upstreamEndpoint);
282
311
  if (typeof status.adminKey === 'string') setAdminKey(status.adminKey);
283
312
  }
284
313
  setError(undefined);
285
314
  } catch (cause) {
286
315
  setError(cause instanceof Error ? cause.message : String(cause));
287
316
  }
288
- }, []);
317
+ }, [base]);
289
318
 
290
319
  React.useEffect(() => {
291
320
  load();
@@ -311,7 +340,7 @@ window.__ModuleLoader__.load({
311
340
 
312
341
  const addKeys = () =>
313
342
  run('add', async () => {
314
- const value = await postJson(`${BASE}/keys`, { action: 'add', keys: draft }, adminKey);
343
+ const value = await postJson(`${base}/keys`, { action: 'add', keys: draft }, adminKey);
315
344
  setDraft('');
316
345
  const parts = [t('added', { added: String(value.added) })];
317
346
  if (value.duplicate > 0) parts.push(t('duplicate', { duplicate: String(value.duplicate) }));
@@ -320,32 +349,32 @@ window.__ModuleLoader__.load({
320
349
 
321
350
  const removeKey = (id) =>
322
351
  run('remove', async () => {
323
- await postJson(`${BASE}/keys`, { action: 'remove', id }, adminKey);
352
+ await postJson(`${base}/keys`, { action: 'remove', id }, adminKey);
324
353
  return t('removed');
325
354
  });
326
355
 
327
356
  const clearKeys = () =>
328
357
  run('clear', async () => {
329
- await postJson(`${BASE}/keys`, { action: 'clear' }, adminKey);
358
+ await postJson(`${base}/keys`, { action: 'clear' }, adminKey);
330
359
  return t('cleared');
331
360
  });
332
361
 
333
362
  const refreshCatalog = () =>
334
363
  run('refresh', async () => {
335
- const value = await postJson(`${BASE}/keys`, { action: 'refresh-catalog' }, adminKey);
364
+ const value = await postJson(`${base}/keys`, { action: 'refresh-catalog' }, adminKey);
336
365
  return t('catalogRefreshed', { count: String(value?.catalog?.count ?? 0) });
337
366
  });
338
367
 
339
368
  const testKey = (id) =>
340
369
  run('test', async () => {
341
- const value = await postJson(`${BASE}/test`, { id }, adminKey);
370
+ const value = await postJson(`${base}/test`, { id }, adminKey);
342
371
  setTested((previous) => ({ ...previous, [id]: value }));
343
372
  return value.ok ? t('testOk', { ms: String(value.latencyMs) }) : t('testFail', { message: String(value.message).slice(0, 80) });
344
373
  });
345
374
 
346
375
  const toggleModel = (id, enabled) =>
347
376
  run('model', async () => {
348
- await postJson(`${BASE}/keys`, { action: 'set-model', id, enabled }, adminKey);
377
+ await postJson(`${base}/keys`, { action: 'set-model', id, enabled }, adminKey);
349
378
  return enabled ? t('modelShown', { id }) : t('modelHidden', { id });
350
379
  });
351
380
 
@@ -372,7 +401,7 @@ window.__ModuleLoader__.load({
372
401
 
373
402
  const submitLimits = (model) =>
374
403
  run('limits', async () => {
375
- await postJson(`${BASE}/keys`, limitsPayload(model, limitWindow, limitOutput), adminKey);
404
+ await postJson(`${base}/keys`, limitsPayload(model, limitWindow, limitOutput), adminKey);
376
405
  closeLimits();
377
406
  return t('limitsSaved', { id: model.id });
378
407
  });
@@ -380,7 +409,7 @@ window.__ModuleLoader__.load({
380
409
  const resetLimits = (model) =>
381
410
  run('limits', async () => {
382
411
  // 两个字段传空 = 恢复默认(服务端会归一成「不存覆盖」)。
383
- await postJson(`${BASE}/keys`, limitsPayload(model, '', ''), adminKey);
412
+ await postJson(`${base}/keys`, limitsPayload(model, '', ''), adminKey);
384
413
  closeLimits();
385
414
  return t('limitsReset', { id: model.id });
386
415
  });
@@ -397,9 +426,12 @@ window.__ModuleLoader__.load({
397
426
  const endpointReady = endpoint !== undefined && typeof endpoint.baseUrl === 'string' && endpoint.baseUrl !== '';
398
427
 
399
428
  return h('div', { style: rootStyle }, [
400
- variant === 'section' ? h('h2', { key: 'title', style: pageTitleStyle }, t('nav')) : null,
401
429
  h('p', { key: 'hint', style: hintStyle }, t('hint')),
402
430
 
431
+ upstream
432
+ ? h('p', { key: 'upstream', style: { ...codeStyle, margin: 0 } }, `${t('epUpstream')}:${upstream.upstream || '—'}`)
433
+ : null,
434
+
403
435
  summary
404
436
  ? h(
405
437
  'div',
@@ -673,6 +705,11 @@ window.__ModuleLoader__.load({
673
705
  copy: 'Copy',
674
706
  copied: 'Copied',
675
707
  copyFailed: 'Copy failed — select the text and copy manually.',
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.',
712
+ epUpstream: 'Upstream',
676
713
  keysTitle: 'Key pool',
677
714
  modelsTitle: 'Models in the picker',
678
715
  modelsHint: '{count} of {total} models are shown. Context window and max output are editable per model — clear a field to restore the default.',
@@ -728,6 +765,11 @@ window.__ModuleLoader__.load({
728
765
  copy: '复制',
729
766
  copied: '已复制',
730
767
  copyFailed: '复制失败,请手动选中文本复制。',
768
+ sitesTitle: '站点管理',
769
+ siteCn: '中国站',
770
+ siteIntl: '国际站',
771
+ sitesHint: '中国站与国际站同时可用,Key 池独立。Tab 仅切换当前显示的管理卡片,不是切换上游;Key 只在发卡站点有效。',
772
+ epUpstream: '上游地址',
731
773
  keysTitle: 'Key 池',
732
774
  modelsTitle: '下拉中的模型',
733
775
  modelsHint: '共 {total} 个模型,当前展示 {count} 个。窗口与最大输出可逐模型修改(清空输入框即恢复默认)。',
@@ -795,7 +837,7 @@ window.__ModuleLoader__.load({
795
837
  locale: NS,
796
838
  inject: () => ({ t }),
797
839
  },
798
- ({ t: seat }) => h(KeyCard, { t: seat, variant: 'section' }),
840
+ ({ t: seat }) => h(SiteTabs, { t: seat, variant: 'section' }),
799
841
  ),
800
842
  ),
801
843
  );
@@ -812,7 +854,7 @@ window.__ModuleLoader__.load({
812
854
  locale: NS,
813
855
  inject: () => ({ t }),
814
856
  },
815
- ({ 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' })),
816
858
  ),
817
859
  ),
818
860
  );
@@ -831,7 +873,7 @@ window.__ModuleLoader__.load({
831
873
  locale: NS,
832
874
  inject: () => ({ t }),
833
875
  },
834
- ({ t: seat }) => h(KeyCard, { t: seat, variant: 'card' }),
876
+ ({ t: seat }) => h(SiteTabs, { t: seat, variant: 'card' }),
835
877
  ),
836
878
  ),
837
879
  );
package/lib/index.d.ts CHANGED
@@ -15,6 +15,7 @@
15
15
  * 好处是「屏蔽 429」这件事被关在一个我们完全掌控的小盒子里:上层看到的永远是
16
16
  * 一个稳定的 OpenAI 兼容端点,429 在盒子内部被消化掉。
17
17
  */
18
+ import { type EndpointId } from './catalog.js';
18
19
  import { keyIdOf, maskKey } from './keypool.js';
19
20
  /** 本插件注册的 provider 路由名(模型选择器里显示为此分组)。 */
20
21
  declare const PROVIDER_ID = "sensenova-pool";
@@ -36,6 +37,7 @@ export declare const inject: string[];
36
37
  */
37
38
  export declare const Config: import("@deepseek-ai/schemastery").Schema;
38
39
  type PluginConfig = {
40
+ endpoint: EndpointId;
39
41
  baseUrl: string;
40
42
  maxAttempts: number;
41
43
  acquireTimeoutMs: number;
@@ -43,5 +45,6 @@ type PluginConfig = {
43
45
  rpmLimit: number;
44
46
  maxConcurrency: number;
45
47
  };
48
+ /** 两站各自创建完整运行实例;Tab 不参与请求路由。 */
46
49
  export declare function apply(ctx: any, config: PluginConfig): void;
47
50
  export { PROVIDER_ID, PROVIDER_NAME, SETTINGS_NS, maskKey, keyIdOf };
package/lib/index.js CHANGED
@@ -21,10 +21,10 @@ 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_BASE_URL, 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
- import { registerKeyRoutes, registerSettingsSection } from './routes.js';
27
+ import { registerKeyRoutes, registerSettingsSection, } from './routes.js';
28
28
  /** 本插件注册的 provider 路由名(模型选择器里显示为此分组)。 */
29
29
  const PROVIDER_ID = 'sensenova-pool';
30
30
  const PROVIDER_NAME = '商汤日日新(Key 轮换池)';
@@ -48,6 +48,22 @@ const STREAM_IDLE_TIMEOUT_MS = 300_000;
48
48
  * 插件配置里调大;设为 0 即关闭本地预限流。
49
49
  */
50
50
  const DEFAULT_RPM_LIMIT = 2;
51
+ /**
52
+ * 每个端点的默认 RPM 预限流值。
53
+ *
54
+ * 两个站的额度互不相干(账号与套餐都在各自的站上),所以额度也分开算:
55
+ * - 中国站沿用实测值 2(真实上限约 3 RPM,见上);
56
+ * - 国际站取保守值 3:2026-11-19 用真实国际站 key 实测连续逐档位打点观察时长
57
+ * 一直在秒级,没有撞到限流。仍取低于「假设上限」的值 —— 本地预限流宁可保守,
58
+ * 调大它不会提高吞吐,只会更容易被限流。
59
+ *
60
+ * 用户在 config 里显式写了 `rpmLimit` 时,该值对**两个端点**都生效(见 apply)。
61
+ */
62
+ const ENDPOINT_RPM_LIMIT = { cn: DEFAULT_RPM_LIMIT, intl: 3 };
63
+ /** 该端点的默认 RPM 上限。 */
64
+ function defaultRpmLimitFor(endpointId) {
65
+ return ENDPOINT_RPM_LIMIT[endpointFor(endpointId).id];
66
+ }
51
67
  /** 与 pi-ai 约定的本路由图片预算;与本插件无关但 profile 形状需要它。 */
52
68
  const REQUEST_IMAGE_BUDGETS = {
53
69
  maxRequestImageBytes: 20_971_520,
@@ -65,14 +81,23 @@ export const inject = ['llm'];
65
81
  * 这类非机密参数。
66
82
  */
67
83
  export const Config = z.object({
68
- baseUrl: z.string().default(DEFAULT_BASE_URL).description('商汤日日新 API 根地址'),
84
+ endpoint: z
85
+ .string()
86
+ .default(DEFAULT_ENDPOINT_ID)
87
+ .description('上游端点:cn = 中国站(token.sensenova.cn),intl = 国际站(token.sensenova.ai)。' +
88
+ '两站同时运行;该字段仅用于旧记录迁移和旧自定义地址归属。' +
89
+ '写错的值不会被拒绝,而是回落到 cn(不让一个拼写问题把插件卡在加载阶段)。'),
90
+ baseUrl: z
91
+ .string()
92
+ .default('')
93
+ .description('覆盖 endpoint 指定站点的地址(留空使用官方地址);另一站保持官方地址,避免跨站发送 Key。'),
69
94
  maxAttempts: z.number().default(6).description('单个请求最多尝试几把 key'),
70
95
  acquireTimeoutMs: z.number().default(180_000).description('等待可用 key 的总预算(毫秒)'),
71
96
  requestTimeoutMs: z.number().default(60_000).description('单次上游请求超时(毫秒)'),
72
97
  rpmLimit: z
73
98
  .number()
74
- .default(DEFAULT_RPM_LIMIT)
75
- .description('每把 key 的本地 RPM 预限流上限;0 表示不限制'),
99
+ .default(-1)
100
+ .description('每把 key 的本地 RPM 预限流上限;0 表示不限制;-1(默认)表示按端点取默认值(中国站 2 / 国际站 3)。'),
76
101
  maxConcurrency: z.number().default(1).description('每把 key 的并发上限;1 表示串行(推荐)'),
77
102
  });
78
103
  /**
@@ -106,13 +131,25 @@ const INERT_AUTH = {
106
131
  },
107
132
  },
108
133
  };
134
+ /** 两站各自创建完整运行实例;Tab 不参与请求路由。 */
109
135
  export function apply(ctx, config) {
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);
144
+ /**
145
+ * config 里显式写的 `rpmLimit`(≥0 才算显式);-1(默认)表示「按端点取默认值」。
146
+ */
147
+ const explicitRpmLimit = typeof config?.rpmLimit === 'number' && config.rpmLimit >= 0 ? config.rpmLimit : null;
110
148
  const resolved = {
111
- baseUrl: config?.baseUrl || DEFAULT_BASE_URL,
149
+ baseUrl: typeof config?.baseUrl === 'string' ? config.baseUrl.trim() : '',
112
150
  maxAttempts: config?.maxAttempts ?? 6,
113
151
  acquireTimeoutMs: config?.acquireTimeoutMs ?? 120_000,
114
152
  requestTimeoutMs: config?.requestTimeoutMs ?? 60_000,
115
- rpmLimit: config?.rpmLimit ?? 0,
116
153
  maxConcurrency: config?.maxConcurrency ?? 1,
117
154
  };
118
155
  const logger = {
@@ -120,9 +157,29 @@ export function apply(ctx, config) {
120
157
  warn: (message) => ctx.logger?.warn?.(`sensenova-pool: ${message}`),
121
158
  error: (message) => ctx.logger?.error?.(`sensenova-pool: ${message}`),
122
159
  };
160
+ /** 本实例的固定站点,凭据重载或 Tab 操作均不改变它。 */
161
+ const currentEndpoint = configEndpoint;
162
+ /**
163
+ * 兼容旧自定义网关:仅 config.endpoint 对应站点使用自定义地址,另一站使用官方地址。
164
+ */
165
+ const baseUrlPinned = resolved.baseUrl.length > 0;
166
+ /** 所选端点对应的上游根地址。 */
167
+ function upstreamFor(endpoint) {
168
+ // 旧版自定义地址只用于其配置所属站,禁止另一站也复用它而泄漏 Key。
169
+ return baseUrlPinned && site === endpointFor(config?.endpoint).id ? resolved.baseUrl : endpoint.baseUrl;
170
+ }
171
+ /** 该端点下每把 key 的本地 RPM 上限(0 表示不限流)。 */
172
+ function rpmLimitFor(endpoint) {
173
+ return explicitRpmLimit ?? defaultRpmLimitFor(endpoint.id);
174
+ }
123
175
  const catalog = new ModelCatalog();
176
+ // 每个实例只装载本站基线;自定义网关不改变站点身份。
177
+ catalog.reset(currentEndpoint.id);
124
178
  const pool = new KeyPool([], {
125
- rpmLimit: resolved.rpmLimit > 0 ? resolved.rpmLimit : null,
179
+ rpmLimit: (() => {
180
+ const limit = rpmLimitFor(currentEndpoint);
181
+ return limit > 0 ? limit : null;
182
+ })(),
126
183
  maxConcurrency: resolved.maxConcurrency,
127
184
  });
128
185
  /**
@@ -164,12 +221,13 @@ export function apply(ctx, config) {
164
221
  let externalKey = '';
165
222
  /** 凭据库里是否**已有**本插件的记录(决定首次装载后要不要立刻补写)。 */
166
223
  let recordExisted = false;
224
+ let migrationPending = false;
167
225
  /** 最近的轮换事件,供状态页展示「刚才发生了什么」。 */
168
226
  const recentRotations = [];
169
227
  const shim = createShim({
170
228
  pool,
171
229
  catalog,
172
- baseUrl: resolved.baseUrl,
230
+ baseUrl: upstreamFor(currentEndpoint),
173
231
  rotation: {
174
232
  maxAttempts: resolved.maxAttempts,
175
233
  acquireTimeoutMs: resolved.acquireTimeoutMs,
@@ -197,6 +255,19 @@ export function apply(ctx, config) {
197
255
  return { baseUrl: '', port: 0, apiKey: shim.token() };
198
256
  }
199
257
  },
258
+ upstreamEndpoint: () => ({
259
+ current: currentEndpoint.id,
260
+ upstream: shim.upstream(),
261
+ // 是否为本站配置了自定义上游。
262
+ pinned: baseUrlPinned && site === endpointFor(config?.endpoint).id,
263
+ rpmLimit: rpmLimitFor(currentEndpoint),
264
+ options: ENDPOINTS.map((option) => ({
265
+ id: option.id,
266
+ label: option.label,
267
+ baseUrl: option.baseUrl,
268
+ active: option.id === currentEndpoint.id,
269
+ })),
270
+ }),
200
271
  models: () => catalog.current().map((model) => {
201
272
  const limits = limitsFor(model);
202
273
  return {
@@ -213,7 +284,8 @@ export function apply(ctx, config) {
213
284
  }),
214
285
  providerId: PROVIDER_ID,
215
286
  providerName: PROVIDER_NAME,
216
- baseUrl: resolved.baseUrl,
287
+ // 当前生效的上游根地址(不是回环地址):用于展示与单把 key 探活。
288
+ baseUrl: shim.upstream(),
217
289
  };
218
290
  // ---------------------------------------------------------------- 凭据装载
219
291
  /**
@@ -228,7 +300,8 @@ export function apply(ctx, config) {
228
300
  * 一套持久化路径不值得。grant 的 payload 是**逐字保留**的,多几个字段完全安全。
229
301
  */
230
302
  const RECORD_SCOPE = 'dsh-sensenova-pool';
231
- const RECORD_ID = `${RECORD_SCOPE}/keys`;
303
+ const RECORD_ID = `${RECORD_SCOPE}/keys-${site}`;
304
+ const LEGACY_RECORD_ID = `${RECORD_SCOPE}/keys`;
232
305
  /**
233
306
  * 写入前等待首次权威装载的上限(毫秒)。
234
307
  *
@@ -279,6 +352,7 @@ export function apply(ctx, config) {
279
352
  * 权威装载之前写入(启动还没完,用户就点了「添加 Key」),池子里只有刚加的那把,
280
353
  * 磁盘上原有的 key 会被静默抹掉。
281
354
  */
355
+ let authoritativeLoaded = false;
282
356
  let notifyKeysLoaded;
283
357
  const firstAuthoritativeLoad = new Promise((resolve) => {
284
358
  notifyKeysLoaded = resolve;
@@ -308,6 +382,18 @@ export function apply(ctx, config) {
308
382
  }
309
383
  }
310
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;
311
397
  notifyKeysLoaded?.();
312
398
  }
313
399
  return added;
@@ -325,14 +411,28 @@ export function apply(ctx, config) {
325
411
  let record;
326
412
  try {
327
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
+ }
328
424
  }
329
425
  catch (error) {
330
- logger.warn(`读取 key 记录失败:${error instanceof Error ? error.message : String(error)}`);
331
- return 0;
426
+ throw new Error(`读取 key 记录失败:${error instanceof Error ? error.message : String(error)}`);
332
427
  }
333
428
  const payload = record?.payload ?? {};
334
429
  recordExisted = record !== undefined && record !== null;
335
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
+ }
336
436
  let added = 0;
337
437
  for (const raw of keys) {
338
438
  if (typeof raw === 'string' && pool.addKey(raw))
@@ -369,6 +469,7 @@ export function apply(ctx, config) {
369
469
  externalKey = payload.externalKey;
370
470
  shim.setToken(externalKey);
371
471
  }
472
+ // 本实例的站点固定,不采纳记录里的切站请求。
372
473
  if (added > 0)
373
474
  logger.info(`已装载 ${added} 把 key`);
374
475
  return added;
@@ -417,6 +518,8 @@ export function apply(ctx, config) {
417
518
  // 只存用户真正改过的模型;没有覆盖的模型不出现在这里。
418
519
  modelLimits: Object.fromEntries(modelLimits),
419
520
  externalKey,
521
+ // 端点选择:只存认得出的 id,避免把脏值写进凭据库。
522
+ endpoint: currentEndpoint.id,
420
523
  },
421
524
  }));
422
525
  }
@@ -622,10 +725,9 @@ export function apply(ctx, config) {
622
725
  return;
623
726
  void loadKeysAndNotify()
624
727
  .then((added) => {
625
- if (added > 0) {
626
- refreshCatalog();
728
+ refreshCatalog();
729
+ if (added > 0)
627
730
  void fetchCatalogFromUpstream();
628
- }
629
731
  })
630
732
  .catch((error) => {
631
733
  logger.warn(`记录变更后重载失败:${error instanceof Error ? error.message : String(error)}`);
@@ -643,7 +745,9 @@ export function apply(ctx, config) {
643
745
  async function fetchCatalogFromUpstream() {
644
746
  if (pool.size === 0)
645
747
  return;
646
- const url = `${resolved.baseUrl.replace(/\/+$/, '')}/models`;
748
+ // 目录和上游固定属于本站,另一站的刷新不会覆盖本实例。
749
+ const endpoint = currentEndpoint;
750
+ const url = `${shim.upstream().replace(/\/+$/, '')}/models`;
647
751
  const attempted = new Set();
648
752
  for (let index = 0; index < Math.min(pool.size + 1, 4); index += 1) {
649
753
  let entry;
@@ -661,7 +765,7 @@ export function apply(ctx, config) {
661
765
  });
662
766
  if (response.ok) {
663
767
  const payload = await response.json();
664
- const count = catalog.apply(payload);
768
+ const count = catalog.apply(payload, builtinModelsFor(endpoint.id));
665
769
  pool.reportSuccess(entry);
666
770
  if (count > 0) {
667
771
  logger.info(`模型目录已更新:${count} 个模型`);
@@ -740,14 +844,20 @@ export function apply(ctx, config) {
740
844
  logger.warn(`模型窗口设置落盘失败(本次会话已生效):${error instanceof Error ? error.message : String(error)}`);
741
845
  }
742
846
  };
847
+ /** 保留旧接口但禁止修改固定站点的上游,避免旧客户端串站。 */
848
+ const handleEndpointChanged = async (id) => {
849
+ if (id !== site)
850
+ throw new Error('站点已隔离,请在设置页切换 Tab,不支持切换实例上游');
851
+ };
743
852
  // 设置页:填 key(用户明确要求只在设置页填)。
744
853
  try {
745
- registerSettingsSection(ctx, {
746
- namespace: SETTINGS_NS,
747
- config,
748
- pool,
749
- onKeysChanged: handleKeysChanged,
750
- });
854
+ if (site === 'cn')
855
+ registerSettingsSection(ctx, {
856
+ namespace: SETTINGS_NS,
857
+ config,
858
+ pool,
859
+ onKeysChanged: handleKeysChanged,
860
+ });
751
861
  }
752
862
  catch (error) {
753
863
  logger.warn(`设置页注册失败(不影响模型可用):${error instanceof Error ? error.message : String(error)}`);
@@ -761,6 +871,14 @@ export function apply(ctx, config) {
761
871
  onKeysChanged: handleKeysChanged,
762
872
  onModelsChanged: handleModelsChanged,
763
873
  onModelLimitsChanged: handleModelLimitsChanged,
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
+ },
764
882
  reload: async () => {
765
883
  // 手动重载:走同一套「装载并宣告」逻辑,因此在启动早期点它也不会把
766
884
  // 「还没读到」误当成「真的没有 key」而清空权威装载信号。
@@ -768,7 +886,7 @@ export function apply(ctx, config) {
768
886
  refreshCatalog();
769
887
  },
770
888
  fetchCatalog: fetchCatalogFromUpstream,
771
- });
889
+ }, site === 'cn' ? undefined : '/plugins/dsh-sensenova-pool/intl');
772
890
  }
773
891
  catch (error) {
774
892
  logger.warn(`Web 路由注册失败:${error instanceof Error ? error.message : String(error)}`);
package/lib/keypool.d.ts CHANGED
@@ -171,6 +171,26 @@ export declare class KeyPool {
171
171
  invalid: number;
172
172
  inflight: number;
173
173
  };
174
+ /**
175
+ * 调整本地 RPM 预限流上限(运行期可改)。
176
+ *
177
+ * 为什么要它:两个端点(中国站 / 国际站)的限流额度并不相同,而插件允许在
178
+ * 设置卡片里切换端点。若不随之调整,换站只会换地址,额度仍压在旧值上。
179
+ * 传 null 表示不限制。
180
+ */
181
+ setRpmLimit(limit: number | null): void;
182
+ get rpmLimitValue(): number | null;
183
+ /** 调整每把 key 的并发上限(运行期可改)。 */
184
+ setMaxConcurrency(value: number): void;
185
+ get maxConcurrencyValue(): number;
186
+ /**
187
+ * 清空冷却与失效标记,重新给每把 key 一次机会。
188
+ *
189
+ * 切换端点时使用:冷却/失效是针对旧端点记下的上游行为,新端点的额度与套餐
190
+ * 都不同,带着旧标记进新站会让刚切过去的几分钟内一把 key 都用不了。
191
+ * key 本身与累计统计(请求数 / 成功率)保留 —— 那些是事实,不该被抹掉。
192
+ */
193
+ resetHealth(): number;
174
194
  /** 当前是否有任何 key 立即可用(不等待)。 */
175
195
  anyUsable(): boolean;
176
196
  }
package/lib/keypool.js CHANGED
@@ -431,6 +431,61 @@ export class KeyPool {
431
431
  inflight: this.entries.reduce((sum, entry) => sum + entry.inflight, 0),
432
432
  };
433
433
  }
434
+ /**
435
+ * 调整本地 RPM 预限流上限(运行期可改)。
436
+ *
437
+ * 为什么要它:两个端点(中国站 / 国际站)的限流额度并不相同,而插件允许在
438
+ * 设置卡片里切换端点。若不随之调整,换站只会换地址,额度仍压在旧值上。
439
+ * 传 null 表示不限制。
440
+ */
441
+ setRpmLimit(limit) {
442
+ const next = limit !== null && limit > 0 ? limit : null;
443
+ if (next === this.rpmLimit)
444
+ return;
445
+ this.rpmLimit = next;
446
+ // 窗口里的历史时间戳保持原样:它们代表真实发过的请求,放宽后立刻生效,
447
+ // 收紧后由 rpmBlockedUntil 自然消化。
448
+ this.notify();
449
+ }
450
+ get rpmLimitValue() {
451
+ return this.rpmLimit;
452
+ }
453
+ /** 调整每把 key 的并发上限(运行期可改)。 */
454
+ setMaxConcurrency(value) {
455
+ const next = Math.max(1, Math.trunc(Number.isFinite(value) ? value : 1));
456
+ if (next === this.maxConcurrency)
457
+ return;
458
+ this.maxConcurrency = next;
459
+ this.notify();
460
+ }
461
+ get maxConcurrencyValue() {
462
+ return this.maxConcurrency;
463
+ }
464
+ /**
465
+ * 清空冷却与失效标记,重新给每把 key 一次机会。
466
+ *
467
+ * 切换端点时使用:冷却/失效是针对旧端点记下的上游行为,新端点的额度与套餐
468
+ * 都不同,带着旧标记进新站会让刚切过去的几分钟内一把 key 都用不了。
469
+ * key 本身与累计统计(请求数 / 成功率)保留 —— 那些是事实,不该被抹掉。
470
+ */
471
+ resetHealth() {
472
+ let reset = 0;
473
+ for (const entry of this.entries) {
474
+ if (entry.status === 'healthy' &&
475
+ entry.cooldownUntil === 0 &&
476
+ entry.consecutiveFailures === 0) {
477
+ continue;
478
+ }
479
+ entry.status = 'healthy';
480
+ entry.cooldownUntil = 0;
481
+ entry.consecutiveFailures = 0;
482
+ entry.lastError = '';
483
+ reset += 1;
484
+ }
485
+ if (reset > 0)
486
+ this.notify();
487
+ return reset;
488
+ }
434
489
  /** 当前是否有任何 key 立即可用(不等待)。 */
435
490
  anyUsable() {
436
491
  const now = Date.now();