The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api-server): stop persisting the virtual model alias as a session's model
Andy Lo-A-Foe152b1940d760
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 5adc1dbf7c6..42cd27069e1 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -2385,8 +2385,19 @@ class APIServerAdapter(BasePlatformAdapter):model = split_model or raw_modelalias_route = self._resolve_route(raw_model) or self._resolve_route(model)route = dict(alias_route) if isinstance(alias_route, dict) else None+ # The virtual model alias (self._model_name, e.g. "hermes-agent") is+ # not a real provider model id — it's the id /v1/models advertises+ # for "use the gateway default". A client that echoes it back+ # (explicitly or via a generic model picker) means "no real request",+ # same as omitting model entirely. Null it out here, upstream of+ # both the route-building below and every caller's "requested"+ # dict, so it never gets persisted as a session's model or+ # misread later as a raw session_model override (#session-model-+ # alias-leak — see _handle_create_session).+ if model == self._model_name:+ model = Noneroute_source = "model_routes" if route else "global"- if not route and model and model != self._model_name:+ if not route and model:route = {"model": model}if provider:route["provider"] = provider@@ -3440,7 +3451,6 @@ class APIServerAdapter(BasePlatformAdapter):if len(session_id) > self._MAX_SESSION_HEADER_LEN:return web.json_response(_openai_error("Session ID too long", code="invalid_session_id"), status=400)- model = body.get("model") or self._model_namesystem_prompt = body.get("system_prompt")if system_prompt is not None and not isinstance(system_prompt, str):return web.json_response(_openai_error("system_prompt must be a string", code="invalid_system_prompt"), status=400)@@ -3450,7 +3460,18 @@ class APIServerAdapter(BasePlatformAdapter):if lock_error is not None:return lock_errorrequested = runtime_request.get("requested") or {}- model_name = self._clean_runtime_id(requested.get("model")) or (str(model) if model else None)+ # requested["model"] is already normalized by+ # _session_runtime_request_from_body: provider-prefixed values+ # (e.g. "provider::hermes-agent") are split, and the virtual model+ # alias (self._model_name, e.g. "hermes-agent") is nulled out+ # there — a bare "hermes-agent" is not a model_routes alias, so a+ # later chat on this session would otherwise fall into the raw+ # session_model precedence branch in _handle_session_chat and get+ # sent to the provider literally, failing with "invalid model+ # identifier" (#session-model-alias-leak). Re-deriving straight+ # from the raw body here would bypass that normalization and+ # reintroduce the leak for the provider-prefixed case.+ model_name = self._clean_runtime_id(requested.get("model")) or Nonemodel_config = Noneif requested.get("model") or requested.get("provider"):model_config = {diff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.pyindex 69aebdebba1..9091bb256c9 100644--- a/tests/gateway/test_api_server.py+++ b/tests/gateway/test_api_server.py@@ -2645,6 +2645,93 @@ class TestSessionDbOffEventLoop:assert captured["thread"] is not Noneassert captured["thread"] != threading.current_thread()+ @pytest.mark.asyncio+ async def test_create_session_without_model_does_not_persist_virtual_alias(self, auth_adapter):+ """A session created with no ``model`` field must not persist the+ virtual model alias (self._model_name, e.g. "hermes-agent") as if it+ were a real provider model id.++ Regression: _handle_create_session previously did+ ``model = body.get("model") or self._model_name``, so an omitted+ model fell back to the virtual alias and that string got stored on+ the session row. _handle_session_chat later reads it back as a raw+ session_model override (since it's not a model_routes alias) and+ sends it to the provider literally — Bedrock/OpenAI then reject+ "hermes-agent" as an invalid model identifier on every turn.+ """+ app = _create_app(auth_adapter)+ app.router.add_post("/api/sessions", auth_adapter._handle_create_session)++ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ "/api/sessions",+ json={},+ headers={"Authorization": "Bearer sk-secret"},+ )+ assert resp.status == 201+ data = await resp.json()+ assert data["session"]["model"] != auth_adapter._model_name+ assert data["session"]["model"] is None++ @pytest.mark.asyncio+ async def test_create_session_with_explicit_virtual_alias_does_not_persist_it(self, auth_adapter):+ """Sending ``model: "hermes-agent"`` explicitly (the virtual alias+ itself, e.g. a client that just echoes /v1/models' advertised id)+ must be treated the same as omitting model entirely."""+ app = _create_app(auth_adapter)+ app.router.add_post("/api/sessions", auth_adapter._handle_create_session)++ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ "/api/sessions",+ json={"model": auth_adapter._model_name},+ headers={"Authorization": "Bearer sk-secret"},+ )+ assert resp.status == 201+ data = await resp.json()+ assert data["session"]["model"] is None++ @pytest.mark.asyncio+ async def test_create_session_with_real_model_persists_it(self, auth_adapter):+ """Regression guard: a genuine model id must still be stored as before."""+ app = _create_app(auth_adapter)+ app.router.add_post("/api/sessions", auth_adapter._handle_create_session)++ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ "/api/sessions",+ json={"model": "openai/gpt-5"},+ headers={"Authorization": "Bearer sk-secret"},+ )+ assert resp.status == 201+ data = await resp.json()+ assert data["session"]["model"] == "openai/gpt-5"++ @pytest.mark.asyncio+ async def test_create_session_with_provider_prefixed_virtual_alias_does_not_persist_it(self, auth_adapter):+ """A provider-prefixed echo of the virtual alias (e.g. a client that+ threads /v1/models' advertised id through a provider:: prefix) must+ also be treated as "no model", not stored as a raw override.++ Regression: _handle_create_session used to re-derive its own `model`+ straight from the raw request body, bypassing the provider-prefix+ split that _session_runtime_request_from_body performs — so+ "openrouter::hermes-agent" never matched self._model_name and leaked+ through as a literal session override.+ """+ app = _create_app(auth_adapter)+ app.router.add_post("/api/sessions", auth_adapter._handle_create_session)++ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ "/api/sessions",+ json={"model": f"openrouter::{auth_adapter._model_name}"},+ headers={"Authorization": "Bearer sk-secret"},+ )+ assert resp.status == 201+ data = await resp.json()+ assert data["session"]["model"] is None+# ---------------------------------------------------------------------------# _api_key_passes_startup_guard — fail-closed on an unverifiable keydiff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.pyindex 5e93d74371b..95b44aead48 100644--- a/tests/gateway/test_session_api.py+++ b/tests/gateway/test_session_api.py@@ -401,6 +401,60 @@ async def test_session_chat_resolves_stored_model_route_alias(session_db, monkeyassert kwargs["session_model"] is None+async def test_session_chat_treats_pre_existing_poisoned_row_as_no_model(session_db):+ """A session row created before the alias-leak fix may still have the+ virtual model alias (e.g. "hermes-agent") persisted literally as its+ model. Reading that back must NOT thread it through as a raw+ session_model override — it must fall through to the global default,+ exactly like a row that never had a model at all (#session-model-+ alias-leak)."""+ adapter = APIServerAdapter(PlatformConfig(enabled=True))+ adapter._session_db = session_db+ session_id = session_db.create_session(+ "poisoned-session", "api_server", model=adapter._model_name+ )++ mock_run = AsyncMock(return_value=({"final_response": "ok", "session_id": session_id}, {"total_tokens": 1}))+ app = _create_session_app(adapter)+ with patch.object(adapter, "_run_agent", mock_run):+ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ f"/api/sessions/{session_id}/chat",+ json={"message": "hi"},+ )+ assert resp.status == 200++ _, kwargs = mock_run.call_args+ assert kwargs["session_model"] is None+++async def test_session_chat_stream_treats_pre_existing_poisoned_row_as_no_model(session_db):+ """Streaming twin of the above: the SSE chat path must apply the same+ guard against a pre-existing poisoned session row."""+ adapter = APIServerAdapter(PlatformConfig(enabled=True))+ adapter._session_db = session_db+ session_id = session_db.create_session(+ "poisoned-stream-session", "api_server", model=adapter._model_name+ )++ async def fake_run(**kwargs):+ return {"final_response": "ok", "session_id": session_id}, {"total_tokens": 1}++ app = _create_session_app(adapter)+ with patch.object(adapter, "_run_agent", side_effect=fake_run) as mock_run:+ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(+ f"/api/sessions/{session_id}/chat/stream",+ json={"message": "hi"},+ )+ assert resp.status == 200++ _, kwargs = mock_run.call_args+ assert kwargs["session_model"] is None++def _register_session_model_route(app, adapter):app.router.add_post("/api/sessions/{session_id}/model", adapter._handle_session_model_lock)