@angelyeye/dsh-cost-tracker 1.8.13 → 1.8.15
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/CHANGELOG.md +129 -0
- package/README.en.md +47 -4
- package/README.md +47 -4
- package/client.js +161 -3
- package/config.js +41 -1
- package/index.js +326 -10
- package/package.json +4 -2
- package/pricing.js +159 -1
- package/volcengine.js +456 -0
package/pricing.js
CHANGED
|
@@ -180,6 +180,163 @@ export const SUBSCRIPTION_RATES = {
|
|
|
180
180
|
kimi: { input: 6.5, output: 27.0, cacheRead: 1.1, cacheWrite: 1.1 },
|
|
181
181
|
}
|
|
182
182
|
|
|
183
|
+
/**
|
|
184
|
+
* 订阅套餐的**模型白名单**:provider 键 → 该套餐覆盖的模型。
|
|
185
|
+
*
|
|
186
|
+
* 为什么必须有这层:订阅制的判定原先只看 provider 名。这对 Kimi 成立
|
|
187
|
+
* (kimi 全部走订阅),但**火山方舟不是**——同一个 provider 下既有
|
|
188
|
+
* Coding Plan 套餐内的模型(订阅,不按量扣费),也有套餐外的模型
|
|
189
|
+
* (按量计费)。只看 provider 会把按量调用错记为订阅,金额从「真实花费」
|
|
190
|
+
* 里凭空消失,且原始记录被标成 subscription 后无法自动回滚。
|
|
191
|
+
*
|
|
192
|
+
* 值为 null 表示「该 provider 全部模型都属于这个套餐」(Kimi 即如此,
|
|
193
|
+
* 保持 1.8.13 及以前的既有行为逐字节不变)。
|
|
194
|
+
* 值为数组时按**归一化模型名**匹配(见 normalizeModelName),
|
|
195
|
+
* 另可用 `prefixes` 放行整族模型(如方舟自动调度的 ark-code 系)。
|
|
196
|
+
*/
|
|
197
|
+
export const SUBSCRIPTION_MODELS = {
|
|
198
|
+
'kimi-coding': null,
|
|
199
|
+
kimi: null,
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* 火山方舟(Volcengine Ark)Coding Plan 订阅套餐。
|
|
204
|
+
*
|
|
205
|
+
* provider 名由用户在 DSH 里自定,故登记多个常见别名(normProvider 已剥离
|
|
206
|
+
* `-official` 后缀)。用户实测 provider 为 `byteblus-coding-plan-cn`
|
|
207
|
+
* (baseURL 指向 ark.cn-beijing.volces.com/api/coding/v3),一并纳入。
|
|
208
|
+
*
|
|
209
|
+
* 模型白名单:套餐内含多厂商模型。**同名模型在按量侧也存在**
|
|
210
|
+
* (如 doubao-seed-2.0-pro、deepseek-v4-pro),因此判定必须靠
|
|
211
|
+
* 「provider 命中 + 模型在白名单内」双重限定,缺一不可。
|
|
212
|
+
*
|
|
213
|
+
* ⚠️ 单价口径(**估算,非官方账单**):套餐内的模型各自牌价差异很大
|
|
214
|
+
* (豆包 / GLM / Kimi / DeepSeek / MiniMax 各档不同),而套餐只有一个
|
|
215
|
+
* 固定月费、按窗口百分比计量,**官方没有给出「套餐内某次调用的等效单价」**。
|
|
216
|
+
* 故此处取**单一代表价**,与既有 Kimi 订阅(同样一个价位代表整档套餐)
|
|
217
|
+
* 的口径一致,仅用于横向比较订阅是否划算。
|
|
218
|
+
* 未逐一登记各模型第三方报价:可核实到的多为聚合站的美元估价,
|
|
219
|
+
* 与方舟官方人民币牌价不可直接对照,按本仓库「不编造价格」的约定不收录。
|
|
220
|
+
* 要精确到模型,请以方舟控制台账单为准。
|
|
221
|
+
*/
|
|
222
|
+
const VOLC_PLAN_RATES = { input: 3.0, output: 12.0, cacheRead: 0.6, cacheWrite: 0.6 }
|
|
223
|
+
|
|
224
|
+
/** 火山方舟 Coding Plan 覆盖的 provider 别名 */
|
|
225
|
+
export const VOLCENGINE_PLAN_PROVIDER_KEYS = [
|
|
226
|
+
'volcengine',
|
|
227
|
+
'volcengine-coding',
|
|
228
|
+
'volcengine-plan',
|
|
229
|
+
'volcengine-coding-plan',
|
|
230
|
+
'byteblus-coding-plan-cn',
|
|
231
|
+
'byteplus-coding-plan-cn',
|
|
232
|
+
]
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* **专属 Coding Plan 端点**的 provider(baseURL 指向 `.../api/coding/v3`)。
|
|
236
|
+
*
|
|
237
|
+
* 与上面的泛 `volcengine` 别名区别对待:这类 provider 本身就是订阅入口,
|
|
238
|
+
* 其可调模型全部来自套餐(调用套餐外模型需另配 `/api/v3` 在线推理 provider,
|
|
239
|
+
* 那属于另一个 provider 名),因此**不再逐模型限定**——这也解决了
|
|
240
|
+
* 「模型 id 带日期后缀、清单永远追不上」的问题。
|
|
241
|
+
*
|
|
242
|
+
* 泛 `volcengine` 走另一个分支:必须靠模型白名单,因为同一个 provider 下
|
|
243
|
+
* 套餐内外的模型混在一起(接入点 id 形如 ep-xxxx 就是按量)。
|
|
244
|
+
*/
|
|
245
|
+
export const VOLCENGINE_PLAN_DEDICATED_PROVIDERS = [
|
|
246
|
+
'byteblus-coding-plan-cn',
|
|
247
|
+
'byteplus-coding-plan-cn',
|
|
248
|
+
'volcengine-coding',
|
|
249
|
+
'volcengine-plan',
|
|
250
|
+
'volcengine-coding-plan',
|
|
251
|
+
]
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 火山方舟 Coding Plan 覆盖的具体模型(原始名,归一化后匹配)。
|
|
255
|
+
*
|
|
256
|
+
* 带上实测见到的**日期/版本后缀**变体:方舟模型 id 普遍带后缀
|
|
257
|
+
* (用户配置里就有 `glm-5-3-flash-260828`、`deepseek-v4-1-flash-260910`、
|
|
258
|
+
* `doubao-seed-2-1-pro-260915`),漏配的后果是订阅调用被当成未知模型、
|
|
259
|
+
* 标成「按量计费 · 价格为估算」——正是本次要修掉的那类误标。
|
|
260
|
+
*/
|
|
261
|
+
const VOLCENGINE_PLAN_MODEL_IDS = [
|
|
262
|
+
'ark-code-latest',
|
|
263
|
+
// 豆包
|
|
264
|
+
'doubao-seed-code',
|
|
265
|
+
'doubao-seed-2.0-code',
|
|
266
|
+
'doubao-seed-2.0-pro',
|
|
267
|
+
'doubao-seed-2.0-lite',
|
|
268
|
+
'doubao-seed-2.1-pro',
|
|
269
|
+
// 智谱(含用户配置里的 5.3 flash 带日期变体)
|
|
270
|
+
'glm-4.7',
|
|
271
|
+
'glm-5.1',
|
|
272
|
+
'glm-5.3-flash',
|
|
273
|
+
// Kimi / DeepSeek / MiniMax
|
|
274
|
+
'kimi-k2.5',
|
|
275
|
+
'deepseek-v3.2',
|
|
276
|
+
'deepseek-v4-pro',
|
|
277
|
+
'deepseek-v4.1-flash',
|
|
278
|
+
'minimax-m2.5',
|
|
279
|
+
]
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* 整族放行的模型前缀(归一化后)。
|
|
283
|
+
*
|
|
284
|
+
* **刻意收得很窄**:只放行方舟自动调度名(`ark-code-*`,会滚动升级,
|
|
285
|
+
* 逐一登记必然过期)。其余一律靠上面的显式清单——
|
|
286
|
+
* 前缀放太宽(如按 `deepseek` / `glm` 整族放行)会把该 provider 下
|
|
287
|
+
* 套餐外的按量模型一并算成订阅,金额从「真实花费」里消失,
|
|
288
|
+
* 那正是本门卫要防的方向,宁可漏配(可显式补清单)也不能错配。
|
|
289
|
+
*/
|
|
290
|
+
export const VOLCENGINE_PLAN_MODEL_PREFIXES = ['arkcode']
|
|
291
|
+
|
|
292
|
+
export const VOLCENGINE_PLAN_RATES = VOLC_PLAN_RATES
|
|
293
|
+
|
|
294
|
+
/** 归一化模型名索引(惰性构建,与下方 eraIndex 同法,避免依赖声明顺序) */
|
|
295
|
+
let VOLC_MODEL_INDEX = null
|
|
296
|
+
function volcModelIndex() {
|
|
297
|
+
if (VOLC_MODEL_INDEX === null) {
|
|
298
|
+
VOLC_MODEL_INDEX = {}
|
|
299
|
+
for (const id of VOLCENGINE_PLAN_MODEL_IDS) VOLC_MODEL_INDEX[normalizeModelName(id)] = id
|
|
300
|
+
}
|
|
301
|
+
return VOLC_MODEL_INDEX
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** 供测试与展示:归一化模型名 → 套餐单价 */
|
|
305
|
+
export function volcenginePlanModels() {
|
|
306
|
+
const idx = volcModelIndex()
|
|
307
|
+
const out = {}
|
|
308
|
+
for (const k of Object.keys(idx)) out[k] = VOLC_PLAN_RATES
|
|
309
|
+
return out
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 解析某次调用是否命中订阅套餐。
|
|
314
|
+
* @param {string} np - 归一化 provider 名
|
|
315
|
+
* @param {string} model - 模型名
|
|
316
|
+
* @returns {object|null} 命中返回单价表,否则 null
|
|
317
|
+
*/
|
|
318
|
+
export function subscriptionPlanFor(np, model) {
|
|
319
|
+
const sub = SUBSCRIPTION_RATES[np]
|
|
320
|
+
if (sub) {
|
|
321
|
+
const allow = SUBSCRIPTION_MODELS[np]
|
|
322
|
+
// null = 该 provider 全部模型都属于订阅(Kimi:保持既有行为不变)
|
|
323
|
+
if (allow === null || allow === undefined) return sub
|
|
324
|
+
const n = normalizeModelName(model)
|
|
325
|
+
if (Array.isArray(allow) && allow.indexOf(n) >= 0) return sub
|
|
326
|
+
return null
|
|
327
|
+
}
|
|
328
|
+
// 火山方舟 Coding Plan:先看专属订阅端点的 provider(全部模型均属套餐),
|
|
329
|
+
// 再看泛 volcengine(必须靠模型白名单,因为套餐内外模型混在同一 provider 下)。
|
|
330
|
+
if (VOLCENGINE_PLAN_PROVIDER_KEYS.indexOf(np) < 0) return null
|
|
331
|
+
if (VOLCENGINE_PLAN_DEDICATED_PROVIDERS.indexOf(np) >= 0) return VOLC_PLAN_RATES
|
|
332
|
+
const n = normalizeModelName(model)
|
|
333
|
+
if (volcModelIndex()[n] !== undefined) return VOLC_PLAN_RATES
|
|
334
|
+
for (const p of VOLCENGINE_PLAN_MODEL_PREFIXES) {
|
|
335
|
+
if (n.startsWith(p)) return VOLC_PLAN_RATES
|
|
336
|
+
}
|
|
337
|
+
return null
|
|
338
|
+
}
|
|
339
|
+
|
|
183
340
|
/** Provider 兜底单价(估算);缓存写入按缓存命中价计。
|
|
184
341
|
* deepseek 兜底已同步至 V4.1 Flash 档(2.0/8.0/0.04),未知模型不再按旧价高估。 */
|
|
185
342
|
export const PROVIDER_RATES = {
|
|
@@ -274,7 +431,8 @@ export function peakPhaseAt(ts, spanDays) {
|
|
|
274
431
|
* 记账应以它入账;未命中精确表时为原模型名。
|
|
275
432
|
*/
|
|
276
433
|
export function priceFor(np, model, ts) {
|
|
277
|
-
|
|
434
|
+
const sub = subscriptionPlanFor(np, model)
|
|
435
|
+
if (sub) return { rates: sub, tiered: false, estimated: true, subscription: true, model, era: null }
|
|
278
436
|
const era = eraAt(ts)
|
|
279
437
|
const hit = resolveModelInEra(era, model)
|
|
280
438
|
if (hit) return { rates: era.models[hit], tiered: true, estimated: false, subscription: false, model: hit, era: era.id }
|
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
|
+
}
|