dsh-token-dash 1.1.2 → 2.0.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/AGENTS.md +66 -51
- package/README.en.md +88 -45
- package/README.md +86 -44
- package/client.js +1004 -338
- package/index.js +103 -38
- package/package.json +3 -1
- package/src/adapters.js +169 -17
- package/src/diagnostics.js +1 -0
- package/src/providers.js +25 -1
- package/src/quota-sources.js +123 -0
package/index.js
CHANGED
|
@@ -9,7 +9,8 @@ import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState,
|
|
|
9
9
|
import { ingest, backfill } from './src/collect.js'
|
|
10
10
|
import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
|
|
11
11
|
import { buildExport, mergeImportDays, validateBundle } from './src/backup.js'
|
|
12
|
-
import { logAdapterEvents, readProviders, readSubscriptions } from './src/adapters.js'
|
|
12
|
+
import { logAdapterEvents, logAdapterFailures, readProviders, readSubscriptions } from './src/adapters.js'
|
|
13
|
+
import { PROVIDER_SOURCES } from './src/quota-sources.js'
|
|
13
14
|
import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
14
15
|
import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
|
|
15
16
|
import { isNewer } from './src/version.js'
|
|
@@ -18,7 +19,27 @@ export const name = 'dsh-token-dash'
|
|
|
18
19
|
|
|
19
20
|
const ROUTE_PREFIX = '/token-dash/api'
|
|
20
21
|
const CURRENT_VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
|
|
21
|
-
const
|
|
22
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
|
|
23
|
+
|
|
24
|
+
/** 宿主版本:优先环境变量,其次 Electron asar 内的 package.json;读不到时写 unknown,避免硬编码过期。 */
|
|
25
|
+
function hostVersion() {
|
|
26
|
+
if (typeof process.env.DSH_VERSION === 'string' && process.env.DSH_VERSION !== '') return process.env.DSH_VERSION
|
|
27
|
+
const resources = join(dirname(process.execPath), 'resources')
|
|
28
|
+
const candidates = [
|
|
29
|
+
join(resources, 'app.asar', 'package.json'),
|
|
30
|
+
join(resources, 'app.asar', 'dsh', 'package.json'),
|
|
31
|
+
join(resources, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'package.json'),
|
|
32
|
+
]
|
|
33
|
+
for (const file of candidates) {
|
|
34
|
+
try {
|
|
35
|
+
const version = JSON.parse(readFileSync(file, 'utf8')).version
|
|
36
|
+
if (typeof version === 'string' && version !== '') return version
|
|
37
|
+
} catch {
|
|
38
|
+
// try next
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return 'unknown'
|
|
42
|
+
}
|
|
22
43
|
let updateCache = { at: 0, data: null }
|
|
23
44
|
|
|
24
45
|
/** Locate the bundled dsh CLI (same layout scripts/e2e.mjs relies on). */
|
|
@@ -155,13 +176,34 @@ function normalizePrefs(input, base) {
|
|
|
155
176
|
return prefs
|
|
156
177
|
}
|
|
157
178
|
|
|
179
|
+
function isLoopbackRequest(req) {
|
|
180
|
+
const remote = String(req.socket?.remoteAddress ?? '')
|
|
181
|
+
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(remote)) return false
|
|
182
|
+
const host = String(req.headers?.host ?? '').replace(/:\d+$/, '')
|
|
183
|
+
if (!LOOPBACK_HOSTS.has(host)) return false
|
|
184
|
+
const origin = req.headers?.origin
|
|
185
|
+
if (origin === undefined) return true
|
|
186
|
+
try {
|
|
187
|
+
const url = new URL(origin)
|
|
188
|
+
return LOOPBACK_HOSTS.has(url.hostname)
|
|
189
|
+
} catch {
|
|
190
|
+
return false
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
158
194
|
export function apply(ctx) {
|
|
159
195
|
const dir = dataDir(ctx)
|
|
160
196
|
const logDir = logsDir(ctx)
|
|
161
|
-
const logger = createLogger({ dir: logDir, version: CURRENT_VERSION, dshVersion:
|
|
197
|
+
const logger = createLogger({ dir: logDir, version: CURRENT_VERSION, dshVersion: hostVersion() })
|
|
162
198
|
let prefs
|
|
163
199
|
let state
|
|
164
|
-
let providerCache =
|
|
200
|
+
let providerCache = new Map()
|
|
201
|
+
let providerCacheMeta = { at: 0, hadProviders: false, degraded: false }
|
|
202
|
+
const cacheData = () => [...providerCache.values()].map((entry) => entry.data).filter((item) => item !== null && item !== undefined)
|
|
203
|
+
const clearProviderCache = () => {
|
|
204
|
+
providerCache.clear()
|
|
205
|
+
providerCacheMeta = { at: 0, hadProviders: false, degraded: false }
|
|
206
|
+
}
|
|
165
207
|
const ready = Promise.all([loadState(dir, logger), loadPrefs(dir, logger)]).then(([loadedState, loadedPrefs]) => {
|
|
166
208
|
state = loadedState ?? emptyState()
|
|
167
209
|
prefs = loadedPrefs
|
|
@@ -248,42 +290,62 @@ export function apply(ctx) {
|
|
|
248
290
|
ctx.inject(['webServer'], (scoped) => {
|
|
249
291
|
const webServer = scoped.webServer
|
|
250
292
|
if (webServer === undefined) return
|
|
293
|
+
let providerRefresh = null
|
|
251
294
|
const refreshProviderCache = async () => {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
logger.
|
|
271
|
-
|
|
272
|
-
|
|
295
|
+
if (providerRefresh !== null) return providerRefresh
|
|
296
|
+
providerRefresh = (async () => {
|
|
297
|
+
const data = await readProviders(scoped, prefs, providerCache)
|
|
298
|
+
const hadProviders = providerCacheMeta.hadProviders === true || data.length > 0
|
|
299
|
+
providerCacheMeta = {
|
|
300
|
+
at: Date.now(),
|
|
301
|
+
hadProviders,
|
|
302
|
+
degraded: data.length === 0 && hadProviders,
|
|
303
|
+
}
|
|
304
|
+
if (data.length === 0) {
|
|
305
|
+
logger.warn('provider', 'probe.miss', {
|
|
306
|
+
misses: data.misses ?? [],
|
|
307
|
+
credentials: scoped.get?.('credentials') !== undefined,
|
|
308
|
+
account: scoped.get?.('deepseekAccount') !== undefined,
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
logAdapterEvents(logger, data)
|
|
312
|
+
logAdapterFailures(logger, data.failures)
|
|
313
|
+
logger.debug('provider', 'cache.state', { entries: providerCache.size, providers: data.length, misses: (data.misses ?? []).length })
|
|
314
|
+
if (stampProviderKinds(state, data)) {
|
|
315
|
+
logger.info('provider', 'kind.stamp', { ids: Object.keys(state.providerKinds) })
|
|
316
|
+
flusher.schedule()
|
|
317
|
+
}
|
|
318
|
+
})().finally(() => { providerRefresh = null })
|
|
319
|
+
return providerRefresh
|
|
273
320
|
}
|
|
274
321
|
const off = webServer.register({
|
|
275
322
|
kind: 'prefix',
|
|
276
323
|
path: ROUTE_PREFIX,
|
|
277
324
|
handler: async (req, res) => {
|
|
278
325
|
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
326
|
+
if (!isLoopbackRequest(req)) {
|
|
327
|
+
let rejection
|
|
328
|
+
try {
|
|
329
|
+
rejection = await scoped.get?.('connection')?.requestRejection?.(req)
|
|
330
|
+
} catch {
|
|
331
|
+
rejection = undefined
|
|
332
|
+
}
|
|
333
|
+
if (rejection !== undefined && rejection !== null) {
|
|
334
|
+
logger.warn('route', 'forbidden', { method: req.method, path: url.pathname, source: 'requestRejection' })
|
|
335
|
+
return rejection
|
|
336
|
+
}
|
|
337
|
+
logger.warn('route', 'forbidden', { method: req.method, path: url.pathname, source: 'loopback' })
|
|
338
|
+
json(res, 403, { ok: false, reason: 'forbidden' })
|
|
339
|
+
return
|
|
340
|
+
}
|
|
279
341
|
try {
|
|
280
342
|
await ready
|
|
281
343
|
if (url.pathname === `${ROUTE_PREFIX}/summary` && req.method === 'GET') {
|
|
282
|
-
if (Date.now() -
|
|
283
|
-
const summary = buildSummary(state, prefs, Date.now(),
|
|
344
|
+
if (Date.now() - providerCacheMeta.at > 5000) await refreshProviderCache()
|
|
345
|
+
const summary = buildSummary(state, prefs, Date.now(), cacheData())
|
|
284
346
|
summary.version = CURRENT_VERSION
|
|
285
347
|
summary.refreshMs = prefs.refreshMs
|
|
286
|
-
summary.providersDegraded =
|
|
348
|
+
summary.providersDegraded = providerCacheMeta.degraded === true
|
|
287
349
|
summary.catalog = catalogInfo()
|
|
288
350
|
logger.info('vm', 'build', { providers: summary.providers.length, api: summary.providers.filter((item) => item.kind === 'api').length, subscription: summary.providers.filter((item) => item.kind === 'subscription').length })
|
|
289
351
|
json(res, 200, { ok: true, data: summary })
|
|
@@ -295,8 +357,8 @@ export function apply(ctx) {
|
|
|
295
357
|
json(res, 400, { ok: false, reason: 'invalid-range' })
|
|
296
358
|
return
|
|
297
359
|
}
|
|
298
|
-
if (Date.now() -
|
|
299
|
-
const usage = buildUsage(state, prefs, range, Date.now(),
|
|
360
|
+
if (Date.now() - providerCacheMeta.at > 5000) await refreshProviderCache()
|
|
361
|
+
const usage = buildUsage(state, prefs, range, Date.now(), cacheData())
|
|
300
362
|
logger.info('vm', 'usage', {
|
|
301
363
|
range,
|
|
302
364
|
models: usage.models.length,
|
|
@@ -310,19 +372,22 @@ export function apply(ctx) {
|
|
|
310
372
|
if (url.pathname === `${ROUTE_PREFIX}/providers/refresh` && req.method === 'POST') {
|
|
311
373
|
// 仅重查订阅 provider 配额(GLM / Kimi Coding),绕过 TTL 缓存;无 Key 的订阅 provider 从缓存移除。
|
|
312
374
|
const subs = await readSubscriptions(scoped, prefs)
|
|
313
|
-
const
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
for (const item of subs)
|
|
317
|
-
|
|
375
|
+
for (const source of PROVIDER_SOURCES) {
|
|
376
|
+
if (source.kind === 'subscription') providerCache.delete(source.id)
|
|
377
|
+
}
|
|
378
|
+
for (const item of subs) {
|
|
379
|
+
providerCache.set(item.id, { at: Date.now(), ok: true, data: item, promise: null })
|
|
380
|
+
}
|
|
381
|
+
providerCacheMeta = { at: Date.now(), hadProviders: true, degraded: false }
|
|
318
382
|
if (stampProviderKinds(state, subs)) flusher.schedule()
|
|
319
383
|
logAdapterEvents(logger, subs)
|
|
384
|
+
logAdapterFailures(logger, subs.failures)
|
|
320
385
|
logger.info('provider', 'subscriptions.refreshed', { ids: subs.map((item) => item.id) })
|
|
321
386
|
json(res, 200, { ok: true, data: { refreshed: subs.map((item) => item.id) } })
|
|
322
387
|
return
|
|
323
388
|
}
|
|
324
389
|
if (url.pathname === `${ROUTE_PREFIX}/export` && req.method === 'GET') {
|
|
325
|
-
const data = buildExport(state, prefs, Date.now(),
|
|
390
|
+
const data = buildExport(state, prefs, Date.now(), cacheData())
|
|
326
391
|
logger.info('data', 'export', { month: data.month, days: Object.keys(data.days).length, models: data.usage.all.models.length })
|
|
327
392
|
json(res, 200, { ok: true, data })
|
|
328
393
|
return
|
|
@@ -343,7 +408,7 @@ export function apply(ctx) {
|
|
|
343
408
|
prefs = normalizePrefs(bundle.prefs ?? {}, prefs)
|
|
344
409
|
state.days = mergeImportDays(state.days, bundle.month, bundle.days)
|
|
345
410
|
state.providerKinds = { ...(state.providerKinds ?? {}), ...(bundle.providerKinds ?? {}) }
|
|
346
|
-
|
|
411
|
+
clearProviderCache()
|
|
347
412
|
flusher.schedule()
|
|
348
413
|
logger.info('data', 'import', {
|
|
349
414
|
month: bundle.month,
|
|
@@ -420,7 +485,7 @@ export function apply(ctx) {
|
|
|
420
485
|
const body = JSON.parse((await readBody(req)) || '{}')
|
|
421
486
|
prefs = normalizePrefs(body, prefs)
|
|
422
487
|
await saveJson(dir, 'prefs.json', prefs)
|
|
423
|
-
|
|
488
|
+
clearProviderCache()
|
|
424
489
|
logger.info('boot', 'prefs.saved', { budgets: Object.keys(prefs.budgets).length, modes: Object.keys(prefs.billingModes).length })
|
|
425
490
|
json(res, 200, { ok: true, data: prefs })
|
|
426
491
|
return
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-token-dash",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "DeepSeek Harness Token 看板:月度预算与订阅配额、账户余额、时间范围费用与真实 Tokens 明细,支持本地 JSON 导出 / 导入备份。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -44,6 +44,8 @@
|
|
|
44
44
|
"e2e": "node scripts/e2e.mjs",
|
|
45
45
|
"logs": "node tools/logs.mjs",
|
|
46
46
|
"shots": "node tools/mock/shots.mjs",
|
|
47
|
+
"preview": "node tools/preview/render.mjs",
|
|
48
|
+
"preview:publish": "node tools/preview/render.mjs --publish",
|
|
47
49
|
"icon": "node tools/mock/icon.mjs",
|
|
48
50
|
"pack": "node -e \"require('fs').mkdirSync('build',{recursive:true})\" && npm pack --pack-destination build",
|
|
49
51
|
"prepublishOnly": "npm test"
|
package/src/adapters.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* External provider adapters. Endpoints and response semantics are copied from
|
|
3
3
|
* the reference plugins; do not invent fields or percentages.
|
|
4
4
|
*/
|
|
5
|
-
import { normalizeProvider, providerCurrency } from './providers.js'
|
|
5
|
+
import { normalizeProvider, providerCurrency, providerLabel } from './providers.js'
|
|
6
|
+
import { PROVIDER_SOURCES } from './quota-sources.js'
|
|
6
7
|
|
|
7
8
|
const TIMEOUT = 6000
|
|
8
9
|
const GLM_QUOTA = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
|
|
@@ -79,6 +80,12 @@ export function parseOpenRouterCredits(body) {
|
|
|
79
80
|
return { amount: Math.max(0, total - usage), currency: 'USD', status: 'ok', updatedAt: Date.now() }
|
|
80
81
|
}
|
|
81
82
|
|
|
83
|
+
async function resolveCredential(ctx, credential) {
|
|
84
|
+
if (credential === undefined || credential === null) return undefined
|
|
85
|
+
if (credential.type !== 'bearer' && credential.type !== 'oauth-reuse') return undefined
|
|
86
|
+
return resolveKey(ctx, credential.refs ?? [])
|
|
87
|
+
}
|
|
88
|
+
|
|
82
89
|
async function resolveKey(ctx, names) {
|
|
83
90
|
const credentials = ctx.get?.('credentials')
|
|
84
91
|
if (credentials === undefined || typeof credentials.resolve !== 'function') return undefined
|
|
@@ -108,7 +115,9 @@ async function requestJson(url, headers) {
|
|
|
108
115
|
|
|
109
116
|
/** #47:错误分类(http+状态码 / timeout / network)——挂在条目 `_error`/`_quotaError` 上供日志还原原因。 */
|
|
110
117
|
function errorDetail(error) {
|
|
111
|
-
if (error?.status !== undefined)
|
|
118
|
+
if (error?.status !== undefined) {
|
|
119
|
+
return { kind: 'http', status: error.status, ...(error.status >= 500 ? { upstream: true } : {}) }
|
|
120
|
+
}
|
|
112
121
|
const name = `${error?.name ?? ''} ${error?.message ?? ''}`
|
|
113
122
|
if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
|
|
114
123
|
return { kind: 'network' }
|
|
@@ -223,6 +232,101 @@ async function qwen(ctx) {
|
|
|
223
232
|
return { id: 'qwen', kind: 'api', currency, balance: { amount: null, status: 'unsupported', currency, updatedAt: Date.now() } }
|
|
224
233
|
}
|
|
225
234
|
|
|
235
|
+
const LEGACY_READERS = { deepseek, glm, kimi, openrouter, qwen }
|
|
236
|
+
const WINDOW_KEYS = new Set(['5h', 'week', 'month'])
|
|
237
|
+
|
|
238
|
+
function normalizeWindows(windows) {
|
|
239
|
+
if (!Array.isArray(windows)) return []
|
|
240
|
+
const out = []
|
|
241
|
+
const seen = new Set()
|
|
242
|
+
for (const item of windows) {
|
|
243
|
+
if (item === null || item === undefined || !WINDOW_KEYS.has(item.key) || seen.has(item.key)) continue
|
|
244
|
+
const usedPercent = clampPercent(item.usedPercent)
|
|
245
|
+
if (usedPercent === null) continue
|
|
246
|
+
seen.add(item.key)
|
|
247
|
+
out.push({ ...item, usedPercent })
|
|
248
|
+
}
|
|
249
|
+
return out
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 通用 preflight:凭据存在才拼 query;异常返回空串,不阻断主请求。 */
|
|
253
|
+
async function sourceQuery(ctx, source) {
|
|
254
|
+
if (source.preflight === undefined) return ''
|
|
255
|
+
try {
|
|
256
|
+
const hit = await resolveKey(ctx, source.preflight.refs ?? [])
|
|
257
|
+
if (hit === undefined) return ''
|
|
258
|
+
return `${source.preflight.param}=${encodeURIComponent(hit.value)}`
|
|
259
|
+
} catch {
|
|
260
|
+
return ''
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function withQuery(url, query) {
|
|
265
|
+
if (query === '') return url
|
|
266
|
+
return `${url}${url.includes('?') ? '&' : '?'}${query}`
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function readDeclarativeSource(ctx, prefs, source) {
|
|
270
|
+
const hit = await resolveCredential(ctx, source.credential)
|
|
271
|
+
if (hit === undefined) return null
|
|
272
|
+
const base = { id: source.id, name: providerLabel(source.id), kind: source.kind, mode: 'subscription', currency: source.currency }
|
|
273
|
+
const query = await sourceQuery(ctx, source)
|
|
274
|
+
let body
|
|
275
|
+
try {
|
|
276
|
+
try {
|
|
277
|
+
body = await requestJson(withQuery(source.quota.url, query), { authorization: `Bearer ${hit.value}` })
|
|
278
|
+
} catch (error) {
|
|
279
|
+
if (source.quota.fallbackUrl === undefined || (error.status !== 404 && error.status !== 405)) throw error
|
|
280
|
+
body = await requestJson(withQuery(source.quota.fallbackUrl, query), { authorization: `Bearer ${hit.value}` })
|
|
281
|
+
}
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return { ...base, windows: [], _quotaError: errorDetail(error) }
|
|
284
|
+
}
|
|
285
|
+
const parsed = source.quota.parse(body)
|
|
286
|
+
const windows = normalizeWindows(Array.isArray(parsed) ? parsed : parsed?.windows)
|
|
287
|
+
const balance = Array.isArray(parsed) ? undefined : parsed?.balance
|
|
288
|
+
if (windows.length === 0 && balance === undefined) return { ...base, windows: [], _quotaError: { kind: 'parse' } }
|
|
289
|
+
return { ...base, windows, ...(balance === undefined ? {} : { balance }) }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function readSource(ctx, prefs, source) {
|
|
293
|
+
if (source.legacy !== undefined) {
|
|
294
|
+
const reader = LEGACY_READERS[source.legacy]
|
|
295
|
+
return reader(ctx, prefs)
|
|
296
|
+
}
|
|
297
|
+
return readDeclarativeSource(ctx, prefs, source)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** 订阅重查专用:Kimi 只查 Coding 配额,不请求 moonshot 余额。 */
|
|
301
|
+
async function readKimiSubscription(ctx, prefs) {
|
|
302
|
+
const quota = await kimiCodingQuota(ctx, prefs)
|
|
303
|
+
if (quota.state === 'ok') return quota.entry
|
|
304
|
+
if (quota.state === 'fallback') return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quota.quotaError ?? null }
|
|
305
|
+
return null
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const TTL_OK = 60000
|
|
309
|
+
const TTL_FAIL = 10000
|
|
310
|
+
|
|
311
|
+
async function readCachedSource(ctx, prefs, source, cache) {
|
|
312
|
+
const now = Date.now()
|
|
313
|
+
const cached = cache.get(source.id)
|
|
314
|
+
const ttl = cached?.ok === true ? TTL_OK : TTL_FAIL
|
|
315
|
+
if (cached !== undefined && cached.promise === null && now - cached.at < ttl) return cached.data
|
|
316
|
+
if (cached?.promise !== undefined && cached.promise !== null) return cached.promise
|
|
317
|
+
const promise = readSource(ctx, prefs, source)
|
|
318
|
+
.then((data) => {
|
|
319
|
+
cache.set(source.id, { at: Date.now(), ok: data !== null, data, promise: null })
|
|
320
|
+
return data
|
|
321
|
+
})
|
|
322
|
+
.catch((error) => {
|
|
323
|
+
cache.set(source.id, { at: Date.now(), ok: false, data: null, promise: null })
|
|
324
|
+
throw error
|
|
325
|
+
})
|
|
326
|
+
cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise })
|
|
327
|
+
return promise
|
|
328
|
+
}
|
|
329
|
+
|
|
226
330
|
function visibleEntry(entry, prefs) {
|
|
227
331
|
return entry !== null && prefs?.billingModes?.[entry.id] !== 'hide'
|
|
228
332
|
}
|
|
@@ -254,20 +358,24 @@ export function toSnapshot(entry) {
|
|
|
254
358
|
}
|
|
255
359
|
}
|
|
256
360
|
|
|
257
|
-
const ADAPTER_IDS = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen']
|
|
258
|
-
|
|
259
361
|
/**
|
|
260
362
|
* Query configured providers; each failure is isolated. Balance/credits are always requested
|
|
261
363
|
* (P2 shows them regardless of the P1-only toggle, #31). 空档原因挂在返回数组的 `misses` 上:
|
|
262
364
|
* `<id>:none` 未配置、`:error` 请求失败、`:hidden` 被计费模式隐藏。
|
|
365
|
+
* 缓存按源保存在调用方传入的 Map 中:成功 60s、失败 10s,并发复用 promise。
|
|
263
366
|
*/
|
|
264
|
-
export async function readProviders(ctx, prefs) {
|
|
265
|
-
const results = await Promise.allSettled(
|
|
367
|
+
export async function readProviders(ctx, prefs, cache = new Map()) {
|
|
368
|
+
const results = await Promise.allSettled(PROVIDER_SOURCES.map((source) => readCachedSource(ctx, prefs, source, cache)))
|
|
266
369
|
const out = []
|
|
267
370
|
const misses = []
|
|
371
|
+
const failures = []
|
|
268
372
|
results.forEach((result, index) => {
|
|
269
|
-
const id =
|
|
270
|
-
if (result.status !== 'fulfilled') {
|
|
373
|
+
const id = PROVIDER_SOURCES[index].id
|
|
374
|
+
if (result.status !== 'fulfilled') {
|
|
375
|
+
misses.push(`${id}:error`)
|
|
376
|
+
failures.push({ id, error: errorDetail(result.reason) })
|
|
377
|
+
return
|
|
378
|
+
}
|
|
271
379
|
if (result.value === null) { misses.push(`${id}:none`); return }
|
|
272
380
|
if (visibleEntry(result.value, prefs) !== true) { misses.push(`${id}:hidden`); return }
|
|
273
381
|
const value = result.value
|
|
@@ -275,22 +383,34 @@ export async function readProviders(ctx, prefs) {
|
|
|
275
383
|
out.push(toSnapshot(value))
|
|
276
384
|
})
|
|
277
385
|
out.misses = misses
|
|
386
|
+
out.failures = failures
|
|
278
387
|
return out
|
|
279
388
|
}
|
|
280
389
|
|
|
281
390
|
/**
|
|
282
|
-
* P3「重新检测」专用:只重查订阅 provider
|
|
283
|
-
*
|
|
391
|
+
* P3「重新检测」专用:只重查订阅 provider 的配额,绕过缓存。
|
|
392
|
+
* 仅返回 subscription 条目;无 Key 的 provider 不返回(由调用方从缓存移除)。
|
|
284
393
|
*/
|
|
285
394
|
export async function readSubscriptions(ctx, prefs) {
|
|
286
|
-
const
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const kimiEntry = kimiQuota.state === 'ok' ? kimiQuota.entry : kimiQuota.state === 'fallback' ? { id: 'moonshot', kind: 'api', currency: 'CNY' } : null
|
|
395
|
+
const sources = PROVIDER_SOURCES.filter((source) => source.kind === 'subscription')
|
|
396
|
+
const results = await Promise.allSettled(sources.map((source) => (
|
|
397
|
+
source.legacy === 'kimi' ? readKimiSubscription(ctx, prefs) : readSource(ctx, prefs, source)
|
|
398
|
+
)))
|
|
291
399
|
const out = []
|
|
292
|
-
|
|
293
|
-
|
|
400
|
+
const failures = []
|
|
401
|
+
results.forEach((result, index) => {
|
|
402
|
+
if (result.status !== 'fulfilled') {
|
|
403
|
+
failures.push({ id: sources[index].id, error: errorDetail(result.reason) })
|
|
404
|
+
return
|
|
405
|
+
}
|
|
406
|
+
if (result.value === null) return
|
|
407
|
+
// 旧源(GLM / Kimi)配额失败时可能回落 API 条目,保留旧行为;新源只保留订阅条目。
|
|
408
|
+
const legacy = sources[index].legacy !== undefined
|
|
409
|
+
if (result.value.kind !== 'subscription' && legacy !== true) return
|
|
410
|
+
if (visibleEntry(result.value, prefs) !== true) return
|
|
411
|
+
out.push(toSnapshot(result.value))
|
|
412
|
+
})
|
|
413
|
+
out.failures = failures
|
|
294
414
|
return out
|
|
295
415
|
}
|
|
296
416
|
|
|
@@ -329,8 +449,40 @@ export function logAdapterEvents(log, providers) {
|
|
|
329
449
|
}
|
|
330
450
|
if (item.id === 'qwen') {
|
|
331
451
|
info('adapter.qwen', item.currency === 'USD' ? 'currency.usd' : 'detected', {})
|
|
452
|
+
continue
|
|
453
|
+
}
|
|
454
|
+
if (item.id === 'opencode-go' || item.id === 'command-code') {
|
|
455
|
+
const module = item.id === 'opencode-go' ? 'adapter.opencode' : 'adapter.commandcode'
|
|
456
|
+
const windows = (item.windows ?? []).length
|
|
457
|
+
if (windows > 0) info(module, 'quota.ok', { windows })
|
|
458
|
+
else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
|
|
459
|
+
else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
|
|
460
|
+
if (item.balance?.status === 'ok') info(module, 'credits.ok', { amount: item.balance.amount })
|
|
332
461
|
}
|
|
333
462
|
}
|
|
334
463
|
}
|
|
335
464
|
|
|
465
|
+
const FAILURE_MODULES = {
|
|
466
|
+
'deepseek-official': 'adapter.deepseek',
|
|
467
|
+
zhipu: 'adapter.glm',
|
|
468
|
+
moonshot: 'adapter.kimi',
|
|
469
|
+
openrouter: 'adapter.openrouter',
|
|
470
|
+
qwen: 'adapter.qwen',
|
|
471
|
+
'opencode-go': 'adapter.opencode',
|
|
472
|
+
'command-code': 'adapter.commandcode',
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** Promise.allSettled 的拒绝项没有 entry,单独补 adapter.<id> 失败日志。 */
|
|
476
|
+
export function logAdapterFailures(log, failures = []) {
|
|
477
|
+
for (const item of failures) {
|
|
478
|
+
const module = FAILURE_MODULES[item.id] ?? `adapter.${item.id}`
|
|
479
|
+
const error = item.error ?? { kind: 'network' }
|
|
480
|
+
log.warn(module, 'detect.fail', {
|
|
481
|
+
errorKind: error.kind,
|
|
482
|
+
...(error.status === undefined ? {} : { httpStatus: error.status }),
|
|
483
|
+
...(error.upstream === true ? { upstream: true } : {}),
|
|
484
|
+
})
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
336
488
|
export { KIMI_USAGES, GLM_QUOTA, KIMI_BALANCE, OPENROUTER_CREDITS }
|
package/src/diagnostics.js
CHANGED
|
@@ -77,6 +77,7 @@ export function createLogger({ dir, level = 'info', version = '0.2.0', dshVersio
|
|
|
77
77
|
ts: new Date().toISOString(),
|
|
78
78
|
level: levelName,
|
|
79
79
|
module,
|
|
80
|
+
prefix: `[TD:${module}]`,
|
|
80
81
|
event,
|
|
81
82
|
...Object.fromEntries(Object.entries(fields).map(([key, value]) => [key, typeof value === 'string' ? redact(value) : value])),
|
|
82
83
|
}
|
package/src/providers.js
CHANGED
|
@@ -20,10 +20,14 @@ const ALIASES = {
|
|
|
20
20
|
aliyun: 'qwen',
|
|
21
21
|
tongyi: 'qwen',
|
|
22
22
|
openrouter: 'openrouter',
|
|
23
|
+
opencode: 'opencode-go',
|
|
24
|
+
'opencode-go': 'opencode-go',
|
|
25
|
+
commandcode: 'command-code',
|
|
26
|
+
'command-code': 'command-code',
|
|
23
27
|
}
|
|
24
28
|
|
|
25
29
|
/** Display order is also the P3 pricing-link order. */
|
|
26
|
-
export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen']
|
|
30
|
+
export const PROVIDER_ORDER = ['deepseek-official', 'zhipu', 'moonshot', 'openrouter', 'qwen', 'opencode-go', 'command-code']
|
|
27
31
|
|
|
28
32
|
const PROVIDERS = {
|
|
29
33
|
'deepseek-official': {
|
|
@@ -92,6 +96,26 @@ const PROVIDERS = {
|
|
|
92
96
|
},
|
|
93
97
|
pricingUrl: 'https://help.aliyun.com/zh/model-studio/billing-for-alibaba-cloud-model-studio',
|
|
94
98
|
},
|
|
99
|
+
'opencode-go': {
|
|
100
|
+
id: 'opencode-go',
|
|
101
|
+
label: 'OpenCode Go',
|
|
102
|
+
currency: 'USD',
|
|
103
|
+
subscription: true,
|
|
104
|
+
defaultModel: '-',
|
|
105
|
+
prefixes: [/^opencode/],
|
|
106
|
+
modelLabels: {},
|
|
107
|
+
pricingUrl: 'https://opencode.ai/',
|
|
108
|
+
},
|
|
109
|
+
'command-code': {
|
|
110
|
+
id: 'command-code',
|
|
111
|
+
label: 'Command Code',
|
|
112
|
+
currency: 'CNY',
|
|
113
|
+
subscription: true,
|
|
114
|
+
defaultModel: '-',
|
|
115
|
+
prefixes: [],
|
|
116
|
+
modelLabels: {},
|
|
117
|
+
pricingUrl: 'https://commandcode.ai/',
|
|
118
|
+
},
|
|
95
119
|
}
|
|
96
120
|
|
|
97
121
|
export function normalizeProvider(raw) {
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Declarative quota/balance sources. Endpoints and credential refs only;
|
|
3
|
+
* request execution lives in adapters.js so this file stays pure data + parsing.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const TIMEOUT = 6000
|
|
7
|
+
|
|
8
|
+
export const OPENCODE_USAGE = 'https://opencode.ai/zen/go/v1/usage'
|
|
9
|
+
export const OPENCODE_USAGE_FALLBACK = 'https://opencode.ai/api/v1/usage'
|
|
10
|
+
export const COMMAND_CODE_CREDITS = 'https://api.commandcode.ai/alpha/billing/credits'
|
|
11
|
+
|
|
12
|
+
function clampPercent(value) {
|
|
13
|
+
const n = Number(value)
|
|
14
|
+
if (!Number.isFinite(n)) return null
|
|
15
|
+
return Math.max(0, Math.min(100, n))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function pickNumber(...values) {
|
|
19
|
+
for (const value of values) {
|
|
20
|
+
const n = Number(value)
|
|
21
|
+
if (Number.isFinite(n)) return n
|
|
22
|
+
}
|
|
23
|
+
return null
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 容错解析单个窗口:usedPercent / used_ratio / percentage / used+limit。 */
|
|
27
|
+
export function parseWindow(raw, key) {
|
|
28
|
+
if (raw === null || raw === undefined || typeof raw !== 'object') return null
|
|
29
|
+
const direct = pickNumber(raw.usedPercent, raw.used_percent, raw.percentage, raw.percent)
|
|
30
|
+
let percent = direct
|
|
31
|
+
if (percent === null && raw.used_ratio !== undefined) percent = Number(raw.used_ratio) * 100
|
|
32
|
+
if (percent === null) {
|
|
33
|
+
const used = pickNumber(raw.used, raw.current, raw.consumed)
|
|
34
|
+
const limit = pickNumber(raw.limit, raw.total, raw.max)
|
|
35
|
+
if (used !== null && limit !== null && limit > 0) percent = (used / limit) * 100
|
|
36
|
+
}
|
|
37
|
+
if (percent === null) return null
|
|
38
|
+
const resetAt = pickNumber(raw.resetAt, raw.reset_at, raw.resetTime, raw.reset_time, raw.nextResetTime, raw.next_reset_time)
|
|
39
|
+
const usedPercent = clampPercent(percent)
|
|
40
|
+
return { key, usedPercent: usedPercent === null ? null : Math.round(usedPercent * 100) / 100, resetAt: resetAt ?? undefined, source: 'official' }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function collectFromMap(source, map) {
|
|
44
|
+
const windows = []
|
|
45
|
+
for (const [key, names] of Object.entries(map)) {
|
|
46
|
+
for (const name of names) {
|
|
47
|
+
const parsed = parseWindow(source?.[name], key)
|
|
48
|
+
if (parsed !== null) { windows.push(parsed); break }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return windows
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* OpenCode Go:兼容 `usage` / `data` 下的 fiveHour / weekly / monthly,
|
|
56
|
+
* 以及数组形式的 windows / limits。无法识别的窗口不补占位。
|
|
57
|
+
*/
|
|
58
|
+
export function parseOpenCodeUsage(body) {
|
|
59
|
+
const data = body?.data ?? body
|
|
60
|
+
const usage = data?.usage ?? data
|
|
61
|
+
const windows = collectFromMap(usage, {
|
|
62
|
+
'5h': ['fiveHour', 'five_hour', 'fiveHourWindow', '5h'],
|
|
63
|
+
week: ['weekly', 'week', 'weekWindow'],
|
|
64
|
+
month: ['monthly', 'month', 'monthWindow'],
|
|
65
|
+
})
|
|
66
|
+
const rows = Array.isArray(usage?.windows) ? usage.windows : Array.isArray(usage?.limits) ? usage.limits : []
|
|
67
|
+
for (const row of rows) {
|
|
68
|
+
const name = String(row?.key ?? row?.type ?? row?.name ?? '').toLowerCase()
|
|
69
|
+
const key = name.includes('5') || name.includes('five') ? '5h'
|
|
70
|
+
: name.includes('week') ? 'week'
|
|
71
|
+
: name.includes('month') ? 'month' : null
|
|
72
|
+
if (key === null || windows.some((item) => item.key === key)) continue
|
|
73
|
+
const parsed = parseWindow(row, key)
|
|
74
|
+
if (parsed !== null) windows.push(parsed)
|
|
75
|
+
}
|
|
76
|
+
return windows
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Command Code:credits(数字或对象)+ windowLimits.fiveHour / weekly。 */
|
|
80
|
+
export function parseCommandCodeCredits(body) {
|
|
81
|
+
const data = body?.data ?? body
|
|
82
|
+
const rawCredits = data?.credits ?? data?.credit ?? data?.balance
|
|
83
|
+
const amount = pickNumber(
|
|
84
|
+
typeof rawCredits === 'object' && rawCredits !== null ? rawCredits.amount : rawCredits,
|
|
85
|
+
typeof rawCredits === 'object' && rawCredits !== null ? rawCredits.balance : undefined,
|
|
86
|
+
typeof rawCredits === 'object' && rawCredits !== null ? rawCredits.value : undefined,
|
|
87
|
+
)
|
|
88
|
+
const limits = data?.windowLimits ?? data?.window_limits ?? data?.limits ?? data
|
|
89
|
+
const windows = []
|
|
90
|
+
const five = parseWindow(limits?.fiveHour ?? limits?.five_hour, '5h')
|
|
91
|
+
const week = parseWindow(limits?.weekly ?? limits?.week, 'week')
|
|
92
|
+
if (five !== null) windows.push(five)
|
|
93
|
+
if (week !== null) windows.push(week)
|
|
94
|
+
const balance = amount === null
|
|
95
|
+
? null
|
|
96
|
+
: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() }
|
|
97
|
+
return { windows, balance }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export const PROVIDER_SOURCES = [
|
|
101
|
+
{ id: 'deepseek-official', kind: 'api', currency: 'CNY', legacy: 'deepseek' },
|
|
102
|
+
{ id: 'zhipu', kind: 'subscription', currency: 'CNY', legacy: 'glm' },
|
|
103
|
+
{ id: 'moonshot', kind: 'subscription', currency: 'CNY', legacy: 'kimi' },
|
|
104
|
+
{ id: 'openrouter', kind: 'api', currency: 'USD', legacy: 'openrouter' },
|
|
105
|
+
{ id: 'qwen', kind: 'api', currency: 'CNY', legacy: 'qwen' },
|
|
106
|
+
{
|
|
107
|
+
id: 'opencode-go',
|
|
108
|
+
kind: 'subscription',
|
|
109
|
+
currency: 'USD',
|
|
110
|
+
credential: { type: 'bearer', refs: ['OPENCODE_GO_API_KEY'] },
|
|
111
|
+
quota: { url: OPENCODE_USAGE, fallbackUrl: OPENCODE_USAGE_FALLBACK, parse: parseOpenCodeUsage },
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
id: 'command-code',
|
|
115
|
+
kind: 'subscription',
|
|
116
|
+
currency: 'CNY',
|
|
117
|
+
credential: { type: 'bearer', refs: ['COMMAND_CODE_API_KEY'] },
|
|
118
|
+
preflight: { refs: ['COMMAND_CODE_ORG_ID'], param: 'orgId' },
|
|
119
|
+
quota: { url: COMMAND_CODE_CREDITS, parse: parseCommandCodeCredits },
|
|
120
|
+
},
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
export { TIMEOUT }
|