413 lines
19 KiB
Swift
413 lines
19 KiB
Swift
// Menu-bar widget: пятичасовое окно зайки (z.ai), баланс DeepSeek и недельный лимит Codex.
|
||
//
|
||
// Ключи не хранятся в коде: читаются из профилей Claude Code и Codex при каждом запросе.
|
||
// Ручка квоты z.ai бесплатна, баланс DeepSeek — обычный GET, ручка Codex — служебный read-only
|
||
// запрос тем же токеном, что использует Codex CLI (он короткоживущий: обновляет его Codex).
|
||
// Показываем израсходованное окно: «зайка 83%», «Codex 14%». При 100% — обратный отсчёт.
|
||
import Cocoa
|
||
import CFNetwork
|
||
import Foundation
|
||
|
||
let home = FileManager.default.homeDirectoryForCurrentUser
|
||
let zaiProfile = home.appendingPathComponent(".claude/settings_z.json")
|
||
let deepseekProfile = home.appendingPathComponent(".claude/settings-deepseek.json")
|
||
let codexAuth = URL(fileURLWithPath: ProcessInfo.processInfo.environment["ZAIKA_WIDGET_CODEX_AUTH"]
|
||
?? home.appendingPathComponent(".codex/auth.json").path)
|
||
let logURL = home.appendingPathComponent(".claude/logs/zaika-widget.log")
|
||
|
||
func logLine(_ text: String) {
|
||
let stamp = ISO8601DateFormatter().string(from: Date())
|
||
let line = "\(stamp) \(text)\n"
|
||
try? FileManager.default.createDirectory(at: logURL.deletingLastPathComponent(),
|
||
withIntermediateDirectories: true)
|
||
if let data = line.data(using: .utf8) {
|
||
if let handle = try? FileHandle(forWritingTo: logURL) {
|
||
handle.seekToEndOfFile()
|
||
handle.write(data)
|
||
try? handle.close()
|
||
} else {
|
||
try? data.write(to: logURL)
|
||
}
|
||
}
|
||
}
|
||
|
||
func token(from profile: URL) -> String? {
|
||
guard let data = try? Data(contentsOf: profile),
|
||
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||
let env = root["env"] as? [String: Any],
|
||
let value = env["ANTHROPIC_AUTH_TOKEN"] as? String,
|
||
!value.isEmpty
|
||
else { return nil }
|
||
return value
|
||
}
|
||
|
||
func codexCredentials() -> (String, String)? {
|
||
guard let data = try? Data(contentsOf: codexAuth),
|
||
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||
let tokens = root["tokens"] as? [String: Any],
|
||
let access = tokens["access_token"] as? String, !access.isEmpty,
|
||
let account = tokens["account_id"] as? String, !account.isEmpty
|
||
else { return nil }
|
||
return (access, account)
|
||
}
|
||
|
||
struct ZaiLimit {
|
||
var percent: Int
|
||
var reset: Date?
|
||
}
|
||
|
||
struct DeepSeekBalance {
|
||
var total: String
|
||
var available: Bool
|
||
}
|
||
|
||
struct CodexLimit {
|
||
var percent: Int
|
||
var reset: Date?
|
||
var plan: String?
|
||
}
|
||
|
||
struct Reply {
|
||
var object: [String: Any]? // JSON-словарь из тела ответа; nil — ответа нет или это не JSON
|
||
var status: Int? // HTTP-код; nil — соединение не состоялось
|
||
var data: Data?
|
||
var error: String?
|
||
}
|
||
|
||
/// Описание отказа для журнала и меню. С verbose добавляется текст страницы: по одному коду 403
|
||
/// не отличить отказ по региону («Unable to load site») от ошибки входа.
|
||
func failureText(_ reply: Reply, verbose: Bool) -> String {
|
||
var parts = ["HTTP \(reply.status.map(String.init) ?? "—")"]
|
||
if let error = reply.error { parts.append(error) }
|
||
if let detail = reply.object?["detail"] as? String { parts.append(String(detail.prefix(160))) }
|
||
if verbose, reply.object == nil, let data = reply.data {
|
||
let html = String(decoding: data.prefix(4000), as: UTF8.self)
|
||
let text = html
|
||
.replacingOccurrences(of: "(?s)<(script|style)[^>]*>.*?</\\1>", with: " ", options: .regularExpression)
|
||
.replacingOccurrences(of: "<[^>]+>", with: " ", options: .regularExpression)
|
||
parts.append("текст ответа: " + String(text.split(whereSeparator: { $0.isWhitespace })
|
||
.joined(separator: " ").prefix(160)))
|
||
}
|
||
return parts.joined(separator: ", ")
|
||
}
|
||
|
||
final class Widget: NSObject, NSApplicationDelegate {
|
||
private var statusItem: NSStatusItem!
|
||
private var menu: NSMenu!
|
||
private var zaiMenuItem: NSMenuItem!
|
||
private var dsMenuItem: NSMenuItem!
|
||
private var codexMenuItem: NSMenuItem!
|
||
private var updatedMenuItem: NSMenuItem!
|
||
|
||
private var zaiLimit: ZaiLimit?
|
||
private var zaiFailed = false
|
||
private var balance: DeepSeekBalance?
|
||
private var balanceFailed = false
|
||
private var codexLimit: CodexLimit?
|
||
private var codexFailed = false
|
||
private var codexNote: String?
|
||
private var updatedAt: Date?
|
||
private var lastZaiRecheckAt = Date.distantPast
|
||
private var lastCodexRecheckAt = Date.distantPast
|
||
private var lastCodexFetchAt = Date.distantPast
|
||
|
||
// Codex CLI ходит в chatgpt.com через местный прокси (codex-proxy.sh), а напрямую OpenAI
|
||
// отказывает адресу этой сети (403 «Unable to load site», 25.11.2026). Виджет идёт тем же
|
||
// путём. Пустое значение — только напрямую; формат — http://хост:порт.
|
||
private let codexProxy = ProcessInfo.processInfo.environment["ZAIKA_WIDGET_CODEX_PROXY"]
|
||
?? "http://127.0.0.1:1091"
|
||
private lazy var codexSession: URLSession = {
|
||
let configuration = URLSessionConfiguration.ephemeral
|
||
configuration.timeoutIntervalForRequest = 10
|
||
if let address = URL(string: codexProxy), let host = address.host, let port = address.port {
|
||
configuration.connectionProxyDictionary = [
|
||
kCFNetworkProxiesHTTPEnable as AnyHashable: 1,
|
||
kCFNetworkProxiesHTTPProxy as AnyHashable: host,
|
||
kCFNetworkProxiesHTTPPort as AnyHashable: port,
|
||
kCFNetworkProxiesHTTPSEnable as AnyHashable: 1,
|
||
kCFNetworkProxiesHTTPSProxy as AnyHashable: host,
|
||
kCFNetworkProxiesHTTPSPort as AnyHashable: port,
|
||
]
|
||
}
|
||
return URLSession(configuration: configuration)
|
||
}()
|
||
|
||
// Адреса можно подменить переменными окружения — так виджет проверяется на
|
||
// подставном сервере, не дожидаясь настоящего исчерпания окна.
|
||
private let zaiURL = URL(string: ProcessInfo.processInfo.environment["ZAIKA_WIDGET_ZAI_URL"]
|
||
?? "https://api.z.ai/api/monitor/usage/quota/limit")!
|
||
private let balanceURL = URL(string: ProcessInfo.processInfo.environment["ZAIKA_WIDGET_DS_URL"]
|
||
?? "https://api.deepseek.com/user/balance")!
|
||
private let codexURL = URL(string: ProcessInfo.processInfo.environment["ZAIKA_WIDGET_CODEX_URL"]
|
||
?? "https://chatgpt.com/backend-api/codex/usage")!
|
||
|
||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
|
||
if let button = statusItem.button {
|
||
button.font = NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .regular)
|
||
button.title = "зайка … · DeepSeek … · Codex …"
|
||
}
|
||
menu = NSMenu()
|
||
zaiMenuItem = NSMenuItem(title: "Зайка: —", action: nil, keyEquivalent: "")
|
||
dsMenuItem = NSMenuItem(title: "DeepSeek: —", action: nil, keyEquivalent: "")
|
||
codexMenuItem = NSMenuItem(title: "Codex: —", action: nil, keyEquivalent: "")
|
||
updatedMenuItem = NSMenuItem(title: "Обновлено: —", action: nil, keyEquivalent: "")
|
||
menu.addItem(zaiMenuItem)
|
||
menu.addItem(dsMenuItem)
|
||
menu.addItem(codexMenuItem)
|
||
menu.addItem(.separator())
|
||
menu.addItem(updatedMenuItem)
|
||
menu.addItem(.separator())
|
||
let refresh = NSMenuItem(title: "Обновить сейчас", action: #selector(refreshNow), keyEquivalent: "r")
|
||
refresh.target = self
|
||
menu.addItem(refresh)
|
||
let quit = NSMenuItem(title: "Выход", action: #selector(quit), keyEquivalent: "q")
|
||
quit.target = self
|
||
menu.addItem(quit)
|
||
statusItem.menu = menu
|
||
|
||
fetchZai()
|
||
fetchBalance()
|
||
fetchCodex()
|
||
Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { _ in self.fetchZai() }
|
||
Timer.scheduledTimer(withTimeInterval: 300, repeats: true) { _ in self.fetchBalance() }
|
||
// Codex: раз в пять минут, а после отказа — каждую минуту: знак вопроса не должен висеть впустую.
|
||
Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { _ in
|
||
if self.codexLimit == nil || Date().timeIntervalSince(self.lastCodexFetchAt) >= 300 {
|
||
self.fetchCodex()
|
||
}
|
||
}
|
||
// Отсчёт идёт посекундно, а запросы остаются редкими.
|
||
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in self.updateTitle() }
|
||
}
|
||
|
||
@objc private func refreshNow() {
|
||
fetchZai()
|
||
fetchBalance()
|
||
fetchCodex()
|
||
}
|
||
|
||
@objc private func quit() {
|
||
NSApplication.shared.terminate(nil)
|
||
}
|
||
|
||
private func getJSON(_ url: URL, token: String, headers: [String: String] = [:],
|
||
session: URLSession = .shared, completion: @escaping (Reply) -> Void) {
|
||
var request = URLRequest(url: url)
|
||
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
|
||
for (key, value) in headers {
|
||
request.setValue(value, forHTTPHeaderField: key)
|
||
}
|
||
request.timeoutInterval = 10
|
||
session.dataTask(with: request) { data, response, error in
|
||
var reply = Reply()
|
||
reply.object = data.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }
|
||
reply.status = (response as? HTTPURLResponse)?.statusCode
|
||
reply.data = data
|
||
reply.error = error?.localizedDescription
|
||
DispatchQueue.main.async { completion(reply) }
|
||
}.resume()
|
||
}
|
||
|
||
private func fetchZai() {
|
||
guard let key = token(from: zaiProfile) else {
|
||
zaiFailed = true
|
||
updateTitle()
|
||
return
|
||
}
|
||
getJSON(zaiURL, token: key) { [weak self] reply in
|
||
guard let self else { return }
|
||
var found: ZaiLimit?
|
||
if let data = reply.object?["data"] as? [String: Any],
|
||
let limits = data["limits"] as? [[String: Any]] {
|
||
for limit in limits where limit["type"] as? String == "TOKENS_LIMIT" {
|
||
if let percent = limit["percentage"] as? Int {
|
||
var reset: Date?
|
||
if let ms = limit["nextResetTime"] as? Double {
|
||
reset = Date(timeIntervalSince1970: ms / 1000)
|
||
}
|
||
found = ZaiLimit(percent: percent, reset: reset)
|
||
}
|
||
}
|
||
}
|
||
if found == nil { logLine("z.ai: \(failureText(reply, verbose: true))") }
|
||
self.zaiLimit = found
|
||
self.zaiFailed = (found == nil)
|
||
self.updatedAt = Date()
|
||
self.updateTitle()
|
||
}
|
||
}
|
||
|
||
private func fetchBalance() {
|
||
guard let key = token(from: deepseekProfile) else {
|
||
balanceFailed = true
|
||
updateTitle()
|
||
return
|
||
}
|
||
getJSON(balanceURL, token: key) { [weak self] reply in
|
||
guard let self else { return }
|
||
var found: DeepSeekBalance?
|
||
if let infos = reply.object?["balance_infos"] as? [[String: Any]],
|
||
let first = infos.first,
|
||
let total = first["total_balance"] as? String {
|
||
found = DeepSeekBalance(total: total,
|
||
available: (reply.object?["is_available"] as? Bool) ?? false)
|
||
}
|
||
if found == nil { logLine("deepseek: \(failureText(reply, verbose: true))") }
|
||
self.balance = found
|
||
self.balanceFailed = (found == nil)
|
||
self.updatedAt = Date()
|
||
self.updateTitle()
|
||
}
|
||
}
|
||
|
||
private func parseCodex(_ root: [String: Any]?) -> CodexLimit? {
|
||
guard let root,
|
||
let rate = root["rate_limit"] as? [String: Any],
|
||
let window = rate["primary_window"] as? [String: Any],
|
||
let used = (window["used_percent"] as? NSNumber)?.intValue else { return nil }
|
||
var reset: Date?
|
||
if let at = (window["reset_at"] as? NSNumber)?.doubleValue {
|
||
reset = Date(timeIntervalSince1970: at)
|
||
}
|
||
let reached = (rate["limit_reached"] as? Bool) ?? false
|
||
return CodexLimit(percent: reached ? max(used, 100) : used, reset: reset,
|
||
plan: root["plan_type"] as? String)
|
||
}
|
||
|
||
private func fetchCodex() {
|
||
guard let (key, account) = codexCredentials() else {
|
||
codexLimit = nil
|
||
codexFailed = true
|
||
codexNote = "токен не читается из ~/.codex/auth.json"
|
||
updateTitle()
|
||
return
|
||
}
|
||
lastCodexFetchAt = Date()
|
||
let headers = ["chatgpt-account-id": account, "User-Agent": "codex-cli/0.167.0"]
|
||
// Прокси выключен — соединение с ним падает сразу, тогда идём напрямую.
|
||
var routes: [(session: URLSession, label: String)] = [(.shared, "напрямую")]
|
||
if !codexProxy.isEmpty { routes.insert((codexSession, "через прокси"), at: 0) }
|
||
func attempt(_ index: Int, _ failures: [(short: String, full: String)]) {
|
||
let route = routes[index]
|
||
self.getJSON(self.codexURL, token: key, headers: headers, session: route.session) { [weak self] reply in
|
||
guard let self else { return }
|
||
if let limit = self.parseCodex(reply.object) {
|
||
self.codexLimit = limit
|
||
self.codexFailed = false
|
||
self.codexNote = nil
|
||
self.updatedAt = Date()
|
||
self.updateTitle()
|
||
return
|
||
}
|
||
let failure = (short: "\(route.label): \(failureText(reply, verbose: false))",
|
||
full: "\(route.label): \(failureText(reply, verbose: true))")
|
||
if index + 1 < routes.count {
|
||
attempt(index + 1, failures + [failure])
|
||
return
|
||
}
|
||
self.codexLimit = nil
|
||
self.codexFailed = true
|
||
let all = failures + [failure]
|
||
self.codexNote = all.map(\.short).joined(separator: "; ")
|
||
logLine("codex: " + all.map(\.full).joined(separator: "; "))
|
||
self.updatedAt = Date()
|
||
self.updateTitle()
|
||
}
|
||
}
|
||
attempt(0, [])
|
||
}
|
||
|
||
private func timeText(_ date: Date?) -> String {
|
||
guard let date else { return "?" }
|
||
let formatter = DateFormatter()
|
||
formatter.dateFormat = "HH:mm"
|
||
return formatter.string(from: date)
|
||
}
|
||
|
||
private func countdown(to date: Date) -> String {
|
||
let total = max(0, Int(date.timeIntervalSinceNow.rounded()))
|
||
let hours = total / 3600
|
||
let minutes = (total % 3600) / 60
|
||
let seconds = total % 60
|
||
if hours > 0 {
|
||
return String(format: "%d:%02d:%02d", hours, minutes, seconds)
|
||
}
|
||
return String(format: "%d:%02d", minutes, seconds)
|
||
}
|
||
|
||
private func updateTitle() {
|
||
var zaiPart = "зайка —"
|
||
var zaiMenu = "Зайка: нет ответа от ручки квоты"
|
||
if let limit = zaiLimit {
|
||
if limit.percent >= 100 {
|
||
// Окно исчерпано: показываем не процент, а сколько ждать сброса.
|
||
if let reset = limit.reset, reset > Date() {
|
||
zaiPart = "зайка →\(countdown(to: reset))"
|
||
zaiMenu = "Зайка: лимит исчерпан, сброс через \(countdown(to: reset)) — в \(timeText(reset))"
|
||
} else {
|
||
zaiPart = "зайка 100%"
|
||
zaiMenu = "Зайка: лимит исчерпан, время сброса наступило — проверяю"
|
||
if Date().timeIntervalSince(lastZaiRecheckAt) > 15 {
|
||
lastZaiRecheckAt = Date()
|
||
fetchZai()
|
||
}
|
||
}
|
||
} else {
|
||
zaiPart = "зайка \(limit.percent)%"
|
||
if limit.percent >= 90 { zaiPart += "⚠" }
|
||
zaiMenu = "Зайка: израсходовано \(limit.percent)% пятичасового окна, сброс \(timeText(limit.reset))"
|
||
}
|
||
} else if zaiFailed {
|
||
zaiPart = "зайка ?"
|
||
}
|
||
|
||
var dsPart = "DeepSeek —"
|
||
if let balance {
|
||
dsPart = "DeepSeek $\(balance.total)"
|
||
if !balance.available { dsPart += "!" }
|
||
} else if balanceFailed {
|
||
dsPart = "DeepSeek ?"
|
||
}
|
||
|
||
var codexPart = "Codex —"
|
||
var codexMenu = "Codex: нет ответа от ручки лимитов"
|
||
if let limit = codexLimit {
|
||
if limit.percent >= 100 {
|
||
if let reset = limit.reset, reset > Date() {
|
||
codexPart = "Codex →\(countdown(to: reset))"
|
||
codexMenu = "Codex: лимит исчерпан, сброс через \(countdown(to: reset)) — в \(timeText(reset))"
|
||
} else {
|
||
codexPart = "Codex 100%"
|
||
codexMenu = "Codex: лимит исчерпан, время сброса наступило — проверяю"
|
||
if Date().timeIntervalSince(lastCodexRecheckAt) > 60 {
|
||
lastCodexRecheckAt = Date()
|
||
fetchCodex()
|
||
}
|
||
}
|
||
} else {
|
||
codexPart = "Codex \(limit.percent)%"
|
||
codexMenu = "Codex: израсходовано \(limit.percent)% недельного окна"
|
||
+ (limit.plan.map { " (\($0))" } ?? "") + ", сброс \(timeText(limit.reset))"
|
||
}
|
||
} else if codexFailed {
|
||
codexPart = "Codex ?"
|
||
codexMenu = "Codex: лимит не получен — " + (codexNote ?? "нет ответа")
|
||
}
|
||
|
||
statusItem.button?.title = "\(zaiPart) · \(dsPart) · \(codexPart)"
|
||
zaiMenuItem.title = zaiMenu
|
||
dsMenuItem.title = balance.map {
|
||
"DeepSeek: $\($0.total) \($0.available ? "— доступен" : "— НЕДОСТУПЕН")"
|
||
} ?? "DeepSeek: баланс не получен"
|
||
codexMenuItem.title = codexMenu
|
||
updatedMenuItem.title = "Обновлено: \(updatedAt.map { timeText($0) } ?? "—")"
|
||
}
|
||
}
|
||
|
||
let app = NSApplication.shared
|
||
let widget = Widget()
|
||
app.delegate = widget
|
||
app.setActivationPolicy(.accessory)
|
||
app.run()
|