The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: gate the legacy WS fallback on the ticket's grant and profile
Tekniumbf7ea2157089
diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.pyindex adc2a890601..67c5db187af 100644--- a/tests/tui_gateway/test_tui_gateway_ws.py+++ b/tests/tui_gateway/test_tui_gateway_ws.py@@ -399,3 +399,73 @@ def test_ws_transport_preserves_cross_batch_order():asyncio.run(scenario())+_INTERACTIVE = frozenset({"session:create", "session:read", "session:submit", "session:control",+ "session:approve", "session:respond"})+++def _drive_authority_fallback(monkeypatch, *, capabilities, profile_id, method):+ """One RPC through handle_ws on an authority connection whose dispatch answers -32601, so the+ request takes the legacy-fallback branch (R2-M3). Returns the reply frame for id 1."""+ import gateway.session_controls as session_controls++ class FakeConnection:+ def __init__(self, authority, transport, identity, operator=False):+ self.actor = type("Actor", (), {"capabilities": frozenset(capabilities), "profile_id": profile_id})()++ async def dispatch(self, req):+ return {"jsonrpc": "2.0", "id": req["id"], "error": {"code": -32601, "message": "unknown method"}}++ async def close(self):+ pass++ monkeypatch.setattr(session_controls, "AuthorityConnection", FakeConnection)+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)+ sent, inbound = [], [json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": {}})]++ class FakeWS:+ scope = {"hermes.session_authority": object()}++ async def accept(self, **_kw):+ pass++ async def send_text(self, line):+ sent.extend(json.loads(part) for part in line.splitlines() if part.strip())++ async def receive_text(self):+ if inbound:+ return inbound.pop()+ raise ws_mod._WebSocketDisconnect()++ async def close(self, **_kw):+ pass++ asyncio.run(ws_mod.handle_ws(FakeWS(), auth_identity={"user_id": "u"}))+ return next(frame for frame in sent if frame.get("id") == 1)+++def test_legacy_fallback_requires_the_interactive_grant(monkeypatch):+ """A worker-adoption ticket (or any connection without the authority's interactive grant) must+ not reach general legacy dispatch after an authority -32601; an interactive one still does."""+ ran = []+ monkeypatch.setitem(server._methods, "probe.legacy",+ lambda rid, params: ran.append(rid) or {"jsonrpc": "2.0", "id": rid, "result": {}})+ launch = str(server._launch_home())+ for restricted in ({"worker:adopt"}, set()):+ reply = _drive_authority_fallback(monkeypatch, capabilities=restricted, profile_id=launch, method="probe.legacy")+ assert reply["error"]["code"] == -32601 and ran == []+ reply = _drive_authority_fallback(monkeypatch, capabilities=_INTERACTIVE, profile_id=launch, method="probe.legacy")+ assert reply["result"] == {} and ran == [1]+++def test_legacy_fallback_keeps_the_ticket_profile_for_sessionless_scoped_handlers(monkeypatch, tmp_path):+ """A secondary-profile ticket's sessionless ``@_profile_scoped`` legacy call runs in THAT profile's+ home, not the launch profile's."""+ from hermes_constants import get_hermes_home++ secondary = tmp_path / "profiles" / "l106742sec"+ secondary.mkdir(parents=True)+ monkeypatch.setitem(server._methods, "probe.scoped", server._profile_scoped(+ lambda rid, params: {"jsonrpc": "2.0", "id": rid, "result": {"home": str(get_hermes_home())}}))+ reply = _drive_authority_fallback(monkeypatch, capabilities=_INTERACTIVE, profile_id=str(secondary),+ method="probe.scoped")+ assert reply["result"]["home"] == str(secondary)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex bf946cba91e..bc68bbe4df1 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -634,8 +634,10 @@ def _profile_scoped(handler):home = _profile_home(p.get("profile"))profile_home = str(home) if home else Noneelse:+ # Sessionless: the authority ticket's profile (WS legacy fallback), else the launch one.+ from tui_gateway.ws_legacy_fallback import connection_profile_homesession = _sessions.get(str(p.get("session_id") or ""))- profile_home = session.get("profile_home") if isinstance(session, dict) else None+ profile_home = session.get("profile_home") if isinstance(session, dict) else connection_profile_home()with _session_profile_runtime_scope({"profile_home": profile_home or None}):return handler(rid, params)return wrapperdiff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex c1d5490d13b..e1da25e6a3c 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -19,6 +19,7 @@ from tui_gateway import serverfrom agent.message_sanitization import _sanitize_surrogatesfrom tui_gateway.event_replay import replay_epochfrom tui_gateway.transport import serialize_frame+from tui_gateway.ws_legacy_fallback import dispatch_legacy, legacy_fallback_allowed_log = logging.getLogger(__name__)@@ -335,12 +336,14 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:try:if authority_connection is not None:resp = await authority_connection.dispatch(req)- if _is_unknown_method(resp) and req_method in server._methods:+ actor = authority_connection.actor+ if (_is_unknown_method(resp) and req_method in server._methods+ and legacy_fallback_allowed(actor)):# Session verbs live on the authority; everything else the sidecar still# registers (pet, wake word, active-session list, connectors) keeps its# legacy handler. A real -32601 reaches the client only for methods# neither side knows, which is what its version-skew notice keys on.- resp = await asyncio.to_thread(server.dispatch, req, transport)+ resp = await asyncio.to_thread(dispatch_legacy, server, req, transport, actor)else:resp = await asyncio.to_thread(server.dispatch, req, transport)except Exception:diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.pynew file mode 100644index 00000000000..235e2d98174--- /dev/null+++ b/tui_gateway/ws_legacy_fallback.py@@ -0,0 +1,53 @@+"""Legacy-handler fallback for authority-backed WebSocket connections.++Session verbs live on the session authority; methods it answers ``-32601`` for may still have a+legacy sidecar handler (pet, wake word, connectors, config). That fallback must not widen what+the connection's ticket grants (R2-M3):++* only connections holding the authority's full interactive grant reach legacy dispatch — a+ worker-adoption ticket (``{'worker:adopt'}``) or a capability-less connection keeps the+ authority's ``-32601``;+* a ticket bound to a secondary profile keeps that profile's scope: sessionless+ ``@_profile_scoped`` handlers read :func:`connection_profile_home` instead of defaulting to the+ launch profile.+"""++from __future__ import annotations++import contextvars+from pathlib import Path+from typing import Any++_connection_profile_home: contextvars.ContextVar[str | None] = contextvars.ContextVar(+ "hermes_ws_connection_profile_home", default=None)+++def legacy_fallback_allowed(actor: Any) -> bool:+ """True when the connection's grant covers the interactive purpose (the authority's own+ capability map; never a second list that could drift)."""+ from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIES+ return _PURPOSE_CAPABILITIES["interactive"] <= frozenset(getattr(actor, "capabilities", ()) or ())+++def connection_profile_home() -> str | None:+ """The non-launch profile home the current legacy fallback request's ticket is bound to."""+ return _connection_profile_home.get()+++def _foreign_profile_home(server: Any, profile_id: Any) -> str | None:+ home = Path(str(profile_id or ""))+ if not home.is_absolute() or not home.is_dir():+ return None+ if home.resolve() == Path(server._launch_home()).resolve():+ return None+ return str(home)+++def dispatch_legacy(server: Any, req: dict, transport: Any, actor: Any) -> dict | None:+ """Run ``server.dispatch`` with the ticket's profile home bound (call from a worker thread;+ the pool path copies this context, so long handlers see it too)."""+ token = _connection_profile_home.set(_foreign_profile_home(server, getattr(actor, "profile_id", None)))+ try:+ return server.dispatch(req, transport)+ finally:+ _connection_profile_home.reset(token)