From 279740ba35e9818d16f78a7ab57f59256c4d0dc5 Mon Sep 17 00:00:00 2001 From: dafuga Date: Sun, 29 Nov 2026 16:13:29 +0000 Subject: [PATCH 1/6] chore: version the host Claude quota helper with private credential transport --- scripts/claude-usage | 95 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100755 scripts/claude-usage diff --git a/scripts/claude-usage b/scripts/claude-usage new file mode 100755 index 00000000000..15f28d051ab --- /dev/null +++ b/scripts/claude-usage @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Print the weekly and five-hour quota for the local Claude Code subscription.""" + +import datetime +import json +import math +import os +import pwd +import subprocess +import sys +import time +import urllib.error +import urllib.request + +SERVICE = "Claude Code-credentials" +USAGE_URL = "https://api.anthropic.com/api/oauth/usage" + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, request, fp, code, msg, headers, newurl): + return None + + +def read_oauth(account=None): + command = ["/usr/bin/security", "find-generic-password", "-s", SERVICE] + if account is not None: + command.extend(["-a", account]) + try: + result = subprocess.run( + [*command, "-w"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + check=True, + timeout=10, + ) + payload = json.loads(result.stdout) + oauth = payload.get("claudeAiOauth") if isinstance(payload, dict) else None + return oauth if isinstance(oauth, dict) else {} + except (subprocess.SubprocessError, ValueError): + return {} + + +def current_token(now_ms): + token = read_oauth().get("accessToken") + return token if isinstance(token, str) and token else None + + +def read_quota(token): + request = urllib.request.Request( + USAGE_URL, + headers={ + "Authorization": f"Bearer {token}", + "anthropic-beta": "oauth-2025-04-20", + }, + ) + with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response: + return json.load(response) + + +def quota_lines(payload): + lines = [] + for name in ("seven_day", "five_hour"): + window = payload[name] + utilization = window["utilization"] + reset = datetime.datetime.fromisoformat(window["resets_at"]) + if ( + type(utilization) not in (int, float) + or not math.isfinite(utilization) + or utilization < 0 + or reset.utcoffset() is None + ): + raise ValueError("Invalid quota window") + lines.append(f"{name} {utilization} {reset.isoformat()}") + return lines + + +def main(): + try: + token = current_token(time.time() * 1000) + if not token: + print("claude-usage: no current Claude Code credential found", file=sys.stderr) + return 1 + lines = quota_lines(read_quota(token)) + except urllib.error.HTTPError as error: + print(f"claude-usage: quota endpoint returned HTTP {error.code}", file=sys.stderr) + return 1 + except (KeyError, TypeError, ValueError, OSError, OverflowError, subprocess.SubprocessError): + print("claude-usage: unable to read both quota windows", file=sys.stderr) + return 1 + print("\n".join(lines)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 158b07ac5392d465a56e539451e3d89cab368546 Mon Sep 17 00:00:00 2001 From: dafuga Date: Sun, 29 Nov 2026 16:13:29 +0000 Subject: [PATCH 2/6] chore: reproduce stale Claude quota credential selection --- test/claude-usage.test.py | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 test/claude-usage.test.py diff --git a/test/claude-usage.test.py b/test/claude-usage.test.py new file mode 100644 index 00000000000..7863a65f582 --- /dev/null +++ b/test/claude-usage.test.py @@ -0,0 +1,52 @@ +"""Offline regression for the host quota helper.""" + +import contextlib +import io +from pathlib import Path +from types import SimpleNamespace +import runpy +import unittest +from unittest.mock import patch +from urllib.error import HTTPError + + +class ClaudeUsageTest(unittest.TestCase): + def test_expired_first_match_does_not_mask_current_account(self): + path = Path(__file__).resolve().parents[1] / "scripts/claude-usage" + main = runpy.run_path(str(path))["main"] + oauth = { + None: {"accessToken": "fixture-expired", "expiresAt": 1000}, + "local-account": {"accessToken": "fixture-current", "expiresAt": 4000}, + } + quota = { + "five_hour": {"utilization": 12, "resets_at": "2026-11-29T17:00:00+00:00"}, + "seven_day": {"utilization": 95.5, "resets_at": "2026-12-01T00:00:00+00:00"}, + } + + def provider(token): + if token != "fixture-current": + raise HTTPError("https://example.invalid", 401, "Invalid bearer token", {}, None) + return quota + + stdout, stderr = io.StringIO(), io.StringIO() + with ( + patch.dict(main.__globals__, { + "read_oauth": lambda account=None: oauth[account], + "read_quota": provider, + }), + patch("pwd.getpwuid", return_value=SimpleNamespace(pw_name="local-account")), + patch("time.time", return_value=2), + contextlib.redirect_stdout(stdout), + contextlib.redirect_stderr(stderr), + ): + self.assertEqual(main(), 0, stderr.getvalue()) + self.assertEqual( + stdout.getvalue(), + "seven_day 95.5 2026-12-01T00:00:00+00:00\n" + "five_hour 12 2026-11-29T17:00:00+00:00\n", + ) + self.assertEqual(stderr.getvalue(), "") + + +if __name__ == "__main__": + unittest.main() From 9d205e7a95dc2d3f5f7e74937eb5a3c0bbb7a983 Mon Sep 17 00:00:00 2001 From: dafuga Date: Sun, 29 Nov 2026 16:13:53 +0000 Subject: [PATCH 3/6] fix: bind Claude quota reads to the current macOS account --- scripts/claude-usage | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/scripts/claude-usage b/scripts/claude-usage index 15f28d051ab..6b09a50c98e 100755 --- a/scripts/claude-usage +++ b/scripts/claude-usage @@ -21,13 +21,10 @@ class NoRedirect(urllib.request.HTTPRedirectHandler): return None -def read_oauth(account=None): - command = ["/usr/bin/security", "find-generic-password", "-s", SERVICE] - if account is not None: - command.extend(["-a", account]) +def read_oauth(account): try: result = subprocess.run( - [*command, "-w"], + ["/usr/bin/security", "find-generic-password", "-s", SERVICE, "-a", account, "-w"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=True, @@ -41,8 +38,18 @@ def read_oauth(account=None): def current_token(now_ms): - token = read_oauth().get("accessToken") - return token if isinstance(token, str) and token else None + oauth = read_oauth(pwd.getpwuid(os.getuid()).pw_name) + token = oauth.get("accessToken") + expiry = oauth.get("expiresAt") + if ( + isinstance(token, str) + and token + and type(expiry) in (int, float) + and math.isfinite(expiry) + and expiry > now_ms + ): + return token + return None def read_quota(token): From 6136cca7a3566019aef2ffaad477d88d7bb1e45f Mon Sep 17 00:00:00 2001 From: dafuga Date: Mon, 30 Nov 2026 15:12:16 +0000 Subject: [PATCH 4/6] chore: reproduce Claude quota rate-limit failures --- test/claude-usage.test.py | 116 ++++++++++++++++++++++++++------------ 1 file changed, 80 insertions(+), 36 deletions(-) diff --git a/test/claude-usage.test.py b/test/claude-usage.test.py index 7863a65f582..144026be4f2 100644 --- a/test/claude-usage.test.py +++ b/test/claude-usage.test.py @@ -5,47 +5,91 @@ from pathlib import Path from types import SimpleNamespace import runpy +import tempfile import unittest -from unittest.mock import patch +from unittest.mock import Mock, patch from urllib.error import HTTPError +NOW = 1795978800 # 2026-11-29T19:00:00Z +QUOTA = { + "five_hour": {"utilization": 12, "resets_at": "2026-11-29T20:00:00+00:00"}, + "seven_day": {"utilization": 95.5, "resets_at": "2026-12-01T00:00:00+00:00"}, +} +EXPECTED = ( + "seven_day 95.5 2026-12-01T00:00:00+00:00\n" + "five_hour 12 2026-11-29T20:00:00+00:00\n" +) + + +def invoke(home, provider, now): + path = Path(__file__).resolve().parents[1] / "scripts/claude-usage" + main = runpy.run_path(str(path))["main"] + oauth = { + None: {"accessToken": "fixture-expired", "expiresAt": (NOW - 1) * 1000}, + "local-account": {"accessToken": "fixture-current", "expiresAt": (NOW + 86400) * 1000}, + } + stdout, stderr = io.StringIO(), io.StringIO() + with ( + patch.dict(main.__globals__, { + "read_oauth": lambda account=None: oauth[account], + "read_quota": provider, + }), + patch("pathlib.Path.home", return_value=home), + patch("pwd.getpwuid", return_value=SimpleNamespace(pw_name="local-account")), + patch("time.time", return_value=now), + contextlib.redirect_stdout(stdout), + contextlib.redirect_stderr(stderr), + ): + result = main() + return result, stdout.getvalue(), stderr.getvalue() + + class ClaudeUsageTest(unittest.TestCase): - def test_expired_first_match_does_not_mask_current_account(self): - path = Path(__file__).resolve().parents[1] / "scripts/claude-usage" - main = runpy.run_path(str(path))["main"] - oauth = { - None: {"accessToken": "fixture-expired", "expiresAt": 1000}, - "local-account": {"accessToken": "fixture-current", "expiresAt": 4000}, - } - quota = { - "five_hour": {"utilization": 12, "resets_at": "2026-11-29T17:00:00+00:00"}, - "seven_day": {"utilization": 95.5, "resets_at": "2026-12-01T00:00:00+00:00"}, - } - - def provider(token): - if token != "fixture-current": - raise HTTPError("https://example.invalid", 401, "Invalid bearer token", {}, None) - return quota - - stdout, stderr = io.StringIO(), io.StringIO() - with ( - patch.dict(main.__globals__, { - "read_oauth": lambda account=None: oauth[account], - "read_quota": provider, - }), - patch("pwd.getpwuid", return_value=SimpleNamespace(pw_name="local-account")), - patch("time.time", return_value=2), - contextlib.redirect_stdout(stdout), - contextlib.redirect_stderr(stderr), - ): - self.assertEqual(main(), 0, stderr.getvalue()) - self.assertEqual( - stdout.getvalue(), - "seven_day 95.5 2026-12-01T00:00:00+00:00\n" - "five_hour 12 2026-11-29T17:00:00+00:00\n", - ) - self.assertEqual(stderr.getvalue(), "") + def test_current_account_reading_survives_rate_limit(self): + rate_limit = HTTPError("https://example.invalid", 429, "Too Many Requests", { + "Retry-After": "90", + }, None) + updated_quota = {**QUOTA, "seven_day": {**QUOTA["seven_day"], "utilization": 97}} + provider = Mock(side_effect=[QUOTA, rate_limit, updated_quota]) + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + self.assertEqual(invoke(home, provider, NOW), (0, EXPECTED, "")) + status, lines, warning = invoke(home, provider, NOW + 1) + self.assertEqual((status, lines), (0, EXPECTED)) + self.assertIn("cached quota", warning) + self.assertEqual(invoke(home, provider, NOW + 90)[:2], (0, EXPECTED)) + self.assertEqual(provider.call_count, 2) + self.assertEqual( + invoke(home, provider, NOW + 91), (0, EXPECTED.replace("95.5", "97"), "") + ) + self.assertEqual([call.args for call in provider.call_args_list], [("fixture-current",)] * 3) + + def test_rate_limit_without_a_current_sample_still_backs_off(self): + rate_limit = HTTPError("https://example.invalid", 429, "Too Many Requests", {}, None) + provider = Mock(side_effect=[rate_limit, QUOTA]) + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + self.assertEqual(invoke(home, provider, NOW)[:2], (1, "")) + self.assertEqual(invoke(home, provider, NOW + 1)[:2], (1, "")) + self.assertEqual(provider.call_count, 1) + self.assertEqual(invoke(home, provider, NOW + 300), (0, EXPECTED, "")) + + def test_cached_reading_expires_at_reset_and_never_hides_an_auth_failure(self): + unauthorized = HTTPError("https://example.invalid", 401, "Invalid bearer token", {}, None) + rate_limit = HTTPError("https://example.invalid", 429, "Too Many Requests", { + "Retry-After": "Sun, 29 Nov 2026 21:00:00 GMT", + }, None) + provider = Mock(side_effect=[QUOTA, rate_limit, unauthorized, rate_limit]) + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + self.assertEqual(invoke(home, provider, NOW), (0, EXPECTED, "")) + self.assertEqual(invoke(home, provider, NOW + 1)[:2], (0, EXPECTED)) + self.assertEqual(invoke(home, provider, NOW + 3600)[:2], (1, "")) + self.assertEqual(provider.call_count, 2) + self.assertEqual(invoke(home, provider, NOW + 7200)[:2], (1, "")) + self.assertEqual(invoke(home, provider, NOW + 7201)[:2], (1, "")) + self.assertEqual(provider.call_count, 4) if __name__ == "__main__": From d2a83478a3c96d7a8a264f6f49feebcd971ca169 Mon Sep 17 00:00:00 2001 From: dafuga Date: Mon, 30 Nov 2026 15:13:19 +0000 Subject: [PATCH 5/6] fix: back off and cache Claude quota on HTTP 429 --- scripts/claude-usage | 110 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 96 insertions(+), 14 deletions(-) diff --git a/scripts/claude-usage b/scripts/claude-usage index 6b09a50c98e..6bc3e3c9d29 100755 --- a/scripts/claude-usage +++ b/scripts/claude-usage @@ -2,18 +2,24 @@ """Print the weekly and five-hour quota for the local Claude Code subscription.""" import datetime +from email.utils import parsedate_to_datetime +import fcntl import json import math import os +from pathlib import Path import pwd import subprocess import sys +import tempfile import time import urllib.error import urllib.request SERVICE = "Claude Code-credentials" USAGE_URL = "https://api.anthropic.com/api/oauth/usage" +WINDOWS = ("seven_day", "five_hour") +DEFAULT_RETRY_SECONDS = 300 class NoRedirect(urllib.request.HTTPRedirectHandler): @@ -64,9 +70,9 @@ def read_quota(token): return json.load(response) -def quota_lines(payload): - lines = [] - for name in ("seven_day", "five_hour"): +def quota_windows(payload): + windows = {} + for name in WINDOWS: window = payload[name] utilization = window["utilization"] reset = datetime.datetime.fromisoformat(window["resets_at"]) @@ -77,24 +83,100 @@ def quota_lines(payload): or reset.utcoffset() is None ): raise ValueError("Invalid quota window") - lines.append(f"{name} {utilization} {reset.isoformat()}") - return lines + windows[name] = {"utilization": utilization, "resets_at": reset.isoformat()} + return windows -def main(): +def read_cache(path): try: - token = current_token(time.time() * 1000) - if not token: - print("claude-usage: no current Claude Code credential found", file=sys.stderr) - return 1 - lines = quota_lines(read_quota(token)) + state = json.loads(path.read_text()) + retry_at = state.get("retry_at", 0) + if not math.isfinite(retry_at): + return {}, 0 + return quota_windows(state["quota"]) if state.get("quota") else {}, retry_at + except (FileNotFoundError, AttributeError, KeyError, TypeError, ValueError, OverflowError): + return {}, 0 + + +def write_cache(path, quota, retry_at=0): + with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream: + temporary = Path(stream.name) + try: + json.dump({"quota": quota, "retry_at": retry_at}, stream) + stream.close() + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + + +def retry_deadline(header, now): + if header: + try: + retry_at = now + int(header) + except ValueError: + try: + retry_at = parsedate_to_datetime(header).timestamp() + except (ValueError, TypeError, OverflowError, OSError): + retry_at = 0 + except OverflowError: + retry_at = 0 + if retry_at > now and math.isfinite(retry_at): + return retry_at + return now + DEFAULT_RETRY_SECONDS + + +def cached_quota(quota, now): + if quota and all( + datetime.datetime.fromisoformat(window["resets_at"]).timestamp() > now + for window in quota.values() + ): + print("claude-usage: rate limited, using cached quota", file=sys.stderr) + return quota + print("claude-usage: rate limited, no current cached quota", file=sys.stderr) + return {} + + +def load_quota(path): + quota, retry_at = read_cache(path) + now = time.time() + if now < retry_at: + return cached_quota(quota, now) + token = current_token(now * 1000) + if not token: + path.unlink(missing_ok=True) + print("claude-usage: no current Claude Code credential found", file=sys.stderr) + return {} + try: + quota = quota_windows(read_quota(token)) except urllib.error.HTTPError as error: - print(f"claude-usage: quota endpoint returned HTTP {error.code}", file=sys.stderr) - return 1 + with error: + if error.code == 429: + now = time.time() + write_cache(path, quota, retry_deadline(error.headers.get("Retry-After"), now)) + return cached_quota(quota, now) + if error.code in (401, 403): + path.unlink(missing_ok=True) + print(f"claude-usage: quota endpoint returned HTTP {error.code}", file=sys.stderr) + return {} + write_cache(path, quota) + return quota + + +def main(): + try: + directory = Path.home() / "Library/Caches/harness-claude-usage" + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + # Hold the lock over the request so simultaneous invocations respect the same backoff. + with (directory / "lock").open("a") as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + quota = load_quota(directory / "quota.json") except (KeyError, TypeError, ValueError, OSError, OverflowError, subprocess.SubprocessError): print("claude-usage: unable to read both quota windows", file=sys.stderr) return 1 - print("\n".join(lines)) + if not quota: + return 1 + for name, window in quota.items(): + print(f"{name} {window['utilization']} {window['resets_at']}") return 0 From 503d9dc30091522996dab0801f1ee5c8de327486 Mon Sep 17 00:00:00 2001 From: dafuga Date: Mon, 30 Nov 2026 15:19:45 +0000 Subject: [PATCH 6/6] chore: register the Claude quota regression for focused checks --- test/claude-usage.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 test/claude-usage.test.ts diff --git a/test/claude-usage.test.ts b/test/claude-usage.test.ts new file mode 100644 index 00000000000..4d863359e05 --- /dev/null +++ b/test/claude-usage.test.ts @@ -0,0 +1,14 @@ +import { execFileSync } from 'node:child_process'; +import { accessSync, constants } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { test } from 'vitest'; + +test('the executable Claude quota helper passes its offline regression', () => { + const helper = new URL('../scripts/claude-usage', import.meta.url); + const regression = new URL('./claude-usage.test.py', import.meta.url); + accessSync(helper, constants.X_OK); + execFileSync('python3', [fileURLToPath(regression)], { + stdio: 'pipe', + timeout: 10_000 + }); +});