The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): seat the bots a gateway serves in Desktop groups, and name a refused one
David Dudok de Wite8e954dc9b8a
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.pyindex 1c4393cea27..3821374706d 100644--- a/gateway/hosted_room_discussion.py+++ b/gateway/hosted_room_discussion.py@@ -233,8 +233,10 @@ def _validate_member_target(value: Any, *, profile: str, known_profiles: set[strtarget = _exact_fields(value, label=f"member {index} {kind} target", required=_TARGET_FIELDS[kind])target_profile = _identifier(target["profile"], label=f"member {index} target profile")if kind == "local":- if target_profile != profile or profile not in known_profiles:- raise DiscussionValidationError(f"member {index} local target does not match a local profile")+ if target_profile != profile:+ raise DiscussionValidationError(f"member {index} local target profile does not match member profile")+ if profile not in known_profiles:+ raise DiscussionValidationError(f"member {index} profile '{profile}' is not local to this gateway")return {"kind": "local", "profile": profile}if target_profile != profile:raise DiscussionValidationError(f"member {index} peer target profile does not match member profile")diff --git a/gateway/session_authorities.py b/gateway/session_authorities.pyindex bf448ca2c14..d858c860afe 100644--- a/gateway/session_authorities.py+++ b/gateway/session_authorities.py@@ -98,7 +98,16 @@ class SessionAuthorities:def serving(self) -> list:"""Authorities that accept work: not a reserved-but-unbuilt slot, not one retiring (afailed serve or an unserve whose turn outlived Stop keeps its slot but refuses admissions)."""- return [a for a in self._by_key.values() if a is not None and not getattr(a, 'retiring', False)]+ # A snapshot: hosted-room coordinator threads read the served set while the loop hot-serves.+ return [a for a in list(self._by_key.values()) if a is not None and not getattr(a, 'retiring', False)]++ def named_serving(self) -> list[tuple[str, object]]:+ """``(name, authority)`` for each of ``serving()``. A secondary goes by the name it was+ reserved under: re-deriving it from the resolved home misnames a ``profiles/<name>`` entry+ that is a link (it resolves outside ``profiles/`` and reads as ``default``), and a group+ must refuse such a profile by its own name rather than bind ``default`` to its home. The+ launch profile keeps ``served_profile_name``, the label its sessions and clients use."""+ return [(self.profile_name(a) or served_profile_name(a.profile_id), a) for a in self.serving()]def served_profiles(self) -> list[dict]:return [{'profile_id': a.profile_id, 'home': a.profile_id} for a in self.serving()]diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 0477b2d8042..83f38693437 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -107,6 +107,12 @@ class AuthorityConnection:self._identity, self._operator, self._siblings = identity, operator, {}authority.events[self.actor.transport_id] = transport+ @property+ def host_scoped(self):+ """A host-scoped grant (the Desktop's shared-primary socket, the dashboard gate) acts for+ every profile this process serves; any other grant is bound to its own profile."""+ return self._identity.get('profile_scope') == 'host'+def _sibling_for(self, profile):"""Connection bound to the sibling authority a ``profile`` param names, or None for our ownhome. Only a host-scoped grant (the Desktop's shared-primary socket, the dashboard gate)@@ -115,7 +121,7 @@ class AuthorityConnection:from hermes_cli.profiles import profile_matches_homeif profile_matches_home(profile, Path(self.authority.profile_id)):return None- if self._identity.get('profile_scope') != 'host':+ if not self.host_scoped:raise RuntimeStoreError('profile_mismatch')registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)for sibling in (registry or ()):diff --git a/gateway/session_group_controls.py b/gateway/session_group_controls.pyindex 43195086b75..43db6486e43 100644--- a/gateway/session_group_controls.py+++ b/gateway/session_group_controls.py@@ -69,7 +69,7 @@ async def dispatch_group_control(connection, method, params):if method == 'profiles.list':return _profiles(authority, actor, home, supplied)try:- return _group(authority, actor, home, method, supplied)+ return _group(authority, actor, method, supplied, host_scope=connection.host_scoped)except RuntimeStoreError:raiseexcept HostedRoomError as exc:@@ -79,7 +79,7 @@ async def dispatch_group_control(connection, method, params):return await asyncio.to_thread(invoke)-def _group(authority, actor, home, method, params):+def _group(authority, actor, method, params, *, host_scope=False):from gateway import hosted_rooms as roomsdb_path = authority.db.db_pathgateway_id = rooms.local_authority_gateway_id()@@ -160,15 +160,21 @@ def _group(authority, actor, home, method, params):return {'rooms': found, 'next_offset': next_offset}def create():- if service is not None:- return {'room': service.create_room(**params, admit=admit)}- from gateway.hosted_room_discussion import validate_roster- from gateway.session_authorities import served_profile_name- name = served_profile_name(home)- profiles = {name}- if name == 'default' and (home / 'profiles').is_dir():- profiles.update(path.name for path in (home / 'profiles').iterdir() if path.is_dir())- members = validate_roster(params.get('members'), local_profiles=profiles)+ from gateway.hosted_room_discussion import DiscussionValidationError, validate_roster+ from gateway.session_hosted_members import member_roster, refuse_unseatable+ # Only a host-scoped grant, the one that may address siblings directly+ # (``AuthorityConnection._sibling_for``), seats served siblings with no entry; a+ # profile-bound one seats its own profile plus its hosted_rooms.profiles entries, as+ # before. Both create paths validate here, by the driver's rule.+ homes, refused = member_roster(authority, siblings=host_scope)+ refuse_unseatable(params.get('members'), refused)+ try:+ members = validate_roster(params.get('members'), local_profiles=homes)+ if service is not None:+ return {'room': service.create_room(**params, admit=admit)}+ except DiscussionValidationError as exc:+ # Name the refused member; the bare code left Desktop and gateway.log silent (#139002).+ raise RuntimeStoreError('invalid_params', field='members', detail=str(exc)) from excnormalized = [{'member_id': m.member_id, 'profile': m.profile, 'handle': m.handle,'target': dict(m.target or {}),**({'display_name': m.display_name} if m.display_name else {})} for m in members]diff --git a/gateway/session_hosted_members.py b/gateway/session_hosted_members.pynew file mode 100644index 00000000000..c7fdfb49424--- /dev/null+++ b/gateway/session_hosted_members.py@@ -0,0 +1,142 @@+"""Which local profiles a hosted group on one authority may seat (#139002).++A group seats the profiles this process serves, plus the ``hosted_rooms.profiles`` destinations,+and nothing else: a profile directory alone seats nobody, because a member's turns need a live+owner. Served siblings need no entry, but only a host-scoped caller seats them that way; a+profile-bound caller seats its own profile plus the profiles its entries name, as before. One home+answers to one name. An entry that would break a rule is ignored and logged once, and only a new+member naming it is refused, so one bad entry never takes the rest of the roster down.+"""+from collections import Counter+import logging+from pathlib import Path++from hermes_state_runtime import RuntimeStoreError++logger = logging.getLogger(__name__)++# (profile, field, value, detail) already logged: the roster is re-read on every poll and turn,+# and an entry fixed and later broken another way is logged again.+_REPORTED: set[tuple[str, str, str, str]] = set()+++def member_roster(authority, *, siblings=True):+ """``(homes, refused)`` for a group on *authority*.++ ``homes`` maps name -> home. It holds *authority*'s own profile, each served sibling when+ ``siblings`` (the room driver, and a host-scoped caller), and each usable entry. A served+ profile keeps its served home under ``siblings``, whatever its entry says; a profile-bound+ caller's entry naming a served profile must match its served home. ``refused`` maps a name a+ new member may not take to ``(reason, field, detail)``. An alias stays in ``homes`` too, so a+ room that already seats it keeps running its other members (its own turns fail, as before).+ """+ from hermes_constants import hermes_home_key+ own, served, refused = _served(authority)+ blocked = set(refused)+ homes = dict(served)+ if not siblings:+ for name in [name for name in homes if name != own]:+ del homes[name]+ refused[name] = ('permission_denied', 'members',+ 'only a host-scoped connection seats a served profile without an entry')+ seated = {hermes_home_key(home): name for name, home in served.items()}+ for name, value in _configured(authority, own).items():+ if name in blocked:+ continue+ field = f'hosted_rooms.profiles.{name}'+ home, reason, detail = _config_entry(name, value, served, seated)+ if siblings and name in served:+ # Served: it needs no entry, and the served home wins over whatever this one says.+ if reason is not None:+ _report(own, field, value, detail)+ elif reason is None:+ homes[name] = home+ seated.setdefault(hermes_home_key(home), name)+ refused.pop(name, None)+ else:+ _report(own, field, value, detail)+ refused[name] = (reason, field, detail)+ if home is None:+ homes.pop(name, None)+ else:+ homes[name] = home+ return homes, refused+++def refuse_unseatable(members, refused):+ """Raise the named refusal for the first local member whose profile *refused* names;+ ``validate_roster`` names every other roster problem."""+ for index, raw in enumerate(members if isinstance(members, list) else ()):+ target = raw.get('target') if isinstance(raw, dict) else None+ profile = raw.get('profile') if isinstance(raw, dict) else None+ if isinstance(target, dict) and target.get('kind', 'local') != 'local':+ continue+ if isinstance(profile, str) and profile in refused:+ reason, field, detail = refused[profile]+ raise RuntimeStoreError(reason, field=field, detail=f"member {index} profile '{profile}': {detail}")+++def _served(authority):+ """``(own name, name -> home, refused)`` over the profiles this process serves, by the names+ the registry reserved them under. A name two homes answer to is refused, never bound."""+ from gateway.session_authorities import served_profile_name+ registry = getattr(getattr(authority, 'runner', None), 'session_authorities', None)+ pairs = registry.named_serving() if registry is not None else []+ own = next((name for name, served in pairs if served is authority), None)+ if own is None:+ # A bare authority (no registry), or a retiring one: it still owns its own rooms.+ own = served_profile_name(authority.profile_id)+ pairs = [(own, authority), *pairs]+ counts = Counter(name for name, _ in pairs)+ served, refused = {}, {}+ for name, served_authority in pairs:+ if counts[name] > 1:+ refused[name] = ('invalid_params', 'members', 'two served homes answer to that name')+ elif name != served_profile_name(served_authority.profile_id):+ # A linked profiles/<name> resolves outside profiles/; the member transport names a+ # destination by its resolved home, so every turn would fail on the name.+ refused[name] = ('invalid_params', 'members', 'a linked profile home is not supported in groups yet')+ else:+ served[name] = Path(served_authority.profile_id)+ return own, served, refused+++def _configured(authority, own):+ """The ``hosted_rooms.profiles`` mapping; a section left with no entries is empty."""+ from gateway.run import _load_gateway_config+ from gateway.session_authorities import owner_scope+ # The coordinator's own threads do not inherit the caller's ContextVars.+ with owner_scope(authority):+ section = _load_gateway_config().get('hosted_rooms')+ profiles = section.get('profiles') if isinstance(section, dict) else section+ if profiles is None or isinstance(profiles, dict):+ return profiles or {}+ _report(own, 'hosted_rooms.profiles', profiles, 'must map profile names to profile homes')+ return {}+++def _config_entry(name, value, served, seated):+ """``(home, reason, detail)`` for one entry: ``reason`` None seats ``home``; otherwise the entry+ is refused, and a ``home`` it still carries is an alias that existing rooms keep."""+ from gateway.hosted_rooms_common import IDENTIFIER_RE+ from hermes_constants import hermes_home_key+ if not isinstance(name, str) or not IDENTIFIER_RE.fullmatch(name) or not isinstance(value, str):+ return None, 'invalid_params', 'must map a profile name to a home'+ target = Path(value)+ if not target.is_absolute() or target != target.resolve():+ return None, 'invalid_params', 'must be an absolute, resolved home'+ key = hermes_home_key(target)+ if name in served and hermes_home_key(served[name]) != key:+ return None, 'permission_denied', 'this gateway serves that profile from another home'+ if seated.get(key, name) != name:+ # Its turns reach that profile under the wrong name and fail every time.+ return target, 'invalid_params', f"names the home already seated as '{seated[key]}'"+ return served.get(name, target), None, None+++def _report(own, field, value, detail):+ """Log one ignored entry once per value, however often the roster is read."""+ key = (own, field, repr(value)[:200], detail)+ if key not in _REPORTED:+ _REPORTED.add(key)+ logger.warning('Ignoring %s for profile=%s: %s', field, own, detail)diff --git a/gateway/session_hosted_service.py b/gateway/session_hosted_service.pyindex 0f38e3df50e..e0bd13e23a2 100644--- a/gateway/session_hosted_service.py+++ b/gateway/session_hosted_service.py@@ -24,27 +24,8 @@ class CanonicalHostedRoomService(HostedControls, HostedRoomService):return selfdef profile_homes(self):- from gateway.run import _load_gateway_config- from gateway.hosted_rooms_common import IDENTIFIER_RE- from gateway.session_authorities import served_profile_name- home = Path(self.authority.profile_id)- own = served_profile_name(home)- # The coordinator's own threads do not inherit the caller's ContextVars.- with owner_scope(self.authority):- configured = _load_gateway_config().get('hosted_rooms', {}).get('profiles', {})- result = {own: home}- if not isinstance(configured, dict):- raise RuntimeStoreError('invalid_params')- for name, value in configured.items():- if not isinstance(name, str) or not isinstance(value, str):- raise RuntimeStoreError('invalid_params')- target = Path(value)- if not IDENTIFIER_RE.fullmatch(name) or not target.is_absolute() or target != target.resolve():- raise RuntimeStoreError('invalid_params')- if name == own and target != home:- raise RuntimeStoreError('permission_denied')- result[name] = target- return result+ from gateway.session_hosted_members import member_roster+ return member_roster(self.authority)[0]def local_profiles(self):return tuple(self.profile_homes())diff --git a/tests/gateway/test_hosted_group_members.py b/tests/gateway/test_hosted_group_members.pynew file mode 100644index 00000000000..2c78060f7f4--- /dev/null+++ b/tests/gateway/test_hosted_group_members.py@@ -0,0 +1,285 @@+"""Which local bots a Desktop group may seat, on a default install with no ``hosted_rooms`` key.++Regression for #139002: Desktop -> Bots -> New Group Chat refused every multi-bot group with a bare+``invalid_params``, because the canonical room service knew only its own profile and the+``hosted_rooms.profiles`` config, not the sibling profiles the same gateway serves. The rule now:+a group seats the profiles this gateway serves, plus configured destinations, and nothing else;+anything else is refused with the member it names.++Every request goes through the Desktop's own path: the host-scoped socket on the launch profile,+routed by ``profile`` to the active profile's real authority and canonical room service. A+connection bound to one profile (``_sibling_for`` refuses it any other) seats that profile plus the+profiles its ``hosted_rooms.profiles`` entries name, as before.+"""+import asyncio+from contextlib import contextmanager+import json+import logging+import os+import threading++import pytest++from tests.gateway.test_session_authorities_multiplex import _reserve_homes+from tests.waiting import wait_until+++@contextmanager+def _gateway(tmp_path, monkeypatch, *, served, unserved=(), linked=(), multiplex=True):+ """A running gateway over ``default`` + ``served`` + ``linked``; ``unserved`` profiles exist on+ disk only, and each ``linked`` profile is a ``profiles/<name>`` link to a home elsewhere."""+ from gateway.config import GatewayConfig+ from gateway.control_socket import GatewayControlServer+ from gateway.run import GatewayRunner+ from gateway.run_runtime import initialize_gateway_runtime, recover_gateway_native_sessions+ from gateway.runtime_ownership import process_ownership++ root, homes = _reserve_homes(tmp_path, monkeypatch, names=(*served, *unserved))+ homes = dict(homes)+ for name in linked:+ target = tmp_path / 'elsewhere' / name+ target.mkdir(parents=True)+ homes[name] = _link(target, root / 'profiles' / name)+ for home in homes.values():+ # A default install's profile config: no hosted_rooms key anywhere.+ (home / 'config.yaml').write_text(json.dumps({'model': {'default': 'fixture'}, 'platform_toolsets': {'cli': []}}))+ reserved = [(name, homes[name]) for name in ('default', *served, *linked)]+ config = GatewayConfig()+ config.multiplex_profiles = multiplex+ config._runtime_profile_homes = tuple(reserved)+ process_ownership.reserve([home for _, home in reserved])+ loop = asyncio.new_event_loop()+ thread = threading.Thread(target=loop.run_forever)+ thread.start()+ runner = GatewayRunner(config)++ def call(coroutine):+ return asyncio.run_coroutine_threadsafe(coroutine, loop).result(15)+ try:+ call(initialize_gateway_runtime(runner))+ descriptor = runner.session_runtime_descriptor+ descriptor.update(state='ready', capabilities=['session-authority-v1'],+ api_origin='http://127.0.0.1:1', supervisor='none')+ runner.session_control_server = GatewayControlServer(+ root, verb_handlers={'identify': lambda: descriptor})+ assert call(runner.session_control_server.start())+ call(recover_gateway_native_sessions(runner))+ yield runner, homes, call+ finally:+ for authority in getattr(runner, 'session_authorities', []):+ service = getattr(authority, 'hosted_room_service', None)+ if service is not None:+ assert service.stop(timeout=5)+ authority.db.close()+ if getattr(runner, 'session_control_server', None) is not None:+ call(runner.session_control_server.stop())+ loop.call_soon_threadsafe(loop.stop)+ thread.join(5)+ assert not thread.is_alive()+ loop.close()+ for _, home in reserved:+ process_ownership.release(home)+++def _link(target, link):+ """A directory link this host makes without privileges: a symlink, else a Windows junction."""+ try:+ os.symlink(target, link, target_is_directory=True)+ except OSError:+ try:+ import _winapi+ _winapi.CreateJunction(str(target), str(link))+ except (ImportError, OSError) as exc:+ pytest.skip(f'this host cannot link a profile directory: {exc}')+ return link+++def _desktop(runner, call, scope='host'):+ """The Desktop's host-scoped socket; ``profile`` names the active bot, as the Bots plugin sends it."""+ from gateway.session_controls import AuthorityConnection+ connection = AuthorityConnection(runner.session_authority, object(),+ {'user_id': 'desktop', 'profile_scope': scope})++ def request(active, method, **params):+ return call(connection.dispatch({'id': 1, 'method': method, 'params': {'profile': active, **params}}))+ return request+++def _members(*profiles):+ """The roster ``createCanonicalGroup`` sends: one local target per bot."""+ return [{'member_id': p, 'profile': p, 'handle': p, 'target': {'kind': 'local', 'profile': p}}+ for p in profiles]+++def test_desktop_group_of_served_bots_is_created_and_runs(tmp_path, monkeypatch):+ from gateway import hosted_rooms, session_finite+ from hermes_constants import get_hermes_home++ ran = []++ async def execute(authority, ref, row):+ ran.append((authority.profile_id, str(get_hermes_home())))+ return 'member reply'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)+ with _gateway(tmp_path, monkeypatch, served=('alpha', 'beta')) as (runner, homes, call):+ desktop = _desktop(runner, call)+ created = desktop('default', 'groups.create', room_id='crew', name='Crew',+ members=_members('default', 'alpha', 'beta'))+ assert 'result' in created, created+ assert [m['profile'] for m in created['result']['room']['members']] == ['default', 'alpha', 'beta']+ # The active bot may be any served sibling, seating the launch profile in turn.+ pair = desktop('beta', 'groups.create', room_id='pair', name='Pair', members=_members('beta', 'default'))+ assert 'result' in pair, pair++ # A seated sibling's turn runs in its own home, through the same membership the create used.+ sent = desktop('default', 'groups.send', room_id='crew', event_id='hello',+ payload={'text': '@alpha hello', 'thread_id': 'thread'})+ assert 'result' in sent, sent+ db_path = runner.session_authority.db.db_path+ wait_until(lambda: any(e['kind'] == 'room.activity' and e['payload'].get('status') == 'settled'+ for e in hosted_rooms.read_events(db_path, room_id='crew')['events']),+ what='the room settled after alpha answered')+ assert ran == [(str(homes['alpha']), str(homes['alpha']))], [+ e['payload'] for e in hosted_rooms.read_events(db_path, room_id='crew')['events']]+++def test_a_bot_this_gateway_does_not_serve_is_refused_by_name(tmp_path, monkeypatch, caplog):+ caplog.set_level(logging.WARNING, logger='gateway.session_controls')+ # gamma is a real profile on disk, but this gateway does not serve it; ghost does not exist.+ with _gateway(tmp_path, monkeypatch, served=('alpha',), unserved=('gamma',)) as (runner, homes, call):+ desktop = _desktop(runner, call)+ # Both create paths apply the same rule: the room driver's, and the one used while it is stopped.+ for driver in ('running', 'stopped'):+ for refused in ('gamma', 'ghost'):+ reply = desktop('default', 'groups.create', room_id=f'{refused}-{driver}', name='Crew',+ members=_members('default', refused))+ assert reply['error']['message'] == 'invalid_params', reply+ assert reply['error']['data']['field'] == 'members', reply+ assert f"profile '{refused}' is not local to this gateway" in reply['error']['data']['detail'], reply+ seated = desktop('default', 'groups.create', room_id=f'seated-{driver}', name='Crew',+ members=_members('default', 'alpha'))+ assert 'result' in seated, seated+ assert runner.session_authority.hosted_room_service.stop(timeout=5)+ assert ("groups.create refused for profile=default: invalid_params field=members "+ "detail=member 1 profile 'gamma' is not local to this gateway") in caplog.text++ # A connection bound to one profile never reaches a sibling, so it cannot seat one either.+ bound = _desktop(runner, call, scope='profile')('default', 'groups.create', room_id='bound', name='Crew',+ members=_members('default', 'alpha'))+ assert bound['error']['data'] == {+ 'reason': 'permission_denied', 'field': 'members',+ 'detail': "member 1 profile 'alpha': only a host-scoped connection seats a served profile "+ "without an entry"}, bound+ # Its own hosted_rooms.profiles entry still seats a served profile at its served home, as on main.+ config = homes['default'] / 'config.yaml'+ alpha = runner.session_authorities.require(homes['alpha']).profile_id+ config.write_text(json.dumps({'hosted_rooms': {'profiles': {'alpha': alpha}}}))+ entry = _desktop(runner, call, scope='profile')('default', 'groups.create', room_id='entry', name='Crew',+ members=_members('default', 'alpha'))+ assert 'result' in entry, entry+ config.write_text('{}')+ # A sibling whose serve is being torn down runs nothing, so it is not seated.+ runner.session_authorities.require(homes['alpha']).retiring = True+ retiring = desktop('default', 'groups.create', room_id='retiring', name='Crew',+ members=_members('default', 'alpha'))+ assert "profile 'alpha' is not local to this gateway" in retiring['error']['data']['detail'], retiring+++def test_single_profile_gateway_seats_only_itself_and_configured_profiles(tmp_path, monkeypatch):+ with _gateway(tmp_path, monkeypatch, served=(), unserved=('beta',), multiplex=False) as (runner, homes, call):+ desktop = _desktop(runner, call)+ refused = desktop('default', 'groups.create', room_id='crew', name='Crew', members=_members('default', 'beta'))+ assert refused['error']['data'] == {+ 'reason': 'invalid_params', 'field': 'members',+ 'detail': "member 1 profile 'beta' is not local to this gateway"}, refused+ # A profile another local gateway owns still joins through its explicit destination entry,+ # from a connection bound to this profile too.+ config = homes['default'] / 'config.yaml'+ config.write_text(json.dumps({'hosted_rooms': {'profiles': {'beta': str(homes['beta'])}}}))+ bound = _desktop(runner, call, scope='profile')+ created = bound('default', 'groups.create', room_id='crew', name='Crew', members=_members('default', 'beta'))+ assert 'result' in created, created+++def test_a_bad_hosted_rooms_entry_refuses_only_the_member_naming_it(tmp_path, monkeypatch, caplog):+ from gateway import hosted_rooms, session_finite++ caplog.set_level(logging.WARNING, logger='gateway.session_hosted_members')+ ran = []++ async def execute(authority, ref, row):+ ran.append(authority.profile_id)+ return 'member reply'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)+ with _gateway(tmp_path, monkeypatch, served=('alpha', 'beta')) as (runner, homes, call):+ desktop, bound = _desktop(runner, call), _desktop(runner, call, scope='profile')+ config = homes['default'] / 'config.yaml'++ def create(request, room_id, *profiles):+ return request('default', 'groups.create', room_id=room_id, name='Crew', members=_members(*profiles))++ def ignored():+ return [r.getMessage() for r in caplog.records if r.name == 'gateway.session_hosted_members']+ # A room that seats helper while its entry names a home of its own.+ config.write_text(json.dumps({'hosted_rooms': {'profiles': {'helper': str(tmp_path.resolve())}}}))+ assert 'result' in create(desktop, 'kept', 'default', 'beta', 'helper')++ # Now alpha's entry moves a served bot, and helper's names beta's home a second time.+ config.write_text(json.dumps({'hosted_rooms': {'profiles': {+ 'alpha': str(homes['beta']), 'helper': str(homes['beta'])}}}))+ for attempt in range(2):+ assert 'result' in desktop('default', 'profiles.list', include_sessions=False)+ assert 'result' in create(desktop, f'rest-{attempt}', 'default', 'beta')+ # Desktop seats a served bot at its served home, whatever its entry says.+ assert 'result' in create(desktop, f'served-{attempt}', 'default', 'alpha')+ # A profile-bound connection seats it only through its entry, which must agree.+ assert create(bound, f'moved-{attempt}', 'default', 'alpha')['error']['data'] == {+ 'reason': 'permission_denied', 'field': 'hosted_rooms.profiles.alpha',+ 'detail': "member 1 profile 'alpha': this gateway serves that profile from another home"}+ assert create(desktop, f'alias-{attempt}', 'default', 'helper')['error']['data'] == {+ 'reason': 'invalid_params', 'field': 'hosted_rooms.profiles.helper',+ 'detail': "member 1 profile 'helper': names the home already seated as 'beta'"}+ # Each ignored entry is logged once, however often the roster is read.+ assert ignored() == [+ 'Ignoring hosted_rooms.profiles.alpha for profile=default: this gateway serves that profile from another home',+ "Ignoring hosted_rooms.profiles.helper for profile=default: names the home already seated as 'beta'"]+ # The room that already seats helper keeps running its other members.+ sent = desktop('default', 'groups.send', room_id='kept', event_id='hello',+ payload={'text': '@beta hello', 'thread_id': 'thread'})+ assert 'result' in sent, sent+ db_path = runner.session_authority.db.db_path+ wait_until(lambda: any(e['kind'] == 'room.activity' and e['payload'].get('status') == 'settled'+ for e in hosted_rooms.read_events(db_path, room_id='kept')['events']),+ what='the room settled after beta answered')+ assert ran == [str(homes['beta'])]++ # An entry fixed and then broken another way is logged again; a bare one does not drop alpha.+ config.write_text(json.dumps({'hosted_rooms': {'profiles': {'alpha': None}}}))+ assert 'result' in create(desktop, 'bare', 'default', 'alpha')+ assert ignored()[-1] == 'Ignoring hosted_rooms.profiles.alpha for profile=default: must map a profile name to a home'+ # A section whose entries are all commented out is empty; another shape is named in the log+ # and leaves every other refusal its own reason.+ config.write_text(json.dumps({'hosted_rooms': None}))+ assert 'result' in create(desktop, 'emptied', 'default', 'alpha')+ config.write_text(json.dumps({'hosted_rooms': {'profiles': ['helper']}}))+ assert 'result' in desktop('default', 'profiles.list', include_sessions=False)+ assert 'result' in create(desktop, 'listed', 'default', 'beta')+ assert create(desktop, 'ghost', 'default', 'ghost')['error']['data'] == {+ 'reason': 'invalid_params', 'field': 'members',+ 'detail': "member 1 profile 'ghost' is not local to this gateway"}+ assert ignored()[-1] == 'Ignoring hosted_rooms.profiles for profile=default: must map profile names to profile homes'+++def test_a_linked_profile_is_refused_by_name_until_groups_support_it(tmp_path, monkeypatch):+ # The member transport names a destination by its resolved home, which for a linked+ # profiles/<name> is outside profiles/: seated, every one of its turns would fail.+ with _gateway(tmp_path, monkeypatch, served=('alpha',), linked=('linked',)) as (runner, _homes, call):+ desktop = _desktop(runner, call)+ refused = desktop('default', 'groups.create', room_id='linked', name='Crew',+ members=_members('default', 'linked'))+ assert refused['error']['data'] == {+ 'reason': 'invalid_params', 'field': 'members',+ 'detail': "member 1 profile 'linked': a linked profile home is not supported in groups yet"}, refused+ # Its home never answers to another name: default still seats the rest.+ seated = desktop('default', 'groups.create', room_id='crew', name='Crew', members=_members('default', 'alpha'))+ assert 'result' in seated, seateddiff --git a/tests/gateway/test_session_group_controls.py b/tests/gateway/test_session_group_controls.pyindex 5ddc3b4136a..37d96398aba 100644--- a/tests/gateway/test_session_group_controls.py+++ b/tests/gateway/test_session_group_controls.py@@ -134,7 +134,7 @@ def test_groups_list_pages_the_actor_visible_rooms(tmp_path):actor = SimpleNamespace(subject='me')pages, params = [], {'limit': 2}while True:- page = _group(authority, actor, tmp_path, 'groups.list', params)+ page = _group(authority, actor, 'groups.list', params)pages.append([room['room_id'] for room in page['rooms']])if page['next_offset'] is None:breakdiff --git a/tests/gateway/test_session_group_execution_controls.py b/tests/gateway/test_session_group_execution_controls.pyindex f1467d89b82..d98c244f066 100644--- a/tests/gateway/test_session_group_execution_controls.py+++ b/tests/gateway/test_session_group_execution_controls.py@@ -1,5 +1,6 @@"""Native room controls retain the service protocol and authenticated ownership."""import asyncio+import jsonfrom types import SimpleNamespacefrom gateway.session_controls import AuthorityConnection@@ -61,6 +62,9 @@ class RoomService:def test_execution_controls_preserve_native_wire_and_exact_task_identity(tmp_path, monkeypatch):monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ # The control boundary validates the roster before any service sees it: helper is a destination.+ helper = (tmp_path / 'profiles' / 'helper').resolve()+ (tmp_path / 'config.yaml').write_text(json.dumps({'hosted_rooms': {'profiles': {'helper': str(helper)}}}))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'})diff --git a/website/docs/developer-guide/hosted-profile-owners.md b/website/docs/developer-guide/hosted-profile-owners.mdindex 1cb8e3a4412..576f9745b36 100644--- a/website/docs/developer-guide/hosted-profile-owners.md+++ b/website/docs/developer-guide/hosted-profile-owners.md@@ -6,7 +6,15 @@ room driver contacts destination owners through their private OS-authenticatedcontrol sockets; it never launches a legacy session worker or opens a destinationdatabase.-Configure explicit destinations in the source profile's configuration:+A room may seat the profiles its gateway serves: the gateway's own profile and,+under `gateway.multiplex_profiles`, every profile the multiplexer currently serves+(each served profile gets its own authority and database there). For a host-scoped+connection (Desktop's shared socket, the dashboard) these need no configuration;+this is the path Desktop's New Group Chat takes. A connection bound to one profile+seats that profile plus the profiles its `hosted_rooms.profiles` entries name, as+before; an entry naming a served profile must point at its served home. A profile+that another local gateway owns joins only as an explicit destination in the source+profile's configuration:```yamlhosted_rooms:@@ -14,13 +22,24 @@ hosted_rooms:helper: /absolute/path/to/profiles/helper```-The name must match the destination profile name. The destination profile needs a-live owner: its own standalone gateway, or the default multiplexer serving it under-`gateway.multiplex_profiles` (each served profile gets its own authority and-database there). Directory existence alone does not authorize execution.-Configuration entries are exposed as roster metadata without reading the-destination config or sessions. Hosted-room execution across two profiles served-by the same multiplexer is not live-certified yet.+The name must match the destination profile name, and the destination needs a live+owner: its own gateway (a `gateway.standalone` profile) or another local+multiplexer that serves it. One home answers to one name. On a host-scoped+connection a served profile keeps its served home whatever its entry says. An entry+that names a home already seated under another name, or is malformed, is ignored+with one log line, and only a new member naming it is refused; a room that already+seats such an alias keeps running its other members. Directory existence alone does+not authorize execution, so a profile that is installed but not served here+(parked, or owned by a gateway this one has no entry for) is refused at room+creation, with the member named in the refusal. A served profile whose+`profiles/<name>` directory is a link is refused too: the member transport cannot+reach it under its name yet. Configuration entries are exposed as roster metadata+without reading the destination config or sessions.++Execution between two profiles served by the same multiplexer is covered by+in-process tests that drive the real private control socket. It is not yet certified+on a live multi-profile install, and members whose profile directory is a link cannot+run turns.The destination reverse-checks current room ownership, membership, exact durabletask identity, hosted generation and frozen prompt with the source at submit and