The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a host's real 'hermes' profile is never answered by its default profile
Teknium8f9e1954e09a
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 44b82c50856..df3dc3b2aa5 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1540,7 +1540,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):async def profile_prefix_middleware(request: web.Request, handler):profile = self._resolve_request_profile(request)if profile is _PROFILE_REJECTED:- return web.json_response({"error": "Unknown or unconfigured profile"}, status=404)+ from gateway.platforms.api_server_profile_prefix import rejection_response+ return rejection_response(request)token = _api_request_profile.set(profile)try:with self._profile_scope(profile):diff --git a/gateway/platforms/api_server_profile_prefix.py b/gateway/platforms/api_server_profile_prefix.pyindex 89a04341eca..06ec806df2b 100644--- a/gateway/platforms/api_server_profile_prefix.py+++ b/gateway/platforms/api_server_profile_prefix.py@@ -5,8 +5,33 @@ from typing import Anylogger = logging.getLogger(__name__)# The @handle Bot Mode advertises a host's default profile under (apps/desktop hermes-bots-# ``botHandle``); it is a reserved profile name, so it never names a profile of its own.+# ``botHandle``). New profiles cannot take the name, but a pre-reservation profiles/hermes can exist.DEFAULT_PROFILE_HANDLE = "hermes"+# 404 body for a prefix naming no profile here; peers key their @hermes -> /p/default fallback on it.+UNKNOWN_PROFILE_ERROR = "Unknown or unconfigured profile"+++def _handle_is_free() -> bool:+ """The handle aliases the default profile only on a host with no profile of that name: a+ pre-reservation ``profiles/hermes`` (served, parked or standalone) keeps it, so its traffic is+ never answered by the default profile. Fail closed: unknown counts as taken."""+ try:+ from hermes_cli.profiles import profile_exists+ return not profile_exists(DEFAULT_PROFILE_HANDLE)+ except Exception:+ logger.warning("Cannot check for a '%s' profile", DEFAULT_PROFILE_HANDLE, exc_info=True)+ return False+++def rejection_response(request: Any):+ """The 404 for a rejected prefix. A 'hermes' profile this gateway does not serve gets its own+ body, so a peer reads it as "exists elsewhere", never as "no such profile, use default"."""+ from aiohttp import web+ if (request.match_info.get("profile") or "").strip() == DEFAULT_PROFILE_HANDLE and not _handle_is_free():+ return web.json_response({"error": {+ "message": f"Profile '{DEFAULT_PROFILE_HANDLE}' exists on this host but this gateway does not serve it",+ "code": "profile_not_served"}}, status=404)+ return web.json_response({"error": UNKNOWN_PROFILE_ERROR}, status=404)def resolve_request_profile(adapter: Any, request: Any):@@ -14,7 +39,7 @@ def resolve_request_profile(adapter: Any, request: Any):prefix names this gateway's own profile), the served profile name, or ``_PROFILE_REJECTED``(-> 404). Fail closed: a foreign prefix must never be ignored. The default profile's handle``hermes`` reaches the default profile, because peers address the mirror by the handle their- roster shows (#118076); a served profile literally named ``hermes`` still wins."""+ roster shows (#118076), unless the host has a profile literally named ``hermes``."""from gateway.platforms.api_server import _PROFILE_REJECTED, _prefix_names_served_profileprofile = (request.match_info.get("profile") or "").strip()if not profile:@@ -22,7 +47,8 @@ def resolve_request_profile(adapter: Any, request: Any):alias = profile == DEFAULT_PROFILE_HANDLEcfg = getattr(adapter.gateway_runner, "config", None)if not getattr(cfg, "multiplex_profiles", False):- served = _prefix_names_served_profile(profile) or (alias and _prefix_names_served_profile("default"))+ served = _prefix_names_served_profile(profile) or (+ alias and _prefix_names_served_profile("default") and _handle_is_free())return None if served else _PROFILE_REJECTEDtry:from hermes_cli.profiles import profiles_to_serve@@ -33,6 +59,6 @@ def resolve_request_profile(adapter: Any, request: Any):return _PROFILE_REJECTEDif profile in served:return profile- if alias and "default" in served:+ if alias and "default" in served and _handle_is_free():return "default"return _PROFILE_REJECTEDdiff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.pyindex ae640bde206..e020b63752f 100644--- a/hermes_cli/subcommands/peer.py+++ b/hermes_cli/subcommands/peer.py@@ -24,8 +24,9 @@ BOT_CHAT_TITLE = "Bot Chat"_PEER_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")_PROFILE_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")-# The @handle Bot Mode shows for a host's default profile, and the body of the 404 a peer's-# /p/<profile>/ prefix middleware returns for a profile it does not serve (gateway/platforms/api_server.py).+# The @handle Bot Mode shows for a host's default profile, and the body of the 404 a peer returns for+# a /p/<profile>/ prefix naming no profile it has (UNKNOWN_PROFILE_ERROR in+# gateway/platforms/api_server_profile_prefix.py; a 'hermes' profile it has but does not serve differs).DEFAULT_PROFILE_HANDLE = "hermes"_UNKNOWN_PROFILE_ERROR = "Unknown or unconfigured profile"diff --git a/tests/gateway/test_multiplex_api_server_routing.py b/tests/gateway/test_multiplex_api_server_routing.pyindex 0736d156e73..6d7d5573b77 100644--- a/tests/gateway/test_multiplex_api_server_routing.py+++ b/tests/gateway/test_multiplex_api_server_routing.py@@ -96,23 +96,37 @@ class TestApiServerProfileResolution:)+_UNKNOWN = {"error": "Unknown or unconfigured profile"}+_NOT_SERVED = "profile_not_served"++@pytest.mark.asyncio[email protected]("gateway_home,answers", [- ("", {"hermes": 200, "default": 200, "worker": 404}), # default-profile gateway- ("profiles/worker", {"hermes": 404, "default": 404, "worker": 200}), # another named profile- ("profiles/hermes", {"hermes": 200, "default": 404, "worker": 404}), # a real legacy 'hermes'[email protected]("multiplex,gateway_home,legacy_hermes,answers", [+ # Single-profile gateways: the handle is the default profile's, and nobody else's.+ (False, "", None, {"hermes": None, "default": None, "worker": _UNKNOWN}),+ (False, "profiles/worker", None, {"hermes": _UNKNOWN, "default": _UNKNOWN, "worker": None}),+ (False, "profiles/hermes", "live", {"hermes": None, "default": _UNKNOWN}),+ # A real legacy 'hermes' profile the gateway does not serve is never answered by default.+ (False, "", "live", {"hermes": _NOT_SERVED, "default": None}),+ (True, "", None, {"hermes": "default", "worker": "worker"}),+ (True, "", "live", {"hermes": "hermes", "default": "default"}),+ (True, "", "parked", {"hermes": _NOT_SERVED, "default": "default"}),])-async def test_single_profile_gateway_answers_the_hermes_handle_only_for_its_own_profile(- tmp_path, monkeypatch, gateway_home, answers):- """Multiplexing off: '/p/hermes/' is Bot Mode's handle for the default profile (#118076), so a- default-profile gateway serves it, a gateway running another profile refuses it with the- unknown-profile 404 peers key their fallback on, and a real 'hermes' profile keeps its name."""+async def test_hermes_handle_reaches_the_default_profile_only_when_no_hermes_profile_exists(+ tmp_path, monkeypatch, multiplex, gateway_home, legacy_hermes, answers):+ """'/p/hermes/' is Bot Mode's handle for the default profile (#118076): a gateway serving the+ default profile answers it, one running another profile refuses it with the unknown-profile+ 404 peers key their /p/default fallback on, and a host with a real pre-reservation 'hermes'+ profile keeps the name for it (refusing distinctly when this gateway does not serve it)."""root = tmp_path / "root"- for home in (root, root / "profiles" / "worker", root / "profiles" / "hermes"):+ homes = [root, root / "profiles" / "worker"] + ([root / "profiles" / "hermes"] if legacy_hermes else [])+ for home in homes:home.mkdir(parents=True, exist_ok=True)(home / "config.yaml").write_text("{}\n", encoding="utf-8")+ if legacy_hermes == "parked":+ (root / "profiles" / "hermes" / "gateway.parked").write_text("", encoding="utf-8")monkeypatch.setenv("HERMES_HOME", str(root / gateway_home))- adapter = _make_adapter(multiplex=False)+ adapter = _make_adapter(multiplex=multiplex)async def handler(request):return web.json_response({"profile": _api_request_profile.get()})@@ -120,11 +134,15 @@ async def test_single_profile_gateway_answers_the_hermes_handle_only_for_its_ownapp = web.Application(middlewares=[adapter._make_profile_prefix_middleware()])app.router.add_get("/p/{profile}/v1/test", handler)async with TestClient(TestServer(app)) as cli:- for prefix, status in answers.items():+ for prefix, expected in answers.items():resp = await cli.get(f"/p/{prefix}/v1/test")body = await resp.json()- assert (prefix, resp.status) == (prefix, status)- assert body == ({"profile": None} if status == 200 else {"error": "Unknown or unconfigured profile"})+ if expected == _NOT_SERVED:+ assert (prefix, resp.status, body["error"]["code"]) == (prefix, 404, _NOT_SERVED)+ elif expected == _UNKNOWN:+ assert (prefix, resp.status, body) == (prefix, 404, _UNKNOWN)+ else:+ assert (prefix, resp.status, body) == (prefix, 200, {"profile": expected})diff --git a/tests/hermes_cli/test_peer_cmd.py b/tests/hermes_cli/test_peer_cmd.pyindex 02d0ed1e840..dea9de46e47 100644--- a/tests/hermes_cli/test_peer_cmd.py+++ b/tests/hermes_cli/test_peer_cmd.py@@ -47,13 +47,14 @@ class _ProfilePeer(BaseHTTPRequestHandler):served: set = set()probe_status: int = 200+ refusal: dict = {"error": "Unknown or unconfigured profile"}hits: list = []def _answer(self):_, _, profile, rest = (self.path.split("/", 3) + ["", "", "", ""])[:4]type(self).hits.append(self.path)if profile not in type(self).served:- return 404, {"error": "Unknown or unconfigured profile"}+ return 404, type(self).refusalif rest == "health":return type(self).probe_status, {"status": "ok"}if rest.startswith("api/sessions?"):@@ -78,16 +79,22 @@ class _ProfilePeer(BaseHTTPRequestHandler):pass[email protected]("served,probe_status,expected", [- ({"default", "hermes"}, 200, "hermes"), # a real legacy 'hermes' profile keeps precedence- ({"default"}, 200, "default"), # the peer says it has none: the @hermes handle is its default- ({"default", "hermes"}, 503, "hermes"), # a transient failure is no verdict, so never reroute+_NOT_SERVED = {"error": {"message": "Profile 'hermes' exists on this host but this gateway does not serve it"}}++[email protected]("served,probe_status,refusal,expected", [+ ({"default", "hermes"}, 200, None, "hermes"), # a real legacy 'hermes' profile keeps precedence+ ({"default"}, 200, None, "default"), # the peer says it has none: @hermes is its default+ ({"default", "hermes"}, 503, None, "hermes"), # a transient failure is no verdict, so never reroute+ ({"default"}, 200, _NOT_SERVED, None), # it has one but does not serve it: an error, not default])-def test_hermes_handle_reaches_the_profile_the_peer_serves(monkeypatch, capsys, served, probe_status, expected):+def test_hermes_handle_reaches_the_profile_the_peer_serves(+ monkeypatch, capsys, served, probe_status, refusal, expected):"""``box/hermes`` names the peer's real 'hermes' profile when it has one, and its defaultprofile (Bot Mode's @hermes handle, #118076) only when the peer answers it has no such profile;dm, status and stop all address the same mirror."""_ProfilePeer.served, _ProfilePeer.probe_status, _ProfilePeer.hits = served, probe_status, []+ _ProfilePeer.refusal = refusal or {"error": "Unknown or unconfigured profile"}server = HTTPServer(("127.0.0.1", 0), _ProfilePeer)threading.Thread(target=server.serve_forever, daemon=True).start()monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"box": {"url": f"http://127.0.0.1:{server.server_port}"}})@@ -101,6 +108,10 @@ def test_hermes_handle_reaches_the_profile_the_peer_serves(monkeypatch, capsys,finally:server.shutdown()out = [json.loads(line) for line in capsys.readouterr().out.splitlines()]+ if expected is None:+ assert (replies, out) == ([1, 1, 1], [])+ assert {hit.split("/")[2] for hit in _ProfilePeer.hits} == {"hermes"}+ returnassert replies == [0, 0, 0]assert [out[0]["reply"], out[1]["status"], out[2]["status"]] == [f"from {expected}", f"run in {expected}", f"run in {expected}"]