The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: compose the existing API into the gateway event loop
Tekniumbac47874ec72
diff --git a/gateway/run_api.py b/gateway/run_api.pynew file mode 100644index 00000000000..b5b4a726107--- /dev/null+++ b/gateway/run_api.py@@ -0,0 +1,82 @@+"""Compose the existing complete HTTP/WS surface into the gateway event loop.++The caller initializes session authority before starting this listener and owns+all runtime services and signals. This module owns only HTTP resources; it does+not bootstrap an agent, scheduler, hosted room, or a second gateway.+"""++import asyncio+from dataclasses import dataclass+import socket+from typing import Any+++@dataclass+class GatewayAPIHandle:+ api_origin: str+ server: Any+ task: asyncio.Task+ app: Any+ socket: socket.socket+++async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -> GatewayAPIHandle:+ from hermes_cli import web_server as web++ # Existing routers/auth helpers share one process-local app. Never rebind it+ # underneath another listener. Multiplex profiles use this same authority.+ if getattr(web.app.state, "gateway_runner", None) is not None:+ raise RuntimeError("gateway API already started")+ web._configure_auth_gate(host, False, None, None)+ config, server = web._build_uvicorn_server(host, port)+ config.timeout_graceful_shutdown = 5+ family, kind, proto, _, address = socket.getaddrinfo(+ host, port, type=socket.SOCK_STREAM,+ )[0]+ listener = socket.socket(family, kind, proto)+ try:+ listener.bind(address)+ listener.setblocking(False)+ except BaseException:+ listener.close()+ raise++ web.app.state.gateway_runner = runner+ web.app.state.bound_host = host+ web.app.state.bound_port = listener.getsockname()[1]+ try:+ if not config.loaded:+ config.load()+ server.lifespan = config.lifespan_class(config)+ await server.startup(sockets=[listener])+ if not server.started or server.should_exit:+ raise RuntimeError("gateway API lifespan startup failed")+ except BaseException:+ listener.close()+ web.app.state.gateway_runner = None+ if hasattr(server, "lifespan") and not server.lifespan.should_exit:+ await server.lifespan.shutdown()+ raise++ async def serve():+ try:+ await server.main_loop()+ finally:+ try:+ await server.shutdown(sockets=[listener])+ finally:+ listener.close()+ web.app.state.gateway_runner = None++ task = asyncio.create_task(serve(), name="gateway-api")+ origin_host = f"[{host}]" if ":" in host else host+ return GatewayAPIHandle(+ api_origin=f"http://{origin_host}:{web.app.state.bound_port}",+ server=server, task=task, app=web.app, socket=listener,+ )+++async def stop_gateway_api(handle: GatewayAPIHandle) -> None:+ """Drain sockets without stopping the session authority or taking signals."""+ handle.server.should_exit = True+ await asyncio.shield(handle.task)diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex f1055eaacf2..4e2d3be3b35 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -129,7 +129,7 @@ def _start_desktop_cron_ticker(stop_event: "threading.Event", interval: int = 60_DESKTOP_MCP_DISCOVERY_DELAY_S = 1.0-from hermes_cli.web_server_app import standalone_lifespan # noqa: E402+from hermes_cli.web_server_app import app_lifespan # noqa: E402def _app_state_default(app: "FastAPI", name: str, factory):@@ -154,7 +154,7 @@ def _get_pty_active_session_files(app: "FastAPI") -> dict[str, Path]:return _app_state_default(app, "pty_active_session_files", dict)-app = FastAPI(title="Hermes Agent", version=__version__, lifespan=standalone_lifespan)+app = FastAPI(title="Hermes Agent", version=__version__, lifespan=app_lifespan)# Memory-provider OAuth connect routes live in the memory layer, not here.diff --git a/hermes_cli/web_server_app.py b/hermes_cli/web_server_app.pyindex 2344d865b15..000052506a5 100644--- a/hermes_cli/web_server_app.py+++ b/hermes_cli/web_server_app.py@@ -146,3 +146,33 @@ async def standalone_lifespan(app: "FastAPI"):passif os.getenv("HERMES_DESKTOP") == "1":_terminate_desktop_managed_gateway()+++@asynccontextmanager+async def http_lifespan(app: FastAPI):+ """The gateway already owns schema, rooms, scheduler and model services."""+ from hermes_cli.web_server import _dashboard_selftest_loop+ from hermes_cli.web_server_chat import PTY_REGISTRY++ app.state.event_channels = {}+ app.state.event_lock = asyncio.Lock()+ app.state.pty_active_session_files = {}+ app.state.chat_argv_lock = asyncio.Lock()+ tasks = [+ asyncio.create_task(run_reaper(PTY_REGISTRY), name="gateway-api-pty-reaper"),+ asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),+ ]+ try:+ yield+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ await PTY_REGISTRY.close_all()+++@asynccontextmanager+async def app_lifespan(app: FastAPI):+ lifespan = http_lifespan if getattr(app.state, "gateway_runner", None) is not None else standalone_lifespan+ async with lifespan(app):+ yielddiff --git a/tests/gateway/test_runtime_api.py b/tests/gateway/test_runtime_api.pynew file mode 100644index 00000000000..60cc02b40a5--- /dev/null+++ b/tests/gateway/test_runtime_api.py@@ -0,0 +1,78 @@+"""Real TCP HTTP/WS coverage for the gateway-owned API lifecycle."""++import asyncio+import json+import signal++import httpx+import pytest+from websockets.asyncio.client import connect+from websockets.exceptions import InvalidStatus+++async def test_http_lifespan_does_not_start_or_stop_runtime_services(monkeypatch):+ from hermes_cli import web_server as web+ from tui_gateway import methods_groups++ calls = []+ monkeypatch.setenv("HERMES_DESKTOP", "1")+ for name in ("_warm_gateway_module", "_eager_reconcile_own_session_db",+ "_start_desktop_cron_ticker", "_terminate_desktop_managed_gateway"):+ monkeypatch.setattr(web, name, lambda *a, _name=name, **k: calls.append(_name))+ for name in ("start_hosted_room_service", "stop_hosted_room_service"):+ monkeypatch.setattr(methods_groups, name, lambda *a, _name=name, **k: calls.append(_name))+ # A real gateway owns these services; HTTP must not acquire or release them.+ monkeypatch.setattr(web.app.state, "gateway_runner", object(), raising=False)+ async with web.app.router.lifespan_context(web.app):+ await asyncio.sleep(0)+ assert calls == []+ assert calls == []+++async def test_owner_serves_existing_routes_and_ws_without_signal_ownership(monkeypatch, tmp_path):+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from hermes_cli import web_server as web++ from gateway.run import GatewayRunner+ from gateway.config import GatewayConfig++ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "gateway-sessions"))+ assert runner.adapters == {}+ before = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}+ handle = await start_gateway_api(runner)+ try:+ assert handle.api_origin == f"http://127.0.0.1:{web.app.state.bound_port}"+ assert web.app.state.bound_port > 0+ assert web.app.state.gateway_runner is runner+ assert before == {sig: signal.getsignal(sig) for sig in before}+ auth = {"Authorization": f"Bearer {web._SESSION_TOKEN}"}+ async with httpx.AsyncClient(base_url=handle.api_origin) as client:+ assert (await client.get("/api/config/raw")).status_code == 401+ assert (await client.get("/api/config/raw", headers=auth)).status_code == 200+ assert (await client.post("/api/ws-ticket")).status_code in (401, 403)+ assert (await client.get("/api/config/raw", headers={**auth, "Host": "attacker.invalid"})).status_code == 400+ url = handle.api_origin.replace("http:", "ws:") + "/api/ws"+ with pytest.raises(InvalidStatus) as rejected:+ async with connect(url):+ pass+ assert rejected.value.response.status_code == 403+ async with connect(url + "?token=" + web._SESSION_TOKEN) as ws:+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "ping", "params": {}}))+ while True:+ reply = json.loads(await asyncio.wait_for(ws.recv(), 10))+ if reply.get("id") == 1:+ break+ assert "result" in reply, reply+ with pytest.raises(RuntimeError, match="already"):+ await start_gateway_api(runner)+ finally:+ await stop_gateway_api(handle)+ if runner._session_db is not None:+ runner._session_db.close()+ await stop_gateway_api(handle)+ assert before == {sig: signal.getsignal(sig) for sig in before}+ with pytest.raises(httpx.ConnectError):+ async with httpx.AsyncClient() as client:+ await client.get(handle.api_origin + "/api/config/raw")