@leviyuan/lodestar 0.1.9 → 0.1.10

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.
Files changed (4) hide show
  1. package/README.md +46 -32
  2. package/package.json +1 -1
  3. package/src/cards.ts +27 -34
  4. package/src/usage.ts +220 -158
package/README.md CHANGED
@@ -4,55 +4,67 @@
4
4
 
5
5
  # 夜航星 (Lodestar)
6
6
 
7
- **在你最熟悉的飞书群里,开一段不熄灯的 Claude Code 会话。**
7
+ **把 Claude Code 装进你的飞书群。一个群 = 一个项目 = 一段不熄灯的对话。**
8
8
 
9
- ## 项目哲学
9
+ 离开终端,但不离开 Claude Code。手机上、地铁里、半夜的床上,你只要拇指能点字,Claude 就在另一头跑着。
10
10
 
11
- AI 不是帮手,是倍率。它放大的不是体力,是你——你的直觉、判断和品味,每一样都被乘以一个你以前不敢想的系数。最终走多远,取决于被放大的你有多强。
11
+ ## 它为什么存在
12
12
 
13
- 夜航星让这件事真正发生:在你思考的地方接住想法,在你转身之后继续把它推向终点。一个群,一个项目,一段不熄灯的对话。你醒着它在听,你睡了它还在跑。
13
+ AI 不是帮手,是倍率。它放大的不是体力,是你——你的直觉、判断和品味,每一样都被乘以一个你以前不敢想的系数。最终走多远,取决于被放大的你有多强。
14
+
15
+ 夜航星让这件事真正发生:在你思考的地方接住想法,在你转身之后继续把它推向终点。**你醒着它在听,你睡了它还在跑。**
16
+
17
+ ## 你会得到什么
18
+
19
+ - 🌊 **真·流式卡片** — 飞书 Card Kit v1 streaming,Claude 一个 token 一个 token 地打在同一张卡片里,不是发一堆零碎消息刷屏。
20
+ - 🧠 **思考过程透明** — `thinking` 流式渲染,turn 结束后自动收起为可展开面板。每次工具调用也是一格折叠面板:折起是概述,展开看完整 input/output。
21
+ - 🔐 **权限审批就地完成** — 需要授权的工具调用,**原地**升级为 🔐 等审批状态,三颗按钮 `允许 / 始终允许 / 拒绝` 直接嵌在面板里。不弹独立卡片,不破坏时序。点完按钮,后续 output 接在同一条线上继续往下走。
22
+ - ❓ **结构化追问** — Claude 的 `AskUserQuestion` 在群里呈现为可点击选项行;不满意?直接在群里**打字回答**,daemon 会把自由文本当作 custom answer 发回去。多题串行,有进度计数和"已答 N 题"折叠历史。
23
+ - 📦 **状态面板一键唤出** — 发 `hi` 弹一张控制台:model、上下文占用 %、累计 tokens/cost、上一轮 delta、session id、订阅额度(5h / 7d 真实 utilization,直读 Anthropic 官方 OAuth Usage API,凭据走 `~/.claude/.credentials.json`,token 过期自动 refresh)、本机所有活跃项目并列展示。
24
+ - 📎 **图片 / 文件双向互传** — 用户在群里发图/文件,Claude 通过消息里的 `[file: /abs/path]` 提示就能读;Claude 在回复里写 `[[send: /abs/path]]`,标记被剥离,文件以独立消息发回群里。出站路径走 realpath + 白名单校验,只允许工作目录、`/tmp/lodestar-*`、inbox 三块,`/etc`、`~/.ssh`、`~/.config` 即使被符号链接绕也拒绝。
25
+ - 📲 **加急锁屏推送** — 需要你回答问题、需要你批准操作、一轮跑完了——三种关键时刻自动触发飞书"应用内加急",直接打穿勿扰、亮屏推送。卡片摘要会同步改写成具体待办("🔐 等审批: Bash · rm -rf …"、"❓ 待回答 3 题: …"),锁屏一瞥就知道发生了什么。
26
+ - 🗂 **多项目并发** — 一个 daemon 同时持有 N 个飞书群 ↔ N 个 Claude session。状态面板能跨群看到所有活跃项目和它们的 uptime,在群 A 里就能查群 B 在干嘛。
27
+ - 🔄 **不丢上下文** — 每次 `system/init` 落盘 SDK session_id;daemon 被 systemd 重启、机器断电、手抖 kill 进程,下次 `restart` 或自动复活都 `--resume` 到同一段对话,Claude 不知道你离开过。
28
+ - 🛡 **后台守护级稳定性** — 单 PID 锁、WS pong watchdog(180s 无心跳自杀,交给 systemd 拉起)、5s 重投 stale 消息丢弃、200 条 message_id 去重、SIGTERM 优雅写盘、`alive marker` 区分"我自己挂的"和"被用户主动 kill 的"——后者不会被复活。
14
29
 
15
30
  ## 怎么用
16
31
 
17
- 每个飞书群对应一个 Claude 会话。**群名 = `~/` 下的项目目录名**。
32
+ 每个飞书群对应一个 Claude 会话。**群名 = `~/` 下的项目目录名**。这套绑定是骨架,新群第一次发消息时,daemon 会自动 `mkdir -p ~/{群名}` + `git init` 把项目骨架打起来,**开新群 = 开新项目**。
18
33
 
19
- - 在群里发任意文字 — Claude 接管这一轮,回复以**流式打字机**实时渲染在一张飞书卡片里。
20
- - 思考过程、每一次工具调用都在卡片里被收纳为**可展开折叠面板**:折起来是概述,展开是详情。你随时能审阅它在做什么。
21
- - 需要授权的操作(执行命令、修改文件……)**就在原来那一格工具调用面板里**升级为 🔐 等审批状态,三颗按钮 `允许` / `始终允许` / `拒绝` 直接内嵌在面板里 — 不再弹独立卡片,决策结果与后续 output 串在同一条时序里。默认 `bypassPermissions`,所以这一格只在 SDK 真的拦下来时才出现。
22
- - **图片、文件双向互传**:用户发到群里的图/文件,Claude 通过消息里的 `[file: /abs/path]` 提示就能读;Claude 想把文件发回来,在回复任意位置写 `[[send: /abs/path]]`,标记会被剥离,文件以独立消息出现在群里。出站路径限制在该会话的工作目录、`/tmp/lodestar-*` 与 inbox 之内,`/etc`、`~/.ssh`、`~/.config` 等敏感目录被白名单拒绝。
23
- - 一轮跑完,卡片合上、可转发;下一句话开新一轮。
34
+ 在群里发任意文字,Claude 接管这一轮。回复以流式打字机渲染在一张卡片里,工具调用、思考过程、权限审批、追问选项,全都收纳在这张卡片的不同面板里——一目了然,可转发,可回看。
35
+
36
+ 下一句话开新一轮卡片。
24
37
 
25
38
  ### 文本控制指令
26
39
 
27
- 直接发这四个**裸词**(不需要斜杠,不区分大小写),daemon 拦截、不转发给 Claude
40
+ 直接发这四个**裸词**(不需要斜杠,不区分大小写),daemon 拦截、不转发给 Claude:
28
41
 
29
42
  | 指令 | 行为 |
30
43
  | --- | --- |
31
- | `hi` | 未运行时启动;运行中弹一张**状态卡片**(model · 上下文占用 · 累计 tokens/cost · 上一轮 delta · session id) |
32
- | `kill` | 优雅关闭 Claude 进程;记住 `sessionId`,下次 `restart` 还能 resume |
33
- | `restart` | 用上一次的 `sessionId` 重启会话(保留上下文) |
34
- | `clear` | 杀掉进程并启动一个全新 session(等价于 Claude Code 的 `/clear`) |
35
-
36
- > 这四个词被全局保留:在群里发 "hi" 当问候也会触发控制台卡片,不会到 Claude 那边。换来的是手机上单手打字的便利。
44
+ | `hi` | 未运行时启动;运行中弹一张**状态卡片** |
45
+ | `kill` | 优雅关闭 Claude 进程;记住 `sessionId`,下次 `restart` 还能 resume |
46
+ | `restart` | 用上一次的 `sessionId` 重启会话(保留上下文) |
47
+ | `clear` | 杀掉进程并启动一个全新 session(等价于 Claude Code 的 `/clear`) |
37
48
 
38
- 整个对话在群里、在手机上、在桌面上完整发生。**离开终端,但不离开 Claude Code。**
49
+ > 这四个词被全局保留:在群里发 "hi" 当问候也会触发控制台卡片,不会到 Claude 那边。换来的是手机上单手打字的便利。
39
50
 
40
51
  ## 安装
41
52
 
42
53
  ### 1. 准备
43
54
 
44
- - 一台能常跑后台进程的机器(自家服务器或闲置主机)
45
- - [Bun](https://bun.sh) 运行时
46
- - [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 已登录 Anthropic 账号 (`claude auth login`)
47
- - 一个飞书自建应用 (`cli_xxx`),开通:
55
+ - 一台能常跑后台进程的机器(自家服务器、闲置 NAS、树莓派均可)
56
+ - [Bun](https://bun.sh) 运行时(≥ 1.0)
57
+ - [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 装好且能跑(怎么认证、走官方账号还是第三方网关,你自己看着办)
58
+ - 一个飞书自建应用 (`cli_xxx`),开通:
48
59
  - `im:message:send_as_bot` / `im:message` / `im:chat:readonly` / `im:resource`
60
+ - `im:message.urgent`(加急推送)
49
61
  - `cardkit:card:read` `cardkit:card:write`
50
62
  `cardkit:card.element:read` `cardkit:card.element:write`
51
63
  `cardkit:card.settings:read` `cardkit:card.settings:write`
52
64
 
53
65
  ### 2. 配置
54
66
 
55
- 把凭据写到 `~/.config/lodestar/config.toml`:
67
+ 把凭据写到 `~/.config/lodestar/config.toml`:
56
68
 
57
69
  ```toml
58
70
  [feishu]
@@ -60,10 +72,10 @@ app_id = "cli_xxxxxxxxxxxxxxxx"
60
72
  app_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
61
73
 
62
74
  [runtime]
63
- projects_root = "~/" # 可选,新建群对应的项目目录会落到这里
75
+ projects_root = "~/" # 可选,新建群对应的项目目录会落到这里
64
76
  ```
65
77
 
66
- 也支持 `LODESTAR_CONFIG=/abs/path.toml` 或 `XDG_CONFIG_HOME` 覆盖。
78
+ 也支持 `LODESTAR_CONFIG=/abs/path.toml` 或 `XDG_CONFIG_HOME` 覆盖。运行时状态走 `~/.local/share/lodestar/`(可用 `LODESTAR_DATA_DIR` 或 `XDG_DATA_HOME` 改写)——daemon.pid、daemon.log、session-chat-map、session-resume-map、alive-marker、inbox/ 都在那里。
67
79
 
68
80
  ### 3. 启动
69
81
 
@@ -72,19 +84,17 @@ bun install -g @leviyuan/lodestar
72
84
  lodestar-daemon
73
85
  ```
74
86
 
75
- 或者一次性跑(无需全局安装):
87
+ 或者一次性跑(无需全局安装):
76
88
 
77
89
  ```bash
78
90
  bunx @leviyuan/lodestar
79
91
  ```
80
92
 
81
- 把机器人拉进任意飞书群,发一条消息——Claude 就上线了。
93
+ 把机器人拉进任意飞书群,发一条消息——Claude 就上线了。
82
94
 
83
- > **小贴士**:群名首次出现时,daemon 会自动在 `~/{群名}/` 创建项目目录并 `git init`。换句话说,开新群 = 开新项目。
95
+ ### 4. 守护进程(推荐)
84
96
 
85
- ### 4. 守护进程(可选)
86
-
87
- 要让 daemon 7×24 跑,最简单的方法是配一个 `systemd --user` 单元:
97
+ daemon 7×24 跑,最简单的方法是配一个 `systemd --user` 单元:
88
98
 
89
99
  ```ini
90
100
  [Unit]
@@ -101,7 +111,11 @@ RestartSec=3
101
111
  WantedBy=default.target
102
112
  ```
103
113
 
104
- `systemctl --user enable --now lodestar`。
114
+ ```bash
115
+ systemctl --user enable --now lodestar
116
+ ```
117
+
118
+ WS watchdog + alive-marker 的联手设计,意味着每次 systemd 拉起,daemon 会把**上次还在运行的 session 全部 `--resume` 自动复活**;你主动 `kill` 过的不会被吵醒。
105
119
 
106
120
  ## 许可
107
121
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leviyuan/lodestar",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
package/src/cards.ts CHANGED
@@ -593,48 +593,41 @@ const PEER_STATUS_EMOJI: Record<string, string> = {
593
593
 
594
594
  /** Render the subscription-usage section of the console card. Pulled out
595
595
  * of `consoleCard` so the caller can patch it in after the initial card
596
- * is on screen (ccusage's first cold call is ~5s; we'd rather not block
597
- * the whole panel on it). Layout intentionally splits 5h and 7d onto
598
- * their own indented lines for readability on phone.
596
+ * is on screen (网络往返可能慢于第一次 paint;先占位、回包后替换)。
599
597
  *
600
- * `usage === undefined` loading placeholder (initial paint).
601
- * `usage === null` → permanent "no data" (treat like installed but
602
- * empty; rare path).
603
- * `usage.installed=false` → install hint.
598
+ * 数据源是 Anthropic 官方 OAuth Usage API ( src/usage.ts)
599
+ * 百分比是真实 utilization,失败态按 state 区分显示具体原因。
600
+ *
601
+ * `usage === undefined` → 初始 loading 占位。
604
602
  */
605
603
  export function consoleUsageContent(
606
- usage: import('./usage').UsageSnapshot | null | undefined,
604
+ usage: import('./usage').UsageSnapshot | undefined,
607
605
  ): string {
608
606
  if (usage === undefined) return '**📊 订阅额度** _加载中…_'
609
- if (usage === null) return '**📊 订阅额度** _无数据_'
610
- if (!usage.installed) return '**📊 订阅额度** 未装 `ccusage` — `bun i -g ccusage`'
611
- // Format follows user spec: `5h X% $Y 剩Zh` / `7d X% $Y 剩Zd`.
612
- // Both % values are vs. the user's own historical peak (peak block
613
- // for 5h, peak week for 7d) since ccusage has no view into the
614
- // actual subscription tier cap. Omit chips that the data layer
615
- // couldn't supply rather than fabricate (no_fallbacks).
616
- const lines: string[] = ['**📊 订阅额度**']
607
+ switch (usage.state) {
608
+ case 'no_credentials':
609
+ return '**📊 订阅额度** 未找到 OAuth 凭据 (`~/.claude/.credentials.json`)'
610
+ case 'auth_failed':
611
+ return '**📊 订阅额度** Token 已过期且刷新失败 重新 `claude auth login`'
612
+ case 'rate_limited':
613
+ return '**📊 订阅额度** API 429 限流,稍后重试'
614
+ case 'network':
615
+ return `**📊 订阅额度** 拉取失败${usage.reason ? ' — `' + usage.reason + '`' : ''}`
616
+ }
617
+ // state === 'ok'
618
+ const head = usage.subscriptionType
619
+ ? `**📊 订阅额度** · ${usage.subscriptionType}`
620
+ : '**📊 订阅额度**'
621
+ const lines: string[] = [head]
617
622
  if (usage.fiveHour) {
618
- const parts: string[] = []
619
- if (usage.fiveHour.percentUsed != null) {
620
- parts.push(`${Math.round(usage.fiveHour.percentUsed)}%`)
621
- }
622
- parts.push(`$${Math.round(usage.fiveHour.costUsd)}`)
623
- if (usage.fiveHour.remainingMinutes != null) {
624
- parts.push(`剩${(usage.fiveHour.remainingMinutes / 60).toFixed(1)}h`)
625
- }
626
- lines.push(` · 5h ${parts.join(' ')}`)
623
+ const parts = [`${Math.round(usage.fiveHour.percent)}%`]
624
+ if (usage.fiveHour.resetsAt) parts.push(`重置 ${fmtResetIn(usage.fiveHour.resetsAt)}`)
625
+ lines.push(` · 5h ${parts.join(' · ')}`)
627
626
  }
628
627
  if (usage.weekly) {
629
- const parts: string[] = []
630
- if (usage.weekly.percentUsed != null) {
631
- parts.push(`${Math.round(usage.weekly.percentUsed)}%`)
632
- }
633
- parts.push(`$${Math.round(usage.weekly.costUsd)}`)
634
- if (usage.weekly.remainingDays != null) {
635
- parts.push(`剩${usage.weekly.remainingDays.toFixed(1)}d`)
636
- }
637
- lines.push(` · 7d ${parts.join(' ')}`)
628
+ const parts = [`${Math.round(usage.weekly.percent)}%`]
629
+ if (usage.weekly.resetsAt) parts.push(`重置 ${fmtResetIn(usage.weekly.resetsAt)}`)
630
+ lines.push(` · 7d ${parts.join(' · ')}`)
638
631
  }
639
632
  return lines.length === 1 ? '**📊 订阅额度** _无数据_' : lines.join('\n')
640
633
  }
package/src/usage.ts CHANGED
@@ -1,201 +1,263 @@
1
1
  /**
2
2
  * Subscription usage snapshot for the `hi` console panel.
3
3
  *
4
- * Source: the `ccusage` CLI (https://github.com/ryoppippi/ccusage), which
5
- * parses Claude Code's local JSONL transcripts on demand. We shell out
6
- * twice in parallel and cache the merged result for CACHE_TTL_MS.
4
+ * Source: Anthropic 官方 OAuth Usage API —— `GET /api/oauth/usage`.
5
+ * 不再依赖外部 ccusage CLI。
7
6
  *
8
- * - `blocks --active --token-limit max` current 5h billing block.
9
- * `tokenLimitStatus.limit` is ccusage's "peak historical block"
10
- * value, used as the denominator for the 5h percentage. NOTE:
11
- * this is consumption relative to your own heaviest 5h ever —
12
- * NOT the Anthropic tier quota (which we have no way to read
13
- * without OAuth roundtrips). It's an internally-consistent burn
14
- * indicator, not an official quota gauge.
7
+ * 凭据来源: `~/.claude/.credentials.json`(Linux 服务器,无 macOS
8
+ * Keychain 分支)。结构由 Claude Code 写入,我们读 `claudeAiOauth`
9
+ * 字段拿 access_token / refresh_token / expires_at / subscriptionType /
10
+ * rateLimitTier。
15
11
  *
16
- * - `weekly --order desc` list of weekly aggregates, newest first.
17
- * ccusage's weekly doesn't expose tokenLimitStatus, so we compute
18
- * the same "peak historical week" ratio locally.
12
+ * access_token 过期时,用 refresh_token platform.claude.com
13
+ * `/v1/oauth/token` 刷新,刷新成功后原子写回凭据文件
14
+ * (tmp + rename),保证多进程并发安全。
19
15
  *
20
- * Failures stay visible (no fallback fabrication):
21
- * - ccusage not on PATH `installed: false` → card renders install hint.
22
- * - ccusage runs but yields nothing `fiveHour: null`, `weekly: null`.
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
+ * 参考实现: oh-my-claudecode HUD `src/hud/usage-api.ts`。这里只保留
30
+ * Lodestar 用得到的最小子集 —— 不处理 keychain、不处理第三方网关
31
+ * (z.ai / MiniMax)、不处理 enterprise 货币换算、不做多文件 cache 与
32
+ * 文件锁。
23
33
  */
24
34
 
25
- import { spawn } from 'node:child_process'
35
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
36
+ import { homedir } from 'node:os'
37
+ import { join } from 'node:path'
26
38
  import { log } from './log'
27
39
 
28
- const CCUSAGE_BIN = 'ccusage'
40
+ const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
41
+ const TOKEN_REFRESH_URL = 'https://platform.claude.com/v1/oauth/token'
42
+ const OAUTH_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'
43
+ const API_TIMEOUT_MS = 10_000
29
44
  const CACHE_TTL_MS = 60_000
30
- const SPAWN_TIMEOUT_MS = 15_000
31
-
32
- export interface FiveHourBlock {
33
- costUsd: number
34
- totalTokens: number
35
- /** End of the current 5h billing window per ccusage. */
36
- windowEndsAt: Date
37
- /** Tokens/min over the current window, if ccusage reported one. */
38
- burnRatePerMin: number | null
39
- /** Consumption vs. user's historical peak 5h block (0–100). Null
40
- * when ccusage hasn't built a peak yet (very new install). */
41
- percentUsed: number | null
42
- /** Minutes left in this 5h window per ccusage's projection. */
43
- remainingMinutes: number | null
45
+
46
+ function credentialsPath(): string {
47
+ return join(homedir(), '.claude', '.credentials.json')
48
+ }
49
+
50
+ interface OAuthCredentials {
51
+ accessToken: string
52
+ refreshToken?: string
53
+ expiresAt?: number
54
+ subscriptionType?: string
55
+ rateLimitTier?: string
44
56
  }
45
57
 
46
- export interface WeeklyAggregate {
47
- /** ISO date of this week's start, format ccusage chose (Sun by default). */
48
- weekStart: string
49
- costUsd: number
50
- totalTokens: number
51
- /** Consumption vs. user's historical peak week (0–100). Null when
52
- * there's no prior week to compare against. */
53
- percentUsed: number | null
54
- /** Fractional days remaining until end of week (start + 7d). */
55
- remainingDays: number | null
58
+ export interface UsageWindow {
59
+ /** 0-100, Anthropic 直接返回的 utilization 真实值 */
60
+ percent: number
61
+ /** 这个窗口何时重置;ISO 解析失败则 null */
62
+ resetsAt: Date | null
56
63
  }
57
64
 
58
65
  export type UsageSnapshot =
59
- | { installed: false }
66
+ | { state: 'no_credentials' }
67
+ | { state: 'auth_failed' }
68
+ | { state: 'rate_limited' }
69
+ | { state: 'network'; reason?: string }
60
70
  | {
61
- installed: true
62
- fiveHour: FiveHourBlock | null
63
- weekly: WeeklyAggregate | null
64
- /** When this snapshot was computed. */
71
+ state: 'ok'
72
+ subscriptionType?: string
73
+ fiveHour: UsageWindow | null
74
+ weekly: UsageWindow | null
65
75
  fetchedAt: number
66
76
  }
67
77
 
68
- function clampPct(v: number): number {
69
- if (!isFinite(v)) return 0
70
- return Math.max(0, Math.min(100, v))
71
- }
72
-
73
78
  let cache: { data: UsageSnapshot; at: number } | null = null
74
79
  let inFlight: Promise<UsageSnapshot> | null = null
75
80
 
76
- /** `null` = not on PATH (ENOENT); `undefined` = ran but failed (timeout,
77
- * non-zero exit, JSON parse error). Distinct so the caller can render
78
- * different UX. */
79
- type RunResult = any | null | undefined
81
+ function readCredentials(): OAuthCredentials | null {
82
+ const path = credentialsPath()
83
+ if (!existsSync(path)) return null
84
+ try {
85
+ const raw = readFileSync(path, 'utf8')
86
+ const parsed = JSON.parse(raw)
87
+ const creds = parsed.claudeAiOauth ?? parsed
88
+ if (!creds?.accessToken) return null
89
+ return {
90
+ accessToken: creds.accessToken,
91
+ refreshToken: creds.refreshToken,
92
+ expiresAt: creds.expiresAt,
93
+ subscriptionType: creds.subscriptionType,
94
+ rateLimitTier: creds.rateLimitTier,
95
+ }
96
+ } catch (e) {
97
+ log(`usage: read credentials failed: ${e}`)
98
+ return null
99
+ }
100
+ }
80
101
 
81
- function runCcusage(args: string[]): Promise<RunResult> {
82
- return new Promise((resolve) => {
83
- let stdout = ''
84
- let stderr = ''
85
- let proc
102
+ /** 把刷新后的 access_token / refresh_token / expires_at 原子写回原文件,
103
+ * 保留其它字段(scopes、subscriptionType、organizationUuid 等)
104
+ * tmp + rename 防止半写状态被读到。 */
105
+ function writeBackCredentials(updated: OAuthCredentials): void {
106
+ const path = credentialsPath()
107
+ if (!existsSync(path)) return
108
+ try {
109
+ const parsed = JSON.parse(readFileSync(path, 'utf8'))
110
+ const target = parsed.claudeAiOauth ?? parsed
111
+ target.accessToken = updated.accessToken
112
+ if (updated.refreshToken) target.refreshToken = updated.refreshToken
113
+ if (updated.expiresAt != null) target.expiresAt = updated.expiresAt
114
+ const tmp = `${path}.tmp.${process.pid}`
86
115
  try {
87
- proc = spawn(CCUSAGE_BIN, args, { stdio: ['ignore', 'pipe', 'pipe'] })
88
- } catch (e: any) {
89
- if (e?.code === 'ENOENT') return resolve(null)
90
- log(`ccusage spawn threw: ${e}`)
91
- return resolve(undefined)
116
+ writeFileSync(tmp, JSON.stringify(parsed, null, 2), { mode: 0o600 })
117
+ renameSync(tmp, path)
118
+ } catch (e) {
119
+ try { if (existsSync(tmp)) unlinkSync(tmp) } catch {}
120
+ throw e
92
121
  }
122
+ } catch (e) {
123
+ log(`usage: writeBackCredentials failed: ${e}`)
124
+ }
125
+ }
93
126
 
94
- const timer = setTimeout(() => {
95
- proc.kill('SIGTERM')
96
- log(`ccusage ${args.join(' ')}: timeout after ${SPAWN_TIMEOUT_MS}ms`)
97
- }, SPAWN_TIMEOUT_MS)
127
+ function isExpired(creds: OAuthCredentials): boolean {
128
+ return creds.expiresAt != null && creds.expiresAt <= Date.now()
129
+ }
98
130
 
99
- proc.on('error', (err: any) => {
100
- clearTimeout(timer)
101
- if (err?.code === 'ENOENT') resolve(null)
102
- else { log(`ccusage error: ${err}`); resolve(undefined) }
131
+ async function refreshAccessToken(refreshToken: string): Promise<OAuthCredentials | null> {
132
+ const body = new URLSearchParams({
133
+ grant_type: 'refresh_token',
134
+ refresh_token: refreshToken,
135
+ client_id: OAUTH_CLIENT_ID,
136
+ }).toString()
137
+ const ctrl = new AbortController()
138
+ const timer = setTimeout(() => ctrl.abort(), API_TIMEOUT_MS)
139
+ try {
140
+ const res = await fetch(TOKEN_REFRESH_URL, {
141
+ method: 'POST',
142
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
143
+ body,
144
+ signal: ctrl.signal,
103
145
  })
104
- proc.stdout!.on('data', (b) => { stdout += b.toString() })
105
- proc.stderr!.on('data', (b) => { stderr += b.toString() })
106
- proc.on('close', (code) => {
107
- clearTimeout(timer)
108
- if (code !== 0) {
109
- log(`ccusage ${args.join(' ')}: exit ${code} stderr=${stderr.slice(0, 200)}`)
110
- return resolve(undefined)
111
- }
112
- try { resolve(JSON.parse(stdout)) }
113
- catch (e) { log(`ccusage JSON parse: ${e}`); resolve(undefined) }
114
- })
115
- })
146
+ if (res.status !== 200) {
147
+ log(`usage: token refresh HTTP ${res.status}`)
148
+ return null
149
+ }
150
+ const json = await res.json() as any
151
+ if (!json?.access_token) return null
152
+ return {
153
+ accessToken: json.access_token,
154
+ refreshToken: json.refresh_token ?? refreshToken,
155
+ expiresAt: json.expires_in
156
+ ? Date.now() + json.expires_in * 1000
157
+ : json.expires_at,
158
+ }
159
+ } catch (e) {
160
+ log(`usage: token refresh threw: ${e}`)
161
+ return null
162
+ } finally {
163
+ clearTimeout(timer)
164
+ }
116
165
  }
117
166
 
118
- async function fetchUsage(): Promise<UsageSnapshot> {
119
- const [blocks, weekly] = await Promise.all([
120
- // --active filters to the current 5h block (cheaper to parse).
121
- // --token-limit max derives a cap from the user's peak historical
122
- // block so ccusage emits `tokenLimitStatus`, giving us a numerator+
123
- // denominator without us reading every block ourselves.
124
- runCcusage(['blocks', '--json', '--active', '--token-limit', 'max']),
125
- runCcusage(['weekly', '--json', '--order', 'desc']),
126
- ])
127
-
128
- if (blocks === null || weekly === null) return { installed: false }
129
-
130
- let fiveHour: FiveHourBlock | null = null
131
- if (blocks && Array.isArray(blocks.blocks)) {
132
- const active = blocks.blocks.find((b: any) => b?.isActive && !b?.isGap)
133
- if (active) {
134
- const totalTokens = Number(active.totalTokens) || 0
135
- const limit = Number(active.tokenLimitStatus?.limit) || 0
136
- fiveHour = {
137
- costUsd: Number(active.costUSD) || 0,
138
- totalTokens,
139
- windowEndsAt: new Date(active.endTime),
140
- burnRatePerMin: typeof active.burnRate?.tokensPerMinute === 'number'
141
- ? active.burnRate.tokensPerMinute : null,
142
- percentUsed: limit > 0 ? clampPct((totalTokens / limit) * 100) : null,
143
- remainingMinutes: typeof active.projection?.remainingMinutes === 'number'
144
- ? active.projection.remainingMinutes : null,
145
- }
167
+ interface UsageApiResponse {
168
+ five_hour?: { utilization?: number; resets_at?: string }
169
+ seven_day?: { utilization?: number; resets_at?: string }
170
+ }
171
+
172
+ function parseDate(s: string | undefined): Date | null {
173
+ if (!s) return null
174
+ const d = new Date(s)
175
+ return isNaN(d.getTime()) ? null : d
176
+ }
177
+
178
+ function clampPct(v: number | undefined): number {
179
+ if (v == null || !isFinite(v)) return 0
180
+ return Math.max(0, Math.min(100, v))
181
+ }
182
+
183
+ interface FetchResult {
184
+ data: UsageApiResponse | null
185
+ /** 失败原因:undefined = 成功;其它字符串是分类错误。 */
186
+ reason?: 'rate_limited' | 'network'
187
+ detail?: string
188
+ }
189
+
190
+ async function fetchUsageFromApi(accessToken: string): Promise<FetchResult> {
191
+ const ctrl = new AbortController()
192
+ const timer = setTimeout(() => ctrl.abort(), API_TIMEOUT_MS)
193
+ try {
194
+ const res = await fetch(USAGE_URL, {
195
+ method: 'GET',
196
+ headers: {
197
+ Authorization: `Bearer ${accessToken}`,
198
+ 'anthropic-beta': 'oauth-2025-04-20',
199
+ 'Content-Type': 'application/json',
200
+ },
201
+ signal: ctrl.signal,
202
+ })
203
+ if (res.status === 200) {
204
+ const data = await res.json() as UsageApiResponse
205
+ return { data }
146
206
  }
207
+ if (res.status === 429) return { data: null, reason: 'rate_limited' }
208
+ return { data: null, reason: 'network', detail: `HTTP ${res.status}` }
209
+ } catch (e: any) {
210
+ return { data: null, reason: 'network', detail: e?.message ?? String(e) }
211
+ } finally {
212
+ clearTimeout(timer)
147
213
  }
214
+ }
148
215
 
149
- let wk: WeeklyAggregate | null = null
150
- if (weekly && Array.isArray(weekly.weekly) && weekly.weekly.length > 0) {
151
- const current = weekly.weekly[0]
152
- const totalTokens = Number(current.totalTokens) || 0
153
- // Peak historical week (excluding the current one — comparing
154
- // against itself would always read 100%). When this is the only
155
- // recorded week we leave percentUsed null.
156
- const peakTokens = weekly.weekly.slice(1).reduce(
157
- (m: number, w: any) => Math.max(m, Number(w?.totalTokens) || 0), 0)
158
- const percentUsed = peakTokens > 0 ? clampPct((totalTokens / peakTokens) * 100) : null
159
- // Week end = weekStart + 7 days. ccusage emits weekStart as YYYY-MM-DD;
160
- // parse as UTC so DST/timezone shifts don't drift the countdown.
161
- const weekStartIso = String(current.week ?? '')
162
- let remainingDays: number | null = null
163
- if (weekStartIso) {
164
- const start = new Date(weekStartIso + 'T00:00:00Z')
165
- if (!isNaN(start.getTime())) {
166
- const endMs = start.getTime() + 7 * 24 * 60 * 60 * 1000
167
- remainingDays = Math.max(0, (endMs - Date.now()) / (24 * 60 * 60 * 1000))
168
- }
169
- }
170
- wk = {
171
- weekStart: weekStartIso,
172
- costUsd: Number(current.totalCost) || 0,
173
- totalTokens,
174
- percentUsed,
175
- remainingDays,
176
- }
216
+ async function fetchUsage(): Promise<UsageSnapshot> {
217
+ let creds = readCredentials()
218
+ if (!creds) return { state: 'no_credentials' }
219
+
220
+ if (isExpired(creds)) {
221
+ if (!creds.refreshToken) return { state: 'auth_failed' }
222
+ const refreshed = await refreshAccessToken(creds.refreshToken)
223
+ if (!refreshed) return { state: 'auth_failed' }
224
+ creds = { ...creds, ...refreshed }
225
+ writeBackCredentials(creds)
177
226
  }
178
227
 
179
- return { installed: true, fiveHour, weekly: wk, fetchedAt: Date.now() }
228
+ const result = await fetchUsageFromApi(creds.accessToken)
229
+ if (result.reason === 'rate_limited') return { state: 'rate_limited' }
230
+ if (result.reason === 'network' || !result.data) return { state: 'network', reason: result.detail }
231
+
232
+ const data = result.data
233
+ const fiveHour = data.five_hour?.utilization != null
234
+ ? { percent: clampPct(data.five_hour.utilization), resetsAt: parseDate(data.five_hour.resets_at) }
235
+ : null
236
+ const weekly = data.seven_day?.utilization != null
237
+ ? { percent: clampPct(data.seven_day.utilization), resetsAt: parseDate(data.seven_day.resets_at) }
238
+ : null
239
+
240
+ return {
241
+ state: 'ok',
242
+ subscriptionType: creds.subscriptionType,
243
+ fiveHour,
244
+ weekly,
245
+ fetchedAt: Date.now(),
246
+ }
180
247
  }
181
248
 
182
- /** Returns a usage snapshot. Cached for CACHE_TTL_MS; concurrent callers
183
- * dedupe to a single in-flight ccusage run. First call after stale-out
184
- * pays the full ccusage cost (~5s on this machine); subsequent reads are
185
- * instant. Never throws — returns `{ installed: false }` if ccusage is
186
- * missing, or an empty `{ installed: true, fiveHour: null, ... }` if it
187
- * runs but yields no data. */
249
+ /** 返回订阅额度快照。CACHE_TTL_MS 内的重复调用读缓存;并发请求去重为
250
+ * 单次后台 fetch。永不抛出 —— 失败状态由 `state` 字段表达,卡片层
251
+ * state 分支渲染。 */
188
252
  export async function readUsage(): Promise<UsageSnapshot> {
189
253
  if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache.data
190
254
  if (inFlight) return inFlight
191
- inFlight = fetchUsage().then(d => {
192
- cache = { data: d, at: Date.now() }
193
- inFlight = null
194
- return d
195
- }).catch(e => {
196
- log(`usage: fetchUsage threw: ${e}`)
197
- inFlight = null
198
- return cache?.data ?? { installed: false }
199
- })
255
+ inFlight = fetchUsage()
256
+ .then(d => { cache = { data: d, at: Date.now() }; inFlight = null; return d })
257
+ .catch(e => {
258
+ log(`usage: fetchUsage threw: ${e}`)
259
+ inFlight = null
260
+ return cache?.data ?? { state: 'network', reason: String(e) }
261
+ })
200
262
  return inFlight
201
263
  }