Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat: add GitHub Copilot monthly quota tracking
JerrettDavisd11feea51126
diff --git a/docs/screenshots/subscription_window_active.png b/docs/screenshots/subscription_window_active.pngindex d826cf4f1..b3bb88e97 100644Binary files a/docs/screenshots/subscription_window_active.png and b/docs/screenshots/subscription_window_active.png differdiff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex 007540bed..3bd8011f7 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -370,6 +370,66 @@</template></div></template>++ <!-- GitHub Copilot Quota panel -->+ <template x-if="stats.copilot_quota && stats.copilot_quota.latest">+ <div class="bg-surface rounded-lg p-4 border border-border mb-6">+ <div class="flex justify-between items-center mb-3">+ <div class="text-sm font-medium text-gray-300">GitHub Copilot Quota</div>+ <div class="flex items-center gap-2">+ <template x-if="stats.copilot_quota.latest.copilot_plan">+ <span class="text-xs text-gray-500 font-mono capitalize" x-text="stats.copilot_quota.latest.copilot_plan + ' plan'"></span>+ </template>+ <template x-if="stats.copilot_quota.latest.login">+ <span class="text-xs text-gray-400" x-text="'@' + stats.copilot_quota.latest.login"></span>+ </template>+ </div>+ </div>++ <!-- Per-category quota bars -->+ <template x-for="[catKey, catLabel] in [['chat', 'Chat'], ['completions', 'Completions'], ['premium_interactions', 'Premium']]" :key="catKey">+ <template x-if="stats.copilot_quota.latest.categories[catKey]">+ <div class="mb-3">+ <div class="flex justify-between items-center mb-1">+ <span class="text-xs text-gray-400" x-text="catLabel"></span>+ <div class="flex items-center gap-2">+ <template x-if="stats.copilot_quota.latest.categories[catKey].unlimited">+ <span class="text-xs text-purple-400">∞ Unlimited</span>+ </template>+ <template x-if="!stats.copilot_quota.latest.categories[catKey].unlimited">+ <span class="text-xs font-mono"+ :class="(stats.copilot_quota.latest.categories[catKey].used_percent||0) > 80 ? 'text-red-400' : (stats.copilot_quota.latest.categories[catKey].used_percent||0) > 50 ? 'text-amber-400' : 'text-emerald-400'"+ x-text="(stats.copilot_quota.latest.categories[catKey].used_percent||0).toFixed(0) + '% used'"></span>+ </template>+ <template x-if="stats.copilot_quota.latest.categories[catKey].remaining !== null && stats.copilot_quota.latest.categories[catKey].remaining !== undefined && !stats.copilot_quota.latest.categories[catKey].unlimited">+ <span class="text-xs text-gray-500 font-mono"+ x-text="stats.copilot_quota.latest.categories[catKey].remaining + ' left'"></span>+ </template>+ </div>+ </div>+ <template x-if="!stats.copilot_quota.latest.categories[catKey].unlimited">+ <div class="h-1.5 bg-gray-700 rounded-full overflow-hidden">+ <div class="h-full rounded-full transition-all duration-500"+ :class="(stats.copilot_quota.latest.categories[catKey].used_percent||0) > 80 ? 'bg-red-500' : (stats.copilot_quota.latest.categories[catKey].used_percent||0) > 50 ? 'bg-amber-500' : 'bg-emerald-500'"+ :style="'width: ' + Math.min(stats.copilot_quota.latest.categories[catKey].used_percent||0, 100) + '%'"></div>+ </div>+ </template>+ <template x-if="stats.copilot_quota.latest.categories[catKey].overage_count > 0">+ <div class="text-xs text-amber-400 mt-0.5"+ x-text="stats.copilot_quota.latest.categories[catKey].overage_count + ' overage uses'"></div>+ </template>+ </div>+ </template>+ </template>++ <!-- Reset date -->+ <template x-if="stats.copilot_quota.latest.quota_reset_date_utc">+ <div class="text-xs text-gray-500 mt-2"+ x-text="'Monthly quota resets: ' + stats.copilot_quota.latest.quota_reset_date_utc"></div>+ </template>+ </div>+ </template>+<template x-if="(stats.prefix_cache?.totals?.requests || 0) > 0"><div class="bg-surface rounded-lg p-4 border border-border mb-6"><div class="flex justify-between items-center mb-3">diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 70d62263e..fae3e9883 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -128,6 +128,7 @@ from headroom.proxy.rate_limiter import TokenBucketRateLimiter # noqa: F401from headroom.proxy.request_logger import RequestLogger # noqa: F401from headroom.proxy.semantic_cache import SemanticCache # noqa: F401from headroom.subscription.codex_rate_limits import get_codex_rate_limit_state+from headroom.subscription.copilot_quota import discover_github_token, get_copilot_quota_trackerfrom headroom.subscription.tracker import (configure_subscription_tracker,get_subscription_tracker,@@ -160,6 +161,14 @@ def _get_codex_rate_limit_stats() -> dict | None:return get_codex_rate_limit_state().get_stats()+def _get_copilot_quota_stats() -> dict | None:+ """Return the latest GitHub Copilot quota snapshot for the /stats endpoint."""+ state = get_copilot_quota_tracker().state+ if state.get("latest") is None and state.get("last_error") is None:+ return None+ return state++logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")@@ -689,6 +698,17 @@ class HeadroomProxy(else:logger.info("Subscription tracking: DISABLED")+ # Start GitHub Copilot quota tracking if a GitHub token is available+ if discover_github_token():+ copilot_tracker = get_copilot_quota_tracker()+ await copilot_tracker.start()+ logger.info("GitHub Copilot quota tracking: ENABLED")+ else:+ logger.info(+ "GitHub Copilot quota tracking: DISABLED "+ "(set GITHUB_TOKEN or GITHUB_COPILOT_GITHUB_TOKEN to enable)"+ )+# Log anonymous telemetry status so operators can see it in the log streamif is_telemetry_enabled():logger.info(@@ -710,6 +730,9 @@ class HeadroomProxy(# Stop subscription trackerawait shutdown_subscription_tracker()+ # Stop Copilot quota tracker+ await get_copilot_quota_tracker().stop()+# Print final statsself._print_summary()@@ -1401,6 +1424,7 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:if get_subscription_tracker()else None,"codex_rate_limits": _get_codex_rate_limit_stats(),+ "copilot_quota": _get_copilot_quota_stats(),}@app.get("/stats-history")diff --git a/headroom/subscription/__init__.py b/headroom/subscription/__init__.pyindex 57661d947..d40a3aca0 100644--- a/headroom/subscription/__init__.py+++ b/headroom/subscription/__init__.py@@ -9,6 +9,14 @@ from headroom.subscription.codex_rate_limits import (get_codex_rate_limit_state,parse_codex_rate_limits,)+from headroom.subscription.copilot_quota import (+ CopilotQuotaCategory,+ CopilotQuotaSnapshot,+ CopilotQuotaState,+ discover_github_token,+ get_copilot_quota_tracker,+ parse_copilot_quota,+)from headroom.subscription.models import (ExtraUsage,HeadroomContribution,@@ -30,6 +38,9 @@ __all__ = ["CodexRateLimitSnapshot","CodexRateLimitState","CodexRateLimitWindow",+ "CopilotQuotaCategory",+ "CopilotQuotaSnapshot",+ "CopilotQuotaState","ExtraUsage","HeadroomContribution","RateLimitWindow",@@ -40,9 +51,12 @@ __all__ = ["WindowDiscrepancy","WindowTokens","configure_subscription_tracker",+ "discover_github_token","get_codex_rate_limit_state",+ "get_copilot_quota_tracker","get_subscription_tracker","parse_codex_rate_limits",+ "parse_copilot_quota","read_cached_oauth_token","shutdown_subscription_tracker",]diff --git a/headroom/subscription/copilot_quota.py b/headroom/subscription/copilot_quota.pynew file mode 100644index 000000000..9c4399da9--- /dev/null+++ b/headroom/subscription/copilot_quota.py@@ -0,0 +1,331 @@+"""GitHub Copilot monthly quota tracking via the copilot_internal/user API.++GitHub Copilot exposes per-category monthly quotas (chat, completions,+premium_interactions) at ``GET https://api.github.com/copilot_internal/user``+authenticated with a GitHub Bearer token.++Token discovery order (first non-empty wins):+ 1. GITHUB_COPILOT_GITHUB_TOKEN+ 2. GITHUB_TOKEN+ 3. COPILOT_GITHUB_TOKEN+ 4. GITHUB_COPILOT_API_TOKEN++The poll is triggered every ``poll_interval_s`` seconds (default 60) as long as+a GitHub token is available. No proxy traffic interception is needed — tokens+come from the environment at headroom start-up.++API response schema (relevant fields from ``/copilot_internal/user``):+ login str GitHub username+ copilot_plan str "free" | "individual" | "business" | "enterprise"+ access_type_sku str plan SKU string+ quota_reset_date_utc str ISO-8601 date when monthly quota resets+ quota_snapshots:+ chat / completions / premium_interactions:+ entitlement int total monthly allocation+ remaining int remaining uses this month+ quota_remaining int (alias for remaining)+ percent_remaining float 0-100+ overage_count int uses beyond entitlement+ overage_permitted bool whether overage is allowed+ unlimited bool whether this category is unlimited+ timestamp_utc str when the snapshot was recorded+"""++from __future__ import annotations++import asyncio+import logging+import os+import time+from dataclasses import dataclass, field+from threading import Lock+from typing import Any++logger = logging.getLogger(__name__)++_GITHUB_API_BASE = "https://api.github.com"+_TOKEN_ENV_VARS = [+ "GITHUB_COPILOT_GITHUB_TOKEN",+ "GITHUB_TOKEN",+ "COPILOT_GITHUB_TOKEN",+ "GITHUB_COPILOT_API_TOKEN",+]++# Categories surfaced by the quota_snapshots endpoint+QUOTA_CATEGORIES = ("chat", "completions", "premium_interactions")+++# ---------------------------------------------------------------------------+# Data classes+# ---------------------------------------------------------------------------+++@dataclass+class CopilotQuotaCategory:+ """Quota data for a single Copilot usage category."""++ name: str+ entitlement: int | None = None # total monthly allocation+ remaining: int | None = None # remaining uses+ percent_remaining: float | None = None # 0-100+ overage_count: int = 0 # uses beyond entitlement+ overage_permitted: bool = False+ unlimited: bool = False+ timestamp_utc: str | None = None++ @property+ def used(self) -> int | None:+ if self.entitlement is not None and self.remaining is not None:+ return max(0, self.entitlement - self.remaining)+ return None++ @property+ def used_percent(self) -> float | None:+ if self.unlimited:+ return 0.0+ if self.percent_remaining is not None:+ return max(0.0, 100.0 - self.percent_remaining)+ if self.entitlement and self.entitlement > 0 and self.remaining is not None:+ return 100.0 * (self.entitlement - self.remaining) / self.entitlement+ return None++ def to_dict(self) -> dict[str, Any]:+ return {+ "name": self.name,+ "entitlement": self.entitlement,+ "remaining": self.remaining,+ "used": self.used,+ "percent_remaining": self.percent_remaining,+ "used_percent": self.used_percent,+ "overage_count": self.overage_count,+ "overage_permitted": self.overage_permitted,+ "unlimited": self.unlimited,+ "timestamp_utc": self.timestamp_utc,+ }+++@dataclass+class CopilotQuotaSnapshot:+ """Full quota snapshot from one /copilot_internal/user response."""++ login: str | None = None+ copilot_plan: str | None = None+ access_type_sku: str | None = None+ quota_reset_date_utc: str | None = None+ categories: dict[str, CopilotQuotaCategory] = field(default_factory=dict)+ fetched_at: float = field(default_factory=time.time)++ def to_dict(self) -> dict[str, Any]:+ return {+ "login": self.login,+ "copilot_plan": self.copilot_plan,+ "access_type_sku": self.access_type_sku,+ "quota_reset_date_utc": self.quota_reset_date_utc,+ "categories": {k: v.to_dict() for k, v in self.categories.items()},+ "fetched_at": self.fetched_at,+ }+++@dataclass+class CopilotQuotaState:+ """Thread-safe singleton state for Copilot quota tracking."""++ latest: CopilotQuotaSnapshot | None = None+ last_error: str | None = None+ last_updated: float | None = None++ def to_dict(self) -> dict[str, Any]:+ return {+ "latest": self.latest.to_dict() if self.latest else None,+ "last_error": self.last_error,+ "last_updated": self.last_updated,+ }+++# ---------------------------------------------------------------------------+# Parsing+# ---------------------------------------------------------------------------+++def parse_copilot_quota(data: dict[str, Any]) -> CopilotQuotaSnapshot:+ """Parse a /copilot_internal/user response into a ``CopilotQuotaSnapshot``."""+ snapshot = CopilotQuotaSnapshot(+ login=data.get("login"),+ copilot_plan=data.get("copilot_plan"),+ access_type_sku=data.get("access_type_sku"),+ quota_reset_date_utc=data.get("quota_reset_date_utc") or data.get("quota_reset_date"),+ )++ raw_qs = data.get("quota_snapshots") or {}+ for cat_name in QUOTA_CATEGORIES:+ raw = raw_qs.get(cat_name)+ if not raw:+ continue+ remaining = raw.get("remaining") or raw.get("quota_remaining")+ cat = CopilotQuotaCategory(+ name=cat_name,+ entitlement=raw.get("entitlement"),+ remaining=remaining,+ percent_remaining=raw.get("percent_remaining"),+ overage_count=raw.get("overage_count") or 0,+ overage_permitted=bool(raw.get("overage_permitted")),+ unlimited=bool(raw.get("unlimited")),+ timestamp_utc=raw.get("timestamp_utc"),+ )+ snapshot.categories[cat_name] = cat++ return snapshot+++# ---------------------------------------------------------------------------+# Token discovery+# ---------------------------------------------------------------------------+++def discover_github_token() -> str | None:+ """Return the first GitHub token found from known environment variables."""+ for var in _TOKEN_ENV_VARS:+ val = os.environ.get(var, "").strip()+ if val:+ return val+ return None+++# ---------------------------------------------------------------------------+# Background tracker singleton+# ---------------------------------------------------------------------------+++class _CopilotQuotaTracker:+ """Singleton background poller for GitHub Copilot quota."""++ def __init__(self, poll_interval_s: float = 60.0) -> None:+ self._poll_interval_s = poll_interval_s+ self._state = CopilotQuotaState()+ self._lock = Lock()+ self._stop_event: asyncio.Event | None = None+ self._task: asyncio.Task | None = None # type: ignore[type-arg]++ # ------------------------------------------------------------------+ # Lifecycle+ # ------------------------------------------------------------------++ async def start(self) -> None:+ """Start the background polling loop."""+ if self._task is not None and not self._task.done():+ return+ self._stop_event = asyncio.Event()+ self._task = asyncio.create_task(self._poll_loop())++ async def stop(self) -> None:+ """Stop the polling loop."""+ if self._stop_event:+ self._stop_event.set()+ if self._task:+ try:+ await asyncio.wait_for(self._task, timeout=5.0)+ except (asyncio.TimeoutError, asyncio.CancelledError):+ pass++ # ------------------------------------------------------------------+ # State+ # ------------------------------------------------------------------++ @property+ def state(self) -> dict[str, Any]:+ with self._lock:+ return self._state.to_dict()++ # ------------------------------------------------------------------+ # Poll loop+ # ------------------------------------------------------------------++ async def _poll_loop(self) -> None:+ assert self._stop_event is not None+ while not self._stop_event.is_set():+ try:+ await self._maybe_poll()+ except Exception as exc:+ logger.warning("Copilot quota poll error: %s", exc)+ try:+ await asyncio.wait_for(+ asyncio.shield(self._stop_event.wait()),+ timeout=self._poll_interval_s,+ )+ break # stop event was set+ except asyncio.TimeoutError:+ pass # normal: poll interval elapsed++ async def _maybe_poll(self) -> None:+ token = discover_github_token()+ if not token:+ return++ try:+ import aiohttp+ except ImportError:+ logger.debug("aiohttp not available; skipping Copilot quota poll")+ return++ url = f"{_GITHUB_API_BASE}/copilot_internal/user"+ headers = {+ "Authorization": f"Bearer {token}",+ "Accept": "application/json",+ "X-GitHub-Api-Version": "2022-11-28",+ }++ try:+ async with aiohttp.ClientSession() as session:+ async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=10)) as resp:+ if resp.status == 401:+ with self._lock:+ self._state.last_error = "unauthorized — check GITHUB_TOKEN"+ return+ if resp.status == 404:+ # API-key-only account or endpoint not available+ with self._lock:+ self._state.last_error = "endpoint not found (non-Copilot account?)"+ return+ if not resp.ok:+ with self._lock:+ self._state.last_error = f"HTTP {resp.status}"+ return++ data = await resp.json()+ except Exception as exc:+ with self._lock:+ self._state.last_error = str(exc)+ logger.debug("Copilot quota fetch failed: %s", exc)+ return++ try:+ snapshot = parse_copilot_quota(data)+ except Exception as exc:+ with self._lock:+ self._state.last_error = f"parse error: {exc}"+ return++ with self._lock:+ self._state.latest = snapshot+ self._state.last_error = None+ self._state.last_updated = time.time()++ logger.debug(+ "Copilot quota polled: plan=%s categories=%s",+ snapshot.copilot_plan,+ list(snapshot.categories.keys()),+ )+++_singleton_lock = Lock()+_singleton: _CopilotQuotaTracker | None = None+++def get_copilot_quota_tracker() -> _CopilotQuotaTracker:+ """Return the global ``_CopilotQuotaTracker`` singleton."""+ global _singleton+ if _singleton is None:+ with _singleton_lock:+ if _singleton is None:+ _singleton = _CopilotQuotaTracker()+ return _singletondiff --git a/tests/test_copilot_quota.py b/tests/test_copilot_quota.pynew file mode 100644index 000000000..9528ff82f--- /dev/null+++ b/tests/test_copilot_quota.py@@ -0,0 +1,259 @@+"""Unit tests for headroom.subscription.copilot_quota."""++from __future__ import annotations++import time++import pytest++from headroom.subscription.copilot_quota import (+ CopilotQuotaCategory,+ CopilotQuotaSnapshot,+ discover_github_token,+ parse_copilot_quota,+)++# ---------------------------------------------------------------------------+# CopilotQuotaCategory helpers+# ---------------------------------------------------------------------------+++class TestCopilotQuotaCategory:+ def test_used_computed_from_entitlement_and_remaining(self):+ cat = CopilotQuotaCategory(name="chat", entitlement=300, remaining=120)+ assert cat.used == 180++ def test_used_percent_computed(self):+ cat = CopilotQuotaCategory(name="chat", entitlement=100, remaining=25)+ assert cat.used_percent == pytest.approx(75.0)++ def test_used_percent_from_percent_remaining(self):+ cat = CopilotQuotaCategory(name="completions", percent_remaining=40.0)+ assert cat.used_percent == pytest.approx(60.0)++ def test_unlimited_used_percent_is_zero(self):+ cat = CopilotQuotaCategory(name="premium_interactions", unlimited=True)+ assert cat.used_percent == 0.0++ def test_used_none_when_entitlement_missing(self):+ cat = CopilotQuotaCategory(name="chat", remaining=50)+ assert cat.used is None++ def test_to_dict_keys(self):+ cat = CopilotQuotaCategory(+ name="chat",+ entitlement=100,+ remaining=60,+ percent_remaining=60.0,+ overage_count=2,+ overage_permitted=True,+ unlimited=False,+ timestamp_utc="2025-01-01T00:00:00Z",+ )+ d = cat.to_dict()+ assert d["name"] == "chat"+ assert d["entitlement"] == 100+ assert d["remaining"] == 60+ assert d["used"] == 40+ assert d["used_percent"] == pytest.approx(40.0)+ assert d["overage_count"] == 2+ assert d["overage_permitted"] is True+ assert d["unlimited"] is False++ def test_used_percent_clipped_at_zero(self):+ # percent_remaining > 100 should not produce negative used_percent+ cat = CopilotQuotaCategory(name="chat", percent_remaining=110.0)+ assert cat.used_percent == pytest.approx(0.0)+++# ---------------------------------------------------------------------------+# parse_copilot_quota+# ---------------------------------------------------------------------------+++_SAMPLE_RESPONSE = {+ "login": "octocat",+ "copilot_plan": "individual",+ "access_type_sku": "copilot_for_individuals",+ "quota_reset_date_utc": "2025-02-01",+ "quota_snapshots": {+ "chat": {+ "entitlement": 50,+ "remaining": 30,+ "quota_remaining": 30,+ "percent_remaining": 60.0,+ "overage_count": 0,+ "overage_permitted": False,+ "unlimited": False,+ "timestamp_utc": "2025-01-15T10:00:00Z",+ },+ "completions": {+ "entitlement": 2000,+ "remaining": 1500,+ "percent_remaining": 75.0,+ "overage_count": 0,+ "overage_permitted": True,+ "unlimited": False,+ "timestamp_utc": "2025-01-15T10:00:00Z",+ },+ "premium_interactions": {+ "entitlement": 300,+ "remaining": 298,+ "percent_remaining": 99.3,+ "overage_count": 2,+ "overage_permitted": True,+ "unlimited": False,+ "timestamp_utc": "2025-01-15T10:00:00Z",+ },+ },+}+++class TestParseCopilotQuota:+ def test_basic_fields(self):+ snap = parse_copilot_quota(_SAMPLE_RESPONSE)+ assert snap.login == "octocat"+ assert snap.copilot_plan == "individual"+ assert snap.access_type_sku == "copilot_for_individuals"+ assert snap.quota_reset_date_utc == "2025-02-01"++ def test_all_categories_parsed(self):+ snap = parse_copilot_quota(_SAMPLE_RESPONSE)+ assert set(snap.categories.keys()) == {"chat", "completions", "premium_interactions"}++ def test_chat_category(self):+ snap = parse_copilot_quota(_SAMPLE_RESPONSE)+ chat = snap.categories["chat"]+ assert chat.entitlement == 50+ assert chat.remaining == 30+ assert chat.percent_remaining == pytest.approx(60.0)+ assert chat.unlimited is False+ assert chat.overage_count == 0++ def test_premium_interactions_overage(self):+ snap = parse_copilot_quota(_SAMPLE_RESPONSE)+ prem = snap.categories["premium_interactions"]+ assert prem.overage_count == 2+ assert prem.overage_permitted is True++ def test_quota_remaining_alias(self):+ """quota_remaining should be used when remaining is absent."""+ data = {+ "quota_snapshots": {+ "chat": {+ "entitlement": 100,+ "quota_remaining": 75,+ }+ }+ }+ snap = parse_copilot_quota(data)+ assert snap.categories["chat"].remaining == 75++ def test_unlimited_category(self):+ data = {+ "quota_snapshots": {+ "completions": {"unlimited": True}+ }+ }+ snap = parse_copilot_quota(data)+ assert snap.categories["completions"].unlimited is True++ def test_empty_quota_snapshots(self):+ snap = parse_copilot_quota({"login": "ghost"})+ assert snap.login == "ghost"+ assert snap.categories == {}++ def test_quota_reset_date_fallback(self):+ data = {"quota_reset_date": "2025-03-01"}+ snap = parse_copilot_quota(data)+ assert snap.quota_reset_date_utc == "2025-03-01"++ def test_fetched_at_is_recent(self):+ before = time.time()+ snap = parse_copilot_quota({})+ after = time.time()+ assert before <= snap.fetched_at <= after++ def test_to_dict_structure(self):+ snap = parse_copilot_quota(_SAMPLE_RESPONSE)+ d = snap.to_dict()+ assert "login" in d+ assert "categories" in d+ assert "chat" in d["categories"]+ assert "used_percent" in d["categories"]["chat"]++ def test_missing_categories_skipped(self):+ data = {+ "quota_snapshots": {+ "chat": {"remaining": 10},+ # completions and premium_interactions absent+ }+ }+ snap = parse_copilot_quota(data)+ assert "chat" in snap.categories+ assert "completions" not in snap.categories+ assert "premium_interactions" not in snap.categories++ def test_free_plan(self):+ data = {"copilot_plan": "free", "quota_snapshots": {}}+ snap = parse_copilot_quota(data)+ assert snap.copilot_plan == "free"+++# ---------------------------------------------------------------------------+# discover_github_token+# ---------------------------------------------------------------------------+++class TestDiscoverGithubToken:+ def test_returns_none_when_no_env_vars(self, monkeypatch):+ for var in ["GITHUB_COPILOT_GITHUB_TOKEN", "GITHUB_TOKEN", "COPILOT_GITHUB_TOKEN", "GITHUB_COPILOT_API_TOKEN"]:+ monkeypatch.delenv(var, raising=False)+ assert discover_github_token() is None++ def test_picks_up_github_token(self, monkeypatch):+ for var in ["GITHUB_COPILOT_GITHUB_TOKEN", "GITHUB_TOKEN", "COPILOT_GITHUB_TOKEN", "GITHUB_COPILOT_API_TOKEN"]:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("GITHUB_TOKEN", "ghp_testtoken123")+ assert discover_github_token() == "ghp_testtoken123"++ def test_prefers_copilot_specific_token(self, monkeypatch):+ for var in ["GITHUB_COPILOT_GITHUB_TOKEN", "GITHUB_TOKEN", "COPILOT_GITHUB_TOKEN", "GITHUB_COPILOT_API_TOKEN"]:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("GITHUB_COPILOT_GITHUB_TOKEN", "ghp_copilot_specific")+ monkeypatch.setenv("GITHUB_TOKEN", "ghp_generic")+ assert discover_github_token() == "ghp_copilot_specific"++ def test_falls_through_to_next_env_var(self, monkeypatch):+ for var in ["GITHUB_COPILOT_GITHUB_TOKEN", "GITHUB_TOKEN", "COPILOT_GITHUB_TOKEN", "GITHUB_COPILOT_API_TOKEN"]:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("COPILOT_GITHUB_TOKEN", "ghp_copilot")+ assert discover_github_token() == "ghp_copilot"++ def test_ignores_empty_strings(self, monkeypatch):+ for var in ["GITHUB_COPILOT_GITHUB_TOKEN", "GITHUB_TOKEN", "COPILOT_GITHUB_TOKEN", "GITHUB_COPILOT_API_TOKEN"]:+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("GITHUB_COPILOT_GITHUB_TOKEN", "")+ monkeypatch.setenv("GITHUB_TOKEN", "ghp_valid")+ assert discover_github_token() == "ghp_valid"+++# ---------------------------------------------------------------------------+# CopilotQuotaSnapshot.to_dict+# ---------------------------------------------------------------------------+++class TestCopilotQuotaSnapshot:+ def test_to_dict_complete(self):+ snap = CopilotQuotaSnapshot(+ login="user1",+ copilot_plan="business",+ access_type_sku="copilot_enterprise",+ quota_reset_date_utc="2025-02-01",+ )+ snap.categories["chat"] = CopilotQuotaCategory(name="chat", entitlement=50, remaining=25)+ d = snap.to_dict()+ assert d["login"] == "user1"+ assert d["copilot_plan"] == "business"+ assert "chat" in d["categories"]+ assert d["categories"]["chat"]["entitlement"] == 50