The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: execute attached websocket turns on the messaging live agent
Teknium47fbfd4ca545
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex ccc3772aad7..7661ec6a06f 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -1202,6 +1202,12 @@ class GatewayInboundMixin:if _reply is not None:return _reply+ authority = getattr(self, 'session_authority', None)+ if authority is not None and not event.get_command() and not is_internal:+ from gateway.session_ingress import admit_message, executing_admission+ if not executing_admission.get():+ return await admit_message(authority, event)+# Evict a leaked/reaped ``_running_agents`` slot before the busy-session fast-path.self._hm_evict_idle_stale_agent(_quick_key)if self._is_session_running(_quick_key):diff --git a/gateway/session_authority.py b/gateway/session_authority.pynew file mode 100644index 00000000000..5e56897719a--- /dev/null+++ b/gateway/session_authority.py@@ -0,0 +1,169 @@+"""Gateway-owned live sessions and canonical durable FIFO scheduling.++Only the runtime bootstrap holding profile ownership may initialize this service.+Transport attachment never constructs an agent or takes a turn lease.+"""+from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+import uuid++from gateway.session_contract import (+ AdmissionReceipt, Principal, SessionHandle, SessionRef, Submission,+ SubscriptionSnapshot,+)+from hermes_state_runtime import (+ RuntimeStoreError, admit_session_input, begin_runtime_epoch,+ cancel_session_input, claim_session_input, get_session_admission,+ list_session_admissions, recover_session_inputs, settle_session_input,+)+++@dataclass+class LiveSession:+ source: object+ route: str+ task: asyncio.Task | None = None+ subscribers: dict = field(default_factory=dict)+ sequence: int = 0+++class SessionAuthority:+ def __init__(self, runner, *, profile_id, instance_id, db, epoch):+ self.runner = runner+ self.profile_id = profile_id+ self.instance_id = instance_id+ self.db = db+ self.epoch = epoch+ self.sessions = {}+ self.waiters = {}+ self.events = {}+ self.native_events = {}++ def authorize(self, actor, ref, capability):+ if actor.profile_id != self.profile_id or ref.profile_id != self.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if capability not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ if ref.session_id not in self.sessions:+ raise RuntimeStoreError('not_found')++ def register(self, source):+ entry = self.runner.session_store.get_or_create_session(source)+ sid = entry.session_id+ self.sessions.setdefault(sid, LiveSession(source, entry.session_key))+ # SessionStore reserves routing metadata before the first AIAgent exists.+ if self.db.get_session(sid) is None:+ self.db.create_session(sid, source=source.platform.value)+ return SessionRef(self.profile_id, sid)++ def agent(self, ref):+ return self.runner._cached_agent_for(self.sessions[ref.session_id].route)++ def _handle(self, ref):+ row = self.db.get_session(ref.session_id)+ pending = list_session_admissions(self.db, session_id=ref.session_id)+ state = 'unknown' if any(r['status'] == 'unknown' for r in pending) else (+ 'running' if any(r['status'] == 'started' for r in pending) else 'idle')+ return SessionHandle(ref, self.instance_id, self.epoch, row['runtime_revision'],+ row['runtime_generation'], state)++ async def resolve(self, actor, ref):+ self.authorize(actor, ref, 'session:read')+ return self._handle(ref)++ async def attach(self, actor, ref):+ self.authorize(actor, ref, 'session:read')+ live = self.sessions[ref.session_id]+ subscription = uuid.uuid4().hex+ live.subscribers[subscription] = actor+ return SubscriptionSnapshot(subscription, self._handle(ref), self.instance_id,+ live.sequence, tuple(self.db.get_messages_as_conversation(ref.session_id)),+ tuple(self._receipt(r) for r in list_session_admissions(+ self.db, session_id=ref.session_id)), ())++ async def detach(self, actor, subscription_id):+ for live in self.sessions.values():+ if subscription_id in live.subscribers:+ if live.subscribers[subscription_id] != actor:+ raise RuntimeStoreError('permission_denied')+ del live.subscribers[subscription_id]+ return+ raise RuntimeStoreError('not_found')++ def _receipt(self, row):+ return AdmissionReceipt(row['admission_id'], SessionRef(self.profile_id, row['target_session_id']),+ row['seq'], row['status'], row['outcome'],+ row['owner_epoch'] or self.epoch, row['generation'])++ async def submit(self, actor: Principal, request: Submission):+ self.authorize(actor, request.ref, 'session:submit')+ if request.intent != 'queue' or set(request.payload) != {'text'} or not isinstance(request.payload['text'], str):+ raise RuntimeStoreError('invalid_params')+ row = admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,+ session_id=request.ref.session_id, request_id=request.request_id,+ payload=dict(request.payload), intent=request.intent)+ live = self.sessions[request.ref.session_id]+ if live.task is None or live.task.done():+ live.task = asyncio.create_task(self._drain(request.ref))+ return self._receipt(row)++ async def receipt(self, actor, ref, admission_id):+ self.authorize(actor, ref, 'session:submit')+ row = get_session_admission(self.db, admission_id=admission_id)+ if row is None or row['target_session_id'] != ref.session_id:+ raise RuntimeStoreError('not_found')+ if row['principal_id'] != actor.subject and 'session:control' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ return self._receipt(row)++ async def cancel_queued(self, actor, ref, admission_id):+ await self.receipt(actor, ref, admission_id)+ return self._receipt(cancel_session_input(self.db, epoch=self.epoch, admission_id=admission_id))++ async def interrupt(self, actor, ref, generation):+ self.authorize(actor, ref, 'session:control')+ handle = self._handle(ref)+ if handle.execution_generation != generation:+ raise RuntimeStoreError('stale_generation')+ agent = self.agent(ref)+ if agent is not None and handle.execution_state == 'running':+ agent.interrupt()+ return self._handle(ref)++ async def _drain(self, ref):+ from gateway.session_ingress import execute_admission+ live = self.sessions[ref.session_id]+ while (row := claim_session_input(self.db, epoch=self.epoch, session_id=ref.session_id)) is not None:+ admission_id = row['admission_id']+ try:+ response = await execute_admission(self, ref, row)+ outcome = 'completed'+ except Exception:+ response = 'The admitted turn failed.'+ outcome = 'failed'+ settled = settle_session_input(self.db, epoch=self.epoch, admission_id=admission_id,+ generation=row['generation'], outcome=outcome)+ live.sequence += 1+ frame = {'jsonrpc': '2.0', 'method': 'event', 'params': {+ 'type': 'message.complete', 'session_id': ref.session_id,+ 'payload': {'text': response, 'content': response, 'admission_id': admission_id,+ 'outcome': settled['outcome']}, 'seq': live.sequence}}+ for actor in tuple(live.subscribers.values()):+ transport = self.events.get(actor.transport_id)+ if transport is not None:+ transport.write(frame)+ waiter = self.waiters.pop(admission_id, None)+ if waiter is not None and not waiter.done():+ waiter.set_result(response)+++async def initialize_session_authority(runner, *, profile_id, instance_id):+ """Call after exclusive profile ownership, before connecting adapters/API."""+ db = getattr(runner._session_db, '_db', runner._session_db)+ epoch = begin_runtime_epoch(db, instance_id=instance_id)+ recover_session_inputs(db, epoch=epoch)+ authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)+ runner.session_authority = authority+ return authoritydiff --git a/gateway/session_controls.py b/gateway/session_controls.pynew file mode 100644index 00000000000..9ec4a642070--- /dev/null+++ b/gateway/session_controls.py@@ -0,0 +1,76 @@+"""Authenticated WS projection of the gateway authority; no TUI execution fallback."""+from dataclasses import asdict+import sqlite3+import uuid++from gateway.session_contract import Principal, SessionRef, Submission+from hermes_state_runtime import RuntimeStoreError+++class AuthorityConnection:+ def __init__(self, authority, transport, identity):+ self.authority = authority+ self.transport = transport+ self.actor = Principal(str(identity.get('user_id') or 'authenticated-dashboard'),+ authority.profile_id,+ frozenset({'session:read', 'session:submit', 'session:control'}),+ uuid.uuid4().hex)+ self.subscriptions = {}+ authority.events[self.actor.transport_id] = transport++ async def dispatch(self, request):+ rid = request.get('id')+ method = request.get('method')+ params = request.get('params') or {}+ ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))+ handlers = {'session.resume': self.resume, 'prompt.submit': self.submit,+ 'prompt.receipt': self.receipt, 'prompt.cancel': self.cancel,+ 'session.interrupt': self.interrupt}+ try:+ if method not in handlers:+ raise RuntimeStoreError('invalid_params')+ result = await handlers[method](ref, params)+ return {'jsonrpc': '2.0', 'id': rid, 'result': result}+ except RuntimeStoreError as exc:+ return {'jsonrpc': '2.0', 'id': rid, 'error': {+ 'code': 4001, 'message': exc.reason, 'data': {'reason': exc.reason}}}+ except sqlite3.Error:+ return {'jsonrpc': '2.0', 'id': rid, 'error': {+ 'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}++ async def resume(self, ref, params):+ snapshot = await self.authority.attach(self.actor, ref)+ self.subscriptions[ref.session_id] = snapshot.subscription_id+ return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,+ 'messages': list(snapshot.history), 'message_count': len(snapshot.history),+ 'running': snapshot.handle.execution_state == 'running',+ 'authority_epoch': snapshot.handle.authority_epoch,+ 'execution_generation': snapshot.handle.execution_generation,+ 'pending': [asdict(r) for r in snapshot.pending], 'info': {}}++ async def submit(self, ref, params):+ if ref.session_id not in self.subscriptions:+ raise RuntimeStoreError('permission_denied')+ forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued'}+ if forbidden:+ raise RuntimeStoreError('invalid_params')+ request_id = params.get('submission_id') or params.get('input_id')+ if not isinstance(request_id, str) or not request_id:+ raise RuntimeStoreError('invalid_params')+ receipt = await self.authority.submit(self.actor, Submission(+ request_id, ref, {'text': params.get('text')}, 'queue'))+ return asdict(receipt)++ async def receipt(self, ref, params):+ return asdict(await self.authority.receipt(self.actor, ref, params.get('admission_id')))++ async def cancel(self, ref, params):+ return asdict(await self.authority.cancel_queued(self.actor, ref, params.get('admission_id')))++ async def interrupt(self, ref, params):+ return asdict(await self.authority.interrupt(self.actor, ref, params.get('execution_generation')))++ async def close(self):+ for subscription in self.subscriptions.values():+ await self.authority.detach(self.actor, subscription)+ self.authority.events.pop(self.actor.transport_id, None)diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pynew file mode 100644index 00000000000..36a46a43acd--- /dev/null+++ b/gateway/session_ingress.py@@ -0,0 +1,47 @@+"""Trusted messaging admission and the existing TurnRunner invocation boundary."""+import asyncio+from contextvars import ContextVar+import json+import uuid++from gateway.platforms.event import MessageEvent+from gateway.session_contract import Principal, Submission++executing_admission = ContextVar('executing_admission', default=False)+++async def admit_message(authority, event):+ ref = authority.register(event.source)+ source = event.source+ identity = json.dumps([source.profile, source.platform.value, source.chat_id,+ source.thread_id, source.user_id], separators=(',', ':'))+ actor = Principal('messaging:' + identity, authority.profile_id,+ frozenset({'session:submit'}), '')+ request_id = str(event.message_id or uuid.uuid4().hex)+ receipt = await authority.submit(actor, Submission(request_id, ref, {'text': event.text}, 'queue'))+ if receipt.status == 'terminal':+ return None+ # These are execution envelopes, not a second queue. The durable ledger alone orders claims.+ authority.native_events[receipt.admission_id] = event+ waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())+ return await asyncio.shield(waiter)+++async def execute_admission(authority, ref, row):+ live = authority.sessions[ref.session_id]+ event = authority.native_events.pop(row['admission_id'], None)+ native = event is not None+ if event is None:+ event = MessageEvent(text=row['payload']['text'], source=live.source,+ message_id=row['admission_id'])+ token = executing_admission.set(True)+ try:+ response = await authority.runner._handle_message(event)+ if not native and response:+ adapter = authority.runner._adapter_for_source(event.source)+ if adapter is not None:+ await adapter.send(event.source.chat_id, response,+ metadata={'thread_id': event.source.thread_id})+ return response+ finally:+ executing_admission.reset(token)diff --git a/tests/gateway/fixtures/shared_authority_peer.py b/tests/gateway/fixtures/shared_authority_peer.pynew file mode 100644index 00000000000..e70c2b23459--- /dev/null+++ b/tests/gateway/fixtures/shared_authority_peer.py@@ -0,0 +1,195 @@+"""Disposable production-runtime peer; only provider and vendor wire are synthetic."""++import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import importlib.util+import json+import os+from pathlib import Path+import socket+import sys+import threading+import traceback+++class ModelPeer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(json.dumps({"data": [{"id": "local-wire-stub", "object": "model"}]}).encode())++ def do_POST(self):+ request = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ last = next((m.get("content", "") for m in reversed(request.get("messages", []))+ if m.get("role") == "user"), "")+ marker = "WS_SHARED" if "WS_SHARED" in json.dumps(last) else "MESSAGING_WARM"+ reply = f"LOCAL_ACK_{marker}"+ self.server.requests.append(request)+ base = {"id": "chatcmpl-local", "model": "local-wire-stub", "created": 1}+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream" if request.get("stream") else "application/json")+ self.end_headers()+ if request.get("stream"):+ for delta, finish in [({"role": "assistant", "content": reply}, None), ({}, "stop")]:+ chunk = {**base, "object": "chat.completion.chunk", "choices": [+ {"index": 0, "delta": delta, "finish_reason": finish}]}+ self.wfile.write(("data: " + json.dumps(chunk) + "\n\n").encode())+ self.wfile.flush()+ self.wfile.write(b"data: [DONE]\n\n")+ else:+ self.wfile.write(json.dumps({**base, "object": "chat.completion", "choices": [+ {"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}).encode())+++async def probe():+ import uvicorn+ import websockets+ from gateway.config import Platform, PlatformConfig+ from gateway.platforms.base import BasePlatformAdapter, SendResult+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session import SessionSource+ from hermes_cli import web_server+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket+ from tui_gateway import server+ from run_agent import AIAgent++ class CaptureAdapter(BasePlatformAdapter):+ def __init__(self):+ super().__init__(PlatformConfig(enabled=True, token="local-fixture"), Platform.TELEGRAM)+ self.sent = []++ async def connect(self, *, is_reconnect=False):+ return True++ async def disconnect(self):+ pass++ async def send(self, chat_id, content, reply_to=None, metadata=None):+ self.sent.append(content)+ return SendResult(success=True, message_id=str(len(self.sent)))++ async def edit_message(self, chat_id, message_id, content, *, finalize=False):+ self.sent.append(content)+ return SendResult(success=True, message_id=message_id)++ async def send_typing(self, chat_id, metadata=None):+ pass++ async def get_chat_info(self, chat_id):+ return {"id": chat_id}++ runner = GatewayRunner()+ if importlib.util.find_spec("gateway.session_authority") is not None:+ from gateway.session_authority import initialize_session_authority+ await initialize_session_authority(runner, profile_id="default", instance_id="test-owner")+ adapter = CaptureAdapter()+ runner.adapters[Platform.TELEGRAM] = adapter+ adapter.set_message_handler(runner._handle_message)+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="fixture-chat", chat_type="dm", user_id="fixture-user")+ event = MessageEvent(text="MESSAGING_WARM", source=source, message_id="warm-1")+ await adapter.handle_message(event)+ async with asyncio.timeout(35):+ while adapter._active_sessions:+ await asyncio.sleep(0.05)+ assert event._gateway_accepted, adapter.sent+ assert any("LOCAL_ACK_MESSAGING_WARM" in text for text in adapter.sent), adapter.sent+ entry = runner.session_store.get_or_create_session(source)+ warm_agent = runner._cached_agent_for(entry.session_key)+ assert isinstance(warm_agent, AIAgent), "Messaging warmup must retain a real live agent"++ app = web_server.app+ app.state.auth_required = True+ app.state.session_authority = getattr(runner, "session_authority", None)+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ listener.setblocking(False)+ port = listener.getsockname()[1]+ http = uvicorn.Server(uvicorn.Config(app, log_level="warning", lifespan="off", ws="websockets"))+ task = asyncio.create_task(http.serve(sockets=[listener]))+ async with asyncio.timeout(10):+ while not http.started:+ if task.done():+ await task+ await asyncio.sleep(0.01)+ frames = []+ receipt = {"messaging_completed": True, "stored_id": entry.session_id,+ "unauthenticated_rejected": False, "ws_completed": False, "same_agent": False}+ try:+ try:+ async with websockets.connect(f"ws://127.0.0.1:{port}/api/ws"):+ raise AssertionError("Missing WS credential was accepted")+ except websockets.exceptions.InvalidStatus as exc:+ assert exc.response.status_code == 403, str(exc)+ receipt["unauthenticated_rejected"] = True+ ticket = mint_ticket(user_id="fixture-user", provider="fixture")+ async with websockets.connect(f"ws://127.0.0.1:{port}/api/ws?ticket={ticket}") as ws:+ async def until(predicate):+ async with asyncio.timeout(35):+ while True:+ frame = json.loads(await ws.recv())+ frames.append(frame)+ if predicate(frame):+ return frame++ await until(lambda f: f.get("params", {}).get("type") == "gateway.ready")+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "session.resume",+ "params": {"session_id": entry.session_id}}))+ resumed = await until(lambda f: f.get("id") == 1)+ receipt["resume"] = resumed+ if "result" in resumed:+ sid = resumed["result"]["session_id"]+ await ws.send(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "prompt.submit",+ "params": {"session_id": sid, "text": "WS_SHARED", "input_id": "ws-1"}}))+ submitted = await until(lambda f: f.get("id") == 2)+ receipt["submit"] = submitted+ if "result" in submitted:+ terminal = await until(lambda f: f.get("params", {}).get("type") in {"message.complete", "error"})+ receipt["terminal"] = terminal+ receipt["ws_completed"] = "LOCAL_ACK_WS_SHARED" in json.dumps(terminal)+ authority = getattr(runner, 'session_authority', None)+ if authority is not None:+ from gateway.session_contract import SessionRef+ receipt["same_agent"] = authority.agent(SessionRef('default', sid)) is warm_agent+ else:+ receipt["same_agent"] = server._sessions[sid].get("agent") is warm_agent+ receipt["messaging_outputs"] = adapter.sent+ finally:+ Path(os.environ["HERMES_HOME"], "receipt.json").write_text(json.dumps(receipt, indent=2))+ Path(os.environ["HERMES_HOME"], "frames.json").write_text(json.dumps(frames, indent=2))+ http.should_exit = True+ await asyncio.wait_for(task, 10)+ listener.close()+ print(json.dumps(receipt))+++if __name__ == "__main__":+ peer = ThreadingHTTPServer(("127.0.0.1", 0), ModelPeer)+ peer.requests = []+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ base_url = f"http://127.0.0.1:{peer.server_port}/v1"+ os.environ.update(OPENAI_API_KEY="explicit-loopback-fixture", OPENAI_BASE_URL=base_url,+ TELEGRAM_ALLOWED_USERS="fixture-user")+ Path(os.environ["HERMES_HOME"], "config.yaml").write_text(+ f"model:\n default: local-wire-stub\n provider: custom\n base_url: {base_url}\n"+ f"terminal:\n cwd: {os.environ['HERMES_HOME']}\n")+ status = 0+ try:+ asyncio.run(probe())+ except BaseException:+ traceback.print_exc()+ status = 1+ finally:+ peer.shutdown()+ peer.server_close()+ sys.stdout.flush()+ sys.stderr.flush()+ # Disposable child owns all runtime background threads (heartbeats, reapers,+ # provider pools); don't leave a lease-wait executor holding pytest hostage.+ os._exit(status)diff --git a/tests/gateway/test_session_authority.py b/tests/gateway/test_session_authority.pynew file mode 100644index 00000000000..2479d1d1eb3--- /dev/null+++ b/tests/gateway/test_session_authority.py@@ -0,0 +1,31 @@+"""Real messaging ingress and authenticated WS must share one warm agent."""++import json+import os+from pathlib import Path+import subprocess+import sys+++def test_messaging_then_authenticated_ws_reuses_live_agent(tmp_path):+ repo = Path(__file__).resolve().parents[2]+ home = tmp_path / "home"+ home.mkdir()+ state = tmp_path / "state"+ state.mkdir()+ # A fresh interpreter keeps import-time profile caches and background workers+ # away from both the user's state and pytest's process-global fixtures.+ env = {key: os.environ[key] for key in ("PATH", "SYSTEMROOT", "LANG", "TZ") if key in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),+ PYTHONPATH=str(repo), PYTHONUNBUFFERED="1")+ result = subprocess.run(+ [sys.executable, str(Path(__file__).parent / "fixtures" / "shared_authority_peer.py")],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100,+ )+ assert result.returncode == 0, result.stdout + "\n" + result.stderr+ receipt = json.loads((state / "receipt.json").read_text())+ print(json.dumps(receipt, indent=2))+ assert receipt["messaging_completed"], receipt+ assert receipt["unauthenticated_rejected"], receipt+ assert receipt["ws_completed"], receipt+ assert receipt["same_agent"], receiptdiff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex fb7e866a979..001a2ca9c49 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -241,6 +241,7 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:``{user_id, provider}`` recorded at WS-upgrade auth, stored as ``WSTransport.auth_identity`` (the only identityauthority for browser-controller registration); callers that omit it (harnesses, embedded TUI child) get None."""peer, transport = _ws_peer_label(ws), None+ authority_connection = Nonemessages = parse_errors = dispatch_crashes = send_failures = 0disconnect_reason = "not_connected"@@ -264,6 +265,10 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:_disable_nagle(ws)_log.info("ws accepted peer=%s", peer)transport = WSTransport(ws, asyncio.get_running_loop(), peer=peer, auth_identity=auth_identity)+ authority = getattr(getattr(getattr(ws, 'app', None), 'state', None), 'session_authority', None)+ if authority is not None:+ from gateway.session_controls import AuthorityConnection+ authority_connection = AuthorityConnection(authority, transport, auth_identity or {})# resolve_skin() is sync I/O + CPU; pooled so the read loop can drain the frontend's initial RPC burst.skin_payload = await asyncio.to_thread(server.resolve_skin)# change_events: this backend broadcasts pet/cron/sessions.changed, so clients can demote legacy@@ -330,7 +335,10 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:# writes the response itself via transport.write (a separate thread, so that is the safe# path). Inline handlers return the response dict, written here from the loop.try:- resp = await asyncio.to_thread(server.dispatch, req, transport)+ if authority_connection is not None:+ resp = await authority_connection.dispatch(req)+ else:+ resp = await asyncio.to_thread(server.dispatch, req, transport)except Exception:dispatch_crashes += 1_log.exception("ws dispatch crash peer=%s id=%s method=%s", peer, req_id, req_method)@@ -343,6 +351,8 @@ async def handle_ws(ws: Any, *, auth_identity: dict | None = None, subprotocol:except _SendFailed:passfinally:+ if authority_connection is not None:+ await authority_connection.close()reaped_sessions = detached_sessions = 0if transport is not None:server.unregister_live_transport(transport)