dsh-token-dash 2.0.2 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +6 -2
- package/README.md +7 -3
- package/client.js +86 -10
- package/index.js +122 -16
- package/locale/en.json +13 -1
- package/locale/zh.json +13 -1
- package/package.json +1 -1
- package/src/adapters.js +88 -15
- package/src/catalog.js +146 -0
- package/src/collect.js +5 -5
- package/src/core.js +177 -38
- package/src/match.js +119 -0
- package/src/pricing.js +146 -204
- package/src/providers.js +13 -1
- package/src/quota-sources.js +101 -0
- package/src/store.js +55 -2
package/README.en.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
</p>
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
12
|
-
See today's model spend, monthly budget headroom, and subscription windows for
|
|
12
|
+
See today's model spend, monthly budget headroom, and subscription windows for 8 providers right next to the DSH input box.<br />
|
|
13
13
|
Paste a key and the billing mode is detected automatically; cost, Tokens and cache hits are estimated locally;<br />
|
|
14
14
|
export the current month and import it back after switching machines or reinstalling.
|
|
15
15
|
</p>
|
|
@@ -41,8 +41,10 @@
|
|
|
41
41
|
| Qwen | API usage | `DASHSCOPE_API_KEY` (CNY) / `DASHSCOPE_INTL_API_KEY` (USD) | Usage only; balance unsupported |
|
|
42
42
|
| OpenCode Go | Subscription | `OPENCODE_GO_API_KEY` | 5h / weekly / monthly windows (USD) |
|
|
43
43
|
| Command Code | Subscription | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | 5h + weekly windows, credits (CNY) |
|
|
44
|
+
| Ollama Cloud | API usage | `OLLAMA_API_KEY` | Plan + purchased credits (USD), plan usage, 30-day channel usage |
|
|
44
45
|
|
|
45
46
|
- Save keys under the names above in DSH's credential settings; the plugin reads them through the host `credentials` service, not environment variables or local login files.
|
|
47
|
+
- Ollama is added through DSH's custom OpenAI-compatible provider: the route id must be `ollama` (the key reference is derived as `<ROUTE>_API_KEY` → `OLLAMA_API_KEY`). Any other id will not resolve the key and the balance card will not appear.
|
|
46
48
|
- Keys are detected automatically; GLM / Kimi / OpenCode Go / Command Code can be re-detected from the dashboard footer.
|
|
47
49
|
- Subscription models count toward Tokens but not cost; billing mode is pinned per key instead of following quota flakiness.
|
|
48
50
|
- Balance, quota and usage are separate; a balance failure never resets today's Token ledger to zero.
|
|
@@ -78,7 +80,7 @@ Screenshots use mock data so the full layout is visible at once.
|
|
|
78
80
|
- Subscription windows use three slots: first left, second center, third right; two windows occupy the first two slots.
|
|
79
81
|
- Model column is capped at 150; Tokens / requests / hit rate are right-aligned.
|
|
80
82
|
|
|
81
|
-
**P3 · Full dashboard**: cards for
|
|
83
|
+
**P3 · Full dashboard**: cards for 8 providers, summary band, 8-column model breakdown and a settings capsule; the page owns its scrollbar at the window edge.
|
|
82
84
|
|
|
83
85
|
<p align="center">
|
|
84
86
|
<img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/settings.png" alt="Full dashboard" />
|
|
@@ -115,6 +117,8 @@ Update: run `update` with the same name, or use the `⤓` button on the right of
|
|
|
115
117
|
- The UI currently ships Chinese / English only. Other DSH languages (Japanese, German, Russian, etc.) fall back to English.
|
|
116
118
|
- After a DSH upgrade the plugin may disappear from the profile; reinstall the same tarball — the ledger is not deleted.
|
|
117
119
|
- Qwen tracks usage only; its balance endpoint is unsupported. Other balances/quotas follow what each API returns.
|
|
120
|
+
- A USD-billed provider that only matches the CNY price table shows "Unpriced" with a reason instead of rendering CNY numbers as USD; add a `currency: "USD"` entry to `prefs.json` `priceOverrides` for exact amounts.
|
|
121
|
+
- Ollama's balance and usage endpoints share a 10 requests/minute limit; when rate limited the card keeps the last values with a "Rate limited" note and recovers automatically.
|
|
118
122
|
- Upstream APIs are rate-limited; successful results are cached for 60s, failures for 10s, and concurrent requests are coalesced.
|
|
119
123
|
|
|
120
124
|
## Data & privacy
|
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
</p>
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
12
|
-
在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及
|
|
12
|
+
在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及 8 家供应商的订阅窗口。<br />
|
|
13
13
|
填 Key 自动识别订阅或 API 用量;费用、Tokens、缓存命中全部在本地估算;<br />
|
|
14
14
|
当月数据可导出备份,换机或重装后一键导入恢复。
|
|
15
15
|
</p>
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
<a href="https://awesome-dsh-plugin.com/zh/p/spartawhy117/dsh-token-dash"><img src="https://img.shields.io/badge/awesome--dsh--plugin-listed-6ea8ff" alt="awesome-dsh-plugin" /></a>
|
|
29
29
|
</p>
|
|
30
30
|
|
|
31
|
-
**三个入口,一份数据**:输入框底栏右侧 Pill 看当前模型;浮层看预算、余额与用量表;整页看
|
|
31
|
+
**三个入口,一份数据**:输入框底栏右侧 Pill 看当前模型;浮层看预算、余额与用量表;整页看 8 家供应商的全量卡片与模型明细。所有页面共用同一份本地账本,不重复计算。
|
|
32
32
|
|
|
33
33
|
## 支持矩阵
|
|
34
34
|
|
|
@@ -41,8 +41,10 @@
|
|
|
41
41
|
| Qwen | API 用量 | `DASHSCOPE_API_KEY`(CNY)/ `DASHSCOPE_INTL_API_KEY`(USD) | 仅用量;余额不支持 |
|
|
42
42
|
| OpenCode Go | 订阅 | `OPENCODE_GO_API_KEY` | 5h / 周 / 月窗口(USD) |
|
|
43
43
|
| Command Code | 订阅 | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | 5h + 周窗口、Credits(CNY) |
|
|
44
|
+
| Ollama Cloud | API 用量 | `OLLAMA_API_KEY` | 套餐剩余 + 购买余额(USD)、套餐已用、渠道 30 天用量 |
|
|
44
45
|
|
|
45
46
|
- 在 DSH 的凭据设置中按上表名称保存 Key;插件只通过宿主 `credentials` 读取,不读环境变量或本机登录文件。
|
|
47
|
+
- Ollama 在 DSH 里需要用「自定义 OpenAI 兼容供应商」接入:route id 必须填 `ollama`(凭据按 `<ROUTE>_API_KEY` 派生成 `OLLAMA_API_KEY`),自定义名填别的会取不到 Key,余额卡也不会出现。
|
|
46
48
|
- 填 Key 后自动探测;GLM / Kimi / OpenCode Go / Command Code 可在「全量看板」底部重新检测订阅。
|
|
47
49
|
- 订阅模型计入 Tokens,但不计费用;计费形态按 Key 固化,不随配额接口抖动。
|
|
48
50
|
- 余额、配额、用量分开展示;余额失败不会把当天的 Token 记账清零。
|
|
@@ -78,7 +80,7 @@
|
|
|
78
80
|
- 订阅窗口固定三槽位:第 1 窗左、第 2 窗中、第 3 窗右;只有两窗时占前两个槽位。
|
|
79
81
|
- 模型列上限 150,Tokens / 请求 / 命中右对齐;长模型名用省略号,悬浮可看全名。
|
|
80
82
|
|
|
81
|
-
**P3 · 整页看板**:
|
|
83
|
+
**P3 · 整页看板**:8 家供应商卡片、摘要带、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
|
|
82
84
|
|
|
83
85
|
<p align="center">
|
|
84
86
|
<img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/settings.png" alt="整页看板" />
|
|
@@ -114,6 +116,8 @@ dsh plugin --profile desktop add /path/to/dsh-token-dash-x.y.z.tgz
|
|
|
114
116
|
- 界面语言当前仅中文 / English;选择日语、德语、俄语等其他 DSH 语言时,插件文案显示英文回退。
|
|
115
117
|
- 升级 DSH 后插件可能从 profile 消失,重装同一个 tarball 即可,账本不会被删。
|
|
116
118
|
- Qwen 只统计用量,余额接口不支持;其余供应商的余额/配额以接口实际返回为准。
|
|
119
|
+
- 美元结算的供应商如果只命中人民币价目表,该模型会显示「未定价」并给出原因(不会把人民币数值当成美元);需要更精确的金额时,可在 `prefs.json` 的 `priceOverrides` 里按 `currency: "USD"` 补单价。
|
|
120
|
+
- Ollama 的余额与用量接口共享 10 次/分钟限流;触发限流时卡片保留上次数值并标「限流中」,恢复后自动更新。
|
|
117
121
|
- 上游接口有速率限制;成功结果缓存 60s、失败结果缓存 10s,并发请求会合并。
|
|
118
122
|
|
|
119
123
|
## 数据与隐私
|
package/client.js
CHANGED
|
@@ -109,8 +109,24 @@ window.__ModuleLoader__.load({
|
|
|
109
109
|
'账户真实余额,不受预算影响': 'Account balance; not affected by budget',
|
|
110
110
|
'本月累计消耗,等于已用/预算 的分子': 'Month-to-date spend; numerator of used/budget',
|
|
111
111
|
'提示': 'Note',
|
|
112
|
+
'按社区表 CNY': 'Community table (CNY)',
|
|
113
|
+
'价格取社区价目表(人民币),与渠道账单可能有差异': 'Priced from the community table (CNY); may differ from your provider bill',
|
|
114
|
+
'无匹配价目': 'No matching price', '候选模型不唯一': 'Ambiguous model match',
|
|
115
|
+
'模型名无效': 'Invalid model name', '订阅不计价': 'Subscription, not billed',
|
|
116
|
+
'套餐已用': 'Plan used', '购买余额': 'Purchased credits',
|
|
117
|
+
'周期至 {time}': 'Cycle ends {time}', '限流中': 'Rate limited',
|
|
118
|
+
'渠道用量 {value}': 'Channel usage {value}',
|
|
119
|
+
'价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价': 'Price table is CNY while this provider bills in USD; add a USD priceOverrides entry',
|
|
112
120
|
}
|
|
113
121
|
const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
|
|
122
|
+
/** 未定价原因 → 可读文案;未知 reason 回退「未定价」。 */
|
|
123
|
+
const REASON_TEXT = {
|
|
124
|
+
'no-model-price': '无匹配价目',
|
|
125
|
+
ambiguous: '候选模型不唯一',
|
|
126
|
+
'invalid-model': '模型名无效',
|
|
127
|
+
'kind-skip': '订阅不计价',
|
|
128
|
+
'currency-mismatch': '价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价',
|
|
129
|
+
}
|
|
114
130
|
const MESSAGES = { zh: ZH, en: EN }
|
|
115
131
|
let localeService = null
|
|
116
132
|
let ctxRef = null
|
|
@@ -841,10 +857,21 @@ window.__ModuleLoader__.load({
|
|
|
841
857
|
h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, row.requests),
|
|
842
858
|
h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
|
|
843
859
|
row.hitRate === null || row.hitRate === undefined ? '—' : fmtRatio(row.hitRate)),
|
|
844
|
-
h('span', {
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
860
|
+
h('span', {
|
|
861
|
+
role: 'cell',
|
|
862
|
+
'data-testid': 'token-dash-detail-cost',
|
|
863
|
+
title: row.kind !== 'api'
|
|
864
|
+
? tr('订阅不计价')
|
|
865
|
+
: row.priced === false
|
|
866
|
+
? tr(REASON_TEXT[row.reason] ?? '未定价')
|
|
867
|
+
: undefined,
|
|
868
|
+
style: { ...styles.cellNum, ...cell, textAlign: 'right' },
|
|
869
|
+
},
|
|
870
|
+
row.kind !== 'api' || row.priced === 'empty'
|
|
871
|
+
? '—'
|
|
872
|
+
: row.priced === false
|
|
873
|
+
? tr('未定价')
|
|
874
|
+
: `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
|
|
848
875
|
}
|
|
849
876
|
|
|
850
877
|
/** P3 两格卡:总费用(多币种同行)与真实 Tokens。 */
|
|
@@ -889,6 +916,18 @@ window.__ModuleLoader__.load({
|
|
|
889
916
|
return tr('查询失败')
|
|
890
917
|
}
|
|
891
918
|
|
|
919
|
+
/** P3 API 卡底部说明:状态 · 比例,再补余额周期 / 限流 / 渠道用量(渠道值只读)。 */
|
|
920
|
+
function apiCardCaption(provider, { hasBudget, percent, budget }) {
|
|
921
|
+
const parts = [`${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`]
|
|
922
|
+
const periodEnd = Number(provider.balance?.periodEnd)
|
|
923
|
+
const period = Number.isFinite(periodEnd) && periodEnd > 0 ? resetParts(periodEnd).absolute : null
|
|
924
|
+
if (period !== null) parts.push(tr('周期至 {time}', { time: period }))
|
|
925
|
+
if (provider.rateLimited === true) parts.push(tr('限流中'))
|
|
926
|
+
const usageUsd = Number(provider.channel?.usageUsd)
|
|
927
|
+
if (Number.isFinite(usageUsd)) parts.push(tr('渠道用量 {value}', { value: fmtMoney(usageUsd, provider.currency) }))
|
|
928
|
+
return parts.join(' · ')
|
|
929
|
+
}
|
|
930
|
+
|
|
892
931
|
function windowLabel(key) { return { '5h': '5h', week: tr('周'), month: tr('月') }[key] ?? key }
|
|
893
932
|
|
|
894
933
|
function subscriptionText(provider) {
|
|
@@ -960,12 +999,14 @@ window.__ModuleLoader__.load({
|
|
|
960
999
|
const [panelShift, setPanelShift] = useState(0)
|
|
961
1000
|
const pillRef = useRef(null)
|
|
962
1001
|
const panelRef = useRef(null)
|
|
1002
|
+
const lastLoadAt = useRef(0)
|
|
963
1003
|
|
|
964
1004
|
useEffect(() => {
|
|
965
1005
|
try { if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true) } catch { /* ignore */ }
|
|
966
1006
|
}, [])
|
|
967
1007
|
|
|
968
1008
|
const load = useCallback(async () => {
|
|
1009
|
+
lastLoadAt.current = Date.now()
|
|
969
1010
|
setRefreshing(true)
|
|
970
1011
|
try {
|
|
971
1012
|
const data = await getJson(summaryPath(active))
|
|
@@ -984,7 +1025,13 @@ window.__ModuleLoader__.load({
|
|
|
984
1025
|
}, [])
|
|
985
1026
|
|
|
986
1027
|
useEffect(() => { load() }, [load])
|
|
987
|
-
|
|
1028
|
+
// 展开即刷新:距上次拉取超过 2s 才发,避免开合抖动与 refreshMs 变化引起的重跑;可见期轮询缩到 10s
|
|
1029
|
+
useEffect(() => {
|
|
1030
|
+
if (!open) return
|
|
1031
|
+
if (Date.now() - lastLoadAt.current < 2000) return
|
|
1032
|
+
void load()
|
|
1033
|
+
}, [open, load])
|
|
1034
|
+
usePolling(load, { refreshMs: open ? Math.min(10_000, refreshMs) : refreshMs })
|
|
988
1035
|
|
|
989
1036
|
const refreshSubs = useCallback(async () => {
|
|
990
1037
|
try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* fall through */ }
|
|
@@ -1544,6 +1591,9 @@ window.__ModuleLoader__.load({
|
|
|
1544
1591
|
const used = Number(budget?.used ?? 0)
|
|
1545
1592
|
const plan = hasBudget ? Number(budget.amount) - used : null
|
|
1546
1593
|
const balance = balanceText(provider, true)
|
|
1594
|
+
// Ollama 这类「额度 + 购买余额」的 provider:进度只用 allowance / used,单值位不重复
|
|
1595
|
+
const allowance = Number(provider.balance?.allowance)
|
|
1596
|
+
const purchased = Number(provider.balance?.purchased)
|
|
1547
1597
|
const entry = prefs?.budgets?.[provider.id]
|
|
1548
1598
|
const initial = entry === undefined ? '' : (entry.amount > 0 ? entry.amount.toFixed(2) : '')
|
|
1549
1599
|
const error = errors[provider.id]
|
|
@@ -1599,12 +1649,37 @@ window.__ModuleLoader__.load({
|
|
|
1599
1649
|
h('div', { style: styles.kvRow },
|
|
1600
1650
|
h('span', { style: styles.kvLabel }, tr('真实余额')),
|
|
1601
1651
|
h('span', { 'data-testid': `token-dash-budget-balance-${provider.id}`, style: styles.kvValue }, balance ?? '—')),
|
|
1652
|
+
Number.isFinite(allowance) && allowance > 0
|
|
1653
|
+
? h('div', { style: styles.kvRow },
|
|
1654
|
+
h('span', { style: styles.kvLabel }, tr('套餐已用')),
|
|
1655
|
+
h('span', {
|
|
1656
|
+
'data-testid': `token-dash-budget-allowance-${provider.id}`,
|
|
1657
|
+
style: styles.kvValue,
|
|
1658
|
+
}, `${fmtMoney(provider.balance?.used, provider.currency)} / ${fmtMoney(allowance, provider.currency)}`))
|
|
1659
|
+
: null,
|
|
1660
|
+
Number.isFinite(purchased) && purchased > 0
|
|
1661
|
+
? h('div', { style: styles.kvRow },
|
|
1662
|
+
h('span', { style: styles.kvLabel }, tr('购买余额')),
|
|
1663
|
+
h('span', {
|
|
1664
|
+
'data-testid': `token-dash-budget-purchased-${provider.id}`,
|
|
1665
|
+
style: styles.kvValue,
|
|
1666
|
+
}, fmtMoney(purchased, provider.currency)))
|
|
1667
|
+
: null,
|
|
1602
1668
|
h('div', { style: styles.kvRow },
|
|
1603
1669
|
h('span', { style: styles.kvLabel }, tr('本月已花')),
|
|
1604
|
-
h('span', {
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1670
|
+
h('span', {
|
|
1671
|
+
'data-testid': `token-dash-budget-month-${provider.id}`,
|
|
1672
|
+
style: { ...styles.kvValue, display: 'inline-flex', alignItems: 'baseline', gap: 4 },
|
|
1673
|
+
},
|
|
1674
|
+
fmtMoney(provider.usage?.monthCost, provider.currency),
|
|
1675
|
+
provider.currencySource === 'community' && provider.currency === 'CNY'
|
|
1676
|
+
? h('span', {
|
|
1677
|
+
'data-testid': `token-dash-currency-source-${provider.id}`,
|
|
1678
|
+
title: tr('价格取社区价目表(人民币),与渠道账单可能有差异'),
|
|
1679
|
+
style: { fontSize: 10, color: T.weak },
|
|
1680
|
+
}, tr('按社区表 CNY'))
|
|
1681
|
+
: null)),
|
|
1682
|
+
h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
|
|
1608
1683
|
}))
|
|
1609
1684
|
}
|
|
1610
1685
|
|
|
@@ -1734,7 +1809,8 @@ window.__ModuleLoader__.load({
|
|
|
1734
1809
|
}, [loadSummary, loadPrefs, loadUsage])
|
|
1735
1810
|
|
|
1736
1811
|
useEffect(() => { void refresh() }, [refresh])
|
|
1737
|
-
|
|
1812
|
+
// 看板常驻,轮询周期取 min(10s, refreshMs);费用与明细来自 /usage,必须一起刷
|
|
1813
|
+
usePolling(() => { void loadSummary(); void loadUsage() }, { refreshMs: Math.min(10_000, Number(summary?.refreshMs) || 60000) })
|
|
1738
1814
|
|
|
1739
1815
|
const savePrefs = useCallback(async (patch) => {
|
|
1740
1816
|
if (prefsRef.current === null) return { ok: false, reason: 'not-ready' }
|
package/index.js
CHANGED
|
@@ -5,13 +5,14 @@ import { readFileSync } from 'node:fs'
|
|
|
5
5
|
import { existsSync } from 'node:fs'
|
|
6
6
|
import { spawn } from 'node:child_process'
|
|
7
7
|
import { dirname, join } from 'node:path'
|
|
8
|
-
import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, stampProviderKinds } from './src/core.js'
|
|
8
|
+
import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, repriceUnpriced, resolveProviderKind, stampProviderKinds } from './src/core.js'
|
|
9
9
|
import { ingest, backfill } from './src/collect.js'
|
|
10
|
-
import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
|
|
10
|
+
import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, normalizeCurrencyMap, normalizeOverrides, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
|
|
11
11
|
import { buildExport, mergeImportDays, validateBundle } from './src/backup.js'
|
|
12
|
-
import { logAdapterEvents, logAdapterFailures, readProviders, readSubscriptions } from './src/adapters.js'
|
|
12
|
+
import { logAdapterEvents, logAdapterFailures, missSignature, readProviders, readSubscriptions } from './src/adapters.js'
|
|
13
13
|
import { PROVIDER_SOURCES } from './src/quota-sources.js'
|
|
14
|
-
import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
14
|
+
import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
15
|
+
import { providerCurrency } from './src/providers.js'
|
|
15
16
|
import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
|
|
16
17
|
import { isNewer } from './src/version.js'
|
|
17
18
|
|
|
@@ -149,6 +150,8 @@ function normalizePrefs(input, base) {
|
|
|
149
150
|
billingModes: { ...(base.billingModes ?? {}) },
|
|
150
151
|
refreshMs: base.refreshMs,
|
|
151
152
|
showBalance: base.showBalance,
|
|
153
|
+
priceOverrides: normalizeOverrides(base.priceOverrides),
|
|
154
|
+
providerCurrency: normalizeCurrencyMap(base.providerCurrency),
|
|
152
155
|
}
|
|
153
156
|
if (input?.budgets !== undefined) {
|
|
154
157
|
if (input.budgets === null || typeof input.budgets !== 'object') throw new Error('invalid-budgets')
|
|
@@ -173,6 +176,13 @@ function normalizePrefs(input, base) {
|
|
|
173
176
|
prefs.refreshMs = refresh
|
|
174
177
|
}
|
|
175
178
|
if (input?.showBalance !== undefined) prefs.showBalance = input.showBalance === true
|
|
179
|
+
// 两个"仅认文件"的键:随 PUT /prefs 与导入一起透传,非法条目静默丢弃(不阻塞保存)
|
|
180
|
+
prefs.priceOverrides = input?.priceOverrides !== undefined
|
|
181
|
+
? normalizeOverrides(input.priceOverrides)
|
|
182
|
+
: normalizeOverrides(base.priceOverrides)
|
|
183
|
+
prefs.providerCurrency = input?.providerCurrency !== undefined
|
|
184
|
+
? normalizeCurrencyMap(input.providerCurrency)
|
|
185
|
+
: normalizeCurrencyMap(base.providerCurrency)
|
|
176
186
|
return prefs
|
|
177
187
|
}
|
|
178
188
|
|
|
@@ -198,11 +208,26 @@ export function apply(ctx) {
|
|
|
198
208
|
let prefs
|
|
199
209
|
let state
|
|
200
210
|
let providerCache = new Map()
|
|
201
|
-
let providerCacheMeta = { at: 0, hadProviders: false, degraded: false }
|
|
211
|
+
let providerCacheMeta = { at: 0, hadProviders: false, degraded: false, missSignature: null }
|
|
202
212
|
const cacheData = () => [...providerCache.values()].map((entry) => entry.data).filter((item) => item !== null && item !== undefined)
|
|
203
213
|
const clearProviderCache = () => {
|
|
204
214
|
providerCache.clear()
|
|
205
|
-
providerCacheMeta = { at: 0, hadProviders: false, degraded: false }
|
|
215
|
+
providerCacheMeta = { at: 0, hadProviders: false, degraded: false, missSignature: null }
|
|
216
|
+
}
|
|
217
|
+
const metaOf = (id) => cacheData().find((item) => item.id === id)
|
|
218
|
+
/** 形态判定:把当前快照交给 core,prefs / registry 的优先级由 core 决定。 */
|
|
219
|
+
const kindOf = (id) => resolveProviderKind(state, prefs, id, metaOf(id))
|
|
220
|
+
/** 币种判定:声明 > 快照 > registry(BND-10,不做换算)。 */
|
|
221
|
+
const currencyOf = (id) => prefs?.providerCurrency?.[id] ?? metaOf(id)?.currency ?? providerCurrency(id)
|
|
222
|
+
let pricingConfigLogged = ''
|
|
223
|
+
const applyPricingConfig = () => {
|
|
224
|
+
configurePricing({ overrides: prefs?.priceOverrides ?? {}, currencyOf })
|
|
225
|
+
const overrides = Object.keys(prefs?.priceOverrides ?? {}).length
|
|
226
|
+
const currencies = Object.keys(prefs?.providerCurrency ?? {}).length
|
|
227
|
+
const signature = `${overrides}/${currencies}`
|
|
228
|
+
if (signature === pricingConfigLogged) return // 启动期会被调用两次,日志只在变化时打
|
|
229
|
+
pricingConfigLogged = signature
|
|
230
|
+
logger.info('pricing', 'config', { overrides, currencies })
|
|
206
231
|
}
|
|
207
232
|
const ready = Promise.all([loadState(dir, logger), loadPrefs(dir, logger)]).then(([loadedState, loadedPrefs]) => {
|
|
208
233
|
state = loadedState ?? emptyState()
|
|
@@ -247,8 +272,29 @@ export function apply(ctx) {
|
|
|
247
272
|
.then((ok) => logger.info('pricing', 'router.loaded', { ok }))
|
|
248
273
|
.catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) })),
|
|
249
274
|
])
|
|
275
|
+
applyPricingConfig()
|
|
250
276
|
})
|
|
251
277
|
|
|
278
|
+
/** 有界就绪门:超时降级用当前表,绝不无限阻塞记账(RSK-05)。 */
|
|
279
|
+
let pricingSettled = false
|
|
280
|
+
function pricingGate() {
|
|
281
|
+
if (pricingSettled) return Promise.resolve()
|
|
282
|
+
let settled = false
|
|
283
|
+
return new Promise((resolve) => {
|
|
284
|
+
const finish = (degraded) => {
|
|
285
|
+
if (settled) return
|
|
286
|
+
settled = true
|
|
287
|
+
pricingSettled = true
|
|
288
|
+
if (degraded) logger.warn('pricing', 'ready', { waitedMs: 5000, source: 'timeout-degraded' })
|
|
289
|
+
resolve()
|
|
290
|
+
}
|
|
291
|
+
const timer = setTimeout(() => finish(true), 5000)
|
|
292
|
+
timer.unref?.()
|
|
293
|
+
// 表已就绪时同步收敛,并清掉定时器——否则孤儿定时器会在 5s 后误报降级
|
|
294
|
+
pricingReady.then(() => { clearTimeout(timer); finish(false) }, () => { clearTimeout(timer); finish(false) })
|
|
295
|
+
})
|
|
296
|
+
}
|
|
297
|
+
|
|
252
298
|
ctx.inject(['sessionPersistence'], (scoped) => {
|
|
253
299
|
ready
|
|
254
300
|
.then(async () => {
|
|
@@ -261,10 +307,17 @@ export function apply(ctx) {
|
|
|
261
307
|
}),
|
|
262
308
|
])
|
|
263
309
|
// 不丢聚合:先并回 1.0.3 迁移备份,再按日级 token 重算旧计价成本
|
|
310
|
+
applyPricingConfig()
|
|
264
311
|
const recovery = await recoverState(dir, state, logger)
|
|
265
|
-
|
|
312
|
+
// 旧计价模型(costVersion < 3)一次性重算,保留给 v2 历史数据
|
|
313
|
+
const repriced = repriceState(state, kindOf)
|
|
266
314
|
if (repriced.repriced) logger.info('boot', 'state.reprice', { rows: repriced.rows, recovered: recovery.recovered })
|
|
267
|
-
const result = await backfill(scoped, state)
|
|
315
|
+
const result = await backfill(scoped, state, kindOf)
|
|
316
|
+
// 启动补算:只补 priced=false,已计价 / 订阅 / 零消耗一律不动(REQ-09)
|
|
317
|
+
const unpriced = repriceUnpriced(state, {}, kindOf)
|
|
318
|
+
if (unpriced.rows > 0 || Object.values(unpriced.skipped).some((count) => count > 0)) {
|
|
319
|
+
logger.info('pricing', 'reprice', unpriced)
|
|
320
|
+
}
|
|
268
321
|
if (flushReady === undefined) {
|
|
269
322
|
await saveJson(dir, 'daily.json', state)
|
|
270
323
|
await saveMonths(dir, state)
|
|
@@ -280,9 +333,12 @@ export function apply(ctx) {
|
|
|
280
333
|
'session/event',
|
|
281
334
|
(session, event) => {
|
|
282
335
|
if (state === undefined) return
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
336
|
+
void pricingGate().then(() => {
|
|
337
|
+
if (state === undefined) return
|
|
338
|
+
const sessionId = session?.id ?? session?.header?.id ?? 'live'
|
|
339
|
+
const record = ingest(state, sessionId, event, num(session?.header?.seedLength), kindOf)
|
|
340
|
+
if (record !== undefined) flushReady?.schedule?.()
|
|
341
|
+
})
|
|
286
342
|
},
|
|
287
343
|
{ global: true },
|
|
288
344
|
)
|
|
@@ -297,6 +353,7 @@ export function apply(ctx) {
|
|
|
297
353
|
const data = await readProviders(scoped, prefs, providerCache)
|
|
298
354
|
const hadProviders = providerCacheMeta.hadProviders === true || data.length > 0
|
|
299
355
|
providerCacheMeta = {
|
|
356
|
+
...providerCacheMeta,
|
|
300
357
|
at: Date.now(),
|
|
301
358
|
hadProviders,
|
|
302
359
|
degraded: data.length === 0 && hadProviders,
|
|
@@ -310,7 +367,17 @@ export function apply(ctx) {
|
|
|
310
367
|
}
|
|
311
368
|
logAdapterEvents(logger, data)
|
|
312
369
|
logAdapterFailures(logger, data.failures)
|
|
313
|
-
|
|
370
|
+
// 只在探测清单变化时记一次:启动首轮必打,之后配 Key / 断网导致清单变动才再打,避免每轮刷屏
|
|
371
|
+
const signature = missSignature(data)
|
|
372
|
+
if (signature !== providerCacheMeta.missSignature) {
|
|
373
|
+
providerCacheMeta = { ...providerCacheMeta, missSignature: signature }
|
|
374
|
+
logger.info('provider', 'cache.state', {
|
|
375
|
+
entries: providerCache.size,
|
|
376
|
+
providers: data.length,
|
|
377
|
+
configured: data.map((item) => item.id),
|
|
378
|
+
misses: data.misses ?? [],
|
|
379
|
+
})
|
|
380
|
+
}
|
|
314
381
|
if (stampProviderKinds(state, data)) {
|
|
315
382
|
logger.info('provider', 'kind.stamp', { ids: Object.keys(state.providerKinds) })
|
|
316
383
|
flusher.schedule()
|
|
@@ -341,13 +408,25 @@ export function apply(ctx) {
|
|
|
341
408
|
try {
|
|
342
409
|
await ready
|
|
343
410
|
if (url.pathname === `${ROUTE_PREFIX}/summary` && req.method === 'GET') {
|
|
344
|
-
|
|
411
|
+
const startedAt = Date.now()
|
|
412
|
+
let probeMs = 0
|
|
413
|
+
if (Date.now() - providerCacheMeta.at > 5000) {
|
|
414
|
+
const probeStartedAt = Date.now()
|
|
415
|
+
await refreshProviderCache()
|
|
416
|
+
probeMs = Date.now() - probeStartedAt
|
|
417
|
+
}
|
|
345
418
|
const summary = buildSummary(state, prefs, Date.now(), cacheData())
|
|
346
419
|
summary.version = CURRENT_VERSION
|
|
347
420
|
summary.refreshMs = prefs.refreshMs
|
|
348
421
|
summary.providersDegraded = providerCacheMeta.degraded === true
|
|
349
422
|
summary.catalog = catalogInfo()
|
|
350
|
-
logger.info('vm', 'build', {
|
|
423
|
+
logger.info('vm', 'build', {
|
|
424
|
+
providers: summary.providers.length,
|
|
425
|
+
api: summary.providers.filter((item) => item.kind === 'api').length,
|
|
426
|
+
subscription: summary.providers.filter((item) => item.kind === 'subscription').length,
|
|
427
|
+
probeMs,
|
|
428
|
+
durationMs: Date.now() - startedAt,
|
|
429
|
+
})
|
|
351
430
|
json(res, 200, { ok: true, data: summary })
|
|
352
431
|
return
|
|
353
432
|
}
|
|
@@ -357,7 +436,13 @@ export function apply(ctx) {
|
|
|
357
436
|
json(res, 400, { ok: false, reason: 'invalid-range' })
|
|
358
437
|
return
|
|
359
438
|
}
|
|
360
|
-
|
|
439
|
+
const startedAt = Date.now()
|
|
440
|
+
let probeMs = 0
|
|
441
|
+
if (Date.now() - providerCacheMeta.at > 5000) {
|
|
442
|
+
const probeStartedAt = Date.now()
|
|
443
|
+
await refreshProviderCache()
|
|
444
|
+
probeMs = Date.now() - probeStartedAt
|
|
445
|
+
}
|
|
361
446
|
const usage = buildUsage(state, prefs, range, Date.now(), cacheData())
|
|
362
447
|
logger.info('vm', 'usage', {
|
|
363
448
|
range,
|
|
@@ -365,6 +450,8 @@ export function apply(ctx) {
|
|
|
365
450
|
billable: usage.models.filter((item) => item.billable === true).length,
|
|
366
451
|
tokens: usage.total.tokens,
|
|
367
452
|
currencies: Object.keys(usage.totals).length,
|
|
453
|
+
probeMs,
|
|
454
|
+
durationMs: Date.now() - startedAt,
|
|
368
455
|
})
|
|
369
456
|
json(res, 200, { ok: true, data: usage })
|
|
370
457
|
return
|
|
@@ -386,6 +473,19 @@ export function apply(ctx) {
|
|
|
386
473
|
json(res, 200, { ok: true, data: { refreshed: subs.map((item) => item.id) } })
|
|
387
474
|
return
|
|
388
475
|
}
|
|
476
|
+
if (url.pathname === `${ROUTE_PREFIX}/pricing/reprice` && req.method === 'POST') {
|
|
477
|
+
// 排障入口(无 UI):只补 priced=false,scope 缺省 = 全部
|
|
478
|
+
const scope = url.searchParams.get('scope')
|
|
479
|
+
if (scope !== null && scope !== 'all' && /^\d{4}-\d{2}$/.test(scope) === false) {
|
|
480
|
+
json(res, 400, { ok: false, reason: 'invalid-scope' })
|
|
481
|
+
return
|
|
482
|
+
}
|
|
483
|
+
const result = repriceUnpriced(state, scope === null || scope === 'all' ? {} : { month: scope }, kindOf)
|
|
484
|
+
await flusher.flush()
|
|
485
|
+
logger.info('pricing', 'reprice', result)
|
|
486
|
+
json(res, 200, { ok: true, data: result })
|
|
487
|
+
return
|
|
488
|
+
}
|
|
389
489
|
if (url.pathname === `${ROUTE_PREFIX}/export` && req.method === 'GET') {
|
|
390
490
|
const data = buildExport(state, prefs, Date.now(), cacheData())
|
|
391
491
|
logger.info('data', 'export', { month: data.month, days: Object.keys(data.days).length, models: data.usage.all.models.length })
|
|
@@ -486,7 +586,13 @@ export function apply(ctx) {
|
|
|
486
586
|
prefs = normalizePrefs(body, prefs)
|
|
487
587
|
await saveJson(dir, 'prefs.json', prefs)
|
|
488
588
|
clearProviderCache()
|
|
489
|
-
|
|
589
|
+
applyPricingConfig()
|
|
590
|
+
logger.info('boot', 'prefs.saved', {
|
|
591
|
+
budgets: Object.keys(prefs.budgets).length,
|
|
592
|
+
modes: Object.keys(prefs.billingModes).length,
|
|
593
|
+
overrides: Object.keys(prefs.priceOverrides).length,
|
|
594
|
+
currencies: Object.keys(prefs.providerCurrency).length,
|
|
595
|
+
})
|
|
490
596
|
json(res, 200, { ok: true, data: prefs })
|
|
491
597
|
return
|
|
492
598
|
}
|
package/locale/en.json
CHANGED
|
@@ -106,5 +106,17 @@
|
|
|
106
106
|
"{name} · {action} Token 看板": "{name} · {action} Token dashboard",
|
|
107
107
|
"{name} 月度预算": "{name} monthly budget",
|
|
108
108
|
"{name},按量 API,{budget},今日 {today}{balance}": "{name}, pay-as-you-go, {budget}, today {today}{balance}",
|
|
109
|
-
"{name},订阅,账户套餐,{value}": "{name}, subscription, account plan, {value}"
|
|
109
|
+
"{name},订阅,账户套餐,{value}": "{name}, subscription, account plan, {value}",
|
|
110
|
+
"按社区表 CNY": "Community table (CNY)",
|
|
111
|
+
"价格取社区价目表(人民币),与渠道账单可能有差异": "Priced from the community table (CNY); may differ from your provider bill",
|
|
112
|
+
"无匹配价目": "No matching price",
|
|
113
|
+
"候选模型不唯一": "Ambiguous model match",
|
|
114
|
+
"模型名无效": "Invalid model name",
|
|
115
|
+
"订阅不计价": "Subscription, not billed",
|
|
116
|
+
"套餐已用": "Plan used",
|
|
117
|
+
"购买余额": "Purchased credits",
|
|
118
|
+
"周期至 {time}": "Cycle ends {time}",
|
|
119
|
+
"限流中": "Rate limited",
|
|
120
|
+
"渠道用量 {value}": "Channel usage {value}",
|
|
121
|
+
"价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "Price table is CNY while this provider bills in USD; add a USD priceOverrides entry"
|
|
110
122
|
}
|
package/locale/zh.json
CHANGED
|
@@ -106,5 +106,17 @@
|
|
|
106
106
|
"{name} · {action} Token 看板": "{name} · {action} Token 看板",
|
|
107
107
|
"{name} 月度预算": "{name} 月度预算",
|
|
108
108
|
"{name},按量 API,{budget},今日 {today}{balance}": "{name},按量 API,{budget},今日 {today}{balance}",
|
|
109
|
-
"{name},订阅,账户套餐,{value}": "{name},订阅,账户套餐,{value}"
|
|
109
|
+
"{name},订阅,账户套餐,{value}": "{name},订阅,账户套餐,{value}",
|
|
110
|
+
"按社区表 CNY": "按社区表 CNY",
|
|
111
|
+
"价格取社区价目表(人民币),与渠道账单可能有差异": "价格取社区价目表(人民币),与渠道账单可能有差异",
|
|
112
|
+
"无匹配价目": "无匹配价目",
|
|
113
|
+
"候选模型不唯一": "候选模型不唯一",
|
|
114
|
+
"模型名无效": "模型名无效",
|
|
115
|
+
"订阅不计价": "订阅不计价",
|
|
116
|
+
"套餐已用": "套餐已用",
|
|
117
|
+
"购买余额": "购买余额",
|
|
118
|
+
"周期至 {time}": "周期至 {time}",
|
|
119
|
+
"限流中": "限流中",
|
|
120
|
+
"渠道用量 {value}": "渠道用量 {value}",
|
|
121
|
+
"价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价"
|
|
110
122
|
}
|