The problem 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. By the end you'll have: a pattern for reading another app's Keychain item without triggering a prompt every hour a provider abstraction that enforces request limits and rate-limit waits in one place a log redaction approach you can test a few AppKit tricks for menu bar and floating-panel apps Architecture in one picture A thin UI on top of UsageCore, where all credential, network and logging logic live 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. Part 1: One protocol, and limits the providers can't skip 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. Part 2: Reading Claude Code's Keychain item without a prompt every hour 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. The request, and a confusing 429 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. Part 3: Codex and Grok, and a route I rejected 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: Drive the CLI. Start grok agent stdio and ask it for billing over ACP, the Agent Client Protocol. Make the CLI's own HTTP call. GET https://cli-chat-proxy.grok.com/v1/billing?format=credits, with the access token from ~/.grok/auth.json. 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: return auth.json, refresh token included, through _x.ai/fs/read_file write files through _x.ai/fs/write_file load user plugins, hooks, MCP servers and a network skill sync on every start Doing that every 5 minutes multiplies the attack surface and the side effects, all to read three numbers. So gas makes a single HTTPS GET instead, with a hardened session: no redirects, no cache, no cookies, and a bounded response size. If the token has expired, gas shows the last good values as stale with "Open Grok CLI to renew its sign-in", and sends nothing. 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. Part 4: A security baseline every provider must meet After the Grok review, two problems turned out to apply to every provider: Server error text was copied into the log and into Copy diagnostics. A server that echoes the credential in an error would put the token into a report a user pastes into a GitHub issue. A rejected sign-in was retried on every refresh, and a routine token renewal could end a rate-limit wait early. 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: Logs hold gas's own text and numbers only. No server text, bodies or headers. Credentials are read-only. gas never writes, refreshes or "repairs" another tool's store. Every provider has a request floor. 4.5 minutes, plus a 60 s debounce for manual refresh. Rate-limit waits belong to the account. They end early only when the account changes, never on a token renewal. Endpoints are fixed HTTPS hosts in code. Never taken from a file, the environment or a response. Tests prove it. Each provider's tests inject fake secrets into error responses and check that none reach the log. 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. Part 5: Bugs found after shipping 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: NSHostingView { 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: Font size Line height 12 pt ~14 pt 16 pt 18.8 pt 17 pt 20.0 pt 18 pt 21.2 pt (touches the edges) The setting became a 12–18 pt slider, with a note above 16 pt that the text may be clipped. Part 6: Shipping without a paid Apple Developer account 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: reads the latest GitHub release downloads the .pkg and a .sha256 file published with it saves the pkg only if the hashes match /// 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. What I'd tell someone building something similar Never write to another tool's credential store. Reading is a privilege. Writing makes you responsible for their bugs. Look at who writes a credential before you read it. It can turn a recurring permission prompt into none. Put rate limiting in one shared layer, and make "was a request sent?" an explicit value. Log only what you derive yourself, and test it with fake secrets. Write down rejected designs. The "obvious" alternative is often the risky one. 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.
Reading Three AI Agents' Usage Limits From Their Own Sign-Ins, Without Ever Writing Them
Full Article
Original Source
Read the full article at Hackernoon →KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.