@angelyeye/dsh-cost-tracker 1.8.13 → 1.8.14

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/volcengine.js ADDED
@@ -0,0 +1,456 @@
1
+ // ============================================================
2
+ // DSH 花费统计插件 —— 火山方舟(Volcengine Ark)Coding Plan 配额查询
3
+ //
4
+ // 与 kimi-usage 的差别:火山方舟的配额走**管控面 OpenAPI**,需要
5
+ // AccessKeyID + SecretAccessKey 做 HMAC-SHA256 签名(不是 Bearer 令牌),
6
+ // 因此不能复用 index.js 里那条「Authorization: Bearer」的简单路径。
7
+ //
8
+ // 签名算法与端点全部硬编码在此,凭据只发往 open.volcengineapi.com 一个域。
9
+ // 纯函数(签名 / 解析 / 凭据归一)单独导出,便于零依赖单测:
10
+ // node test/volcengine-plan.test.js
11
+ //
12
+ // 实测依据(2026-09,上游 dsh-cost-meter issue #60 / #71 与本机实测):
13
+ // - GetCodingPlanUsage 无参即可返回 Result.QuotaUsage[{Level,Percent,ResetTimestamp}],
14
+ // Level 为 session / weekly / monthly 三档;**该接口只给 Percent,没有 used/total**;
15
+ // - GetAFPUsage 实为 AgentPlan 接口(CodingPlan 账号会拿到空/全 0),作兜底;
16
+ // - GetUsageDetails 裸调 400(缺 Filter.StartTime),GetPersonalPlan 亦需额外参数,
17
+ // 仅保留为兜底变体;
18
+ // - 需控制台创建 IAM 子用户并授予 ArkReadOnlyAccess + BillingCenterReadOnlyAccess。
19
+ //
20
+ // 归一化输出(与 kimi 面板同形,便于客户端复用同一套渲染):
21
+ // windows = { fiveHour|weekly|monthly|daily: { percent, resetsAt, ... } }
22
+ // percent 一律为 0-100 的**已用**百分比;resetsAt 为 ISO 字符串(无重置为 '')。
23
+ // ============================================================
24
+
25
+ import { createHash, createHmac } from 'node:crypto'
26
+
27
+ // ---------- 固定官方端点(硬编码白名单,凭据只发往此域) ----------
28
+
29
+ export const VOLCENGINE_HOST = 'open.volcengineapi.com'
30
+ export const VOLCENGINE_SERVICE = 'ark'
31
+ export const VOLCENGINE_REGION = 'cn-beijing'
32
+ export const VOLCENGINE_VERSION = '2024-01-01'
33
+
34
+ /**
35
+ * 管控面 Action 白名单(按序尝试)。
36
+ * GetCodingPlanUsage 为 CodingPlan 官方用量接口,置于首位;
37
+ * 其余为 AgentPlan / 计费明细 / 个人版套餐的兜底变体。
38
+ */
39
+ export const VOLCENGINE_ACTIONS = ['GetCodingPlanUsage', 'GetAFPUsage', 'GetUsageDetails', 'GetPersonalPlan']
40
+
41
+ /** 用户可见的凭据发现线索(面板中性提示里展示) */
42
+ export const VOLCENGINE_KEY_ENVS = ['VOLC_ACCESSKEY', 'VOLCENGINE_ACCESS_KEY_ID', 'VOLCENGINE_ACCESS_KEY', 'ARK_ACCESS_KEY_ID']
43
+ export const VOLCENGINE_SECRET_ENVS = ['VOLC_SECRETKEY', 'VOLCENGINE_SECRET_ACCESS_KEY', 'VOLCENGINE_SECRET_KEY', 'ARK_SECRET_ACCESS_KEY']
44
+
45
+ // ---------- 签名 ----------
46
+
47
+ function hmacSha256(key, data) {
48
+ return createHmac('sha256', key).update(data, 'utf8').digest()
49
+ }
50
+
51
+ function hashHex(data) {
52
+ return createHash('sha256').update(data, 'utf8').digest('hex')
53
+ }
54
+
55
+ /** RFC3986 百分号编码(火山签名要求,与 encodeURIComponent 的差异在于 !'()* 需转义) */
56
+ export function uriEscape(str) {
57
+ return encodeURIComponent(String(str))
58
+ .replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
59
+ }
60
+
61
+ /** 查询串规范化:键排序、值转义(数组值各自转义后排序) */
62
+ export function queryParamsToString(params) {
63
+ return Object.keys(params).sort().map((key) => {
64
+ const val = params[key]
65
+ if (val === undefined || val === null) return undefined
66
+ const ek = uriEscape(key)
67
+ if (!ek) return undefined
68
+ if (Array.isArray(val)) return `${ek}=${val.map(uriEscape).sort().join(`&${ek}=`)}`
69
+ return `${ek}=${uriEscape(String(val))}`
70
+ }).filter(Boolean).join('&')
71
+ }
72
+
73
+ /** 火山要求的 X-Date 格式:YYYYMMDDTHHMMSSZ(UTC,无分隔符) */
74
+ export function volcengineDateTimeNow(date) {
75
+ const d = date instanceof Date ? date : new Date()
76
+ return d.toISOString().replace(/[:-]|\.\d{3}/g, '')
77
+ }
78
+
79
+ /**
80
+ * 生成火山引擎 OpenAPI HMAC-SHA256 签名头。
81
+ * 仅对 host / x-content-sha256 / x-date 三头加签;GET 无 body 时 bodySha = sha256('')。
82
+ * @param {object} o - { accessKeyId, secretAccessKey, method, host, path, query, body, region, service, datetime }
83
+ * @returns {{'X-Date':string,'X-Content-Sha256':string,Host:string,Authorization:string}}
84
+ */
85
+ export function volcengineAuthorization({
86
+ accessKeyId,
87
+ secretAccessKey,
88
+ method = 'GET',
89
+ host = VOLCENGINE_HOST,
90
+ path = '/',
91
+ query = {},
92
+ body = '',
93
+ region = VOLCENGINE_REGION,
94
+ service = VOLCENGINE_SERVICE,
95
+ datetime,
96
+ } = {}) {
97
+ const xDate = datetime ?? volcengineDateTimeNow()
98
+ const date = xDate.slice(0, 8)
99
+ const bodySha = hashHex(body)
100
+ const signedHeaders = 'host;x-content-sha256;x-date'
101
+ const canonicalHeaders = `host:${host}\nx-content-sha256:${bodySha}\nx-date:${xDate}`
102
+ const qs = queryParamsToString(query)
103
+ const canonicalRequest = [method.toUpperCase(), path, qs, `${canonicalHeaders}\n`, signedHeaders, bodySha].join('\n')
104
+ const credentialScope = [date, region, service, 'request'].join('/')
105
+ const stringToSign = ['HMAC-SHA256', xDate, credentialScope, hashHex(canonicalRequest)].join('\n')
106
+ const kDate = hmacSha256(secretAccessKey, date)
107
+ const kRegion = hmacSha256(kDate, region)
108
+ const kService = hmacSha256(kRegion, service)
109
+ const kSigning = hmacSha256(kService, 'request')
110
+ const signature = hmacSha256(kSigning, stringToSign).toString('hex')
111
+ const authorization = `HMAC-SHA256 Credential=${accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
112
+ return { 'X-Date': xDate, 'X-Content-Sha256': bodySha, Host: host, Authorization: authorization }
113
+ }
114
+
115
+ // ---------- 凭据归一 ----------
116
+
117
+ /**
118
+ * 归一化火山双凭据(AK/SK)。支持:
119
+ * - 对象 { accessKeyId, secretAccessKey }(首选,字段名多重兼容)
120
+ * - 字符串 "AKID:SK" 或 "AKID SK"(冒号/空白分隔)
121
+ * 返回 { accessKeyId, secretAccessKey } 或 null(任一为空即不合格)。
122
+ */
123
+ export function normalizeVolcengineKey(key) {
124
+ if (key !== null && typeof key === 'object' && !Array.isArray(key)) {
125
+ const id = String(key.accessKeyId ?? key.accessKeyID ?? key.ak ?? key.apiKey ?? '').trim()
126
+ const secret = String(key.secretAccessKey ?? key.secretKey ?? key.sk ?? key.apiSecret ?? '').trim()
127
+ if (id.length > 0 && secret.length > 0) return { accessKeyId: id, secretAccessKey: secret }
128
+ return null
129
+ }
130
+ if (typeof key === 'string') {
131
+ const trimmed = key.trim()
132
+ if (trimmed.length === 0) return null
133
+ const colonIdx = trimmed.indexOf(':')
134
+ if (colonIdx > 0) {
135
+ const id = trimmed.slice(0, colonIdx).trim()
136
+ const secret = trimmed.slice(colonIdx + 1).trim()
137
+ if (id.length > 0 && secret.length > 0) return { accessKeyId: id, secretAccessKey: secret }
138
+ }
139
+ const parts = trimmed.split(/\s+/)
140
+ if (parts.length === 2 && parts[0].length > 0 && parts[1].length > 0 && parts[0].startsWith('AK')) {
141
+ return { accessKeyId: parts[0], secretAccessKey: parts[1] }
142
+ }
143
+ return null
144
+ }
145
+ return null
146
+ }
147
+
148
+ // ---------- 响应解析(纯函数) ----------
149
+
150
+ function clampPct(p) {
151
+ // 保留 2 位小数:实测 Coding Plan 的用量长期在 0.05%–0.4% 量级
152
+ // (刚开通/轻度使用时),只留 1 位会把 0.05 显示成「0%」——
153
+ // 看上去像「没统计到」,实际是有数据的。
154
+ return Math.max(0, Math.min(100, Math.round(p * 100) / 100))
155
+ }
156
+
157
+ /**
158
+ * 火山的百分比一律已是 0-100。
159
+ * 注意**不能**复用配置层那套「≤1 视为小数」的规则:0.5 表示 0.5%,
160
+ * 按小数解释会放大成 50%(十倍误差)。
161
+ *
162
+ * 负数是**非法数据**(不是 0):钳位成 0 会渲染出「已用 0%」这种看似
163
+ * 正常的假数据,反而掩盖接口异常。故负数返回 null,由调用方丢弃该窗口。
164
+ * 超过 100 则钳位(用量统计口径上的浮点溢出,钳位不影响判断)。
165
+ */
166
+ function percentOf(v) {
167
+ const n = Number(v)
168
+ if (!Number.isFinite(n) || n < 0) return null
169
+ return clampPct(n)
170
+ }
171
+
172
+ /**
173
+ * 归一化重置时刻:unix 秒 / unix 毫秒 / ISO 字符串 → ISO 字符串。
174
+ * -1 / 0 / 负数表示「该窗口无重置」(方舟零用量窗口会回 -1),返回 ''。
175
+ */
176
+ export function normalizeVolcResetAt(value) {
177
+ if (value === undefined || value === null || value === '') return ''
178
+ if (typeof value === 'string') {
179
+ const ms = Date.parse(value)
180
+ if (Number.isFinite(ms)) return new Date(ms).toISOString()
181
+ const asNum = Number(value)
182
+ if (!Number.isFinite(asNum) || asNum <= 0) return ''
183
+ return new Date(asNum > 1e12 ? asNum : asNum * 1000).toISOString()
184
+ }
185
+ const n = Number(value)
186
+ if (!Number.isFinite(n) || n <= 0) return ''
187
+ return new Date(n > 1e12 ? n : n * 1000).toISOString()
188
+ }
189
+
190
+ /** 归一化窗口名:五小时 / 周 / 月 / 日。未识别返回 null。 */
191
+ export function normalizeVolcWindowName(raw) {
192
+ if (raw === undefined || raw === null) return null
193
+ const raw0 = String(raw)
194
+ // 中文标签先行:中文经 [^a-z0-9] 过滤后会变成空串,若放在英文判定之后,
195
+ // 会被 s.length === 0 提前判为「不识别」,中文窗口名就全丢了。
196
+ if (raw0.includes('小时')) return 'fiveHour'
197
+ if (raw0.includes('日')) return 'daily'
198
+ if (raw0.includes('周')) return 'weekly'
199
+ if (raw0.includes('月')) return 'monthly'
200
+ const s = raw0.toLowerCase().replace(/[^a-z0-9]/g, '')
201
+ if (s.length === 0) return null
202
+ if (s.includes('5h') || s.includes('fivehour') || s === 'session' || s === 'rolling' || s === 'hour5') return 'fiveHour'
203
+ if (s.includes('daily') || s === 'day' || s === '1d' || s.includes('afpdaily')) return 'daily'
204
+ if (s.includes('week') || s === '7d' || s === 'seven') return 'weekly'
205
+ if (s.includes('month') || s === '30d') return 'monthly'
206
+ return null
207
+ }
208
+
209
+ /** 窗口名 → 中文展示名(客户端与面板共用) */
210
+ export const VOLC_WINDOW_LABELS = {
211
+ fiveHour: '5 小时窗口',
212
+ weekly: '本周配额',
213
+ monthly: '本月配额',
214
+ daily: '当日配额',
215
+ }
216
+
217
+ /** 从一个窗口对象里抽百分比:Percent 优先,其次 used/total、remaining/total。 */
218
+ function windowPercent(entry) {
219
+ const direct = percentOf(entry.Percent ?? entry.percent ?? entry.Percentage ?? entry.percentage ?? entry.UsedPercent ?? entry.usedPercent)
220
+ if (direct !== null) return direct
221
+ const total = Number(entry.Total ?? entry.total ?? entry.Limit ?? entry.limit ?? entry.Quota ?? entry.quota ?? entry.Capacity ?? entry.capacity ?? entry.Max ?? entry.max)
222
+ const used = Number(entry.Used ?? entry.used ?? entry.Usage ?? entry.usage ?? entry.Consumed ?? entry.consumed ?? entry.CurrentValue ?? entry.currentValue)
223
+ const remain = Number(entry.Remaining ?? entry.remaining ?? entry.Remain ?? entry.remain ?? entry.Available ?? entry.available)
224
+ if (Number.isFinite(total) && total > 0) {
225
+ if (Number.isFinite(used)) return clampPct((used / total) * 100)
226
+ if (Number.isFinite(remain)) return clampPct(((total - remain) / total) * 100)
227
+ }
228
+ return null
229
+ }
230
+
231
+ /** 从一条窗口记录里抽重置时刻(字段名多重兼容) */
232
+ function windowResetAt(entry) {
233
+ return normalizeVolcResetAt(
234
+ entry.ResetTimestamp ?? entry.resetTimestamp ?? entry.ResetTime ?? entry.resetTime
235
+ ?? entry.ResetAt ?? entry.resetAt ?? entry.NextResetTime ?? entry.nextResetTime
236
+ ?? entry.ExpiresAt ?? entry.expiresAt ?? entry.EndTime ?? entry.endTime,
237
+ )
238
+ }
239
+
240
+ /**
241
+ * 组装一条窗口;百分比非法则返回 null。绝对数值一并透传。
242
+ *
243
+ * CodingPlan 官方响应实测形态(2026-09,GetCodingPlanUsage):
244
+ * { Level:'session', Percent:0.394, ResetTimestamp:1789833269, Cap:100, RewardTotalPercent:0 }
245
+ * 即 Percent 已是「占 Cap 的百分比」,Cap 恒为 100;HasReward 为账户级字段。
246
+ * 换算成绝对量只为让客户端的用量文案更具体,percent 仍是唯一权威口径。
247
+ */
248
+ function buildWindow(entry) {
249
+ const percent = windowPercent(entry)
250
+ if (percent === null) return null
251
+ const win = { percent, resetsAt: windowResetAt(entry) }
252
+ const quota = Number(entry.Quota ?? entry.quota ?? entry.Total ?? entry.total ?? entry.Limit ?? entry.limit ?? entry.Capacity ?? entry.capacity)
253
+ const used = Number(entry.Used ?? entry.used ?? entry.Usage ?? entry.usage ?? entry.CurrentValue ?? entry.currentValue)
254
+ if (Number.isFinite(quota) && quota > 0) win.quota = quota
255
+ if (Number.isFinite(used) && used >= 0) win.used = used
256
+ const cap = Number(entry.Cap ?? entry.cap)
257
+ if (Number.isFinite(cap) && cap > 0) {
258
+ win.cap = cap
259
+ // 只有 Cap 到位才能把百分比折算成绝对量(Percent 为 0-100 的百分数)
260
+ if (win.used === undefined) win.used = Math.round((percent / 100) * cap * 100) / 100
261
+ if (win.quota === undefined) win.quota = cap
262
+ }
263
+ const reward = Number(entry.RewardTotalPercent ?? entry.rewardTotalPercent)
264
+ if (Number.isFinite(reward) && reward > 0) win.rewardTotalPercent = reward
265
+ return win
266
+ }
267
+
268
+ /**
269
+ * 解析火山方舟配额响应。兼容形态(按优先级):
270
+ * ① { Result: { QuotaUsage: [{ Level:'session', Percent, ResetTimestamp, Cap }] } } ← CodingPlan 官方
271
+ * ② { Result: { UsageDetails: [{ QuotaType, Total, Used, Remaining, ResetTime }] } }
272
+ * ③ arkcli 形态 { items: [{ product:'coding-plan', periods:[{ label, percent, reset_at }] }] }
273
+ * ④ 扁平窗口对象 { AFPFiveHour:{Quota,Used,ResetTime}, ... } / { fiveHour:{...} }
274
+ * 容忍字段名与大小写差异;非法窗口忽略;无任何可解析窗口时返回 null。
275
+ * @returns {{[name:string]:{percent:number,resetsAt:string}}|null}
276
+ */
277
+ export function parseVolcengineUsage(data) {
278
+ if (data === null || typeof data !== 'object') return null
279
+
280
+ // 形态 ③:arkcli(items → coding-plan.periods)
281
+ if (Array.isArray(data.items)) {
282
+ const item = data.items.find((i) => i !== null && typeof i === 'object' && String(i.product ?? '').toLowerCase().includes('coding'))
283
+ ?? data.items.find((i) => i !== null && typeof i === 'object' && Array.isArray(i.periods))
284
+ if (item !== null && typeof item === 'object' && Array.isArray(item.periods)) {
285
+ const windows = {}
286
+ for (const p of item.periods) {
287
+ if (p === null || typeof p !== 'object') continue
288
+ const name = normalizeVolcWindowName(p.label ?? p.name ?? p.type ?? p.quotaType ?? p.window)
289
+ if (name === null) continue
290
+ const win = buildWindow(p)
291
+ if (win === null) continue
292
+ if (windows[name] === undefined) windows[name] = win
293
+ }
294
+ if (Object.keys(windows).length > 0) return windows
295
+ }
296
+ }
297
+
298
+ // 形态 ①②:定位承载窗口数组的根对象
299
+ const roots = [data.Result, data.result, data.data?.Result, data.data?.result, data.data].filter((v) => v !== null && typeof v === 'object')
300
+ const root = roots.length > 0 ? roots[0] : data
301
+
302
+ if (root !== null && typeof root === 'object' && !Array.isArray(root)) {
303
+ const list = root.QuotaUsage ?? root.quotaUsage ?? root.UsageDetails ?? root.usageDetails
304
+ ?? root.usages ?? root.limits ?? root.quotas ?? root.windows ?? root.periods ?? root.details ?? null
305
+ if (Array.isArray(list)) {
306
+ const windows = {}
307
+ for (const entry of list) {
308
+ if (entry === null || typeof entry !== 'object') continue
309
+ // GetCodingPlanUsage 的窗口名字段是 Level,置于候选最前。
310
+ const name = normalizeVolcWindowName(
311
+ entry.Level ?? entry.level ?? entry.QuotaType ?? entry.quotaType ?? entry.Type ?? entry.type
312
+ ?? entry.Label ?? entry.label ?? entry.Period ?? entry.period ?? entry.Name ?? entry.name
313
+ ?? entry.Window ?? entry.window ?? entry.QuotaName ?? entry.quotaName,
314
+ )
315
+ if (name === null) continue
316
+ const win = buildWindow(entry)
317
+ if (win === null) continue
318
+ if (windows[name] === undefined) windows[name] = win
319
+ }
320
+ if (Object.keys(windows).length > 0) return windows
321
+ }
322
+ }
323
+
324
+ // 形态 ④:扁平窗口对象(含 AFP* 与 fiveHour/weekly/monthly 两种命名)
325
+ const windows = {}
326
+ const scan = (obj) => {
327
+ for (const [k, v] of Object.entries(obj)) {
328
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) continue
329
+ const name = normalizeVolcWindowName(k)
330
+ if (name === null || windows[name] !== undefined) continue
331
+ const win = buildWindow(v)
332
+ if (win !== null) windows[name] = win
333
+ }
334
+ }
335
+ if (root !== null && typeof root === 'object') scan(root)
336
+ if (Object.keys(windows).length === 0) scan(data)
337
+ return Object.keys(windows).length > 0 ? windows : null
338
+ }
339
+
340
+ // ---------- 查询 ----------
341
+
342
+ /** 火山业务错误信封:ResponseMetadata.Error.Code/Message 非空即失败 */
343
+ function volcEnvelopeMessage(data) {
344
+ const err = data?.ResponseMetadata?.Error
345
+ if (err === null || err === undefined || typeof err !== 'object') return null
346
+ const code = String(err.Code ?? '').trim()
347
+ const msg = String(err.Message ?? '').trim()
348
+ if (code.length === 0 && msg.length === 0) return null
349
+ if (code === 'ok' || code === 'OK' || code === 'Success') return null
350
+ return (code.length > 0 ? code : 'Error') + (msg.length > 0 ? ': ' + msg : '')
351
+ }
352
+
353
+ /**
354
+ * 查询火山方舟 Coding Plan 配额。按 Action 白名单顺序尝试:
355
+ * 401/403 视为「当前 Action 不可用」继续下一个(多 Action 变体语义差异),
356
+ * 解析成功立即返回;200 但解析失败的「结构化错误」单独保留并优先抛出
357
+ * (比末尾 Action 的 404 更有诊断价值)。
358
+ * @param {object} o - { accessKeyId, secretAccessKey, fetchImpl, timeoutMs, signal }
359
+ * @returns {Promise<{windows:object, action:string, endpoint:string}>}
360
+ */
361
+ export async function queryVolcenginePlan({
362
+ accessKeyId,
363
+ secretAccessKey,
364
+ fetchImpl,
365
+ timeoutMs = 15000,
366
+ signal,
367
+ } = {}) {
368
+ const creds = normalizeVolcengineKey({ accessKeyId, secretAccessKey })
369
+ if (creds === null) {
370
+ const error = new Error('未找到火山引擎访问密钥(需 AccessKeyID + SecretAccessKey 成对提供)')
371
+ error.soft = true
372
+ throw error
373
+ }
374
+ const doFetch = fetchImpl ?? globalThis.fetch
375
+ let lastError = null
376
+ let parseError = null
377
+
378
+ for (const action of VOLCENGINE_ACTIONS) {
379
+ const query = { Action: action, Version: VOLCENGINE_VERSION }
380
+ const url = `https://${VOLCENGINE_HOST}/?${queryParamsToString(query)}`
381
+ let response
382
+ try {
383
+ const auth = volcengineAuthorization({
384
+ accessKeyId: creds.accessKeyId,
385
+ secretAccessKey: creds.secretAccessKey,
386
+ method: 'GET',
387
+ host: VOLCENGINE_HOST,
388
+ path: '/',
389
+ query,
390
+ body: '',
391
+ })
392
+ const ac = new AbortController()
393
+ const timer = setTimeout(() => ac.abort(), timeoutMs)
394
+ const onAbort = () => ac.abort()
395
+ if (signal) {
396
+ if (signal.aborted) ac.abort()
397
+ else signal.addEventListener('abort', onAbort, { once: true })
398
+ }
399
+ try {
400
+ response = await doFetch(url, {
401
+ method: 'GET',
402
+ headers: {
403
+ 'x-date': auth['X-Date'],
404
+ 'x-content-sha256': auth['X-Content-Sha256'],
405
+ host: auth.Host,
406
+ authorization: auth.Authorization,
407
+ accept: 'application/json',
408
+ 'user-agent': 'dsh-cost-tracker/1.8 (DeepSeek Harness plugin)',
409
+ },
410
+ signal: ac.signal,
411
+ })
412
+ } finally {
413
+ clearTimeout(timer)
414
+ if (signal) signal.removeEventListener?.('abort', onAbort)
415
+ }
416
+ } catch (error) {
417
+ lastError = error
418
+ continue // 传输层错误:换下一个 Action 变体
419
+ }
420
+
421
+ const status = Number(response?.status) || 0
422
+ if (status === 401 || status === 403) {
423
+ // 多 Action 变体之间权限语义不同:单个 Action 的 401/403 只说明该 Action
424
+ // 不可用(或该账号是另一类套餐),继续尝试下一个。
425
+ const error = new Error(`火山方舟凭据无效或无权限访问 ${action}(HTTP ${status})`)
426
+ error.soft = true
427
+ lastError = error
428
+ continue
429
+ }
430
+ let text = ''
431
+ try { text = await response.text() } catch (e) { text = '' }
432
+ if (status < 200 || status >= 300) {
433
+ lastError = new Error(`火山方舟配额接口 HTTP ${status}(${action})`)
434
+ continue
435
+ }
436
+ let data = null
437
+ try { data = JSON.parse(text) } catch (e) {
438
+ parseError ??= new Error(`火山方舟配额响应不是合法 JSON(${action})`)
439
+ lastError = parseError
440
+ continue
441
+ }
442
+ const envelope = volcEnvelopeMessage(data)
443
+ const windows = parseVolcengineUsage(data)
444
+ if (windows === null) {
445
+ // 200 但无可解析窗口:优先透出服务端业务信封的真实原因。
446
+ const error = envelope !== null
447
+ ? new Error(`火山方舟: ${envelope}`)
448
+ : new Error(`火山方舟配额响应中未解析出用量窗口(${action}),接口结构可能已变化`)
449
+ parseError ??= error
450
+ lastError = error
451
+ continue
452
+ }
453
+ return { windows, action, endpoint: url }
454
+ }
455
+ throw parseError ?? lastError ?? new Error('火山方舟配额查询失败:所有接口变体均未返回可用用量')
456
+ }