easy-claude 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +48 -2
- package/bin/easy-claude.js +20 -0
- package/native/Overlay.swift +339 -0
- package/native/build/EasyClaudeOverlay.app/Contents/Info.plist +12 -0
- package/native/build/EasyClaudeOverlay.app/Contents/MacOS/EasyClaudeOverlay +0 -0
- package/native/build/EasyClaudeOverlay.app/Contents/_CodeSignature/CodeResources +115 -0
- package/package.json +37 -4
- package/scripts/build-overlay.mjs +34 -0
- package/src/format.js +37 -0
- package/src/overlay-data.js +25 -0
- package/src/overlay-query.js +14 -0
- package/src/overlay.js +15 -0
- package/src/usage.js +74 -0
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,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# easy-claude
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
- 默认显示剩余最少的已知窗口;右键切换窗口、刷新、恢复位置或退出,双击刷新,拖动校准。
|
|
22
|
+
- 可见时每 5 分钟查询,10 分钟前的快照或已到重置时间的数据标为过期;接口错误会立即标记未知。
|
|
23
|
+
- 不显示“7天”等底部文字,详情在悬停提示和菜单。菜单栏标记为 EA。
|
|
24
|
+
- 基于窗口边界定位,不识别头像,不读取桌面聊天或截图;无法自动核对桌面账号与 CLI 账号一致。
|
|
25
|
+
|
|
26
|
+
## 数据与认证边界
|
|
27
|
+
|
|
28
|
+
使用本机 Claude Code 中存在的 `https://api.anthropic.com/api/oauth/usage` 接口,仅发送只读 GET,不创建模型请求或刷新/修改凭据。它不是公开稳定 API,可能因服务调整失效。
|
|
29
|
+
|
|
30
|
+
macOS 优先读取 `Claude Code-credentials` 钥匙串项;其他情况读取 Claude Code 的 `.credentials.json`。设置 `CLAUDE_CONFIG_DIR` 时只读取该目录的凭据文件,不猜测自定义钥匙串名称。可能需要系统允许访问已有钥匙串项。
|
|
31
|
+
|
|
32
|
+
登录令牌只在内存中用于固定官方源;禁止跟随重定向,不输出原始错误正文或令牌。查询总超时 15 秒,遇到 429 提示稍后重试。OAuth 权限可能不足;如重新登录仍无法查询,应停止请求并检查接口兼容性。
|
|
33
|
+
|
|
34
|
+
展示服务端 `utilization` 的剩余值 `100 - utilization`。各窗口独立,额外付费额度不混入百分比。未知字段不硬编码为零。此接口读取的是订阅窗口,不是当前聊天上下文剩余量。
|
|
35
|
+
|
|
36
|
+
## 开发
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npm test
|
|
40
|
+
npm run build:overlay
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
构建需要 Swift 6 与 Xcode Command Line Tools,生成 Intel/Apple Silicon 通用应用;使用 ad-hoc 签名,未开发者签名或公证。测试使用模拟响应,不发送模型请求。
|
|
44
|
+
|
|
45
|
+
## 发布
|
|
46
|
+
|
|
47
|
+
升级 package.json 版本,提交后推送同版本 v 标签,由 GitHub Actions 自动测试、构建通用浮窗并发布 npm。稳定版使用 latest,预发布使用 next。发布任务使用 npm Environment,仓库 Deployments 可查看记录。
|
|
48
|
+
|
|
49
|
+
发布使用 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,339 @@
|
|
|
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
|
+
final class RingView: NSView {
|
|
72
|
+
var remaining: Double?
|
|
73
|
+
var stale = true
|
|
74
|
+
var caption = "等待额度"
|
|
75
|
+
var makeMenu: (() -> NSMenu)?
|
|
76
|
+
var moved: ((CGPoint) -> Void)?
|
|
77
|
+
var refresh: (() -> Void)?
|
|
78
|
+
var dragging = false
|
|
79
|
+
private var dragStart = CGPoint.zero
|
|
80
|
+
private var originStart = CGPoint.zero
|
|
81
|
+
|
|
82
|
+
override func draw(_ dirtyRect: NSRect) {
|
|
83
|
+
let center = CGPoint(x: bounds.midX, y: bounds.midY)
|
|
84
|
+
let track = NSBezierPath(ovalIn: CGRect(x: center.x - 14, y: center.y - 14, width: 28, height: 28))
|
|
85
|
+
track.lineWidth = 2
|
|
86
|
+
NSColor.labelColor.withAlphaComponent(0.12).setStroke()
|
|
87
|
+
track.stroke()
|
|
88
|
+
let state = RingState.resolve(remaining, stale: stale)
|
|
89
|
+
if let remaining, remaining > 0, !stale {
|
|
90
|
+
let arc = NSBezierPath()
|
|
91
|
+
arc.lineWidth = 2
|
|
92
|
+
arc.lineCapStyle = .round
|
|
93
|
+
arc.appendArc(withCenter: center, radius: 14, startAngle: 90,
|
|
94
|
+
endAngle: 90 - CGFloat(min(100, max(0, remaining))) * 3.6, clockwise: true)
|
|
95
|
+
state.color.setStroke()
|
|
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)
|
|
100
|
+
}
|
|
101
|
+
private func drawText(_ text: String, y: CGFloat, font: NSFont, color: NSColor) {
|
|
102
|
+
let style = NSMutableParagraphStyle()
|
|
103
|
+
style.alignment = .center
|
|
104
|
+
style.lineBreakMode = .byTruncatingTail
|
|
105
|
+
(text as NSString).draw(in: CGRect(x: 2, y: y, width: bounds.width - 4, height: 12),
|
|
106
|
+
withAttributes: [.font: font, .foregroundColor: color, .paragraphStyle: style])
|
|
107
|
+
}
|
|
108
|
+
override func mouseDown(with event: NSEvent) {
|
|
109
|
+
if event.clickCount == 2 { refresh?(); return }
|
|
110
|
+
dragging = true
|
|
111
|
+
dragStart = NSEvent.mouseLocation
|
|
112
|
+
originStart = window?.frame.origin ?? .zero
|
|
113
|
+
}
|
|
114
|
+
override func mouseDragged(with event: NSEvent) {
|
|
115
|
+
guard dragging else { return }
|
|
116
|
+
let point = NSEvent.mouseLocation
|
|
117
|
+
window?.setFrameOrigin(CGPoint(x: originStart.x + point.x - dragStart.x, y: originStart.y + point.y - dragStart.y))
|
|
118
|
+
}
|
|
119
|
+
override func mouseUp(with event: NSEvent) {
|
|
120
|
+
if dragging, let origin = window?.frame.origin { moved?(origin) }
|
|
121
|
+
dragging = false
|
|
122
|
+
}
|
|
123
|
+
override func rightMouseDown(with event: NSEvent) {
|
|
124
|
+
if let menu = makeMenu?() { NSMenu.popUpContextMenu(menu, with: event, for: self) }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@MainActor
|
|
129
|
+
final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
|
130
|
+
let panel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 32, height: 32),
|
|
131
|
+
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
|
132
|
+
let ring = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
|
|
133
|
+
var status: NSStatusItem?
|
|
134
|
+
var timer: Timer?
|
|
135
|
+
var query: Process?
|
|
136
|
+
var snapshot: Snapshot?
|
|
137
|
+
var error: String?
|
|
138
|
+
var selectedID: String?
|
|
139
|
+
var lastAttempt = Date.distantPast
|
|
140
|
+
var lastRect: CGRect?
|
|
141
|
+
var inset = CGPoint(x: 10, y: 74)
|
|
142
|
+
var node = ""
|
|
143
|
+
var script = ""
|
|
144
|
+
var searchPath = ""
|
|
145
|
+
var claudeHome = ""
|
|
146
|
+
|
|
147
|
+
func applicationDidFinishLaunching(_ notification: Notification) {
|
|
148
|
+
let args = CommandLine.arguments
|
|
149
|
+
guard args.count >= 4 else { NSApp.terminate(nil); return }
|
|
150
|
+
node = args[1]; script = args[2]; searchPath = args[3]
|
|
151
|
+
claudeHome = args.count > 4 ? args[4] : ""
|
|
152
|
+
let prefs = UserDefaults.standard
|
|
153
|
+
if prefs.object(forKey: "leftInset") != nil {
|
|
154
|
+
inset = CGPoint(x: prefs.double(forKey: "leftInset"), y: prefs.double(forKey: "bottomInset"))
|
|
155
|
+
}
|
|
156
|
+
selectedID = prefs.string(forKey: "selectedWindow")
|
|
157
|
+
panel.isOpaque = false
|
|
158
|
+
panel.backgroundColor = .clear
|
|
159
|
+
panel.hasShadow = false
|
|
160
|
+
panel.level = .floating
|
|
161
|
+
panel.hidesOnDeactivate = false
|
|
162
|
+
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
|
|
163
|
+
panel.contentView = ring
|
|
164
|
+
ring.makeMenu = { [weak self] in self?.makeMenu() ?? NSMenu() }
|
|
165
|
+
ring.refresh = { [weak self] in self?.refresh() }
|
|
166
|
+
ring.moved = { [weak self] point in
|
|
167
|
+
guard let self, let rect = self.lastRect else { return }
|
|
168
|
+
self.inset = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY)
|
|
169
|
+
prefs.set(self.inset.x, forKey: "leftInset")
|
|
170
|
+
prefs.set(self.inset.y, forKey: "bottomInset")
|
|
171
|
+
}
|
|
172
|
+
ring.setAccessibilityElement(true)
|
|
173
|
+
ring.setAccessibilityRole(.button)
|
|
174
|
+
status = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
|
|
175
|
+
status?.button?.title = "EA"
|
|
176
|
+
status?.button?.toolTip = "Easy Claude 额度浮窗"
|
|
177
|
+
let menu = NSMenu(); menu.delegate = self; status?.menu = menu
|
|
178
|
+
timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
|
|
179
|
+
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
|
|
180
|
+
tick()
|
|
181
|
+
}
|
|
182
|
+
@objc func hide() { panel.orderOut(nil) }
|
|
183
|
+
@objc func tick() {
|
|
184
|
+
guard let rect = targetWindow() else { panel.orderOut(nil); lastRect = nil; return }
|
|
185
|
+
lastRect = rect
|
|
186
|
+
if !ring.dragging { panel.setFrameOrigin(ringOrigin(in: rect, inset: inset)) }
|
|
187
|
+
if !panel.isVisible { panel.orderFrontRegardless() }
|
|
188
|
+
if Date().timeIntervalSince(lastAttempt) >= 300 { refresh() }
|
|
189
|
+
updateRing()
|
|
190
|
+
}
|
|
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
|
+
func updateRing() {
|
|
200
|
+
let stale = error != nil || snapshot == nil || Date().timeIntervalSince1970 - (snapshot?.fetchedAt ?? 0) > 600
|
|
201
|
+
|| (chosen?.resetsAt.map { $0 <= Date().timeIntervalSince1970 } ?? false)
|
|
202
|
+
ring.remaining = chosen?.remaining
|
|
203
|
+
ring.stale = stale
|
|
204
|
+
ring.caption = stale ? (snapshot == nil ? "等待额度" : "数据过期") : chosen?.label ?? "额度未知"
|
|
205
|
+
let fetched = snapshot.map { Date(timeIntervalSince1970: $0.fetchedAt).formatted(date: .omitted, time: .standard) } ?? "尚未更新"
|
|
206
|
+
ring.toolTip = "本机 Claude CLI 账号额度\n\(chosen?.name ?? "未选择窗口")\n\(error ?? snapshot?.detail ?? "正在读取")\n状态:\(stale ? "数据未知或已过期" : "已更新")\n更新时间:\(fetched)\n拖动校准位置;双击刷新;右键打开菜单"
|
|
207
|
+
ring.setAccessibilityLabel("Claude \(chosen?.name ?? "") 剩余 \(chosen?.remaining.map { "\(Int($0.rounded()))%" } ?? "未知"),\(ring.caption)")
|
|
208
|
+
ring.needsDisplay = true
|
|
209
|
+
}
|
|
210
|
+
@objc func refresh() {
|
|
211
|
+
guard query == nil else { return }
|
|
212
|
+
lastAttempt = Date()
|
|
213
|
+
let process = Process(), pipe = Pipe()
|
|
214
|
+
process.executableURL = URL(fileURLWithPath: node)
|
|
215
|
+
process.arguments = [script]
|
|
216
|
+
var env = ProcessInfo.processInfo.environment
|
|
217
|
+
env["PATH"] = searchPath
|
|
218
|
+
if !claudeHome.isEmpty { env["CLAUDE_CONFIG_DIR"] = claudeHome }
|
|
219
|
+
process.environment = env
|
|
220
|
+
process.standardOutput = pipe
|
|
221
|
+
process.standardError = FileHandle.nullDevice
|
|
222
|
+
process.terminationHandler = { [weak self] process in
|
|
223
|
+
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
|
224
|
+
Task { @MainActor in
|
|
225
|
+
guard let self else { return }
|
|
226
|
+
self.query = nil
|
|
227
|
+
do {
|
|
228
|
+
let value = try JSONDecoder().decode(Snapshot.self, from: data)
|
|
229
|
+
if let message = value.error { self.error = message }
|
|
230
|
+
else if process.terminationStatus == 0, value.fetchedAt > 0 {
|
|
231
|
+
self.snapshot = value; self.error = nil
|
|
232
|
+
} else { self.error = "额度查询失败" }
|
|
233
|
+
} catch { self.error = "无法读取额度响应,请检查 CLI 和网络" }
|
|
234
|
+
self.updateRing()
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
query = process
|
|
238
|
+
do { try process.run() }
|
|
239
|
+
catch { query = nil; self.error = "无法启动额度查询,请重新运行 easy-claude overlay"; updateRing() }
|
|
240
|
+
}
|
|
241
|
+
func item(_ title: String, _ action: Selector?) -> NSMenuItem {
|
|
242
|
+
let item = NSMenuItem(title: title, action: action, keyEquivalent: "")
|
|
243
|
+
item.target = self
|
|
244
|
+
return item
|
|
245
|
+
}
|
|
246
|
+
func makeMenu() -> NSMenu {
|
|
247
|
+
let menu = NSMenu()
|
|
248
|
+
menu.addItem(item("Easy Claude · CLI 账号额度", nil))
|
|
249
|
+
menu.addItem(item(lastRect == nil ? "等待 Claude 前台窗口" : "拖动圆环可调整位置", nil))
|
|
250
|
+
if let error { menu.addItem(item(error, nil)) }
|
|
251
|
+
if snapshot?.restricted == true { menu.addItem(item("服务端提示:当前使用受限", nil)) }
|
|
252
|
+
menu.addItem(.separator())
|
|
253
|
+
for window in snapshot?.windows ?? [] {
|
|
254
|
+
let remaining = window.remaining.map { "\(Int($0.rounded()))%" } ?? "未知"
|
|
255
|
+
let option = item("\(window.name) · \(remaining)", #selector(selectWindow(_:)))
|
|
256
|
+
option.representedObject = window.id
|
|
257
|
+
option.state = chosen?.id == window.id ? .on : .off
|
|
258
|
+
menu.addItem(option)
|
|
259
|
+
}
|
|
260
|
+
menu.addItem(item(query == nil ? "立即刷新" : "正在刷新…", query == nil ? #selector(refresh) : nil))
|
|
261
|
+
menu.addItem(item("恢复默认位置", #selector(resetPosition)))
|
|
262
|
+
menu.addItem(.separator())
|
|
263
|
+
menu.addItem(item("退出浮窗", #selector(quit)))
|
|
264
|
+
return menu
|
|
265
|
+
}
|
|
266
|
+
func menuNeedsUpdate(_ menu: NSMenu) {
|
|
267
|
+
menu.removeAllItems()
|
|
268
|
+
let fresh = makeMenu()
|
|
269
|
+
for item in fresh.items { fresh.removeItem(item); menu.addItem(item) }
|
|
270
|
+
}
|
|
271
|
+
@objc func selectWindow(_ sender: NSMenuItem) {
|
|
272
|
+
selectedID = sender.representedObject as? String
|
|
273
|
+
UserDefaults.standard.set(selectedID, forKey: "selectedWindow")
|
|
274
|
+
updateRing()
|
|
275
|
+
}
|
|
276
|
+
@objc func resetPosition() {
|
|
277
|
+
inset = CGPoint(x: 10, y: 74)
|
|
278
|
+
UserDefaults.standard.removeObject(forKey: "leftInset")
|
|
279
|
+
UserDefaults.standard.removeObject(forKey: "bottomInset")
|
|
280
|
+
tick()
|
|
281
|
+
}
|
|
282
|
+
@objc func quit() { NSApp.terminate(nil) }
|
|
283
|
+
func applicationWillTerminate(_ notification: Notification) {
|
|
284
|
+
timer?.invalidate()
|
|
285
|
+
query?.terminate()
|
|
286
|
+
NSWorkspace.shared.notificationCenter.removeObserver(self)
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
@main
|
|
291
|
+
struct Main {
|
|
292
|
+
@MainActor static func main() {
|
|
293
|
+
if CommandLine.arguments.contains("--self-test") {
|
|
294
|
+
assert(RingState.resolve(51, stale: false) == .green)
|
|
295
|
+
assert(RingState.resolve(50, stale: false) == .orange)
|
|
296
|
+
assert(RingState.resolve(20, stale: false) == .orange)
|
|
297
|
+
assert(RingState.resolve(19, stale: false) == .red)
|
|
298
|
+
assert(RingState.resolve(nil, stale: false) == .unknown)
|
|
299
|
+
assert(RingState.resolve(99, stale: true) == .unknown)
|
|
300
|
+
assert(appKitRect(CGRect(x: -900, y: 100, width: 800, height: 600), primaryHeight: 900).origin == CGPoint(x: -900, y: 200))
|
|
301
|
+
let bounds = CGRect(x: 100, y: 100, width: 800, height: 600)
|
|
302
|
+
assert(ringOrigin(in: bounds, inset: CGPoint(x: 10, y: 74)) == CGPoint(x: 110, y: 174))
|
|
303
|
+
assert(ringOrigin(in: bounds, inset: CGPoint(x: -100, y: -100)) == CGPoint(x: 100, y: 100))
|
|
304
|
+
assert(ringOrigin(in: bounds, inset: CGPoint(x: 9999, y: 9999)) == CGPoint(x: 868, y: 668))
|
|
305
|
+
print("Swift 圆环颜色与窗口坐标检查通过")
|
|
306
|
+
return
|
|
307
|
+
}
|
|
308
|
+
let app = NSApplication.shared
|
|
309
|
+
app.setActivationPolicy(.accessory)
|
|
310
|
+
if CommandLine.arguments.contains("--diagnose") {
|
|
311
|
+
print("targetFrontmost=\(NSWorkspace.shared.frontmostApplication?.bundleIdentifier == "com.anthropic.claudefordesktop")")
|
|
312
|
+
print("targetWindow=\(targetWindow().map { NSStringFromRect($0) } ?? "unavailable")")
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
if let i = CommandLine.arguments.firstIndex(of: "--render-preview"), CommandLine.arguments.count > i + 1 {
|
|
316
|
+
let image = NSImage(size: NSSize(width: 340, height: 100))
|
|
317
|
+
image.lockFocus()
|
|
318
|
+
for (index, value) in [75.0, 35.0, 10.0, -1.0].enumerated() {
|
|
319
|
+
NSGraphicsContext.saveGraphicsState()
|
|
320
|
+
let transform = AffineTransform(translationByX: CGFloat(index * 84 + 4), byY: 8)
|
|
321
|
+
(transform as NSAffineTransform).concat()
|
|
322
|
+
let view = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
|
|
323
|
+
view.remaining = value < 0 ? nil : value; view.stale = value < 0
|
|
324
|
+
view.caption = value < 0 ? "额度未知" : "7天"
|
|
325
|
+
view.draw(view.bounds)
|
|
326
|
+
NSGraphicsContext.restoreGraphicsState()
|
|
327
|
+
}
|
|
328
|
+
image.unlockFocus()
|
|
329
|
+
if let tiff = image.tiffRepresentation, let bitmap = NSBitmapImageRep(data: tiff), let png = bitmap.representation(using: .png, properties: [:]) {
|
|
330
|
+
do { try png.write(to: URL(fileURLWithPath: CommandLine.arguments[i+1])) }
|
|
331
|
+
catch { fputs("预览写入失败\n", stderr); exit(1) }
|
|
332
|
+
}
|
|
333
|
+
return
|
|
334
|
+
}
|
|
335
|
+
let delegate = Overlay()
|
|
336
|
+
app.delegate = delegate
|
|
337
|
+
withExtendedLifetime(delegate) { app.run() }
|
|
338
|
+
}
|
|
339
|
+
}
|
|
@@ -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.1.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.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Claude Code subscription usage and transparent Claude desktop quota ring",
|
|
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
|
+
}
|
package/src/usage.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
export { formatUsage } from './format.js';
|
|
7
|
+
const run = promisify(execFile);
|
|
8
|
+
const loginMessage = '请执行 claude auth login 登录与 Claude 桌面相同的订阅账号。';
|
|
9
|
+
|
|
10
|
+
export function credentialToken(raw, now = Date.now()) {
|
|
11
|
+
let auth;
|
|
12
|
+
try { auth = JSON.parse(raw)?.claudeAiOauth; } catch { throw new Error(`Claude Code 登录数据格式不受支持。${loginMessage}`); }
|
|
13
|
+
if (!auth || typeof auth.accessToken !== 'string' || !auth.accessToken.trim()) throw new Error(loginMessage);
|
|
14
|
+
if (Number.isFinite(auth.expiresAt) && auth.expiresAt <= now) throw new Error(`Claude Code 登录已过期。${loginMessage}`);
|
|
15
|
+
return auth.accessToken;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function loadToken({ signal } = {}) {
|
|
19
|
+
let raw;
|
|
20
|
+
// 自定义配置目录不猜测钥匙串名称,以免读到另一个账号。
|
|
21
|
+
if (process.platform === 'darwin' && !process.env.CLAUDE_CONFIG_DIR) {
|
|
22
|
+
try { raw = (await run('/usr/bin/security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], { timeout: 5000, maxBuffer: 1024 * 1024, signal })).stdout; }
|
|
23
|
+
catch { if (signal?.aborted) throw new Error('查询已取消。'); }
|
|
24
|
+
}
|
|
25
|
+
if (!raw) {
|
|
26
|
+
try { raw = await readFile(join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), '.credentials.json'), { encoding: 'utf8', signal }); }
|
|
27
|
+
catch { throw new Error(signal?.aborted ? '查询已取消。' : `未找到可读取的 Claude Code 订阅登录。${loginMessage}`); }
|
|
28
|
+
}
|
|
29
|
+
return credentialToken(raw);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function normalizeUsage(data) {
|
|
33
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('额度响应格式无效。');
|
|
34
|
+
const rateLimitsByLimitId = {};
|
|
35
|
+
for (const [key, value] of Object.entries(data)) {
|
|
36
|
+
if (!/^(five_hour|seven_day)(_[a-z0-9_]+)?$/.test(key) || value == null) continue;
|
|
37
|
+
if (typeof value !== 'object' || Array.isArray(value)) throw new Error('额度窗口格式无效。');
|
|
38
|
+
// 明细汇总也使用 seven_day 前缀,只有比例字段才代表额度窗口。
|
|
39
|
+
if (!Object.hasOwn(value, 'utilization')) continue;
|
|
40
|
+
const used = value.utilization;
|
|
41
|
+
if (used != null && (!Number.isFinite(used) || used < 0 || used > 100)) throw new Error('额度比例格式无效。');
|
|
42
|
+
const reset = typeof value.resets_at === 'string' ? Date.parse(value.resets_at) / 1000 : null;
|
|
43
|
+
const primary = { usedPercent: used ?? null, resetsAt: Number.isFinite(reset) ? reset : null, windowDurationMins: key.startsWith('five_hour') ? 300 : 10080 };
|
|
44
|
+
const label = key === 'five_hour' ? 'Claude · 5 小时' : key === 'seven_day' ? 'Claude · 7 天' : key.replaceAll('_', ' ');
|
|
45
|
+
rateLimitsByLimitId[key] = { limitId: key, limitName: label, primary };
|
|
46
|
+
}
|
|
47
|
+
if (!Object.keys(rateLimitsByLimitId).length) throw new Error('服务端未提供订阅额度,不能判断剩余额度;API Key 余额不在范围内。');
|
|
48
|
+
return { rateLimitsByLimitId };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function readUsage({ signal, timeoutMs = 15000, getToken = loadToken, fetchImpl = fetch } = {}) {
|
|
52
|
+
const controller = new AbortController();
|
|
53
|
+
const abort = () => controller.abort();
|
|
54
|
+
if (signal?.aborted) throw new Error('查询已取消。');
|
|
55
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
56
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
57
|
+
try {
|
|
58
|
+
const token = await getToken({ signal: controller.signal });
|
|
59
|
+
// 固定官方源且禁止重定向,避免登录凭据发送到其他站点。
|
|
60
|
+
const response = await fetchImpl('https://api.anthropic.com/api/oauth/usage', {
|
|
61
|
+
headers: { authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20', accept: 'application/json' },
|
|
62
|
+
redirect: 'error', signal: controller.signal,
|
|
63
|
+
}).catch(() => { throw new Error('无法连接 Claude 额度服务,请检查网络。'); });
|
|
64
|
+
if (response.status === 401 || response.status === 403) throw new Error(`订阅登录无效或无额度权限。${loginMessage}`);
|
|
65
|
+
if (response.status === 429) throw new Error('额度查询过于频繁,请稍后再试。');
|
|
66
|
+
if (!response.ok) throw new Error(`Claude 额度服务暂不可用(HTTP ${response.status})。`);
|
|
67
|
+
let data;
|
|
68
|
+
try { data = await response.json(); } catch { throw new Error('Claude 返回了无效的额度数据。'); }
|
|
69
|
+
return normalizeUsage(data);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (controller.signal.aborted) throw new Error(signal?.aborted ? '查询已取消。' : '额度查询超时,请检查网络。');
|
|
72
|
+
throw error;
|
|
73
|
+
} finally { clearTimeout(timer); signal?.removeEventListener('abort', abort); }
|
|
74
|
+
}
|