dsh-token-dash 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +72 -0
- package/LICENSE +21 -0
- package/README.en.md +169 -0
- package/README.md +192 -2
- package/client.js +752 -0
- package/cordis.patch.yml +5 -0
- package/doc/pic/panel-dashboard.png +0 -0
- package/doc/pic/pill-home.png +0 -0
- package/doc/pic/pill-session.png +0 -0
- package/doc/pic/settings.png +0 -0
- package/index.js +342 -0
- package/locale/en.json +8 -0
- package/locale/zh.json +8 -0
- package/package.json +64 -4
- package/src/adapters.js +297 -0
- package/src/catalog.json +154 -0
- package/src/collect.js +103 -0
- package/src/core.js +399 -0
- package/src/diagnostics.js +113 -0
- package/src/pricing.js +241 -0
- package/src/providers.js +129 -0
- package/src/store.js +127 -0
package/src/pricing.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Price catalog: bundled catalog.json, optional community feed and
|
|
3
|
+
* OpenRouter /models overrides. Pure matching logic is separated from I/O.
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync } from 'node:fs'
|
|
6
|
+
import { normalizeModel, normalizeProvider, providerCurrency } from './providers.js'
|
|
7
|
+
|
|
8
|
+
const BUNDLED = JSON.parse(readFileSync(new URL('./catalog.json', import.meta.url), 'utf8'))
|
|
9
|
+
const GITEE = 'https://gitee.com/oyw125/model-price-table/raw/master/model_pricing.json'
|
|
10
|
+
const GITHUB = 'https://raw.githubusercontent.com/LaoYueHanNi/model-price-table/master/model_pricing.json'
|
|
11
|
+
const ROUTER = 'https://openrouter.ai/api/v1/models'
|
|
12
|
+
|
|
13
|
+
let catalog = normalizeCatalog(BUNDLED)
|
|
14
|
+
let catalogUpdatedAt = BUNDLED.updatedAt ?? null
|
|
15
|
+
let catalogSource = 'bundled'
|
|
16
|
+
let routerPrices = null
|
|
17
|
+
let communityCache = { at: 0, value: null }
|
|
18
|
+
|
|
19
|
+
function finite(value) {
|
|
20
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function pricesOf(raw) {
|
|
24
|
+
return {
|
|
25
|
+
input: finite(raw?.input),
|
|
26
|
+
cacheRead: finite(raw?.cacheRead) ?? 0,
|
|
27
|
+
cacheWrite: finite(raw?.cacheWrite) ?? 0,
|
|
28
|
+
output: finite(raw?.output),
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function normalizeEntry(raw) {
|
|
33
|
+
const provider = normalizeProvider(raw?.provider)
|
|
34
|
+
const model = normalizeModel(raw?.model)
|
|
35
|
+
if (provider === 'unknown' || model === 'unknown') return null
|
|
36
|
+
const currency = raw?.currency === 'USD' ? 'USD' : (raw?.currency === 'CNY' || raw?.currency === 'RMB' ? 'CNY' : providerCurrency(provider))
|
|
37
|
+
const prices = raw?.prices !== undefined ? pricesOf(raw.prices) : pricesOf(raw)
|
|
38
|
+
const peak = raw?.peak !== undefined ? pricesOf(raw.peak) : null
|
|
39
|
+
const offPeak = raw?.offPeak !== undefined ? pricesOf(raw.offPeak) : null
|
|
40
|
+
const hasFlat = prices.input !== null && prices.output !== null
|
|
41
|
+
const hasTiers = peak !== null && offPeak !== null && peak.input !== null && peak.output !== null && offPeak.input !== null && offPeak.output !== null
|
|
42
|
+
if (!hasFlat && !hasTiers) return null
|
|
43
|
+
return {
|
|
44
|
+
provider,
|
|
45
|
+
model,
|
|
46
|
+
displayName: String(raw?.displayName ?? model),
|
|
47
|
+
family: String(raw?.family ?? model),
|
|
48
|
+
releasedAt: String(raw?.releasedAt ?? raw?.updatedAt ?? ''),
|
|
49
|
+
currency,
|
|
50
|
+
aliases: Array.isArray(raw?.aliases) ? raw.aliases.map((alias) => normalizeModel(alias)) : [],
|
|
51
|
+
prices: peak !== null && offPeak !== null ? null : prices,
|
|
52
|
+
peak,
|
|
53
|
+
offPeak,
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function normalizeCatalog(raw) {
|
|
58
|
+
const models = []
|
|
59
|
+
for (const item of Array.isArray(raw?.models) ? raw.models : []) {
|
|
60
|
+
const entry = normalizeEntry(item)
|
|
61
|
+
if (entry !== null) models.push(entry)
|
|
62
|
+
}
|
|
63
|
+
return { models }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function allEntries() {
|
|
67
|
+
return [...catalog.models, ...(routerPrices?.models ?? [])]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function exactEntry(provider, model) {
|
|
71
|
+
return allEntries().find((entry) => entry.provider === provider && entry.model === model) ?? null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function aliasEntry(provider, model) {
|
|
75
|
+
return allEntries().find((entry) => entry.provider === provider && entry.aliases.includes(model)) ?? null
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function familyEntry(provider, model) {
|
|
79
|
+
const candidates = allEntries().filter((entry) => entry.provider === provider && entry.family !== '' && model.startsWith(entry.family))
|
|
80
|
+
if (candidates.length === 0) return null
|
|
81
|
+
return candidates.sort((left, right) => String(right.releasedAt).localeCompare(String(left.releasedAt)))[0]
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function effectivePrices(entry, ts) {
|
|
85
|
+
if (entry.peak !== null && entry.offPeak !== null) {
|
|
86
|
+
const hour = new Date(ts + 8 * 60 * 60 * 1000).getUTCHours()
|
|
87
|
+
const peak = (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
|
|
88
|
+
return peak ? entry.peak : entry.offPeak
|
|
89
|
+
}
|
|
90
|
+
return entry.prices
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Resolve one price. Returns null when no exact, alias or same-family entry.
|
|
95
|
+
* `approximate` is true only for same-family fallback.
|
|
96
|
+
*/
|
|
97
|
+
export function priceFor(provider, model, ts = Date.now()) {
|
|
98
|
+
const providerId = normalizeProvider(provider)
|
|
99
|
+
const modelId = normalizeModel(model)
|
|
100
|
+
const exact = exactEntry(providerId, modelId)
|
|
101
|
+
if (exact !== null) {
|
|
102
|
+
const prices = effectivePrices(exact, ts)
|
|
103
|
+
return { ...prices, currency: exact.currency, approximate: false, source: catalogSource, catalogModel: exact.model }
|
|
104
|
+
}
|
|
105
|
+
const alias = aliasEntry(providerId, modelId)
|
|
106
|
+
if (alias !== null) {
|
|
107
|
+
const prices = effectivePrices(alias, ts)
|
|
108
|
+
return { ...prices, currency: alias.currency, approximate: false, source: catalogSource, catalogModel: alias.model }
|
|
109
|
+
}
|
|
110
|
+
const family = familyEntry(providerId, modelId)
|
|
111
|
+
if (family !== null) {
|
|
112
|
+
const prices = effectivePrices(family, ts)
|
|
113
|
+
return { ...prices, currency: family.currency, approximate: true, source: catalogSource, catalogModel: family.model }
|
|
114
|
+
}
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function catalogInfo() {
|
|
119
|
+
return { source: catalogSource, updatedAt: catalogUpdatedAt, models: allEntries().length }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function setCatalogForTests(models) {
|
|
123
|
+
catalog = normalizeCatalog({ models })
|
|
124
|
+
catalogSource = 'test'
|
|
125
|
+
catalogUpdatedAt = null
|
|
126
|
+
routerPrices = null
|
|
127
|
+
communityCache = { at: 0, value: null }
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function remoteEntry(raw) {
|
|
131
|
+
return normalizeEntry({
|
|
132
|
+
provider: raw.provider ?? raw.family ?? 'unknown',
|
|
133
|
+
model: raw.modelId ?? raw.model,
|
|
134
|
+
displayName: raw.displayName ?? raw.modelId ?? raw.model,
|
|
135
|
+
family: raw.family ?? '',
|
|
136
|
+
releasedAt: raw.releasedAt ?? raw.updatedAt ?? '',
|
|
137
|
+
currency: raw.currency === 'RMB' ? 'CNY' : raw.currency,
|
|
138
|
+
input: raw.input ?? raw.inputCostPerMillion,
|
|
139
|
+
cacheRead: raw.cacheRead ?? raw.cacheReadCostPerMillion,
|
|
140
|
+
cacheWrite: raw.cacheWrite ?? raw.cacheCreationCostPerMillion,
|
|
141
|
+
output: raw.output ?? raw.outputCostPerMillion,
|
|
142
|
+
aliases: Array.isArray(raw.aliases) ? raw.aliases : [],
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function fetchJson(url, timeoutMs = 6000) {
|
|
147
|
+
const response = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) })
|
|
148
|
+
if (!response.ok) throw new Error(`http-${response.status}`)
|
|
149
|
+
return response.json()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Load community catalog; Gitee first, GitHub second. Never throws. */
|
|
153
|
+
export async function loadCommunityPricing({ force = false } = {}) {
|
|
154
|
+
if (!force && communityCache.value !== null && Date.now() - communityCache.at < 24 * 3600 * 1000) return communityCache.value
|
|
155
|
+
for (const url of [GITEE, GITHUB]) {
|
|
156
|
+
try {
|
|
157
|
+
const raw = await fetchJson(url)
|
|
158
|
+
const parsed = normalizeCatalog({
|
|
159
|
+
models: (Array.isArray(raw?.models) ? raw.models : []).map((item) => {
|
|
160
|
+
const normalized = remoteEntry({ ...item, provider: item.provider ?? inferProvider(item.modelId) })
|
|
161
|
+
return normalized === null ? null : {
|
|
162
|
+
provider: normalized.provider,
|
|
163
|
+
model: normalized.model,
|
|
164
|
+
displayName: normalized.displayName,
|
|
165
|
+
family: normalized.family,
|
|
166
|
+
releasedAt: normalized.releasedAt,
|
|
167
|
+
currency: normalized.currency,
|
|
168
|
+
aliases: normalized.aliases,
|
|
169
|
+
prices: normalized.prices,
|
|
170
|
+
peak: normalized.peak,
|
|
171
|
+
offPeak: normalized.offPeak,
|
|
172
|
+
}
|
|
173
|
+
}).filter(Boolean),
|
|
174
|
+
})
|
|
175
|
+
if (parsed.models.length === 0) throw new Error('empty-catalog')
|
|
176
|
+
catalog = parsed
|
|
177
|
+
catalogSource = url === GITEE ? 'community-gitee' : 'community-github'
|
|
178
|
+
catalogUpdatedAt = raw?.updatedAt === undefined ? null : String(raw.updatedAt)
|
|
179
|
+
communityCache = { at: Date.now(), value: catalogInfo() }
|
|
180
|
+
return catalogInfo()
|
|
181
|
+
} catch {
|
|
182
|
+
// try next mirror, then bundled
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return catalogInfo()
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function inferProvider(modelId) {
|
|
189
|
+
const id = String(modelId ?? '').toLowerCase()
|
|
190
|
+
if (id.includes('glm')) return 'zhipu'
|
|
191
|
+
if (id.includes('kimi')) return 'moonshot'
|
|
192
|
+
if (id.includes('qwen')) return 'qwen'
|
|
193
|
+
if (id.includes('deepseek')) return 'deepseek-official'
|
|
194
|
+
return 'unknown'
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** OpenRouter public model prices; used only for provider=openrouter. */
|
|
198
|
+
export async function loadRouterPricing() {
|
|
199
|
+
try {
|
|
200
|
+
const raw = await fetchJson(ROUTER)
|
|
201
|
+
const models = []
|
|
202
|
+
for (const item of Array.isArray(raw?.data) ? raw.data : []) {
|
|
203
|
+
const prices = item?.pricing
|
|
204
|
+
const input = Number(prices?.prompt)
|
|
205
|
+
const output = Number(prices?.completion)
|
|
206
|
+
if (!Number.isFinite(input) || !Number.isFinite(output)) continue
|
|
207
|
+
models.push({
|
|
208
|
+
provider: 'openrouter',
|
|
209
|
+
model: normalizeModel(item.id),
|
|
210
|
+
displayName: String(item.name ?? item.id),
|
|
211
|
+
family: String(item.id).split('/')[0] ?? '',
|
|
212
|
+
releasedAt: '',
|
|
213
|
+
currency: 'USD',
|
|
214
|
+
aliases: [],
|
|
215
|
+
prices: {
|
|
216
|
+
input: input * 1_000_000,
|
|
217
|
+
cacheRead: Number(prices?.input_cache_read ?? 0) * 1_000_000,
|
|
218
|
+
cacheWrite: Number(prices?.input_cache_write ?? 0) * 1_000_000,
|
|
219
|
+
output: output * 1_000_000,
|
|
220
|
+
},
|
|
221
|
+
peak: null,
|
|
222
|
+
offPeak: null,
|
|
223
|
+
})
|
|
224
|
+
}
|
|
225
|
+
if (models.length > 0) {
|
|
226
|
+
routerPrices = { models }
|
|
227
|
+
return true
|
|
228
|
+
}
|
|
229
|
+
} catch {
|
|
230
|
+
// keep bundled/community
|
|
231
|
+
}
|
|
232
|
+
return false
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export function resetPricingForTests() {
|
|
236
|
+
catalog = normalizeCatalog(BUNDLED)
|
|
237
|
+
catalogUpdatedAt = BUNDLED.updatedAt ?? null
|
|
238
|
+
catalogSource = 'bundled'
|
|
239
|
+
routerPrices = null
|
|
240
|
+
communityCache = { at: 0, value: null }
|
|
241
|
+
}
|
package/src/providers.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider identity, billing mode and currency.
|
|
3
|
+
* Pure functions only; no I/O.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const ALIASES = {
|
|
7
|
+
'deepseek-account': 'deepseek-official',
|
|
8
|
+
'deepseek-official': 'deepseek-official',
|
|
9
|
+
deepseek: 'deepseek-official',
|
|
10
|
+
glm: 'zhipu',
|
|
11
|
+
zhipu: 'zhipu',
|
|
12
|
+
'z.ai': 'zhipu',
|
|
13
|
+
'zai-coding': 'zhipu',
|
|
14
|
+
'zai-coding-cn': 'zhipu',
|
|
15
|
+
kimi: 'moonshot',
|
|
16
|
+
moonshot: 'moonshot',
|
|
17
|
+
'kimi-coding': 'moonshot',
|
|
18
|
+
qwen: 'qwen',
|
|
19
|
+
dashscope: 'qwen',
|
|
20
|
+
aliyun: 'qwen',
|
|
21
|
+
tongyi: 'qwen',
|
|
22
|
+
openrouter: 'openrouter',
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const NAMES = {
|
|
26
|
+
'deepseek-official': 'DeepSeek 官方',
|
|
27
|
+
zhipu: '智谱 AI',
|
|
28
|
+
moonshot: 'Kimi',
|
|
29
|
+
qwen: '通义千问',
|
|
30
|
+
openrouter: 'OpenRouter',
|
|
31
|
+
unknown: '未知来源',
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const SUBSCRIPTION = new Set(['zhipu', 'moonshot'])
|
|
35
|
+
const CURRENCY = {
|
|
36
|
+
'deepseek-official': 'CNY',
|
|
37
|
+
zhipu: 'CNY',
|
|
38
|
+
moonshot: 'CNY',
|
|
39
|
+
qwen: 'CNY',
|
|
40
|
+
openrouter: 'USD',
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function normalizeProvider(raw) {
|
|
44
|
+
const id = String(raw ?? '').trim().toLowerCase()
|
|
45
|
+
if (id === '') return 'unknown'
|
|
46
|
+
return ALIASES[id] ?? id
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function providerLabel(raw) {
|
|
50
|
+
const id = normalizeProvider(raw)
|
|
51
|
+
return NAMES[id] ?? id
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function isSupportedProvider(raw) {
|
|
55
|
+
return Object.prototype.hasOwnProperty.call(NAMES, normalizeProvider(raw)) && normalizeProvider(raw) !== 'unknown'
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function providerCurrency(raw) {
|
|
59
|
+
return CURRENCY[normalizeProvider(raw)] ?? 'CNY'
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function canBeSubscription(raw) {
|
|
63
|
+
return SUBSCRIPTION.has(normalizeProvider(raw))
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function providerKind(raw, mode) {
|
|
67
|
+
const id = normalizeProvider(raw)
|
|
68
|
+
if (mode === 'api' || mode === 'subscription') return mode
|
|
69
|
+
return canBeSubscription(id) ? 'subscription' : 'api'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** #41:模型名前缀 → provider 归因(DSH 会话事件无 provider 标注时,unknown 行按此兜底归属)。 */
|
|
73
|
+
const MODEL_OWNER_RULES = [
|
|
74
|
+
[/^deepseek/, 'deepseek-official'],
|
|
75
|
+
[/^glm/, 'zhipu'],
|
|
76
|
+
[/^kimi|^moonshot/, 'moonshot'],
|
|
77
|
+
[/^qwen/, 'qwen'],
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
export function providerFromModel(modelId) {
|
|
81
|
+
const id = normalizeModel(modelId)
|
|
82
|
+
if (id === 'unknown') return null
|
|
83
|
+
for (const [pattern, owner] of MODEL_OWNER_RULES) {
|
|
84
|
+
if (pattern.test(id)) return owner
|
|
85
|
+
}
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** #44/#45:已配置 provider 的默认模型——明细表在本月无真实消耗行时补一行(数值 0),保证"配置即可见"。
|
|
90
|
+
* OpenRouter 为中转无默认模型:值为 '-' 表示占位行(OpenRouter / -),该 provider 出现任何真实模型行后不再补。 */
|
|
91
|
+
export const DEFAULT_MODELS = {
|
|
92
|
+
'deepseek-official': 'deepseek-v4.1-flash',
|
|
93
|
+
zhipu: 'glm-5.3',
|
|
94
|
+
moonshot: 'kimi-k3',
|
|
95
|
+
qwen: 'qwen3.8-max',
|
|
96
|
+
openrouter: '-',
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function modelLabel(raw) {
|
|
100
|
+
const id = normalizeModel(raw)
|
|
101
|
+
const labels = {
|
|
102
|
+
'deepseek-flash': 'DeepSeek-V4.1-Flash',
|
|
103
|
+
'deepseek-v4.1-flash': 'DeepSeek-V4.1-Flash',
|
|
104
|
+
'deepseek-v4-flash': 'DeepSeek-V4.1-Flash',
|
|
105
|
+
'deepseek-pro': 'DeepSeek-V4.1-Pro',
|
|
106
|
+
'deepseek-v4-pro': 'DeepSeek-V4.1-Pro',
|
|
107
|
+
'glm-5.3': 'GLM-5.3',
|
|
108
|
+
'glm-5.3-flash': 'GLM-5.3-Flash',
|
|
109
|
+
'kimi-k3': 'Kimi K3',
|
|
110
|
+
'kimi-k3.1-pro': 'Kimi K3.1 Pro',
|
|
111
|
+
'kimi-k2.7-code': 'Kimi K2.7 Code',
|
|
112
|
+
'qwen3.8-max': 'Qwen3.8-Max',
|
|
113
|
+
'qwen3.8-flash': 'Qwen3.8-Flash',
|
|
114
|
+
}
|
|
115
|
+
return labels[id] ?? id
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Only folds casing/provider prefix/date suffixes; never merges generations. */
|
|
119
|
+
export function normalizeModel(raw) {
|
|
120
|
+
let name = String(raw ?? '').trim().toLowerCase()
|
|
121
|
+
if (name === '') return 'unknown'
|
|
122
|
+
name = name.replace(/^[^/]+\//, '')
|
|
123
|
+
name = name.replace(/@/g, '-')
|
|
124
|
+
name = name.replace(/-free\b/g, '')
|
|
125
|
+
name = name.replace(/-\d{4}-\d{2}-\d{2}\b/g, '')
|
|
126
|
+
name = name.replace(/-\d{8}\b/g, '')
|
|
127
|
+
name = name.replace(/\s+/g, '-')
|
|
128
|
+
return name === '' ? 'unknown' : name
|
|
129
|
+
}
|
package/src/store.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { homedir } from 'node:os'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { emptyState } from './core.js'
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_PREFS = {
|
|
7
|
+
version: 1,
|
|
8
|
+
budget: { amount: 3500, currency: 'CNY' },
|
|
9
|
+
budgets: {},
|
|
10
|
+
billingModes: {},
|
|
11
|
+
refreshMs: 60000,
|
|
12
|
+
showBalance: true,
|
|
13
|
+
showMonthTokens: true,
|
|
14
|
+
logLevel: 'info',
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function resolveHome(ctx) {
|
|
18
|
+
try {
|
|
19
|
+
const fn = ctx.get?.('dshHomePath')
|
|
20
|
+
if (typeof fn === 'function') {
|
|
21
|
+
const value = fn()
|
|
22
|
+
if (typeof value === 'string' && value.trim() !== '') return value
|
|
23
|
+
}
|
|
24
|
+
} catch {
|
|
25
|
+
// fall through
|
|
26
|
+
}
|
|
27
|
+
const env = process.env.DSH_HOME
|
|
28
|
+
if (typeof env === 'string' && env.trim() !== '') return env
|
|
29
|
+
return join(homedir(), '.dsh')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function dataDir(ctx) {
|
|
33
|
+
return join(resolveHome(ctx), 'dsh-token-dash')
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function logsDir(ctx) {
|
|
37
|
+
return join(resolveHome(ctx), 'logs', 'dsh-token-dash')
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function readJson(file, fallback, onCorrupt) {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(await readFile(file, 'utf8'))
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error?.code === 'ENOENT') return fallback
|
|
45
|
+
const backup = `${file}.corrupt-${Date.now()}`
|
|
46
|
+
try {
|
|
47
|
+
await rename(file, backup)
|
|
48
|
+
} catch {
|
|
49
|
+
// ignore
|
|
50
|
+
}
|
|
51
|
+
// #47:损坏文件不再静默丢弃——报障时日志可还原"数据为何重置"
|
|
52
|
+
if (typeof onCorrupt === 'function') onCorrupt(file, backup, error)
|
|
53
|
+
return fallback
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function loadState(dir, logger) {
|
|
58
|
+
await mkdir(dir, { recursive: true })
|
|
59
|
+
const state = await readJson(join(dir, 'daily.json'), emptyState(), (file, backup) => {
|
|
60
|
+
logger?.warn('boot', 'state.corrupt', { file, backup })
|
|
61
|
+
})
|
|
62
|
+
if (state?.version !== 1 || typeof state.days !== 'object') return emptyState()
|
|
63
|
+
for (const bucket of Object.values(state.days)) {
|
|
64
|
+
if (bucket === null || typeof bucket !== 'object') continue
|
|
65
|
+
if (bucket.providers === undefined) {
|
|
66
|
+
bucket.providers = { unknown: { models: bucket.models ?? {} } }
|
|
67
|
+
delete bucket.models
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
state.watermarks ??= {}
|
|
71
|
+
state.headers ??= {}
|
|
72
|
+
state.currentProvider ??= null
|
|
73
|
+
return state
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function loadPrefs(dir, logger) {
|
|
77
|
+
const prefs = await readJson(join(dir, 'prefs.json'), DEFAULT_PREFS, (file, backup) => {
|
|
78
|
+
logger?.warn('boot', 'state.corrupt', { file, backup })
|
|
79
|
+
})
|
|
80
|
+
return {
|
|
81
|
+
...DEFAULT_PREFS,
|
|
82
|
+
...prefs,
|
|
83
|
+
budget: { ...DEFAULT_PREFS.budget, ...(prefs?.budget ?? {}) },
|
|
84
|
+
budgets: { ...(prefs?.budgets ?? {}) },
|
|
85
|
+
billingModes: { ...(prefs?.billingModes ?? {}) },
|
|
86
|
+
logLevel: prefs?.logLevel === 'debug' ? 'debug' : 'info',
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function saveJson(dir, name, value) {
|
|
91
|
+
await mkdir(dir, { recursive: true })
|
|
92
|
+
const file = join(dir, name)
|
|
93
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
94
|
+
await writeFile(tmp, JSON.stringify(value), 'utf8')
|
|
95
|
+
await rename(tmp, file)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function createFlusher(dir, state, delay = 2000, logger) {
|
|
99
|
+
let timer
|
|
100
|
+
let saving
|
|
101
|
+
const flush = async () => {
|
|
102
|
+
if (saving !== undefined) return saving
|
|
103
|
+
saving = saveJson(dir, 'daily.json', state)
|
|
104
|
+
.catch((error) => {
|
|
105
|
+
// #47:写盘失败不再静默——数据丢失报障的关键线索
|
|
106
|
+
logger?.warn('collect', 'state.write-fail', { message: String(error?.message ?? error) })
|
|
107
|
+
})
|
|
108
|
+
.finally(() => {
|
|
109
|
+
saving = undefined
|
|
110
|
+
})
|
|
111
|
+
return saving
|
|
112
|
+
}
|
|
113
|
+
const schedule = () => {
|
|
114
|
+
clearTimeout(timer)
|
|
115
|
+
timer = setTimeout(() => {
|
|
116
|
+
void flush()
|
|
117
|
+
}, delay)
|
|
118
|
+
timer.unref?.()
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
schedule,
|
|
122
|
+
flush,
|
|
123
|
+
stop() {
|
|
124
|
+
clearTimeout(timer)
|
|
125
|
+
},
|
|
126
|
+
}
|
|
127
|
+
}
|