Skip to content

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.

fix: support live copilot oauth runtime

JerrettDavisd60cf7914c5c
diff --git a/headroom/copilot_auth.py b/headroom/copilot_auth.py
index d31f56e19..a4540bd00 100644
--- a/headroom/copilot_auth.py
+++ b/headroom/copilot_auth.py
@@ -3,10 +3,13 @@
from __future__ import annotations
import asyncio
+import ctypes
import json
import logging
import os
+import subprocess
import time
+from ctypes import wintypes
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
@@ -67,6 +70,11 @@ def _token_exchange_url() -> str:
return os.environ.get("GITHUB_COPILOT_TOKEN_EXCHANGE_URL", DEFAULT_TOKEN_EXCHANGE_URL).strip()
+def _should_exchange_oauth_token() -> bool:
+ raw = os.environ.get("GITHUB_COPILOT_USE_TOKEN_EXCHANGE", "").strip().lower()
+ return raw in {"1", "true", "yes", "on"}
+
+
def _resolve_token_file_paths() -> list[Path]:
override = os.environ.get("GITHUB_COPILOT_TOKEN_FILE", "").strip()
if override:
@@ -83,6 +91,104 @@ def _resolve_token_file_paths() -> list[Path]:
return paths
+def _read_gh_cli_oauth_token() -> str | None:
+ gh_bin = os.environ.get("GH_PATH", "").strip() or "gh"
+ command = [gh_bin, "auth", "token"]
+ host = _github_host()
+ if host and host != DEFAULT_GITHUB_HOST:
+ command.extend(["--hostname", host])
+
+ try:
+ result = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ )
+ except OSError as exc:
+ logger.debug("Unable to invoke GitHub CLI for Copilot auth discovery: %s", exc)
+ return None
+
+ if result.returncode != 0:
+ logger.debug("GitHub CLI auth token lookup failed with exit code %s", result.returncode)
+ return None
+
+ token = result.stdout.strip()
+ return token or None
+
+
+def _read_windows_copilot_cli_oauth_token() -> str | None:
+ if os.name != "nt":
+ return None
+
+ class FILETIME(ctypes.Structure):
+ _fields_ = [
+ ("dwLowDateTime", wintypes.DWORD),
+ ("dwHighDateTime", wintypes.DWORD),
+ ]
+
+ class CREDENTIAL(ctypes.Structure):
+ _fields_ = [
+ ("Flags", wintypes.DWORD),
+ ("Type", wintypes.DWORD),
+ ("TargetName", wintypes.LPWSTR),
+ ("Comment", wintypes.LPWSTR),
+ ("LastWritten", FILETIME),
+ ("CredentialBlobSize", wintypes.DWORD),
+ ("CredentialBlob", ctypes.POINTER(ctypes.c_ubyte)),
+ ("Persist", wintypes.DWORD),
+ ("AttributeCount", wintypes.DWORD),
+ ("Attributes", wintypes.LPVOID),
+ ("TargetAlias", wintypes.LPWSTR),
+ ("UserName", wintypes.LPWSTR),
+ ]
+
+ cred_ptr = ctypes.POINTER(CREDENTIAL)
+ credentials = ctypes.POINTER(cred_ptr)()
+ count = wintypes.DWORD()
+ advapi32 = ctypes.WinDLL("Advapi32.dll")
+ advapi32.CredEnumerateW.argtypes = [
+ wintypes.LPCWSTR,
+ wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD),
+ ctypes.POINTER(ctypes.POINTER(cred_ptr)),
+ ]
+ advapi32.CredEnumerateW.restype = wintypes.BOOL
+ advapi32.CredFree.argtypes = [wintypes.LPVOID]
+
+ try:
+ if not advapi32.CredEnumerateW(None, 0, ctypes.byref(count), ctypes.byref(credentials)):
+ return None
+ except OSError as exc:
+ logger.debug("Unable to enumerate Windows credentials for Copilot auth discovery: %s", exc)
+ return None
+
+ host = _github_host().lower()
+ service_prefixes = [f"copilot-cli/{host}:"]
+ if "://" not in host:
+ service_prefixes.append(f"copilot-cli/https://{host}:")
+
+ try:
+ for idx in range(count.value):
+ credential = credentials[idx].contents
+ target = (credential.TargetName or "").strip().lower()
+ if not any(target.startswith(prefix) for prefix in service_prefixes):
+ continue
+ if credential.CredentialBlobSize <= 0 or not credential.CredentialBlob:
+ continue
+ blob = ctypes.string_at(credential.CredentialBlob, credential.CredentialBlobSize)
+ token = blob.decode("utf-8", errors="replace").strip()
+ if token:
+ return token
+ finally:
+ if credentials:
+ advapi32.CredFree(credentials)
+
+ return None
+
+
def _parse_expiry(value: Any) -> float | None:
if value in (None, ""):
return None
@@ -157,6 +263,14 @@ def read_cached_oauth_token() -> str | None:
if token:
return token
+ windows_copilot_token = _read_windows_copilot_cli_oauth_token()
+ if windows_copilot_token:
+ return windows_copilot_token
+
+ gh_token = _read_gh_cli_oauth_token()
+ if gh_token:
+ return gh_token
+
host = _github_host()
for path in _resolve_token_file_paths():
try:
@@ -203,6 +317,16 @@ def is_copilot_api_url(url: str | None) -> bool:
return "githubcopilot.com" in host
+def build_copilot_upstream_url(base_url: str, path: str) -> str:
+ """Build an upstream URL, normalizing GitHub Copilot's non-/v1 path layout."""
+
+ normalized_base = base_url.rstrip("/")
+ normalized_path = path if path.startswith("/") else f"/{path}"
+ if is_copilot_api_url(normalized_base) and normalized_path.startswith("/v1/"):
+ normalized_path = normalized_path[3:]
+ return f"{normalized_base}{normalized_path}"
+
+
class CopilotTokenProvider:
"""Resolve and cache short-lived Copilot API tokens."""
@@ -233,6 +357,16 @@ class CopilotTokenProvider:
if not oauth_token:
raise RuntimeError("No GitHub Copilot OAuth token is available.")
+ if not _should_exchange_oauth_token():
+ direct_token = CopilotAPIToken(
+ token=oauth_token,
+ expires_at=time.time() + 3600,
+ api_url=os.environ.get("GITHUB_COPILOT_API_URL", DEFAULT_API_URL).strip()
+ or DEFAULT_API_URL,
+ )
+ self._cached = direct_token
+ return direct_token
+
exchanged = await self._exchange_token(oauth_token)
self._cached = exchanged
return exchanged
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index e80dbc5de..7cbb0dd30 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -31,7 +31,7 @@ if TYPE_CHECKING:
import httpx
-from headroom.copilot_auth import apply_copilot_api_auth
+from headroom.copilot_auth import apply_copilot_api_auth, build_copilot_upstream_url
logger = logging.getLogger("headroom.proxy")
@@ -558,7 +558,7 @@ class OpenAIHandlerMixin:
)
# Direct OpenAI API (no backend configured)
- url = f"{self.OPENAI_API_URL}/v1/chat/completions"
+ url = build_copilot_upstream_url(self.OPENAI_API_URL, "/v1/chat/completions")
try:
if stream:
@@ -1075,7 +1075,7 @@ class OpenAIHandlerMixin:
if is_chatgpt_auth:
url = "https://chatgpt.com/backend-api/codex/responses"
else:
- url = f"{self.OPENAI_API_URL}/v1/responses"
+ url = build_copilot_upstream_url(self.OPENAI_API_URL, "/v1/responses")
try:
if stream:
@@ -1354,7 +1354,7 @@ class OpenAIHandlerMixin:
# API key auth → route to configured OpenAI API URL
base = self.OPENAI_API_URL
ws_base = base.replace("https://", "wss://").replace("http://", "ws://")
- upstream_url = f"{ws_base}/v1/responses"
+ upstream_url = build_copilot_upstream_url(ws_base, "/v1/responses")
# Unit 3: attach the resolved upstream URL to the session handle.
if session_handle is not None:
@@ -2163,7 +2163,7 @@ class OpenAIHandlerMixin:
if "chatgpt-account-id" in _lower:
http_url = "https://chatgpt.com/backend-api/codex/responses"
else:
- http_url = f"{self.OPENAI_API_URL}/v1/responses"
+ http_url = build_copilot_upstream_url(self.OPENAI_API_URL, "/v1/responses")
# Build HTTP body from the WS response.create payload.
# WS messages use {"type": "response.create", "response": {...}} wrapper.
@@ -2457,7 +2457,7 @@ class OpenAIHandlerMixin:
start_time = time.time()
path = request.url.path
- url = f"{base_url}{path}"
+ url = build_copilot_upstream_url(base_url, path)
# Preserve query string parameters
if request.url.query:
diff --git a/tests/test_cli/test_wrap_copilot.py b/tests/test_cli/test_wrap_copilot.py
index dc8bafbab..29105f437 100644
--- a/tests/test_cli/test_wrap_copilot.py
+++ b/tests/test_cli/test_wrap_copilot.py
@@ -44,13 +44,16 @@ def test_wrap_copilot_auto_anthropic_injects_instructions(
def fake_launch_tool(**kwargs): # noqa: ANN003
captured.update(kwargs)
- with patch("headroom.cli.wrap.shutil.which", return_value="copilot"):
- with patch("headroom.cli.wrap._ensure_rtk_binary", return_value=Path("/tmp/rtk")):
- with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool):
- result = runner.invoke(
- main,
- ["wrap", "copilot", "--", "--model", "claude-sonnet-4-20250514"],
- )
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="copilot"),
+ patch("headroom.cli.wrap.has_oauth_auth", return_value=False),
+ patch("headroom.cli.wrap._ensure_rtk_binary", return_value=Path("/tmp/rtk")),
+ patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool),
+ ):
+ result = runner.invoke(
+ main,
+ ["wrap", "copilot", "--", "--model", "claude-sonnet-4-20250514"],
+ )
assert result.exit_code == 0, result.output
instructions = tmp_path / ".github" / "copilot-instructions.md"
@@ -78,25 +81,28 @@ def test_wrap_copilot_openai_backend_sets_completions_env(
def fake_launch_tool(**kwargs): # noqa: ANN003
captured.update(kwargs)
- with patch("headroom.cli.wrap.shutil.which", return_value="copilot"):
- with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool):
- result = runner.invoke(
- main,
- [
- "wrap",
- "copilot",
- "--no-rtk",
- "--backend",
- "anyllm",
- "--anyllm-provider",
- "groq",
- "--region",
- "us-central1",
- "--",
- "--model",
- "gpt-4o",
- ],
- )
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="copilot"),
+ 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",
+ "--no-rtk",
+ "--backend",
+ "anyllm",
+ "--anyllm-provider",
+ "groq",
+ "--region",
+ "us-central1",
+ "--",
+ "--model",
+ "gpt-4o",
+ ],
+ )
assert result.exit_code == 0, result.output
@@ -120,14 +126,17 @@ def test_wrap_copilot_auto_detects_running_proxy_backend(
def fake_launch_tool(**kwargs): # noqa: ANN003
captured.update(kwargs)
- with patch("headroom.cli.wrap.shutil.which", return_value="copilot"):
- with patch("headroom.cli.wrap._check_proxy", return_value=True):
- with patch("headroom.cli.wrap._detect_running_proxy_backend", return_value="anyllm"):
- with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool):
- result = runner.invoke(
- main,
- ["wrap", "copilot", "--no-rtk", "--", "--model", "gpt-4o"],
- )
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="copilot"),
+ patch("headroom.cli.wrap.has_oauth_auth", return_value=False),
+ patch("headroom.cli.wrap._check_proxy", return_value=True),
+ patch("headroom.cli.wrap._detect_running_proxy_backend", return_value="anyllm"),
+ patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool),
+ ):
+ result = runner.invoke(
+ main,
+ ["wrap", "copilot", "--no-rtk", "--", "--model", "gpt-4o"],
+ )
assert result.exit_code == 0, result.output
env = captured["env"]
@@ -237,16 +246,19 @@ def test_wrap_copilot_clears_stale_wire_api_in_anthropic_mode(
def fake_launch_tool(**kwargs): # noqa: ANN003
captured.update(kwargs)
- with patch("headroom.cli.wrap.shutil.which", return_value="copilot"):
- with patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool):
- result = runner.invoke(
- main,
- ["wrap", "copilot", "--no-rtk", "--", "--model", "claude-sonnet-4-20250514"],
- env={
- "COPILOT_PROVIDER_WIRE_API": "responses",
- "ANTHROPIC_API_KEY": "sk-test-dummy",
- },
- )
+ with (
+ patch("headroom.cli.wrap.shutil.which", return_value="copilot"),
+ 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", "--no-rtk", "--", "--model", "claude-sonnet-4-20250514"],
+ env={
+ "COPILOT_PROVIDER_WIRE_API": "responses",
+ "ANTHROPIC_API_KEY": "sk-test-dummy",
+ },
+ )
assert result.exit_code == 0, result.output
env = captured["env"]
diff --git a/tests/test_copilot_auth.py b/tests/test_copilot_auth.py
index 663dc66d3..d3bd94221 100644
--- a/tests/test_copilot_auth.py
+++ b/tests/test_copilot_auth.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import json
import time
from pathlib import Path
@@ -14,6 +15,32 @@ def test_read_cached_oauth_token_prefers_env(monkeypatch: pytest.MonkeyPatch) ->
assert copilot_auth.read_cached_oauth_token() == "gho-env"
+def test_read_cached_oauth_token_falls_back_to_gh_cli(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("GITHUB_COPILOT_GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_COPILOT_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
+ monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
+ monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: "gho-gh-cli")
+
+ assert copilot_auth.read_cached_oauth_token() == "gho-gh-cli"
+
+
+def test_read_cached_oauth_token_prefers_copilot_cli_windows_token(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.delenv("GITHUB_COPILOT_GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_COPILOT_TOKEN", raising=False)
+ monkeypatch.delenv("GITHUB_TOKEN", raising=False)
+ monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
+ monkeypatch.setattr(
+ copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: "gho-copilot"
+ )
+ monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: "gho-gh-cli")
+
+ assert copilot_auth.read_cached_oauth_token() == "gho-copilot"
+
+
def test_read_cached_oauth_token_reads_hosts_file(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
@@ -31,6 +58,8 @@ def test_read_cached_oauth_token_reads_hosts_file(
)
monkeypatch.delenv("GITHUB_COPILOT_TOKEN", raising=False)
monkeypatch.setenv("GITHUB_COPILOT_TOKEN_FILE", str(hosts))
+ monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
+ monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
assert copilot_auth.read_cached_oauth_token() == "gho-file"
@@ -44,10 +73,33 @@ def test_read_cached_oauth_token_skips_expired_entries(
encoding="utf-8",
)
monkeypatch.setenv("GITHUB_COPILOT_TOKEN_FILE", str(hosts))
+ monkeypatch.setattr(copilot_auth, "_read_windows_copilot_cli_oauth_token", lambda: None)
+ monkeypatch.setattr(copilot_auth, "_read_gh_cli_oauth_token", lambda: None)
assert copilot_auth.read_cached_oauth_token() is None
+def test_read_gh_cli_oauth_token_uses_hostname(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+
+ class CompletedProcess:
+ def __init__(self) -> None:
+ self.returncode = 0
+ self.stdout = "gho-gh-cli\n"
+
+ def fake_run(*args: object, **kwargs: object) -> CompletedProcess:
+ calls.append(list(args[0]))
+ assert kwargs["capture_output"] is True
+ assert kwargs["check"] is False
+ return CompletedProcess()
+
+ monkeypatch.setenv("GITHUB_COPILOT_HOST", "example.ghe.com")
+ monkeypatch.setattr(copilot_auth.subprocess, "run", fake_run)
+
+ assert copilot_auth._read_gh_cli_oauth_token() == "gho-gh-cli"
+ assert calls == [["gh", "auth", "token", "--hostname", "example.ghe.com"]]
+
+
def test_resolve_client_bearer_token_prefers_api_token(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("GITHUB_COPILOT_API_TOKEN", "copilot-api")
monkeypatch.setenv("GITHUB_COPILOT_TOKEN", "gho-oauth")
@@ -61,10 +113,24 @@ def test_is_copilot_api_url_matches_expected_hosts() -> None:
assert not copilot_auth.is_copilot_api_url("https://api.openai.com/v1/chat/completions")
-async def test_apply_copilot_api_auth_replaces_authorization(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
+def test_build_copilot_upstream_url_strips_v1_only_for_copilot_hosts() -> None:
+ assert (
+ copilot_auth.build_copilot_upstream_url(
+ "https://api.githubcopilot.com",
+ "/v1/chat/completions",
+ )
+ == "https://api.githubcopilot.com/chat/completions"
+ )
+ assert (
+ copilot_auth.build_copilot_upstream_url(
+ "https://api.openai.com",
+ "/v1/chat/completions",
+ )
+ == "https://api.openai.com/v1/chat/completions"
+ )
+
+
+def test_apply_copilot_api_auth_replaces_authorization(monkeypatch: pytest.MonkeyPatch) -> None:
async def fake_get_api_token() -> copilot_auth.CopilotAPIToken:
return copilot_auth.CopilotAPIToken(
token="copilot-session",
@@ -78,18 +144,48 @@ async def test_apply_copilot_api_auth_replaces_authorization(
fake_get_api_token,
)
- headers = await copilot_auth.apply_copilot_api_auth(
- {"authorization": "Bearer downstream-token"},
- url="https://api.githubcopilot.com/v1/chat/completions",
+ headers = asyncio.run(
+ copilot_auth.apply_copilot_api_auth(
+ {"authorization": "Bearer downstream-token"},
+ url="https://api.githubcopilot.com/v1/chat/completions",
+ )
)
assert headers["Authorization"] == "Bearer copilot-session"
assert "authorization" not in headers
-async def test_token_provider_exchanges_and_caches(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_token_provider_reuses_oauth_token_without_exchange(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("GITHUB_COPILOT_TOKEN", "gho-oauth")
+
+ provider = copilot_auth.CopilotTokenProvider()
+ calls = {"count": 0}
+
+ def fake_exchange(headers: dict[str, str]) -> dict[str, object]:
+ calls["count"] += 1
+ return {
+ "token": "copilot-api",
+ "expires_at": int(time.time()) + 3600,
+ "refresh_in": 1200,
+ "endpoints": {"api": "https://api.githubcopilot.com"},
+ "sku": "copilot_individual",
+ }
+
+ 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 == "gho-oauth"
+ assert second.token == "gho-oauth"
+ assert calls["count"] == 0
+
+
+def test_token_provider_can_exchange_when_enabled(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("GITHUB_COPILOT_TOKEN", "gho-oauth")
+ monkeypatch.setenv("GITHUB_COPILOT_USE_TOKEN_EXCHANGE", "true")
provider = copilot_auth.CopilotTokenProvider()
calls = {"count": 0}
@@ -106,8 +202,8 @@ async def test_token_provider_exchanges_and_caches(monkeypatch: pytest.MonkeyPat
monkeypatch.setattr(provider, "_exchange_token_sync", staticmethod(fake_exchange))
- first = await provider.get_api_token()
- second = await provider.get_api_token()
+ first = asyncio.run(provider.get_api_token())
+ second = asyncio.run(provider.get_api_token())
assert first.token == "copilot-api"
assert second.token == "copilot-api"
diff --git a/tests/test_proxy_copilot_auth_hooks.py b/tests/test_proxy_copilot_auth_hooks.py
index 5a89d8017..289ab282c 100644
--- a/tests/test_proxy_copilot_auth_hooks.py
+++ b/tests/test_proxy_copilot_auth_hooks.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import importlib.util
import sys
import types
@@ -50,8 +51,7 @@ def _load_handler_module(module_name: str, relative_path: str):
return module
-async def test_openai_passthrough_applies_copilot_auth(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_openai_passthrough_applies_copilot_auth(monkeypatch: pytest.MonkeyPatch) -> None:
openai_mod = _load_handler_module(
"tests.headroom_proxy_handlers_openai",
"headroom/proxy/handlers/openai.py",
@@ -95,20 +95,21 @@ async def test_openai_passthrough_applies_copilot_auth(monkeypatch: pytest.Monke
request.body = body
handler = Dummy()
- response = await handler.handle_passthrough(
- request,
- "https://api.githubcopilot.com",
- "models",
- "openai",
+ response = asyncio.run(
+ handler.handle_passthrough(
+ request,
+ "https://api.githubcopilot.com",
+ "models",
+ "openai",
+ )
)
- assert seen["url"] == "https://api.githubcopilot.com/v1/models"
+ assert seen["url"] == "https://api.githubcopilot.com/models"
assert seen["request_kwargs"]["headers"] == {"Authorization": "Bearer upstream-token"}
assert response.status_code == 200
-async def test_streaming_response_applies_copilot_auth(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_streaming_response_applies_copilot_auth(monkeypatch: pytest.MonkeyPatch) -> None:
streaming_mod = _load_handler_module(
"tests.headroom_proxy_handlers_streaming",
"headroom/proxy/handlers/streaming.py",
@@ -149,19 +150,21 @@ async def test_streaming_response_applies_copilot_auth(monkeypatch: pytest.Monke
return SimpleNamespace(headers={}, status_code=200)
handler = Dummy()
- response = await handler._stream_response(
- url="https://api.githubcopilot.com/v1/responses",
- headers={"authorization": "Bearer downstream"},
- body={"model": "gpt-4o"},
- provider="openai",
- model="gpt-4o",
- request_id="req-test",
- original_tokens=0,
- optimized_tokens=0,
- tokens_saved=0,
- transforms_applied=[],
- tags={},
- optimization_latency=0.0,
+ response = asyncio.run(
+ handler._stream_response(
+ url="https://api.githubcopilot.com/v1/responses",
+ headers={"authorization": "Bearer downstream"},
+ body={"model": "gpt-4o"},
+ provider="openai",
+ model="gpt-4o",
+ request_id="req-test",
+ original_tokens=0,
+ optimized_tokens=0,
+ tokens_saved=0,
+ transforms_applied=[],
+ tags={},
+ optimization_latency=0.0,
+ )
)
assert seen["url"] == "https://api.githubcopilot.com/v1/responses"