dsh-sensenova-pool 0.1.2 → 0.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/README.md +349 -267
- package/lib/client.js +297 -73
- package/lib/index.js +299 -29
- package/lib/routes.d.ts +16 -0
- package/lib/routes.js +26 -0
- package/lib/shim.d.ts +9 -0
- package/lib/shim.js +36 -9
- package/package.json +79 -78
package/lib/index.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* 好处是「屏蔽 429」这件事被关在一个我们完全掌控的小盒子里:上层看到的永远是
|
|
16
16
|
* 一个稳定的 OpenAI 兼容端点,429 在盒子内部被消化掉。
|
|
17
17
|
*/
|
|
18
|
+
import { randomBytes } from 'node:crypto';
|
|
18
19
|
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai';
|
|
19
20
|
import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm';
|
|
20
21
|
import { createProvider } from '@earendil-works/pi-ai';
|
|
@@ -124,6 +125,22 @@ export function apply(ctx, config) {
|
|
|
124
125
|
rpmLimit: resolved.rpmLimit > 0 ? resolved.rpmLimit : null,
|
|
125
126
|
maxConcurrency: resolved.maxConcurrency,
|
|
126
127
|
});
|
|
128
|
+
/**
|
|
129
|
+
* 被用户隐藏的模型 id。
|
|
130
|
+
*
|
|
131
|
+
* 「下拉里展示什么」是用户自己的偏好,与 key 一样跨重启保留:勾掉的模型不进入
|
|
132
|
+
* `buildModels()`,因此不会出现在模型选择器里(上游仍然可用,只是不展示)。
|
|
133
|
+
*/
|
|
134
|
+
const disabledModels = new Set();
|
|
135
|
+
/**
|
|
136
|
+
* 对外暴露的 API Key(别的服务用它访问本地 shim)。
|
|
137
|
+
*
|
|
138
|
+
* 持久化在凭据记录里,重启后保持不变 —— 否则每次启动都换一把,外部服务就得
|
|
139
|
+
* 反复改配置。启动装载完成前它是空串,此时 shim 用的是进程内随机密钥。
|
|
140
|
+
*/
|
|
141
|
+
let externalKey = '';
|
|
142
|
+
/** 凭据库里是否**已有**本插件的记录(决定首次装载后要不要立刻补写)。 */
|
|
143
|
+
let recordExisted = false;
|
|
127
144
|
/** 最近的轮换事件,供状态页展示「刚才发生了什么」。 */
|
|
128
145
|
const recentRotations = [];
|
|
129
146
|
const shim = createShim({
|
|
@@ -148,23 +165,127 @@ export function apply(ctx, config) {
|
|
|
148
165
|
summary: () => pool.summary(),
|
|
149
166
|
catalog: () => catalog.status(),
|
|
150
167
|
rotations: () => recentRotations.slice(0, 20),
|
|
168
|
+
endpoint: () => {
|
|
169
|
+
// shim 监听失败时 baseUrl() 会抛;这里降级成空串,让界面显示「不可用」而不是崩。
|
|
170
|
+
try {
|
|
171
|
+
return { baseUrl: `${shim.baseUrl()}/v1`, port: shim.port(), apiKey: shim.token() };
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return { baseUrl: '', port: 0, apiKey: shim.token() };
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
models: () => catalog.current().map((model) => ({
|
|
178
|
+
id: model.id,
|
|
179
|
+
name: model.name,
|
|
180
|
+
contextWindow: model.contextWindow,
|
|
181
|
+
maxTokens: model.maxTokens,
|
|
182
|
+
enabled: !disabledModels.has(model.id),
|
|
183
|
+
})),
|
|
151
184
|
providerId: PROVIDER_ID,
|
|
152
185
|
providerName: PROVIDER_NAME,
|
|
153
186
|
baseUrl: resolved.baseUrl,
|
|
154
187
|
};
|
|
155
188
|
// ---------------------------------------------------------------- 凭据装载
|
|
156
189
|
/**
|
|
157
|
-
* 从 DSH
|
|
190
|
+
* 从 DSH 凭据库读取本插件的状态。
|
|
158
191
|
*
|
|
159
|
-
* 存储方案:一个 `<scope>/keys` 记录,payload 里放 key
|
|
160
|
-
*
|
|
161
|
-
*
|
|
192
|
+
* 存储方案:一个 `<scope>/keys` 记录,payload 里放 key 数组、被隐藏的模型 id,
|
|
193
|
+
* 以及对外暴露的 API Key。用记录而不是环境变量引用,是因为用户要求「可以填多把
|
|
194
|
+
* key」——环境变量引用是单值的,无法表达一个池子。
|
|
195
|
+
*
|
|
196
|
+
* 为什么把「模型可见性」和「对外密钥」也塞进这条记录:DSH 的 settings 服务是
|
|
197
|
+
* 围绕插件 Config + profile patch 的配置编辑器,不是通用 KV;为这两个字段单开
|
|
198
|
+
* 一套持久化路径不值得。grant 的 payload 是**逐字保留**的,多几个字段完全安全。
|
|
162
199
|
*/
|
|
163
200
|
const RECORD_SCOPE = 'dsh-sensenova-pool';
|
|
164
201
|
const RECORD_ID = `${RECORD_SCOPE}/keys`;
|
|
202
|
+
/**
|
|
203
|
+
* 写入前等待首次权威装载的上限(毫秒)。
|
|
204
|
+
*
|
|
205
|
+
* 只作为兜底:正常路径下 `firstAuthoritativeLoad` 会在凭据服务就绪的那一刻兑现。
|
|
206
|
+
* 设上限是为了「宿主没有凭据服务」时不要永远挂住写入请求。
|
|
207
|
+
*/
|
|
208
|
+
const SAVE_LOAD_WAIT_MS = 10_000;
|
|
209
|
+
/** 严格读取:只返回**已就绪**(fiber ACTIVE)的凭据服务。 */
|
|
165
210
|
function credentialsService() {
|
|
166
211
|
return ctx.get?.('credentials');
|
|
167
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* 宽松读取:服务**已注册但可能仍在加载**时也能拿到实例。
|
|
215
|
+
*
|
|
216
|
+
* 用来区分两种「读不到凭据」:服务正在加载(应继续等),还是宿主压根没有这个
|
|
217
|
+
* 服务(应直接提示用户填 key)。
|
|
218
|
+
*/
|
|
219
|
+
function credentialsRegistered() {
|
|
220
|
+
try {
|
|
221
|
+
return ctx.get?.('credentials', false) !== undefined;
|
|
222
|
+
}
|
|
223
|
+
catch {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* 「首次**权威**装载」完成信号。
|
|
229
|
+
*
|
|
230
|
+
* 权威 = 凭据服务**真正就绪**(fiber 已 ACTIVE、`.credentials.yaml` 已解析进内存
|
|
231
|
+
* 快照),而不是「服务对象已构造」。这两者的区别正是 issue #1:
|
|
232
|
+
*
|
|
233
|
+
* 1. **已构造** —— `Service` 在构造函数里就 `provide()`,服务已能被解析到,但
|
|
234
|
+
* 所属 fiber 还停在 PENDING/LOADING,`Service.init` 尚未跑完;
|
|
235
|
+
* 2. **已就绪** —— `Service.init` 已结束,credentials-local 的 `loadInitial()`
|
|
236
|
+
* 已把 `.credentials.yaml` 填进内存快照。
|
|
237
|
+
*
|
|
238
|
+
* 本插件只 `inject: ['llm']`,与 credentials 之间**没有顺序保证**。冷启动磁盘 IO
|
|
239
|
+
* 慢时 `loadKeys()` 会先于 `loadInitial()` 执行,`readRecord()` 读到空快照 → key
|
|
240
|
+
* 池为 0,且此后没有任何补载机制(`credentials/record-updated` 只在运行期写入时
|
|
241
|
+
* 触发,覆盖不到启动装载)—— 这就是「重启电脑后 Key 池为空」。
|
|
242
|
+
*
|
|
243
|
+
* 修复方式不是「轮询 + 超时」,而是用 cordis 自己的就绪通知:`ctx.inject` 的回调
|
|
244
|
+
* **只在服务所属 fiber 变为 ACTIVE 时才触发**(已用真实 cordis 验证)。它精确、
|
|
245
|
+
* 零延迟,也不会给「宿主根本没有凭据服务」的环境白等一段超时 —— 那种情况下回调
|
|
246
|
+
* 只是不触发,启动路径照常给出「请填入 key」的提示。
|
|
247
|
+
*
|
|
248
|
+
* 之所以要等它再允许写入:`saveKeys()` 是用 `pool.keys()` **整体覆盖**记录。若在
|
|
249
|
+
* 权威装载之前写入(启动还没完,用户就点了「添加 Key」),池子里只有刚加的那把,
|
|
250
|
+
* 磁盘上原有的 key 会被静默抹掉。
|
|
251
|
+
*/
|
|
252
|
+
let notifyKeysLoaded;
|
|
253
|
+
const firstAuthoritativeLoad = new Promise((resolve) => {
|
|
254
|
+
notifyKeysLoaded = resolve;
|
|
255
|
+
});
|
|
256
|
+
/**
|
|
257
|
+
* 装载 key、模型可见性与对外密钥,并在**凭据快照确实可读**时宣告首次权威装载完成。
|
|
258
|
+
*
|
|
259
|
+
* 只有凭据服务可见时才宣告:否则「池子为空」只代表「还没读到」,不代表「真的没有
|
|
260
|
+
* key」,提前宣告会让 `saveKeys()` 把空池覆盖写回记录。
|
|
261
|
+
*/
|
|
262
|
+
async function loadKeysAndNotify() {
|
|
263
|
+
const added = await loadKeys();
|
|
264
|
+
if (credentialsService() !== undefined) {
|
|
265
|
+
// 记录里还没有对外密钥时生成一把。是否立刻落盘取决于记录**原本是否存在**:
|
|
266
|
+
// - 存在(老用户 / 已用过插件)→ 补写一次,把这把密钥固化下来;
|
|
267
|
+
// - 不存在(首次安装)→ 只放在内存里,等用户第一次添加 key 时随那次写入
|
|
268
|
+
// 一起落盘,避免仅为一把尚未使用的密钥就在凭据库里建记录。
|
|
269
|
+
if (!externalKey) {
|
|
270
|
+
externalKey = newExternalKey();
|
|
271
|
+
shim.setToken(externalKey);
|
|
272
|
+
if (recordExisted) {
|
|
273
|
+
try {
|
|
274
|
+
await persistRecord();
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
logger.warn(`对外密钥落盘失败(本次会话仍可用):${error instanceof Error ? error.message : String(error)}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
notifyKeysLoaded?.();
|
|
282
|
+
}
|
|
283
|
+
return added;
|
|
284
|
+
}
|
|
285
|
+
/** 生成一把形如商汤 key 的对外密钥(只被本地 shim 校验,不发给上游)。 */
|
|
286
|
+
function newExternalKey() {
|
|
287
|
+
return `sk-dsh-${randomBytes(24).toString('hex')}`;
|
|
288
|
+
}
|
|
168
289
|
async function loadKeys() {
|
|
169
290
|
const credentials = credentialsService();
|
|
170
291
|
if (credentials === undefined) {
|
|
@@ -179,21 +300,53 @@ export function apply(ctx, config) {
|
|
|
179
300
|
logger.warn(`读取 key 记录失败:${error instanceof Error ? error.message : String(error)}`);
|
|
180
301
|
return 0;
|
|
181
302
|
}
|
|
182
|
-
const
|
|
303
|
+
const payload = record?.payload ?? {};
|
|
304
|
+
recordExisted = record !== undefined && record !== null;
|
|
305
|
+
const keys = Array.isArray(payload.keys) ? payload.keys : [];
|
|
183
306
|
let added = 0;
|
|
184
307
|
for (const raw of keys) {
|
|
185
308
|
if (typeof raw === 'string' && pool.addKey(raw))
|
|
186
309
|
added += 1;
|
|
187
310
|
}
|
|
311
|
+
// 模型可见性:记录里没有该字段时表示「全部展示」。
|
|
312
|
+
disabledModels.clear();
|
|
313
|
+
if (Array.isArray(payload.disabledModels)) {
|
|
314
|
+
for (const id of payload.disabledModels) {
|
|
315
|
+
if (typeof id === 'string' && id.length > 0)
|
|
316
|
+
disabledModels.add(id);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// 对外密钥:拿到持久化的那把后立刻换上,DSH 与外部服务从此用同一个。
|
|
320
|
+
if (typeof payload.externalKey === 'string' && payload.externalKey.length >= 16) {
|
|
321
|
+
externalKey = payload.externalKey;
|
|
322
|
+
shim.setToken(externalKey);
|
|
323
|
+
}
|
|
188
324
|
if (added > 0)
|
|
189
325
|
logger.info(`已装载 ${added} 把 key`);
|
|
190
326
|
return added;
|
|
191
327
|
}
|
|
192
|
-
|
|
328
|
+
/**
|
|
329
|
+
* 可被进程退出的定时器(`unref`)。
|
|
330
|
+
*
|
|
331
|
+
* 为什么不用裸 `setTimeout`:这里只拿它当「兜底超时」,正常路径下由 Promise 先行
|
|
332
|
+
* 兑现。裸定时器会一直挂在事件循环上,让 DSH 退出时多等一段、也让测试无谓变慢。
|
|
333
|
+
*/
|
|
334
|
+
function delay(ms) {
|
|
335
|
+
return new Promise((resolve) => {
|
|
336
|
+
const timer = setTimeout(resolve, ms);
|
|
337
|
+
timer?.unref?.();
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* 把当前内存状态整体写回记录(**不等待**权威装载)。
|
|
342
|
+
*
|
|
343
|
+
* 只给两条路径用:启动装载完成后的补写(此时快照刚读过,权威),以及已经等过
|
|
344
|
+
* `firstAuthoritativeLoad` 的 `saveKeys()`。别在启动早期直接调它。
|
|
345
|
+
*/
|
|
346
|
+
async function persistRecord() {
|
|
193
347
|
const credentials = credentialsService();
|
|
194
348
|
if (credentials === undefined)
|
|
195
|
-
throw new Error('凭据服务不可用,无法保存
|
|
196
|
-
const keys = pool.keys();
|
|
349
|
+
throw new Error('凭据服务不可用,无法保存');
|
|
197
350
|
// 必须用 `grant`,不能用 `api-key`。
|
|
198
351
|
//
|
|
199
352
|
// credentials-local 对记录做白名单校验(`assertFields`),两种标签允许的字段
|
|
@@ -210,13 +363,34 @@ export function apply(ctx, config) {
|
|
|
210
363
|
// 的标签必须与 schema 严格对齐。
|
|
211
364
|
await credentials.modifyRecord(RECORD_ID, async () => ({
|
|
212
365
|
kind: 'grant',
|
|
213
|
-
payload: {
|
|
366
|
+
payload: {
|
|
367
|
+
keys: pool.keys(),
|
|
368
|
+
disabledModels: [...disabledModels],
|
|
369
|
+
externalKey,
|
|
370
|
+
},
|
|
214
371
|
}));
|
|
215
372
|
}
|
|
373
|
+
async function saveKeys() {
|
|
374
|
+
// 写入前必须确保首次**权威**装载已完成:写入是整体覆盖,若此时池子还是
|
|
375
|
+
// 空的(快照尚未读到),磁盘上原有的 key 会被这次写入静默抹掉。
|
|
376
|
+
//
|
|
377
|
+
// 只在凭据服务**确实存在**时才等:宿主压根没有该服务时,等它没有意义,直接让
|
|
378
|
+
// 下面给出明确错误,而不是让用户对着转圈的按钮等满超时。
|
|
379
|
+
if (credentialsRegistered()) {
|
|
380
|
+
await Promise.race([firstAuthoritativeLoad, delay(SAVE_LOAD_WAIT_MS)]);
|
|
381
|
+
}
|
|
382
|
+
if (credentialsService() === undefined)
|
|
383
|
+
throw new Error('凭据服务不可用,无法保存 key');
|
|
384
|
+
await persistRecord();
|
|
385
|
+
}
|
|
216
386
|
// ------------------------------------------------------------ provider 注册
|
|
217
387
|
function buildModels() {
|
|
218
388
|
const baseUrl = `${shim.baseUrl()}/v1`;
|
|
219
|
-
return catalog
|
|
389
|
+
return catalog
|
|
390
|
+
.current()
|
|
391
|
+
// 用户在下拉里勾掉的模型不注册,因此不会出现在模型选择器里。
|
|
392
|
+
.filter((model) => !disabledModels.has(model.id))
|
|
393
|
+
.map((model) => ({
|
|
220
394
|
id: model.id,
|
|
221
395
|
name: model.name,
|
|
222
396
|
api: 'openai-completions',
|
|
@@ -320,6 +494,8 @@ export function apply(ctx, config) {
|
|
|
320
494
|
}
|
|
321
495
|
catch (error) {
|
|
322
496
|
logger.error(`回环端点启动失败:${error instanceof Error ? error.message : String(error)}`);
|
|
497
|
+
// 监听失败时 server 可能已部分启动;显式关闭,避免留下半开的句柄。
|
|
498
|
+
await shim.close().catch(() => { });
|
|
323
499
|
return;
|
|
324
500
|
}
|
|
325
501
|
// ---- 端口就绪,此时才能安全构建模型描述符并注册 provider ----------------
|
|
@@ -327,29 +503,97 @@ export function apply(ctx, config) {
|
|
|
327
503
|
adapter = createAdapter();
|
|
328
504
|
registration = ctx.llm.registerAdapter([PROVIDER_ID], adapter);
|
|
329
505
|
ctx.effect?.(() => () => {
|
|
506
|
+
// 必须**返回** close() 的 Promise:cordis 的 disposer 可以是异步的,返回它
|
|
507
|
+
// 才会等回环服务真正关闭。原先写成 `void shim.close()`,卸载时 Promise 无人
|
|
508
|
+
// 等待,server 仍在监听的状态下进程就可能退出 —— 在 Windows 上表现为 libuv
|
|
509
|
+
// 断言(async.c: !(handle->flags & UV_HANDLE_CLOSING)),退出码 0xC0000409。
|
|
330
510
|
try {
|
|
331
511
|
registration?.();
|
|
332
512
|
}
|
|
333
513
|
finally {
|
|
334
|
-
|
|
514
|
+
return shim.close();
|
|
335
515
|
}
|
|
336
516
|
});
|
|
337
517
|
logger.info(`已注册 provider "${PROVIDER_ID}",模型分组「${PROVIDER_NAME}」`);
|
|
338
518
|
}
|
|
339
519
|
catch (error) {
|
|
340
520
|
logger.error(`注册 provider 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
341
|
-
|
|
521
|
+
await shim.close();
|
|
342
522
|
return;
|
|
343
523
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
524
|
+
// ---- 装载 key(issue #1:等凭据快照真正就绪) --------------------------
|
|
525
|
+
//
|
|
526
|
+
// 这里不再「立刻读一次就算」,而是等凭据服务就绪的通知:`ctx.inject` 的回调
|
|
527
|
+
// 只在 credentials 所属 fiber 变为 ACTIVE(`loadInitial()` 已填充快照)时触发。
|
|
528
|
+
// 冷启动磁盘 IO 慢时,正是这一等把「读到空快照」变成了「读到真实的 key 列表」。
|
|
529
|
+
//
|
|
530
|
+
// 回调可能因服务重注册而多次触发;`pool.addKey()` 幂等,重复装载安全。
|
|
531
|
+
const onCredentialsReady = () => {
|
|
532
|
+
void loadKeysAndNotify()
|
|
533
|
+
.then((added) => {
|
|
534
|
+
if (added > 0) {
|
|
535
|
+
refreshCatalog();
|
|
536
|
+
void fetchCatalogFromUpstream();
|
|
537
|
+
}
|
|
538
|
+
else {
|
|
539
|
+
logger.info('key 池为空 —— 请在「设置 → 插件 → 商汤日日新(Key 轮换池)」里填入 key');
|
|
540
|
+
}
|
|
541
|
+
})
|
|
542
|
+
.catch((error) => {
|
|
543
|
+
logger.warn(`装载 key 失败:${error instanceof Error ? error.message : String(error)}`);
|
|
544
|
+
});
|
|
545
|
+
};
|
|
546
|
+
if (typeof ctx.inject === 'function') {
|
|
547
|
+
try {
|
|
548
|
+
ctx.inject(['credentials'], onCredentialsReady);
|
|
549
|
+
}
|
|
550
|
+
catch (error) {
|
|
551
|
+
// 注入注册失败(例如 ctx 形状不符):退化为「服务已就绪就直接装载一次」,
|
|
552
|
+
// 至少不比旧行为更差。
|
|
553
|
+
logger.warn(`等待凭据服务就绪失败,改为立即尝试装载:${error instanceof Error ? error.message : String(error)}`);
|
|
554
|
+
if (credentialsService() !== undefined)
|
|
555
|
+
onCredentialsReady();
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
else if (credentialsService() !== undefined) {
|
|
559
|
+
// 极老的宿主没有 ctx.inject:退化为直接装载一次(此时服务已就绪)。
|
|
560
|
+
onCredentialsReady();
|
|
348
561
|
}
|
|
349
|
-
|
|
562
|
+
// 宿主没有凭据服务时,上面的回调永不触发 —— 仍需给出可操作的提示(与旧行为一致)。
|
|
563
|
+
// 但如果服务**已注册、只是在加载**(冷启动的竞态场景),就绝不能在这里报
|
|
564
|
+
// 「池为空」:那是还没读到,不是真的没有 key。此时静默等待即可。
|
|
565
|
+
await delay(0);
|
|
566
|
+
if (credentialsService() === undefined && !credentialsRegistered()) {
|
|
350
567
|
logger.info('key 池为空 —— 请在「设置 → 插件 → 商汤日日新(Key 轮换池)」里填入 key');
|
|
351
568
|
}
|
|
352
569
|
})();
|
|
570
|
+
/**
|
|
571
|
+
* 兜底补载:凭据记录被**本进程之外**改动时(手工编辑 `.credentials.yaml`、
|
|
572
|
+
* 另一次 boot 迁移了文档布局),credentials-local 的 watcher 会 emit
|
|
573
|
+
* `credentials/record-updated`。这里据此重载,使池子最终一致。
|
|
574
|
+
*
|
|
575
|
+
* 注意这不是启动竞态的修复手段 —— 那条路径由 `ctx.inject(['credentials'])` 负责,
|
|
576
|
+
* 因为启动装载**早于**任何事件发生,等事件是等不到的。这里只覆盖运行期变更。
|
|
577
|
+
*/
|
|
578
|
+
try {
|
|
579
|
+
ctx.on?.('credentials/record-updated', (key) => {
|
|
580
|
+
if (key !== RECORD_ID)
|
|
581
|
+
return;
|
|
582
|
+
void loadKeysAndNotify()
|
|
583
|
+
.then((added) => {
|
|
584
|
+
if (added > 0) {
|
|
585
|
+
refreshCatalog();
|
|
586
|
+
void fetchCatalogFromUpstream();
|
|
587
|
+
}
|
|
588
|
+
})
|
|
589
|
+
.catch((error) => {
|
|
590
|
+
logger.warn(`记录变更后重载失败:${error instanceof Error ? error.message : String(error)}`);
|
|
591
|
+
});
|
|
592
|
+
});
|
|
593
|
+
}
|
|
594
|
+
catch {
|
|
595
|
+
// 事件总线形状不符:不影响主路径。
|
|
596
|
+
}
|
|
353
597
|
/**
|
|
354
598
|
* 用池里的 key 拉取真实模型目录。
|
|
355
599
|
*
|
|
@@ -405,35 +649,61 @@ export function apply(ctx, config) {
|
|
|
405
649
|
}
|
|
406
650
|
}
|
|
407
651
|
// --------------------------------------------------------------- 可选界面
|
|
652
|
+
/**
|
|
653
|
+
* 保存 key 列表并刷新模型目录。
|
|
654
|
+
*
|
|
655
|
+
* 顺序有讲究:先落盘再 refreshCatalog —— 刷新会让模型选择器立刻重读模型,
|
|
656
|
+
* 若此时记录还没写成功,用户会看到「列表变了但重启又回去了」。
|
|
657
|
+
*/
|
|
658
|
+
const handleKeysChanged = async () => {
|
|
659
|
+
await saveKeys();
|
|
660
|
+
refreshCatalog();
|
|
661
|
+
void fetchCatalogFromUpstream();
|
|
662
|
+
};
|
|
663
|
+
/**
|
|
664
|
+
* 应用「哪些模型出现在下拉里」。
|
|
665
|
+
*
|
|
666
|
+
* 落盘失败不算失败:可见性已经作用于内存,下次写入会一并带上;这里只记一条
|
|
667
|
+
* 日志,不让界面上的勾选因为磁盘问题而回弹。
|
|
668
|
+
*/
|
|
669
|
+
const handleModelsChanged = async (nextDisabled) => {
|
|
670
|
+
disabledModels.clear();
|
|
671
|
+
for (const id of nextDisabled) {
|
|
672
|
+
if (typeof id === 'string' && id.length > 0)
|
|
673
|
+
disabledModels.add(id);
|
|
674
|
+
}
|
|
675
|
+
refreshCatalog();
|
|
676
|
+
try {
|
|
677
|
+
await saveKeys();
|
|
678
|
+
}
|
|
679
|
+
catch (error) {
|
|
680
|
+
logger.warn(`模型可见性落盘失败(本次会话已生效):${error instanceof Error ? error.message : String(error)}`);
|
|
681
|
+
}
|
|
682
|
+
};
|
|
408
683
|
// 设置页:填 key(用户明确要求只在设置页填)。
|
|
409
684
|
try {
|
|
410
685
|
registerSettingsSection(ctx, {
|
|
411
686
|
namespace: SETTINGS_NS,
|
|
412
687
|
config,
|
|
413
688
|
pool,
|
|
414
|
-
onKeysChanged:
|
|
415
|
-
await saveKeys();
|
|
416
|
-
refreshCatalog();
|
|
417
|
-
void fetchCatalogFromUpstream();
|
|
418
|
-
},
|
|
689
|
+
onKeysChanged: handleKeysChanged,
|
|
419
690
|
});
|
|
420
691
|
}
|
|
421
692
|
catch (error) {
|
|
422
693
|
logger.warn(`设置页注册失败(不影响模型可用):${error instanceof Error ? error.message : String(error)}`);
|
|
423
694
|
}
|
|
424
|
-
// Web 路由:给设置卡片读写 key /
|
|
695
|
+
// Web 路由:给设置卡片读写 key / 模型可见性 / 查看对外接口。
|
|
425
696
|
try {
|
|
426
697
|
registerKeyRoutes(ctx, {
|
|
427
698
|
status,
|
|
428
699
|
pool,
|
|
429
700
|
logger,
|
|
430
|
-
onKeysChanged:
|
|
431
|
-
|
|
432
|
-
refreshCatalog();
|
|
433
|
-
void fetchCatalogFromUpstream();
|
|
434
|
-
},
|
|
701
|
+
onKeysChanged: handleKeysChanged,
|
|
702
|
+
onModelsChanged: handleModelsChanged,
|
|
435
703
|
reload: async () => {
|
|
436
|
-
|
|
704
|
+
// 手动重载:走同一套「装载并宣告」逻辑,因此在启动早期点它也不会把
|
|
705
|
+
// 「还没读到」误当成「真的没有 key」而清空权威装载信号。
|
|
706
|
+
await loadKeysAndNotify();
|
|
437
707
|
refreshCatalog();
|
|
438
708
|
},
|
|
439
709
|
fetchCatalog: fetchCatalogFromUpstream,
|
package/lib/routes.d.ts
CHANGED
|
@@ -40,6 +40,20 @@ export interface StatusProvider {
|
|
|
40
40
|
message: string;
|
|
41
41
|
at: number;
|
|
42
42
|
}>;
|
|
43
|
+
/** 本地 shim 的对外接入信息(地址、端口、API Key)。 */
|
|
44
|
+
endpoint(): {
|
|
45
|
+
baseUrl: string;
|
|
46
|
+
port: number;
|
|
47
|
+
apiKey: string;
|
|
48
|
+
};
|
|
49
|
+
/** 目录里的全部模型 + 是否在下拉中展示。 */
|
|
50
|
+
models(): Array<{
|
|
51
|
+
id: string;
|
|
52
|
+
name: string;
|
|
53
|
+
contextWindow: number;
|
|
54
|
+
maxTokens: number;
|
|
55
|
+
enabled: boolean;
|
|
56
|
+
}>;
|
|
43
57
|
providerId: string;
|
|
44
58
|
providerName: string;
|
|
45
59
|
baseUrl: string;
|
|
@@ -55,6 +69,8 @@ export interface RouteDeps {
|
|
|
55
69
|
logger: Logger;
|
|
56
70
|
/** key 列表发生变更后回调(持久化 + 刷新目录)。 */
|
|
57
71
|
onKeysChanged(): Promise<void>;
|
|
72
|
+
/** 模型可见性发生变更后回调(收到完整的「被隐藏」列表)。 */
|
|
73
|
+
onModelsChanged(disabled: string[]): Promise<void>;
|
|
58
74
|
/** 重新从凭据库装载。 */
|
|
59
75
|
reload(): Promise<void>;
|
|
60
76
|
/** 主动拉取上游模型目录。 */
|
package/lib/routes.js
CHANGED
|
@@ -153,8 +153,11 @@ export function registerKeyRoutes(ctx, deps) {
|
|
|
153
153
|
provider: deps.status.providerId,
|
|
154
154
|
displayName: deps.status.providerName,
|
|
155
155
|
baseUrl: deps.status.baseUrl,
|
|
156
|
+
// 对外接入信息:地址 / 端口 / API Key,供卡片展示并可复制到别的服务。
|
|
157
|
+
endpoint: deps.status.endpoint(),
|
|
156
158
|
summary: deps.status.summary(),
|
|
157
159
|
catalog: deps.status.catalog(),
|
|
160
|
+
models: deps.status.models(),
|
|
158
161
|
rotations: deps.status.rotations(),
|
|
159
162
|
// 卡片靠这一份数据渲染列表,并从响应里取写令牌(同源页面才拿得到)。
|
|
160
163
|
keys: deps.status.pool(),
|
|
@@ -214,6 +217,29 @@ export function registerKeyRoutes(ctx, deps) {
|
|
|
214
217
|
sendJson(res, 200, { cleared: true, total: 0, keys: [] });
|
|
215
218
|
return;
|
|
216
219
|
}
|
|
220
|
+
// ---- 模型可见性:切换单个模型是否出现在模型选择器里 ----------------
|
|
221
|
+
//
|
|
222
|
+
// 一次只改一个:界面是勾选框,逐项切换最贴合操作,也避免「整表覆盖」
|
|
223
|
+
// 在并发点击时互相抹掉。
|
|
224
|
+
if (action === 'set-model') {
|
|
225
|
+
const id = typeof body?.id === 'string' ? body.id : '';
|
|
226
|
+
if (!id) {
|
|
227
|
+
sendJson(res, 400, { error: '缺少模型 id' });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const all = deps.status.models();
|
|
231
|
+
if (!all.some((model) => model.id === id)) {
|
|
232
|
+
sendJson(res, 404, { error: `未知模型:${id}` });
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
const enabled = body?.enabled !== false;
|
|
236
|
+
const nextDisabled = all
|
|
237
|
+
.filter((model) => (model.id === id ? !enabled : !model.enabled))
|
|
238
|
+
.map((model) => model.id);
|
|
239
|
+
await deps.onModelsChanged(nextDisabled);
|
|
240
|
+
sendJson(res, 200, { id, enabled, models: deps.status.models() });
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
217
243
|
if (action === 'revive') {
|
|
218
244
|
// 手动复活被误判失效的 key。
|
|
219
245
|
const revived = deps.pool.reviveInvalid();
|
package/lib/shim.d.ts
CHANGED
|
@@ -56,7 +56,16 @@ export interface ShimOptions {
|
|
|
56
56
|
export interface Shim {
|
|
57
57
|
ready: Promise<void>;
|
|
58
58
|
baseUrl(): string;
|
|
59
|
+
port(): number;
|
|
60
|
+
/** 当前对外暴露的 API Key(DSH 自己也用它访问本服务)。 */
|
|
59
61
|
token(): string;
|
|
62
|
+
/**
|
|
63
|
+
* 换一把对外密钥。
|
|
64
|
+
*
|
|
65
|
+
* 旧密钥**继续接受**:pi-ai 可能缓存了 `resolveApiKey` 的结果,切换瞬间在途的
|
|
66
|
+
* 请求不该因此 401。持久化的密钥在启动装载完成后才拿到,正是走这条路径。
|
|
67
|
+
*/
|
|
68
|
+
setToken(next: string): void;
|
|
60
69
|
close(): Promise<void>;
|
|
61
70
|
}
|
|
62
71
|
/** 起一个只监听 127.0.0.1 的 OpenAI 兼容服务。 */
|
package/lib/shim.js
CHANGED
|
@@ -62,7 +62,11 @@ export function createShim(options) {
|
|
|
62
62
|
const { pool, catalog } = options;
|
|
63
63
|
const rotation = { ...DEFAULT_ROTATION, ...options.rotation };
|
|
64
64
|
// 每进程随机共享密钥:DSH 用 Bearer 带上它,别的本地进程猜不到。
|
|
65
|
-
|
|
65
|
+
// 启动装载完成后会被凭据库里那把持久化密钥替换(见 setToken),以便外部服务
|
|
66
|
+
// 配置一次就能长期使用。
|
|
67
|
+
let primaryToken = randomBytes(24).toString('base64url');
|
|
68
|
+
/** 仍被接受的密钥集合:切换后旧值保留,避免在途请求被 401。 */
|
|
69
|
+
const acceptedTokens = new Set([primaryToken]);
|
|
66
70
|
const server = createServer((req, res) => {
|
|
67
71
|
void handle(req, res);
|
|
68
72
|
});
|
|
@@ -71,13 +75,14 @@ export function createShim(options) {
|
|
|
71
75
|
server.once('error', reject);
|
|
72
76
|
});
|
|
73
77
|
server.listen(0, '127.0.0.1');
|
|
74
|
-
const
|
|
78
|
+
const listeningAddress = () => {
|
|
75
79
|
const address = server.address();
|
|
76
80
|
if (address === null || typeof address === 'string') {
|
|
77
81
|
throw new Error('sensenova-pool shim has no listening address');
|
|
78
82
|
}
|
|
79
|
-
return
|
|
83
|
+
return address;
|
|
80
84
|
};
|
|
85
|
+
const baseUrl = () => `http://127.0.0.1:${listeningAddress().port}`;
|
|
81
86
|
async function handle(req, res) {
|
|
82
87
|
try {
|
|
83
88
|
// 防 DNS rebinding:只接受回环 Host / Origin。
|
|
@@ -213,7 +218,23 @@ export function createShim(options) {
|
|
|
213
218
|
return {
|
|
214
219
|
ready,
|
|
215
220
|
baseUrl,
|
|
216
|
-
|
|
221
|
+
port: () => listeningAddress().port,
|
|
222
|
+
token: () => primaryToken,
|
|
223
|
+
setToken: (next) => {
|
|
224
|
+
if (typeof next !== 'string' || next.length < 8 || next === primaryToken)
|
|
225
|
+
return;
|
|
226
|
+
primaryToken = next;
|
|
227
|
+
acceptedTokens.add(next);
|
|
228
|
+
// 只留最近两把:换密钥不常发生,但别让集合无限增长。
|
|
229
|
+
if (acceptedTokens.size > 2) {
|
|
230
|
+
for (const token of acceptedTokens) {
|
|
231
|
+
if (token === primaryToken)
|
|
232
|
+
continue;
|
|
233
|
+
acceptedTokens.delete(token);
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
},
|
|
217
238
|
close: async () => {
|
|
218
239
|
await new Promise((resolve) => {
|
|
219
240
|
server.close(() => resolve());
|
|
@@ -229,11 +250,17 @@ export function createShim(options) {
|
|
|
229
250
|
const match = /^Bearer\s+(.+)$/i.exec(header.trim());
|
|
230
251
|
if (!match)
|
|
231
252
|
return false;
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
253
|
+
const presented = Buffer.from(match[1]);
|
|
254
|
+
let ok = false;
|
|
255
|
+
// 逐个常量时间比较:命中哪一把都不提前返回,避免从耗时推断密钥。
|
|
256
|
+
for (const token of acceptedTokens) {
|
|
257
|
+
const expected = Buffer.from(token);
|
|
258
|
+
if (expected.length !== presented.length)
|
|
259
|
+
continue;
|
|
260
|
+
if (timingSafeEqual(presented, expected))
|
|
261
|
+
ok = true;
|
|
262
|
+
}
|
|
263
|
+
return ok;
|
|
237
264
|
}
|
|
238
265
|
}
|
|
239
266
|
function summarizeFailure(message, attempts) {
|