Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model-hub): tell the engine's own 401 from an upstream's before blaming the Source (#2764)
Call White10f6b8d38418
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex e2666bab5..b9d5dcbe2 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -1194,6 +1194,15 @@ scenarios:test:- tests/test_model_hub_transport_leases.py::test_an_engine_that_lost_its_configuration_restarts_only_once_its_streams_end- tests/test_model_hub_runtime.py::test_an_engine_that_lost_its_configuration_is_reported_once_and_restarted_by_its_drainer+ - id: MH-RUNTIME-015+ name: >-+ A pre-output 401 is the engine's own only when its engine-local model listing refuses the same gateway key;+ then the turn ends as the engine being down, the Source keeps its health and the engine is checked again,+ while an upstream's identical 401 still settles the Source+ status: covered+ kind: recovery+ layer: contract+ test: tests/test_model_hub_retry_lifecycle.py::test_a_401_the_engine_itself_gave_spares_the_source- id: MH-USAGE-001name: Tokens an upstream reported before the turn ended are still meteredstatus: covereddiff --git a/tests/test_model_hub_retry_lifecycle.py b/tests/test_model_hub_retry_lifecycle.pyindex 4824344b2..681102ec3 100644--- a/tests/test_model_hub_retry_lifecycle.py+++ b/tests/test_model_hub_retry_lifecycle.py@@ -86,7 +86,7 @@ async def gateway_client(service, backend, model):@asynccontextmanager-async def loopback_engine(tmp_path, service, respond):+async def loopback_engine(tmp_path, service, respond, *, models=None):"""Use the production client/admission/stream observer against local HTTP."""config = service.store.load()source = config.sources[0]@@ -96,6 +96,8 @@ async def loopback_engine(tmp_path, service, respond):state.sync_sources(service._bindings(config))app = web.Application()app.router.add_post("/{path:.*}", respond)+ if models is not None:+ app.router.add_get("/v1/models", models)runner = web.AppRunner(app, handler_cancellation=True)await runner.setup()await web.TCPSite(runner, "127.0.0.1", 0).start()@@ -440,6 +442,44 @@ def test_a_usage_cap_cools_its_source_as_quota_until_the_upstream_reset(tmp_pathasyncio.run(run())[email protected]("engine_refuses", [True, False], ids=["engine", "upstream"])+def test_a_401_the_engine_itself_gave_spares_the_source(tmp_path, engine_refuses):+ """MH-RUNTIME-015: the engine's own 401 is told from an upstream's by a witness no upstream answers (#2755).++ The bodies are identical, as an upstream JSON error passes through the+ engine unchanged. Only the engine-local listing refusing the same key makes+ the 401 the engine's: the turn ends as the engine being down, the Source+ keeps its health, and the next admission checks the engine again.+ """+ async def run():+ service, _clock, models = configured_service(tmp_path)+ before = service.store.load().sources[0].state++ async def respond(request):+ await request.read()+ return web.json_response({"error": "Invalid API key"}, status=401)++ async def listing(_request):+ if engine_refuses:+ return web.json_response({"error": "Invalid API key"}, status=401)+ return web.json_response({"object": "list", "data": []})++ rechecks = []+ async with loopback_engine(tmp_path, service, respond, models=listing) as (adapter, _engine):+ adapter.supervisor.recheck_engine = lambda: rechecks.append(True)+ async with gateway_client(service, "codex", models["codex"]) as (_gateway, client, url, headers):+ async with client.post(url, headers=headers, json={"model": "shared-model"}) as response:+ assert response.status >= 400+ state = service.store.load().sources[0].state+ if engine_refuses:+ assert state == before+ assert rechecks == [True]+ else:+ assert (state.status, state.detail_key) == ("needs_action", "models.source.needs_action.credential_revoked")+ assert rechecks == []+ asyncio.run(run())++_SPEND_LIMIT = ("needs_action", "models.source.needs_action.spend_limit_reached")diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 6b8c1177f..438ee192d 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -30,6 +30,7 @@ from core.handlers.model_hub.adapter import (EngineHealth,OAuthSubmissionRejectedError,OriginNotAllowedError,+ RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,RuntimePlatformUnsupportedError,@@ -55,7 +56,7 @@ from vibe.model_hub_runtime import installer as runtime_installer_modulefrom vibe.model_hub_runtime import supervisor as supervisor_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapterfrom vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog, official_models_dev_provider-from vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnection+from vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnection, completed_handlefrom vibe.model_hub_runtime.config import expected_model_names, write_engine_configfrom vibe.model_hub_runtime.environment import engine_subprocess_environmentfrom vibe.model_hub_runtime.installer import (@@ -2944,6 +2945,14 @@ def test_adapter_provisions_probes_and_revokes_credential(tmp_path: Path) -> Nonasyncio.run(run(base_url, handler))+def _served_handle(source, model_id):+ """A real handle for a call the stub engine served: the adapter reads its outcome."""+ return completed_handle(RawCallOutcome(+ kind=RawOutcomeKind.SUCCESS, http_status=200, error_code=None, redacted_message=None,+ stream_started=False, model_id=model_id, source_id=source.source_id,+ ))++def _write_mock_engine(path: Path,*,@@ -4649,7 +4658,7 @@ def test_adapter_uses_origin_protocol_for_engine_translation(self.request_protocol = request_protocolself.request_headers = request_headerson_transport_done()- return object()+ return _served_handle(source, model_id)class Supervisor:def __init__(self, client: Client) -> None:@@ -4816,7 +4825,7 @@ def test_adapter_serializes_source_sync_with_new_invocations(tmp_path: Path) ->):invoked_refs.append(source.credential_ref)on_transport_done()- return object()+ return _served_handle(source, model_id)class Supervisor:def __init__(self) -> None:diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 90e63edc1..933f694d7 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -55,6 +55,7 @@ from vibe.model_hub_runtime.client import (EngineClientError,EngineInvokeHandle,completed_handle,+ engine_refused_gateway_key,probe_models,upstream_api_url,)@@ -2892,7 +2893,7 @@ class CLIProxyEngineAdapter:"claude": "anthropic","codex": "openai_responses",}.get(origin, getattr(request, "protocol", None) or source.protocol)- return await client.invoke(+ handle = await client.invoke(source,model_id,request,@@ -2902,6 +2903,12 @@ class CLIProxyEngineAdapter:on_transport_done=release,on_request_sent=request_sent,)+ if handle.outcome_available and engine_refused_gateway_key(await handle.outcome()):+ # The engine's last health check vouches for it no longer: the+ # next admission checks it, finds the lost configuration, and+ # restores it once the open streams end (#2753, #2755).+ await asyncio.to_thread(self.supervisor.recheck_engine)+ return handleexcept BaseException:release()raisediff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 32d39ed88..6d404bb25 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -632,6 +632,19 @@ class EngineClient:response.close()await session.close()return ended(outcome)+ if response.status == 401 and await self._engine_refuses_gateway_key(session):+ # The engine itself refused Avibe's key, so no upstream judged+ # the Source's credential and nothing was sent past the engine.+ response.close()+ await session.close()+ return ended(_outcome(+ kind=RawOutcomeKind.NETWORK_ERROR,+ source=source,+ model_id=model_id,+ http_status=response.status,+ error_code="engine_down",+ message="engine refused Avibe's gateway key",+ ))outcome = _reduce_protocol_observation(replace(observed_payload,@@ -921,6 +934,28 @@ class EngineClient:os_errno=local_os_errno(exc),) from None+ async def _engine_refuses_gateway_key(self, session: aiohttp.ClientSession) -> bool:+ """Whether the engine itself refuses Avibe's gateway key (#2755).++ A 401 body cannot tell the engine's refusal from an upstream's: the engine+ passes an upstream's JSON error body through unchanged, so a relay+ answering ``{"error":"Invalid API key"}`` reads exactly like the engine's+ own access check. ``/v1/models`` is answered by the engine alone, so the+ same key refused there is the engine's refusal. A witness that cannot be+ asked proves nothing, and the 401 stays the upstream's.+ """++ try:+ async with session.get(+ self._url("/v1/models"),+ headers={"Authorization": f"Bearer {self.connection.gateway_token}"},+ timeout=aiohttp.ClientTimeout(total=min(self.timeout, 2.0)),+ allow_redirects=False,+ ) as witness:+ return witness.status == 401+ except (asyncio.TimeoutError, aiohttp.ClientError):+ return False+def _url(self, path: str, *, query: Mapping[str, str] | None = None) -> str:url = f"{self.connection.base_url.rstrip('/')}{path}"if query:@@ -1360,6 +1395,16 @@ def _project_model_inventory_before_deadline()+def engine_refused_gateway_key(outcome: RawCallOutcome) -> bool:+ """Whether a call ended on the engine refusing Avibe's own gateway key, which the client witnessed."""++ return (+ outcome.kind is RawOutcomeKind.NETWORK_ERROR+ and outcome.error_code == "engine_down"+ and outcome.http_status == 401+ )++def _is_local_model_registration_failure(status: int,payload: bytes,diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.pyindex 012445de9..00056ac15 100644--- a/vibe/model_hub_runtime/supervisor.py+++ b/vibe/model_hub_runtime/supervisor.py@@ -142,6 +142,11 @@ class EngineSupervisor:self._stop_locked()return self._start_locked()+ def recheck_engine(self) -> None:+ """Make the next call check the running engine instead of trusting its last passed check."""+ with self._lock:+ self._verified_at = None+def restart_lost_engine(self) -> None:"""Restart an engine that lost its configuration, from the config Avibe renders.