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
fix(copilot): refresh wrapped subscription tokens (#2156) (#2182)
Rod Boev4364eb8dc4a1
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex e91cf885f..5dd182fbe 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -138,6 +138,17 @@ from headroom.proxy.project_context import with_project_prefix as _with_project_from .main import main+_COPILOT_PROXY_SEED_ENV_VARS = (+ "GITHUB_COPILOT_API_TOKEN",+ "GITHUB_COPILOT_REFRESH_OAUTH_TOKEN",+ "GITHUB_COPILOT_API_TOKEN_EXPIRES_AT",+)+++def _scrub_copilot_proxy_seed_env(env: dict[str, str]) -> None:+ for key in _COPILOT_PROXY_SEED_ENV_VARS:+ env.pop(key, None)+def _read_text(path: Path) -> str:"""Read a text file as UTF-8, falling back to the system locale encoding."""@@ -435,6 +446,8 @@ def _start_proxy(vertex_api_url: str | None = None,clear_vertex_api_url: bool = False,copilot_api_token: str | None = None,+ copilot_refresh_oauth_token: str | None = None,+ copilot_api_token_expires_at: float | None = None,) -> subprocess.Popen:"""Start Headroom proxy as a background subprocess.@@ -494,6 +507,7 @@ def _start_proxy(# Ensure proxy subprocess uses UTF-8 (Windows defaults to cp1252)proxy_env = os.environ.copy()+ _scrub_copilot_proxy_seed_env(proxy_env)proxy_env["PYTHONIOENCODING"] = "utf-8"# Vertex AI RST_STREAMs HTTP/2 connections (error_code:2). Force HTTP/1.1# when wrapping a Vertex-mode client so upstream requests succeed.@@ -522,6 +536,10 @@ def _start_proxy(proxy_env["GITHUB_COPILOT_API_TOKEN"] = copilot_api_tokenif openai_api_url:proxy_env["GITHUB_COPILOT_API_URL"] = openai_api_url+ if copilot_refresh_oauth_token:+ proxy_env["GITHUB_COPILOT_REFRESH_OAUTH_TOKEN"] = copilot_refresh_oauth_token+ if copilot_api_token_expires_at is not None:+ proxy_env["GITHUB_COPILOT_API_TOKEN_EXPIRES_AT"] = str(copilot_api_token_expires_at)# Detach the proxy from the launching console on Windows so an ungraceful# close of the owning agent (closing the terminal window, taskkill, or a@@ -3005,9 +3023,14 @@ def _ensure_proxy(vertex_api_url: str | None = None,clear_vertex_api_url: bool = False,copilot_api_token: str | None = None,+ copilot_refresh_oauth_token: str | None = None,+ copilot_api_token_expires_at: float | None = None,) -> tuple[subprocess.Popen | None, int]:"""Start or verify proxy. Returns (process_handle, actual_port)."""helpers = _live_wrap_module()+ copilot_subscription_seed_requested = bool(copilot_refresh_oauth_token) or (+ copilot_api_token_expires_at is not None+ )# --no-proxy reuses an already-running proxy, so backend/region/provider# flags (which only apply when we start one) would be silently dropped.if no_proxy and (backend or anyllm_provider or region):@@ -3017,7 +3040,15 @@ def _ensure_proxy()if not no_proxy:manifest = helpers._find_persistent_manifest(port)- if manifest is not None:+ isolated_copilot_subscription_proxy = copilot_subscription_seed_requested and (+ manifest is not None or helpers._check_proxy(port)+ )+ if isolated_copilot_subscription_proxy:+ click.echo(+ " Copilot subscription refresh seeds are session-specific; "+ "starting a dedicated local proxy instance for this wrap session."+ )+ if not isolated_copilot_subscription_proxy and manifest is not None:from headroom.install.health import probe_readyif probe_ready(manifest.health_url):@@ -3062,6 +3093,8 @@ def _ensure_proxy(missing.append("learn")if code_graph and not running_config.get("code_graph"):missing.append("code_graph")+ if copilot_subscription_seed_requested:+ missing.append("copilot-subscription-auth")if openai_api_url:running_openai_url = _normalize_proxy_api_url(running_config.get("openai_api_url")@@ -3082,7 +3115,15 @@ def _ensure_proxy(# the shared running-proxy checks below so mismatch-driven# restart logic can run. For plain recover-only calls,# preserve the historical fast return.- if not any((memory, learn, code_graph, openai_api_url)):+ if not any(+ (+ memory,+ learn,+ code_graph,+ openai_api_url,+ copilot_subscription_seed_requested,+ )+ ):return None, portif not helpers._check_proxy(port):return None, port@@ -3116,6 +3157,8 @@ def _ensure_proxy(missing.append("learn")if code_graph and not running_config.get("code_graph"):missing.append("code-graph")+ if copilot_subscription_seed_requested:+ missing.append("copilot-subscription-auth")if openai_api_url:running_openai_url = _normalize_proxy_api_url(running_config.get("openai_api_url")@@ -3146,7 +3189,7 @@ def _ensure_proxy("is stale; starting a fresh proxy instead.")- if helpers._check_proxy(port):+ if not isolated_copilot_subscription_proxy and helpers._check_proxy(port):# Proxy is running — check if it has the features we needneeds_restart = Falsehealth_payload = helpers._query_proxy_health(port)@@ -3203,6 +3246,8 @@ def _ensure_proxy(missing.append("learn")if code_graph and not running_config.get("code_graph"):missing.append("code_graph")+ if copilot_subscription_seed_requested:+ missing.append("copilot-subscription-auth")expected_savings_profile = helpers._wrap_agent_savings_profile(agent_type)if (expected_savings_profile is not None@@ -3274,17 +3319,26 @@ def _ensure_proxy(click.echo(f" Dashboard: http://127.0.0.1:{port}/dashboard")return None, port- # Start (or restart) the proxy with the requested flags- # Find an available port (port may be busy from a stale proxy).+ # Start (or restart) the proxy with the requested flags.+ # Subscription-seeded sessions must not claim the shared port even if+ # it is momentarily free; the persistent install or shared proxy still+ # owns that slot semantically.+ port_search_start = port + 1 if isolated_copilot_subscription_proxy else porttry:- actual_port = helpers._find_available_port(port)+ actual_port = helpers._find_available_port(port_search_start)except OSError as e:raise click.ClickException(f"Port {port} is unavailable: {e}") from eexcept RuntimeError as e:raise click.ClickException(str(e)) from eif actual_port != port:- click.echo(f" Port {port} is in use, using port {actual_port} instead.")+ if isolated_copilot_subscription_proxy:+ click.echo(+ f" Port {port} is reserved for the shared proxy; "+ f"using port {actual_port} for this dedicated session instead."+ )+ else:+ click.echo(f" Port {port} is in use, using port {actual_port} instead.")click.echo(f" Starting Headroom proxy on port {actual_port}...")try:@@ -3304,6 +3358,8 @@ def _ensure_proxy(vertex_api_url=vertex_api_url,clear_vertex_api_url=clear_vertex_api_url,copilot_api_token=copilot_api_token,+ copilot_refresh_oauth_token=copilot_refresh_oauth_token,+ copilot_api_token_expires_at=copilot_api_token_expires_at,),)click.echo(f" Proxy ready on http://127.0.0.1:{actual_port}")@@ -3516,6 +3572,8 @@ def _launch_tool(region: str | None = None,openai_api_url: str | None = None,copilot_api_token: str | None = None,+ copilot_refresh_oauth_token: str | None = None,+ copilot_api_token_expires_at: float | None = None,) -> None:"""Common logic: start proxy, launch tool, clean up."""proxy_holder: list[subprocess.Popen | None] = [None]@@ -3545,6 +3603,8 @@ def _launch_tool(region=region,openai_api_url=openai_api_url,copilot_api_token=copilot_api_token,+ copilot_refresh_oauth_token=copilot_refresh_oauth_token,+ copilot_api_token_expires_at=copilot_api_token_expires_at,)if actual_port != port:_unregister_proxy_client(port)@@ -4458,8 +4518,11 @@ def copilot(_inject_rtk_instructions(copilot_instructions, verbose=verbose)env = os.environ.copy()+ _scrub_copilot_proxy_seed_env(env)openai_api_url: str | None = Nonecopilot_proxy_token: str | None = None+ copilot_refresh_oauth_token: str | None = None+ copilot_api_token_expires_at: float | None = Nonesubscription_resolution = Noneif _should_use_copilot_oauth(backend=effective_backend,@@ -4521,6 +4584,9 @@ def copilot(# os.environ — keeps the token off shared state and out of unrelated# code paths.copilot_proxy_token = client_bearer+ if subscription_resolution is not None:+ copilot_refresh_oauth_token = subscription_resolution.refresh_oauth_token+ copilot_api_token_expires_at = subscription_resolution.api_token_expires_atenv_vars_display = ["COPILOT_PROVIDER_TYPE=openai",f"COPILOT_PROVIDER_BASE_URL={env['COPILOT_PROVIDER_BASE_URL']}",@@ -4603,6 +4669,8 @@ def copilot(region=region,openai_api_url=openai_api_url,copilot_api_token=copilot_proxy_token,+ copilot_refresh_oauth_token=copilot_refresh_oauth_token,+ copilot_api_token_expires_at=copilot_api_token_expires_at,)diff --git a/headroom/copilot_auth.py b/headroom/copilot_auth.pyindex aa1d0edd9..442cd3985 100644--- a/headroom/copilot_auth.py+++ b/headroom/copilot_auth.py@@ -7,6 +7,7 @@ import ctypesimport hashlibimport jsonimport logging+import mathimport osimport timefrom ctypes import wintypes@@ -41,6 +42,8 @@ _API_TOKEN_ENV_VARS = ("GITHUB_COPILOT_API_TOKEN","COPILOT_PROVIDER_BEARER_TOKEN",)+_REFRESH_OAUTH_TOKEN_ENV_VAR = "GITHUB_COPILOT_REFRESH_OAUTH_TOKEN"+_API_TOKEN_EXPIRES_AT_ENV_VAR = "GITHUB_COPILOT_API_TOKEN_EXPIRES_AT"_COPILOT_OAUTH_TOKEN_ENV_VARS = ("GITHUB_COPILOT_GITHUB_TOKEN","GITHUB_COPILOT_TOKEN",@@ -94,6 +97,8 @@ class CopilotSubscriptionTokenResolution:confidence: strapi_url: strtoken_fingerprint: str+ refresh_oauth_token: str | None = None+ api_token_expires_at: float | None = Nonedef token_fingerprint(token: str) -> str:@@ -369,6 +374,8 @@ def _parse_expiry(value: Any) -> float | None:if isinstance(value, int | float):number = float(value)+ if not math.isfinite(number):+ return Noneif number > 10_000_000_000:return number / 1000.0return number@@ -379,6 +386,10 @@ def _parse_expiry(value: Any) -> float | None:return Noneif raw.isdigit():return _parse_expiry(int(raw))+ try:+ return _parse_expiry(float(raw))+ except ValueError:+ passtry:normalized = raw.replace("Z", "+00:00")return datetime.fromisoformat(normalized).timestamp()@@ -795,6 +806,8 @@ def _subscription_resolution(source: str,confidence: str,api_url: str,+ refresh_oauth_token: str | None = None,+ api_token_expires_at: float | None = None,) -> CopilotSubscriptionTokenResolution:return CopilotSubscriptionTokenResolution(token=token,@@ -802,6 +815,8 @@ def _subscription_resolution(confidence=confidence,api_url=api_url,token_fingerprint=token_fingerprint(token),+ refresh_oauth_token=refresh_oauth_token,+ api_token_expires_at=api_token_expires_at,)@@ -833,6 +848,8 @@ def _subscription_resolution_from_token_exchange(source=f"{candidate.source}:token-exchange",confidence="copilot-token-exchange",api_url=_api_url_from_exchange_payload(payload, oauth_token=candidate.token),+ refresh_oauth_token=candidate.token,+ api_token_expires_at=_parse_expiry(payload.get("expires_at")),)@@ -990,7 +1007,8 @@ class CopilotTokenProvider:async def get_api_token(self) -> CopilotAPIToken:explicit_api_token = os.environ.get("GITHUB_COPILOT_API_TOKEN", "").strip()- if explicit_api_token:+ refresh_oauth_token = os.environ.get(_REFRESH_OAUTH_TOKEN_ENV_VAR, "").strip()+ if explicit_api_token and not refresh_oauth_token:return CopilotAPIToken(token=explicit_api_token,expires_at=time.time() + 3600,@@ -1006,6 +1024,21 @@ class CopilotTokenProvider:if cached is not None and cached.is_valid:return cached+ if explicit_api_token and refresh_oauth_token:+ if cached is None:+ seeded_expires_at = _parse_expiry(os.environ.get(_API_TOKEN_EXPIRES_AT_ENV_VAR))+ seeded = CopilotAPIToken(+ token=explicit_api_token,+ expires_at=seeded_expires_at if seeded_expires_at is not None else 0.0,+ api_url=_configured_api_url(),+ )+ self._cached = seeded+ if seeded.is_valid:+ return seeded+ exchanged = await self._exchange_token(refresh_oauth_token)+ self._cached = exchanged+ return exchanged+oauth_token = read_cached_oauth_token()if not oauth_token:raise RuntimeError("No GitHub Copilot OAuth token is available.")@@ -1142,6 +1175,20 @@ def _token_kind(token: str) -> str:return "unknown" if t else "empty"+def _is_managed_copilot_seeded_bearer(token: str) -> bool:+ """Return True when the incoming bearer is the proxy's seeded wrapper token."""++ refresh_oauth_token = os.environ.get(_REFRESH_OAUTH_TOKEN_ENV_VAR, "").strip()+ explicit_api_token = os.environ.get("GITHUB_COPILOT_API_TOKEN", "").strip()+ normalized = token.strip()+ return bool(+ refresh_oauth_token+ and explicit_api_token+ and normalized+ and normalized == explicit_api_token+ )++async def apply_copilot_api_auth(headers: dict[str, str], *, url: str) -> dict[str, str]:"""Apply Copilot auth headers for GitHub Copilot API requests."""resolved = dict(headers)@@ -1159,14 +1206,20 @@ async def apply_copilot_api_auth(headers: dict[str, str], *, url: str) -> dict[sand raw_tokenand _is_forwardable_copilot_bearer_token(raw_token)):- logger.info(- "apply_copilot_api_auth: passing through client token kind=%s",- _token_kind(raw_token),- )- for key in list(resolved):- if key.lower() == "x-api-key":- resolved.pop(key)- return resolved+ if _is_managed_copilot_seeded_bearer(raw_token):+ logger.info(+ "apply_copilot_api_auth: managed seed token kind=%s, will replace",+ _token_kind(raw_token),+ )+ else:+ logger.info(+ "apply_copilot_api_auth: passing through client token kind=%s",+ _token_kind(raw_token),+ )+ for key in list(resolved):+ if key.lower() == "x-api-key":+ resolved.pop(key)+ return resolvedlogger.info("apply_copilot_api_auth: incoming token not suitable (kind=%s), will replace",_token_kind(raw_token) if raw_token else "none",diff --git a/tests/test_cli/test_wrap_copilot.py b/tests/test_cli/test_wrap_copilot.pyindex a99794d13..033d37d73 100644--- a/tests/test_cli/test_wrap_copilot.py+++ b/tests/test_cli/test_wrap_copilot.py@@ -3,7 +3,6 @@from __future__ import annotationsimport importlib-import osimport sysimport typesfrom pathlib import Path@@ -33,6 +32,8 @@ def _subscription_resolution(api_url: str = DEFAULT_API_URL,source: str = "headroom-copilot-auth:/tmp/copilot_auth.json:token-exchange",confidence: str = "copilot-token-exchange",+ refresh_oauth_token: str | None = None,+ api_token_expires_at: float | None = None,) -> CopilotSubscriptionTokenResolution:return CopilotSubscriptionTokenResolution(token=token,@@ -40,6 +41,8 @@ def _subscription_resolution(confidence=confidence,api_url=api_url,token_fingerprint="sha256:0123456789ab",+ refresh_oauth_token=refresh_oauth_token,+ api_token_expires_at=api_token_expires_at,)@@ -287,6 +290,9 @@ def test_wrap_copilot_subscription_uses_github_auth_without_provider_key(_wrap_cli, main = wrap_modulesfor var in ("COPILOT_PROVIDER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"):monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "stale-parent-token")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "stale-parent-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", "1")captured: dict[str, object] = {}def fake_launch_tool(**kwargs): # noqa: ANN003@@ -463,12 +469,25 @@ def test_wrap_copilot_subscription_pins_validated_token_for_proxy(patch("headroom.cli.wrap.shutil.which", return_value="copilot"),patch("headroom.cli.wrap.resolve_subscription_bearer_token_details",- return_value=_subscription_resolution("gho-validated", api_url=business_api),+ return_value=_subscription_resolution(+ "gho-validated",+ api_url=business_api,+ refresh_oauth_token="gho-refresh",+ api_token_expires_at=1234567890.0,+ ),),patch("headroom.cli.wrap.has_oauth_auth", return_value=False),patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool),):- result = runner.invoke(main, ["wrap", "copilot", "--subscription", "--no-rtk"])+ result = runner.invoke(+ main,+ ["wrap", "copilot", "--subscription", "--no-rtk"],+ env={+ "GITHUB_COPILOT_API_TOKEN": "stale-parent-token",+ "GITHUB_COPILOT_REFRESH_OAUTH_TOKEN": "stale-parent-refresh",+ "GITHUB_COPILOT_API_TOKEN_EXPIRES_AT": "1",+ },+ )assert result.exit_code == 0, result.outputenv = captured["env"]@@ -476,8 +495,11 @@ def test_wrap_copilot_subscription_pins_validated_token_for_proxy(# The validated token is handed to the proxy as an explicit launch# argument — not via the child env, not via the parent's os.environ.assert captured["copilot_api_token"] == "gho-validated"+ assert captured["copilot_refresh_oauth_token"] == "gho-refresh"+ assert captured["copilot_api_token_expires_at"] == 1234567890.0assert "GITHUB_COPILOT_API_TOKEN" not in env- assert os.environ.get("GITHUB_COPILOT_API_TOKEN") is None+ assert "GITHUB_COPILOT_REFRESH_OAUTH_TOKEN" not in env+ assert "GITHUB_COPILOT_API_TOKEN_EXPIRES_AT" not in envassert env["COPILOT_PROVIDER_TYPE"] == "openai"assert env["COPILOT_PROVIDER_BEARER_TOKEN"] == "gho-validated"assert env["GITHUB_COPILOT_USE_TOKEN_EXCHANGE"] == "false"@@ -803,9 +825,12 @@ def _clear_copilot_env(monkeypatch: pytest.MonkeyPatch) -> None:"COPILOT_PROVIDER_BEARER_TOKEN","OPENAI_API_KEY","ANTHROPIC_API_KEY",+ "GITHUB_COPILOT_API_TOKEN","GITHUB_COPILOT_API_URL",+ "GITHUB_COPILOT_API_TOKEN_EXPIRES_AT","GITHUB_COPILOT_ENTERPRISE_URL","GITHUB_COPILOT_ENTERPRISE_DOMAIN",+ "GITHUB_COPILOT_REFRESH_OAUTH_TOKEN","GITHUB_COPILOT_TOKEN","GITHUB_COPILOT_GITHUB_TOKEN","COPILOT_MODEL",diff --git a/tests/test_cli/test_wrap_persistent.py b/tests/test_cli/test_wrap_persistent.pyindex 648386cab..6f242f03e 100644--- a/tests/test_cli/test_wrap_persistent.py+++ b/tests/test_cli/test_wrap_persistent.py@@ -374,6 +374,97 @@ def test_ensure_proxy_restarts_ephemeral_proxy_for_openai_api_url_mismatch(monkeassert calls[1][2]["openai_api_url"] == "https://api.individual.githubcopilot.com"+def test_ensure_proxy_starts_isolated_ephemeral_proxy_for_copilot_subscription_seed(+ monkeypatch,+) -> None:+ calls: list[object] = []++ monkeypatch.setattr(wrap_cli, "_find_persistent_manifest", lambda port: None)+ monkeypatch.setattr(wrap_cli, "_check_proxy", lambda port: port == 8787)+ monkeypatch.setattr(+ wrap_cli,+ "_find_available_port",+ lambda start_port, **kw: calls.append(("find_port", start_port)) or 8788,+ )+ monkeypatch.setattr(+ wrap_cli,+ "_kill_proxy_by_pid",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ AssertionError("subscription-seeded session should not restart the shared proxy")+ ),+ )+ monkeypatch.setattr(+ wrap_cli,+ "_start_proxy",+ lambda *args, **kwargs: calls.append(("start", args, kwargs)),+ )++ proc, actual_port = wrap_cli._ensure_proxy(+ 8787,+ False,+ copilot_api_token="tid-session-token",+ copilot_refresh_oauth_token="gho-refresh",+ copilot_api_token_expires_at=456.5,+ )++ assert proc is None+ assert actual_port == 8788+ assert calls[0] == ("find_port", 8788)+ assert calls[1][0] == "start"+ assert calls[1][1][0] == 8788+ assert calls[1][2]["copilot_api_token"] == "tid-session-token"+ assert calls[1][2]["copilot_refresh_oauth_token"] == "gho-refresh"+ assert calls[1][2]["copilot_api_token_expires_at"] == 456.5+++def test_ensure_proxy_starts_isolated_ephemeral_proxy_when_subscription_seed_targets_persistent_port(+ monkeypatch,+) -> None:+ calls: list[object] = []++ monkeypatch.setattr(wrap_cli, "_find_persistent_manifest", lambda port: _Manifest())+ monkeypatch.setattr(+ "headroom.install.health.probe_ready",+ lambda url: (_ for _ in ()).throw(+ AssertionError("subscription-seeded session should skip persistent probing")+ ),+ )+ monkeypatch.setattr(+ wrap_cli,+ "_restart_persistent_proxy",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ AssertionError("subscription-seeded session should not restart the persistent proxy")+ ),+ )+ monkeypatch.setattr(+ wrap_cli,+ "_find_available_port",+ lambda start_port, **kw: calls.append(("find_port", start_port)) or 8788,+ )+ monkeypatch.setattr(+ wrap_cli,+ "_start_proxy",+ lambda *args, **kwargs: calls.append(("start", args, kwargs)),+ )++ proc, actual_port = wrap_cli._ensure_proxy(+ 8787,+ False,+ copilot_api_token="tid-session-token",+ copilot_refresh_oauth_token="gho-refresh",+ copilot_api_token_expires_at=456.5,+ )++ assert proc is None+ assert actual_port == 8788+ assert calls[0] == ("find_port", 8788)+ assert calls[1][0] == "start"+ assert calls[1][1][0] == 8788+ assert calls[1][2]["copilot_api_token"] == "tid-session-token"+ assert calls[1][2]["copilot_refresh_oauth_token"] == "gho-refresh"+ assert calls[1][2]["copilot_api_token_expires_at"] == 456.5++def test_ensure_proxy_reuses_agent_proxy_without_savings_profile(monkeypatch) -> None:health = {"version": wrap_cli._HEADROOM_VERSION,diff --git a/tests/test_cli_proxy_env.py b/tests/test_cli_proxy_env.pyindex 8904c2e54..903166bfa 100644--- a/tests/test_cli_proxy_env.py+++ b/tests/test_cli_proxy_env.py@@ -106,6 +106,39 @@ class TestCLIWrapProxyTimeout:assert env["GITHUB_COPILOT_API_URL"] == "https://copilot-api.acme.ghe.com"assert env["GITHUB_COPILOT_API_TOKEN"] == "copilot-api-token"+ def test_start_proxy_scrubs_inherited_copilot_refresh_seed_env(self, monkeypatch, tmp_path):+ fake_proc = _FakeProxyProcess()+ captured: dict[str, object] = {}++ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "stale-parent-token")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "stale-parent-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", "123")+ monkeypatch.delenv(wrap_mod._WRAP_PROXY_TIMEOUT_ENV, raising=False)+ monkeypatch.setattr(wrap_mod, "_ml_wrap_extras_detected", lambda: False)+ monkeypatch.setattr(wrap_mod, "_get_log_path", lambda: tmp_path / "proxy.log")+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)+ monkeypatch.setattr(wrap_mod.time, "sleep", lambda _seconds: None)++ def fake_popen(*args, **kwargs): # noqa: ANN002, ANN003+ captured["kwargs"] = kwargs+ return fake_proc++ monkeypatch.setattr(wrap_mod.subprocess, "Popen", fake_popen)++ proc = wrap_mod._start_proxy(+ 8787,+ agent_type="copilot",+ copilot_api_token="copilot-api-token",+ copilot_refresh_oauth_token="gho-refresh",+ copilot_api_token_expires_at=456.5,+ )++ assert proc is fake_proc+ env = captured["kwargs"]["env"]+ assert env["GITHUB_COPILOT_API_TOKEN"] == "copilot-api-token"+ assert env["GITHUB_COPILOT_REFRESH_OAUTH_TOKEN"] == "gho-refresh"+ assert env["GITHUB_COPILOT_API_TOKEN_EXPIRES_AT"] == "456.5"+def test_start_proxy_redirects_subprocess_stdio_to_standalone_log(self, monkeypatch, tmp_path):fake_proc = _FakeProxyProcess()captured: dict[str, object] = {}diff --git a/tests/test_copilot_auth.py b/tests/test_copilot_auth.pyindex f766da4db..8412e44ad 100644--- a/tests/test_copilot_auth.py+++ b/tests/test_copilot_auth.py@@ -162,6 +162,8 @@ def test_resolve_subscription_bearer_token_details_exchanges_oauth_candidate(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.delenv("GITHUB_COPILOT_API_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", raising=False)monkeypatch.delenv("COPILOT_PROVIDER_BEARER_TOKEN", raising=False)monkeypatch.delenv("GITHUB_COPILOT_API_URL", raising=False)monkeypatch.delenv("GITHUB_COPILOT_ENTERPRISE_URL", raising=False)@@ -202,6 +204,8 @@ def test_resolve_subscription_bearer_token_details_exchanges_oauth_candidate(assert resolution.confidence == "copilot-token-exchange"assert resolution.api_url == "https://api.business.githubcopilot.com"assert resolution.token_fingerprint == copilot_auth.token_fingerprint("copilot-api")+ assert resolution.refresh_oauth_token == "gho-oauth"+ assert isinstance(resolution.api_token_expires_at, float)assert captured == {"Accept": "application/json","Authorization": "Bearer gho-oauth",@@ -677,6 +681,39 @@ def test_apply_copilot_api_auth_passes_through_existing_api_token(assert "x-api-key" not in headers+def test_apply_copilot_api_auth_replaces_managed_seeded_api_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def fake_get_api_token() -> copilot_auth.CopilotAPIToken:+ return copilot_auth.CopilotAPIToken(+ token="copilot-refreshed",+ expires_at=time.time() + 3600,+ api_url=copilot_auth.DEFAULT_API_URL,+ )++ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "tid_existing_copilot_token")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "gho-refresh")+ monkeypatch.setattr(+ copilot_auth.get_copilot_token_provider(),+ "get_api_token",+ fake_get_api_token,+ )++ headers = asyncio.run(+ copilot_auth.apply_copilot_api_auth(+ {+ "authorization": "Bearer tid_existing_copilot_token",+ "x-api-key": "sk-downstream",+ },+ url="https://api.githubcopilot.com/v1/chat/completions",+ )+ )++ assert headers["Authorization"] == "Bearer copilot-refreshed"+ assert "authorization" not in headers+ assert "x-api-key" not in headers++def test_apply_copilot_api_auth_passes_through_github_oauth_bearer(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -942,6 +979,8 @@ def test_token_provider_can_exchange_when_enabled(monkeypatch: pytest.MonkeyPatcdef test_token_provider_prefers_explicit_api_token(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-api")+ monkeypatch.delenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", raising=False)monkeypatch.setenv("GITHUB_COPILOT_API_URL", "https://api.githubcopilot.com")token = asyncio.run(copilot_auth.CopilotTokenProvider().get_api_token())@@ -952,6 +991,8 @@ def test_token_provider_prefers_explicit_api_token(monkeypatch: pytest.MonkeyPatdef test_token_provider_raises_without_oauth_token(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.delenv("GITHUB_COPILOT_API_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", raising=False)monkeypatch.setattr(copilot_auth, "read_cached_oauth_token", lambda: None)with pytest.raises(RuntimeError, match="No GitHub Copilot OAuth token"):@@ -972,6 +1013,145 @@ def test_exchange_token_raises_when_exchange_returns_empty_token(asyncio.run(provider._exchange_token("gho-oauth"))+def test_token_provider_refreshes_expired_seeded_explicit_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-expired")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "gho-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", str(time.time() - 120))+ monkeypatch.delenv("GITHUB_COPILOT_USE_TOKEN_EXCHANGE", raising=False)++ provider = copilot_auth.CopilotTokenProvider()+ calls = {"count": 0}+ captured: dict[str, str] = {}++ def fake_exchange(headers: dict[str, str]) -> dict[str, object]:+ calls["count"] += 1+ captured.update(headers)+ return {+ "token": "copilot-refreshed",+ "expires_at": int(time.time()) + 3600,+ "endpoints": {"api": "https://api.business.githubcopilot.com"},+ }++ monkeypatch.setattr(provider, "_exchange_token_sync", staticmethod(fake_exchange))++ token = asyncio.run(provider.get_api_token())++ assert token.token == "copilot-refreshed"+ assert captured["Authorization"] == "Bearer gho-refresh"+ assert calls["count"] == 1+++def test_token_provider_reuses_valid_seeded_explicit_token_without_exchange(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-valid")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "gho-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", str(time.time() + 3600))++ provider = copilot_auth.CopilotTokenProvider()+ calls = {"count": 0}++ def fake_exchange(_headers: dict[str, str]) -> dict[str, object]:+ calls["count"] += 1+ return {+ "token": "copilot-refreshed",+ "expires_at": int(time.time()) + 3600,+ "endpoints": {"api": "https://api.githubcopilot.com"},+ }++ monkeypatch.setattr(provider, "_exchange_token_sync", staticmethod(fake_exchange))++ first = asyncio.run(provider.get_api_token())+ second = asyncio.run(provider.get_api_token())++ assert first.token == "copilot-valid"+ assert second.token == "copilot-valid"+ assert calls["count"] == 0+++def test_token_provider_refreshes_seeded_token_when_expiry_is_nonfinite(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-expired")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "gho-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", "inf")++ provider = copilot_auth.CopilotTokenProvider()+ calls = {"count": 0}++ def fake_exchange(_headers: dict[str, str]) -> dict[str, object]:+ calls["count"] += 1+ return {+ "token": "copilot-refreshed",+ "expires_at": int(time.time()) + 3600,+ "endpoints": {"api": "https://api.githubcopilot.com"},+ }++ monkeypatch.setattr(provider, "_exchange_token_sync", staticmethod(fake_exchange))++ token = asyncio.run(provider.get_api_token())++ assert token.token == "copilot-refreshed"+ assert calls["count"] == 1+++def test_token_provider_refreshes_seeded_token_even_when_exchange_flag_is_false(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-expired")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "gho-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", str(time.time() - 120))+ monkeypatch.setenv("GITHUB_COPILOT_USE_TOKEN_EXCHANGE", "false")++ provider = copilot_auth.CopilotTokenProvider()+ calls = {"count": 0}++ def fake_exchange(_headers: dict[str, str]) -> dict[str, object]:+ calls["count"] += 1+ return {+ "token": "copilot-refreshed",+ "expires_at": int(time.time()) + 3600,+ "endpoints": {"api": "https://api.githubcopilot.com"},+ }++ monkeypatch.setattr(provider, "_exchange_token_sync", staticmethod(fake_exchange))++ token = asyncio.run(provider.get_api_token())++ assert token.token == "copilot-refreshed"+ assert calls["count"] == 1+++def test_token_provider_preserves_configured_api_url_when_refreshing_seeded_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-expired")+ monkeypatch.setenv("GITHUB_COPILOT_REFRESH_OAUTH_TOKEN", "gho-refresh")+ monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN_EXPIRES_AT", str(time.time() - 120))+ monkeypatch.setenv("GITHUB_COPILOT_API_URL", "https://proxy.internal.example.com")++ provider = copilot_auth.CopilotTokenProvider()++ monkeypatch.setattr(+ provider,+ "_exchange_token_sync",+ staticmethod(+ lambda _headers: {+ "token": "copilot-refreshed",+ "expires_at": int(time.time()) + 3600,+ "endpoints": {"api": "https://api.other.githubcopilot.com"},+ }+ ),+ )++ token = asyncio.run(provider.get_api_token())++ assert token.token == "copilot-refreshed"+ assert token.api_url == "https://proxy.internal.example.com"++def test_exchange_token_sync_raises_for_http_error(monkeypatch: pytest.MonkeyPatch) -> None:class DummyResponse:def read(self) -> bytes: