dsh-router-core 0.3.3 → 0.3.4
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 +1 -1
- package/docs/suppliers.md +71 -30
- package/lib/client-registry.js +7 -3
- package/lib/client.js +7 -3
- package/lib/index.js +140 -49
- package/lib/types/router/index.d.ts +23 -5
- package/lib/types/router/types.d.ts +0 -2
- package/lib/types/supplier-config.d.ts +23 -0
- package/lib/types/suppliers/contract.d.ts +9 -6
- package/package.json +1 -1
- package/src/client/SupplierDetail.tsx +7 -2
- package/src/router/index.ts +88 -28
- package/src/router/models-cache.test.ts +137 -2
- package/src/router/types.ts +0 -2
- package/src/supplier-config.test.ts +98 -0
- package/src/supplier-config.ts +60 -1
- package/src/suppliers/contract.ts +9 -9
- package/src/suppliers/loader.test.ts +118 -0
- package/src/suppliers/loader.ts +19 -4
- package/src/suppliers/nvidia/plugin.ts +12 -15
- package/src/suppliers/opencode/plugin.ts +10 -13
- package/src/suppliers/openrouter/plugin.ts +12 -15
- package/src/suppliers/registry.ts +4 -1
|
@@ -46,6 +46,12 @@ export type AccountState = 'ok' | 'rate_limit' | 'quota' | 'session_dead' | 'una
|
|
|
46
46
|
export interface SupplierAccountNow {
|
|
47
47
|
uid: string;
|
|
48
48
|
nickname?: string;
|
|
49
|
+
/**
|
|
50
|
+
* 剩余额度。**拿不到就报 `-1`**,不是 0:
|
|
51
|
+
* 插件刚重启(内存缓存空)、积分拉取失败、或压根不支持积分时都是 `-1`。
|
|
52
|
+
* 核心据此保留上一次持久化下来的值 —— 报 0 会把缓存冲成 0(0 是真值
|
|
53
|
+
* 「用完了」,核心分不清「拿到 0」和「没拿到」)。
|
|
54
|
+
*/
|
|
49
55
|
credits: number;
|
|
50
56
|
/** 插件观察到的上游状态。 */
|
|
51
57
|
state: AccountState;
|
|
@@ -91,19 +97,16 @@ export interface SupplierModule {
|
|
|
91
97
|
status(): SupplierStatusNow;
|
|
92
98
|
/** 模型来源。`force=true` 时强制刷新来源(核心「获取模型」按钮调用)。 */
|
|
93
99
|
listModels(force?: boolean): Promise<ModelInfo[]> | ModelInfo[];
|
|
94
|
-
/** 默认前缀(可被通用层 alias 覆盖)。 */
|
|
95
|
-
getAlias(): string;
|
|
96
100
|
/**
|
|
97
101
|
* 对**单个账号**调一次上游。插件不遍历账号、不管冷却、不写 res——
|
|
98
102
|
* 选号/回退/健康判定全是核心的活。
|
|
99
103
|
* 无账号供应商(如 opencode)传空 uid,忽略即可。
|
|
104
|
+
*
|
|
105
|
+
* 失败原因通过返回值的 `message` 报(核心在测试模型时直接用它做诊断提示),
|
|
106
|
+
* 插件不必自己存一份「上次失败」的状态。
|
|
100
107
|
*/
|
|
101
108
|
chatOnce(uid: string, req: ChatRequest): Promise<ChatOnceResult>;
|
|
102
109
|
dispose(): void;
|
|
103
|
-
/** 上次 chatOnce 失败的原因(诊断用)。
|
|
104
|
-
* 测试模型由 dsh-router 核心统一走 chatOnce 路径(账号池回退/冷却自动生效),
|
|
105
|
-
* 插件只需把失败原因暴露出来供核心汇总;不实现则测试失败时只有通用提示。 */
|
|
106
|
-
lastError?(): string | undefined;
|
|
107
110
|
/** 生成登录链接(加账号)。有它才显示连接池(账号池)。 */
|
|
108
111
|
generateLoginUrl?(): string | {
|
|
109
112
|
ok: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-router-core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"description": "DSH plugin: a simplified 9router (AI routing gateway). Adds a 路由系统 (Routing System) sidebar entry beside 记忆系统; the panel shows suppliers, account pool, combos, and endpoint/API keys.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -673,11 +673,16 @@ export function SupplierDetail({ supplier, accounts, statusLoading, onBack, onRe
|
|
|
673
673
|
<div className="dshr-linkSub">
|
|
674
674
|
<span className="dshr-mono dshr-linkUid">{account.uid}</span>
|
|
675
675
|
<span className="dshr-linkDot">·</span>
|
|
676
|
-
<
|
|
676
|
+
{/* credits < 0 = 插件还没拉到过积分(缓存也没值),
|
|
677
|
+
别显示成「-1 积分」或直接吃掉整段 */}
|
|
678
|
+
<span className="dshr-mono dshr-linkCredits">
|
|
679
|
+
{account.credits < 0 ? '积分未知' : `${Math.ceil(account.credits)} 积分`}
|
|
680
|
+
</span>
|
|
681
|
+
{/* err_count 是限流退避等级(反复被限流的号递增,成功后清零) */}
|
|
677
682
|
{account.err_count !== undefined && account.err_count > 0 && (
|
|
678
683
|
<>
|
|
679
684
|
<span className="dshr-linkDot">·</span>
|
|
680
|
-
<span className="dshr-linkErr"
|
|
685
|
+
<span className="dshr-linkErr">退避 {account.err_count} 级</span>
|
|
681
686
|
</>
|
|
682
687
|
)}
|
|
683
688
|
{coolingText !== '' && <span className="dshr-reason dshr-linkCooling">{coolingText}</span>}
|
package/src/router/index.ts
CHANGED
|
@@ -26,8 +26,15 @@ interface ChatTrace {
|
|
|
26
26
|
lastState?: AccountState
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
/**
|
|
30
|
-
|
|
29
|
+
/**
|
|
30
|
+
* 模型列表缓存有效期。
|
|
31
|
+
*
|
|
32
|
+
* 取 10 分钟而不是 60s:模型列表本来很少变(上游上新/下线才动),而每次
|
|
33
|
+
* TTL 过期都会穿透到插件真打一次上游——实测冷路径 0.3~1.0s/供应商,组合页
|
|
34
|
+
* 取最慢那家就是 1s+ 的白屏。拉长 TTL 直接把这个穿透频率降一个量级;真要
|
|
35
|
+
* 立刻看新模型,点「获取模型」走 force 即可。
|
|
36
|
+
*/
|
|
37
|
+
const MODELS_TTL_MS = 10 * 60 * 1000
|
|
31
38
|
|
|
32
39
|
function openAIError(code: string, msg: string): Record<string, unknown> {
|
|
33
40
|
return { error: { message: msg, type: 'api_error', code } }
|
|
@@ -444,6 +451,11 @@ export class Router {
|
|
|
444
451
|
private store: SupplierConfigStore
|
|
445
452
|
/** 模型列表缓存(supplierId → 模型 + 拉取时间)。插件只管拉,不缓存。 */
|
|
446
453
|
private modelsCache = new Map<string, { models: ModelWithEnabled[]; fetchedAt: number }>()
|
|
454
|
+
/**
|
|
455
|
+
* 正在拉模型的供应商 → in-flight promise。
|
|
456
|
+
* 组合页会同时从多个入口触发同一个供应商的刷新,不去重上游就被按 N 倍打。
|
|
457
|
+
*/
|
|
458
|
+
private modelsInflight = new Map<string, Promise<ModelWithEnabled[]>>()
|
|
447
459
|
/** 请求日志出口(面板/宿主 logger)。 */
|
|
448
460
|
private log: (msg: string) => void
|
|
449
461
|
/** 用量统计(概览看板)。 */
|
|
@@ -592,37 +604,80 @@ export class Router {
|
|
|
592
604
|
* 取某供应商的模型(核心统一缓存)。
|
|
593
605
|
*
|
|
594
606
|
* 模型列表只在这里缓存一次:`/suppliers/:id/models`(供应商详情)和
|
|
595
|
-
* `/combos
|
|
596
|
-
* 冷启动(缓存还没建)时才拉一次;真正刷新由详情页打开或「获取模型」
|
|
597
|
-
* 按钮(force)触发。
|
|
607
|
+
* `/combos`(组合加模型)共用。
|
|
598
608
|
*
|
|
599
|
-
*
|
|
600
|
-
*
|
|
609
|
+
* **过期后走 stale-while-revalidate**:先返回旧值让面板立刻有内容,后台
|
|
610
|
+
* 重新拉,拉完下次请求就是新的。为什么必须这样:插件的 `listModels` 大多
|
|
611
|
+
* 无条件打上游(实测冷路径 0.3~1.0s/供应商),而组合页要拉全部供应商、
|
|
612
|
+
* 取最慢那家——同步等就是 1s+ 的白屏。旧值只可能「少列了新模型」,
|
|
613
|
+
* 比白屏划算;想立刻看新模型点「获取模型」(force)即可。
|
|
614
|
+
*
|
|
615
|
+
* 只有两种情况会真的等:`force`(用户主动刷新)和**从来没有过缓存值**
|
|
616
|
+
* (冷启动,没有旧值可给)。后者只发生一次。
|
|
601
617
|
*/
|
|
602
618
|
async modelsOf(supplierId: string, force = false): Promise<ModelWithEnabled[]> {
|
|
603
619
|
const s = this.suppliers.find((x) => x.id === supplierId)
|
|
604
620
|
if (s === undefined) return []
|
|
605
621
|
const hit = this.modelsCache.get(supplierId)
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
enabled: !disabled.has(mm.id),
|
|
614
|
-
custom: custom.has(mm.id) ? true : undefined,
|
|
615
|
-
}))
|
|
616
|
-
// 自定义模型(listModels 之外的)并入显示
|
|
617
|
-
const seen = new Set(models.map((mm) => mm.id))
|
|
618
|
-
for (const id of custom) {
|
|
619
|
-
if (!seen.has(id)) {
|
|
620
|
-
seen.add(id)
|
|
621
|
-
models.push({ id, enabled: !disabled.has(id), custom: true })
|
|
622
|
-
}
|
|
622
|
+
const fresh = hit !== undefined && Date.now() - hit.fetchedAt < MODELS_TTL_MS
|
|
623
|
+
if (!force && fresh) return hit!.models
|
|
624
|
+
// 有旧值(只是过期了):立刻返回旧值,后台刷新
|
|
625
|
+
if (!force && hit !== undefined) {
|
|
626
|
+
// 后台刷新的失败不能冒出来:这是 fire-and-forget,没人接
|
|
627
|
+
void this.refreshModels(supplierId, s).catch(() => {})
|
|
628
|
+
return hit.models
|
|
623
629
|
}
|
|
624
|
-
this.
|
|
625
|
-
|
|
630
|
+
return await this.refreshModels(supplierId, s)
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* 真拉一次上游并写缓存。并发调用共享同一个 in-flight promise——
|
|
635
|
+
* 组合页会同时触发多个入口,不去重会把上游按 N 倍打(各家插件自己没做这层)。
|
|
636
|
+
*
|
|
637
|
+
* 失败时:**有旧值就退回旧值**(宁可显示几分钟前的列表,也别让面板空掉),
|
|
638
|
+
* **没旧值就把错误抛回去**——调用方(`supplierModels`)据此把该供应商整个
|
|
639
|
+
* 剔除,而不是显示一个「有 0 个模型」的空壳。
|
|
640
|
+
*/
|
|
641
|
+
private refreshModels(supplierId: string, s: Supplier): Promise<ModelWithEnabled[]> {
|
|
642
|
+
const inflight = this.modelsInflight.get(supplierId)
|
|
643
|
+
if (inflight !== undefined) return inflight
|
|
644
|
+
const p = (async (): Promise<ModelWithEnabled[]> => {
|
|
645
|
+
const cfg = this.store.get(supplierId)
|
|
646
|
+
const custom = new Set(cfg.custom)
|
|
647
|
+
const disabled = new Set(cfg.disabled)
|
|
648
|
+
const list = await Promise.resolve(s.listModels())
|
|
649
|
+
const models: ModelWithEnabled[] = list.map((mm) => ({
|
|
650
|
+
...mm,
|
|
651
|
+
enabled: !disabled.has(mm.id),
|
|
652
|
+
custom: custom.has(mm.id) ? true : undefined,
|
|
653
|
+
}))
|
|
654
|
+
// 自定义模型(listModels 之外的)并入显示
|
|
655
|
+
const seen = new Set(models.map((mm) => mm.id))
|
|
656
|
+
for (const id of custom) {
|
|
657
|
+
if (!seen.has(id)) {
|
|
658
|
+
seen.add(id)
|
|
659
|
+
models.push({ id, enabled: !disabled.has(id), custom: true })
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
const stale = this.modelsCache.get(supplierId)
|
|
663
|
+
// 拉到空列表当「上游抖了一下」:有旧值就保住旧值并返回它,别把面板清空。
|
|
664
|
+
// 真的一家模型都没有的供应商,第一次(无旧值)就该拿到空,不受影响。
|
|
665
|
+
if (models.length === 0 && stale !== undefined && stale.models.length > 0) {
|
|
666
|
+
return stale.models
|
|
667
|
+
}
|
|
668
|
+
this.modelsCache.set(supplierId, { models, fetchedAt: Date.now() })
|
|
669
|
+
return models
|
|
670
|
+
})()
|
|
671
|
+
.catch((err: unknown) => {
|
|
672
|
+
const stale = this.modelsCache.get(supplierId)
|
|
673
|
+
if (stale !== undefined) return stale.models
|
|
674
|
+
throw err instanceof Error ? err : new Error(String(err))
|
|
675
|
+
})
|
|
676
|
+
.finally(() => {
|
|
677
|
+
this.modelsInflight.delete(supplierId)
|
|
678
|
+
})
|
|
679
|
+
this.modelsInflight.set(supplierId, p)
|
|
680
|
+
return p
|
|
626
681
|
}
|
|
627
682
|
|
|
628
683
|
/** 失效某供应商的模型缓存(增删改模型后调用)。 */
|
|
@@ -973,15 +1028,20 @@ export class Router {
|
|
|
973
1028
|
rawBody: JSON.stringify({ model, messages: [{ role: 'user', content: 'ping' }], stream: false, max_tokens: 1 }),
|
|
974
1029
|
}
|
|
975
1030
|
let served = false
|
|
1031
|
+
const trace: ChatTrace = { attempts: 0 }
|
|
976
1032
|
try {
|
|
977
|
-
served = await this.chatWithSupplier(s, req, sink)
|
|
1033
|
+
served = await this.chatWithSupplier(s, req, sink, trace)
|
|
978
1034
|
} catch (err) {
|
|
979
1035
|
return { ok: false, error: (err as Error).message }
|
|
980
1036
|
}
|
|
981
1037
|
// 供应商可能「服务了但写出错误响应」(如 opencode:唯一能处理该模型的供应商,错误自己上报)
|
|
982
1038
|
if (served && sink.status() < 400) return { ok: true }
|
|
983
1039
|
const fromSink = served && sink.status() >= 400 ? extractUpstreamError(sink.body()) : ''
|
|
984
|
-
|
|
1040
|
+
// 失败原因优先从上游响应体取,其次用 chatOnce 返回的 message(trace.lastError)。
|
|
1041
|
+
// 以前这里问插件的 lastError()——那是「最后一次失败」的可变全局,既可能串到
|
|
1042
|
+
// 别的账号/别的请求,也有插件压根没实现(codebuddy 就漏了,于是永远拿不到兜底)。
|
|
1043
|
+
// chatOnce 的返回值本身就带 message,用它更准,插件也不必再维护一份状态。
|
|
1044
|
+
const detail = fromSink !== '' ? fromSink : trace.lastError
|
|
985
1045
|
return {
|
|
986
1046
|
ok: false,
|
|
987
1047
|
error: detail !== undefined && detail !== ''
|
|
@@ -66,6 +66,21 @@ function addSupplier(router: Router, s: unknown): void {
|
|
|
66
66
|
;(router as unknown as { suppliers: unknown[] }).suppliers.push(s)
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
/**
|
|
70
|
+
* 把某供应商的缓存标记成「已过期」(TTL 现在 10 分钟,测试不能真等)。
|
|
71
|
+
* 白盒改 fetchedAt,模拟插件重启/TTL 到期的冷路径。
|
|
72
|
+
*/
|
|
73
|
+
function expire(router: Router, id: string): void {
|
|
74
|
+
const cache = (router as unknown as { modelsCache: Map<string, { fetchedAt: number }> }).modelsCache
|
|
75
|
+
const hit = cache.get(id)
|
|
76
|
+
if (hit !== undefined) hit.fetchedAt = 0
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 等一轮 microtask/定时器,让 fire-and-forget 的后台刷新跑完。 */
|
|
80
|
+
function tick(ms = 20): Promise<void> {
|
|
81
|
+
return new Promise((r) => setTimeout(r, ms))
|
|
82
|
+
}
|
|
83
|
+
|
|
69
84
|
test('组合面板连开两次只拉一次上游(缓存生效)', async () => {
|
|
70
85
|
const router = new Router('')
|
|
71
86
|
const a = supplier('a', [{ id: 'a-1' }])
|
|
@@ -137,9 +152,129 @@ test('单个供应商拉模型失败不影响其它供应商', async () => {
|
|
|
137
152
|
assert.equal(groups[0]?.supplier.id, 'good')
|
|
138
153
|
})
|
|
139
154
|
|
|
140
|
-
|
|
155
|
+
/**
|
|
156
|
+
* 冷启动慢的回归(2026-09-03 实测):插件的 listModels 大多无条件打上游
|
|
157
|
+
* (0.3~1.0s/供应商),TTL 一过就穿透到插件,组合页取最慢那家 = 1s+ 白屏。
|
|
158
|
+
* 现在核心走 stale-while-revalidate:过期先返回旧值,后台刷新。
|
|
159
|
+
*/
|
|
160
|
+
test('过期后不等上游:立刻返回旧值,后台刷新', async () => {
|
|
161
|
+
const router = new Router('')
|
|
162
|
+
// 慢供应商:真等它就是 300ms
|
|
163
|
+
const a = supplier('a', [{ id: 'a-1' }], 300)
|
|
164
|
+
addSupplier(router, a.s)
|
|
165
|
+
|
|
166
|
+
await router.modelsOf('a')
|
|
167
|
+
assert.equal(a.state.calls, 1)
|
|
168
|
+
expire(router, 'a')
|
|
169
|
+
|
|
170
|
+
const t0 = Date.now()
|
|
171
|
+
const models = await router.modelsOf('a')
|
|
172
|
+
const dt = Date.now() - t0
|
|
173
|
+
|
|
174
|
+
assert.ok(dt < 100, `过期后不该同步等上游(实测 ${dt}ms)`)
|
|
175
|
+
assert.deepEqual(models.map((m) => m.id), ['a-1'], '旧值要立刻返回,面板不空')
|
|
176
|
+
await tick(400)
|
|
177
|
+
assert.equal(a.state.calls, 2, '后台要真的刷新一次')
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
test('后台刷新后缓存变新:再取不再触发拉取', async () => {
|
|
141
181
|
const router = new Router('')
|
|
142
|
-
|
|
182
|
+
const a = supplier('a', [{ id: 'a-1' }])
|
|
183
|
+
addSupplier(router, a.s)
|
|
184
|
+
|
|
185
|
+
await router.modelsOf('a')
|
|
186
|
+
expire(router, 'a')
|
|
187
|
+
await router.modelsOf('a') // 触发后台刷新
|
|
188
|
+
await tick()
|
|
189
|
+
assert.equal(a.state.calls, 2)
|
|
190
|
+
|
|
191
|
+
await router.modelsOf('a') // 已刷新过,不该再拉
|
|
192
|
+
await tick()
|
|
193
|
+
assert.equal(a.state.calls, 2)
|
|
194
|
+
})
|
|
195
|
+
|
|
196
|
+
test('并发刷新共享一次上游请求(不去重会把上游按 N 倍打)', async () => {
|
|
197
|
+
const router = new Router('')
|
|
198
|
+
const a = supplier('a', [{ id: 'a-1' }], 50)
|
|
199
|
+
addSupplier(router, a.s)
|
|
200
|
+
await router.modelsOf('a')
|
|
201
|
+
expire(router, 'a')
|
|
202
|
+
|
|
203
|
+
// 组合页的实际情况:多个入口同时触发同一个供应商
|
|
204
|
+
await Promise.all([router.modelsOf('a'), router.modelsOf('a'), router.modelsOf('a')])
|
|
205
|
+
await tick(200)
|
|
206
|
+
assert.equal(a.state.calls, 2, `并发只应多拉一次,实测 ${a.state.calls}`)
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
test('force 仍然同步等(用户主动点「获取模型」,要看到结果)', async () => {
|
|
210
|
+
const router = new Router('')
|
|
211
|
+
const a = supplier('a', [{ id: 'a-1' }], 150)
|
|
212
|
+
addSupplier(router, a.s)
|
|
213
|
+
await router.modelsOf('a')
|
|
214
|
+
expire(router, 'a')
|
|
215
|
+
|
|
216
|
+
const t0 = Date.now()
|
|
217
|
+
await router.modelsOf('a', true)
|
|
218
|
+
assert.ok(Date.now() - t0 >= 100, 'force 必须等上游拉完')
|
|
219
|
+
assert.equal(a.state.calls, 2)
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
test('拉到空列表不覆盖旧值(上游抖一下不该清空面板)', async () => {
|
|
223
|
+
const router = new Router('')
|
|
224
|
+
const a = supplier('a', [{ id: 'a-1' }])
|
|
225
|
+
addSupplier(router, a.s)
|
|
226
|
+
await router.modelsOf('a')
|
|
227
|
+
|
|
228
|
+
a.s.listModels = async (): Promise<ModelInfo[]> => []
|
|
229
|
+
expire(router, 'a')
|
|
230
|
+
const models = await router.modelsOf('a', true)
|
|
231
|
+
|
|
232
|
+
assert.deepEqual(models.map((m) => m.id), ['a-1'], '空结果不该冲掉旧列表')
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
test('后台刷新失败 → 保留旧值,不抛(fire-and-forget 没人接异常)', async () => {
|
|
236
|
+
const router = new Router('')
|
|
237
|
+
const a = supplier('a', [{ id: 'a-1' }])
|
|
238
|
+
addSupplier(router, a.s)
|
|
239
|
+
await router.modelsOf('a')
|
|
240
|
+
|
|
241
|
+
a.s.listModels = async (): Promise<ModelInfo[]> => {
|
|
242
|
+
throw new Error('upstream down')
|
|
243
|
+
}
|
|
244
|
+
expire(router, 'a')
|
|
245
|
+
const models = await router.modelsOf('a')
|
|
246
|
+
assert.deepEqual(models.map((m) => m.id), ['a-1'], '失败也要保住旧值')
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
test('首次就失败且无旧值 → 抛错(让 supplierModels 剔除该供应商,别显示空壳)', async () => {
|
|
250
|
+
const router = new Router('')
|
|
251
|
+
const a = supplier('a', [])
|
|
252
|
+
a.s.listModels = async (): Promise<ModelInfo[]> => {
|
|
253
|
+
throw new Error('upstream down')
|
|
254
|
+
}
|
|
255
|
+
addSupplier(router, a.s)
|
|
256
|
+
|
|
257
|
+
await assert.rejects(() => router.modelsOf('a'), /upstream down/)
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* 回归(2026-09-03 契约精简):删了插件 lastError() 后,testModel 的失败原因
|
|
262
|
+
* 必须从 chatOnce 返回值的 message 取(经 trace.lastError 透传)。以前问插件
|
|
263
|
+
* 的 lastError() 是个「最后一次失败」的可变全局,可能串别的请求,也有插件
|
|
264
|
+
* 压根没实现照样能走到。锁住:chatOnce 报的 message 能作为诊断呈现。
|
|
265
|
+
*/
|
|
266
|
+
test('testModel 失败 → 用 chatOnce 返回的 message 作诊断,不依赖插件 lastError()', async () => {
|
|
267
|
+
const router = new Router('')
|
|
268
|
+
const a = supplier('a', [{ id: 'a-1' }])
|
|
269
|
+
// 明确不实现 lastError()——合约删了它
|
|
270
|
+
a.s.chatOnce = async (): Promise<ChatOnceResult> =>
|
|
271
|
+
({ ok: false, state: 'quota', message: 'no quota for this plan' })
|
|
272
|
+
addSupplier(router, a.s)
|
|
273
|
+
|
|
274
|
+
const r = await router.testModel('a', 'a-1')
|
|
275
|
+
assert.equal(r.ok, false)
|
|
276
|
+
assert.match(r.error ?? '', /no quota for this plan/, '失败原因要来自 chatOnce 的 message')
|
|
277
|
+
assert.match(r.error ?? '', /账号\/额度\/限流问题/, '要带上可诊断的归类提示')
|
|
143
278
|
})
|
|
144
279
|
|
|
145
280
|
/**
|
package/src/router/types.ts
CHANGED
|
@@ -80,8 +80,6 @@ export interface Supplier {
|
|
|
80
80
|
accounts(): SupplierAccountNow[]
|
|
81
81
|
/** 对单个账号调一次上游。不遍历账号、不管冷却、不写 res。 */
|
|
82
82
|
chatOnce(uid: string, req: ChatRequest): Promise<ChatOnceResult>
|
|
83
|
-
/** 上次 chatOnce 失败原因(诊断用,可选)。 */
|
|
84
|
-
lastError?(): string | undefined
|
|
85
83
|
/** 删除链接(清理凭证;内部能力,js 契约不要求实现)。 */
|
|
86
84
|
removeLink?(uid: string): Promise<boolean>
|
|
87
85
|
dispose(): void
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 积分缓存(核心统一持久化)测试 —— node --test 直接跑。
|
|
3
|
+
*
|
|
4
|
+
* 锁定的契约(2026-09-03 修的 bug:codebuddy 重启后面板永久显示 0 积分):
|
|
5
|
+
* - 插件报真值 → 落盘,重启后还在
|
|
6
|
+
* - 插件报 -1(没拉到)→ 顶上次的缓存,不能显示 0
|
|
7
|
+
* - 插件报 0(真用完了)→ 缓存被冲成 0,不能被当成「未知」保住旧值
|
|
8
|
+
* - 删链接 → 缓存一起清
|
|
9
|
+
* - 坏数据(负数/NaN/缺字段)读盘时不炸,当没缓存过
|
|
10
|
+
*/
|
|
11
|
+
import test from 'node:test'
|
|
12
|
+
import assert from 'node:assert/strict'
|
|
13
|
+
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import { tmpdir } from 'node:os'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
import { SupplierConfigStore } from './supplier-config.ts'
|
|
17
|
+
|
|
18
|
+
/** 每个用例一个独立数据目录(stateFile 推导出 supplier-config.json 的位置)。 */
|
|
19
|
+
function tempStore(preload?: unknown): { store: SupplierConfigStore; file: string } {
|
|
20
|
+
const dir = mkdtempSync(join(tmpdir(), 'dshr-credits-'))
|
|
21
|
+
const stateFile = join(dir, 'state.json')
|
|
22
|
+
if (preload !== undefined) {
|
|
23
|
+
writeFileSync(join(dir, 'supplier-config.json'), JSON.stringify(preload))
|
|
24
|
+
}
|
|
25
|
+
return { store: new SupplierConfigStore(stateFile), file: join(dir, 'supplier-config.json') }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const UNKNOWN = -1
|
|
29
|
+
|
|
30
|
+
test('报真值 → 落盘,重开还在', () => {
|
|
31
|
+
const { store, file } = tempStore()
|
|
32
|
+
assert.equal(store.putCredits('codebuddy', 'cb-1', 1234.5), 1234.5)
|
|
33
|
+
const raw = JSON.parse(readFileSync(file, 'utf8')) as {
|
|
34
|
+
suppliers: Record<string, { credits: Record<string, number> }>
|
|
35
|
+
}
|
|
36
|
+
assert.equal(raw.suppliers.codebuddy?.credits['cb-1'], 1234.5)
|
|
37
|
+
// 新实例 = 模拟重启
|
|
38
|
+
assert.equal(new SupplierConfigStore(join(file, '..', 'state.json')).getCredits('codebuddy', 'cb-1'), 1234.5)
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
test('报 -1(没拉到)→ 顶上次缓存,不是 0', () => {
|
|
42
|
+
const { store } = tempStore()
|
|
43
|
+
store.putCredits('codebuddy', 'cb-1', 900)
|
|
44
|
+
// 插件重启后内存缓存空 → 报 -1
|
|
45
|
+
assert.equal(store.putCredits('codebuddy', 'cb-1', UNKNOWN), 900)
|
|
46
|
+
assert.equal(store.getCredits('codebuddy', 'cb-1'), 900)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
test('从来没拿到过 → 就是 -1(读不到就别编 0)', () => {
|
|
50
|
+
const { store } = tempStore()
|
|
51
|
+
assert.equal(store.getCredits('codebuddy', 'cb-1'), UNKNOWN)
|
|
52
|
+
assert.equal(store.putCredits('codebuddy', 'cb-1', UNKNOWN), UNKNOWN)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('报 0(真用完了)→ 缓存被冲成 0', () => {
|
|
56
|
+
const { store } = tempStore()
|
|
57
|
+
store.putCredits('codebuddy', 'cb-1', 500)
|
|
58
|
+
assert.equal(store.putCredits('codebuddy', 'cb-1', 0), 0)
|
|
59
|
+
assert.equal(store.getCredits('codebuddy', 'cb-1'), 0)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test('删链接 → 积分缓存一起清', () => {
|
|
63
|
+
const { store } = tempStore()
|
|
64
|
+
store.putCredits('codebuddy', 'cb-1', 700)
|
|
65
|
+
store.clearCredits('codebuddy', 'cb-1')
|
|
66
|
+
assert.equal(store.getCredits('codebuddy', 'cb-1'), UNKNOWN)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
test('同值重复写入不落盘(status() 是高频调用)', () => {
|
|
70
|
+
const { store, file } = tempStore()
|
|
71
|
+
store.putCredits('codebuddy', 'cb-1', 42)
|
|
72
|
+
const before = readFileSync(file, 'utf8')
|
|
73
|
+
store.putCredits('codebuddy', 'cb-1', 42)
|
|
74
|
+
assert.equal(readFileSync(file, 'utf8'), before)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('坏数据读盘不炸:负数/NaN/非数字当没缓存过', () => {
|
|
78
|
+
const { store } = tempStore({
|
|
79
|
+
suppliers: { codebuddy: { credits: { 'cb-bad': -5, 'cb-nan': null, 'cb-ok': 300 } } },
|
|
80
|
+
})
|
|
81
|
+
assert.equal(store.getCredits('codebuddy', 'cb-bad'), UNKNOWN)
|
|
82
|
+
assert.equal(store.getCredits('codebuddy', 'cb-nan'), UNKNOWN)
|
|
83
|
+
assert.equal(store.getCredits('codebuddy', 'cb-ok'), 300)
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
test('旧配置文件(无 credits 字段)能读,不炸', () => {
|
|
87
|
+
const { store } = tempStore({ suppliers: { codebuddy: { alias: 'cb', poolOrder: ['cb-1'] } } })
|
|
88
|
+
assert.equal(store.getCredits('codebuddy', 'cb-1'), UNKNOWN)
|
|
89
|
+
assert.deepEqual(store.get('codebuddy').poolOrder, ['cb-1'])
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
test('按供应商隔离:同 uid 不同供应商互不干扰', () => {
|
|
93
|
+
const { store } = tempStore()
|
|
94
|
+
store.putCredits('codebuddy', 'key-1', 100)
|
|
95
|
+
store.putCredits('traework', 'key-1', 200)
|
|
96
|
+
assert.equal(store.getCredits('codebuddy', 'key-1'), 100)
|
|
97
|
+
assert.equal(store.getCredits('traework', 'key-1'), 200)
|
|
98
|
+
})
|
package/src/supplier-config.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* - 别名 alias(前缀,模型全名 = alias/id)
|
|
6
6
|
* - 模型管理:启用/禁用 disabled、自定义 custom
|
|
7
7
|
* - 连接池:poolOrder(拖动排序)、poolStrategy(回退/轮询)
|
|
8
|
+
* - 积分缓存 credits:按 supplier/uid 缓存最后一次拿到的剩余额度
|
|
8
9
|
*
|
|
9
10
|
* 持久化到 data/supplier-config.json。
|
|
10
11
|
*/
|
|
@@ -13,18 +14,40 @@ import { dirname, join } from 'node:path'
|
|
|
13
14
|
|
|
14
15
|
export type PoolStrategy = 'fallback' | 'round-robin'
|
|
15
16
|
|
|
17
|
+
/**
|
|
18
|
+
* 积分哨兵:插件还**没拿到过**真实额度(刚重启、积分拉取失败、或压根不支持
|
|
19
|
+
* 积分)时报 `-1`,核心据此保留上一次的缓存值,而不是把 0 写进去。
|
|
20
|
+
*
|
|
21
|
+
* 为什么不能用 0 表示未知:积分 0 是有意义的真值(用完了),核心无法区分
|
|
22
|
+
* 「拿到 0」和「没拿到」。用 0 当哨兵会把缓存冲成 0 —— 这正是 codebuddy
|
|
23
|
+
* 重启后面板永久显示 0 积分的原因(插件只在内存里缓存积分)。
|
|
24
|
+
*/
|
|
25
|
+
export const CREDITS_UNKNOWN = -1
|
|
26
|
+
|
|
16
27
|
export interface SupplierConfig {
|
|
17
28
|
alias: string
|
|
18
29
|
disabled: string[]
|
|
19
30
|
custom: string[]
|
|
20
31
|
poolOrder: string[]
|
|
21
32
|
poolStrategy: PoolStrategy
|
|
33
|
+
/** 积分缓存:uid → 剩余额度(最后一次从插件拿到的非 -1 值)。 */
|
|
34
|
+
credits: Record<string, number>
|
|
22
35
|
}
|
|
23
36
|
|
|
24
37
|
interface ConfigFile {
|
|
25
38
|
suppliers: Record<string, Partial<SupplierConfig>>
|
|
26
39
|
}
|
|
27
40
|
|
|
41
|
+
/** 读盘时的积分字段校验:只留有限非负数(负数一律当没缓存过)。 */
|
|
42
|
+
function readCredits(raw: unknown): Record<string, number> {
|
|
43
|
+
const out: Record<string, number> = {}
|
|
44
|
+
if (typeof raw !== 'object' || raw === null) return out
|
|
45
|
+
for (const [uid, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
46
|
+
if (typeof v === 'number' && Number.isFinite(v) && v >= 0) out[uid] = v
|
|
47
|
+
}
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
28
51
|
/** 通用供应商配置存储。 */
|
|
29
52
|
export class SupplierConfigStore {
|
|
30
53
|
private fp = ''
|
|
@@ -55,7 +78,7 @@ export class SupplierConfigStore {
|
|
|
55
78
|
get(supplierId: string): SupplierConfig {
|
|
56
79
|
let cfg = this.bySupplier.get(supplierId)
|
|
57
80
|
if (!cfg) {
|
|
58
|
-
cfg = { alias: '', disabled: [], custom: [], poolOrder: [], poolStrategy: 'fallback' }
|
|
81
|
+
cfg = { alias: '', disabled: [], custom: [], poolOrder: [], poolStrategy: 'fallback', credits: {} }
|
|
59
82
|
this.bySupplier.set(supplierId, cfg)
|
|
60
83
|
}
|
|
61
84
|
return cfg
|
|
@@ -116,6 +139,40 @@ export class SupplierConfigStore {
|
|
|
116
139
|
this.saveLocked()
|
|
117
140
|
}
|
|
118
141
|
|
|
142
|
+
// ---- 积分缓存(核心统一持久化,插件只管报) ----
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 读缓存的积分。没缓存过返回 `CREDITS_UNKNOWN`(-1),让调用方自己决定
|
|
146
|
+
* 显示什么——不要把 -1 当 0 展示。
|
|
147
|
+
*/
|
|
148
|
+
getCredits(supplierId: string, uid: string): number {
|
|
149
|
+
const v = this.get(supplierId).credits[uid]
|
|
150
|
+
return typeof v === 'number' && Number.isFinite(v) ? v : CREDITS_UNKNOWN
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 合并插件报的积分:非 -1 就写入并返回它;-1(未知)则回落到上次缓存值。
|
|
155
|
+
* @returns 面板该显示的积分(仍可能是 -1 = 从来没拿到过)
|
|
156
|
+
*/
|
|
157
|
+
putCredits(supplierId: string, uid: string, reported: number): number {
|
|
158
|
+
if (typeof reported !== 'number' || !Number.isFinite(reported) || reported < 0) {
|
|
159
|
+
return this.getCredits(supplierId, uid)
|
|
160
|
+
}
|
|
161
|
+
const prev = this.getCredits(supplierId, uid)
|
|
162
|
+
if (prev === reported) return reported // 值没变,不写盘(status() 是高频调用)
|
|
163
|
+
this.get(supplierId).credits[uid] = reported
|
|
164
|
+
this.saveLocked()
|
|
165
|
+
return reported
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** 删除链接时清掉它的积分缓存(不写盘:下一行 removeLink 会带出保存)。 */
|
|
169
|
+
clearCredits(supplierId: string, uid: string): void {
|
|
170
|
+
const credits = this.get(supplierId).credits
|
|
171
|
+
if (credits[uid] === undefined) return
|
|
172
|
+
delete credits[uid]
|
|
173
|
+
this.saveLocked()
|
|
174
|
+
}
|
|
175
|
+
|
|
119
176
|
private load(): void {
|
|
120
177
|
if (this.fp === '') return
|
|
121
178
|
let f: ConfigFile
|
|
@@ -131,6 +188,7 @@ export class SupplierConfigStore {
|
|
|
131
188
|
custom: Array.isArray(c.custom) ? c.custom.filter((m) => typeof m === 'string') : [],
|
|
132
189
|
poolOrder: Array.isArray(c.poolOrder) ? c.poolOrder.filter((u) => typeof u === 'string') : [],
|
|
133
190
|
poolStrategy: c.poolStrategy === 'round-robin' ? 'round-robin' : 'fallback',
|
|
191
|
+
credits: readCredits(c.credits),
|
|
134
192
|
})
|
|
135
193
|
}
|
|
136
194
|
}
|
|
@@ -145,6 +203,7 @@ export class SupplierConfigStore {
|
|
|
145
203
|
custom: [...cfg.custom],
|
|
146
204
|
poolOrder: [...cfg.poolOrder],
|
|
147
205
|
poolStrategy: cfg.poolStrategy,
|
|
206
|
+
credits: { ...cfg.credits },
|
|
148
207
|
}
|
|
149
208
|
}
|
|
150
209
|
try {
|
|
@@ -57,6 +57,12 @@ export type AccountState =
|
|
|
57
57
|
export interface SupplierAccountNow {
|
|
58
58
|
uid: string
|
|
59
59
|
nickname?: string
|
|
60
|
+
/**
|
|
61
|
+
* 剩余额度。**拿不到就报 `-1`**,不是 0:
|
|
62
|
+
* 插件刚重启(内存缓存空)、积分拉取失败、或压根不支持积分时都是 `-1`。
|
|
63
|
+
* 核心据此保留上一次持久化下来的值 —— 报 0 会把缓存冲成 0(0 是真值
|
|
64
|
+
* 「用完了」,核心分不清「拿到 0」和「没拿到」)。
|
|
65
|
+
*/
|
|
60
66
|
credits: number
|
|
61
67
|
/** 插件观察到的上游状态。 */
|
|
62
68
|
state: AccountState
|
|
@@ -96,25 +102,19 @@ export interface SupplierModule {
|
|
|
96
102
|
status(): SupplierStatusNow
|
|
97
103
|
/** 模型来源。`force=true` 时强制刷新来源(核心「获取模型」按钮调用)。 */
|
|
98
104
|
listModels(force?: boolean): Promise<ModelInfo[]> | ModelInfo[]
|
|
99
|
-
/** 默认前缀(可被通用层 alias 覆盖)。 */
|
|
100
|
-
getAlias(): string
|
|
101
105
|
/**
|
|
102
106
|
* 对**单个账号**调一次上游。插件不遍历账号、不管冷却、不写 res——
|
|
103
107
|
* 选号/回退/健康判定全是核心的活。
|
|
104
108
|
* 无账号供应商(如 opencode)传空 uid,忽略即可。
|
|
109
|
+
*
|
|
110
|
+
* 失败原因通过返回值的 `message` 报(核心在测试模型时直接用它做诊断提示),
|
|
111
|
+
* 插件不必自己存一份「上次失败」的状态。
|
|
105
112
|
*/
|
|
106
113
|
chatOnce(uid: string, req: ChatRequest): Promise<ChatOnceResult>
|
|
107
114
|
dispose(): void
|
|
108
115
|
|
|
109
116
|
// ---- 差异化能力(可选,按存在性暴露端点/UI) ----
|
|
110
117
|
|
|
111
|
-
/** 上次 chatOnce 失败的原因(诊断用)。
|
|
112
|
-
* 测试模型由 dsh-router 核心统一走 chatOnce 路径(账号池回退/冷却自动生效),
|
|
113
|
-
* 插件只需把失败原因暴露出来供核心汇总;不实现则测试失败时只有通用提示。 */
|
|
114
|
-
lastError?(): string | undefined
|
|
115
|
-
|
|
116
|
-
// ---- 差异化能力(可选,按存在性暴露端点/UI) ----
|
|
117
|
-
|
|
118
118
|
/** 生成登录链接(加账号)。有它才显示连接池(账号池)。 */
|
|
119
119
|
generateLoginUrl?(): string | { ok: boolean; error?: string; loginUrl?: string } | Promise<string | { ok: boolean; error?: string; loginUrl?: string }>
|
|
120
120
|
/** 回调完成登录。 */
|