0ef5fcb1c5
Security / Dependency audit (pip-audit) (push) Has been cancelled
Security / CodeQL (javascript-typescript) (push) Has been cancelled
Security / CodeQL (python) (push) Has been cancelled
Security / Secret scan (gitleaks) (push) Has been cancelled
rust / test (ubuntu) (push) Has been cancelled
rust / simulator e2e (macos-latest) (push) Has been cancelled
rust / simulator e2e (ubuntu-latest) (push) Has been cancelled
rust / simulator e2e (windows-latest) (push) Has been cancelled
rust / wheels (aarch64-apple-darwin) (push) Has been cancelled
rust / wheels (x86_64-unknown-linux-gnu) (push) Has been cancelled
rust / wheels (x86_64-apple-darwin) (push) Has been cancelled
rust / audit (push) Has been cancelled
rust / parity (nightly, allowed to fail during Phase 0) (push) Has been cancelled
CI / commitlint (push) Has been skipped
Dev Containers / validate (.devcontainer/devcontainer.json, default) (push) Failing after 0s
Dev Containers / validate (.devcontainer/memory-stack/devcontainer.json, memory-stack) (push) Failing after 0s
Dev Containers / validate-worktree (push) Failing after 0s
CI / changes (push) Failing after 4s
Deploy Documentation / validate (push) Has been skipped
Deploy Documentation / deploy (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, claude) (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, codex) (push) Failing after 1s
Install Native E2E / install-native (ubuntu-latest) (push) Failing after 1s
OpenCode Plugin / typecheck + build + test (push) Failing after 1s
Init Native E2E / init-native (ubuntu-latest, copilot) (push) Failing after 1s
Release Please / release-please (push) Failing after 1s
Wrap E2E / docker-wrap-e2e (push) Failing after 1s
Wrap Native E2E / wrap-native (ubuntu-latest) (push) Failing after 1s
Init E2E / docker-init-e2e (push) Failing after 4s
Merge Conflicts / merge-conflicts (push) Failing after 4s
CI / lint (push) Has been cancelled
CI / build-wheel (push) Has been cancelled
CI / build-wheel-windows (push) Has been cancelled
CI / prefetch-model (push) Has been cancelled
CI / test-dashboard-ui (push) Has been cancelled
CI / test (1) (push) Has been cancelled
CI / test (2) (push) Has been cancelled
CI / test (3) (push) Has been cancelled
CI / test (4) (push) Has been cancelled
CI / test-extras (push) Has been cancelled
CI / test-agno (push) Has been cancelled
CI / build (push) Has been cancelled
CI / workflow-validation (push) Has been cancelled
CI / docker-native-e2e (push) Has been cancelled
CI / windows-native-wrapper (push) Has been cancelled
CI / macos-native-wrapper (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-manifest (map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-nonroot name:code-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim name:code-slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-code-slim-nonroot name:code-slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-nonroot name:nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim name:slim]) (push) Has been cancelled
Docker / docker-build (map[name:amd64 platform:linux/amd64 runs_on:ubuntu-24.04], map[bake_target:runtime-slim-nonroot name:slim-nonroot]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime name:]) (push) Has been cancelled
Docker / docker-build (map[name:arm64 platform:linux/arm64 runs_on:ubuntu-24.04-arm], map[bake_target:runtime-code name:code]) (push) Has been cancelled
Docker / promote-latest (push) Has been cancelled
Init Native E2E / init-native (macos-latest, claude) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, codex) (push) Has been cancelled
Init Native E2E / init-native (macos-latest, copilot) (push) Has been cancelled
Install Native E2E / install-native (macos-latest) (push) Has been cancelled
Wrap Native E2E / wrap-native (macos-latest) (push) Has been cancelled
132 lines
4.3 KiB
Python
132 lines
4.3 KiB
Python
"""Async HTTP client for Anthropic's OAuth usage API.
|
|
|
|
Endpoint: GET https://api.anthropic.com/api/oauth/usage
|
|
Required header: anthropic-beta: oauth-2025-04-20
|
|
Auth: Authorization: Bearer <oauth_access_token>
|
|
|
|
Token resolution order (highest → lowest priority):
|
|
1. Explicit token passed to :meth:`fetch`
|
|
2. ``CLAUDE_CODE_OAUTH_TOKEN`` env-var
|
|
3. ``~/.claude/.credentials.json`` → ``claudeAiOauth.accessToken``
|
|
(respects ``CLAUDE_CONFIG_DIR`` env-var override)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from headroom.subscription.models import SubscriptionSnapshot
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"
|
|
_BETA_HEADER = "oauth-2025-04-20"
|
|
_TOKEN_EXPIRY_BUFFER_S = 60
|
|
|
|
|
|
def _credentials_path() -> Path:
|
|
base = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude")
|
|
return Path(base) / ".credentials.json"
|
|
|
|
|
|
def _load_credentials_file() -> dict[str, Any] | None:
|
|
"""Load raw credentials dict from the Claude Code credentials file."""
|
|
path = _credentials_path()
|
|
try:
|
|
with path.open() as fh:
|
|
return json.load(fh) # type: ignore[no-any-return]
|
|
except FileNotFoundError:
|
|
return None
|
|
except Exception as exc:
|
|
logger.debug("Cannot read credentials file %s: %s", path, exc)
|
|
return None
|
|
|
|
|
|
def read_cached_oauth_token() -> str | None:
|
|
"""Resolve a stored OAuth token for background polling (no request needed).
|
|
|
|
Returns the raw access token string if found and not expired, else None.
|
|
"""
|
|
# 1. Env var
|
|
env_token = os.environ.get("CLAUDE_CODE_OAUTH_TOKEN", "").strip()
|
|
if env_token:
|
|
return env_token
|
|
|
|
# 2. Credentials file
|
|
creds = _load_credentials_file()
|
|
if not creds:
|
|
return None
|
|
oauth = creds.get("claudeAiOauth") or {}
|
|
token = oauth.get("accessToken") or ""
|
|
if not token:
|
|
return None
|
|
|
|
# Check expiry (Anthropic stores timestamp in milliseconds)
|
|
expires_at_ms = oauth.get("expiresAt")
|
|
if expires_at_ms is not None:
|
|
import time
|
|
|
|
now_ms = time.time() * 1000
|
|
if now_ms >= (expires_at_ms - _TOKEN_EXPIRY_BUFFER_S * 1000):
|
|
logger.debug("Cached OAuth token expired; skipping background poll")
|
|
return None
|
|
|
|
return token
|
|
|
|
|
|
class SubscriptionClient:
|
|
"""Thin async wrapper around the Anthropic OAuth usage endpoint."""
|
|
|
|
def __init__(self, timeout: float = 10.0) -> None:
|
|
self._timeout = timeout
|
|
|
|
async def fetch(self, token: str | None = None) -> SubscriptionSnapshot | None:
|
|
"""Fetch current subscription window data.
|
|
|
|
:param token: OAuth access token. When *None*, falls back to
|
|
:func:`read_cached_oauth_token`.
|
|
:returns: :class:`SubscriptionSnapshot` or *None* on auth failure /
|
|
unsupported account.
|
|
"""
|
|
resolved = (token or "").strip() or read_cached_oauth_token()
|
|
if not resolved:
|
|
logger.debug("No OAuth token available for subscription polling")
|
|
return None
|
|
|
|
headers = {
|
|
"Authorization": f"Bearer {resolved}",
|
|
"anthropic-beta": _BETA_HEADER,
|
|
"Content-Type": "application/json",
|
|
}
|
|
|
|
try:
|
|
async with httpx.AsyncClient(timeout=self._timeout) as client:
|
|
resp = await client.get(_USAGE_URL, headers=headers)
|
|
|
|
if resp.status_code == 401:
|
|
logger.debug("OAuth token rejected (401) by Anthropic usage API")
|
|
return None
|
|
if resp.status_code == 404:
|
|
# API key accounts (non-subscription) return 404
|
|
logger.debug("Subscription usage API returned 404; likely API-key account")
|
|
return None
|
|
if resp.status_code != 200:
|
|
logger.warning("Anthropic usage API returned %s", resp.status_code)
|
|
return None
|
|
|
|
data: dict[str, Any] = resp.json()
|
|
return SubscriptionSnapshot.from_api_response(data, token=resolved)
|
|
|
|
except httpx.TimeoutException:
|
|
logger.debug("Timeout fetching Anthropic subscription window")
|
|
return None
|
|
except Exception as exc:
|
|
logger.warning("Error fetching subscription window: %s", exc)
|
|
return None
|