dsh-token-dash 2.0.2 → 2.2.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.
@@ -8,6 +8,8 @@ const TIMEOUT = 6000
8
8
  export const OPENCODE_USAGE = 'https://opencode.ai/zen/go/v1/usage'
9
9
  export const OPENCODE_USAGE_FALLBACK = 'https://opencode.ai/api/v1/usage'
10
10
  export const COMMAND_CODE_CREDITS = 'https://api.commandcode.ai/alpha/billing/credits'
11
+ export const OLLAMA_BALANCE = 'https://ollama.com/api/balance'
12
+ export const OLLAMA_USAGE = 'https://ollama.com/api/usage'
11
13
 
12
14
  function clampPercent(value) {
13
15
  const n = Number(value)
@@ -97,6 +99,97 @@ export function parseCommandCodeCredits(body) {
97
99
  return { windows, balance }
98
100
  }
99
101
 
102
+ function round2(value) {
103
+ return Math.round(value * 100) / 100
104
+ }
105
+
106
+ function round6(value) {
107
+ return Math.round(value * 1e6) / 1e6
108
+ }
109
+
110
+ /** 旧套餐窗口:只有剩余百分比与重置时间,没有金额。 */
111
+ function legacyWindow(key, raw) {
112
+ if (raw === null || raw === undefined || typeof raw !== 'object') return null
113
+ const remaining = pickNumber(raw.remaining_percent)
114
+ if (remaining === null) return null
115
+ const resetAt = Date.parse(raw.resets_at)
116
+ return {
117
+ key,
118
+ usedPercent: round2(clampPercent(100 - remaining)),
119
+ resetAt: Number.isFinite(resetAt) ? resetAt : undefined,
120
+ source: 'official',
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Ollama Cloud:`included` 是 oneOf 二态——金额态(balance_usd / allowance_usd / period)
126
+ * 与旧套餐态(session / weekly 百分比)。`purchased` 恒有,只含未过期额度。
127
+ * 金额态 `amount` = 套餐剩余 + 购买余额,`used` 只用于套餐进度,不做分母混用。
128
+ */
129
+ export function parseOllamaBalance(body) {
130
+ const data = body?.data ?? body
131
+ const included = data?.included
132
+ const purchased = pickNumber(data?.purchased?.balance_usd)
133
+ const updatedAt = Date.now()
134
+ if (included === null || included === undefined || typeof included !== 'object') {
135
+ return { windows: [], balance: { amount: null, status: 'error', currency: 'USD', updatedAt, _error: { kind: 'parse' } } }
136
+ }
137
+ if (included.session !== undefined || included.weekly !== undefined) {
138
+ const windows = []
139
+ const session = legacyWindow('session', included.session)
140
+ const weekly = legacyWindow('week', included.weekly)
141
+ if (session !== null) windows.push(session)
142
+ if (weekly !== null) windows.push(weekly)
143
+ return {
144
+ windows,
145
+ balance: {
146
+ amount: purchased ?? 0,
147
+ ...(purchased === null ? {} : { purchased }),
148
+ legacy: true,
149
+ status: 'ok',
150
+ currency: 'USD',
151
+ updatedAt,
152
+ },
153
+ }
154
+ }
155
+ const left = pickNumber(included.balance_usd)
156
+ const allowance = pickNumber(included.allowance_usd)
157
+ if (left === null || allowance === null) {
158
+ return { windows: [], balance: { amount: null, status: 'error', currency: 'USD', updatedAt, _error: { kind: 'parse' } } }
159
+ }
160
+ const periodEnd = Date.parse(included.period?.until)
161
+ return {
162
+ windows: [],
163
+ balance: {
164
+ amount: round6(left + (purchased ?? 0)),
165
+ packageLeft: left,
166
+ allowance,
167
+ used: round6(Math.max(0, allowance - left)),
168
+ ...(purchased === null ? {} : { purchased }),
169
+ ...(Number.isFinite(periodEnd) ? { periodEnd } : {}),
170
+ status: 'ok',
171
+ currency: 'USD',
172
+ updatedAt,
173
+ },
174
+ }
175
+ }
176
+
177
+ /** `/api/usage` 只读参考:仅取 totals,缺失字段留 null,不参与任何计价。 */
178
+ export function parseOllamaUsage(body) {
179
+ const totals = body?.totals
180
+ if (totals === null || totals === undefined || typeof totals !== 'object') return {}
181
+ return {
182
+ channel: {
183
+ range: typeof body?.range === 'string' ? body.range : null,
184
+ usageUsd: pickNumber(totals.usage_usd),
185
+ requests: pickNumber(totals.request_count),
186
+ inputTokens: pickNumber(totals.input_tokens),
187
+ cachedInputTokens: pickNumber(totals.cached_input_tokens),
188
+ outputTokens: pickNumber(totals.output_tokens),
189
+ },
190
+ }
191
+ }
192
+
100
193
  export const PROVIDER_SOURCES = [
101
194
  { id: 'deepseek-official', kind: 'api', currency: 'CNY', legacy: 'deepseek' },
102
195
  { id: 'zhipu', kind: 'subscription', currency: 'CNY', legacy: 'glm' },
@@ -118,6 +211,14 @@ export const PROVIDER_SOURCES = [
118
211
  preflight: { refs: ['COMMAND_CODE_ORG_ID'], param: 'orgId' },
119
212
  quota: { url: COMMAND_CODE_CREDITS, parse: parseCommandCodeCredits },
120
213
  },
214
+ {
215
+ id: 'ollama',
216
+ kind: 'api',
217
+ currency: 'USD',
218
+ credential: { type: 'bearer', refs: ['OLLAMA_API_KEY'] },
219
+ quota: { url: OLLAMA_BALANCE, parse: parseOllamaBalance },
220
+ usage: { url: OLLAMA_USAGE, range: '30d', parse: parseOllamaUsage },
221
+ },
121
222
  ]
122
223
 
123
224
  export { TIMEOUT }
package/src/store.js CHANGED
@@ -2,9 +2,10 @@ import { homedir } from 'node:os'
2
2
  import { join } from 'node:path'
3
3
  import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises'
4
4
  import { emptyState, num } from './core.js'
5
+ import { normalizeModel, normalizeProvider } from './providers.js'
5
6
 
6
- /** 计价模型版本:3 = 内置价对齐官方、社区峰谷识别与工作日/周末规则。 */
7
- export const COST_MODEL_VERSION = 3
7
+ /** 计价模型版本:4 = 币种不匹配不计价(含 override),重算按形态与币种双判定。 */
8
+ export const COST_MODEL_VERSION = 4
8
9
 
9
10
  export const DEFAULT_PREFS = {
10
11
  version: 1,
@@ -12,6 +13,56 @@ export const DEFAULT_PREFS = {
12
13
  billingModes: {},
13
14
  refreshMs: 60000,
14
15
  showBalance: true,
16
+ /** 价目逃生阀:仅认文件,无 UI;键为 `provider:model` 或 `model`。 */
17
+ priceOverrides: {},
18
+ /** 币种声明:仅认文件,无 UI;`{ [providerId]: 'CNY' | 'USD' }`。 */
19
+ providerCurrency: {},
20
+ }
21
+
22
+ function quoteOf(raw) {
23
+ const input = Number(raw?.input)
24
+ const output = Number(raw?.output)
25
+ if (!Number.isFinite(input) || input < 0 || !Number.isFinite(output) || output < 0) return null
26
+ const optional = (value) => {
27
+ const parsed = Number(value ?? 0)
28
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
29
+ }
30
+ return {
31
+ input,
32
+ cacheRead: optional(raw?.cacheRead),
33
+ cacheWrite: optional(raw?.cacheWrite),
34
+ output,
35
+ currency: raw?.currency === 'USD' ? 'USD' : 'CNY',
36
+ }
37
+ }
38
+
39
+ /** 键两侧归一(provider 走别名表),非法条目直接丢弃,不阻塞启动。 */
40
+ export function normalizeOverrides(raw) {
41
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
42
+ const out = {}
43
+ for (const [key, value] of Object.entries(raw)) {
44
+ const quote = quoteOf(value)
45
+ if (quote === null) continue
46
+ const [left, right] = String(key).split(':')
47
+ const normalized = right === undefined
48
+ ? normalizeModel(left)
49
+ : `${normalizeProvider(left)}:${normalizeModel(right)}`
50
+ if (normalized === 'unknown' || normalized.endsWith(':unknown')) continue
51
+ out[normalized] = quote
52
+ }
53
+ return out
54
+ }
55
+
56
+ /** 币种声明只接受 CNY / USD;其余值丢弃(不做启发式猜测)。 */
57
+ export function normalizeCurrencyMap(raw) {
58
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return {}
59
+ const out = {}
60
+ for (const [key, value] of Object.entries(raw)) {
61
+ const id = normalizeProvider(key)
62
+ if (id === 'unknown') continue
63
+ if (value === 'CNY' || value === 'USD') out[id] = value
64
+ }
65
+ return out
15
66
  }
16
67
 
17
68
  /** 刷新间隔唯一枚举:loadPrefs 归一与 normalizePrefs 校验共用。 */
@@ -240,6 +291,8 @@ export async function loadPrefs(dir, logger) {
240
291
  billingModes: { ...(prefs?.billingModes ?? {}) },
241
292
  refreshMs,
242
293
  showBalance: prefs?.showBalance !== false,
294
+ priceOverrides: normalizeOverrides(prefs?.priceOverrides),
295
+ providerCurrency: normalizeCurrencyMap(prefs?.providerCurrency),
243
296
  }
244
297
  }
245
298