ai newsDi., 1. Dez.

macOS-App liest Nutzungslimits von Claude Code, Codex und Grok direkt aus den Logins

Ein Entwickler beschreibt eine macOS-Menueleisten-App, die die Tarif-Limits von Claude Code, Codex und Grok ausliest. Dabei kamen Keychain-Tricks, undokumentierte Endpunkte und erst nach dem Launch entdeckte Fehler zum Vorschein.

HackerNoonMontag 16:08 · 30.11.DE8 Min. Lesezeit
Bild: HackerNoon

Signup Write New Story Reading Three AI Agents' Usage Limits From Their Own Sign-Ins, Without Ever Writing Them by Gilad Or by Gilad Or | @ gor84 I build tools that make everyday tasks disappear. Latest: gas, an open-source macOS menu bar app for Claude, Codex and Grok usage limits.

I build tools that make everyday tasks disappear. Latest: gas, an open-source macOS menu bar app for Claude, Codex and Grok usage limits.

I use Claude Code, OpenAI's Codex and the Grok CLI every day, each on a subscription plan with its own limits: a session window that resets every few hours, and a weekly cap. Each tool shows its own number, in its own place, only when you ask. More than once I found out a limit was spent in the middle of a task.

I wanted all three numbers in the menu bar, always visible. The catch: none of these vendors offers a public "how much of my plan have I used" API. The numbers exist, because each CLI shows them, but they come from internal endpoints, authorized with the CLI's own sign-in.

So the real problem is this: how do you read another tool's credentials and call its private endpoint, without becoming the weakest link in that tool's security?

This article walks through how gas, an open-source Swift app, does it: the parts that worked, the routes I rejected, and the bugs users reported after release.

All logic lives in a SwiftPM package, UsageCore, which has around 440 tests. The app target is a thin SwiftUI and AppKit shell. That split matters: everything risky (credentials, networking, retry policy) can be tested without launching a UI.

Each provider implements one small protocol:

public protocol UsageProvider: Sendable { var id: ProviderID { get } /// Seconds that must pass between two requests to this provider, whatever the app's refresh tick is. var minimumInterval: TimeInterval { get } /// Debounce for manual (user-triggered) refreshes. var manualMinimumInterval: TimeInterval { get } func fetch() async throws -> FetchOutcome /// The account of the current credential, so signing in to another account can end a rate-limit wait. func credentialFingerprint() -> String?} public extension UsageProvider { /// Just under the 5-minute tick, so timer jitter does not skip every second call. var minimumInterval: TimeInterval { 5 * 60 - 30 } var manualMinimumInterval: TimeInterval { 60 }} Two details came from real mistakes.

minimumInterval is 4.5 minutes, not 5. The app ticks every 5 minutes. With a floor of exactly 5 minutes, timer jitter made every second tick arrive a few milliseconds early, so half the refreshes were skipped.

fetch() returns whether a request was actually sent:

public struct FetchOutcome: Sendable, Equatable { public let snapshot: UsageSnapshot /// True when a request reached the network, so it counts toward the provider's limits. public let requestSent: Bool public let credentialFingerprint: String?} The shared UsageRefresher, not each provider, decides when to call. Any request that reached the server counts toward the floor, whatever the result. A new provider can't forget to rate-limit itself, because it never makes that decision.

Claude Code stores its OAuth token in the macOS Keychain, under the generic password Claude Code-credentials.

The obvious way: read it with SecItemCopyMatching. It works, and macOS asks the user to allow gas, which is reasonable. They click Always Allow, and all seems well.

The catch: the prompt keeps coming back. When Claude Code refreshes its token, it rewrites the Keychain item, and rewriting resets the item's access list. The "Always Allow" granted to gas was wiped on every refresh.

The fix: look at who writes the item. Claude Code writes it with /usr/bin/security, so that binary is always on the item's access list. If gas reads through the same binary, there is never a prompt:

/// Reads Claude Code's token through /usr/bin/security. Claude Code writes the item with that tool,/// so the item's access list always trusts it: no Keychain prompt, even after Claude Code rewrites/// the item on a token refresh (which resets any "Always Allow" granted to other apps).public struct SecurityCLITokenReader: TokenReader { private static let itemNotFound: Int32 = 44 public func readClaudeToken() throws -> ClaudeToken { let result = try run(URL(fileURLWithPath: "/usr/bin/security"), ["find-generic-password", "-s", service, "-a", account, "-w"]) switch result.status { case 0: return try ClaudeCredentials.parse(result.output) case Self.itemNotFound: throw TokenReaderError.notFound default: throw TokenReaderError.accessDenied } }} stderr goes to /dev/null, and the runner is injected, so tests never touch the real Keychain.

The lesson: when a credential's access control keeps resetting, check which process writes it. Reading through that process may avoid the reset.

With the token, gas calls the same endpoint Claude Code's /usage uses:

let url = baseURL.appendingPathComponent("api/oauth/usage")let headers = [ "Authorization": "Bearer \(token.accessToken)", "anthropic-beta": "oauth-2025-04-20", "Content-Type": "application/json", "User-Agent": Self.userAgent] One surprise: when the session has been logged out, this endpoint answers 429 Too Many Requests, not 401. From one response alone, a real rate limit and a dead session look identical. gas tells them apart by asking Claude Code to renew its own token once. If the renewal fails, the user is told to sign in. If it succeeds, the 429 was real and gas waits it out. gas never refreshes the token itself.

Codex keeps its sign-in in ~/.codex/auth.json. gas reads only the access token and account ID (sent as ChatGPT-Account-Id ), and calls backend-api/wham/usage, the same call the Codex CLI makes.

Grok was more interesting, because there were two ways in:

Option 1 looked cleaner, because gas wouldn't handle the token at all. A security review changed my mind. Without a session or a prompt, the agent mode would:

That decision is recorded in an ADR, an Architecture Decision Record. A future contributor (or a future me) who thinks "why not just call the CLI?" finds the answer before rebuilding the risky version.

After the Grok review, two problems turned out to apply to every provider:

Fixing these one provider at a time would leave the next one exposed, so they became a written baseline (ADR-0004) that shared code enforces:

Here's what a log line is allowed to contain:

/// Only what gas derives itself: status, its category, a validated Retry-After and the body size.static func response(_ provider: ProviderID, _ response: HTTPURLResponse, data: Data) { let retryAfter = RetryAfter.logValue(response.value(forHTTPHeaderField: "Retry-After")) record("\(provider.rawValue) HTTP \(response.statusCode) \(category(response.statusCode)) retry-after=\(retryAfter) bytes=\(data.count)")} Even Retry-After is validated before it's logged. If it isn't a short number or a valid HTTP date, the log gets -, so a server can't smuggle text in through a header. As a backstop, every line passes through a redactor for anything token-shaped:

private static let secretPatterns = [ #"Bearer\s+\S+"#, #"[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"#, // JWT-shaped #"[A-Za-z0-9_\-+/=]{32,}"# // long opaque tokens] The trade-off is real: when a provider errors, I debug from a status category and the user's description, not the server's message. For an app that reads other tools' sign-ins, I'll take that trade.

Shipping taught me more than designing did. A few examples:

Usage stopped refreshing after a reconnect. Offline failures counted as sent requests, so when the network returned, the 4.5-minute floor blocked the retry. The fix: URLError.notConnectedToInternet does not count as a sent request, because nothing could have left the machine. Timeouts and dropped connections still count, conservatively, since the server might have seen them. A reconnect now waits for any refresh in flight, then retries each provider as soon as its own floor allows.

"Grok returned no usage." Right after the weekly reset, the billing response had no creditUsagePercent field at all. The endpoint serializes protobuf to JSON, and protobuf JSON drops fields whose value is zero. gas read the missing field as an error, when it actually meant 0%. Now, with a valid token and a known billing period, a missing percent maps to 0%. The lesson: with an undocumented endpoint, "missing" can mean "zero".

Users could drag the floating panel only by a tiny handle. The panel is an NSPanel in an app that is never active, because it lives in the menu bar. In that setup, SwiftUI's.onHover never fires. The fix is a tracking area with.activeAlways:

/// SwiftUI hover tracking stays silent in a panel of an app that is never active, so track with `.activeAlways`.final class TrackingHostingView<Content: View>: NSHostingView<Content> { override func updateTrackingAreas() { super.updateTrackingAreas() if let pointerArea { removeTrackingArea(pointerArea) } let area = NSTrackingArea(rect:.zero, options: [.activeAlways,.mouseEnteredAndExited,.mouseMoved,.inVisibleRect], owner: self, userInfo: nil) addTrackingArea(area) pointerArea = area }} With hover working, the whole panel became draggable. A 3 pt minimum drag distance keeps a still click a click.

A small one: how big can text get in the menu bar? A user asked for larger numbers. Rather than guess, I measured. NSStatusBar.system.thickness is 22 pt, and the line height of the system font at medium weight is:

The setting became a 12–18 pt slider, with a note above 16 pt that the text may be clipped.

gas is free, so it's signed ad-hoc, not with a Developer ID. That means it can't be notarized, and macOS asks the user to approve it once in Privacy & Security. Ad-hoc signing has one benefit: no developer name or email ends up in the signature.

To update safely without notarization, the in-app updater:

/// Saves the pkg only after its SHA-256 matches the release's checksum file, so a bad download is never opened.guard Self.sha256Hex(pkg) == expected else { throw UpdateDownloadError.checksumMismatch } Releases go through a single script, release.sh. It refuses to run without new commits on main or with local changes, then runs the tests, builds, signs, publishes the pkg, dmg and checksum, and updates the Homebrew cask's version and sha256. Every release goes the same way, whether I run it or a coding agent does.

gas is MIT-licensed. The provider code, the ADRs mentioned here and the tests are on GitHub: https://github.com/gilador/gas. If you've found another way to read these limits, or another tool's limits to add, I'd like to hear it in the issues.

Originaltitel: Reading Three AI Agents' Usage Limits From Their Own Sign-Ins, Without Ever Writing ThemQuelle: HackerNoon (HackerNoon). Original öffnen