easy-claude 0.1.0 → 0.2.1
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.md +17 -4
- package/bin/easy-claude.js +6 -3
- package/native/Overlay.swift +274 -45
- package/native/build/EasyClaudeOverlay.app/Contents/Info.plist +1 -1
- package/native/build/EasyClaudeOverlay.app/Contents/MacOS/EasyClaudeOverlay +0 -0
- package/package.json +2 -2
- package/src/overlay.js +1 -1
- package/src/transport.js +62 -0
- package/src/usage.js +4 -2
package/README.md
CHANGED
|
@@ -9,27 +9,35 @@
|
|
|
9
9
|
```sh
|
|
10
10
|
npm i -g easy-claude
|
|
11
11
|
easy-claude
|
|
12
|
-
easy-claude
|
|
12
|
+
easy-claude show
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
读取 Claude Code 登录账号,桌面端请使用同一账号。登录不存在或过期时,执行 `claude auth login` 后重试。仅安装 Claude 桌面端、没有 Claude Code 登录时不能查询。
|
|
16
16
|
|
|
17
17
|
## 圆环
|
|
18
18
|
|
|
19
|
-
- macOS 14+;跟随 Claude
|
|
19
|
+
- macOS 14+;跟随 Claude 桌面应用窗口,前台显示,后台隐藏。默认左下角账户栏右侧,32×32,透明背景,无底板和阴影。
|
|
20
20
|
- 显示剩余百分比:大于 50% 为绿色、20%–50% 橙色、低于 20% 红色;未知或过期为灰色,不伪装满额。
|
|
21
|
-
-
|
|
21
|
+
- 按返回的真实额度自适应:只有周额度时显示单周环和周剩余数字,不显示5小时项;只有5小时则显示单5小时环,两项都有时双环同时显示:周额度为外侧粗实线环,5 小时额度为内侧细实线环(外环未使用部分为淡色虚线底轨),中心数字默认显示 5 小时剩余百分比(环内省略 %,菜单保留),可在菜单点击“5小时”或“周”切换并记住选择;两环独立配色和判断过期。右键查看“5小时 · 剩余百分比 · 重置时间”和“周 · 剩余百分比 · 重置时间”(重置使用电脑本地时区)、刷新、恢复位置或退出,双击刷新,拖动校准。
|
|
22
22
|
- 可见时每 5 分钟查询,10 分钟前的快照或已到重置时间的数据标为过期;接口错误会立即标记未知。
|
|
23
23
|
- 不显示“7天”等底部文字,详情在悬停提示和菜单。菜单栏标记为 EA。
|
|
24
24
|
- 基于窗口边界定位,不识别头像,不读取桌面聊天或截图;无法自动核对桌面账号与 CLI 账号一致。
|
|
25
25
|
|
|
26
|
+
## 电子时钟
|
|
27
|
+
|
|
28
|
+
运行 `easy-claude show` 时同时显示透明电子时钟,跟随 Claude 前台窗口,后台隐藏;可独立拖动位置。默认与额度环并排放在左下角,额度环在左、时钟在右;已有拖动位置继续保留,可从菜单选择“恢复默认位置”应用新布局。
|
|
29
|
+
|
|
30
|
+
默认硅谷 `America/Los_Angeles`,24 小时制,仅显示时分;自动按目标时区处理夏令时,与电脑系统时区无关。右键时钟、圆环或菜单栏 EA,使用城市时间子菜单按顺序选择硅谷、洛杉矶、西雅图、华盛顿、哥伦布、新加坡、上海,或输入其他 IANA 时区名称。时区、位置和显示开关自动保留;“恢复默认位置”同时重置圆环与时钟的位置。数字颜色按所选时区切换:09:00–15:00 绿色,15:00–24:00 橙色,00:00–09:00 红色。边界 09:00 起为绿、15:00 起为橙、午夜转红。时钟使用本机系统时间,无需登录或网络校时,不修改系统时区。
|
|
31
|
+
|
|
32
|
+
华盛顿指美国华盛顿特区,哥伦布指俄亥俄州哥伦布,二者使用 `America/New_York`;硅谷、洛杉矶和西雅图使用 `America/Los_Angeles`。城市名称独立保存,相同时区也可分别选择并显示。
|
|
33
|
+
|
|
26
34
|
## 数据与认证边界
|
|
27
35
|
|
|
28
36
|
使用本机 Claude Code 中存在的 `https://api.anthropic.com/api/oauth/usage` 接口,仅发送只读 GET,不创建模型请求或刷新/修改凭据。它不是公开稳定 API,可能因服务调整失效。
|
|
29
37
|
|
|
30
38
|
macOS 优先读取 `Claude Code-credentials` 钥匙串项;其他情况读取 Claude Code 的 `.credentials.json`。设置 `CLAUDE_CONFIG_DIR` 时只读取该目录的凭据文件,不猜测自定义钥匙串名称。可能需要系统允许访问已有钥匙串项。
|
|
31
39
|
|
|
32
|
-
登录令牌只在内存中用于固定官方源;禁止跟随重定向,不输出原始错误正文或令牌。查询总超时 15 秒,遇到 429 提示稍后重试。OAuth 权限可能不足;如重新登录仍无法查询,应停止请求并检查接口兼容性。
|
|
40
|
+
登录令牌只在内存中用于固定官方源;禁止跟随重定向,不输出原始错误正文或令牌。查询总超时 15 秒,遇到 429 提示稍后重试。macOS 优先使用 HTTPS_PROXY/ALL_PROXY 环境变量,否则读取已启用的系统 HTTPS 代理;经系统 curl 校验 TLS,凭据仅经标准输入传入,不出现在命令参数中,不修改系统代理。未配置代理时直连。HTTP 403 提示服务拒绝访问,与 401 登录失效区分。OAuth 权限可能不足;如重新登录仍无法查询,应停止请求并检查接口兼容性。
|
|
33
41
|
|
|
34
42
|
展示服务端 `utilization` 的剩余值 `100 - utilization`。各窗口独立,额外付费额度不混入百分比。未知字段不硬编码为零。此接口读取的是订阅窗口,不是当前聊天上下文剩余量。
|
|
35
43
|
|
|
@@ -47,3 +55,8 @@ npm run build:overlay
|
|
|
47
55
|
升级 package.json 版本,提交后推送同版本 v 标签,由 GitHub Actions 自动测试、构建通用浮窗并发布 npm。稳定版使用 latest,预发布使用 next。发布任务使用 npm Environment,仓库 Deployments 可查看记录。
|
|
48
56
|
|
|
49
57
|
发布使用 Easy 系列共用的 NPM_TOKEN Secret;每次发布前检查有效期和包权限。首次配置后,普通代码推送只运行 CI,版本标签才发布 npm。
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
浮窗使用 `easy-claude show` 启动;原 `overlay` 命令保留兼容。
|
|
61
|
+
|
|
62
|
+
周倒计时只显示最大单位,例如“6天后 25日 06:17 重置”,不足一天按小时、不足一小时按分钟。5小时窗口保留时分组合,例如“3小时2分后 07:59 重置”,没有小时则“22分后 07:59 重置”,省略为零的单位。绝对重置时刻使用电脑本地时区;周含日,5小时不含日期。
|
package/bin/easy-claude.js
CHANGED
|
@@ -5,16 +5,19 @@ import { readUsage, formatUsage } from '../src/usage.js';
|
|
|
5
5
|
|
|
6
6
|
const args = process.argv.slice(2);
|
|
7
7
|
if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
|
|
8
|
-
console.log('用法:easy-claude [usage|overlay]\n显示已登录 Claude 账号的剩余百分比和重置时间。需要 Claude Code 订阅登录。');
|
|
8
|
+
console.log('用法:easy-claude [usage|show|overlay|agent mcp|agent worker 配置路径 [--check|--once]]\n显示已登录 Claude 账号的剩余百分比和重置时间。需要 Claude Code 订阅登录。');
|
|
9
9
|
} else if (args.length === 1 && ['--version', '-v'].includes(args[0])) {
|
|
10
10
|
console.log(version);
|
|
11
|
-
} else if (args.length === 1 &&
|
|
11
|
+
} else if (args.length === 1 && ['show', 'overlay'].includes(args[0])) {
|
|
12
12
|
try { const { launchOverlay } = await import('../src/overlay.js'); await launchOverlay(); }
|
|
13
13
|
catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
|
|
14
|
+
} else if (args[0] === 'agent') {
|
|
15
|
+
try { const { runAgent } = await import('../src/agent.js'); await runAgent(args.slice(1), 'claude'); }
|
|
16
|
+
catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
|
|
14
17
|
} else if (args.length === 0 || (args.length === 1 && args[0] === 'usage')) {
|
|
15
18
|
try { console.log(formatUsage(await readUsage())); }
|
|
16
19
|
catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
|
|
17
20
|
} else {
|
|
18
|
-
console.error('未知参数。用法:easy-claude [usage|overlay],或 easy-claude --help');
|
|
21
|
+
console.error('未知参数。用法:easy-claude [usage|show|overlay|agent mcp|agent worker 配置路径 [--check|--once]],或 easy-claude --help');
|
|
19
22
|
process.exitCode = 1;
|
|
20
23
|
}
|
package/native/Overlay.swift
CHANGED
|
@@ -68,8 +68,14 @@ func targetWindow() -> CGRect? {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
@MainActor
|
|
71
|
-
|
|
71
|
+
class RingView: NSView {
|
|
72
72
|
var remaining: Double?
|
|
73
|
+
var weeklyRemaining: Double?
|
|
74
|
+
var weeklyStale = true
|
|
75
|
+
var showWeeklyPercentage = false
|
|
76
|
+
var showWeeklyRing = true
|
|
77
|
+
var showFiveHourRing = true
|
|
78
|
+
var displaysWeeklyPercentage: Bool { showWeeklyRing && (showWeeklyPercentage || !showFiveHourRing) }
|
|
73
79
|
var stale = true
|
|
74
80
|
var caption = "等待额度"
|
|
75
81
|
var makeMenu: (() -> NSMenu)?
|
|
@@ -80,23 +86,31 @@ final class RingView: NSView {
|
|
|
80
86
|
private var originStart = CGPoint.zero
|
|
81
87
|
|
|
82
88
|
override func draw(_ dirtyRect: NSRect) {
|
|
89
|
+
if showWeeklyRing { drawRing(radius: 14, remaining: weeklyRemaining, stale: weeklyStale, dashed: true) }
|
|
90
|
+
if showFiveHourRing { drawRing(radius: showWeeklyRing ? 10 : 14, remaining: remaining, stale: stale) }
|
|
91
|
+
let useWeekly = displaysWeeklyPercentage
|
|
92
|
+
let percentage = useWeekly ? weeklyRemaining : remaining
|
|
93
|
+
let percentageStale = useWeekly ? weeklyStale : stale
|
|
94
|
+
let state = RingState.resolve(percentage, stale: percentageStale)
|
|
95
|
+
let text = percentage.map { "\(Int($0.rounded()))" } ?? "—"
|
|
96
|
+
drawText(text, y: 10, font: .monospacedDigitSystemFont(ofSize: 9, weight: .semibold), color: state.color)
|
|
97
|
+
}
|
|
98
|
+
private func drawRing(radius: CGFloat, remaining: Double?, stale: Bool, dashed: Bool = false) {
|
|
83
99
|
let center = CGPoint(x: bounds.midX, y: bounds.midY)
|
|
84
|
-
let track = NSBezierPath(ovalIn: CGRect(x: center.x -
|
|
85
|
-
|
|
100
|
+
let track = NSBezierPath(ovalIn: CGRect(x: center.x - radius, y: center.y - radius,
|
|
101
|
+
width: radius * 2, height: radius * 2))
|
|
102
|
+
track.lineWidth = dashed ? 3 : 2
|
|
103
|
+
if dashed { track.setLineDash([2, 2], count: 2, phase: 0) }
|
|
86
104
|
NSColor.labelColor.withAlphaComponent(0.12).setStroke()
|
|
87
105
|
track.stroke()
|
|
88
|
-
let
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
arc.stroke()
|
|
97
|
-
}
|
|
98
|
-
let text = remaining.map { "\(Int($0.rounded()))%" } ?? "—"
|
|
99
|
-
drawText(text, y: 10, font: .monospacedDigitSystemFont(ofSize: 9, weight: .semibold), color: state.color)
|
|
106
|
+
guard let remaining, remaining > 0, !stale else { return }
|
|
107
|
+
let arc = NSBezierPath()
|
|
108
|
+
arc.lineWidth = dashed ? 3 : 2
|
|
109
|
+
arc.lineCapStyle = .round
|
|
110
|
+
arc.appendArc(withCenter: center, radius: radius, startAngle: 90,
|
|
111
|
+
endAngle: 90 - CGFloat(min(100, max(0, remaining))) * 3.6, clockwise: true)
|
|
112
|
+
RingState.resolve(remaining, stale: stale).color.setStroke()
|
|
113
|
+
arc.stroke()
|
|
100
114
|
}
|
|
101
115
|
private func drawText(_ text: String, y: CGFloat, font: NSFont, color: NSColor) {
|
|
102
116
|
let style = NSMutableParagraphStyle()
|
|
@@ -125,20 +139,97 @@ final class RingView: NSView {
|
|
|
125
139
|
}
|
|
126
140
|
}
|
|
127
141
|
|
|
142
|
+
struct ClockCity {
|
|
143
|
+
let name: String
|
|
144
|
+
let identifier: String
|
|
145
|
+
static let presets: [ClockCity] = [
|
|
146
|
+
ClockCity(name: "硅谷", identifier: "America/Los_Angeles"),
|
|
147
|
+
ClockCity(name: "洛杉矶", identifier: "America/Los_Angeles"),
|
|
148
|
+
ClockCity(name: "西雅图", identifier: "America/Los_Angeles"),
|
|
149
|
+
ClockCity(name: "华盛顿", identifier: "America/New_York"),
|
|
150
|
+
ClockCity(name: "哥伦布", identifier: "America/New_York"),
|
|
151
|
+
ClockCity(name: "新加坡", identifier: "Asia/Singapore"),
|
|
152
|
+
ClockCity(name: "上海", identifier: "Asia/Shanghai")
|
|
153
|
+
]
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
func resetDescription(_ resetsAt: Double?, weekly: Bool, now: Date = Date(), zone: TimeZone = .current) -> String {
|
|
157
|
+
guard let resetsAt, resetsAt.isFinite, abs(resetsAt) < 8.64e12 else { return "重置时间未知" }
|
|
158
|
+
let remaining = resetsAt - now.timeIntervalSince1970
|
|
159
|
+
guard remaining > 0 else { return "已到重置时间,等待更新" }
|
|
160
|
+
let formatter = DateFormatter()
|
|
161
|
+
formatter.locale = Locale(identifier: "zh_CN")
|
|
162
|
+
formatter.timeZone = zone
|
|
163
|
+
formatter.dateFormat = weekly ? "d'日' HH:mm" : "HH:mm"
|
|
164
|
+
let time = formatter.string(from: Date(timeIntervalSince1970: resetsAt))
|
|
165
|
+
let duration: String
|
|
166
|
+
if weekly {
|
|
167
|
+
if remaining >= 86400 { duration = "\(Int(remaining / 86400))天" }
|
|
168
|
+
else if remaining >= 3600 { duration = "\(Int(remaining / 3600))小时" }
|
|
169
|
+
else { duration = "\(Int(ceil(remaining / 60)))分钟" }
|
|
170
|
+
} else {
|
|
171
|
+
let totalMinutes = Int(ceil(remaining / 60))
|
|
172
|
+
let hours = totalMinutes / 60
|
|
173
|
+
let minutes = totalMinutes % 60
|
|
174
|
+
duration = (hours > 0 ? "\(hours)小时" : "") + (minutes > 0 ? "\(minutes)分" : "")
|
|
175
|
+
}
|
|
176
|
+
return "\(duration)后 \(time) 重置"
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
func clockText(at date: Date, zone: TimeZone) -> String {
|
|
180
|
+
let formatter = DateFormatter()
|
|
181
|
+
formatter.locale = Locale(identifier: "en_US_POSIX")
|
|
182
|
+
formatter.timeZone = zone
|
|
183
|
+
formatter.dateFormat = "HH:mm"
|
|
184
|
+
return formatter.string(from: date)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
func clockState(at date: Date, zone: TimeZone) -> RingState {
|
|
188
|
+
var calendar = Calendar(identifier: .gregorian)
|
|
189
|
+
calendar.timeZone = zone
|
|
190
|
+
let hour = calendar.component(.hour, from: date)
|
|
191
|
+
if hour >= 9 && hour < 15 { return .green }
|
|
192
|
+
if hour >= 15 { return .orange }
|
|
193
|
+
return .red
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
@MainActor
|
|
197
|
+
final class ClockView: RingView {
|
|
198
|
+
var zone = TimeZone(identifier: "America/Los_Angeles")!
|
|
199
|
+
var cityName = "硅谷"
|
|
200
|
+
override func draw(_ dirtyRect: NSRect) {
|
|
201
|
+
let style = NSMutableParagraphStyle()
|
|
202
|
+
style.alignment = .center
|
|
203
|
+
let now = Date()
|
|
204
|
+
let time = clockText(at: now, zone: zone)
|
|
205
|
+
(time as NSString).draw(in: CGRect(x: 0, y: 17, width: bounds.width, height: 25),
|
|
206
|
+
withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 20, weight: .medium),
|
|
207
|
+
.foregroundColor: clockState(at: now, zone: zone).color, .paragraphStyle: style])
|
|
208
|
+
let city = cityName
|
|
209
|
+
(city as NSString).draw(in: CGRect(x: 0, y: 1, width: bounds.width, height: 15),
|
|
210
|
+
withAttributes: [.font: NSFont.systemFont(ofSize: 10),
|
|
211
|
+
.foregroundColor: NSColor.secondaryLabelColor, .paragraphStyle: style])
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
128
215
|
@MainActor
|
|
129
216
|
final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
130
217
|
let panel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 32, height: 32),
|
|
131
218
|
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
|
132
219
|
let ring = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
|
|
220
|
+
let clockPanel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 96, height: 46),
|
|
221
|
+
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
|
222
|
+
let clock = ClockView(frame: CGRect(x: 0, y: 0, width: 96, height: 46))
|
|
223
|
+
var clockInset = CGPoint(x: 164, y: 0)
|
|
224
|
+
var clockEnabled = true
|
|
133
225
|
var status: NSStatusItem?
|
|
134
226
|
var timer: Timer?
|
|
135
227
|
var query: Process?
|
|
136
228
|
var snapshot: Snapshot?
|
|
137
229
|
var error: String?
|
|
138
|
-
var selectedID: String?
|
|
139
230
|
var lastAttempt = Date.distantPast
|
|
140
231
|
var lastRect: CGRect?
|
|
141
|
-
var inset = CGPoint(x:
|
|
232
|
+
var inset = CGPoint(x: 138, y: 4)
|
|
142
233
|
var node = ""
|
|
143
234
|
var script = ""
|
|
144
235
|
var searchPath = ""
|
|
@@ -153,7 +244,32 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
153
244
|
if prefs.object(forKey: "leftInset") != nil {
|
|
154
245
|
inset = CGPoint(x: prefs.double(forKey: "leftInset"), y: prefs.double(forKey: "bottomInset"))
|
|
155
246
|
}
|
|
156
|
-
|
|
247
|
+
if let identifier = prefs.string(forKey: "clockTimeZone"), let zone = TimeZone(identifier: identifier) {
|
|
248
|
+
clock.zone = zone
|
|
249
|
+
let savedCity = prefs.string(forKey: "clockCity")
|
|
250
|
+
let preset = ClockCity.presets.first { $0.name == savedCity && $0.identifier == identifier }
|
|
251
|
+
?? ClockCity.presets.first { $0.identifier == identifier }
|
|
252
|
+
clock.cityName = preset?.name ?? identifier
|
|
253
|
+
}
|
|
254
|
+
ring.showWeeklyPercentage = prefs.bool(forKey: "showWeeklyPercentage")
|
|
255
|
+
clockEnabled = prefs.object(forKey: "clockEnabled") == nil || prefs.bool(forKey: "clockEnabled")
|
|
256
|
+
if prefs.object(forKey: "clockLeftInset") != nil {
|
|
257
|
+
clockInset = CGPoint(x: prefs.double(forKey: "clockLeftInset"), y: prefs.double(forKey: "clockBottomInset"))
|
|
258
|
+
}
|
|
259
|
+
clockPanel.isOpaque = false
|
|
260
|
+
clockPanel.backgroundColor = .clear
|
|
261
|
+
clockPanel.hasShadow = false
|
|
262
|
+
clockPanel.level = .floating
|
|
263
|
+
clockPanel.hidesOnDeactivate = false
|
|
264
|
+
clockPanel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
|
|
265
|
+
clockPanel.contentView = clock
|
|
266
|
+
clock.makeMenu = { [weak self] in self?.makeMenu() ?? NSMenu() }
|
|
267
|
+
clock.moved = { [weak self] point in
|
|
268
|
+
guard let self, let rect = self.lastRect else { return }
|
|
269
|
+
self.clockInset = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY)
|
|
270
|
+
prefs.set(self.clockInset.x, forKey: "clockLeftInset")
|
|
271
|
+
prefs.set(self.clockInset.y, forKey: "clockBottomInset")
|
|
272
|
+
}
|
|
157
273
|
panel.isOpaque = false
|
|
158
274
|
panel.backgroundColor = .clear
|
|
159
275
|
panel.hasShadow = false
|
|
@@ -179,32 +295,49 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
179
295
|
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
|
|
180
296
|
tick()
|
|
181
297
|
}
|
|
182
|
-
@objc func hide() { panel.orderOut(nil) }
|
|
298
|
+
@objc func hide() { panel.orderOut(nil); clockPanel.orderOut(nil) }
|
|
183
299
|
@objc func tick() {
|
|
184
|
-
guard let rect = targetWindow() else {
|
|
300
|
+
guard let rect = targetWindow() else { hide(); lastRect = nil; return }
|
|
185
301
|
lastRect = rect
|
|
302
|
+
if clockEnabled {
|
|
303
|
+
if !clock.dragging {
|
|
304
|
+
let x: CGFloat = max(rect.minX, min(rect.maxX - 96, rect.minX + clockInset.x))
|
|
305
|
+
let y: CGFloat = max(rect.minY, min(rect.maxY - 46, rect.minY + clockInset.y))
|
|
306
|
+
clockPanel.setFrameOrigin(CGPoint(x: x, y: y))
|
|
307
|
+
}
|
|
308
|
+
clock.needsDisplay = true
|
|
309
|
+
clock.toolTip = "\(clock.cityName) · \(clock.zone.identifier)"
|
|
310
|
+
clock.setAccessibilityLabel("\(clock.cityName) \(clock.zone.identifier) \(clockText(at: Date(), zone: clock.zone))")
|
|
311
|
+
if !clockPanel.isVisible { clockPanel.orderFrontRegardless() }
|
|
312
|
+
} else { clockPanel.orderOut(nil) }
|
|
186
313
|
if !ring.dragging { panel.setFrameOrigin(ringOrigin(in: rect, inset: inset)) }
|
|
187
314
|
if !panel.isVisible { panel.orderFrontRegardless() }
|
|
188
315
|
if Date().timeIntervalSince(lastAttempt) >= 300 { refresh() }
|
|
189
316
|
updateRing()
|
|
190
317
|
}
|
|
191
|
-
var chosen: UsageWindow? {
|
|
192
|
-
guard let windows = snapshot?.windows else { return nil }
|
|
193
|
-
if let selectedID { return windows.first { $0.id == selectedID } }
|
|
194
|
-
// 默认优先 claude 桶,取其中最紧张的窗口,不把不同窗口相加。
|
|
195
|
-
let claude = windows.filter { $0.id.hasPrefix("claude:") }
|
|
196
|
-
return (claude.isEmpty ? windows : claude).filter { $0.remaining != nil }.min { $0.remaining! < $1.remaining! }
|
|
197
|
-
?? windows.first
|
|
198
|
-
}
|
|
199
318
|
func updateRing() {
|
|
200
|
-
let
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
319
|
+
let windows = snapshot?.windows ?? []
|
|
320
|
+
let weekly = windows.first { $0.id == "seven_day:primary" }
|
|
321
|
+
let fiveHour = windows.first { $0.id == "five_hour:primary" }
|
|
322
|
+
let now = Date().timeIntervalSince1970
|
|
323
|
+
let snapshotStale = error != nil || snapshot == nil || now - (snapshot?.fetchedAt ?? 0) > 600
|
|
324
|
+
func stale(_ window: UsageWindow?) -> Bool {
|
|
325
|
+
snapshotStale || window?.remaining == nil || (window?.resetsAt.map { $0 <= now } ?? false)
|
|
326
|
+
}
|
|
327
|
+
ring.showWeeklyRing = weekly != nil || fiveHour == nil
|
|
328
|
+
ring.showFiveHourRing = fiveHour != nil
|
|
329
|
+
ring.remaining = fiveHour?.remaining
|
|
330
|
+
ring.stale = stale(fiveHour)
|
|
331
|
+
ring.weeklyRemaining = weekly?.remaining
|
|
332
|
+
ring.weeklyStale = stale(weekly)
|
|
333
|
+
func label(_ value: Double?) -> String { value.map { "\(Int($0.rounded()))%" } ?? "未知" }
|
|
334
|
+
let summary = [
|
|
335
|
+
weekly == nil ? nil : "外侧粗环 · 周额度:\(label(weekly?.remaining))\(ring.weeklyStale ? "(未知或已过期)" : "")",
|
|
336
|
+
fiveHour == nil ? nil : "\(weekly == nil ? "单环" : "内侧细环") · 5 小时:\(label(fiveHour?.remaining))\(ring.stale ? "(未知或已过期)" : "")"
|
|
337
|
+
].compactMap { $0 }.joined(separator: "\n")
|
|
205
338
|
let fetched = snapshot.map { Date(timeIntervalSince1970: $0.fetchedAt).formatted(date: .omitted, time: .standard) } ?? "尚未更新"
|
|
206
|
-
ring.toolTip = "本机 Claude CLI 账号额度\n\(
|
|
207
|
-
ring.setAccessibilityLabel("Claude \(
|
|
339
|
+
ring.toolTip = "本机 Claude CLI 账号额度\n\(summary)\n\(error ?? snapshot?.detail ?? "正在读取")\n更新时间:\(fetched)\n中心数字为\(ring.displaysWeeklyPercentage ? "周" : "5小时")剩余;拖动校准位置;双击刷新;右键打开菜单"
|
|
340
|
+
ring.setAccessibilityLabel("Claude \(summary)")
|
|
208
341
|
ring.needsDisplay = true
|
|
209
342
|
}
|
|
210
343
|
@objc func refresh() {
|
|
@@ -236,7 +369,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
236
369
|
}
|
|
237
370
|
query = process
|
|
238
371
|
do { try process.run() }
|
|
239
|
-
catch { query = nil; self.error = "无法启动额度查询,请重新运行 easy-claude
|
|
372
|
+
catch { query = nil; self.error = "无法启动额度查询,请重新运行 easy-claude show"; updateRing() }
|
|
240
373
|
}
|
|
241
374
|
func item(_ title: String, _ action: Selector?) -> NSMenuItem {
|
|
242
375
|
let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
|
|
@@ -250,16 +383,33 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
250
383
|
if let error { menu.addItem(item(error, nil)) }
|
|
251
384
|
if snapshot?.restricted == true { menu.addItem(item("服务端提示:当前使用受限", nil)) }
|
|
252
385
|
menu.addItem(.separator())
|
|
253
|
-
for
|
|
386
|
+
for (id, label) in [("five_hour:primary", "5小时"), ("seven_day:primary", "周")] {
|
|
387
|
+
guard let window = snapshot?.windows.first(where: { $0.id == id }) else { continue }
|
|
254
388
|
let remaining = window.remaining.map { "\(Int($0.rounded()))%" } ?? "未知"
|
|
255
|
-
let
|
|
256
|
-
option
|
|
257
|
-
option.
|
|
389
|
+
let reset = resetDescription(window.resetsAt, weekly: id == "seven_day:primary")
|
|
390
|
+
let option = item("\(label) · \(remaining) · \(reset)", #selector(selectPercentage(_:)))
|
|
391
|
+
option.representedObject = id
|
|
392
|
+
option.state = (ring.displaysWeeklyPercentage == (id == "seven_day:primary")) ? .on : .off
|
|
258
393
|
menu.addItem(option)
|
|
259
394
|
}
|
|
260
395
|
menu.addItem(item(query == nil ? "立即刷新" : "正在刷新…", query == nil ? #selector(refresh) : nil))
|
|
261
396
|
menu.addItem(item("恢复默认位置", #selector(resetPosition)))
|
|
262
397
|
menu.addItem(.separator())
|
|
398
|
+
let toggle = item("显示时间", #selector(toggleClock))
|
|
399
|
+
toggle.state = clockEnabled ? .on : .off
|
|
400
|
+
menu.addItem(toggle)
|
|
401
|
+
let zones = NSMenu()
|
|
402
|
+
for city in ClockCity.presets {
|
|
403
|
+
let option = item(city.name, #selector(selectTimeZone(_:)))
|
|
404
|
+
option.representedObject = city.name
|
|
405
|
+
option.state = clock.cityName == city.name && clock.zone.identifier == city.identifier ? .on : .off
|
|
406
|
+
zones.addItem(option)
|
|
407
|
+
}
|
|
408
|
+
zones.addItem(item("自定义时区…", #selector(customTimeZone)))
|
|
409
|
+
let zoneItem = item("\(clock.cityName)·\(clockText(at: Date(), zone: clock.zone))", nil)
|
|
410
|
+
zoneItem.submenu = zones
|
|
411
|
+
menu.addItem(zoneItem)
|
|
412
|
+
menu.addItem(.separator())
|
|
263
413
|
menu.addItem(item("退出浮窗", #selector(quit)))
|
|
264
414
|
return menu
|
|
265
415
|
}
|
|
@@ -268,13 +418,52 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
268
418
|
let fresh = makeMenu()
|
|
269
419
|
for item in fresh.items { fresh.removeItem(item); menu.addItem(item) }
|
|
270
420
|
}
|
|
271
|
-
@objc func
|
|
272
|
-
|
|
273
|
-
|
|
421
|
+
@objc func selectPercentage(_ sender: NSMenuItem) {
|
|
422
|
+
guard let id = sender.representedObject as? String else { return }
|
|
423
|
+
ring.showWeeklyPercentage = id == "seven_day:primary"
|
|
424
|
+
UserDefaults.standard.set(ring.showWeeklyPercentage, forKey: "showWeeklyPercentage")
|
|
274
425
|
updateRing()
|
|
275
426
|
}
|
|
427
|
+
@objc func toggleClock() {
|
|
428
|
+
clockEnabled.toggle()
|
|
429
|
+
UserDefaults.standard.set(clockEnabled, forKey: "clockEnabled")
|
|
430
|
+
tick()
|
|
431
|
+
}
|
|
432
|
+
func setTimeZone(_ identifier: String, cityName: String? = nil) -> Bool {
|
|
433
|
+
guard let zone = TimeZone(identifier: identifier) else { return false }
|
|
434
|
+
clock.zone = zone
|
|
435
|
+
clock.cityName = cityName ?? ClockCity.presets.first { $0.identifier == zone.identifier }?.name ?? zone.identifier
|
|
436
|
+
UserDefaults.standard.set(clock.cityName, forKey: "clockCity")
|
|
437
|
+
UserDefaults.standard.set(zone.identifier, forKey: "clockTimeZone")
|
|
438
|
+
clock.needsDisplay = true
|
|
439
|
+
return true
|
|
440
|
+
}
|
|
441
|
+
@objc func selectTimeZone(_ sender: NSMenuItem) {
|
|
442
|
+
if let name = sender.representedObject as? String,
|
|
443
|
+
let city = ClockCity.presets.first(where: { $0.name == name }) {
|
|
444
|
+
_ = setTimeZone(city.identifier, cityName: city.name)
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
@objc func customTimeZone() {
|
|
448
|
+
let alert = NSAlert()
|
|
449
|
+
alert.messageText = "设置电子时钟时区"
|
|
450
|
+
alert.informativeText = "输入 IANA 时区,例如 America/Los_Angeles;自动适应夏令时。"
|
|
451
|
+
let field = NSTextField(string: clock.zone.identifier)
|
|
452
|
+
field.frame = CGRect(x: 0, y: 0, width: 300, height: 24)
|
|
453
|
+
alert.accessoryView = field
|
|
454
|
+
alert.addButton(withTitle: "保存")
|
|
455
|
+
alert.addButton(withTitle: "取消")
|
|
456
|
+
NSApp.activate(ignoringOtherApps: true)
|
|
457
|
+
while alert.runModal() == .alertFirstButtonReturn {
|
|
458
|
+
if setTimeZone(field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)) { break }
|
|
459
|
+
alert.informativeText = "无效时区,请输入有效的 IANA 名称,例如 America/Los_Angeles。"
|
|
460
|
+
}
|
|
461
|
+
}
|
|
276
462
|
@objc func resetPosition() {
|
|
277
|
-
|
|
463
|
+
clockInset = CGPoint(x: 164, y: 0)
|
|
464
|
+
UserDefaults.standard.removeObject(forKey: "clockLeftInset")
|
|
465
|
+
UserDefaults.standard.removeObject(forKey: "clockBottomInset")
|
|
466
|
+
inset = CGPoint(x: 138, y: 4)
|
|
278
467
|
UserDefaults.standard.removeObject(forKey: "leftInset")
|
|
279
468
|
UserDefaults.standard.removeObject(forKey: "bottomInset")
|
|
280
469
|
tick()
|
|
@@ -291,6 +480,43 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
|
291
480
|
struct Main {
|
|
292
481
|
@MainActor static func main() {
|
|
293
482
|
if CommandLine.arguments.contains("--self-test") {
|
|
483
|
+
precondition(ClockCity.presets.map(\.name) == ["硅谷", "洛杉矶", "西雅图", "华盛顿", "哥伦布", "新加坡", "上海"])
|
|
484
|
+
precondition(ClockCity.presets.allSatisfy { TimeZone(identifier: $0.identifier) != nil })
|
|
485
|
+
let countdownStart = ISO8601DateFormatter().date(from: "2026-10-15T04:57:00Z")!
|
|
486
|
+
let countdownUTC = TimeZone(secondsFromGMT: 0)!
|
|
487
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 10920, weekly: false, now: countdownStart, zone: countdownUTC) == "3小时2分后 07:59 重置")
|
|
488
|
+
let weekStart = ISO8601DateFormatter().date(from: "2026-10-14T08:03:00Z")!
|
|
489
|
+
precondition(resetDescription(weekStart.timeIntervalSince1970 + 345360, weekly: true, now: weekStart, zone: countdownUTC) == "3天后 18日 07:59 重置")
|
|
490
|
+
precondition(resetDescription(nil, weekly: true) == "重置时间未知")
|
|
491
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970, weekly: false, now: countdownStart) == "已到重置时间,等待更新")
|
|
492
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 1, weekly: false, now: countdownStart, zone: countdownUTC) == "1分后 04:57 重置")
|
|
493
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86160, weekly: true, now: countdownStart, zone: countdownUTC) == "23小时后 16日 04:53 重置")
|
|
494
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 120, weekly: true, now: countdownStart, zone: countdownUTC) == "2分钟后 15日 04:59 重置")
|
|
495
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86400, weekly: true, now: countdownStart, zone: countdownUTC) == "1天后 16日 04:57 重置")
|
|
496
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 86399, weekly: true, now: countdownStart, zone: countdownUTC) == "23小时后 16日 04:56 重置")
|
|
497
|
+
precondition(resetDescription(countdownStart.timeIntervalSince1970 + 3599, weekly: false, now: countdownStart, zone: countdownUTC) == "1小时后 05:56 重置")
|
|
498
|
+
let testRing = RingView()
|
|
499
|
+
testRing.showFiveHourRing = false
|
|
500
|
+
precondition(testRing.displaysWeeklyPercentage)
|
|
501
|
+
testRing.showWeeklyPercentage = true
|
|
502
|
+
testRing.showWeeklyRing = false
|
|
503
|
+
testRing.showFiveHourRing = true
|
|
504
|
+
precondition(!testRing.displaysWeeklyPercentage)
|
|
505
|
+
let la = TimeZone(identifier: "America/Los_Angeles")!
|
|
506
|
+
let singapore = TimeZone(identifier: "Asia/Singapore")!
|
|
507
|
+
let winter = ISO8601DateFormatter().date(from: "2026-01-15T12:00:00Z")!
|
|
508
|
+
let summer = ISO8601DateFormatter().date(from: "2026-07-15T12:00:00Z")!
|
|
509
|
+
precondition(clockText(at: winter, zone: la) == "04:00")
|
|
510
|
+
precondition(clockText(at: summer, zone: la) == "05:00")
|
|
511
|
+
precondition(clockText(at: winter, zone: singapore) == "20:00")
|
|
512
|
+
precondition(TimeZone(identifier: "Invalid/Zone") == nil)
|
|
513
|
+
let utc = TimeZone(secondsFromGMT: 0)!
|
|
514
|
+
for (hour, state) in [(0, RingState.red), (6, .red), (8, .red), (9, .green), (14, .green), (15, .orange), (23, .orange)] {
|
|
515
|
+
let date = Date(timeIntervalSince1970: Double(hour * 3600))
|
|
516
|
+
precondition(clockState(at: date, zone: utc) == state)
|
|
517
|
+
}
|
|
518
|
+
precondition(clockState(at: winter, zone: la) == .red)
|
|
519
|
+
precondition(clockState(at: winter, zone: singapore) == .orange)
|
|
294
520
|
assert(RingState.resolve(51, stale: false) == .green)
|
|
295
521
|
assert(RingState.resolve(50, stale: false) == .orange)
|
|
296
522
|
assert(RingState.resolve(20, stale: false) == .orange)
|
|
@@ -299,7 +525,7 @@ struct Main {
|
|
|
299
525
|
assert(RingState.resolve(99, stale: true) == .unknown)
|
|
300
526
|
assert(appKitRect(CGRect(x: -900, y: 100, width: 800, height: 600), primaryHeight: 900).origin == CGPoint(x: -900, y: 200))
|
|
301
527
|
let bounds = CGRect(x: 100, y: 100, width: 800, height: 600)
|
|
302
|
-
assert(ringOrigin(in: bounds, inset: CGPoint(x:
|
|
528
|
+
assert(ringOrigin(in: bounds, inset: CGPoint(x: 138, y: 4)) == CGPoint(x: 238, y: 104))
|
|
303
529
|
assert(ringOrigin(in: bounds, inset: CGPoint(x: -100, y: -100)) == CGPoint(x: 100, y: 100))
|
|
304
530
|
assert(ringOrigin(in: bounds, inset: CGPoint(x: 9999, y: 9999)) == CGPoint(x: 868, y: 668))
|
|
305
531
|
print("Swift 圆环颜色与窗口坐标检查通过")
|
|
@@ -321,6 +547,9 @@ struct Main {
|
|
|
321
547
|
(transform as NSAffineTransform).concat()
|
|
322
548
|
let view = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
|
|
323
549
|
view.remaining = value < 0 ? nil : value; view.stale = value < 0
|
|
550
|
+
view.weeklyRemaining = value < 0 ? nil : 100 - value; view.weeklyStale = value < 0
|
|
551
|
+
if index == 0 { view.showFiveHourRing = false }
|
|
552
|
+
if index == 1 { view.showWeeklyRing = false }
|
|
324
553
|
view.caption = value < 0 ? "额度未知" : "7天"
|
|
325
554
|
view.draw(view.bounds)
|
|
326
555
|
NSGraphicsContext.restoreGraphicsState()
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<key>CFBundleIdentifier</key><string>com.unionschool.easy-claude.overlay</string>
|
|
6
6
|
<key>CFBundleName</key><string>Easy Claude Overlay</string>
|
|
7
7
|
<key>CFBundlePackageType</key><string>APPL</string>
|
|
8
|
-
<key>CFBundleShortVersionString</key><string>0.1
|
|
8
|
+
<key>CFBundleShortVersionString</key><string>0.2.1</string>
|
|
9
9
|
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
|
10
10
|
<key>LSUIElement</key><true/>
|
|
11
11
|
<key>NSHighResolutionCapable</key><true/>
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easy-claude",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "Claude Code
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Claude Code quota rings and transparent world clock for Claude desktop",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"easy-claude": "bin/easy-claude.js"
|
package/src/overlay.js
CHANGED
|
@@ -11,5 +11,5 @@ export async function launchOverlay() {
|
|
|
11
11
|
catch { throw new Error('尚未构建浮窗,请在项目目录执行 npm run build:overlay。'); }
|
|
12
12
|
await promisify(execFile)('/usr/bin/open', ['-g', '-a', app, '--args',
|
|
13
13
|
process.execPath, fileURLToPath(new URL('./overlay-query.js', import.meta.url)), process.env.PATH ?? '', process.env.CLAUDE_CONFIG_DIR ?? '']);
|
|
14
|
-
console.log('
|
|
14
|
+
console.log('额度与电子时钟浮窗已启动;Claude 在前台时显示。拖动调整位置,右键或菜单栏 EA 可设置时区、查看双环额度和退出。');
|
|
15
15
|
}
|
package/src/transport.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
|
|
4
|
+
const run = promisify(execFile);
|
|
5
|
+
const endpoint = 'https://api.anthropic.com/api/oauth/usage';
|
|
6
|
+
|
|
7
|
+
export function systemProxy(text) {
|
|
8
|
+
const value = key => text.match(new RegExp(`^\\s*${key} : (.+)$`, 'm'))?.[1].trim();
|
|
9
|
+
if (value('HTTPSEnable') !== '1') return null;
|
|
10
|
+
const host = value('HTTPSProxy');
|
|
11
|
+
const port = Number(value('HTTPSPort'));
|
|
12
|
+
if (!host || !/^[a-zA-Z0-9.:-]+$/.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) {
|
|
13
|
+
throw new Error('系统 HTTPS 代理配置无效。');
|
|
14
|
+
}
|
|
15
|
+
return `http://${host.includes(':') ? `[${host}]` : host}:${port}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function curlConfig(url, headers, proxy) {
|
|
19
|
+
if (url !== endpoint) throw new Error('仅允许官方额度地址。');
|
|
20
|
+
const quote = value => {
|
|
21
|
+
if (/[\r\n\0]/.test(value)) throw new Error('请求配置包含无效字符。');
|
|
22
|
+
return `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`;
|
|
23
|
+
};
|
|
24
|
+
return [`url = ${quote(url)}`, `proxy = ${quote(proxy)}`,
|
|
25
|
+
...Object.entries(headers).map(([key, value]) => `header = ${quote(`${key}: ${value}`)}`)].join('\n');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// macOS 上 Node fetch 不读取系统代理。复用系统 curl 的 CONNECT/TLS 校验,令牌只从 stdin 传入。
|
|
29
|
+
export async function quotaFetch(url, options) {
|
|
30
|
+
if (process.platform !== 'darwin') return fetch(url, options);
|
|
31
|
+
const { stdout } = await run('/usr/sbin/scutil', ['--proxy'], { timeout: 2000, signal: options.signal });
|
|
32
|
+
const proxy = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.all_proxy || process.env.ALL_PROXY || systemProxy(stdout);
|
|
33
|
+
if (!proxy) return fetch(url, options);
|
|
34
|
+
const config = curlConfig(url, options.headers, proxy);
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
const child = spawn('/usr/bin/curl', ['-q', '--config', '-', '--silent', '--show-error', '--proto', '=https',
|
|
37
|
+
'--max-time', '15', '--max-redirs', '0', '--write-out', '\n%{http_code}'],
|
|
38
|
+
{ signal: options.signal, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
39
|
+
const chunks = [];
|
|
40
|
+
let size = 0;
|
|
41
|
+
child.stdout.on('data', data => {
|
|
42
|
+
size += data.length;
|
|
43
|
+
if (size > 1024 * 1024) { child.kill(); reject(new Error('额度响应过大。')); }
|
|
44
|
+
else chunks.push(data);
|
|
45
|
+
});
|
|
46
|
+
child.on('error', () => reject(new Error('额度代理请求失败。')));
|
|
47
|
+
child.stdin.on('error', () => {});
|
|
48
|
+
child.on('close', code => {
|
|
49
|
+
if (code !== 0) { reject(new Error('额度代理请求失败。')); return; }
|
|
50
|
+
const output = Buffer.concat(chunks).toString('utf8');
|
|
51
|
+
const split = output.lastIndexOf('\n');
|
|
52
|
+
const status = Number(output.slice(split + 1));
|
|
53
|
+
if (status < 200 || status >= 300) {
|
|
54
|
+
if (status >= 400 && status <= 599) resolve(new Response(null, { status }));
|
|
55
|
+
else reject(new Error('额度请求收到无效响应或重定向。'));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
resolve(new Response(output.slice(0, split), { status }));
|
|
59
|
+
});
|
|
60
|
+
child.stdin.end(config);
|
|
61
|
+
});
|
|
62
|
+
}
|
package/src/usage.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { quotaFetch } from './transport.js';
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import { join } from 'node:path';
|
|
@@ -48,7 +49,7 @@ export function normalizeUsage(data) {
|
|
|
48
49
|
return { rateLimitsByLimitId };
|
|
49
50
|
}
|
|
50
51
|
|
|
51
|
-
export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToken, fetchImpl =
|
|
52
|
+
export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToken, fetchImpl = quotaFetch } = {}) {
|
|
52
53
|
const controller = new AbortController();
|
|
53
54
|
const abort = () => controller.abort();
|
|
54
55
|
if (signal?.aborted) throw new Error('查询已取消。');
|
|
@@ -61,7 +62,8 @@ export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToke
|
|
|
61
62
|
headers: { authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20', accept: 'application/json' },
|
|
62
63
|
redirect: 'error', signal: controller.signal,
|
|
63
64
|
}).catch(() => { throw new Error('无法连接 Claude 额度服务,请检查网络。'); });
|
|
64
|
-
if (response.status === 401
|
|
65
|
+
if (response.status === 401) throw new Error(`订阅登录已失效(HTTP 401)。${loginMessage}`);
|
|
66
|
+
if (response.status === 403) throw new Error('Claude 官方额度服务拒绝访问(HTTP 403)。可能是账号权限、网络访问限制或接口兼容变化;请先检查 Claude Code 的 /usage,不能仅据此判断登录已过期。');
|
|
65
67
|
if (response.status === 429) throw new Error('额度查询过于频繁,请稍后再试。');
|
|
66
68
|
if (!response.ok) throw new Error(`Claude 额度服务暂不可用(HTTP ${response.status})。`);
|
|
67
69
|
let data;
|