Skip to content

The agent that grows with you

feat: bind hosted service ownership and canonical member admission

Teknium5cc62a4de781
diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.py
new file mode 100644
index 00000000000..d18bdc45f58
--- /dev/null
+++ b/gateway/session_hosted_service.py
@@ -0,0 +1,149 @@
+"""Authority-bound hosted service; no legacy session server is constructed."""
+import asyncio
+from contextlib import nullcontext
+from pathlib import Path
+
+from gateway.session_contract import Principal
+from hermes_state_runtime import RuntimeStoreError, _epoch
+from tui_gateway.hosted_room_service import HostedRoomService
+
+_OWNER = 'gateway.hosted.owner.v1:'
+
+
+class CanonicalHostedRoomService(HostedRoomService):
+ def __init__(self, authority, loop):
+ self.authority, self.loop = authority, loop
+ self.member_rpcs = {}
+ super().__init__(None, db_path=authority.db.db_path)
+
+ def _make_rpc(self, server):
+ # Member-specific canonical transports retain exact durable history. They
+ # intentionally use the runtime's receipt-capable (non-legacy) recovery path.
+ return self
+
+ def local_profiles(self):
+ home = Path(self.authority.profile_id)
+ return (home.name if home.parent.name == 'profiles' else 'default',)
+
+ def bindings(self):
+ with self.authority.db._read_ctx() as conn:
+ owned = {r[0][len(_OWNER):] for r in conn.execute(
+ 'SELECT key FROM state_meta WHERE key LIKE ?', (_OWNER + '%',))}
+ return tuple(b for b in super().bindings() if b.room_id in owned)
+
+ def _turn_lock(self, profile):
+ return nullcontext()
+
+ def authorize_room(self, actor_subject, room_id, *, create=False):
+ from gateway.hosted_rooms_common import IDENTIFIER_RE
+ if (not isinstance(actor_subject, str) or not actor_subject
+ or not isinstance(room_id, str) or len(room_id) > 128
+ or not IDENTIFIER_RE.fullmatch(room_id)):
+ raise RuntimeStoreError('invalid_params')
+ def write(conn):
+ _epoch(conn, self.authority.epoch)
+ key = _OWNER + room_id
+ row = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if row is None and create:
+ historical = conn.execute(
+ 'SELECT 1 FROM hosted_rooms WHERE room_id=? UNION ALL '
+ 'SELECT 1 FROM hosted_room_retired_ids WHERE room_id=?',
+ (room_id, room_id)).fetchone()
+ if historical is None:
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, actor_subject))
+ return True
+ if row is None or row[0] != actor_subject:
+ raise RuntimeStoreError('permission_denied')
+ return True
+ return self.authority.db._execute_write(write)
+
+ def _owner(self, room_id):
+ with self.authority.db._read_ctx() as conn:
+ row = conn.execute('SELECT value FROM state_meta WHERE key=?', (_OWNER + room_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('permission_denied')
+ return row[0]
+
+ def _resolve_member_transport(self, binding, task):
+ if self._member_is_peer(binding.room_id, str(task['payload'].get('target_member_id') or task['payload'].get('target_profile'))):
+ return super()._resolve_member_transport(binding, task)
+ from gateway.session_hosted_rpc import HostedRoomAuthorityRPC
+ payload = task['payload']
+ member = str(payload.get('target_member_id') or payload.get('target_profile'))
+ profile = payload['target_profile']
+ owner = self._owner(binding.room_id)
+ key = binding.room_id, member, profile, owner
+ if key not in self.member_rpcs:
+ def authorize(operation, identity, generation):
+ self.authorize_room(owner, binding.room_id)
+ room = self._room(binding.room_id)
+ if (room['authority_gateway_id'], room['authority_epoch']) != (binding.gateway_id, binding.authority_epoch):
+ return False
+ members = room['members']
+ if not any(m.get('member_id') == member and m.get('profile') == profile for m in members):
+ return False
+ if profile not in self.local_profiles():
+ return False
+ if identity is not None:
+ from gateway.hosted_room_driver import list_tasks
+ return any(t['identity'] == identity and t['execution_generation'] == generation
+ and t['payload'].get('target_profile') == profile
+ and t['status'] in {'running', 'stopping'}
+ for t in list_tasks(self.db_path, room_id=binding.room_id))
+ return True
+ principal = Principal(owner, self.authority.profile_id,
+ frozenset({'session:create', 'session:read', 'session:submit', 'session:control', 'session:approve'}),
+ 'hosted:' + binding.room_id + ':' + member)
+ self.member_rpcs[key] = HostedRoomAuthorityRPC(self.authority, self.loop,
+ room_id=binding.room_id, member_id=member, profile=profile, principal=principal, authorize=authorize)
+ return self.member_rpcs[key]
+
+ def check_admission(self, ref, row):
+ """Reconstruct the private producer from durable task state before claim."""
+ import json
+ from gateway.hosted_room_driver import TaskIdentity, list_tasks
+ from tui_gateway.hosted_room_driver import HostedRoomBinding
+ try:
+ if not row['request_id'].startswith('hosted:'):
+ raise ValueError('not a hosted admission')
+ identity, generation = json.loads(row['request_id'][7:])
+ identity = TaskIdentity(**identity)
+ if type(generation) is not int or generation < 1:
+ raise ValueError('invalid generation')
+ owner = self._owner(identity.room_id)
+ if owner != row['principal_id']:
+ raise ValueError('foreign owner')
+ room = self._room(identity.room_id)
+ task = next(t for t in list_tasks(self.db_path, room_id=identity.room_id)
+ if t['identity'] == identity and t['execution_generation'] == generation)
+ rpc = self._resolve_member_transport(HostedRoomBinding(identity.room_id,
+ room['authority_gateway_id'], room['authority_epoch']), task)
+ if (getattr(rpc, 'ref', None) != ref or task['status'] != 'running'
+ or row['payload'] != {'text': task['payload']['prompt']}
+ or rpc.authorizer('execute', identity, generation) is not True):
+ raise ValueError('changed hosted binding')
+ return task
+ except (ValueError, TypeError, KeyError, StopIteration) as exc:
+ raise RuntimeStoreError('permission_denied') from exc
+
+ def approve(self, *, session_id, request_id, choice):
+ rpc = next((r for r in self.member_rpcs.values() if r.ref.session_id == session_id), None)
+ if rpc is None:
+ raise RuntimeStoreError('permission_denied')
+ return rpc.approve(session_id=session_id, request_id=request_id, choice=choice)
+
+
+async def ensure_hosted_service(runner):
+ authority = runner.session_authority
+ service = getattr(authority, 'hosted_room_service', None)
+ if service is None:
+ loop = asyncio.get_running_loop()
+ service = await asyncio.to_thread(CanonicalHostedRoomService, authority, loop)
+ authority.hosted_room_service = service
+ await asyncio.to_thread(service.start)
+ return service
+
+
+async def stop_hosted_service(runner, timeout=5):
+ service = getattr(runner.session_authority, 'hosted_room_service', None)
+ return True if service is None else await asyncio.to_thread(service.stop, timeout=timeout)
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index f0e7025924e..f4b58087081 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -231,7 +231,7 @@ def restore_policy(data):
try:
policy = LocalSessionPolicy(**data)
from gateway.session_a2a import is_forward_policy
- surfaces = {**SURFACES, 'cron': 'cron', 'kanban': 'cli'}
+ surfaces = {**SURFACES, 'cron': 'cron', 'kanban': 'cli', 'bot_room': 'bot_room'}
if ((not is_forward_policy(policy) and
(policy.source not in surfaces or policy.platform != surfaces[policy.source]))
or not isinstance(policy.cwd, str) or not Path(policy.cwd).is_absolute()
diff --git a/tests/gateway/test_session_hosted_rpc.py b/tests/gateway/test_session_hosted_rpc.py
index 2af3a3aeb8a..1301632d4d6 100644
--- a/tests/gateway/test_session_hosted_rpc.py
+++ b/tests/gateway/test_session_hosted_rpc.py
@@ -141,6 +141,10 @@ def test_terminal_callback_follows_canonical_drain_without_polling(owner, monkey
sid = rpc.create(**coords, title='Group: room')['session_id']
async def execute(authority, ref, row):
return 'canonical reply'
+ # This RPC component fixture supplies the service gate explicitly; daemon
+ # coverage exercises the real durable member/task authorizer.
+ authority.runner._adapter_for_source = lambda source: authority.runner.adapters[source.platform]
+ authority.hosted_room_service = SimpleNamespace(check_admission=lambda ref, row: True)
monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
monkeypatch.setattr(authority, '_schedule', SessionAuthority._schedule.__get__(authority))
done, receipts = threading.Event(), []
diff --git a/tests/gateway/test_session_hosted_service.py b/tests/gateway/test_session_hosted_service.py
new file mode 100644
index 00000000000..43d8003cfcc
--- /dev/null
+++ b/tests/gateway/test_session_hosted_service.py
@@ -0,0 +1,115 @@
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch, RuntimeStoreError
+
+
+async def test_room_owner_survives_service_restart_and_foreign_actor_cannot_claim(tmp_path, monkeypatch):
+ from gateway.session_hosted_service import CanonicalHostedRoomService
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ db = SessionDB(tmp_path / 'state.db')
+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), epoch=begin_runtime_epoch(db, instance_id='test'))
+ try:
+ from tui_gateway import hosted_room_service
+ def forbidden_legacy(*args):
+ raise AssertionError('canonical service constructed legacy RPC')
+ monkeypatch.setattr(hosted_room_service, 'HostedRoomServerRPC', forbidden_legacy)
+ service = CanonicalHostedRoomService(authority, asyncio.get_running_loop())
+ service.authorize_room('alice', 'room', create=True)
+ from gateway.hosted_rooms import create_room
+ create_room(db.db_path, room_id='room', name='Room', authority_gateway_id='test', members=[
+ {'member_id': 'default', 'profile': 'default', 'handle': 'bot'},
+ {'member_id': 'other', 'profile': 'other', 'handle': 'other'}])
+ service = CanonicalHostedRoomService(authority, asyncio.get_running_loop())
+ assert service.authorize_room('alice', 'room') is True
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.authorize_room('bob', 'room', create=True)
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.authorize_room('bob', 'room')
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.authorize_room('alice', 'absent')
+ # A historical row without an owner cannot be adopted, including retired IDs.
+ with db._lock:
+ db._conn.execute("INSERT INTO hosted_room_retired_ids(room_id,retired_at) VALUES('retired',1)")
+ db._conn.commit()
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.authorize_room('alice', 'retired', create=True)
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ service.authorize_room('alice', ' room ', create=True)
+ finally:
+ db.close()
+
+
+def test_private_hosted_policy_restores_without_public_source_admission(tmp_path):
+ from dataclasses import asdict, replace
+ from gateway.session_policy import build_policy, restore_policy
+ policy = replace(build_policy({'source': 'gui', 'cwd': str(tmp_path), 'model': 'fixture'}, {}),
+ source='bot_room', platform='bot_room')
+ assert restore_policy(asdict(policy)).source == 'bot_room'
+ with pytest.raises(RuntimeStoreError):
+ build_policy({'source': 'bot_room'}, {})
+
+
+
+def test_hosted_dequeue_checks_exact_task_member_and_frozen_input(tmp_path, monkeypatch):
+ import json
+ import time
+ from dataclasses import asdict
+ from gateway.session_hosted_service import CanonicalHostedRoomService
+ from gateway import hosted_room_driver as tasks
+ from gateway.hosted_rooms import create_room, local_authority_gateway_id
+ from tui_gateway.hosted_room_driver import HostedRoomBinding
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ with SessionDB(tmp_path / 'state.db') as db:
+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), epoch=begin_runtime_epoch(db, instance_id='test'))
+ service = CanonicalHostedRoomService(authority, None)
+ service.authorize_room('alice', 'room', create=True)
+ gateway = local_authority_gateway_id()
+ create_room(db.db_path, room_id='room', name='Room', authority_gateway_id=gateway, members=[
+ {'member_id': 'one', 'profile': 'default', 'handle': 'one'},
+ {'member_id': 'two', 'profile': 'other', 'handle': 'two'}])
+ identity = tasks.TaskIdentity('room', 'task', 'thread', 'turn')
+ payload = {'target_profile': 'default', 'target_member_id': 'one', 'source_event_seq': 1, 'prompt': 'frozen'}
+ tasks.admit_task(db.db_path, identity, payload=payload, clock=time.time)
+ lease = tasks.acquire_lease(db.db_path, room_id='room', gateway_id=gateway, authority_epoch=1,
+ process_generation='test', ttl_seconds=30, clock=time.time)
+ tasks.start_task(db.db_path, identity, lease, expected_cancel_generation=0, clock=time.time)
+ task, = tasks.list_tasks(db.db_path, room_id='room')
+ rpc = service._resolve_member_transport(HostedRoomBinding('room', gateway, 1), task)
+ row = {'principal_id': 'alice', 'request_id': 'hosted:' + json.dumps([asdict(identity), task['execution_generation']]),
+ 'payload': {'text': 'frozen'}}
+ assert service.check_admission(rpc.ref, row) == task
+ for bad in ({**row, 'principal_id': 'bob'}, {**row, 'payload': {'text': 'changed'}},
+ {**row, 'request_id': 'hosted:' + json.dumps([asdict(identity), 999])}):
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.check_admission(rpc.ref, bad)
+ with db._lock:
+ db._conn.execute("UPDATE hosted_rooms SET members_json=? WHERE room_id='room'", (json.dumps([
+ {'member_id': 'replacement', 'profile': 'default', 'handle': 'replacement'},
+ {'member_id': 'two', 'profile': 'other', 'handle': 'two'}]),))
+ db._conn.commit()
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ service.check_admission(rpc.ref, row)
+
+
+
+async def test_service_does_not_plan_or_run_historical_unowned_rooms(tmp_path, monkeypatch):
+ from gateway.session_hosted_service import CanonicalHostedRoomService
+ from gateway.hosted_rooms import create_room, local_authority_gateway_id
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ with SessionDB(tmp_path / 'state.db') as db:
+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), epoch=begin_runtime_epoch(db, instance_id='test'))
+ service = CanonicalHostedRoomService(authority, asyncio.get_running_loop())
+ for room_id in ('unowned', 'owned'):
+ if room_id == 'owned':
+ service.authorize_room('alice', room_id, create=True)
+ create_room(db.db_path, room_id=room_id, name=room_id,
+ authority_gateway_id=local_authority_gateway_id(), members=[
+ {'member_id': 'one', 'profile': 'default', 'handle': 'one'},
+ {'member_id': 'two', 'profile': 'other', 'handle': 'two'}])
+ assert [b.room_id for b in service.bindings()] == ['owned']
diff --git a/tui_gateway/hosted_room_service.py b/tui_gateway/hosted_room_service.py
index ca23d955edd..63740b76821 100644
--- a/tui_gateway/hosted_room_service.py
+++ b/tui_gateway/hosted_room_service.py
@@ -73,7 +73,7 @@ class HostedRoomService:
self._policy_lock = threading.RLock()
self._pending_actions: dict[tuple[str, str], dict[str, Any]] = {}
self.policy_checkpoint = HostedRoomPolicyCheckpoint(self.db_path)
- self.rpc = HostedRoomServerRPC(server)
+ self.rpc = self._make_rpc(server)
self._link_load_error = None
self._peer_route_status: dict[tuple[str, str], str] = {}
self.peer_routes: dict[tuple[str, str], PeerMemberRoute] = {}
@@ -97,6 +97,9 @@ class HostedRoomService:
active_poll_interval_seconds=_HOSTED_ROOM_ACTIVE_POLL_SECONDS,
turn_timeout_seconds=_hosted_room_turn_timeout_seconds())
+ def _make_rpc(self, server):
+ return HostedRoomServerRPC(server)
+
def _load_stored_links(self) -> None:
"""Rehydrate persisted peer routes; collect per-link errors into one string."""
stored_links, load_errors = hosted_room_links.load_room_links_tolerant(self.db_path)