fix(proxy): keep Copilot requests on Copilot when an extension advises another provider (#4894)

## Description

A proxy in front of GitHub Copilot (started by `headroom wrap vscode` /
`wrap copilot`) holds only a Copilot token. When a proxy extension
published cross-provider route advice (`request.state.headroom_route`),
`BackendResolver.for_request` built a translating LiteLLM backend for it
without looking at the upstream. A GPT-family Copilot call advised onto
a Claude model was sent to Anthropic directly and failed:

```
LiteLLM backend initialized (provider=anthropic, region=None)
route advice: claude-sonnet-5-5 via anthropic (...)
/stats -> failed_by_provider: litellm-anthropic
```

The resolver now takes the request's upstream and ignores cross-provider
advice when that upstream is Copilot.

Companion change: headroomlabs-ai/routemegood#49 stops the routing
extension publishing such advice in shadow mode and for holdouts. This
PR is the safety property for apply mode.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/route_advice.py`: `for_request` takes `upstream_url`.
When `is_copilot_upstream_url(upstream_url)` it returns the default
backend and leaves `body["model"]` alone, with one info log line (model
id and provider only).
- `headroom/proxy/handlers/openai.py`, `handlers/anthropic.py`: all five
call sites pass the request's upstream. The Anthropic sites are included
because `wrap vscode` points the Anthropic target at Copilot as well.
- `handlers/openai.py`: chat-stream CCR eligibility asks the resolver
whether a backend will serve the request, instead of treating any advice
as "routed to backend". Ignored advice no longer disables CCR tool
injection.
- `tests/test_route_advice_native_providers.py`: a resolver-level test
(GHE Copilot host) and an end-to-end test through `create_app`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
CI on this PR: 34 checks passed, 12 skipped, 0 failed (lint, commitlint, test shards 1-4, test-macos).
Locally: ruff 0.17.4 check + format --check clean on the 4 changed files; mypy clean on the 3 source files.
tests/test_route_advice_native_providers.py: 8 passed.
With the Copilot check disabled, test_copilot_chat_stays_on_copilot_despite_cross_provider_advice fails with: assert ['anthropic'] == []
```

## Real Behavior Proof

- Environment: macOS 27.2.1, Python 3.12.13, core run from source (this
branch vs `origin/main` 5023c84e), `routemegood` from its unfixed
`origin/main` (f53bcb5) loaded as the only proxy extension with a valid
licence, default (shadow) mode. Upstream: the real GitHub Copilot API on
a signed-in Copilot account, proxy started by `headroom wrap vscode -p
8795 --settings-file <temp file>`.
- Exact command / steps: start the wrap proxy, then send one
Copilot-shaped call, and read `/stats` and the proxy log:
  ```
  curl -s http://127.0.0.1:8795/chat/completions \
-H "Authorization: Bearer placeholder" -H "Content-Type:
application/json" \
-H "Copilot-Integration-Id: vscode-chat" -H "Editor-Version:
vscode/1.145.2" \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Reply
with the single word OK"}],"max_tokens":16,"stream":false}'
  ```
- Observed result:

**Before (`origin/main` 5023c84e)** — the request leaves Copilot and
fails at Anthropic:
  ```text
  HTTP 401
error: litellm.AuthenticationError: AnthropicException -
{"type":"error","error":{"type":"authentication_error","message":"invalid
x-api-key"}, ...}
/stats: {'total': 0, 'failed': 0, 'by_model': {}, 'by_provider': {},
'failed_by_provider': {'unknown': 0}}
09:33:54,229 headroom.backends.litellm - INFO - LiteLLM backend
initialized (provider=anthropic, region=None)
09:33:54,234 headroom.proxy.route_advice - INFO - route advice:
claude-sonnet-5-5 via anthropic (cannot cache (prefix 7 < min 512); ...
09:33:54,438 headroom.backends.litellm - ERROR - LiteLLM OpenAI error:
litellm.AuthenticationError: AnthropicException - ... "invalid
x-api-key" ...
09:33:54,438 headroom.proxy - INFO - event=proxy_inbound_response ...
method=POST path=/chat/completions status=401
  ```

**After (this branch, fcfa965b)** — same extension, same request, served
by Copilot:
  ```text
  HTTP 200
  served model: gpt-4o-mini-2024-07-18 | reply: OK
/stats: {'total': 1, 'failed': 0, 'by_model': {'gpt-4o-mini': 1},
'by_provider': {'copilot': 1}, 'failed_by_provider': {'unknown': 0}}
09:34:11,511 headroom.proxy.route_advice - INFO - route advice ignored:
claude-sonnet-5-5 via anthropic; the upstream is GitHub Copilot
09:34:13,044 headroom.proxy - INFO - event=proxy_inbound_response ...
method=POST path=/chat/completions status=200
  ```
- Not tested: a request sent by the VS Code UI itself (the call above is
the same shape, sent with curl); a streaming request; the
Anthropic-handler (`/v1/messages`) call sites end to end; a custom
`GITHUB_COPILOT_PROXY_URL` host; Windows.

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: n/a.
- Stable/default behavior changed: only for proxies whose upstream is a
GitHub Copilot host, and only when an extension publishes cross-provider
route advice. Those requests now stay on Copilot instead of being sent
to another provider.
- Kill switch / disable path: none added. Not loading the extension that
publishes advice restores the old path trivially.
- Unsafe override required: no.
- Qualification impact: none expected.
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

- Documentation: no user-facing docs describe route advice, so none were
changed.
- A custom `GITHUB_COPILOT_PROXY_URL` host is recognised only when that
variable is set, since recognition goes through the existing helper.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-17 09:50:56 +05:30
committed by GitHub
co-authored by Claude Fable 5.2 JD Davis
parent ac932eb7c4
commit 998d71080c
4 changed files with 112 additions and 10 deletions
+14 -2
View File
@@ -1646,7 +1646,13 @@ class AnthropicHandlerMixin:
request, headers, routed_to_omlx=routed_to_omlx
)
backend = (
None if routed_to_omlx else resolver_for(self).for_request(request, body=body)
None
if routed_to_omlx
else resolver_for(self).for_request(
request,
body=body,
upstream_url=upstream_base_url or self.ANTHROPIC_API_URL,
)
)
if backend is not None:
if model_override and not body.get("model"):
@@ -4255,7 +4261,13 @@ class AnthropicHandlerMixin:
from headroom.proxy.route_advice import resolver_for
request_backend = (
None if force_direct else resolver_for(self).for_request(request, body=body)
None
if force_direct
else resolver_for(self).for_request(
request,
body=body,
upstream_url=upstream_base_url or self.ANTHROPIC_API_URL,
)
)
if request_backend is not None:
# Route through Bedrock backend
+13 -8
View File
@@ -3786,7 +3786,10 @@ class OpenAIHandlerMixin:
COMPRESSION_BODY_MAX_BYTES,
)
backend = resolver_for(self).for_request(
request, body=body, native_providers=("openai",)
request,
body=body,
native_providers=("openai",),
upstream_url=upstream_base_url,
)
passthrough_model = body.get("model", "unknown")
if not isinstance(passthrough_model, str):
@@ -4574,7 +4577,7 @@ class OpenAIHandlerMixin:
# Decided before injection: a turn that can buffer can answer the tool,
# so it may carry it even though the client asked for a stream. Whether
# it actually buffers is settled at dispatch, from the final body.
from headroom.proxy.route_advice import advice_from
from headroom.proxy.route_advice import resolver_for
_ccr_handler = getattr(self, "ccr_response_handler", None)
chat_stream_ccr_eligible = _is_openai_chat_stream_ccr_eligible(
@@ -4584,10 +4587,12 @@ class OpenAIHandlerMixin:
_ccr_handler and getattr(_ccr_handler.config, "enabled", True)
),
ccr_inject_tool=self.config.ccr_inject_tool,
routed_to_backend=(
getattr(self, "anthropic_backend", None) is not None
or advice_from(request) is not None
),
# Ask the resolver, not the advice: advice it ignores (a Copilot
# upstream) leaves this request on the direct path.
routed_to_backend=resolver_for(self).for_request(
request, native_providers=("openai",), upstream_url=upstream_base_url
)
is not None,
upstream_base_url=upstream_base_url,
)
can_inject_ccr_tool = _should_inject_openai_chat_ccr_tool(
@@ -5164,7 +5169,7 @@ class OpenAIHandlerMixin:
_normalize_openai_max_tokens(
body,
backend_owns_translation=resolver_for(self).for_request(
request, native_providers=("openai",)
request, native_providers=("openai",), upstream_url=upstream_base_url
)
is not None,
)
@@ -5235,7 +5240,7 @@ class OpenAIHandlerMixin:
# litellm backend; same-family (openai) advice still resolves to
# `self.anthropic_backend`, unchanged.
request_backend = resolver_for(self).for_request(
request, body=body, native_providers=("openai",)
request, body=body, native_providers=("openai",), upstream_url=upstream_base_url
)
if request_backend is not None:
try:
+16
View File
@@ -34,6 +34,7 @@ import logging
from dataclasses import dataclass
from typing import Any
from headroom.copilot_auth import is_copilot_upstream_url
from headroom.offline import pin_litellm_cost_map_local
log = logging.getLogger(__name__)
@@ -110,6 +111,7 @@ class BackendResolver:
*,
body: dict | None = None,
native_providers: tuple[str, ...] = _NATIVE,
upstream_url: str | None = None,
) -> Any:
"""The backend to serve this request. Falls back to the default.
@@ -122,6 +124,12 @@ class BackendResolver:
short-circuited to the default backend. One proxy instance serves both
wires from a single shared resolver, so native-ness cannot live on the
resolver; it must be supplied per dispatch site.
``upstream_url`` is where the caller sends this request when no backend
is used. When it is GitHub Copilot, cross-provider advice is ignored and
the body is left alone: Copilot serves every model family on the one
upstream, and the proxy holds a Copilot token, not a key for the
provider a translating backend would call.
"""
advice = advice_from(request)
if advice is None:
@@ -133,6 +141,14 @@ class BackendResolver:
# rewrite is enough and the extension has already done it. Nothing
# to switch.
return self._default
if is_copilot_upstream_url(upstream_url):
if body is not None:
log.info(
"route advice ignored: %s via %s; the upstream is GitHub Copilot",
advice.model,
provider,
)
return self._default
if provider in self._failed:
return self._default
@@ -12,7 +12,13 @@ from __future__ import annotations
from types import SimpleNamespace
import httpx
import pytest
from fastapi.testclient import TestClient
from headroom import copilot_auth
from headroom.proxy.route_advice import BackendResolver, RouteAdvice
from headroom.proxy.server import ProxyConfig, create_app
class _Sentinel:
@@ -79,3 +85,66 @@ def test_failed_provider_falls_back_to_default() -> None:
assert r1 == "DEFAULT_BACKEND"
r2 = resolver.for_request(_request("claude-opus-5", "anthropic"), native_providers=("openai",))
assert r2 == "DEFAULT_BACKEND"
def test_copilot_upstream_ignores_cross_provider_advice() -> None:
# A Copilot proxy holds only a Copilot token, so advice naming another
# provider must not move the request or rewrite its model. A GHE host
# counts as Copilot too.
resolver = _resolver()
body: dict = {"model": "gpt-5-mini"}
result = resolver.for_request(
_request("claude-opus-5", "anthropic"),
body=body,
native_providers=("openai",),
upstream_url="https://copilot-api.acme.ghe.com",
)
assert result == "DEFAULT_BACKEND"
assert body["model"] == "gpt-5-mini"
def test_copilot_chat_stays_on_copilot_despite_cross_provider_advice(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# A proxy in front of GitHub Copilot holds a Copilot token only, and Copilot
# serves every model family on its own /chat/completions. Advice naming
# another provider used to send the request to Anthropic through a
# translating backend, where it failed for want of a key.
class _Provider:
async def get_api_token(self, *, integration_id=None): # noqa: ANN001, ANN202
return SimpleNamespace(token="test-copilot-token")
monkeypatch.setattr(copilot_auth, "get_copilot_token_provider", lambda: _Provider())
built: list[str] = []
monkeypatch.setattr(BackendResolver, "_build", lambda self, provider: built.append(provider))
sent: list[tuple[str, str]] = []
async def fake_retry(method, url, headers, body, *args, **kwargs): # noqa: ANN001, ANN002, ANN003, ANN202
sent.append((url, body["model"]))
return httpx.Response(200, json={"choices": [], "usage": {}})
app = create_app(
ProxyConfig(
optimize=False,
cache_enabled=False,
rate_limit_enabled=False,
openai_api_url="https://api.business.githubcopilot.com",
)
)
@app.middleware("http")
async def publish_advice(request, call_next): # noqa: ANN001, ANN202
request.state.headroom_route = RouteAdvice(model="claude-sonnet-5-5", provider="anthropic")
return await call_next(request)
with TestClient(app) as client:
client.app.state.proxy._retry_request = fake_retry
response = client.post(
"/v1/chat/completions",
json={"model": "gpt-5-mini", "messages": [{"role": "user", "content": "hi"}]},
headers={"Authorization": "Bearer test-key"},
)
assert response.status_code == 200, response.text
assert built == [], "no translating backend may be built for a Copilot upstream"
assert sent == [("https://api.business.githubcopilot.com/chat/completions", "gpt-5-mini")]