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): honour GitHub's advertised Business/Enterprise host by default (#4155)
Tejas Chopra1dc7a183f55d
diff --git a/TESTING-copilot-subscription.md b/TESTING-copilot-subscription.mdindex ebcc3b910..3eec7e67c 100644--- a/TESTING-copilot-subscription.md+++ b/TESTING-copilot-subscription.md@@ -26,17 +26,25 @@ default — with your token.)## API host & Enterprise / data-residency-Headroom routes wrapped Copilot traffic to GitHub's **generic public host**,-`https://api.githubcopilot.com`, for both `--subscription` and the implicit-OAuth path. That host serves the full model set (including newer models on the-responses API) and matches the routing that worked before 0.23.--Headroom deliberately does **not** auto-select a per-account host from-`/copilot_internal/user`. That endpoint advertises a segmented host (e.g.-`api.individual.githubcopilot.com`) that does **not** serve newer models on the-responses API and is not the host the official Copilot client routes with — using-it regressed `headroom wrap copilot` after 0.22.4-([#610](https://github.com/headroomlabs-ai/headroom/issues/610)).+Which host a wrapped session talks to depends on the lane:++- **`--subscription`, `headroom wrap vscode`, and OpenCode `--copilot-subscription`**+ resolve the host from GitHub's token exchange. Business and Enterprise seats+ route to the plan host GitHub advertises (`api.business.githubcopilot.com` /+ `api.enterprise.githubcopilot.com`), which is what GitHub's own clients use and+ the only host an enterprise firewall on GitHub's subscription-based network+ routing allows. If that host rejects a model the generic host serves, set+ `GITHUB_COPILOT_USE_ADVERTISED_HOST=0` to fold back to the generic host.+ Individual seats route to the generic host: `api.individual.githubcopilot.com`+ does **not** serve newer models on the responses API, and using it regressed+ `headroom wrap copilot` after 0.22.4+ ([#610](https://github.com/headroomlabs-ai/headroom/issues/610)).+- **The implicit OAuth path** (plain `headroom wrap copilot` with a GitHub login+ and no provider key) performs no token exchange at launch and always uses the+ **generic public host** `https://api.githubcopilot.com`. On a firewall that+ allows only the plan host, use `--subscription` or pin the host as below.++An explicit `GITHUB_COPILOT_API_URL` wins over all of the above.**Enterprise / data-residency:** if your organization is provisioned on adedicated Copilot API host (GitHub Enterprise Cloud with data residency, or an@@ -48,11 +56,8 @@ export GITHUB_COPILOT_API_URL=https://api.<your-host>.githubcopilot.comheadroom wrap copilot --subscription -- --model gpt-5.4```-If you operate such an environment and would like Headroom to **auto-detect** the-correct host instead of pinning it, please [open an issue](https://github.com/headroomlabs-ai/headroom/issues/new) —-the intended path is to resolve it from GitHub's token-exchange endpoint (the-source the official Copilot client uses), and we'd want to validate it against a-real enterprise tenant.+The Business and Enterprise plan hosts are detected from GitHub's token-exchange+endpoint (see above); only data-residency and egress-proxy hosts still need the pin.## Statusdiff --git a/docs/content/docs/corporate-networks.mdx b/docs/content/docs/corporate-networks.mdxindex df314cdf5..f62dc3144 100644--- a/docs/content/docs/corporate-networks.mdx+++ b/docs/content/docs/corporate-networks.mdx@@ -73,7 +73,7 @@ Headroom runs on the developer's machine and talks to the same services the AI t|---|---|---|| `api.anthropic.com` | Claude / Claude Code | yes, for Anthropic || `api.openai.com`, `chatgpt.com` | OpenAI API, Codex | yes, for OpenAI / Codex |-| `api.githubcopilot.com`, `api.github.com` | GitHub Copilot | for Copilot |+| `api.githubcopilot.com` (or `api.business.githubcopilot.com` / `api.enterprise.githubcopilot.com` for those plans), `api.github.com` | GitHub Copilot | for Copilot || `huggingface.co` and the storage hosts it redirects to (`cdn-lfs.hf.co`, `cas-bridge.xethub.hf.co`) | Compression models (downloaded once) | recommended || `openaipublic.blob.core.windows.net` | Tokenizer vocabulary (downloaded once) | recommended |diff --git a/docs/content/docs/vscode-copilot.mdx b/docs/content/docs/vscode-copilot.mdxindex 28ca276e1..2f0c5786a 100644--- a/docs/content/docs/vscode-copilot.mdx+++ b/docs/content/docs/vscode-copilot.mdx@@ -144,10 +144,19 @@ remote, and profile-specific settings should use `--settings-file` explicitly.## Enterprise-GitHub.com Enterprise Cloud normally requires no override; Headroom uses the API-URL advertised during token exchange. For GitHub Enterprise Server/custom domains,-set `GITHUB_COPILOT_ENTERPRISE_URL` or `GITHUB_COPILOT_ENTERPRISE_DOMAIN` before-both `copilot-auth login` and `wrap vscode`.+GitHub.com Enterprise Cloud normally requires no override. Copilot Business and+Enterprise seats are routed to the host GitHub advertises during token exchange+(`api.business.githubcopilot.com` or `api.enterprise.githubcopilot.com`), which is+the host GitHub's own clients use. This matters on networks that follow GitHub's+[subscription-based network routing](https://docs.github.com/en/copilot/how-tos/administer-copilot/manage-for-enterprise/manage-access/manage-network-access):+their firewall allows only the plan host, and the generic `api.githubcopilot.com`+is blocked. If the plan host rejects a model the generic host serves, set+`GITHUB_COPILOT_USE_ADVERTISED_HOST=0` to route through the generic host again.+An explicit `GITHUB_COPILOT_API_URL` still wins over both.++For GitHub Enterprise Server/custom domains, set `GITHUB_COPILOT_ENTERPRISE_URL`+or `GITHUB_COPILOT_ENTERPRISE_DOMAIN` before both `copilot-auth login` and+`wrap vscode`.## Verification and troubleshootingdiff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex a7ece946a..f43d5aafa 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -6727,11 +6727,13 @@ def copilot(headroom wrap copilot --subscription -- --model gpt-4.1\b- Copilot hosted API (--subscription and the implicit OAuth path) routes to the- generic host https://api.githubcopilot.com, which serves the full model set.- Enterprise / data-residency accounts provisioned on a dedicated host pin it- explicitly with GITHUB_COPILOT_API_URL (the override flows through to upstream).- See TESTING-copilot-subscription.md for details.+ Copilot hosted API: --subscription routes Business / Enterprise seats to+ the plan host GitHub advertises (GITHUB_COPILOT_USE_ADVERTISED_HOST=0 folds+ them back to the generic host) and individual seats to the generic host+ https://api.githubcopilot.com; the implicit OAuth path always uses the+ generic host. Data-residency accounts provisioned on a dedicated host pin+ it explicitly with GITHUB_COPILOT_API_URL (the override flows through to+ upstream). See TESTING-copilot-subscription.md for details."""copilot_bin = _require_binary("copilot",diff --git a/headroom/copilot_auth.py b/headroom/copilot_auth.pyindex a1fe3554e..c81e1036c 100644--- a/headroom/copilot_auth.py+++ b/headroom/copilot_auth.py@@ -1065,6 +1065,28 @@ def _api_url_from_payload(payload: dict[str, Any] | None) -> str | None:return None+#: Opt-out: ``0``/``false``/``no``/``off`` folds the Business and Enterprise+#: hosts below back into the generic host, for seats where the segmented host+#: still lags on model availability (#2455 folded them after a Business seat+#: got "model not supported" for Claude models on its plan host).+_USE_ADVERTISED_HOST_ENV = "GITHUB_COPILOT_USE_ADVERTISED_HOST"++#: Per-plan chat hosts GitHub advertises in ``endpoints.api`` for Business and+#: Enterprise seats. Honoured by default: they are the hosts GitHub's own+#: clients route with, and an enterprise on GitHub's subscription-based network+#: routing allows only its own plan host, so the generic host is unreachable+#: there and the failure looks like a random connection error. The individual+#: host is still folded (#610: it did not serve newer models on the Responses+#: API). An explicit ``GITHUB_COPILOT_API_URL`` or enterprise domain wins over+#: both.+_ADVERTISED_PLAN_HOSTS: frozenset[str] = frozenset(+ {+ "api.business.githubcopilot.com",+ "api.enterprise.githubcopilot.com",+ }+)++def _subscription_api_url_from_user_info_payload(payload: dict[str, Any] | None) -> str:configured = _configured_api_url_override()if configured:@@ -1075,12 +1097,21 @@ def _subscription_api_url_from_user_info_payload(payload: dict[str, Any] | None)return DEFAULT_API_URLhost = urlparse(api_url).netloc.lower()- if host in {- "api.githubcopilot.com",- "api.individual.githubcopilot.com",- "api.business.githubcopilot.com",- "api.enterprise.githubcopilot.com",- }:+ if host in _ADVERTISED_PLAN_HOSTS:+ opt_out = os.environ.get(_USE_ADVERTISED_HOST_ENV, "").strip().lower()+ if opt_out in {"0", "false", "no", "off"}:+ return DEFAULT_API_URL+ # Named in the log so a "model not supported" 400 from the plan host+ # sits next to the escape hatch instead of looking like a proxy fault.+ logger.info(+ "Routing Copilot subscription traffic to the advertised plan host %s "+ "(set %s=0 to use %s instead)",+ api_url,+ _USE_ADVERTISED_HOST_ENV,+ DEFAULT_API_URL,+ )+ return api_url+ if host in {"api.githubcopilot.com", "api.individual.githubcopilot.com"}:return DEFAULT_API_URLif host.endswith(".githubcopilot.com"):return api_url@@ -1406,14 +1437,14 @@ def resolve_copilot_api_url(oauth_token: str | None = None) -> str:(corporate proxy, enterprise / data-residency host, tests).2. The generic public host ``https://api.githubcopilot.com``.- The account-specific ``endpoints.api`` advertised by ``/copilot_internal/user``- is intentionally NOT used to route. It returns a segmented host (e.g.- ``api.individual.githubcopilot.com``) that does not serve newer models on the- responses API — wrapping such a request regressed after 0.22.4 (#610) — and it- is not the host the official Copilot client routes with (that comes from the- token-exchange endpoint, not user info). Accounts that genuinely require a- dedicated host set ``GITHUB_COPILOT_API_URL`` explicitly. ``oauth_token`` is- accepted for call-site compatibility but no longer triggers a network lookup.+ This path performs no network lookup, so it cannot see the per-plan host a+ token exchange advertises. The subscription lanes (``wrap vscode``,+ ``wrap copilot --subscription``, OpenCode) resolve that host through+ :func:`resolve_subscription_bearer_token_details` and pin it into the proxy+ as ``GITHUB_COPILOT_API_URL``, which step 1 then honours. The+ ``api.individual.githubcopilot.com`` host is never routed to (#610: it did+ not serve newer models on the Responses API). ``oauth_token`` is accepted+ for call-site compatibility but no longer triggers a network lookup."""del oauth_token # reserved; routing no longer depends on a user-info lookupdiff --git a/tests/test_cli/test_wrap_copilot.py b/tests/test_cli/test_wrap_copilot.pyindex 9772b3bdb..caaa2cba1 100644--- a/tests/test_cli/test_wrap_copilot.py+++ b/tests/test_cli/test_wrap_copilot.py@@ -6,7 +6,7 @@ import importlibimport sysimport typesfrom pathlib import Path-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom urllib.parse import quoteimport click@@ -876,6 +876,48 @@ def test_wrap_copilot_oauth_keeps_generic_endpoint_when_account_advertised(assert env["GITHUB_COPILOT_API_URL"] == DEFAULT_API_URL+def test_wrap_copilot_implicit_oauth_stays_generic_and_does_no_account_lookup(+ runner: CliRunner,+ wrap_modules: tuple[types.ModuleType, click.Group],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The implicit OAuth lane performs no user-info or token-exchange lookup at+ launch, so it cannot see a plan host and always routes to the generic host.+ Pinned so the guide's split between the lanes stays true: an Enterprise seat+ that needs its plan host must use --subscription or wrap vscode."""+ _wrap_cli, main = wrap_modules+ _clear_copilot_env(monkeypatch)+ captured: dict[str, object] = {}++ def fake_launch_tool(**kwargs): # noqa: ANN003+ captured.update(kwargs)++ enterprise = {"endpoints": {"api": "https://api.enterprise.githubcopilot.com"}}+ user_info = MagicMock(return_value=enterprise)+ exchange = MagicMock(return_value={"token": "copilot-api", **enterprise})++ with (+ patch("headroom.cli.wrap.shutil.which", return_value="copilot"),+ patch("headroom.cli.wrap.resolve_client_bearer_token", return_value="gho-oauth"),+ patch("headroom.cli.wrap.has_oauth_auth", return_value=True),+ patch("headroom.copilot_auth._fetch_copilot_user_info", user_info),+ patch(+ "headroom.copilot_auth.CopilotTokenProvider._exchange_token_sync",+ staticmethod(exchange),+ ),+ patch("headroom.cli.wrap._launch_tool", side_effect=fake_launch_tool),+ ):+ result = runner.invoke(main, ["wrap", "copilot", "--", "--model", "gpt-5.4"])++ assert result.exit_code == 0, result.output+ assert captured["openai_api_url"] == DEFAULT_API_URL+ # The lane never asks GitHub which host the seat is on: neither the+ # user-info lookup nor the token exchange that would advertise the+ # Enterprise host is consulted.+ assert user_info.call_count == 0+ assert exchange.call_count == 0++def test_wrap_copilot_oauth_honors_api_url_override(runner: CliRunner,wrap_modules: tuple[types.ModuleType, click.Group],@@ -982,11 +1024,13 @@ def test_wrap_copilot_subscription_uses_resolved_subscription_endpoint(assert env["COPILOT_PROVIDER_BEARER_TOKEN"] == "copilot-api"-def test_wrap_copilot_subscription_normalizes_enterprise_host(+def test_wrap_copilot_subscription_honours_advertised_enterprise_host(runner: CliRunner,wrap_modules: tuple[types.ModuleType, click.Group],monkeypatch: pytest.MonkeyPatch,) -> None:+ """An Enterprise seat routes to the host its token exchange advertised; a+ firewall on GitHub's subscription-based routing allows only that host."""_wrap_cli, main = wrap_modules_clear_copilot_env(monkeypatch)captured: dict[str, object] = {}@@ -1028,9 +1072,10 @@ def test_wrap_copilot_subscription_normalizes_enterprise_host(assert result.exit_code == 0, result.outputenv = captured["env"]assert isinstance(env, dict)- assert captured["openai_api_url"] == DEFAULT_API_URL- assert env["OPENAI_TARGET_API_URL"] == DEFAULT_API_URL- assert env["GITHUB_COPILOT_API_URL"] == DEFAULT_API_URL+ enterprise_api = "https://api.enterprise.githubcopilot.com"+ assert captured["openai_api_url"] == enterprise_api+ assert env["OPENAI_TARGET_API_URL"] == enterprise_api+ assert env["GITHUB_COPILOT_API_URL"] == enterprise_apidef test_wrap_copilot_subscription_honors_api_url_override(diff --git a/tests/test_cli/test_wrap_opencode.py b/tests/test_cli/test_wrap_opencode.pyindex cd0e0c610..26911babd 100644--- a/tests/test_cli/test_wrap_opencode.py+++ b/tests/test_cli/test_wrap_opencode.py@@ -73,7 +73,7 @@ def _subscription_resolution() -> CopilotSubscriptionTokenResolution:# ----------------------------------------------------------------------------def test_wrap_opencode_copilot_subscription_normalizes_enterprise_host_and_handoffs_seed_after_actual_port(+def test_wrap_opencode_copilot_subscription_honours_advertised_enterprise_host_and_handoffs_seed_after_actual_port(runner: CliRunner,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -144,7 +144,7 @@ def test_wrap_opencode_copilot_subscription_normalizes_enterprise_host_and_handoassert result.exit_code == 0, result.outputensure = captured["ensure"]- assert ensure["openai_api_url"] == "https://api.githubcopilot.com"+ assert ensure["openai_api_url"] == "https://api.enterprise.githubcopilot.com"assert ensure["copilot_api_token"] == "copilot-api-secret"assert ensure["copilot_refresh_oauth_token"] == "gho-oauth"assert ensure["copilot_api_token_expires_at"] == 123.5diff --git a/tests/test_copilot_auth.py b/tests/test_copilot_auth.pyindex 23cec644b..1accbcfff 100644--- a/tests/test_copilot_auth.py+++ b/tests/test_copilot_auth.py@@ -541,7 +541,7 @@ def test_subscription_enterprise_host_repro(assert resolution.token == "copilot-api"assert resolution.source == "headroom-copilot-auth:/tmp/copilot_auth.json:token-exchange"assert resolution.confidence == "copilot-token-exchange"- assert resolution.api_url == copilot_auth.DEFAULT_API_URL+ assert resolution.api_url == "https://api.enterprise.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)@@ -589,7 +589,7 @@ def test_resolve_subscription_exchange_uses_cloud_enterprise_advertised_api(resolution = copilot_auth.resolve_subscription_bearer_token_details()assert resolution is not None- assert resolution.api_url == copilot_auth.DEFAULT_API_URL+ assert resolution.api_url == "https://api.enterprise.githubcopilot.com"assert copilot_auth._token_exchange_url() == "https://api.github.com/copilot_internal/v2/token"@@ -610,7 +610,8 @@ def test_api_url_from_exchange_payload_rejects_non_copilot_host(oauth_token="gho-oauth",)- assert resolved == copilot_auth.DEFAULT_API_URL+ # The foreign host is ignored; the user-info lookup's Business host is used.+ assert resolved == "https://api.business.githubcopilot.com"def _resolve_subscription_producer_path(@@ -718,19 +719,69 @@ def test_subscription_unknown_host_passthrough(monkeypatch: pytest.MonkeyPatch)["https://api.githubcopilot.com","https://api.individual.githubcopilot.com",+ ],+)+def test_subscription_individual_host_normalizes_to_default(+ monkeypatch: pytest.MonkeyPatch, payload_host: str+) -> None:+ """#610: the individual host lags on newer models, so it is never routed to."""+ monkeypatch.delenv("GITHUB_COPILOT_API_URL", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_USE_ADVERTISED_HOST", raising=False)+ assert (+ copilot_auth._subscription_api_url_from_user_info_payload(+ {"endpoints": {"api": payload_host}}+ )+ == copilot_auth.DEFAULT_API_URL+ )+++ "payload_host",+ ["https://api.business.githubcopilot.com","https://api.enterprise.githubcopilot.com",],)-def test_subscription_known_hosts_normalize_to_default(payload_host: str) -> None:+def test_subscription_business_and_enterprise_hosts_are_honoured(+ monkeypatch: pytest.MonkeyPatch, payload_host: str+) -> None:+ """A firewall on GitHub's subscription-based routing allows only the plan host."""+ monkeypatch.delenv("GITHUB_COPILOT_API_URL", raising=False)+ monkeypatch.delenv("GITHUB_COPILOT_USE_ADVERTISED_HOST", raising=False)assert (copilot_auth._subscription_api_url_from_user_info_payload(- {"endpoints": {"api": payload_host}}+ {"endpoints": {"api": payload_host + "/"}}+ )+ == payload_host+ )++[email protected]("opt_out", ["0", "false", "no", "off", " OFF "])+def test_subscription_advertised_host_opt_out_restores_generic_fold(+ monkeypatch: pytest.MonkeyPatch, opt_out: str+) -> None:+ """#2455: seats whose plan host lags on models can fold back to the generic host."""+ monkeypatch.delenv("GITHUB_COPILOT_API_URL", raising=False)+ monkeypatch.setenv("GITHUB_COPILOT_USE_ADVERTISED_HOST", opt_out)+ assert (+ copilot_auth._subscription_api_url_from_user_info_payload(+ {"endpoints": {"api": "https://api.enterprise.githubcopilot.com"}})== copilot_auth.DEFAULT_API_URL)+def test_subscription_advertised_host_explicit_pin_wins(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("GITHUB_COPILOT_USE_ADVERTISED_HOST", raising=False)+ monkeypatch.setenv("GITHUB_COPILOT_API_URL", "https://api.githubcopilot.com")+ assert (+ copilot_auth._subscription_api_url_from_user_info_payload(+ {"endpoints": {"api": "https://api.enterprise.githubcopilot.com"}}+ )+ == "https://api.githubcopilot.com"+ )++@pytest.mark.parametrize("payload",[