The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui-gateway): legacy fallback verbs run in a profile-bound ticket's own profile
Tekniume8ee0324f395
diff --git a/tests/tui_gateway/test_legacy_fallback_ticket_profile_verbs.py b/tests/tui_gateway/test_legacy_fallback_ticket_profile_verbs.pynew file mode 100644index 00000000000..50b1b37ffec--- /dev/null+++ b/tests/tui_gateway/test_legacy_fallback_ticket_profile_verbs.py@@ -0,0 +1,66 @@+"""N86: every legacy-fallback verb from a ticket bound to a secondary profile runs in THAT profile.++Only ``@_profile_scoped`` handlers and two hand-fixed ones read the connection's profile; the+account connector path (``_profile_home(request.profile)`` with no ``profile``) and billing (which+ignores ``profile`` and resolves the Nous token through the runtime scope) ran in the launch+profile, so bee's Ink connected accounts and charged top-ups on default's portal account.+"""+import threading+import types+from pathlib import Path++import pytest+++def homes(tmp_path, monkeypatch):+ from tui_gateway import server+ launch = tmp_path / 'root'+ bee = launch / 'profiles' / 'bee'+ bee.mkdir(parents=True)+ monkeypatch.setenv('HERMES_HOME', str(launch))+ monkeypatch.setattr(server, '_hermes_home', launch)+ return server, launch, bee+++def _call(server, profile_id, method, params):+ from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIES+ from tui_gateway.ws_legacy_fallback import dispatch_legacy+ actor = types.SimpleNamespace(profile_id=str(profile_id), capabilities=frozenset(_PURPOSE_CAPABILITIES['interactive']))+ written, done = [], threading.Event()+ transport = types.SimpleNamespace(write=lambda frame: written.append(frame) or done.set() or True)+ reply = dispatch_legacy(server, {'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}, transport, actor)+ return reply if reply is not None else (done.wait(10) and written[0])+++def test_secondary_ticket_runs_connectors_and_billing_in_its_own_profile(homes, monkeypatch):+ import hermes_cli.nous_billing+ import tools.connectors+ import tools.connectors.managed+ from hermes_constants import get_hermes_home+ server, launch, bee = homes+ seen = []++ def rec(label):+ seen.append((label, Path(str(get_hermes_home())).resolve()))++ monkeypatch.setattr(tools.connectors, 'connectors_available', lambda *a, **k: True)+ monkeypatch.setattr(tools.connectors.managed, 'managed_client',+ lambda: types.SimpleNamespace(list_connectors=lambda: rec('list') or []))+ monkeypatch.setattr(hermes_cli.nous_billing, 'post_charge', lambda **k: rec('charge') or {'chargeId': 'c'})+ for method, params in (('connectors.list', {'owner': {'type': 'account'}}), ('billing.charge', {'amount_usd': 5})):+ _call(server, bee, method, params)+ assert {label for label, _ in seen} == {'list', 'charge'}, seen+ assert {home for _, home in seen} == {bee.resolve()}, seen++ # The launch profile's own ticket is unchanged.+ seen.clear()+ _call(server, launch, 'billing.charge', {'amount_usd': 5})+ assert [home for _, home in seen] == [launch.resolve()]+++def test_ticket_whose_home_vanished_is_refused_not_the_launch_profile(homes):+ server, _launch, bee = homes+ gone = bee.parent / 'gone'+ reply = _call(server, gone, 'billing.charge', {'amount_usd': 5})+ assert reply['error']['code'] == 4064, replydiff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.pyindex 680a5ddbe3d..1b049d7538c 100644--- a/tui_gateway/ws_legacy_fallback.py+++ b/tui_gateway/ws_legacy_fallback.py@@ -14,6 +14,7 @@ the connection's ticket grants (R2-M3):from __future__ import annotations+import contextlibimport contextvarsfrom pathlib import Pathfrom typing import Any@@ -69,14 +70,48 @@ def connection_profile_home() -> str | None:def _foreign_profile_home(server: Any, profile_id: Any) -> str | None:+ """The ticket's non-launch home, or None for the launch profile. Raises when the ticket names a+ home that stopped being a directory: that is a refusal, never the launch profile (N86)."""home = Path(str(profile_id or ""))- if not home.is_absolute() or not home.is_dir():+ if not home.is_absolute():return None+ if not home.is_dir():+ raise FileNotFoundError(str(home))if home.resolve() == Path(server._launch_home()).resolve():return Nonereturn str(home)+def _ticket_profile_request(server: Any, req: dict, home: str) -> tuple[dict, str | None]:+ """Bind a non-launch ticket's profile into a legacy verb (N86). The verb runs in the ticket's+ home, or in the one an explicit ``profile`` names (Desktop's host-scoped routing), so handlers+ that ignore ``profile`` (billing, usage) resolve through that runtime scope instead of the+ launch home. A method whose contract declares ``profile`` and got none is handed the ticket's+ own profile name (refused when that name does not resolve to the ticket's home). Returns the+ request plus the home to scope ("" = launch), or an error frame and None."""+ from hermes_constants import profile_name_for_home+ from tui_gateway.contracts.registry import METHODS+ params = req.get("params") if isinstance(req.get("params"), dict) else {}+ refused = {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4064, "message": "profile unavailable"}}+ if explicit := str(params.get("profile") or "").strip():+ try:+ named = server._profile_home(explicit)+ except Exception:+ return refused, None+ return req, str(named) if named else ""+ contract = METHODS.get(req.get("method"))+ if contract is None or "profile" not in contract.params.model_fields:+ return req, home+ name = profile_name_for_home(home)+ try:+ resolved = server._profile_home(name) if name else None+ except (OSError, ValueError):+ resolved = None+ if resolved is None or Path(resolved).resolve() != Path(home).resolve():+ return refused, None+ return dict(req, params={**params, "profile": name}), home++def _own_profile_read(server: Any, req: dict, home: str) -> dict:"""A store-wide session read for a ticket bound to the non-launch *home*. Those handlers defaultto the LAUNCH profile's store and ``session.active_list`` lists every profile's live sessions, so@@ -107,14 +142,25 @@ def dispatch_legacy(server: Any, req: dict, transport: Any, actor: Any) -> dictactions, refusal = _PROCESS_GLOBAL_ACTIONS.get(req.get("method"), ((), ""))if (req.get("params") or {}).get("action", "status") in actions:return {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4030, "message": refusal}}- home = _foreign_profile_home(server, getattr(actor, "profile_id", None))+ try:+ home = _foreign_profile_home(server, getattr(actor, "profile_id", None))+ except OSError:+ return {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4064, "message": "profile unavailable"}}+ scope = contextlib.nullcontext()if home is not None and req.get("method") in _SESSION_FALLBACK_ALLOWED:scoped = _own_profile_read(server, req, home)if "result" in scoped or "error" in scoped:return scopedreq = scoped+ elif home is not None:+ req, target = _ticket_profile_request(server, req, home)+ if target is None:+ return req+ if target:+ scope = server._session_profile_runtime_scope({"profile_home": target})token = _connection_profile_home.set(home)try:- return server.dispatch(req, transport)+ with scope:+ return server.dispatch(req, transport)finally:_connection_profile_home.reset(token)