The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: wire canonical hosted group controls
Tekniumfa2179bb8c3b
diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.pyindex f45926b4dab..1d20c08e1b9 100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@ -1,9 +1,4 @@-"""Profile-owned non-inference room controls and roster discovery.--The legacy local room driver creates TUI agents, so it is not an execution-capability of this transport. Room metadata still uses the existing durable-room protocol, on the authority's database rather than the install-wide default.-"""+"""Profile-owned room controls over the canonical hosted service."""import asynciofrom pathlib import Path@@ -18,6 +13,10 @@ GROUP_METHODS = {'groups.create': 'session:control','groups.rename': 'session:control','groups.disband': 'session:control',+ 'groups.send': 'session:submit',+ 'groups.stop': 'session:control',+ 'groups.retry': 'session:control',+ 'groups.approve': 'session:approve',}_FIELDS = {'groups.capabilities': set(),@@ -26,7 +25,12 @@ _FIELDS = {'groups.log': {'room_id', 'since_seq', 'limit', 'include_disbanded'},'groups.create': {'room_id', 'name', 'members'},'groups.rename': {'room_id', 'event_id', 'name'},- 'groups.disband': {'room_id'},+ 'groups.disband': {'room_id', 'cancel_id'},+ 'groups.send': {'room_id', 'event_id', 'payload'},+ 'groups.stop': {'room_id', 'cancel_id'},+ 'groups.retry': {'room_id', 'task_id'},+ 'groups.approve': {'room_id', 'member_id', 'task_id', 'execution_generation',+ 'choice', 'request_id'},'profiles.list': {'include_sessions'},}@@ -58,7 +62,9 @@ async def dispatch_group_control(connection, method, params):if method == 'profiles.list':return _profiles(authority, actor, home, supplied)try:- return _group(authority, home, method, supplied)+ return _group(authority, actor, home, method, supplied)+ except RuntimeStoreError:+ raiseexcept HostedRoomError as exc:raise RuntimeStoreError(getattr(exc, 'reason', None) or 'invalid_params') from excexcept (ValueError, TypeError) as exc:@@ -66,13 +72,33 @@ async def dispatch_group_control(connection, method, params):return await asyncio.to_thread(invoke)-def _group(authority, home, method, params):+def _group(authority, actor, home, method, params):from gateway import hosted_rooms as roomsdb_path = authority.db.db_pathgateway_id = rooms.local_authority_gateway_id()+ service = getattr(authority, 'hosted_room_service', None)+ room_authorizer = getattr(service, 'authorize_room', None)+ if service is not None:+ if Path(service.db_path).resolve() != Path(db_path).resolve():+ raise RuntimeStoreError('profile_mismatch')+ status = service.runtime.status()+ if not status.get('running') or status.get('stopping'):+ service = None++ execution_methods = {'groups.send', 'groups.stop', 'groups.retry', 'groups.approve'}+ if service is not None and 'room_id' in params:+ if room_authorizer is None:+ raise RuntimeStoreError('permission_denied')+ room_authorizer(actor.subject, params['room_id'], create=method == 'groups.create')+ if method in execution_methods:+ if service is None:+ raise RuntimeStoreError('runtime_coordination_required')+ if not params.get('room_id'):+ raise RuntimeStoreError('invalid_params')+ return _execution_control(service, method, params)def capabilities():- return {'protocol_version': rooms.PROTOCOL_VERSION, 'driver': False,+ return {'protocol_version': rooms.PROTOCOL_VERSION, 'driver': service is not None,'persistent_process': True, 'authority_gateway_id': gateway_id,'room_link': {'enabled': False, 'reason': 'canonical_driver_required'},'features': ['room_identity', 'monotonic_log', 'replayable_disband'],@@ -84,6 +110,8 @@ def _group(authority, home, method, params):return {'rooms': result, 'next_offset': offset + limit if len(result) == limit else None}def create():+ if service is not None:+ return {'room': service.create_room(**params)}from gateway.hosted_room_discussion import validate_rostername = home.name if home.parent.name == 'profiles' else 'default'profiles = {name}@@ -98,19 +126,32 @@ def _group(authority, home, method, params):def disband():from gateway.hosted_room_driver import list_tasks+ state = rooms.room_state(db_path, room_id=params.get('room_id'), include_disbanded=True)+ if service is not None and state.get('disbanded_at') is None:+ service.stop_room(params.get('room_id'),+ cancel_id=params.get('cancel_id') or 'room-disbanded',+ require_acknowledged=True)+ service.revoke_room_routes(params.get('room_id'))# Metadata control must not destroy an active execution or bypass Stop.- if any(list_tasks(db_path, room_id=params.get('room_id'), status=status)+ if service is None and any(list_tasks(db_path, room_id=params.get('room_id'), status=status)for status in ('queued', 'running', 'stopping', 'indeterminate', 'deferred')):raise RuntimeStoreError('runtime_coordination_required')state = rooms.room_state(db_path, room_id=params.get('room_id'), include_disbanded=True)return {'tombstone': rooms.disband_room(db_path, room_id=params.get('room_id'),expected_gateway_id=gateway_id, expected_epoch=state['authority_epoch'])}+ def state():+ room = rooms.room_state(db_path, **params)+ result = {'room': room}+ if service is not None and room.get('disbanded_at') is None:+ result['driver_status'] = service.status(room['room_id'])+ return result+handlers = {'groups.capabilities': capabilities,'groups.list': listing,'groups.create': create,- 'groups.state': lambda: {'room': rooms.room_state(db_path, **params)},+ 'groups.state': state,'groups.log': lambda: rooms.read_events(db_path, **params),'groups.rename': lambda: {'room': rooms.rename_room(db_path, **params)},'groups.disband': disband,@@ -118,6 +159,42 @@ def _group(authority, home, method, params):return handlers[method]()+def _execution_control(service, method, params):+ def send():+ from gateway.hosted_rooms import user_event_id+ event = service.send(room_id=params.get('room_id'),+ event_id=user_event_id(params.get('event_id')),+ payload=params.get('payload'))+ return {'event': event, 'client_event_id': params.get('event_id'),+ 'accepted': True, 'driver_started': True}++ def retry():+ task = service.retry_room_task(params.get('room_id'), task_id=params.get('task_id'))+ identity = task['identity']+ receipt = {field: getattr(identity, field) for field in+ ('room_id', 'task_id', 'thread_id', 'turn_id')}+ receipt.update({field: task[field] for field in+ ('status', 'execution_generation', 'cancel_generation')})+ return {'retried': True, 'task': receipt}++ def approve():+ if (type(params.get('execution_generation')) is not int+ or params['execution_generation'] < 1+ or params.get('choice') not in {'once', 'deny'}+ or not isinstance(params.get('request_id'), str) or not params['request_id']):+ raise RuntimeStoreError('invalid_params')+ return {'approved': True, 'result': service.approve_room_task(**params)}++ handlers = {+ 'groups.send': send,+ 'groups.stop': lambda: {'cancelled': service.stop_room(+ params.get('room_id'), cancel_id=params.get('cancel_id') or 'desktop-stop')},+ 'groups.retry': retry,+ 'groups.approve': approve,+ }+ return handlers[method]()++def _profiles(authority, actor, home, params):from hermes_cli.profiles import _profile_info, read_profile_metaimport yamldiff --git a/tests/gateway/test_session_group_execution_controls.py b/tests/gateway/test_session_group_execution_controls.pynew file mode 100644index 00000000000..038f6b1ba28--- /dev/null+++ b/tests/gateway/test_session_group_execution_controls.py@@ -0,0 +1,138 @@+"""Native room controls retain the service protocol and authenticated ownership."""+import asyncio+from types import SimpleNamespace++from gateway.session_controls import AuthorityConnection+from hermes_state import SessionDB+from hermes_state_runtime import RuntimeStoreError+++class RoomService:+ def __init__(self, path, owner):+ self.db_path = path+ self.owner = owner+ self.calls = []+ self.runtime = SimpleNamespace(status=lambda: {'running': True, 'stopping': False})++ def authorize_room(self, actor_subject, room_id, *, create=False):+ if actor_subject != self.owner or room_id != 'owned':+ raise RuntimeStoreError('permission_denied')++ def create_room(self, *, room_id, name, members):+ from gateway.hosted_rooms import create_room, local_authority_gateway_id+ self.calls.append(('create', room_id))+ return create_room(self.db_path, room_id=room_id, name=name, members=members,+ authority_gateway_id=local_authority_gateway_id())++ def status(self, room_id):+ return {'room_id': room_id, 'pending_actions': [{'kind': 'retry', 'task_id': 'task'}]}++ def revoke_room_routes(self, room_id):+ self.calls.append(('revoke', room_id))++ def send(self, *, room_id, event_id, payload):+ self.calls.append(('send', room_id, event_id, payload))+ return {'event_id': event_id, 'payload': payload}++ def stop_room(self, room_id, *, cancel_id, require_acknowledged=False):+ self.calls.append(('stop', room_id, cancel_id, require_acknowledged))+ return 1++ def retry_room_task(self, room_id, *, task_id):+ self.calls.append(('retry', room_id, task_id))+ return {'identity': SimpleNamespace(room_id=room_id, task_id=task_id,+ thread_id='thread', turn_id='turn'),+ 'status': 'queued', 'execution_generation': 3, 'cancel_generation': 2}++ def approve_room_task(self, room_id, *, member_id, task_id, execution_generation,+ choice, request_id=None):+ self.calls.append(('approve', room_id, member_id, task_id, execution_generation,+ choice, request_id))+ return {'resolved': request_id}+++def test_execution_controls_preserve_native_wire_and_exact_task_identity(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(profile_id=str(tmp_path), instance_id='owner', db=db, events={})+ connection = AuthorityConnection(authority, object(), {'user_id': 'alice'})+ service = authority.hosted_room_service = RoomService(db.db_path, connection.actor.subject)++ async def probe():+ async def call(method, **params):+ return await connection.dispatch({'id': 1, 'method': method, 'params': params})+ caps = await call('groups.capabilities')+ assert caps['result']['driver'] is True+ created = await call('groups.create', room_id='owned', name='Room', members=[+ {'member_id': 'one', 'profile': 'default', 'handle': 'one'},+ {'member_id': 'two', 'profile': 'helper', 'handle': 'two'}])+ assert 'result' in created, created+ assert service.calls[-1] == ('create', 'owned')+ state = await call('groups.state', room_id='owned')+ assert state['result']['driver_status'] == service.status('owned')++ payload = {'text': '@one hello', 'mentions': ['one']}+ sent = await call('groups.send', room_id='owned', event_id='input', payload=payload)+ assert sent['result']['accepted'] and sent['result']['driver_started']+ assert sent['result']['client_event_id'] == 'input'+ from gateway.hosted_rooms import user_event_id+ assert service.calls[-1] == ('send', 'owned', user_event_id('input'), payload)+ stopped = await call('groups.stop', room_id='owned', cancel_id='cancel-exact')+ assert stopped['result'] == {'cancelled': 1}+ retried = await call('groups.retry', room_id='owned', task_id='task-exact')+ assert retried['result']['task'] == {+ 'room_id': 'owned', 'task_id': 'task-exact', 'thread_id': 'thread',+ 'turn_id': 'turn', 'status': 'queued', 'execution_generation': 3,+ 'cancel_generation': 2}+ approved = await call('groups.approve', room_id='owned', member_id='one',+ task_id='task-exact', execution_generation=3,+ choice='once', request_id='approval-exact')+ assert approved['result'] == {'approved': True, 'result': {'resolved': 'approval-exact'}}+ assert service.calls[-1] == ('approve', 'owned', 'one', 'task-exact', 3,+ 'once', 'approval-exact')+ disbanded = await call('groups.disband', room_id='owned', cancel_id='disband-exact')+ assert 'result' in disbanded, disbanded+ assert service.calls[-2:] == [('stop', 'owned', 'disband-exact', True), ('revoke', 'owned')]+ asyncio.run(probe())+++def test_execution_controls_reject_foreign_actor_profile_room_and_unready_service(tmp_path, monkeypatch):+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(profile_id=str(tmp_path), instance_id='owner', db=db, events={})+ owner = AuthorityConnection(authority, object(), {'user_id': 'alice'})+ service = authority.hosted_room_service = RoomService(db.db_path, owner.actor.subject)++ async def probe():+ requests = {+ 'groups.state': {},+ 'groups.log': {},+ 'groups.rename': {'event_id': 'rename', 'name': 'No'},+ 'groups.disband': {},+ 'groups.send': {'event_id': 'input', 'payload': {'text': 'hello'}},+ 'groups.stop': {'cancel_id': 'cancel'},+ 'groups.retry': {'task_id': 'task'},+ 'groups.approve': {'member_id': 'one', 'task_id': 'task',+ 'execution_generation': 1, 'request_id': 'approval', 'choice': 'once'},+ }+ for method, params in requests.items():+ for identity, extra, reason in [+ ({'user_id': 'bob'}, {}, 'permission_denied'),+ ({'user_id': 'alice', 'capabilities': []}, {}, 'permission_denied'),+ ({'user_id': 'alice', 'profile_id': 'foreign'}, {}, 'profile_mismatch'),+ ({'user_id': 'alice'}, {'room_id': 'foreign'}, 'permission_denied'),+ ({'user_id': 'alice'}, {'actor': 'bob'}, 'invalid_params'),+ ]:+ peer = AuthorityConnection(authority, object(), identity)+ result = await peer.dispatch({'id': 1, 'method': method,+ 'params': {'room_id': 'owned', **params, **extra}})+ assert result['error']['message'] == reason, result+ assert service.calls == []+ service.runtime = SimpleNamespace(status=lambda: {'running': True, 'stopping': True})+ result = await owner.dispatch({'id': 1, 'method': 'groups.stop', 'params': {'room_id': 'owned'}})+ assert result['error']['message'] == 'runtime_coordination_required'+ caps = await owner.dispatch({'id': 1, 'method': 'groups.capabilities', 'params': {}})+ assert caps['result']['driver'] is False++ assert service.calls == []+ asyncio.run(probe())