Skip to content

The agent that grows with you

fix(runtime): route every session_authority consumer by the routed profile's home

Teknium02420976354c
diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.py
index 39cc2cfc028..cfaddf95f78 100644
--- a/gateway/platforms/api_server_authority_runs.py
+++ b/gateway/platforms/api_server_authority_runs.py
@@ -4,8 +4,14 @@ from gateway.session_results import admission_result
from hermes_state_runtime import RuntimeStoreError, _row
+def _authority(adapter):
+ """The routed profile's authority: ``/p/<profile>/`` middleware already entered its scope."""
+ from gateway.session_authorities import active_authority
+ return active_authority(adapter.gateway_runner)
+
+
def run_admission(adapter, run_id):
- authority = getattr(adapter.gateway_runner, 'session_authority', None)
+ authority = _authority(adapter)
if authority is None:
return None
with authority.db._read_ctx() as conn:
@@ -39,7 +45,7 @@ def run_projection(adapter, run_id):
async def send_clarify(adapter, *, chat_id, **kwargs):
from gateway.platforms.base import SendResult
- authority = getattr(adapter.gateway_runner, 'session_authority', None)
+ authority = _authority(adapter)
if authority is None or chat_id not in authority.sessions:
return SendResult(success=False, error='No canonical API session')
handle = authority._handle(SessionRef(authority.profile_id, chat_id))
diff --git a/gateway/platforms/api_server_room_dispatch.py b/gateway/platforms/api_server_room_dispatch.py
index ddd483614ba..9eaf1af792f 100644
--- a/gateway/platforms/api_server_room_dispatch.py
+++ b/gateway/platforms/api_server_room_dispatch.py
@@ -26,7 +26,8 @@ async def _ensure_hosted_member_session(self, dispatch: Any) -> str:
f"{dispatch.home_install_id}\0{dispatch.room_id}\0"
f"{dispatch.member_id}\0{dispatch.target_profile}")
session_id = f"room_{hashlib.sha256(seed.encode()).hexdigest()[:32]}"
- authority = getattr(self.gateway_runner, 'session_authority', None)
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self.gateway_runner)
if authority is not None:
from gateway.session_api import bind_api_session
if db is not authority.db:
diff --git a/gateway/platforms/api_server_store.py b/gateway/platforms/api_server_store.py
index 77e78b4cdad..cbe5f4ee752 100644
--- a/gateway/platforms/api_server_store.py
+++ b/gateway/platforms/api_server_store.py
@@ -3,12 +3,11 @@ from pathlib import Path
def selected_session_db(adapter, home):
- authority = getattr(adapter.gateway_runner, 'session_authority', None)
+ from gateway.session_authorities import authority_for_home
+ # Only a home this runtime reserved has a store here; a multiplex route alone is not proof.
+ authority = authority_for_home(adapter.gateway_runner, home)
if authority is None:
return None
- if Path(authority.db.db_path).parent.resolve() != Path(home).resolve():
- # A multiplex route is not evidence that this runtime owns that profile.
- return None
with adapter._session_db_cache_lock:
if adapter._session_db_cache_closed:
return None
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py
index 0c017ea5117..3eebf6272fa 100644
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@ -594,7 +594,8 @@ class WebhookAdapter(BasePlatformAdapter):
return _json_error("Admission unavailable; retry this delivery", 503)
if getattr(event, '_webhook_duplicate', False):
return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)
- authority = self._message_handler.__self__.session_authority
+ from gateway.session_authorities import authority_for_profile_id
+ authority = authority_for_profile_id(self._message_handler.__self__, receipt.ref.profile_id)
task = asyncio.create_task(self._finalize_delivery(event, authority, receipt))
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
diff --git a/gateway/platforms/webhook_delivery.py b/gateway/platforms/webhook_delivery.py
index bdc3c0f7d23..012a03651fd 100644
--- a/gateway/platforms/webhook_delivery.py
+++ b/gateway/platforms/webhook_delivery.py
@@ -60,12 +60,17 @@ def retained_destination(adapter, chat_id):
"""Readback also checks today's connector and authorization; retained data is not a grant."""
from gateway.session_envelope import restore_native, _validate_native
runner = adapter.gateway_runner or getattr(adapter._message_handler, '__self__', None)
- authority = getattr(runner, 'session_authority', None)
- if authority is None:
+ from gateway.session_authorities import active_authority, all_authorities
+ if not all_authorities(runner):
return validate_destination(adapter._delivery_info.get(chat_id))
- rows = authority.db._read_all("""SELECT payload_json FROM session_admissions
+ # The reply leg runs in the routed profile's scope; that ledger holds the destination. A
+ # delivery id is unique per route, so an unscoped caller may search every served ledger.
+ scoped = active_authority(runner)
+ candidates = [scoped] if scoped is not None else all_authorities(runner)
+ query = """SELECT payload_json FROM session_admissions
WHERE json_extract(payload_json, '$.native_text_v1.source.chat_id')=?
- AND json_extract(payload_json, '$.native_text_v1.source.platform')='webhook'""", (chat_id,))
+ AND json_extract(payload_json, '$.native_text_v1.source.platform')='webhook'"""
+ rows = [row for authority in candidates for row in authority.db._read_all(query, (chat_id,))]
if len(rows) != 1:
raise RuntimeStoreError('not_found')
payload = json.loads(rows[0]['payload_json'])
diff --git a/gateway/platforms/webhook_ingress.py b/gateway/platforms/webhook_ingress.py
index 69d94be21e8..4a42e8244e6 100644
--- a/gateway/platforms/webhook_ingress.py
+++ b/gateway/platforms/webhook_ingress.py
@@ -9,9 +9,9 @@ async def producer_scope(adapter, event):
from gateway.run import _async_profile_runtime_scope
from gateway.session_ingress_context import native_callback
+ from gateway.session_authorities import authority_for_home
runner = getattr(adapter._message_handler, '__self__', None)
- authority = getattr(runner, 'session_authority', None)
- if authority is None:
+ if getattr(runner, 'session_authority', None) is None:
raise RuntimeStoreError('not_found')
registered, profile = runner._owning_profile(adapter, adapter.platform)
home = getattr(runner, '_native_transport_homes', {}).get(profile)
@@ -24,6 +24,10 @@ async def producer_scope(adapter, event):
source.profile_route_rejected = True
source._authorization_profile_home = home
runtime_home = runner._resolve_profile_home_for_source(source) if source.profile else home
+ # The routed profile's own ledger admits the delivery; an unserved route is refused.
+ authority = authority_for_home(runner, runtime_home)
+ if authority is None:
+ raise RuntimeStoreError('profile_mismatch')
with native_callback(runner, event, home, profile):
async with _async_profile_runtime_scope(runtime_home):
yield authority
diff --git a/gateway/run_api.py b/gateway/run_api.py
index 6a77bbb0eed..63913c7d0dd 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -142,20 +142,26 @@ class GatewayRuntimeAPI:
await ws.close(code=4403)
return
try:
- grant = self.runner.session_ticket_store.redeem(
- ticket, profile_id=self.runner.session_authority.profile_id,
- purpose='interactive')
+ grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='interactive')
except PermissionError:
try:
- grant = self.runner.session_ticket_store.redeem(
- ticket, profile_id=self.runner.session_authority.profile_id,
- purpose='worker-adoption')
+ grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='worker-adoption')
except PermissionError:
# Browser/OAuth tickets have a separate issuer.
return await self.app(scope, receive, send)
+ from gateway.session_authorities import authority_for_profile_id
+ authority = authority_for_profile_id(self.runner, grant['profile_id'])
+ if authority is None:
+ await ws.close(code=4403)
+ return
+ # The ticket names the served profile; this connection binds to that home's authority.
+ scope['hermes.session_authority'] = authority
from tui_gateway.ws import handle_ws
- await handle_ws(ws, auth_identity={'user_id': grant['subject'], 'provider': 'local',
- 'profile_id': grant['profile_id'],
- 'instance_id': grant['instance_id'],
- 'capabilities': grant['capabilities'], 'native_bootstrap': True},
- subprotocol='hermes-gateway-v1')
+ from gateway.run import _profile_runtime_scope
+ from pathlib import Path
+ with _profile_runtime_scope(Path(authority.profile_id), hydrate_secrets=False):
+ await handle_ws(ws, auth_identity={'user_id': grant['subject'], 'provider': 'local',
+ 'profile_id': grant['profile_id'],
+ 'instance_id': grant['instance_id'],
+ 'capabilities': grant['capabilities'], 'native_bootstrap': True},
+ subprotocol='hermes-gateway-v1')
diff --git a/gateway/run_heartbeat_acceptance.py b/gateway/run_heartbeat_acceptance.py
index 99e06a161a7..bf293b377d3 100644
--- a/gateway/run_heartbeat_acceptance.py
+++ b/gateway/run_heartbeat_acceptance.py
@@ -51,7 +51,10 @@ async def admit_heartbeat(runner, adapter, source, session_id, route):
from hermes_cli.heartbeat import HeartbeatManager
from hermes_state_runtime import list_session_admissions
- authority = runner.session_authority
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
+ if authority is None:
+ return
pending = list_session_admissions(authority.db, session_id=session_id)
if any(row['payload'].get('native_text_v1', {}).get('automation', {}).get('heartbeat')
for row in pending):
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index f29afa65fb3..37b070ec1f3 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -1211,11 +1211,18 @@ class GatewayInboundMixin:
if _reply is not None:
return _reply
- authority = getattr(self, 'session_authority', None)
+ # The message handler entered the routed profile's scope; its authority owns this turn.
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
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)
+ if (authority is None and not is_internal and not event.get_command()
+ and getattr(self, 'session_authority', None) is not None):
+ # Scoped to a home this process does not serve: never fall back to the launch ledger.
+ from hermes_state_runtime import RuntimeStoreError
+ raise RuntimeStoreError('profile_mismatch')
# Evict a leaked/reaped ``_running_agents`` slot before the busy-session fast-path.
self._hm_evict_idle_stale_agent(_quick_key)
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 95bc2521cba..4f3674b7720 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -1081,7 +1081,8 @@ class GatewayNotificationsMixin:
_prime = getattr(adapter, "prime_routing_cache", None)
if callable(_prime):
_prime(synth_event)
- authority = getattr(self, 'session_authority', None)
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
if authority is not None:
from gateway.session_automation import producer_identity
from hermes_state_runtime import RuntimeStoreError
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index c042714f78f..684f4c64012 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -526,13 +526,11 @@ class GatewayStartupMixin:
for entry in candidates:
# Canonical admissions own restart decisions, including unknown pauses.
# Legacy synthetic resume must not race their restored FIFO.
- authority = getattr(self, 'session_authority', None)
- if authority is not None:
- if authority.db._read_one(
+ from gateway.session_authorities import all_authorities
+ if any(authority.db._read_one(
'SELECT 1 FROM session_admissions WHERE target_session_id=? LIMIT 1',
- (entry.session_id,),
- ):
- continue
+ (entry.session_id,)) for authority in all_authorities(self)):
+ continue
marker = entry.last_resume_marked_at or entry.updated_at
if marker is not None and (now - marker).total_seconds() > window:
continue
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 9107155c3e3..224e6827f95 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -797,7 +797,8 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
from gateway.status_phrases import choose_status_phrase, resolve_status_phrase_catalog
from gateway.session_policy import policy_for_source
policy = policy_for_source(self, source)
- user_config = policy.config(self.session_authority) if policy else _load_gateway_config()
+ from gateway.session_authorities import active_authority
+ user_config = policy.config(active_authority(self)) if policy else _load_gateway_config()
platform_key = policy.platform if policy else _platform_config_key(source.platform)
enabled_toolsets, disabled_toolsets = self._resolve_turn_toolsets(user_config, source, platform_key)
if policy:
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index d2fd38cb5f9..06a498488e3 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -59,8 +59,10 @@ class GatewayTurnPrepareMixin:
from gateway.run import _runtime_agent_kwargs
from gateway.session_policy import launch_key
from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
- frozen = policy.config(self.session_authority)
- key = launch_key(self.session_authority, policy)
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
+ frozen = policy.config(authority)
+ key = launch_key(authority, policy)
import json
runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,
explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),
@@ -516,10 +518,15 @@ class GatewayTurnPrepareMixin:
# Multiplex: the home channel may live only in the profile secret scope, not os.environ.
home_env = ""
if env_key:
- with suppress(Exception):
- from agent.secret_scope import get_secret
+ # A secondary with no home channel must not borrow the default profile's from
+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.
+ from agent.secret_scope import UnscopedSecretError, get_secret
+ try:
home_env = (get_secret(env_key) or "").strip()
- home_env = home_env or (os.getenv(env_key) or "").strip()
+ except UnscopedSecretError:
+ home_env = (os.getenv(env_key) or "").strip()
+ except Exception:
+ home_env = ""
# Also honor in-memory / yaml home_channel on this platform.
with suppress(Exception):
if not home_env and self.config.get_home_channel(source.platform):
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index 0418874446b..44633c74626 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -55,7 +55,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
def __init__(self, runner: "GatewayRunner", ctx: TurnContext) -> None:
self._runner = runner
self._ctx = ctx
- authority = getattr(runner, "session_authority", None)
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
self._approval_owner = None
if authority is not None:
source = getattr(ctx, 'source', None)
@@ -810,8 +811,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
def run_sync(self):
from gateway.session_policy import policy_for_source, policy_scope
from gateway.session_api_turn import api_policy_scope
+ from gateway.session_authorities import active_authority
with policy_scope(policy_for_source(self._runner, self._ctx.source),
- authority=getattr(self._runner, "session_authority", None)), api_policy_scope():
+ authority=active_authority(self._runner)), api_policy_scope():
result = self._run_sync_scoped()
from gateway.session_results import execution_result
captured = execution_result.get()
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index cae494aa9f2..5b3f5fc7f3b 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -79,8 +79,10 @@ def api_policy_scope():
def admit_api_turn(adapter, **kwargs):
- authority = adapter.gateway_runner.session_authority
- if adapter._ensure_session_db() is not authority.db:
+ # ``/p/<profile>/`` middleware scoped this request; the routed home's authority admits it.
+ from gateway.session_authorities import active_authority
+ authority = active_authority(adapter.gateway_runner)
+ if authority is None or adapter._ensure_session_db() is not authority.db:
raise RuntimeStoreError('profile_mismatch')
sid = kwargs.get('session_id') or uuid.uuid4().hex
declared_key = kwargs.get('gateway_session_key') if kwargs.get('bind_declared_conversation') else None
@@ -122,9 +124,12 @@ def admit_api_turn(adapter, **kwargs):
def recover_api_turns(adapter):
"""Recover committed work only after the real API adapter is published."""
- authority = getattr(adapter.gateway_runner, 'session_authority', None)
- if authority is None:
- return
+ from gateway.session_authorities import all_authorities
+ for authority in all_authorities(adapter.gateway_runner):
+ _recover_api_turns(adapter, authority)
+
+
+def _recover_api_turns(adapter, authority):
from hermes_state_runtime import list_session_admissions
import logging
with authority.db._read_ctx() as conn:
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index c2989f7356a..088ca287291 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -21,7 +21,8 @@ def producer_identity(runner, event):
def completion_admission(runner, event):
- authority = getattr(runner, 'session_authority', None)
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
if authority is None:
return None
entry = runner.session_store.lookup_by_session_key(str(event.get('session_key') or ''))
@@ -49,7 +50,8 @@ def _owner(runner, event):
raise RuntimeStoreError('admission_conflict')
if expected != entry.session_id:
# A completed child may follow compression, but never /new or an unrelated resume.
- if runner.session_authority.db.get_compression_tip(expected) != entry.session_id:
+ from gateway.session_authorities import active_authority
+ if active_authority(runner).db.get_compression_tip(expected) != entry.session_id:
raise RuntimeStoreError('admission_conflict')
return entry
diff --git a/gateway/session_envelope.py b/gateway/session_envelope.py
index d33abd2a039..58d6d937551 100644
--- a/gateway/session_envelope.py
+++ b/gateway/session_envelope.py
@@ -117,7 +117,8 @@ def _snapshot_native(runner, event, provenance, fresh_roles=False):
# ordinary admissions must bind homes too, including execution after restart.
if provenance is not None and not getattr(runner.config, 'multiplex_profiles', False):
from hermes_state_runtime import list_session_admissions
- authority = runner.session_authority
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
entry = runner.session_store.lookup_by_session_key(envelope['route'])
if entry is not None:
legacy = deepcopy(payload)
diff --git a/gateway/session_ingress_context.py b/gateway/session_ingress_context.py
index 062de9a1ab2..89f648c63e4 100644
--- a/gateway/session_ingress_context.py
+++ b/gateway/session_ingress_context.py
@@ -93,10 +93,12 @@ def _binding(runner, source, profile):
homes = {}
for name, path in reserved:
canonical = Path(path).resolve()
- if name in homes or canonical in homes.values() or not canonical.is_dir():
+ if name in homes or canonical in homes.values():
raise RuntimeStoreError('profile_mismatch')
homes[name] = canonical
- primary = getattr(runner, '_primary_profile_name', None) or 'default'
+ primary = getattr(runner, '_primary_profile_name', None)
+ if not primary:
+ raise RuntimeStoreError('profile_mismatch')
owner_name = profile or primary
if homes.get(owner_name) != home:
raise RuntimeStoreError('profile_mismatch')
@@ -109,14 +111,23 @@ def _binding(runner, source, profile):
if len(best) != 1:
raise RuntimeStoreError('admission_conflict')
runtime_profile = best[0].profile
+ elif source.profile and source.profile in homes and source.platform.value in ('webhook', 'api_server', 'msgraph_webhook'):
+ # ``/p/<profile>/`` producers address a served profile explicitly on the HOST's
+ # listener; that URL prefix is the route (webhook.py / api_server.py stamp it).
+ runtime_profile = source.profile
else:
runtime_profile = owner_name
if (source.profile or primary) != runtime_profile or runtime_profile not in homes:
raise RuntimeStoreError('profile_mismatch')
runtime_home = homes[runtime_profile]
- # A configured/transport home is NOT proof of a runtime DB owner. The current
- # single-authority runner must refuse another runtime rather than use launch DB.
- if Path(runner.session_authority.db.db_path).resolve().parent != runtime_home:
+ # Revoking ONE served profile (its directory removed) fails that profile only.
+ if not runtime_home.is_dir():
+ raise RuntimeStoreError('profile_mismatch')
+ # A configured/transport home is NOT proof of a runtime DB owner: the runtime home must be
+ # one this process reserved and built an authority for, never a borrowed launch DB.
+ from gateway.session_authorities import authority_for_home
+ authority = authority_for_home(runner, runtime_home)
+ if authority is None:
raise RuntimeStoreError('profile_mismatch')
if relay:
transport, connector = _relay_connector(adapter, source)
diff --git a/hermes_cli/dashboard_auth/native_http.py b/hermes_cli/dashboard_auth/native_http.py
index 6a0043e08c9..a9f6bc6ffd9 100644
--- a/hermes_cli/dashboard_auth/native_http.py
+++ b/hermes_cli/dashboard_auth/native_http.py
@@ -83,24 +83,28 @@ async def authenticate_native_http(request):
tickets = request.headers.getlist(HEADER)
if not tickets:
return None
+ from gateway.session_authorities import all_authorities, authority_for_profile_id
runner = getattr(request.app.state, 'gateway_runner', None)
descriptor = getattr(runner, 'session_runtime_descriptor', {})
- authority = getattr(runner, 'session_authority', None)
+ authorities = all_authorities(runner)
store = getattr(runner, 'session_ticket_store', None)
peer = request.scope.get('hermes.gateway_socket_peer')
if (len(tickets) != 1 or 'origin' in request.headers or not peer
or peer[0] not in {'127.0.0.1', '::1'}
or descriptor.get('state') != 'ready' or getattr(runner, '_draining', True)
- or authority is None or store is None
+ or not authorities or store is None
or store.instance_id != descriptor.get('instance_id')
- or authority.instance_id != store.instance_id
+ or any(a.instance_id != store.instance_id for a in authorities)
or descriptor.get('served_profiles') != [
- {'profile_id': authority.profile_id, 'home': authority.profile_id}]):
+ {'profile_id': a.profile_id, 'home': a.profile_id} for a in authorities]):
return JSONResponse({'detail': 'Unauthorized'}, status_code=401)
try:
- grant = store.redeem(tickets[0], profile_id=authority.profile_id, purpose='native-http')
+ # The ticket names the served profile it was minted for; that home's authority owns it.
+ grant = store.redeem(tickets[0], profile_id=None, purpose='native-http')
if grant['capabilities'] != frozenset({'http:owner'}):
raise PermissionError('invalid native grant')
+ if authority_for_profile_id(runner, grant['profile_id']) is None:
+ raise PermissionError('unserved native grant')
except PermissionError:
return JSONResponse({'detail': 'Unauthorized'}, status_code=401)
try:
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.py
index 86759f06380..488422a5e83 100644
--- a/hermes_cli/web_server_sessions.py
+++ b/hermes_cli/web_server_sessions.py
@@ -91,8 +91,15 @@ def _session_mutation_context(request, profile):
if authority is None:
raise HTTPException(status_code=503, detail='session_authority_unavailable')
home = Path(_cron_profile_home(profile)[1]) if profile else Path(_default_db_path()).parent
- if home.resolve() != Path(authority.db.db_path).parent.resolve():
+ # ``?profile=`` selects a served home; its own authority (not the launch one) owns the mutation.
+ from gateway.session_authorities import authority_for_home
+ runner = getattr(request.app.state, 'gateway_runner', None)
+ owner = authority_for_home(runner, home) if runner is not None else None
+ if owner is None and home.resolve() == Path(authority.db.db_path).parent.resolve():
+ owner = authority
+ if owner is None:
raise HTTPException(status_code=403, detail='profile_mismatch')
+ authority = owner
if native is not None and native['profile_id'] != authority.profile_id:
raise HTTPException(status_code=403, detail='profile_mismatch')
return authority, Principal(subject, authority.profile_id,
@@ -191,6 +198,12 @@ def _open_session_db_at_path(db_path: Path, *, read_only: bool):
db.close()
raise
except (sqlite3.DatabaseError, UnicodeDecodeError) as exc:
+ from hermes_state_errors import is_malformed_db_error
+ if isinstance(exc, sqlite3.DatabaseError) and is_malformed_db_error(exc):
+ # Same structured 503 the analytics routers publish (``corrupt_store_as_status``): a
+ # corrupt image names the repair (`hermes doctor`), never a generic "schema unavailable".
+ from hermes_cli.web_routers._common import corrupt_store_status
+ raise corrupt_store_status(db_path, exc) from exc
if isinstance(exc, sqlite3.OperationalError) and is_transient_sqlite_error(exc):
detail = "Session store is busy (disk I/O or lock). Retry; the list was not cleared."
else:
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 5722f0fcd08..a89b46e2114 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -290,7 +290,8 @@ 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)
+ authority = ws.scope.get('hermes.session_authority') or 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 {})