@leviyuan/lodestar 0.2.8 → 0.3.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/src/usage.ts DELETED
@@ -1,327 +0,0 @@
1
- /**
2
- * Subscription usage snapshot for the `hi` console panel.
3
- *
4
- * Source: Anthropic 官方 OAuth Usage API —— `GET /api/oauth/usage`.
5
- * 不再依赖外部 ccusage CLI。
6
- *
7
- * 凭据来源: `~/.claude/.credentials.json`(Linux 服务器,无 macOS
8
- * Keychain 分支)。结构由 Claude Code 写入,我们读 `claudeAiOauth`
9
- * 字段拿 access_token / refresh_token / expires_at / subscriptionType /
10
- * rateLimitTier。
11
- *
12
- * access_token 过期时,用 refresh_token 调 platform.claude.com
13
- * `/v1/oauth/token` 刷新,刷新成功后原子写回凭据文件
14
- * (tmp + rename),保证多进程并发安全。
15
- *
16
- * 失败可见 (no_fallbacks):
17
- * - 凭据缺失 → state='no_credentials'
18
- * - 刷新也失败 → state='auth_failed'
19
- * - API 返回 429 → state='rate_limited' (+ resetsAt 可选)
20
- * - 其它网络异常 → state='network'
21
- *
22
- * 卡片渲染层 (`cards.consoleUsageContent`) 按 state 分别显示具体原因,
23
- * 不静默回退到旧值,不伪造百分比。
24
- *
25
- * Lodestar 启动后,每次 `hi` 弹板都会拉一次;CACHE_TTL_MS 内的重复
26
- * 调用共享同一份快照,不打 API。in-flight 去重保证并发的多个
27
- * 群同时唤出控制台时只触发一次后台请求。
28
- *
29
- * Stale fallback (照 omchud HUD 规则): 单独记最后一次成功拉到的
30
- * `state:'ok'` 快照,本次拉取失败 (network/rate_limited/auth_failed)
31
- * 且距上次成功 <= MAX_STALE_MS (15 分钟) 时,返回上次的 ok 快照并打
32
- * `stale:true` 标签,卡片层加 "缓存 Xm 前" 提示。这是 no_fallbacks
33
- * 规则的显式例外 —— 用户明确要求订阅额度面板用缓存兜底,因为短暂
34
- * 网络抖动里把面板上的数字抹成红色"拉取失败"信息密度反而更低。
35
- *
36
- * 429 指数退避: 收到 rate_limited 时增加 rateLimitedCount,下次允许
37
- * 实拉的时间设为 now + CACHE_TTL_MS * 2^(count-1),封顶 5 分钟。
38
- * 退避窗口内的 readUsage 直接走 stale fallback,不打 API。任何非 429
39
- * 的响应 (ok / network / auth_failed) 都会重置计数器。
40
- *
41
- * 参考实现: oh-my-claudecode HUD `src/hud/usage-api.ts`。这里只保留
42
- * Lodestar 用得到的最小子集 —— 不处理 keychain、不处理第三方网关
43
- * (z.ai / MiniMax)、不处理 enterprise 货币换算、不做多文件 cache 与
44
- * 文件锁。
45
- */
46
-
47
- import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
48
- import { homedir } from 'node:os'
49
- import { join } from 'node:path'
50
- import { log } from './log'
51
-
52
- const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
53
- const TOKEN_REFRESH_URL = 'https://platform.claude.com/v1/oauth/token'
54
- const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'
55
- const API_TIMEOUT_MS = 10_000
56
- const CACHE_TTL_MS = 60_000
57
- /** 失败时回退到上次成功快照的最大年龄。超过此值就不再用缓存兜底,
58
- * 显示真实失败状态 —— 跟 omchud HUD 的 MAX_STALE_DATA_MS 对齐。 */
59
- const MAX_STALE_MS = 15 * 60 * 1000
60
- /** 429 退避封顶,跟 omchud HUD 的 MAX_RATE_LIMITED_BACKOFF_MS 对齐。 */
61
- const RATE_LIMITED_MAX_BACKOFF_MS = 5 * 60 * 1000
62
-
63
- function credentialsPath(): string {
64
- return join(homedir(), '.claude', '.credentials.json')
65
- }
66
-
67
- interface OAuthCredentials {
68
- accessToken: string
69
- refreshToken?: string
70
- expiresAt?: number
71
- subscriptionType?: string
72
- rateLimitTier?: string
73
- }
74
-
75
- export interface UsageWindow {
76
- /** 0-100, Anthropic 直接返回的 utilization 真实值 */
77
- percent: number
78
- /** 这个窗口何时重置;ISO 解析失败则 null */
79
- resetsAt: Date | null
80
- }
81
-
82
- export type UsageSnapshot =
83
- | { state: 'no_credentials' }
84
- | { state: 'auth_failed' }
85
- | { state: 'rate_limited' }
86
- | { state: 'network'; reason?: string }
87
- | {
88
- state: 'ok'
89
- subscriptionType?: string
90
- fiveHour: UsageWindow | null
91
- weekly: UsageWindow | null
92
- fetchedAt: number
93
- /** true 时本快照不是这次实拉的,而是 lastOk 兜底回来的旧数据。
94
- * 卡片层据此显示 "缓存" 标记 + 重置时间加 `~` 前缀。 */
95
- stale?: boolean
96
- }
97
-
98
- type UsageSnapshotOk = Extract<UsageSnapshot, { state: 'ok' }>
99
-
100
- let cache: { data: UsageSnapshot; at: number } | null = null
101
- /** 最近一次 state:'ok' 的快照,用于失败时兜底。和 cache 分开存:
102
- * cache 是短时去重 (60s),lastOk 是长尾兜底 (15min)。 */
103
- let lastOk: { snapshot: UsageSnapshotOk; at: number } | null = null
104
- let inFlight: Promise<UsageSnapshot> | null = null
105
- /** 连续 429 计数,用于指数退避;遇到任何非 429 响应就重置为 0。 */
106
- let rateLimitedCount = 0
107
- /** 在这个时间戳之前不打 API,直接走 stale fallback。 */
108
- let rateLimitedUntil = 0
109
-
110
- function rateLimitedBackoffMs(count: number): number {
111
- return Math.min(
112
- CACHE_TTL_MS * Math.pow(2, Math.max(0, count - 1)),
113
- RATE_LIMITED_MAX_BACKOFF_MS,
114
- )
115
- }
116
-
117
- function readCredentials(): OAuthCredentials | null {
118
- const path = credentialsPath()
119
- if (!existsSync(path)) return null
120
- try {
121
- const raw = readFileSync(path, 'utf8')
122
- const parsed = JSON.parse(raw)
123
- const creds = parsed.claudeAiOauth ?? parsed
124
- if (!creds?.accessToken) return null
125
- return {
126
- accessToken: creds.accessToken,
127
- refreshToken: creds.refreshToken,
128
- expiresAt: creds.expiresAt,
129
- subscriptionType: creds.subscriptionType,
130
- rateLimitTier: creds.rateLimitTier,
131
- }
132
- } catch (e) {
133
- log(`usage: read credentials failed: ${e}`)
134
- return null
135
- }
136
- }
137
-
138
- /** 把刷新后的 access_token / refresh_token / expires_at 原子写回原文件,
139
- * 保留其它字段(scopes、subscriptionType、organizationUuid 等)。
140
- * 走 tmp + rename 防止半写状态被读到。 */
141
- function writeBackCredentials(updated: OAuthCredentials): void {
142
- const path = credentialsPath()
143
- if (!existsSync(path)) return
144
- try {
145
- const parsed = JSON.parse(readFileSync(path, 'utf8'))
146
- const target = parsed.claudeAiOauth ?? parsed
147
- target.accessToken = updated.accessToken
148
- if (updated.refreshToken) target.refreshToken = updated.refreshToken
149
- if (updated.expiresAt != null) target.expiresAt = updated.expiresAt
150
- const tmp = `${path}.tmp.${process.pid}`
151
- try {
152
- writeFileSync(tmp, JSON.stringify(parsed, null, 2), { mode: 0o600 })
153
- renameSync(tmp, path)
154
- } catch (e) {
155
- try { if (existsSync(tmp)) unlinkSync(tmp) } catch {}
156
- throw e
157
- }
158
- } catch (e) {
159
- log(`usage: writeBackCredentials failed: ${e}`)
160
- }
161
- }
162
-
163
- function isExpired(creds: OAuthCredentials): boolean {
164
- return creds.expiresAt != null && creds.expiresAt <= Date.now()
165
- }
166
-
167
- async function refreshAccessToken(refreshToken: string): Promise<OAuthCredentials | null> {
168
- const body = new URLSearchParams({
169
- grant_type: 'refresh_token',
170
- refresh_token: refreshToken,
171
- client_id: OAUTH_CLIENT_ID,
172
- }).toString()
173
- const ctrl = new AbortController()
174
- const timer = setTimeout(() => ctrl.abort(), API_TIMEOUT_MS)
175
- try {
176
- const res = await fetch(TOKEN_REFRESH_URL, {
177
- method: 'POST',
178
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
179
- body,
180
- signal: ctrl.signal,
181
- })
182
- if (res.status !== 200) {
183
- log(`usage: token refresh HTTP ${res.status}`)
184
- return null
185
- }
186
- const json = await res.json() as any
187
- if (!json?.access_token) return null
188
- return {
189
- accessToken: json.access_token,
190
- refreshToken: json.refresh_token ?? refreshToken,
191
- expiresAt: json.expires_in
192
- ? Date.now() + json.expires_in * 1000
193
- : json.expires_at,
194
- }
195
- } catch (e) {
196
- log(`usage: token refresh threw: ${e}`)
197
- return null
198
- } finally {
199
- clearTimeout(timer)
200
- }
201
- }
202
-
203
- interface UsageApiResponse {
204
- five_hour?: { utilization?: number; resets_at?: string }
205
- seven_day?: { utilization?: number; resets_at?: string }
206
- }
207
-
208
- function parseDate(s: string | undefined): Date | null {
209
- if (!s) return null
210
- const d = new Date(s)
211
- return isNaN(d.getTime()) ? null : d
212
- }
213
-
214
- function clampPct(v: number | undefined): number {
215
- if (v == null || !isFinite(v)) return 0
216
- return Math.max(0, Math.min(100, v))
217
- }
218
-
219
- interface FetchResult {
220
- data: UsageApiResponse | null
221
- /** 失败原因:undefined = 成功;其它字符串是分类错误。 */
222
- reason?: 'rate_limited' | 'network'
223
- detail?: string
224
- }
225
-
226
- async function fetchUsageFromApi(accessToken: string): Promise<FetchResult> {
227
- const ctrl = new AbortController()
228
- const timer = setTimeout(() => ctrl.abort(), API_TIMEOUT_MS)
229
- try {
230
- const res = await fetch(USAGE_URL, {
231
- method: 'GET',
232
- headers: {
233
- Authorization: `Bearer ${accessToken}`,
234
- 'anthropic-beta': 'oauth-2025-04-20',
235
- 'Content-Type': 'application/json',
236
- },
237
- signal: ctrl.signal,
238
- })
239
- if (res.status === 200) {
240
- const data = await res.json() as UsageApiResponse
241
- return { data }
242
- }
243
- if (res.status === 429) return { data: null, reason: 'rate_limited' }
244
- return { data: null, reason: 'network', detail: `HTTP ${res.status}` }
245
- } catch (e: any) {
246
- return { data: null, reason: 'network', detail: e?.message ?? String(e) }
247
- } finally {
248
- clearTimeout(timer)
249
- }
250
- }
251
-
252
- async function fetchUsage(): Promise<UsageSnapshot> {
253
- let creds = readCredentials()
254
- if (!creds) return { state: 'no_credentials' }
255
-
256
- if (isExpired(creds)) {
257
- if (!creds.refreshToken) return { state: 'auth_failed' }
258
- const refreshed = await refreshAccessToken(creds.refreshToken)
259
- if (!refreshed) return { state: 'auth_failed' }
260
- creds = { ...creds, ...refreshed }
261
- writeBackCredentials(creds)
262
- }
263
-
264
- const result = await fetchUsageFromApi(creds.accessToken)
265
- if (result.reason === 'rate_limited') return { state: 'rate_limited' }
266
- if (result.reason === 'network' || !result.data) return { state: 'network', reason: result.detail }
267
-
268
- const data = result.data
269
- const fiveHour = data.five_hour?.utilization != null
270
- ? { percent: clampPct(data.five_hour.utilization), resetsAt: parseDate(data.five_hour.resets_at) }
271
- : null
272
- const weekly = data.seven_day?.utilization != null
273
- ? { percent: clampPct(data.seven_day.utilization), resetsAt: parseDate(data.seven_day.resets_at) }
274
- : null
275
-
276
- return {
277
- state: 'ok',
278
- subscriptionType: creds.subscriptionType,
279
- fiveHour,
280
- weekly,
281
- fetchedAt: Date.now(),
282
- }
283
- }
284
-
285
- /** 失败快照 → 如果 MAX_STALE_MS 内还有 lastOk,就返回 lastOk 的副本
286
- * (打 stale 标);否则透传失败快照。state:'ok' 走 fast path 原样返回。 */
287
- function withStaleFallback(snapshot: UsageSnapshot): UsageSnapshot {
288
- if (snapshot.state === 'ok') return snapshot
289
- if (lastOk && Date.now() - lastOk.at < MAX_STALE_MS) {
290
- return { ...lastOk.snapshot, stale: true }
291
- }
292
- return snapshot
293
- }
294
-
295
- /** 返回订阅额度快照。CACHE_TTL_MS 内的重复调用读缓存;并发请求去重为
296
- * 单次后台 fetch。拉取失败但 lastOk 仍在 MAX_STALE_MS 内时,回退到
297
- * lastOk 并打 stale 标。连续 429 走指数退避,退避窗口内不打 API。
298
- * 永不抛出 —— 失败状态由 `state` 字段表达,卡片层按 state 分支渲染。 */
299
- export async function readUsage(): Promise<UsageSnapshot> {
300
- // 429 退避窗口内不打 API。cache 里可能存的就是 rate_limited 失败态,
301
- // withStaleFallback 会自动用 lastOk 顶上(15min 内)。
302
- if (Date.now() < rateLimitedUntil) {
303
- return withStaleFallback(cache?.data ?? { state: 'rate_limited' })
304
- }
305
- if (cache && Date.now() - cache.at < CACHE_TTL_MS) return withStaleFallback(cache.data)
306
- if (inFlight) return inFlight
307
- inFlight = fetchUsage()
308
- .then(d => {
309
- cache = { data: d, at: Date.now() }
310
- if (d.state === 'ok') lastOk = { snapshot: d, at: Date.now() }
311
- if (d.state === 'rate_limited') {
312
- rateLimitedCount += 1
313
- rateLimitedUntil = Date.now() + rateLimitedBackoffMs(rateLimitedCount)
314
- } else {
315
- rateLimitedCount = 0
316
- rateLimitedUntil = 0
317
- }
318
- inFlight = null
319
- return withStaleFallback(d)
320
- })
321
- .catch(e => {
322
- log(`usage: fetchUsage threw: ${e}`)
323
- inFlight = null
324
- return withStaleFallback({ state: 'network', reason: String(e) })
325
- })
326
- return inFlight
327
- }