easy-claude 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UnionSchool
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # easy-claude
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 查看 Claude Code 订阅剩余额度,并在 Claude 桌面应用旁显示透明彩色圆环。第三方辅助工具,与 Anthropic 无官方隶属关系。
4
+
5
+ 需要 Node.js 22+ 与 Claude Code 订阅登录;不支持把 API Key 账单余额当作订阅额度。
6
+
7
+ ## 安装与使用
8
+
9
+ ```sh
10
+ npm i -g easy-claude
11
+ easy-claude
12
+ easy-claude overlay
13
+ ```
14
+
15
+ 读取 Claude Code 登录账号,桌面端请使用同一账号。登录不存在或过期时,执行 `claude auth login` 后重试。仅安装 Claude 桌面端、没有 Claude Code 登录时不能查询。
16
+
17
+ ## 圆环
18
+
19
+ - macOS 14+;跟随 Claude 桌面应用窗口,前台显示,后台隐藏。默认左下角账户栏右侧,32×32,透明背景,无底板和阴影。
20
+ - 显示剩余百分比:大于 50% 为绿色、20%–50% 橙色、低于 20% 红色;未知或过期为灰色,不伪装满额。
21
+ - 双环同时显示:周额度为外侧粗实线环,5 小时额度为内侧细实线环(外环未使用部分为淡色虚线底轨),中心数字默认显示 5 小时剩余百分比(环内省略 %,菜单保留),可在菜单点击“5小时”或“周”切换并记住选择;两环独立配色和判断过期。右键查看“5小时 · 剩余百分比 · 重置时间”和“周 · 剩余百分比 · 重置时间”(重置使用电脑本地时区)、刷新、恢复位置或退出,双击刷新,拖动校准。
22
+ - 可见时每 5 分钟查询,10 分钟前的快照或已到重置时间的数据标为过期;接口错误会立即标记未知。
23
+ - 不显示“7天”等底部文字,详情在悬停提示和菜单。菜单栏标记为 EA。
24
+ - 基于窗口边界定位,不识别头像,不读取桌面聊天或截图;无法自动核对桌面账号与 CLI 账号一致。
25
+
26
+ ## 电子时钟
27
+
28
+ 运行 `easy-claude overlay` 时同时显示透明电子时钟,跟随 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
+
34
+ ## 数据与认证边界
35
+
36
+ 使用本机 Claude Code 中存在的 `https://api.anthropic.com/api/oauth/usage` 接口,仅发送只读 GET,不创建模型请求或刷新/修改凭据。它不是公开稳定 API,可能因服务调整失效。
37
+
38
+ macOS 优先读取 `Claude Code-credentials` 钥匙串项;其他情况读取 Claude Code 的 `.credentials.json`。设置 `CLAUDE_CONFIG_DIR` 时只读取该目录的凭据文件,不猜测自定义钥匙串名称。可能需要系统允许访问已有钥匙串项。
39
+
40
+ 登录令牌只在内存中用于固定官方源;禁止跟随重定向,不输出原始错误正文或令牌。查询总超时 15 秒,遇到 429 提示稍后重试。macOS 优先使用 HTTPS_PROXY/ALL_PROXY 环境变量,否则读取已启用的系统 HTTPS 代理;经系统 curl 校验 TLS,凭据仅经标准输入传入,不出现在命令参数中,不修改系统代理。未配置代理时直连。HTTP 403 提示服务拒绝访问,与 401 登录失效区分。OAuth 权限可能不足;如重新登录仍无法查询,应停止请求并检查接口兼容性。
41
+
42
+ 展示服务端 `utilization` 的剩余值 `100 - utilization`。各窗口独立,额外付费额度不混入百分比。未知字段不硬编码为零。此接口读取的是订阅窗口,不是当前聊天上下文剩余量。
43
+
44
+ ## 开发
45
+
46
+ ```sh
47
+ npm test
48
+ npm run build:overlay
49
+ ```
50
+
51
+ 构建需要 Swift 6 与 Xcode Command Line Tools,生成 Intel/Apple Silicon 通用应用;使用 ad-hoc 签名,未开发者签名或公证。测试使用模拟响应,不发送模型请求。
52
+
53
+ ## 发布
54
+
55
+ 升级 package.json 版本,提交后推送同版本 v 标签,由 GitHub Actions 自动测试、构建通用浮窗并发布 npm。稳定版使用 latest,预发布使用 next。发布任务使用 npm Environment,仓库 Deployments 可查看记录。
56
+
57
+ 发布使用 Easy 系列共用的 NPM_TOKEN Secret;每次发布前检查有效期和包权限。首次配置后,普通代码推送只运行 CI,版本标签才发布 npm。
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
4
+ import { readUsage, formatUsage } from '../src/usage.js';
5
+
6
+ const args = process.argv.slice(2);
7
+ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
8
+ console.log('用法:easy-claude [usage|overlay]\n显示已登录 Claude 账号的剩余百分比和重置时间。需要 Claude Code 订阅登录。');
9
+ } else if (args.length === 1 && ['--version', '-v'].includes(args[0])) {
10
+ console.log(version);
11
+ } else if (args.length === 1 && args[0] === 'overlay') {
12
+ try { const { launchOverlay } = await import('../src/overlay.js'); await launchOverlay(); }
13
+ catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
14
+ } else if (args.length === 0 || (args.length === 1 && args[0] === 'usage')) {
15
+ try { console.log(formatUsage(await readUsage())); }
16
+ catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
17
+ } else {
18
+ console.error('未知参数。用法:easy-claude [usage|overlay],或 easy-claude --help');
19
+ process.exitCode = 1;
20
+ }
@@ -0,0 +1,521 @@
1
+ import AppKit
2
+ import CoreGraphics
3
+
4
+ struct UsageWindow: Decodable {
5
+ let id: String
6
+ let label: String
7
+ let name: String
8
+ let remaining: Double?
9
+ let resetsAt: Double?
10
+ }
11
+ struct Snapshot: Decodable {
12
+ var windows: [UsageWindow] = []
13
+ var detail: String = ""
14
+ var fetchedAt: Double = 0
15
+ var restricted: Bool = false
16
+ var error: String?
17
+
18
+ enum CodingKeys: CodingKey { case windows, detail, fetchedAt, restricted, error }
19
+ init(from decoder: any Decoder) throws {
20
+ let c = try decoder.container(keyedBy: CodingKeys.self)
21
+ windows = try c.decodeIfPresent([UsageWindow].self, forKey: .windows) ?? []
22
+ detail = try c.decodeIfPresent(String.self, forKey: .detail) ?? ""
23
+ fetchedAt = try c.decodeIfPresent(Double.self, forKey: .fetchedAt) ?? 0
24
+ restricted = try c.decodeIfPresent(Bool.self, forKey: .restricted) ?? false
25
+ error = try c.decodeIfPresent(String.self, forKey: .error)
26
+ }
27
+ }
28
+
29
+ enum RingState: Equatable {
30
+ case green, orange, red, unknown
31
+ static func resolve(_ remaining: Double?, stale: Bool) -> RingState {
32
+ guard !stale, let remaining, remaining.isFinite else { return .unknown }
33
+ return remaining > 50 ? .green : remaining >= 20 ? .orange : .red
34
+ }
35
+ var color: NSColor {
36
+ switch self {
37
+ case .green: .systemGreen
38
+ case .orange: .systemOrange
39
+ case .red: .systemRed
40
+ case .unknown: .secondaryLabelColor
41
+ }
42
+ }
43
+ }
44
+
45
+ func appKitRect(_ rect: CGRect, primaryHeight: CGFloat) -> CGRect {
46
+ CGRect(x: rect.minX, y: primaryHeight - rect.maxY, width: rect.width, height: rect.height)
47
+ }
48
+ func ringOrigin(in rect: CGRect, inset: CGPoint) -> CGPoint {
49
+ CGPoint(x: max(rect.minX, min(rect.maxX - 32, rect.minX + inset.x)),
50
+ y: max(rect.minY, min(rect.maxY - 32, rect.minY + inset.y)))
51
+ }
52
+
53
+ @MainActor
54
+ func targetWindow() -> CGRect? {
55
+ guard let app = NSWorkspace.shared.frontmostApplication,
56
+ app.bundleIdentifier == "com.anthropic.claudefordesktop" else { return nil }
57
+ let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
58
+ for window in windows {
59
+ guard (window[kCGWindowOwnerPID as String] as? Int) == Int(app.processIdentifier),
60
+ (window[kCGWindowLayer as String] as? Int) == 0,
61
+ let bounds = window[kCGWindowBounds as String] as? [String: Any],
62
+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary),
63
+ rect.width >= 300, rect.height >= 200 else { continue }
64
+ // CG 坐标原点在主屏左上;AppKit 使用主屏左下,多屏位置也按同一基准转换。
65
+ return appKitRect(rect, primaryHeight: NSScreen.screens.first?.frame.height ?? 0)
66
+ }
67
+ return nil
68
+ }
69
+
70
+ @MainActor
71
+ class RingView: NSView {
72
+ var remaining: Double?
73
+ var weeklyRemaining: Double?
74
+ var weeklyStale = true
75
+ var showWeeklyPercentage = false
76
+ var stale = true
77
+ var caption = "等待额度"
78
+ var makeMenu: (() -> NSMenu)?
79
+ var moved: ((CGPoint) -> Void)?
80
+ var refresh: (() -> Void)?
81
+ var dragging = false
82
+ private var dragStart = CGPoint.zero
83
+ private var originStart = CGPoint.zero
84
+
85
+ override func draw(_ dirtyRect: NSRect) {
86
+ drawRing(radius: 14, remaining: weeklyRemaining, stale: weeklyStale, dashed: true)
87
+ drawRing(radius: 10, remaining: remaining, stale: stale)
88
+ let percentage = showWeeklyPercentage ? weeklyRemaining : remaining
89
+ let percentageStale = showWeeklyPercentage ? weeklyStale : stale
90
+ let state = RingState.resolve(percentage, stale: percentageStale)
91
+ let text = percentage.map { "\(Int($0.rounded()))" } ?? "—"
92
+ drawText(text, y: 10, font: .monospacedDigitSystemFont(ofSize: 9, weight: .semibold), color: state.color)
93
+ }
94
+ private func drawRing(radius: CGFloat, remaining: Double?, stale: Bool, dashed: Bool = false) {
95
+ let center = CGPoint(x: bounds.midX, y: bounds.midY)
96
+ let track = NSBezierPath(ovalIn: CGRect(x: center.x - radius, y: center.y - radius,
97
+ width: radius * 2, height: radius * 2))
98
+ track.lineWidth = dashed ? 3 : 2
99
+ if dashed { track.setLineDash([2, 2], count: 2, phase: 0) }
100
+ NSColor.labelColor.withAlphaComponent(0.12).setStroke()
101
+ track.stroke()
102
+ guard let remaining, remaining > 0, !stale else { return }
103
+ let arc = NSBezierPath()
104
+ arc.lineWidth = dashed ? 3 : 2
105
+ arc.lineCapStyle = .round
106
+ arc.appendArc(withCenter: center, radius: radius, startAngle: 90,
107
+ endAngle: 90 - CGFloat(min(100, max(0, remaining))) * 3.6, clockwise: true)
108
+ RingState.resolve(remaining, stale: stale).color.setStroke()
109
+ arc.stroke()
110
+ }
111
+ private func drawText(_ text: String, y: CGFloat, font: NSFont, color: NSColor) {
112
+ let style = NSMutableParagraphStyle()
113
+ style.alignment = .center
114
+ style.lineBreakMode = .byTruncatingTail
115
+ (text as NSString).draw(in: CGRect(x: 2, y: y, width: bounds.width - 4, height: 12),
116
+ withAttributes: [.font: font, .foregroundColor: color, .paragraphStyle: style])
117
+ }
118
+ override func mouseDown(with event: NSEvent) {
119
+ if event.clickCount == 2 { refresh?(); return }
120
+ dragging = true
121
+ dragStart = NSEvent.mouseLocation
122
+ originStart = window?.frame.origin ?? .zero
123
+ }
124
+ override func mouseDragged(with event: NSEvent) {
125
+ guard dragging else { return }
126
+ let point = NSEvent.mouseLocation
127
+ window?.setFrameOrigin(CGPoint(x: originStart.x + point.x - dragStart.x, y: originStart.y + point.y - dragStart.y))
128
+ }
129
+ override func mouseUp(with event: NSEvent) {
130
+ if dragging, let origin = window?.frame.origin { moved?(origin) }
131
+ dragging = false
132
+ }
133
+ override func rightMouseDown(with event: NSEvent) {
134
+ if let menu = makeMenu?() { NSMenu.popUpContextMenu(menu, with: event, for: self) }
135
+ }
136
+ }
137
+
138
+ struct ClockCity {
139
+ let name: String
140
+ let identifier: String
141
+ static let presets: [ClockCity] = [
142
+ ClockCity(name: "硅谷", identifier: "America/Los_Angeles"),
143
+ ClockCity(name: "洛杉矶", identifier: "America/Los_Angeles"),
144
+ ClockCity(name: "西雅图", identifier: "America/Los_Angeles"),
145
+ ClockCity(name: "华盛顿", identifier: "America/New_York"),
146
+ ClockCity(name: "哥伦布", identifier: "America/New_York"),
147
+ ClockCity(name: "新加坡", identifier: "Asia/Singapore"),
148
+ ClockCity(name: "上海", identifier: "Asia/Shanghai")
149
+ ]
150
+ }
151
+
152
+ func clockText(at date: Date, zone: TimeZone) -> String {
153
+ let formatter = DateFormatter()
154
+ formatter.locale = Locale(identifier: "en_US_POSIX")
155
+ formatter.timeZone = zone
156
+ formatter.dateFormat = "HH:mm"
157
+ return formatter.string(from: date)
158
+ }
159
+
160
+ func clockState(at date: Date, zone: TimeZone) -> RingState {
161
+ var calendar = Calendar(identifier: .gregorian)
162
+ calendar.timeZone = zone
163
+ let hour = calendar.component(.hour, from: date)
164
+ if hour >= 9 && hour < 15 { return .green }
165
+ if hour >= 15 { return .orange }
166
+ return .red
167
+ }
168
+
169
+ @MainActor
170
+ final class ClockView: RingView {
171
+ var zone = TimeZone(identifier: "America/Los_Angeles")!
172
+ var cityName = "硅谷"
173
+ override func draw(_ dirtyRect: NSRect) {
174
+ let style = NSMutableParagraphStyle()
175
+ style.alignment = .center
176
+ let now = Date()
177
+ let time = clockText(at: now, zone: zone)
178
+ (time as NSString).draw(in: CGRect(x: 0, y: 17, width: bounds.width, height: 25),
179
+ withAttributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 20, weight: .medium),
180
+ .foregroundColor: clockState(at: now, zone: zone).color, .paragraphStyle: style])
181
+ let city = cityName
182
+ (city as NSString).draw(in: CGRect(x: 0, y: 1, width: bounds.width, height: 15),
183
+ withAttributes: [.font: NSFont.systemFont(ofSize: 10),
184
+ .foregroundColor: NSColor.secondaryLabelColor, .paragraphStyle: style])
185
+ }
186
+ }
187
+
188
+ @MainActor
189
+ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
190
+ let panel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 32, height: 32),
191
+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
192
+ let ring = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
193
+ let clockPanel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 96, height: 46),
194
+ styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
195
+ let clock = ClockView(frame: CGRect(x: 0, y: 0, width: 96, height: 46))
196
+ var clockInset = CGPoint(x: 164, y: 0)
197
+ var clockEnabled = true
198
+ var status: NSStatusItem?
199
+ var timer: Timer?
200
+ var query: Process?
201
+ var snapshot: Snapshot?
202
+ var error: String?
203
+ var lastAttempt = Date.distantPast
204
+ var lastRect: CGRect?
205
+ var inset = CGPoint(x: 138, y: 4)
206
+ var node = ""
207
+ var script = ""
208
+ var searchPath = ""
209
+ var claudeHome = ""
210
+
211
+ func applicationDidFinishLaunching(_ notification: Notification) {
212
+ let args = CommandLine.arguments
213
+ guard args.count >= 4 else { NSApp.terminate(nil); return }
214
+ node = args[1]; script = args[2]; searchPath = args[3]
215
+ claudeHome = args.count > 4 ? args[4] : ""
216
+ let prefs = UserDefaults.standard
217
+ if prefs.object(forKey: "leftInset") != nil {
218
+ inset = CGPoint(x: prefs.double(forKey: "leftInset"), y: prefs.double(forKey: "bottomInset"))
219
+ }
220
+ if let identifier = prefs.string(forKey: "clockTimeZone"), let zone = TimeZone(identifier: identifier) {
221
+ clock.zone = zone
222
+ let savedCity = prefs.string(forKey: "clockCity")
223
+ let preset = ClockCity.presets.first { $0.name == savedCity && $0.identifier == identifier }
224
+ ?? ClockCity.presets.first { $0.identifier == identifier }
225
+ clock.cityName = preset?.name ?? identifier
226
+ }
227
+ ring.showWeeklyPercentage = prefs.bool(forKey: "showWeeklyPercentage")
228
+ clockEnabled = prefs.object(forKey: "clockEnabled") == nil || prefs.bool(forKey: "clockEnabled")
229
+ if prefs.object(forKey: "clockLeftInset") != nil {
230
+ clockInset = CGPoint(x: prefs.double(forKey: "clockLeftInset"), y: prefs.double(forKey: "clockBottomInset"))
231
+ }
232
+ clockPanel.isOpaque = false
233
+ clockPanel.backgroundColor = .clear
234
+ clockPanel.hasShadow = false
235
+ clockPanel.level = .floating
236
+ clockPanel.hidesOnDeactivate = false
237
+ clockPanel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
238
+ clockPanel.contentView = clock
239
+ clock.makeMenu = { [weak self] in self?.makeMenu() ?? NSMenu() }
240
+ clock.moved = { [weak self] point in
241
+ guard let self, let rect = self.lastRect else { return }
242
+ self.clockInset = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY)
243
+ prefs.set(self.clockInset.x, forKey: "clockLeftInset")
244
+ prefs.set(self.clockInset.y, forKey: "clockBottomInset")
245
+ }
246
+ panel.isOpaque = false
247
+ panel.backgroundColor = .clear
248
+ panel.hasShadow = false
249
+ panel.level = .floating
250
+ panel.hidesOnDeactivate = false
251
+ panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
252
+ panel.contentView = ring
253
+ ring.makeMenu = { [weak self] in self?.makeMenu() ?? NSMenu() }
254
+ ring.refresh = { [weak self] in self?.refresh() }
255
+ ring.moved = { [weak self] point in
256
+ guard let self, let rect = self.lastRect else { return }
257
+ self.inset = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY)
258
+ prefs.set(self.inset.x, forKey: "leftInset")
259
+ prefs.set(self.inset.y, forKey: "bottomInset")
260
+ }
261
+ ring.setAccessibilityElement(true)
262
+ ring.setAccessibilityRole(.button)
263
+ status = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
264
+ status?.button?.title = "EA"
265
+ status?.button?.toolTip = "Easy Claude 额度浮窗"
266
+ let menu = NSMenu(); menu.delegate = self; status?.menu = menu
267
+ timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
268
+ NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
269
+ tick()
270
+ }
271
+ @objc func hide() { panel.orderOut(nil); clockPanel.orderOut(nil) }
272
+ @objc func tick() {
273
+ guard let rect = targetWindow() else { hide(); lastRect = nil; return }
274
+ lastRect = rect
275
+ if clockEnabled {
276
+ if !clock.dragging {
277
+ let x: CGFloat = max(rect.minX, min(rect.maxX - 96, rect.minX + clockInset.x))
278
+ let y: CGFloat = max(rect.minY, min(rect.maxY - 46, rect.minY + clockInset.y))
279
+ clockPanel.setFrameOrigin(CGPoint(x: x, y: y))
280
+ }
281
+ clock.needsDisplay = true
282
+ clock.toolTip = "\(clock.cityName) · \(clock.zone.identifier)"
283
+ clock.setAccessibilityLabel("\(clock.cityName) \(clock.zone.identifier) \(clockText(at: Date(), zone: clock.zone))")
284
+ if !clockPanel.isVisible { clockPanel.orderFrontRegardless() }
285
+ } else { clockPanel.orderOut(nil) }
286
+ if !ring.dragging { panel.setFrameOrigin(ringOrigin(in: rect, inset: inset)) }
287
+ if !panel.isVisible { panel.orderFrontRegardless() }
288
+ if Date().timeIntervalSince(lastAttempt) >= 300 { refresh() }
289
+ updateRing()
290
+ }
291
+ func updateRing() {
292
+ let windows = snapshot?.windows ?? []
293
+ let weekly = windows.first { $0.id == "seven_day:primary" }
294
+ let fiveHour = windows.first { $0.id == "five_hour:primary" }
295
+ let now = Date().timeIntervalSince1970
296
+ let snapshotStale = error != nil || snapshot == nil || now - (snapshot?.fetchedAt ?? 0) > 600
297
+ func stale(_ window: UsageWindow?) -> Bool {
298
+ snapshotStale || window?.remaining == nil || (window?.resetsAt.map { $0 <= now } ?? false)
299
+ }
300
+ ring.remaining = fiveHour?.remaining
301
+ ring.stale = stale(fiveHour)
302
+ ring.weeklyRemaining = weekly?.remaining
303
+ ring.weeklyStale = stale(weekly)
304
+ func label(_ value: Double?) -> String { value.map { "\(Int($0.rounded()))%" } ?? "未知" }
305
+ let summary = "外侧粗环 · 周额度:\(label(weekly?.remaining))\(ring.weeklyStale ? "(未知或已过期)" : "")\n内侧细环 · 5 小时:\(label(fiveHour?.remaining))\(ring.stale ? "(未知或已过期)" : "")"
306
+ let fetched = snapshot.map { Date(timeIntervalSince1970: $0.fetchedAt).formatted(date: .omitted, time: .standard) } ?? "尚未更新"
307
+ ring.toolTip = "本机 Claude CLI 账号额度\n\(summary)\n\(error ?? snapshot?.detail ?? "正在读取")\n更新时间:\(fetched)\n中心数字为\(ring.showWeeklyPercentage ? "周" : "5小时")剩余;拖动校准位置;双击刷新;右键打开菜单"
308
+ ring.setAccessibilityLabel("Claude \(summary)")
309
+ ring.needsDisplay = true
310
+ }
311
+ @objc func refresh() {
312
+ guard query == nil else { return }
313
+ lastAttempt = Date()
314
+ let process = Process(), pipe = Pipe()
315
+ process.executableURL = URL(fileURLWithPath: node)
316
+ process.arguments = [script]
317
+ var env = ProcessInfo.processInfo.environment
318
+ env["PATH"] = searchPath
319
+ if !claudeHome.isEmpty { env["CLAUDE_CONFIG_DIR"] = claudeHome }
320
+ process.environment = env
321
+ process.standardOutput = pipe
322
+ process.standardError = FileHandle.nullDevice
323
+ process.terminationHandler = { [weak self] process in
324
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
325
+ Task { @MainActor in
326
+ guard let self else { return }
327
+ self.query = nil
328
+ do {
329
+ let value = try JSONDecoder().decode(Snapshot.self, from: data)
330
+ if let message = value.error { self.error = message }
331
+ else if process.terminationStatus == 0, value.fetchedAt > 0 {
332
+ self.snapshot = value; self.error = nil
333
+ } else { self.error = "额度查询失败" }
334
+ } catch { self.error = "无法读取额度响应,请检查 CLI 和网络" }
335
+ self.updateRing()
336
+ }
337
+ }
338
+ query = process
339
+ do { try process.run() }
340
+ catch { query = nil; self.error = "无法启动额度查询,请重新运行 easy-claude overlay"; updateRing() }
341
+ }
342
+ func item(_ title: String, _ action: Selector?) -> NSMenuItem {
343
+ let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
344
+ item.target = self
345
+ return item
346
+ }
347
+ func makeMenu() -> NSMenu {
348
+ let menu = NSMenu()
349
+ menu.addItem(item("Easy Claude · CLI 账号额度", nil))
350
+ menu.addItem(item(lastRect == nil ? "等待 Claude 前台窗口" : "拖动圆环可调整位置", nil))
351
+ if let error { menu.addItem(item(error, nil)) }
352
+ if snapshot?.restricted == true { menu.addItem(item("服务端提示:当前使用受限", nil)) }
353
+ menu.addItem(.separator())
354
+ for (id, label) in [("five_hour:primary", "5小时"), ("seven_day:primary", "周")] {
355
+ let window = snapshot?.windows.first { $0.id == id }
356
+ let remaining = window?.remaining.map { "\(Int($0.rounded()))%" } ?? "未知"
357
+ let reset: String
358
+ if let seconds = window?.resetsAt {
359
+ let formatter = DateFormatter()
360
+ formatter.locale = Locale(identifier: "zh_CN")
361
+ formatter.timeZone = .current
362
+ formatter.dateFormat = "MM-dd HH:mm"
363
+ reset = formatter.string(from: Date(timeIntervalSince1970: seconds))
364
+ } else { reset = "未知" }
365
+ let option = item("\(label) · \(remaining) · 重置 \(reset)", #selector(selectPercentage(_:)))
366
+ option.representedObject = id
367
+ option.state = (ring.showWeeklyPercentage == (id == "seven_day:primary")) ? .on : .off
368
+ menu.addItem(option)
369
+ }
370
+ menu.addItem(item(query == nil ? "立即刷新" : "正在刷新…", query == nil ? #selector(refresh) : nil))
371
+ menu.addItem(item("恢复默认位置", #selector(resetPosition)))
372
+ menu.addItem(.separator())
373
+ let toggle = item("显示电子时钟", #selector(toggleClock))
374
+ toggle.state = clockEnabled ? .on : .off
375
+ menu.addItem(toggle)
376
+ let zones = NSMenu()
377
+ for city in ClockCity.presets {
378
+ let option = item(city.name, #selector(selectTimeZone(_:)))
379
+ option.representedObject = city.name
380
+ option.state = clock.cityName == city.name && clock.zone.identifier == city.identifier ? .on : .off
381
+ zones.addItem(option)
382
+ }
383
+ zones.addItem(item("自定义时区…", #selector(customTimeZone)))
384
+ let zoneItem = item("时区 · \(clock.cityName)", nil)
385
+ zoneItem.submenu = zones
386
+ menu.addItem(zoneItem)
387
+ menu.addItem(.separator())
388
+ menu.addItem(item("退出浮窗", #selector(quit)))
389
+ return menu
390
+ }
391
+ func menuNeedsUpdate(_ menu: NSMenu) {
392
+ menu.removeAllItems()
393
+ let fresh = makeMenu()
394
+ for item in fresh.items { fresh.removeItem(item); menu.addItem(item) }
395
+ }
396
+ @objc func selectPercentage(_ sender: NSMenuItem) {
397
+ guard let id = sender.representedObject as? String else { return }
398
+ ring.showWeeklyPercentage = id == "seven_day:primary"
399
+ UserDefaults.standard.set(ring.showWeeklyPercentage, forKey: "showWeeklyPercentage")
400
+ updateRing()
401
+ }
402
+ @objc func toggleClock() {
403
+ clockEnabled.toggle()
404
+ UserDefaults.standard.set(clockEnabled, forKey: "clockEnabled")
405
+ tick()
406
+ }
407
+ func setTimeZone(_ identifier: String, cityName: String? = nil) -> Bool {
408
+ guard let zone = TimeZone(identifier: identifier) else { return false }
409
+ clock.zone = zone
410
+ clock.cityName = cityName ?? ClockCity.presets.first { $0.identifier == zone.identifier }?.name ?? zone.identifier
411
+ UserDefaults.standard.set(clock.cityName, forKey: "clockCity")
412
+ UserDefaults.standard.set(zone.identifier, forKey: "clockTimeZone")
413
+ clock.needsDisplay = true
414
+ return true
415
+ }
416
+ @objc func selectTimeZone(_ sender: NSMenuItem) {
417
+ if let name = sender.representedObject as? String,
418
+ let city = ClockCity.presets.first(where: { $0.name == name }) {
419
+ _ = setTimeZone(city.identifier, cityName: city.name)
420
+ }
421
+ }
422
+ @objc func customTimeZone() {
423
+ let alert = NSAlert()
424
+ alert.messageText = "设置电子时钟时区"
425
+ alert.informativeText = "输入 IANA 时区,例如 America/Los_Angeles;自动适应夏令时。"
426
+ let field = NSTextField(string: clock.zone.identifier)
427
+ field.frame = CGRect(x: 0, y: 0, width: 300, height: 24)
428
+ alert.accessoryView = field
429
+ alert.addButton(withTitle: "保存")
430
+ alert.addButton(withTitle: "取消")
431
+ NSApp.activate(ignoringOtherApps: true)
432
+ while alert.runModal() == .alertFirstButtonReturn {
433
+ if setTimeZone(field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines)) { break }
434
+ alert.informativeText = "无效时区,请输入有效的 IANA 名称,例如 America/Los_Angeles。"
435
+ }
436
+ }
437
+ @objc func resetPosition() {
438
+ clockInset = CGPoint(x: 164, y: 0)
439
+ UserDefaults.standard.removeObject(forKey: "clockLeftInset")
440
+ UserDefaults.standard.removeObject(forKey: "clockBottomInset")
441
+ inset = CGPoint(x: 138, y: 4)
442
+ UserDefaults.standard.removeObject(forKey: "leftInset")
443
+ UserDefaults.standard.removeObject(forKey: "bottomInset")
444
+ tick()
445
+ }
446
+ @objc func quit() { NSApp.terminate(nil) }
447
+ func applicationWillTerminate(_ notification: Notification) {
448
+ timer?.invalidate()
449
+ query?.terminate()
450
+ NSWorkspace.shared.notificationCenter.removeObserver(self)
451
+ }
452
+ }
453
+
454
+ @main
455
+ struct Main {
456
+ @MainActor static func main() {
457
+ if CommandLine.arguments.contains("--self-test") {
458
+ precondition(ClockCity.presets.map(\.name) == ["硅谷", "洛杉矶", "西雅图", "华盛顿", "哥伦布", "新加坡", "上海"])
459
+ precondition(ClockCity.presets.allSatisfy { TimeZone(identifier: $0.identifier) != nil })
460
+ let la = TimeZone(identifier: "America/Los_Angeles")!
461
+ let singapore = TimeZone(identifier: "Asia/Singapore")!
462
+ let winter = ISO8601DateFormatter().date(from: "2026-01-15T12:00:00Z")!
463
+ let summer = ISO8601DateFormatter().date(from: "2026-07-15T12:00:00Z")!
464
+ precondition(clockText(at: winter, zone: la) == "04:00")
465
+ precondition(clockText(at: summer, zone: la) == "05:00")
466
+ precondition(clockText(at: winter, zone: singapore) == "20:00")
467
+ precondition(TimeZone(identifier: "Invalid/Zone") == nil)
468
+ let utc = TimeZone(secondsFromGMT: 0)!
469
+ for (hour, state) in [(0, RingState.red), (6, .red), (8, .red), (9, .green), (14, .green), (15, .orange), (23, .orange)] {
470
+ let date = Date(timeIntervalSince1970: Double(hour * 3600))
471
+ precondition(clockState(at: date, zone: utc) == state)
472
+ }
473
+ precondition(clockState(at: winter, zone: la) == .red)
474
+ precondition(clockState(at: winter, zone: singapore) == .orange)
475
+ assert(RingState.resolve(51, stale: false) == .green)
476
+ assert(RingState.resolve(50, stale: false) == .orange)
477
+ assert(RingState.resolve(20, stale: false) == .orange)
478
+ assert(RingState.resolve(19, stale: false) == .red)
479
+ assert(RingState.resolve(nil, stale: false) == .unknown)
480
+ assert(RingState.resolve(99, stale: true) == .unknown)
481
+ assert(appKitRect(CGRect(x: -900, y: 100, width: 800, height: 600), primaryHeight: 900).origin == CGPoint(x: -900, y: 200))
482
+ let bounds = CGRect(x: 100, y: 100, width: 800, height: 600)
483
+ assert(ringOrigin(in: bounds, inset: CGPoint(x: 138, y: 4)) == CGPoint(x: 238, y: 104))
484
+ assert(ringOrigin(in: bounds, inset: CGPoint(x: -100, y: -100)) == CGPoint(x: 100, y: 100))
485
+ assert(ringOrigin(in: bounds, inset: CGPoint(x: 9999, y: 9999)) == CGPoint(x: 868, y: 668))
486
+ print("Swift 圆环颜色与窗口坐标检查通过")
487
+ return
488
+ }
489
+ let app = NSApplication.shared
490
+ app.setActivationPolicy(.accessory)
491
+ if CommandLine.arguments.contains("--diagnose") {
492
+ print("targetFrontmost=\(NSWorkspace.shared.frontmostApplication?.bundleIdentifier == "com.anthropic.claudefordesktop")")
493
+ print("targetWindow=\(targetWindow().map { NSStringFromRect($0) } ?? "unavailable")")
494
+ return
495
+ }
496
+ if let i = CommandLine.arguments.firstIndex(of: "--render-preview"), CommandLine.arguments.count > i + 1 {
497
+ let image = NSImage(size: NSSize(width: 340, height: 100))
498
+ image.lockFocus()
499
+ for (index, value) in [75.0, 35.0, 10.0, -1.0].enumerated() {
500
+ NSGraphicsContext.saveGraphicsState()
501
+ let transform = AffineTransform(translationByX: CGFloat(index * 84 + 4), byY: 8)
502
+ (transform as NSAffineTransform).concat()
503
+ let view = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
504
+ view.remaining = value < 0 ? nil : value; view.stale = value < 0
505
+ view.weeklyRemaining = value < 0 ? nil : 100 - value; view.weeklyStale = value < 0
506
+ view.caption = value < 0 ? "额度未知" : "7天"
507
+ view.draw(view.bounds)
508
+ NSGraphicsContext.restoreGraphicsState()
509
+ }
510
+ image.unlockFocus()
511
+ if let tiff = image.tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiff), let png = bitmap.representation(using: .png, properties: [:]) {
512
+ do { try png.write(to: URL(fileURLWithPath: CommandLine.arguments[i+1])) }
513
+ catch { fputs("预览写入失败\n", stderr); exit(1) }
514
+ }
515
+ return
516
+ }
517
+ let delegate = Overlay()
518
+ app.delegate = delegate
519
+ withExtendedLifetime(delegate) { app.run() }
520
+ }
521
+ }
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>CFBundleExecutable</key><string>EasyClaudeOverlay</string>
5
+ <key>CFBundleIdentifier</key><string>com.unionschool.easy-claude.overlay</string>
6
+ <key>CFBundleName</key><string>Easy Claude Overlay</string>
7
+ <key>CFBundlePackageType</key><string>APPL</string>
8
+ <key>CFBundleShortVersionString</key><string>0.2.0</string>
9
+ <key>LSMinimumSystemVersion</key><string>14.0</string>
10
+ <key>LSUIElement</key><true/>
11
+ <key>NSHighResolutionCapable</key><true/>
12
+ </dict></plist>
@@ -0,0 +1,115 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>files</key>
6
+ <dict/>
7
+ <key>files2</key>
8
+ <dict/>
9
+ <key>rules</key>
10
+ <dict>
11
+ <key>^Resources/</key>
12
+ <true/>
13
+ <key>^Resources/.*\.lproj/</key>
14
+ <dict>
15
+ <key>optional</key>
16
+ <true/>
17
+ <key>weight</key>
18
+ <real>1000</real>
19
+ </dict>
20
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
21
+ <dict>
22
+ <key>omit</key>
23
+ <true/>
24
+ <key>weight</key>
25
+ <real>1100</real>
26
+ </dict>
27
+ <key>^Resources/Base\.lproj/</key>
28
+ <dict>
29
+ <key>weight</key>
30
+ <real>1010</real>
31
+ </dict>
32
+ <key>^version.plist$</key>
33
+ <true/>
34
+ </dict>
35
+ <key>rules2</key>
36
+ <dict>
37
+ <key>.*\.dSYM($|/)</key>
38
+ <dict>
39
+ <key>weight</key>
40
+ <real>11</real>
41
+ </dict>
42
+ <key>^(.*/)?\.DS_Store$</key>
43
+ <dict>
44
+ <key>omit</key>
45
+ <true/>
46
+ <key>weight</key>
47
+ <real>2000</real>
48
+ </dict>
49
+ <key>^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/</key>
50
+ <dict>
51
+ <key>nested</key>
52
+ <true/>
53
+ <key>weight</key>
54
+ <real>10</real>
55
+ </dict>
56
+ <key>^.*</key>
57
+ <true/>
58
+ <key>^Info\.plist$</key>
59
+ <dict>
60
+ <key>omit</key>
61
+ <true/>
62
+ <key>weight</key>
63
+ <real>20</real>
64
+ </dict>
65
+ <key>^PkgInfo$</key>
66
+ <dict>
67
+ <key>omit</key>
68
+ <true/>
69
+ <key>weight</key>
70
+ <real>20</real>
71
+ </dict>
72
+ <key>^Resources/</key>
73
+ <dict>
74
+ <key>weight</key>
75
+ <real>20</real>
76
+ </dict>
77
+ <key>^Resources/.*\.lproj/</key>
78
+ <dict>
79
+ <key>optional</key>
80
+ <true/>
81
+ <key>weight</key>
82
+ <real>1000</real>
83
+ </dict>
84
+ <key>^Resources/.*\.lproj/locversion.plist$</key>
85
+ <dict>
86
+ <key>omit</key>
87
+ <true/>
88
+ <key>weight</key>
89
+ <real>1100</real>
90
+ </dict>
91
+ <key>^Resources/Base\.lproj/</key>
92
+ <dict>
93
+ <key>weight</key>
94
+ <real>1010</real>
95
+ </dict>
96
+ <key>^[^/]+$</key>
97
+ <dict>
98
+ <key>nested</key>
99
+ <true/>
100
+ <key>weight</key>
101
+ <real>10</real>
102
+ </dict>
103
+ <key>^embedded\.provisionprofile$</key>
104
+ <dict>
105
+ <key>weight</key>
106
+ <real>20</real>
107
+ </dict>
108
+ <key>^version\.plist$</key>
109
+ <dict>
110
+ <key>weight</key>
111
+ <real>20</real>
112
+ </dict>
113
+ </dict>
114
+ </dict>
115
+ </plist>
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "easy-claude",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Claude Code quota rings and transparent world clock for Claude desktop",
5
+ "type": "module",
6
+ "bin": {
7
+ "easy-claude": "bin/easy-claude.js"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md",
13
+ "native/Overlay.swift",
14
+ "native/build/EasyClaudeOverlay.app",
15
+ "scripts/build-overlay.mjs"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "scripts": {
21
+ "test": "node --test",
22
+ "start": "node bin/easy-claude.js",
23
+ "build:overlay": "node scripts/build-overlay.mjs"
24
+ },
25
+ "license": "MIT",
26
+ "author": "UnionSchool",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/UnionSchool/easy-claude.git"
30
+ },
31
+ "homepage": "https://github.com/UnionSchool/easy-claude#readme",
32
+ "bugs": {
33
+ "url": "https://github.com/UnionSchool/easy-claude/issues"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public",
37
+ "registry": "https://registry.npmjs.org"
38
+ }
39
+ }
@@ -0,0 +1,34 @@
1
+ import { readFileSync } from 'node:fs';
2
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
3
+ import { mkdir, writeFile, mkdtemp, rm } from 'node:fs/promises';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { fileURLToPath } from 'node:url';
6
+ const root = fileURLToPath(new URL('../', import.meta.url));
7
+ if (process.platform !== 'darwin') throw new Error('浮窗只能在 macOS 构建。');
8
+ const app = `${root}native/build/EasyClaudeOverlay.app/Contents`;
9
+ await mkdir(`${app}/MacOS`, { recursive: true });
10
+ const temporary = await mkdtemp('/tmp/easy-claude-build-');
11
+ try {
12
+ for (const architecture of ['arm64', 'x86_64']) {
13
+ execFileSync('xcrun', ['swiftc', '-swift-version', '6', '-parse-as-library',
14
+ '-target', `${architecture}-apple-macosx14.0`, '-module-cache-path', `${temporary}/cache`,
15
+ `${root}native/Overlay.swift`, '-o', `${temporary}/${architecture}`, '-framework', 'AppKit'], { stdio: 'inherit' });
16
+ }
17
+ execFileSync('lipo', ['-create', `${temporary}/arm64`, `${temporary}/x86_64`, '-output', `${app}/MacOS/EasyClaudeOverlay`], { stdio: 'inherit' });
18
+ } finally {
19
+ await rm(temporary, { recursive: true, force: true });
20
+ }
21
+ await writeFile(`${app}/Info.plist`, `<?xml version="1.0" encoding="UTF-8"?>
22
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
23
+ <plist version="1.0"><dict>
24
+ <key>CFBundleExecutable</key><string>EasyClaudeOverlay</string>
25
+ <key>CFBundleIdentifier</key><string>com.unionschool.easy-claude.overlay</string>
26
+ <key>CFBundleName</key><string>Easy Claude Overlay</string>
27
+ <key>CFBundlePackageType</key><string>APPL</string>
28
+ <key>CFBundleShortVersionString</key><string>${version}</string>
29
+ <key>LSMinimumSystemVersion</key><string>14.0</string>
30
+ <key>LSUIElement</key><true/>
31
+ <key>NSHighResolutionCapable</key><true/>
32
+ </dict></plist>`);
33
+ execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', `${root}native/build/EasyClaudeOverlay.app`], { stdio: 'inherit' });
34
+ execFileSync(`${app}/MacOS/EasyClaudeOverlay`, ['--self-test'], { stdio: 'inherit' });
package/src/format.js ADDED
@@ -0,0 +1,37 @@
1
+ function duration(minutes, fallback) {
2
+ if (!Number.isFinite(minutes) || minutes <= 0) return fallback;
3
+ if (minutes % 1440 === 0) return `${minutes / 1440} 天`;
4
+ if (minutes % 60 === 0) return `${minutes / 60} 小时`;
5
+ return `${minutes} 分钟`;
6
+ }
7
+
8
+ function windowText(window, label) {
9
+ if (!window || typeof window !== 'object') return ` ${label}:未知(未提供数据)`;
10
+ const remaining = Number.isFinite(window.usedPercent)
11
+ ? `${Number(Math.max(0, Math.min(100, 100 - window.usedPercent)).toFixed(1))}%`
12
+ : '未知';
13
+ const date = Number.isFinite(window.resetsAt) ? new Date(window.resetsAt * 1000) : null;
14
+ const reset = date && Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '未知';
15
+ return ` ${duration(window.windowDurationMins, label)}:剩余 ${remaining};重置 ${reset}`;
16
+ }
17
+
18
+ export function formatUsage(result) {
19
+ if (!result || typeof result !== 'object') throw new Error('额度响应格式无效。');
20
+ const buckets = result.rateLimitsByLimitId;
21
+ const entries = buckets && typeof buckets === 'object' && !Array.isArray(buckets)
22
+ ? Object.entries(buckets).filter(([, value]) => value && typeof value === 'object') : [];
23
+ if (!entries.length && result.rateLimits && typeof result.rateLimits === 'object') {
24
+ entries.push([result.rateLimits.limitId ?? 'claude', result.rateLimits]);
25
+ }
26
+ if (!entries.length) throw new Error('服务端未提供额度数据,无法判断剩余额度。');
27
+ const output = ['Claude Code 剩余额度(账号共享,非当前会话)'];
28
+ for (const [id, bucket] of entries) {
29
+ // 限制服务端标签中的控制字符,避免终端转义序列影响显示。
30
+ const label = String(bucket.limitName || bucket.limitId || id).replace(/[\x00-\x1f\x7f-\x9f]/g, '');
31
+ output.push(label, windowText(bucket.primary, '主窗口'));
32
+ if (bucket.secondary) output.push(windowText(bucket.secondary, '次窗口'));
33
+ }
34
+ if (result.ordinaryUsageAllowed === false) output.push('服务端提示:当前普通额度使用受限。');
35
+ output.push(`重置时间使用本机时区:${Intl.DateTimeFormat().resolvedOptions().timeZone}`);
36
+ return output.join('\n');
37
+ }
@@ -0,0 +1,25 @@
1
+ import { formatUsage } from './usage.js';
2
+
3
+ export function overlayData(result, now = Date.now()) {
4
+ const detail = formatUsage(result);
5
+ const map = result.rateLimitsByLimitId;
6
+ const entries = map && typeof map === 'object' && !Array.isArray(map)
7
+ ? Object.entries(map).filter(([, b]) => b && typeof b === 'object') : [];
8
+ if (!entries.length) entries.push([result.rateLimits.limitId ?? 'claude', result.rateLimits]);
9
+ const windows = [];
10
+ for (const [id, bucket] of entries) {
11
+ for (const key of ['primary', 'secondary']) {
12
+ const w = bucket[key];
13
+ if (!w) continue;
14
+ const mins = w.windowDurationMins;
15
+ const label = Number.isFinite(mins) && mins > 0
16
+ ? mins % 1440 === 0 ? `${mins / 1440}天` : mins % 60 === 0 ? `${mins / 60}小时` : `${mins}分钟`
17
+ : key === 'primary' ? '主窗口' : '次窗口';
18
+ windows.push({ id: `${id}:${key}`, label,
19
+ name: `${String(bucket.limitName || id).replace(/[\x00-\x1f\x7f-\x9f]/g, '')} · ${label}`,
20
+ remaining: Number.isFinite(w.usedPercent) ? Math.max(0, Math.min(100, 100 - w.usedPercent)) : null,
21
+ resetsAt: Number.isFinite(w.resetsAt) && Math.abs(w.resetsAt) < 8.64e12 ? w.resetsAt : null });
22
+ }
23
+ }
24
+ return { windows, detail, fetchedAt: now / 1000, restricted: result.ordinaryUsageAllowed === false };
25
+ }
@@ -0,0 +1,14 @@
1
+ import { readUsage } from './usage.js';
2
+ import { overlayData } from './overlay-data.js';
3
+ const controller = new AbortController();
4
+ process.once('SIGTERM', () => controller.abort());
5
+ process.once('SIGINT', () => controller.abort());
6
+ try {
7
+ const text = JSON.stringify(overlayData(await readUsage({ signal: controller.signal })));
8
+ // 原生端在进程结束后读取管道;限制体积以免写端等待管道空间。
9
+ if (Buffer.byteLength(text) > 12000) throw new Error('额度响应过大,请使用 easy-claude 查看完整数据。');
10
+ console.log(text);
11
+ } catch (error) {
12
+ console.log(JSON.stringify({ error: error.message }));
13
+ process.exitCode = 1;
14
+ }
package/src/overlay.js ADDED
@@ -0,0 +1,15 @@
1
+ import { access } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+
7
+ export async function launchOverlay() {
8
+ if (process.platform !== 'darwin') throw new Error('浮窗首版仅支持 macOS。');
9
+ const app = fileURLToPath(new URL('../native/build/EasyClaudeOverlay.app', import.meta.url));
10
+ try { await access(`${app}/Contents/MacOS/EasyClaudeOverlay`, constants.X_OK); }
11
+ catch { throw new Error('尚未构建浮窗,请在项目目录执行 npm run build:overlay。'); }
12
+ await promisify(execFile)('/usr/bin/open', ['-g', '-a', app, '--args',
13
+ process.execPath, fileURLToPath(new URL('./overlay-query.js', import.meta.url)), process.env.PATH ?? '', process.env.CLAUDE_CONFIG_DIR ?? '']);
14
+ console.log('额度与电子时钟浮窗已启动;Claude 在前台时显示。拖动调整位置,右键或菜单栏 EA 可设置时区、查看双环额度和退出。');
15
+ }
@@ -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 ADDED
@@ -0,0 +1,76 @@
1
+ import { quotaFetch } from './transport.js';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { execFile } from 'node:child_process';
6
+ import { promisify } from 'node:util';
7
+ export { formatUsage } from './format.js';
8
+ const run = promisify(execFile);
9
+ const loginMessage = '请执行 claude auth login 登录与 Claude 桌面相同的订阅账号。';
10
+
11
+ export function credentialToken(raw, now = Date.now()) {
12
+ let auth;
13
+ try { auth = JSON.parse(raw)?.claudeAiOauth; } catch { throw new Error(`Claude Code 登录数据格式不受支持。${loginMessage}`); }
14
+ if (!auth || typeof auth.accessToken !== 'string' || !auth.accessToken.trim()) throw new Error(loginMessage);
15
+ if (Number.isFinite(auth.expiresAt) && auth.expiresAt <= now) throw new Error(`Claude Code 登录已过期。${loginMessage}`);
16
+ return auth.accessToken;
17
+ }
18
+
19
+ export async function loadToken({ signal } = {}) {
20
+ let raw;
21
+ // 自定义配置目录不猜测钥匙串名称,以免读到另一个账号。
22
+ if (process.platform === 'darwin' && !process.env.CLAUDE_CONFIG_DIR) {
23
+ try { raw = (await run('/usr/bin/security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], { timeout: 5000, maxBuffer: 1024 * 1024, signal })).stdout; }
24
+ catch { if (signal?.aborted) throw new Error('查询已取消。'); }
25
+ }
26
+ if (!raw) {
27
+ try { raw = await readFile(join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), '.credentials.json'), { encoding: 'utf8', signal }); }
28
+ catch { throw new Error(signal?.aborted ? '查询已取消。' : `未找到可读取的 Claude Code 订阅登录。${loginMessage}`); }
29
+ }
30
+ return credentialToken(raw);
31
+ }
32
+
33
+ export function normalizeUsage(data) {
34
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('额度响应格式无效。');
35
+ const rateLimitsByLimitId = {};
36
+ for (const [key, value] of Object.entries(data)) {
37
+ if (!/^(five_hour|seven_day)(_[a-z0-9_]+)?$/.test(key) || value == null) continue;
38
+ if (typeof value !== 'object' || Array.isArray(value)) throw new Error('额度窗口格式无效。');
39
+ // 明细汇总也使用 seven_day 前缀,只有比例字段才代表额度窗口。
40
+ if (!Object.hasOwn(value, 'utilization')) continue;
41
+ const used = value.utilization;
42
+ if (used != null && (!Number.isFinite(used) || used < 0 || used > 100)) throw new Error('额度比例格式无效。');
43
+ const reset = typeof value.resets_at === 'string' ? Date.parse(value.resets_at) / 1000 : null;
44
+ const primary = { usedPercent: used ?? null, resetsAt: Number.isFinite(reset) ? reset : null, windowDurationMins: key.startsWith('five_hour') ? 300 : 10080 };
45
+ const label = key === 'five_hour' ? 'Claude · 5 小时' : key === 'seven_day' ? 'Claude · 7 天' : key.replaceAll('_', ' ');
46
+ rateLimitsByLimitId[key] = { limitId: key, limitName: label, primary };
47
+ }
48
+ if (!Object.keys(rateLimitsByLimitId).length) throw new Error('服务端未提供订阅额度,不能判断剩余额度;API Key 余额不在范围内。');
49
+ return { rateLimitsByLimitId };
50
+ }
51
+
52
+ export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToken, fetchImpl = quotaFetch } = {}) {
53
+ const controller = new AbortController();
54
+ const abort = () => controller.abort();
55
+ if (signal?.aborted) throw new Error('查询已取消。');
56
+ signal?.addEventListener('abort', abort, { once: true });
57
+ const timer = setTimeout(abort, timeoutMs);
58
+ try {
59
+ const token = await getToken({ signal: controller.signal });
60
+ // 固定官方源且禁止重定向,避免登录凭据发送到其他站点。
61
+ const response = await fetchImpl('https://api.anthropic.com/api/oauth/usage', {
62
+ headers: { authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20', accept: 'application/json' },
63
+ redirect: 'error', signal: controller.signal,
64
+ }).catch(() => { throw new Error('无法连接 Claude 额度服务,请检查网络。'); });
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,不能仅据此判断登录已过期。');
67
+ if (response.status === 429) throw new Error('额度查询过于频繁,请稍后再试。');
68
+ if (!response.ok) throw new Error(`Claude 额度服务暂不可用(HTTP ${response.status})。`);
69
+ let data;
70
+ try { data = await response.json(); } catch { throw new Error('Claude 返回了无效的额度数据。'); }
71
+ return normalizeUsage(data);
72
+ } catch (error) {
73
+ if (controller.signal.aborted) throw new Error(signal?.aborted ? '查询已取消。' : '额度查询超时,请检查网络。');
74
+ throw error;
75
+ } finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
76
+ }