dsh-token-dash 2.3.1 → 2.5.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.en.md +8 -5
- package/README.md +9 -5
- package/client.js +450 -133
- package/index.js +86 -17
- package/locale/en.json +5 -0
- package/locale/zh.json +5 -0
- package/package.json +3 -2
- package/src/adapters.js +608 -561
- package/src/core.js +936 -887
- package/src/diagnostics.js +160 -108
- package/src/quota-sources.js +228 -224
- package/src/version.js +44 -37
package/src/adapters.js
CHANGED
|
@@ -1,561 +1,608 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* External provider adapters. Endpoints and response semantics are copied from
|
|
3
|
-
* the reference plugins; do not invent fields or percentages.
|
|
4
|
-
*/
|
|
5
|
-
import { normalizeProvider, providerCurrency, providerLabel } from './providers.js'
|
|
6
|
-
import { PROVIDER_SOURCES } from './quota-sources.js'
|
|
7
|
-
|
|
8
|
-
const TIMEOUT = 6000
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
function
|
|
37
|
-
const
|
|
38
|
-
if (
|
|
39
|
-
return
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function
|
|
43
|
-
const
|
|
44
|
-
const
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
if (
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
return
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
const
|
|
335
|
-
return
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
const
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
*
|
|
444
|
-
*
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
const
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
if (
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
if (
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
if (item.
|
|
525
|
-
else if (item.
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
const
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
|
|
1
|
+
/**
|
|
2
|
+
* External provider adapters. Endpoints and response semantics are copied from
|
|
3
|
+
* the reference plugins; do not invent fields or percentages.
|
|
4
|
+
*/
|
|
5
|
+
import { normalizeProvider, providerCurrency, providerLabel } from './providers.js'
|
|
6
|
+
import { PROVIDER_SOURCES } from './quota-sources.js'
|
|
7
|
+
|
|
8
|
+
const TIMEOUT = 6000
|
|
9
|
+
// 宿主服务调用没有内置超时(2026-11-23:deepseekAccount.getBalance 曾挂起 30s)。
|
|
10
|
+
// 超时抛 HostTimeoutError,由 errorDetail 归类 host-timeout;不吞宿主真实异常。
|
|
11
|
+
const HOST_TIMEOUT = 5000
|
|
12
|
+
class HostTimeoutError extends Error {
|
|
13
|
+
constructor(label) {
|
|
14
|
+
super(`host-timeout:${label}`)
|
|
15
|
+
this.name = 'HostTimeout'
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async function withHostTimeout(promise, label) {
|
|
19
|
+
let timer = null
|
|
20
|
+
try {
|
|
21
|
+
return await Promise.race([
|
|
22
|
+
promise,
|
|
23
|
+
new Promise((_, reject) => {
|
|
24
|
+
timer = setTimeout(() => reject(new HostTimeoutError(label)), HOST_TIMEOUT)
|
|
25
|
+
}),
|
|
26
|
+
])
|
|
27
|
+
} finally {
|
|
28
|
+
clearTimeout(timer)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const GLM_QUOTA = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
|
|
32
|
+
const KIMI_USAGES = 'https://api.kimi.com/coding/v1/usages'
|
|
33
|
+
const KIMI_BALANCE = 'https://api.moonshot.cn/v1/users/me/balance'
|
|
34
|
+
const OPENROUTER_CREDITS = 'https://openrouter.ai/api/v1/credits'
|
|
35
|
+
|
|
36
|
+
export function clampPercent(value) {
|
|
37
|
+
const n = Number(value)
|
|
38
|
+
if (!Number.isFinite(n)) return null
|
|
39
|
+
return Math.max(0, Math.min(100, n))
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function parseGlmQuota(body) {
|
|
43
|
+
const data = body?.data ?? body
|
|
44
|
+
const rows = Array.isArray(data?.limits) ? data.limits : []
|
|
45
|
+
const windows = []
|
|
46
|
+
for (const row of rows) {
|
|
47
|
+
if (String(row?.type ?? '').toUpperCase() !== 'TOKENS_LIMIT') continue
|
|
48
|
+
const unit = Number(row.unit)
|
|
49
|
+
const key = unit === 3 ? '5h' : unit === 6 ? 'week' : null
|
|
50
|
+
if (key === null) continue
|
|
51
|
+
const percent = clampPercent(row.percentage)
|
|
52
|
+
if (percent === null) continue
|
|
53
|
+
windows.push({ key, usedPercent: percent, resetAt: Number(row.nextResetTime) || undefined, source: 'official' })
|
|
54
|
+
}
|
|
55
|
+
return windows
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function ratioWindow(key, raw) {
|
|
59
|
+
const used = clampPercent(raw?.used_ratio)
|
|
60
|
+
if (used === null) return undefined
|
|
61
|
+
return { key, usedPercent: used, resetAt: Number(raw?.reset_time) || undefined, source: 'official' }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function parseKimiQuota(body) {
|
|
65
|
+
const record = body?.data ?? body
|
|
66
|
+
const windows = []
|
|
67
|
+
const usages = record?.usages
|
|
68
|
+
if (usages !== null && typeof usages === 'object') {
|
|
69
|
+
const five = ratioWindow('5h', usages.limit_5h)
|
|
70
|
+
const month = ratioWindow('month', usages.limit_month_code) ?? ratioWindow('month', usages.limit_month_total)
|
|
71
|
+
if (five) windows.push(five)
|
|
72
|
+
if (month) windows.push(month)
|
|
73
|
+
}
|
|
74
|
+
const weekly = ratioWindow('week', record?.usage)
|
|
75
|
+
if (weekly) windows.push(weekly)
|
|
76
|
+
if (windows.length === 0) {
|
|
77
|
+
const limits = Array.isArray(record?.limits) ? record.limits : []
|
|
78
|
+
const five = limits
|
|
79
|
+
.map((item) => {
|
|
80
|
+
const detail = item?.detail ?? item
|
|
81
|
+
const limit = Number(detail?.limit)
|
|
82
|
+
const used = detail?.used !== undefined ? Number(detail.used) : (limit - Number(detail?.remaining))
|
|
83
|
+
const percent = limit > 0 && Number.isFinite(used) ? clampPercent((used / limit) * 100) : null
|
|
84
|
+
return percent === null ? null : { key: '5h', usedPercent: percent, resetAt: Number(detail?.resetTime) || undefined, source: 'official' }
|
|
85
|
+
})
|
|
86
|
+
.filter(Boolean)
|
|
87
|
+
.sort((left, right) => (right.resetAt ?? 0) - (left.resetAt ?? 0))
|
|
88
|
+
if (five[0]) windows.push(five[0])
|
|
89
|
+
const usage = record?.usage
|
|
90
|
+
const limit = Number(usage?.limit)
|
|
91
|
+
const used = Number(usage?.used)
|
|
92
|
+
if (limit > 0 && Number.isFinite(used)) windows.push({ key: 'week', usedPercent: clampPercent((used / limit) * 100), resetAt: Number(usage.resetTime) || undefined, source: 'official' })
|
|
93
|
+
}
|
|
94
|
+
return windows
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function parseOpenRouterCredits(body) {
|
|
98
|
+
const data = body?.data ?? body
|
|
99
|
+
const total = Number(data?.total_credits)
|
|
100
|
+
const usage = Number(data?.total_usage)
|
|
101
|
+
if (!Number.isFinite(total) || !Number.isFinite(usage)) return null
|
|
102
|
+
return { amount: Math.max(0, total - usage), currency: 'USD', status: 'ok', updatedAt: Date.now() }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function resolveCredential(ctx, credential) {
|
|
106
|
+
if (credential === undefined || credential === null) return undefined
|
|
107
|
+
if (credential.type !== 'bearer' && credential.type !== 'oauth-reuse') return undefined
|
|
108
|
+
return resolveKey(ctx, credential.refs ?? [])
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function resolveKey(ctx, names) {
|
|
112
|
+
const credentials = ctx.get?.('credentials')
|
|
113
|
+
if (credentials === undefined || typeof credentials.resolve !== 'function') return undefined
|
|
114
|
+
for (const name of names) {
|
|
115
|
+
try {
|
|
116
|
+
const hit = await withHostTimeout(credentials.resolve(name), 'credentials.resolve')
|
|
117
|
+
const value = hit?.value
|
|
118
|
+
if (typeof value === 'string' && value.trim() !== '') return { value: value.trim(), name }
|
|
119
|
+
} catch {
|
|
120
|
+
// try next name
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return undefined
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function requestJson(url, headers) {
|
|
127
|
+
const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(TIMEOUT) })
|
|
128
|
+
const body = await response.json().catch(() => null)
|
|
129
|
+
if (!response.ok) {
|
|
130
|
+
const error = new Error(`http-${response.status}`)
|
|
131
|
+
error.status = response.status
|
|
132
|
+
error.body = body
|
|
133
|
+
// 429 带整数秒的 Retry-After,属于源级退避输入,不进任何展示文案
|
|
134
|
+
const retryAfter = Number(response.headers?.get?.('retry-after'))
|
|
135
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter
|
|
136
|
+
throw error
|
|
137
|
+
}
|
|
138
|
+
return body
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** #47:错误分类(http+状态码 / timeout / network)——挂在条目 `_error`/`_quotaError` 上供日志还原原因。 */
|
|
142
|
+
function errorDetail(error) {
|
|
143
|
+
if (error?.status !== undefined) {
|
|
144
|
+
return {
|
|
145
|
+
kind: 'http',
|
|
146
|
+
status: error.status,
|
|
147
|
+
...(error.status >= 500 ? { upstream: true } : {}),
|
|
148
|
+
...(error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter }),
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const name = `${error?.name ?? ''} ${error?.message ?? ''}`
|
|
152
|
+
if (error?.name === 'HostTimeout') return { kind: 'host-timeout' }
|
|
153
|
+
if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
|
|
154
|
+
return { kind: 'network' }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function deepseek(ctx) {
|
|
158
|
+
const account = ctx.get?.('deepseekAccount')
|
|
159
|
+
if (account !== undefined && typeof account.getBalance === 'function') {
|
|
160
|
+
try {
|
|
161
|
+
const data = await withHostTimeout(account.getBalance({ version: '1.0.2', locale: 'zh-CN', timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 }), 'deepseekAccount.getBalance')
|
|
162
|
+
if (data?.status === 'ready') {
|
|
163
|
+
const wallets = [...(Array.isArray(data.value) ? data.value : Object.values(data.value ?? {})), ...(data.bonusWallets ?? [])]
|
|
164
|
+
const amount = wallets.filter((wallet) => wallet?.currency === undefined || wallet.currency === 'CNY')
|
|
165
|
+
.reduce((sum, wallet) => sum + (Number(wallet?.balance ?? wallet?.amount) || 0), 0)
|
|
166
|
+
return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
|
|
167
|
+
}
|
|
168
|
+
} catch {
|
|
169
|
+
// fall through to key
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const key = await resolveKey(ctx, ['DEEPSEEK_API_KEY'])
|
|
173
|
+
if (key === undefined) return null
|
|
174
|
+
try {
|
|
175
|
+
const body = await requestJson('https://api.deepseek.com/user/balance', { authorization: `Bearer ${key.value}` })
|
|
176
|
+
const amount = (body?.balance_infos ?? []).reduce((sum, item) => sum + (Number(item?.total_balance) || 0), 0)
|
|
177
|
+
return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
|
|
178
|
+
} catch (error) {
|
|
179
|
+
return { id: 'deepseek-official', kind: 'api', currency: 'CNY', _error: errorDetail(error), balance: { amount: null, status: error.status === 401 ? 'unconfigured' : 'error', currency: 'CNY', updatedAt: Date.now() } }
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function glm(ctx, prefs) {
|
|
184
|
+
const key = await resolveKey(ctx, ['ZHIPU_API_KEY', 'GLM_API_KEY', 'ZAI_API_KEY'])
|
|
185
|
+
if (key === undefined) return null
|
|
186
|
+
const mode = prefs?.billingModes?.zhipu
|
|
187
|
+
if (mode === 'api') return { id: 'zhipu', kind: 'api', mode: 'api', currency: 'CNY' }
|
|
188
|
+
// 手动覆盖为订阅时,quota 失败/无窗口仍保留订阅卡(显示“套餐查询失败”),不回落 api。
|
|
189
|
+
const subscriptionFallback = mode === 'subscription'
|
|
190
|
+
? { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [] }
|
|
191
|
+
: null
|
|
192
|
+
try {
|
|
193
|
+
const body = await requestJson(GLM_QUOTA, { authorization: key.value })
|
|
194
|
+
const windows = parseGlmQuota(body)
|
|
195
|
+
if (windows.length > 0) return { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows }
|
|
196
|
+
// 响应可解析但无窗口:解析问题(quota.parse),非网络错误
|
|
197
|
+
return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: { kind: 'parse' } }
|
|
198
|
+
} catch (error) {
|
|
199
|
+
return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: errorDetail(error) }
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Kimi Coding 配额查询。
|
|
205
|
+
* 返回 { state }:'no-key'(无 Coding Key 或显式 api 模式)、'ok'(含 entry)、'fallback'(自动模式下配额失败,走按量路径)。
|
|
206
|
+
*/
|
|
207
|
+
async function kimiCodingQuota(ctx, prefs) {
|
|
208
|
+
const coding = await resolveKey(ctx, ['KIMI_API_KEY', 'KIMI_CODING_API_KEY'])
|
|
209
|
+
if (coding === undefined) return { state: 'no-key' }
|
|
210
|
+
const mode = prefs?.billingModes?.moonshot
|
|
211
|
+
if (mode === 'api') return { state: 'no-key' }
|
|
212
|
+
let quotaError = null
|
|
213
|
+
try {
|
|
214
|
+
const body = await requestJson(KIMI_USAGES, { authorization: `Bearer ${coding.value}` })
|
|
215
|
+
const windows = parseKimiQuota(body)
|
|
216
|
+
if (windows.length > 0) return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows } }
|
|
217
|
+
quotaError = { kind: 'parse' }
|
|
218
|
+
} catch (error) {
|
|
219
|
+
quotaError = errorDetail(error)
|
|
220
|
+
}
|
|
221
|
+
if (mode === 'subscription') return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [], _quotaError: quotaError } }
|
|
222
|
+
return { state: 'fallback', quotaError }
|
|
223
|
+
return { state: 'fallback' }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function kimi(ctx, prefs) {
|
|
227
|
+
const quota = await kimiCodingQuota(ctx, prefs)
|
|
228
|
+
if (quota.state === 'ok') return quota.entry
|
|
229
|
+
const quotaError = quota.quotaError ?? null
|
|
230
|
+
const normal = await resolveKey(ctx, ['MOONSHOT_API_KEY'])
|
|
231
|
+
if (normal === undefined) return quota.state === 'no-key' ? null : { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError }
|
|
232
|
+
try {
|
|
233
|
+
const body = await requestJson(KIMI_BALANCE, { authorization: `Bearer ${normal.value}` })
|
|
234
|
+
const amount = Number(body?.data?.available_balance)
|
|
235
|
+
const ok = Number.isFinite(amount)
|
|
236
|
+
return {
|
|
237
|
+
id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError,
|
|
238
|
+
balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency: 'CNY', updatedAt: Date.now(), ...(ok ? {} : { _error: { kind: 'parse' } }) },
|
|
239
|
+
}
|
|
240
|
+
} catch (error) {
|
|
241
|
+
return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError, _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'CNY', updatedAt: Date.now() } }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function openrouter(ctx) {
|
|
246
|
+
const key = await resolveKey(ctx, ['OPENROUTER_API_KEY'])
|
|
247
|
+
if (key === undefined) return null
|
|
248
|
+
try {
|
|
249
|
+
const body = await requestJson(OPENROUTER_CREDITS, { authorization: `Bearer ${key.value}` })
|
|
250
|
+
const balance = parseOpenRouterCredits(body)
|
|
251
|
+
return { id: 'openrouter', kind: 'api', currency: 'USD', balance: balance ?? { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now(), _error: { kind: 'parse' } } }
|
|
252
|
+
} catch (error) {
|
|
253
|
+
return { id: 'openrouter', kind: 'api', currency: 'USD', _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now() } }
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Qwen 仅按量;国际站 Key(DASHSCOPE_INTL_API_KEY)按 USD,其余 CNY。无 quota 请求。 */
|
|
258
|
+
async function qwen(ctx) {
|
|
259
|
+
const key = await resolveKey(ctx, ['DASHSCOPE_INTL_API_KEY', 'DASHSCOPE_API_KEY', 'QWEN_API_KEY'])
|
|
260
|
+
if (key === undefined) return null
|
|
261
|
+
const intl = key.name === 'DASHSCOPE_INTL_API_KEY'
|
|
262
|
+
const currency = intl ? 'USD' : 'CNY'
|
|
263
|
+
return { id: 'qwen', kind: 'api', currency, balance: { amount: null, status: 'unsupported', currency, updatedAt: Date.now() } }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const LEGACY_READERS = { deepseek, glm, kimi, openrouter, qwen }
|
|
267
|
+
const WINDOW_KEYS = new Set(['5h', 'week', 'month'])
|
|
268
|
+
|
|
269
|
+
function normalizeWindows(windows) {
|
|
270
|
+
if (!Array.isArray(windows)) return []
|
|
271
|
+
const out = []
|
|
272
|
+
const seen = new Set()
|
|
273
|
+
for (const item of windows) {
|
|
274
|
+
if (item === null || item === undefined || !WINDOW_KEYS.has(item.key) || seen.has(item.key)) continue
|
|
275
|
+
const usedPercent = clampPercent(item.usedPercent)
|
|
276
|
+
if (usedPercent === null) continue
|
|
277
|
+
seen.add(item.key)
|
|
278
|
+
out.push({ ...item, usedPercent })
|
|
279
|
+
}
|
|
280
|
+
return out
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 通用 preflight:凭据存在才拼 query;异常返回空串,不阻断主请求。 */
|
|
284
|
+
async function sourceQuery(ctx, source) {
|
|
285
|
+
if (source.preflight === undefined) return ''
|
|
286
|
+
try {
|
|
287
|
+
const hit = await resolveKey(ctx, source.preflight.refs ?? [])
|
|
288
|
+
if (hit === undefined) return ''
|
|
289
|
+
return `${source.preflight.param}=${encodeURIComponent(hit.value)}`
|
|
290
|
+
} catch {
|
|
291
|
+
return ''
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function withQuery(url, query) {
|
|
296
|
+
if (query === '') return url
|
|
297
|
+
return `${url}${url.includes('?') ? '&' : '?'}${query}`
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** 可选 usage 钩子:失败只留错误详情,绝不影响余额结果与账本。 */
|
|
301
|
+
async function readSourceUsage(source, hit) {
|
|
302
|
+
if (source.usage === undefined) return { channel: undefined, error: undefined }
|
|
303
|
+
try {
|
|
304
|
+
const query = source.usage.range === undefined ? '' : `range=${encodeURIComponent(source.usage.range)}`
|
|
305
|
+
const body = await requestJson(withQuery(source.usage.url, query), { authorization: `Bearer ${hit.value}` })
|
|
306
|
+
const parsed = source.usage.parse(body)
|
|
307
|
+
return { channel: parsed?.channel ?? undefined, error: undefined }
|
|
308
|
+
} catch (error) {
|
|
309
|
+
return { channel: undefined, error: errorDetail(error) }
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function readDeclarativeSource(ctx, prefs, source, previous) {
|
|
314
|
+
const hit = await resolveCredential(ctx, source.credential)
|
|
315
|
+
if (hit === undefined) return null
|
|
316
|
+
const subscription = source.kind === 'subscription'
|
|
317
|
+
// mode 必须由 kind 派生:声明式订阅源才是订阅;写成常量会把 api 源固化成订阅(cost=0)
|
|
318
|
+
const base = { id: source.id, name: providerLabel(source.id), kind: source.kind, mode: subscription ? 'subscription' : 'api', currency: source.currency }
|
|
319
|
+
const query = await sourceQuery(ctx, source)
|
|
320
|
+
let body
|
|
321
|
+
try {
|
|
322
|
+
try {
|
|
323
|
+
body = await requestJson(withQuery(source.quota.url, query), { authorization: `Bearer ${hit.value}` })
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (source.quota.fallbackUrl === undefined || (error.status !== 404 && error.status !== 405)) throw error
|
|
326
|
+
body = await requestJson(withQuery(source.quota.fallbackUrl, query), { authorization: `Bearer ${hit.value}` })
|
|
327
|
+
}
|
|
328
|
+
} catch (error) {
|
|
329
|
+
const detail = errorDetail(error)
|
|
330
|
+
// 限流复用上一份快照,避免卡片在 429 时闪成「查询失败」;退避由缓存 until 承担
|
|
331
|
+
if (error.status === 429 && previous !== null && previous !== undefined) {
|
|
332
|
+
return { ...previous, _quotaError: detail, _rateLimited: true, fetchedAt: Date.now() }
|
|
333
|
+
}
|
|
334
|
+
const status = error.status === 401 ? 'unconfigured' : 'error'
|
|
335
|
+
return {
|
|
336
|
+
...base,
|
|
337
|
+
windows: [],
|
|
338
|
+
...(subscription ? {} : { balance: { amount: null, status, currency: source.currency, updatedAt: Date.now() } }),
|
|
339
|
+
_quotaError: detail,
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const parsed = source.quota.parse(body)
|
|
343
|
+
const windows = normalizeWindows(Array.isArray(parsed) ? parsed : parsed?.windows)
|
|
344
|
+
const balance = Array.isArray(parsed) ? undefined : parsed?.balance
|
|
345
|
+
const usage = await readSourceUsage(source, hit)
|
|
346
|
+
const extra = {
|
|
347
|
+
...(balance === undefined ? {} : { balance }),
|
|
348
|
+
...(usage.channel === undefined ? {} : { channel: usage.channel }),
|
|
349
|
+
...(usage.error === undefined ? {} : { _channelError: usage.error }),
|
|
350
|
+
}
|
|
351
|
+
if (windows.length === 0 && balance === undefined) return { ...base, windows: [], _quotaError: { kind: 'parse' }, ...extra }
|
|
352
|
+
return { ...base, windows, ...extra }
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function readSource(ctx, prefs, source, previous) {
|
|
356
|
+
if (source.legacy !== undefined) {
|
|
357
|
+
const reader = LEGACY_READERS[source.legacy]
|
|
358
|
+
return reader(ctx, prefs)
|
|
359
|
+
}
|
|
360
|
+
return readDeclarativeSource(ctx, prefs, source, previous)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** 订阅重查专用:Kimi 只查 Coding 配额,不请求 moonshot 余额。 */
|
|
364
|
+
async function readKimiSubscription(ctx, prefs) {
|
|
365
|
+
const quota = await kimiCodingQuota(ctx, prefs)
|
|
366
|
+
if (quota.state === 'ok') return quota.entry
|
|
367
|
+
if (quota.state === 'fallback') return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quota.quotaError ?? null }
|
|
368
|
+
return null
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const TTL_OK = 60000
|
|
372
|
+
const TTL_FAIL = 10000
|
|
373
|
+
|
|
374
|
+
/** 限流条目按 Retry-After 延后重试,成功 60s / 失败 10s 的基线不变。 */
|
|
375
|
+
function cacheExpiry(data, now) {
|
|
376
|
+
const retryAfter = data?._rateLimited === true ? Number(data?._quotaError?.retryAfter) : NaN
|
|
377
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0) return now + Math.max(TTL_FAIL, retryAfter * 1000)
|
|
378
|
+
return now + (data === null || data?._rateLimited === true ? TTL_FAIL : TTL_OK)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
async function readCachedSource(ctx, prefs, source, cache) {
|
|
382
|
+
const now = Date.now()
|
|
383
|
+
const cached = cache.get(source.id)
|
|
384
|
+
if (cached !== undefined && cached.promise === null && now < (cached.until ?? now)) return cached.data
|
|
385
|
+
if (cached?.promise !== undefined && cached.promise !== null) return cached.promise
|
|
386
|
+
const promise = readSource(ctx, prefs, source, cached?.data ?? null)
|
|
387
|
+
.then((data) => {
|
|
388
|
+
const at = Date.now()
|
|
389
|
+
// null 且有旧值时降级沿用旧快照(保留 _stale 标记),TTL 仍按失败档 10s 重试;
|
|
390
|
+
// 无旧值的确定性 :none 维持 data=null,避免掩盖"Key 真被删除"。
|
|
391
|
+
const stored = data === null && cached?.data != null ? { ...cached.data, _stale: true } : data
|
|
392
|
+
cache.set(source.id, { at, ok: data !== null && data?._rateLimited !== true, data: stored, promise: null, until: cacheExpiry(data, at) })
|
|
393
|
+
return data
|
|
394
|
+
})
|
|
395
|
+
.catch((error) => {
|
|
396
|
+
const at = Date.now()
|
|
397
|
+
const stored = cached?.data != null ? { ...cached.data, _stale: true } : null
|
|
398
|
+
cache.set(source.id, { at, ok: false, data: stored, promise: null, until: at + TTL_FAIL })
|
|
399
|
+
throw error
|
|
400
|
+
})
|
|
401
|
+
cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise, until: cached?.until ?? null })
|
|
402
|
+
return promise
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function visibleEntry(entry, prefs) {
|
|
406
|
+
return entry !== null && prefs?.billingModes?.[entry.id] !== 'hide'
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Adapter → VM boundary: normalize ad-hoc adapter rows into ProviderSnapshot. */
|
|
410
|
+
export function toSnapshot(entry) {
|
|
411
|
+
const error = entry.error ?? entry._error ?? null
|
|
412
|
+
const quotaError = entry.quotaError ?? entry._quotaError ?? null
|
|
413
|
+
const balance = entry.balance ?? null
|
|
414
|
+
const status = error !== null
|
|
415
|
+
? 'error'
|
|
416
|
+
: balance?.status === 'unconfigured'
|
|
417
|
+
? 'unconfigured'
|
|
418
|
+
: balance?.status === 'error'
|
|
419
|
+
? 'error'
|
|
420
|
+
: 'ok'
|
|
421
|
+
return {
|
|
422
|
+
id: entry.id,
|
|
423
|
+
name: entry.name,
|
|
424
|
+
kind: entry.kind === 'subscription' ? 'subscription' : 'api',
|
|
425
|
+
currency: entry.currency,
|
|
426
|
+
status,
|
|
427
|
+
balance,
|
|
428
|
+
// 渠道侧只读用量与限流标记:仅展示用,不参与计价(REQ-04)
|
|
429
|
+
...(entry.channel === undefined ? {} : { channel: entry.channel }),
|
|
430
|
+
...(entry._channelError === undefined ? {} : { channelError: entry._channelError }),
|
|
431
|
+
rateLimited: entry._rateLimited === true,
|
|
432
|
+
stale: entry._stale === true,
|
|
433
|
+
mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
|
|
434
|
+
windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
|
|
435
|
+
error,
|
|
436
|
+
quotaError,
|
|
437
|
+
fetchedAt: entry.fetchedAt ?? Date.now(),
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Query configured providers; each failure is isolated. Balance/credits are always requested
|
|
443
|
+
* (P2 shows them regardless of the P1-only toggle, #31). 空档原因挂在返回数组的 `misses` 上:
|
|
444
|
+
* `<id>:none` 未配置、`:error` 请求失败、`:hidden` 被计费模式隐藏。
|
|
445
|
+
* 缓存按源保存在调用方传入的 Map 中:成功 60s、失败 10s,并发复用 promise。
|
|
446
|
+
*/
|
|
447
|
+
export async function readProviders(ctx, prefs, cache = new Map()) {
|
|
448
|
+
const timings = []
|
|
449
|
+
const results = await Promise.allSettled(PROVIDER_SOURCES.map(async (source) => {
|
|
450
|
+
const startedAt = Date.now()
|
|
451
|
+
try {
|
|
452
|
+
return await readCachedSource(ctx, prefs, source, cache)
|
|
453
|
+
} finally {
|
|
454
|
+
timings.push({ id: source.id, ms: Date.now() - startedAt })
|
|
455
|
+
}
|
|
456
|
+
}))
|
|
457
|
+
const out = []
|
|
458
|
+
const misses = []
|
|
459
|
+
const failures = []
|
|
460
|
+
results.forEach((result, index) => {
|
|
461
|
+
const id = PROVIDER_SOURCES[index].id
|
|
462
|
+
if (result.status !== 'fulfilled') {
|
|
463
|
+
misses.push(`${id}:error`)
|
|
464
|
+
failures.push({ id, error: errorDetail(result.reason) })
|
|
465
|
+
return
|
|
466
|
+
}
|
|
467
|
+
if (result.value === null) {
|
|
468
|
+
// 声明式源返回 null 即凭据未命中;并入 failures 以便 detect.fail 归因(不改变 :none 契约)
|
|
469
|
+
const refs = PROVIDER_SOURCES[index].credential?.refs ?? []
|
|
470
|
+
misses.push(`${id}:none`)
|
|
471
|
+
if (refs.length > 0) failures.push({ id, error: { kind: 'missing-credential', refs } })
|
|
472
|
+
return
|
|
473
|
+
}
|
|
474
|
+
if (visibleEntry(result.value, prefs) !== true) { misses.push(`${id}:hidden`); return }
|
|
475
|
+
const value = result.value
|
|
476
|
+
value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
|
|
477
|
+
out.push(toSnapshot(value))
|
|
478
|
+
})
|
|
479
|
+
out.misses = misses
|
|
480
|
+
out.failures = failures
|
|
481
|
+
// 缓存命中的源计时趋近 0,最慢者即真实拖慢探测的源
|
|
482
|
+
out.slowest = timings.length === 0 ? null : timings.reduce((a, b) => (b.ms > a.ms ? b : a))
|
|
483
|
+
return out
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* P3「重新检测」专用:只重查订阅 provider 的配额,绕过缓存。
|
|
488
|
+
* 仅返回 subscription 条目;无 Key 的 provider 不返回(由调用方从缓存移除)。
|
|
489
|
+
*/
|
|
490
|
+
export async function readSubscriptions(ctx, prefs) {
|
|
491
|
+
const sources = PROVIDER_SOURCES.filter((source) => source.kind === 'subscription')
|
|
492
|
+
const results = await Promise.allSettled(sources.map((source) => (
|
|
493
|
+
source.legacy === 'kimi' ? readKimiSubscription(ctx, prefs) : readSource(ctx, prefs, source)
|
|
494
|
+
)))
|
|
495
|
+
const out = []
|
|
496
|
+
const failures = []
|
|
497
|
+
results.forEach((result, index) => {
|
|
498
|
+
if (result.status !== 'fulfilled') {
|
|
499
|
+
failures.push({ id: sources[index].id, error: errorDetail(result.reason) })
|
|
500
|
+
return
|
|
501
|
+
}
|
|
502
|
+
if (result.value === null) return
|
|
503
|
+
// 旧源(GLM / Kimi)配额失败时可能回落 API 条目,保留旧行为;新源只保留订阅条目。
|
|
504
|
+
const legacy = sources[index].legacy !== undefined
|
|
505
|
+
if (result.value.kind !== 'subscription' && legacy !== true) return
|
|
506
|
+
if (visibleEntry(result.value, prefs) !== true) return
|
|
507
|
+
out.push(toSnapshot(result.value))
|
|
508
|
+
})
|
|
509
|
+
out.failures = failures
|
|
510
|
+
return out
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** #46/#47:按 §2.5 adapter.* 事件表记侦测结果与错误原因——只记状态/计数/错误分类,不记 Key/响应体(脱敏约束)。 */
|
|
514
|
+
export function logAdapterEvents(log, providers) {
|
|
515
|
+
const info = (module, event, meta) => log.info(module, event, meta)
|
|
516
|
+
// 错误详情合并进 meta:kind=http 时带 status,便于报障还原原因
|
|
517
|
+
const errorMeta = (detail) => (detail === null || detail === undefined
|
|
518
|
+
? {}
|
|
519
|
+
: detail.kind === 'http'
|
|
520
|
+
? { errorKind: detail.kind, httpStatus: detail.status, ...(detail.retryAfter === undefined ? {} : { retryAfter: detail.retryAfter }) }
|
|
521
|
+
: { errorKind: detail.kind })
|
|
522
|
+
for (const item of providers) {
|
|
523
|
+
if (item.id === 'deepseek-official') {
|
|
524
|
+
if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
|
|
525
|
+
else if (item.balance?.status === 'unconfigured') info('adapter.deepseek', 'balance.auth', errorMeta(item.error))
|
|
526
|
+
else if (item.balance !== undefined) info('adapter.deepseek', 'balance.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
|
|
527
|
+
continue
|
|
528
|
+
}
|
|
529
|
+
if (item.id === 'zhipu' || item.id === 'moonshot') {
|
|
530
|
+
const module = item.id === 'zhipu' ? 'adapter.glm' : 'adapter.kimi'
|
|
531
|
+
if (item.kind === 'subscription') {
|
|
532
|
+
const windows = (item.windows ?? []).length
|
|
533
|
+
if (windows > 0) info(module, 'quota.ok', { windows })
|
|
534
|
+
else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
|
|
535
|
+
else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
|
|
536
|
+
} else if (item.quotaError !== undefined && item.quotaError !== null) {
|
|
537
|
+
info(module, 'quota.fail', { ...errorMeta(item.quotaError) })
|
|
538
|
+
} else {
|
|
539
|
+
info(module, 'quota.miss', {})
|
|
540
|
+
}
|
|
541
|
+
if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { amount: item.balance.amount })
|
|
542
|
+
if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item.error ?? item.balance._error) })
|
|
543
|
+
continue
|
|
544
|
+
}
|
|
545
|
+
if (item.id === 'openrouter') {
|
|
546
|
+
if (item.balance?.status === 'ok') info('adapter.openrouter', 'credits.ok', { amount: item.balance.amount })
|
|
547
|
+
else if (item.balance !== undefined) info('adapter.openrouter', 'credits.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
|
|
548
|
+
continue
|
|
549
|
+
}
|
|
550
|
+
if (item.id === 'qwen') {
|
|
551
|
+
info('adapter.qwen', item.currency === 'USD' ? 'currency.usd' : 'detected', {})
|
|
552
|
+
continue
|
|
553
|
+
}
|
|
554
|
+
if (item.id === 'opencode-go' || item.id === 'command-code') {
|
|
555
|
+
const module = item.id === 'opencode-go' ? 'adapter.opencode' : 'adapter.commandcode'
|
|
556
|
+
const windows = (item.windows ?? []).length
|
|
557
|
+
if (windows > 0) info(module, 'quota.ok', { windows })
|
|
558
|
+
else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
|
|
559
|
+
else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
|
|
560
|
+
if (item.balance?.status === 'ok') info(module, 'credits.ok', { amount: item.balance.amount })
|
|
561
|
+
continue
|
|
562
|
+
}
|
|
563
|
+
if (item.id === 'ollama') {
|
|
564
|
+
const balance = item.balance
|
|
565
|
+
if (balance?.status === 'ok') info('adapter.ollama', 'quota.ok', { amount: balance.amount, purchased: balance.purchased ?? 0, legacy: balance.legacy === true })
|
|
566
|
+
else if (balance?.status === 'unconfigured') info('adapter.ollama', 'quota.auth', {})
|
|
567
|
+
else info('adapter.ollama', 'quota.fail', { status: balance?.status ?? 'error', ...errorMeta(item.quotaError ?? item.error) })
|
|
568
|
+
if (item.channel !== undefined) info('adapter.ollama', 'usage', { range: item.channel.range, usageUsd: item.channel.usageUsd })
|
|
569
|
+
else if (item.channelError !== undefined) info('adapter.ollama', 'usage.fail', errorMeta(item.channelError))
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const FAILURE_MODULES = {
|
|
575
|
+
'deepseek-official': 'adapter.deepseek',
|
|
576
|
+
zhipu: 'adapter.glm',
|
|
577
|
+
moonshot: 'adapter.kimi',
|
|
578
|
+
openrouter: 'adapter.openrouter',
|
|
579
|
+
qwen: 'adapter.qwen',
|
|
580
|
+
'opencode-go': 'adapter.opencode',
|
|
581
|
+
'command-code': 'adapter.commandcode',
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* 探测结果签名:miss 清单不变时无需重复记日志,避免每轮刷新刷屏。
|
|
586
|
+
* 返回 `id:none,id:hidden,...` 的稳定字符串;无 miss 时为空串。
|
|
587
|
+
*/
|
|
588
|
+
export function missSignature(providers) {
|
|
589
|
+
return (providers?.misses ?? []).join(',')
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Promise.allSettled 的拒绝项没有 entry,单独补 adapter.<id> 失败日志。 */
|
|
593
|
+
export function logAdapterFailures(log, failures = []) {
|
|
594
|
+
for (const item of failures) {
|
|
595
|
+
const module = FAILURE_MODULES[item.id] ?? `adapter.${item.id}`
|
|
596
|
+
const error = item.error ?? { kind: 'network' }
|
|
597
|
+
log.warn(module, 'detect.fail', {
|
|
598
|
+
errorKind: error.kind,
|
|
599
|
+
...(Array.isArray(error.refs) ? { refs: error.refs } : {}),
|
|
600
|
+
...(error.status === undefined ? {} : { httpStatus: error.status }),
|
|
601
|
+
...(error.upstream === true ? { upstream: true } : {}),
|
|
602
|
+
})
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
export { KIMI_USAGES, GLM_QUOTA, KIMI_BALANCE, OPENROUTER_CREDITS }
|
|
607
|
+
// 内部工具导出:仅用于单元测试验证超时与降级行为
|
|
608
|
+
export { HostTimeoutError, withHostTimeout, errorDetail }
|