dsh-notify-tray 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/quota.js CHANGED
@@ -1,290 +1,290 @@
1
- /**
2
- * Plan quota / balance fetchers for providers that expose one to an API key.
3
- *
4
- * Each `kind` names a parser that turns the provider's JSON into one normalized
5
- * reading:
6
- * { balance?, currency?, remaining?, total?, used?, unit?, percent?, resetAt?, lines: [] }
7
- * `lines` is the human summary the tray menu and the settings page print, so
8
- * the parsers own the wording and the callers stay provider-agnostic.
9
- * Parsers are pure (fixture-testable); `fetchQuota` wires them to `fetch`.
10
- */
11
-
12
- /** Request timeout for one quota poll. */
13
- const TIMEOUT_MS = 12_000
14
-
15
- const num = v => {
16
- const n = typeof v === 'string' ? Number(v) : v
17
- return typeof n === 'number' && Number.isFinite(n) ? n : undefined
18
- }
19
-
20
- const pct = (used, total) => (total > 0 ? Math.round((used / total) * 100) : undefined)
21
-
22
- const when = value => {
23
- if (value === undefined || value === null || value === '') return undefined
24
- const ms = typeof value === 'number' ? (value < 1e12 ? value * 1000 : value) : Date.parse(value)
25
- return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined
26
- }
27
-
28
- export function moneyText(value, currency) {
29
- if (typeof value !== 'number') return undefined
30
- const symbol = currency === 'CNY' ? '¥' : currency === 'USD' ? '$' : `${currency ?? ''} `
31
- return `${symbol}${value < 10 ? value.toFixed(2) : value.toFixed(1)}`
32
- }
33
-
34
- export function clockText(iso) {
35
- if (!iso) return undefined
36
- const d = new Date(iso)
37
- if (Number.isNaN(d.getTime())) return undefined
38
- const pad = n => String(n).padStart(2, '0')
39
- const today = new Date()
40
- const sameDay = d.toDateString() === today.toDateString()
41
- return `${sameDay ? '' : `${d.getMonth() + 1}/${d.getDate()} `}${pad(d.getHours())}:${pad(d.getMinutes())}`
42
- }
43
-
44
- /** `GET https://api.deepseek.com/user/balance` */
45
- function parseDeepseekBalance(json) {
46
- const infos = Array.isArray(json?.balance_infos) ? json.balance_infos : []
47
- const first = infos.find(i => i?.currency === 'CNY') ?? infos[0]
48
- if (!first) throw new Error('响应里没有 balance_infos')
49
- const balance = num(first.total_balance)
50
- return {
51
- balance,
52
- currency: first.currency,
53
- lines: [`账户余额 ${moneyText(balance, first.currency)}${json?.is_available === false ? '(不可用)' : ''}`],
54
- }
55
- }
56
-
57
- /** `GET https://api.moonshot.cn/v1/users/me/balance` */
58
- function parseMoonshotBalance(json) {
59
- const data = json?.data
60
- const balance = num(data?.available_balance)
61
- if (balance === undefined) throw new Error(json?.error?.message ?? '响应里没有 available_balance')
62
- const lines = [`可用余额 ${moneyText(balance, 'CNY')}`]
63
- const voucher = num(data?.voucher_balance)
64
- if (voucher) lines.push(`其中代金券 ${moneyText(voucher, 'CNY')}`)
65
- return { balance, currency: 'CNY', lines }
66
- }
67
-
68
- /**
69
- * Kimi Code plan usage, `GET https://api.kimi.com/coding/v1/usages` (needs the Kimi Code OAuth token):
70
- * `{ usage: { limit, remaining, resetTime }, limits: [{ window: { duration, timeUnit }, detail: { limit, remaining, resetTime } }], user: { membership } }`.
71
- * Numbers arrive as strings; older spellings (`used`, `reset_time`) are folded too.
72
- */
73
- function parseKimiUsage(json) {
74
- const buckets = []
75
- const read = (obj, label) => {
76
- if (!obj || typeof obj !== 'object') return
77
- const limit = num(obj.limit ?? obj.total ?? obj.quota)
78
- const used = num(obj.used ?? obj.usage)
79
- const remaining = num(obj.remaining ?? obj.remain ?? obj.left) ?? (limit !== undefined && used !== undefined ? limit - used : undefined)
80
- const reset = when(obj.resetTime ?? obj.reset_time ?? obj.resetAt ?? obj.reset_at ?? obj.nextResetTime)
81
- if (limit !== undefined || remaining !== undefined) buckets.push({ label, limit, used: used ?? (limit !== undefined && remaining !== undefined ? limit - remaining : undefined), remaining, reset })
82
- }
83
- read(json?.usage, '总额度')
84
- for (const entry of Array.isArray(json?.limits) ? json.limits : []) {
85
- const minutes = entry?.window?.timeUnit === 'TIME_UNIT_HOUR' ? num(entry.window.duration) * 60
86
- : entry?.window?.timeUnit === 'TIME_UNIT_DAY' ? num(entry.window.duration) * 1440
87
- : num(entry?.window?.duration)
88
- const label = minutes === undefined ? '窗口' : minutes % 1440 === 0 ? `${minutes / 1440} 天窗口` : minutes % 60 === 0 ? `${minutes / 60} 小时窗口` : `${minutes} 分钟窗口`
89
- read(entry?.detail ?? entry, label)
90
- }
91
- for (const [key, value] of Object.entries(json ?? {})) {
92
- if (key === 'usage' || key === 'user' || key === 'limits') continue
93
- if (value && typeof value === 'object' && !Array.isArray(value)) read(value, key)
94
- }
95
- if (!buckets.length) throw new Error(json?.error?.message ?? json?.message ?? '响应里没有额度字段')
96
- const main = buckets[0]
97
- const lines = buckets.map(b => {
98
- const parts = [`${b.label} 剩余 ${b.remaining ?? '?'}${b.limit !== undefined ? ` / ${b.limit}` : ''}`]
99
- if (b.reset) parts.push(`重置 ${clockText(b.reset)}`)
100
- return parts.join(' · ')
101
- })
102
- const level = json?.user?.membership?.level ?? json?.user?.membership
103
- if (typeof level === 'string') lines.push(`会员 ${level.replace(/^LEVEL_/u, '').toLowerCase()}`)
104
- return { remaining: main.remaining, total: main.limit, used: main.used, percent: main.limit && main.remaining !== undefined ? Math.round((main.remaining / main.limit) * 100) : undefined, resetAt: main.reset, lines }
105
- }
106
-
107
- /**
108
- * Z.ai / 智谱 GLM Coding Plan: `GET /api/monitor/usage/quota/limit`
109
- * `{ code, data: { limits: [{ type: 'CREDIT_LIMIT'|'TOKENS_LIMIT'|'TIME_LIMIT', usage, currentValue, remaining, percentage, nextResetTime, unit, number }] } }`
110
- * The first credit/token limit is the 5-hour window, the second the weekly one; TIME_LIMIT rows are MCP usage.
111
- */
112
- function parseZaiQuota(json) {
113
- const limits = Array.isArray(json?.data?.limits) ? json.data.limits : []
114
- if (!limits.length) throw new Error(json?.msg ?? json?.message ?? '响应里没有 limits')
115
- const lines = []
116
- let main
117
- let windows = 0
118
- for (const limit of limits) {
119
- const total = num(limit.usage ?? limit.total)
120
- const used = num(limit.currentValue ?? limit.used)
121
- const remaining = num(limit.remaining) ?? (total !== undefined && used !== undefined ? total - used : undefined)
122
- const percent = num(limit.percentage) ?? (total && used !== undefined ? pct(used, total) : undefined)
123
- if (percent === undefined && remaining === undefined) continue
124
- const reset = when(limit.nextResetTime ?? limit.resetTime)
125
- const isWindow = limit.type !== 'TIME_LIMIT'
126
- const label = isWindow ? (windows === 0 ? '5 小时额度' : windows === 1 ? '本周额度' : `额度 ${windows + 1}`) : 'MCP 用量'
127
- if (isWindow) windows += 1
128
- const parts = [`${label} 已用 ${percent ?? '?'}%`]
129
- if (remaining !== undefined) parts.push(`剩余 ${compact(remaining)}${total !== undefined ? ` / ${compact(total)}` : ''}`)
130
- if (reset) parts.push(`重置 ${clockText(reset)}`)
131
- lines.push(parts.join(' · '))
132
- if (isWindow && (!main || windows === 1)) main = { remaining, total, used, percent: percent !== undefined ? 100 - percent : undefined, resetAt: reset }
133
- }
134
- if (!lines.length) throw new Error('响应里没有可用的额度数字')
135
- return { ...main, lines }
136
- }
137
-
138
- /**
139
- * MiniMax Coding Plan: `GET /v1/coding_plan/remains`
140
- * `{ model_remains: [{ model_name, current_interval_total_count, current_interval_usage_count, remains_count, start_time, end_time }] }`
141
- */
142
- function parseMinimaxRemains(json) {
143
- const rows = Array.isArray(json?.model_remains) ? json.model_remains : []
144
- if (!rows.length) throw new Error(json?.base_resp?.status_msg ?? '响应里没有 model_remains')
145
- const lines = []
146
- let main
147
- for (const row of rows) {
148
- const total = num(row.current_interval_total_count)
149
- const used = num(row.current_interval_usage_count)
150
- const remaining = num(row.remains_count) ?? (total !== undefined && used !== undefined ? total - used : undefined)
151
- const reset = when(row.end_time)
152
- const parts = [`${row.model_name ?? '额度'} 剩余 ${remaining ?? '?'}${total !== undefined ? ` / ${total}` : ''}`]
153
- if (reset) parts.push(`重置 ${clockText(reset)}`)
154
- lines.push(parts.join(' · '))
155
- if (!main) main = { remaining, total, used, percent: total && remaining !== undefined ? Math.round((remaining / total) * 100) : undefined, resetAt: reset }
156
- }
157
- return { ...main, lines }
158
- }
159
-
160
- /** xAI: `GET https://api.x.ai/v1/api-key` only tells us the key is alive; no balance is exposed. */
161
- function parseXaiKey(json) {
162
- if (!json?.api_key_id && !json?.name) throw new Error(json?.error ?? '响应里没有 api_key_id')
163
- return { lines: [`API Key「${json.name ?? json.api_key_id}」有效${json.api_key_disabled ? '(已禁用)' : ''};xAI 不提供余额接口`] }
164
- }
165
-
166
- /** OpenAI-compatible `/dashboard/billing/credit_grants`-style shapes some gateways still serve. */
167
- function parseCreditGrants(json) {
168
- const total = num(json?.total_granted)
169
- const used = num(json?.total_used)
170
- const remaining = num(json?.total_available) ?? (total !== undefined && used !== undefined ? total - used : undefined)
171
- if (remaining === undefined) throw new Error('响应里没有 total_available')
172
- return { balance: remaining, currency: 'USD', total, used, lines: [`剩余额度 ${moneyText(remaining, 'USD')}${total !== undefined ? ` / ${moneyText(total, 'USD')}` : ''}`] }
173
- }
174
-
175
- /** Anything else: best-effort scan for balance / remaining-looking numbers. */
176
- function parseGeneric(json) {
177
- const found = []
178
- const walk = (obj, depth) => {
179
- if (!obj || typeof obj !== 'object' || depth > 4) return
180
- for (const [key, value] of Object.entries(obj)) {
181
- if (typeof value === 'object') walk(value, depth + 1)
182
- else if (/balance|remain|quota|credit|left/iu.test(key) && num(value) !== undefined) found.push([key, num(value)])
183
- }
184
- }
185
- walk(json, 0)
186
- if (!found.length) throw new Error('看不懂这个响应,请用自定义字段手填')
187
- return { lines: found.slice(0, 4).map(([k, v]) => `${k} ${v}`) }
188
- }
189
-
190
- export const PARSERS = {
191
- 'deepseek-balance': parseDeepseekBalance,
192
- 'moonshot-balance': parseMoonshotBalance,
193
- 'kimi-usage': parseKimiUsage,
194
- 'zai-quota': parseZaiQuota,
195
- 'minimax-remains': parseMinimaxRemains,
196
- 'xai-key': parseXaiKey,
197
- 'credit-grants': parseCreditGrants,
198
- generic: parseGeneric,
199
- }
200
-
201
- function compact(n) {
202
- if (n >= 1e8) return `${(n / 1e8).toFixed(1)}亿`
203
- if (n >= 1e4) return `${(n / 1e4).toFixed(1)}万`
204
- return String(Math.round(n))
205
- }
206
-
207
- /** Headers for one auth style. */
208
- export function authHeaders(auth, key) {
209
- if (auth === 'x-api-key') return { 'x-api-key': key, 'anthropic-version': '2023-06-01' }
210
- if (auth === 'x-goog-api-key') return { 'x-goog-api-key': key }
211
- return { authorization: `Bearer ${key}` }
212
- }
213
-
214
- /**
215
- * Fetch and parse one quota reading.
216
- * @param {{ url: string, kind?: string, auth?: string, method?: string }} spec
217
- * @param {string} key - the API key.
218
- * @returns {Promise<{ ok: true, at: number, data: object } | { ok: false, at: number, error: string }>}
219
- */
220
- export async function fetchQuota(spec, key, { fetchImpl = globalThis.fetch, now = () => Date.now() } = {}) {
221
- const at = now()
222
- const parse = PARSERS[spec.kind ?? 'generic'] ?? parseGeneric
223
- const controller = typeof AbortController === 'function' ? new AbortController() : undefined
224
- const timer = controller ? setTimeout(() => controller.abort(), TIMEOUT_MS) : undefined
225
- timer?.unref?.()
226
- try {
227
- const res = await fetchImpl(spec.url, {
228
- method: spec.method ?? 'GET',
229
- headers: { accept: 'application/json', ...authHeaders(spec.auth, key), ...(spec.headers ?? {}) },
230
- signal: controller?.signal,
231
- })
232
- const text = await res.text()
233
- let json
234
- try { json = JSON.parse(text) } catch { json = undefined }
235
- if (!res.ok) {
236
- const detail = json?.error?.message ?? json?.message ?? json?.msg ?? text.slice(0, 120)
237
- throw Object.assign(new Error(`HTTP ${res.status}${detail ? `:${detail}` : ''}`), { status: res.status })
238
- }
239
- if (json === undefined) throw new Error('响应不是 JSON')
240
- return { ok: true, at, data: parse(json) }
241
- } catch (error) {
242
- const failed = { ok: false, at, error: error?.name === 'AbortError' ? '请求超时' : (error?.message ?? String(error)) }
243
- return error?.status ? { ...failed, status: error.status } : failed
244
- } finally {
245
- clearTimeout(timer)
246
- }
247
- }
248
-
249
- /** A plain-words reason for a failed reading, so the settings page can say what to fix. */
250
- export function failureHint(reading) {
251
- if (reading?.status === 401 || reading?.status === 403) return 'Key 不对、已过期,或没有查询额度的权限'
252
- if (reading?.status === 404) return '查询地址不对,检查「额度查询地址」'
253
- if (reading?.status === 429) return '查得太频繁,稍后会自动再试'
254
- if (reading?.error === '请求超时' || /fetch failed|ENOTFOUND|ECONN/u.test(reading?.error ?? '')) return '连不上查询接口,检查网络或代理'
255
- return undefined
256
- }
257
-
258
- /**
259
- * Run a quota fetch plan (after CodexBar's provider pipeline): strategies are
260
- * tried in order; each says whether it can run here (`available` resolves to
261
- * true, or to the reason it cannot), fetches, and whether its failure lets
262
- * the next one try (`fallback`, default: always). Every step is recorded in
263
- * `attempts`, so the settings page can say why nothing came back.
264
- *
265
- * @param {{ id: string, label: string, available: () => Promise<true | string> | true | string, fetch: () => Promise<object>, fallback?: (reading: object) => boolean }[]} strategies
266
- * @param {{ now?: () => number, noneError?: string }} [options] - `noneError`: the error when no strategy could run.
267
- * @returns {Promise<object>} the last reading (or a failure when nothing could run), plus `attempts`.
268
- */
269
- export async function runQuotaPlan(strategies, { now = () => Date.now(), noneError } = {}) {
270
- const attempts = []
271
- let last
272
- for (const strategy of strategies) {
273
- let available
274
- try { available = await strategy.available() } catch (error) { available = error?.message ?? String(error) }
275
- if (available !== true) {
276
- attempts.push({ id: strategy.id, label: strategy.label, outcome: 'skipped', detail: String(available || '不可用') })
277
- continue
278
- }
279
- const reading = await strategy.fetch()
280
- attempts.push(reading.ok
281
- ? { id: strategy.id, label: strategy.label, outcome: 'ok' }
282
- : { id: strategy.id, label: strategy.label, outcome: 'failed', detail: reading.error, hint: failureHint(reading) })
283
- last = reading
284
- if (reading.ok || (strategy.fallback && !strategy.fallback(reading))) break
285
- }
286
- if (last === undefined) {
287
- last = { ok: false, at: now(), error: noneError ?? attempts.map(a => `${a.label}:${a.detail}`).join(';') }
288
- }
289
- return { ...last, attempts }
290
- }
1
+ /**
2
+ * Plan quota / balance fetchers for providers that expose one to an API key.
3
+ *
4
+ * Each `kind` names a parser that turns the provider's JSON into one normalized
5
+ * reading:
6
+ * { balance?, currency?, remaining?, total?, used?, unit?, percent?, resetAt?, lines: [] }
7
+ * `lines` is the human summary the tray menu and the settings page print, so
8
+ * the parsers own the wording and the callers stay provider-agnostic.
9
+ * Parsers are pure (fixture-testable); `fetchQuota` wires them to `fetch`.
10
+ */
11
+
12
+ /** Request timeout for one quota poll. */
13
+ const TIMEOUT_MS = 12_000
14
+
15
+ const num = v => {
16
+ const n = typeof v === 'string' ? Number(v) : v
17
+ return typeof n === 'number' && Number.isFinite(n) ? n : undefined
18
+ }
19
+
20
+ const pct = (used, total) => (total > 0 ? Math.round((used / total) * 100) : undefined)
21
+
22
+ const when = value => {
23
+ if (value === undefined || value === null || value === '') return undefined
24
+ const ms = typeof value === 'number' ? (value < 1e12 ? value * 1000 : value) : Date.parse(value)
25
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined
26
+ }
27
+
28
+ export function moneyText(value, currency) {
29
+ if (typeof value !== 'number') return undefined
30
+ const symbol = currency === 'CNY' ? '¥' : currency === 'USD' ? '$' : `${currency ?? ''} `
31
+ return `${symbol}${value < 10 ? value.toFixed(2) : value.toFixed(1)}`
32
+ }
33
+
34
+ export function clockText(iso) {
35
+ if (!iso) return undefined
36
+ const d = new Date(iso)
37
+ if (Number.isNaN(d.getTime())) return undefined
38
+ const pad = n => String(n).padStart(2, '0')
39
+ const today = new Date()
40
+ const sameDay = d.toDateString() === today.toDateString()
41
+ return `${sameDay ? '' : `${d.getMonth() + 1}/${d.getDate()} `}${pad(d.getHours())}:${pad(d.getMinutes())}`
42
+ }
43
+
44
+ /** `GET https://api.deepseek.com/user/balance` */
45
+ function parseDeepseekBalance(json) {
46
+ const infos = Array.isArray(json?.balance_infos) ? json.balance_infos : []
47
+ const first = infos.find(i => i?.currency === 'CNY') ?? infos[0]
48
+ if (!first) throw new Error('响应里没有 balance_infos')
49
+ const balance = num(first.total_balance)
50
+ return {
51
+ balance,
52
+ currency: first.currency,
53
+ lines: [`账户余额 ${moneyText(balance, first.currency)}${json?.is_available === false ? '(不可用)' : ''}`],
54
+ }
55
+ }
56
+
57
+ /** `GET https://api.moonshot.cn/v1/users/me/balance` */
58
+ function parseMoonshotBalance(json) {
59
+ const data = json?.data
60
+ const balance = num(data?.available_balance)
61
+ if (balance === undefined) throw new Error(json?.error?.message ?? '响应里没有 available_balance')
62
+ const lines = [`可用余额 ${moneyText(balance, 'CNY')}`]
63
+ const voucher = num(data?.voucher_balance)
64
+ if (voucher) lines.push(`其中代金券 ${moneyText(voucher, 'CNY')}`)
65
+ return { balance, currency: 'CNY', lines }
66
+ }
67
+
68
+ /**
69
+ * Kimi Code plan usage, `GET https://api.kimi.com/coding/v1/usages` (needs the Kimi Code OAuth token):
70
+ * `{ usage: { limit, remaining, resetTime }, limits: [{ window: { duration, timeUnit }, detail: { limit, remaining, resetTime } }], user: { membership } }`.
71
+ * Numbers arrive as strings; older spellings (`used`, `reset_time`) are folded too.
72
+ */
73
+ function parseKimiUsage(json) {
74
+ const buckets = []
75
+ const read = (obj, label) => {
76
+ if (!obj || typeof obj !== 'object') return
77
+ const limit = num(obj.limit ?? obj.total ?? obj.quota)
78
+ const used = num(obj.used ?? obj.usage)
79
+ const remaining = num(obj.remaining ?? obj.remain ?? obj.left) ?? (limit !== undefined && used !== undefined ? limit - used : undefined)
80
+ const reset = when(obj.resetTime ?? obj.reset_time ?? obj.resetAt ?? obj.reset_at ?? obj.nextResetTime)
81
+ if (limit !== undefined || remaining !== undefined) buckets.push({ label, limit, used: used ?? (limit !== undefined && remaining !== undefined ? limit - remaining : undefined), remaining, reset })
82
+ }
83
+ read(json?.usage, '总额度')
84
+ for (const entry of Array.isArray(json?.limits) ? json.limits : []) {
85
+ const minutes = entry?.window?.timeUnit === 'TIME_UNIT_HOUR' ? num(entry.window.duration) * 60
86
+ : entry?.window?.timeUnit === 'TIME_UNIT_DAY' ? num(entry.window.duration) * 1440
87
+ : num(entry?.window?.duration)
88
+ const label = minutes === undefined ? '窗口' : minutes % 1440 === 0 ? `${minutes / 1440} 天窗口` : minutes % 60 === 0 ? `${minutes / 60} 小时窗口` : `${minutes} 分钟窗口`
89
+ read(entry?.detail ?? entry, label)
90
+ }
91
+ for (const [key, value] of Object.entries(json ?? {})) {
92
+ if (key === 'usage' || key === 'user' || key === 'limits') continue
93
+ if (value && typeof value === 'object' && !Array.isArray(value)) read(value, key)
94
+ }
95
+ if (!buckets.length) throw new Error(json?.error?.message ?? json?.message ?? '响应里没有额度字段')
96
+ const main = buckets[0]
97
+ const lines = buckets.map(b => {
98
+ const parts = [`${b.label} 剩余 ${b.remaining ?? '?'}${b.limit !== undefined ? ` / ${b.limit}` : ''}`]
99
+ if (b.reset) parts.push(`重置 ${clockText(b.reset)}`)
100
+ return parts.join(' · ')
101
+ })
102
+ const level = json?.user?.membership?.level ?? json?.user?.membership
103
+ if (typeof level === 'string') lines.push(`会员 ${level.replace(/^LEVEL_/u, '').toLowerCase()}`)
104
+ return { remaining: main.remaining, total: main.limit, used: main.used, percent: main.limit && main.remaining !== undefined ? Math.round((main.remaining / main.limit) * 100) : undefined, resetAt: main.reset, lines }
105
+ }
106
+
107
+ /**
108
+ * Z.ai / 智谱 GLM Coding Plan: `GET /api/monitor/usage/quota/limit`
109
+ * `{ code, data: { limits: [{ type: 'CREDIT_LIMIT'|'TOKENS_LIMIT'|'TIME_LIMIT', usage, currentValue, remaining, percentage, nextResetTime, unit, number }] } }`
110
+ * The first credit/token limit is the 5-hour window, the second the weekly one; TIME_LIMIT rows are MCP usage.
111
+ */
112
+ function parseZaiQuota(json) {
113
+ const limits = Array.isArray(json?.data?.limits) ? json.data.limits : []
114
+ if (!limits.length) throw new Error(json?.msg ?? json?.message ?? '响应里没有 limits')
115
+ const lines = []
116
+ let main
117
+ let windows = 0
118
+ for (const limit of limits) {
119
+ const total = num(limit.usage ?? limit.total)
120
+ const used = num(limit.currentValue ?? limit.used)
121
+ const remaining = num(limit.remaining) ?? (total !== undefined && used !== undefined ? total - used : undefined)
122
+ const percent = num(limit.percentage) ?? (total && used !== undefined ? pct(used, total) : undefined)
123
+ if (percent === undefined && remaining === undefined) continue
124
+ const reset = when(limit.nextResetTime ?? limit.resetTime)
125
+ const isWindow = limit.type !== 'TIME_LIMIT'
126
+ const label = isWindow ? (windows === 0 ? '5 小时额度' : windows === 1 ? '本周额度' : `额度 ${windows + 1}`) : 'MCP 用量'
127
+ if (isWindow) windows += 1
128
+ const parts = [`${label} 已用 ${percent ?? '?'}%`]
129
+ if (remaining !== undefined) parts.push(`剩余 ${compact(remaining)}${total !== undefined ? ` / ${compact(total)}` : ''}`)
130
+ if (reset) parts.push(`重置 ${clockText(reset)}`)
131
+ lines.push(parts.join(' · '))
132
+ if (isWindow && (!main || windows === 1)) main = { remaining, total, used, percent: percent !== undefined ? 100 - percent : undefined, resetAt: reset }
133
+ }
134
+ if (!lines.length) throw new Error('响应里没有可用的额度数字')
135
+ return { ...main, lines }
136
+ }
137
+
138
+ /**
139
+ * MiniMax Coding Plan: `GET /v1/coding_plan/remains`
140
+ * `{ model_remains: [{ model_name, current_interval_total_count, current_interval_usage_count, remains_count, start_time, end_time }] }`
141
+ */
142
+ function parseMinimaxRemains(json) {
143
+ const rows = Array.isArray(json?.model_remains) ? json.model_remains : []
144
+ if (!rows.length) throw new Error(json?.base_resp?.status_msg ?? '响应里没有 model_remains')
145
+ const lines = []
146
+ let main
147
+ for (const row of rows) {
148
+ const total = num(row.current_interval_total_count)
149
+ const used = num(row.current_interval_usage_count)
150
+ const remaining = num(row.remains_count) ?? (total !== undefined && used !== undefined ? total - used : undefined)
151
+ const reset = when(row.end_time)
152
+ const parts = [`${row.model_name ?? '额度'} 剩余 ${remaining ?? '?'}${total !== undefined ? ` / ${total}` : ''}`]
153
+ if (reset) parts.push(`重置 ${clockText(reset)}`)
154
+ lines.push(parts.join(' · '))
155
+ if (!main) main = { remaining, total, used, percent: total && remaining !== undefined ? Math.round((remaining / total) * 100) : undefined, resetAt: reset }
156
+ }
157
+ return { ...main, lines }
158
+ }
159
+
160
+ /** xAI: `GET https://api.x.ai/v1/api-key` only tells us the key is alive; no balance is exposed. */
161
+ function parseXaiKey(json) {
162
+ if (!json?.api_key_id && !json?.name) throw new Error(json?.error ?? '响应里没有 api_key_id')
163
+ return { lines: [`API Key「${json.name ?? json.api_key_id}」有效${json.api_key_disabled ? '(已禁用)' : ''};xAI 不提供余额接口`] }
164
+ }
165
+
166
+ /** OpenAI-compatible `/dashboard/billing/credit_grants`-style shapes some gateways still serve. */
167
+ function parseCreditGrants(json) {
168
+ const total = num(json?.total_granted)
169
+ const used = num(json?.total_used)
170
+ const remaining = num(json?.total_available) ?? (total !== undefined && used !== undefined ? total - used : undefined)
171
+ if (remaining === undefined) throw new Error('响应里没有 total_available')
172
+ return { balance: remaining, currency: 'USD', total, used, lines: [`剩余额度 ${moneyText(remaining, 'USD')}${total !== undefined ? ` / ${moneyText(total, 'USD')}` : ''}`] }
173
+ }
174
+
175
+ /** Anything else: best-effort scan for balance / remaining-looking numbers. */
176
+ function parseGeneric(json) {
177
+ const found = []
178
+ const walk = (obj, depth) => {
179
+ if (!obj || typeof obj !== 'object' || depth > 4) return
180
+ for (const [key, value] of Object.entries(obj)) {
181
+ if (typeof value === 'object') walk(value, depth + 1)
182
+ else if (/balance|remain|quota|credit|left/iu.test(key) && num(value) !== undefined) found.push([key, num(value)])
183
+ }
184
+ }
185
+ walk(json, 0)
186
+ if (!found.length) throw new Error('看不懂这个响应,请用自定义字段手填')
187
+ return { lines: found.slice(0, 4).map(([k, v]) => `${k} ${v}`) }
188
+ }
189
+
190
+ export const PARSERS = {
191
+ 'deepseek-balance': parseDeepseekBalance,
192
+ 'moonshot-balance': parseMoonshotBalance,
193
+ 'kimi-usage': parseKimiUsage,
194
+ 'zai-quota': parseZaiQuota,
195
+ 'minimax-remains': parseMinimaxRemains,
196
+ 'xai-key': parseXaiKey,
197
+ 'credit-grants': parseCreditGrants,
198
+ generic: parseGeneric,
199
+ }
200
+
201
+ function compact(n) {
202
+ if (n >= 1e8) return `${(n / 1e8).toFixed(1)}亿`
203
+ if (n >= 1e4) return `${(n / 1e4).toFixed(1)}万`
204
+ return String(Math.round(n))
205
+ }
206
+
207
+ /** Headers for one auth style. */
208
+ export function authHeaders(auth, key) {
209
+ if (auth === 'x-api-key') return { 'x-api-key': key, 'anthropic-version': '2023-06-01' }
210
+ if (auth === 'x-goog-api-key') return { 'x-goog-api-key': key }
211
+ return { authorization: `Bearer ${key}` }
212
+ }
213
+
214
+ /**
215
+ * Fetch and parse one quota reading.
216
+ * @param {{ url: string, kind?: string, auth?: string, method?: string }} spec
217
+ * @param {string} key - the API key.
218
+ * @returns {Promise<{ ok: true, at: number, data: object } | { ok: false, at: number, error: string }>}
219
+ */
220
+ export async function fetchQuota(spec, key, { fetchImpl = globalThis.fetch, now = () => Date.now() } = {}) {
221
+ const at = now()
222
+ const parse = PARSERS[spec.kind ?? 'generic'] ?? parseGeneric
223
+ const controller = typeof AbortController === 'function' ? new AbortController() : undefined
224
+ const timer = controller ? setTimeout(() => controller.abort(), TIMEOUT_MS) : undefined
225
+ timer?.unref?.()
226
+ try {
227
+ const res = await fetchImpl(spec.url, {
228
+ method: spec.method ?? 'GET',
229
+ headers: { accept: 'application/json', ...authHeaders(spec.auth, key), ...(spec.headers ?? {}) },
230
+ signal: controller?.signal,
231
+ })
232
+ const text = await res.text()
233
+ let json
234
+ try { json = JSON.parse(text) } catch { json = undefined }
235
+ if (!res.ok) {
236
+ const detail = json?.error?.message ?? json?.message ?? json?.msg ?? text.slice(0, 120)
237
+ throw Object.assign(new Error(`HTTP ${res.status}${detail ? `:${detail}` : ''}`), { status: res.status })
238
+ }
239
+ if (json === undefined) throw new Error('响应不是 JSON')
240
+ return { ok: true, at, data: parse(json) }
241
+ } catch (error) {
242
+ const failed = { ok: false, at, error: error?.name === 'AbortError' ? '请求超时' : (error?.message ?? String(error)) }
243
+ return error?.status ? { ...failed, status: error.status } : failed
244
+ } finally {
245
+ clearTimeout(timer)
246
+ }
247
+ }
248
+
249
+ /** A plain-words reason for a failed reading, so the settings page can say what to fix. */
250
+ export function failureHint(reading) {
251
+ if (reading?.status === 401 || reading?.status === 403) return 'Key 不对、已过期,或没有查询额度的权限'
252
+ if (reading?.status === 404) return '查询地址不对,检查「额度查询地址」'
253
+ if (reading?.status === 429) return '查得太频繁,稍后会自动再试'
254
+ if (reading?.error === '请求超时' || /fetch failed|ENOTFOUND|ECONN/u.test(reading?.error ?? '')) return '连不上查询接口,检查网络或代理'
255
+ return undefined
256
+ }
257
+
258
+ /**
259
+ * Run a quota fetch plan (after CodexBar's provider pipeline): strategies are
260
+ * tried in order; each says whether it can run here (`available` resolves to
261
+ * true, or to the reason it cannot), fetches, and whether its failure lets
262
+ * the next one try (`fallback`, default: always). Every step is recorded in
263
+ * `attempts`, so the settings page can say why nothing came back.
264
+ *
265
+ * @param {{ id: string, label: string, available: () => Promise<true | string> | true | string, fetch: () => Promise<object>, fallback?: (reading: object) => boolean }[]} strategies
266
+ * @param {{ now?: () => number, noneError?: string }} [options] - `noneError`: the error when no strategy could run.
267
+ * @returns {Promise<object>} the last reading (or a failure when nothing could run), plus `attempts`.
268
+ */
269
+ export async function runQuotaPlan(strategies, { now = () => Date.now(), noneError } = {}) {
270
+ const attempts = []
271
+ let last
272
+ for (const strategy of strategies) {
273
+ let available
274
+ try { available = await strategy.available() } catch (error) { available = error?.message ?? String(error) }
275
+ if (available !== true) {
276
+ attempts.push({ id: strategy.id, label: strategy.label, outcome: 'skipped', detail: String(available || '不可用') })
277
+ continue
278
+ }
279
+ const reading = await strategy.fetch()
280
+ attempts.push(reading.ok
281
+ ? { id: strategy.id, label: strategy.label, outcome: 'ok' }
282
+ : { id: strategy.id, label: strategy.label, outcome: 'failed', detail: reading.error, hint: failureHint(reading) })
283
+ last = reading
284
+ if (reading.ok || (strategy.fallback && !strategy.fallback(reading))) break
285
+ }
286
+ if (last === undefined) {
287
+ last = { ok: false, at: now(), error: noneError ?? attempts.map(a => `${a.label}:${a.detail}`).join(';') }
288
+ }
289
+ return { ...last, attempts }
290
+ }