The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: canonical API turns rebind the request's browser-controller identity
Teknium0aa578a51a05
diff --git a/gateway/run.py b/gateway/run.pyindex 2b69d04d113..8e1041d868e 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -4016,11 +4016,11 @@ class GatewayRunner(# True keeps CLI/unknown paths working; stateless adapters (api_server) declare False._adapter = (getattr(self, "adapters", None) or {}).get(context.source.platform)_async_delivery = getattr(_adapter, "supports_async_delivery", True)- # #98619: an admitted API turn carries its session-id provenance in the admission settings;- # every other platform leaves it undeclared (= not wake-capable).- from gateway.session_api_turn import api_execution- _api = api_execution.get()- _history_delivery = (_api["settings"].get("session_history_delivery") or "") if _api else None+ # #98619: an admitted API turn carries its session-id provenance in the admission settings,+ # and its rebound browser-controller identity; every other platform leaves both undeclared.+ from gateway.session_api_turn import api_session_vars+ _api_vars = api_session_vars()+ _history_delivery = _api_vars.pop("session_history_delivery", None)return set_session_vars(platform=context.source.platform.value,chat_id=context.source.chat_id,@@ -4039,7 +4039,7 @@ class GatewayRunner(message_id=str(context.source.message_id) if context.source.message_id else "",profile=getattr(context.source, "profile", "") or "",async_delivery=_async_delivery,- cron_session="", session_history_delivery=_history_delivery)+ cron_session="", session_history_delivery=_history_delivery, **_api_vars)def _clear_session_env(self, tokens: list) -> None:"""Restore session context variables to their pre-handler values."""diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex 66ee4c6d26e..52b0b4e5a27 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -40,10 +40,11 @@ def check_api_turn(authority, ref, payload):raise RuntimeStoreError('runtime_draining')if 'api_turn_v1' in payload:data = payload['api_turn_v1']- if (set(data) - {'history', 'settings', 'turn_author', 'media', 'run_owner_scope'}+ if (set(data) - {'history', 'settings', 'turn_author', 'media', 'run_owner_scope', 'browser_control'}or not {'history', 'settings'} <= set(data)or (data['history'] is not None and not isinstance(data['history'], list))- or ('run_owner_scope' in data and not _valid_owner_scope(data['run_owner_scope']))):+ or ('run_owner_scope' in data and not _valid_owner_scope(data['run_owner_scope']))+ or ('browser_control' in data and not _valid_browser_control(data['browser_control']))):raise RuntimeStoreError('invalid_params')if set(data['settings']) - set(_SETTING_KEYS):raise RuntimeStoreError('invalid_params')@@ -56,6 +57,52 @@ def _valid_owner_scope(value):return isinstance(value, str) and _OWNER_SCOPE_RE.fullmatch(value) is not None+def _valid_browser_control(value):+ return (isinstance(value, dict) and set(value) == {'principal', 'transport_family'}+ and isinstance(value['principal'], str) and value['principal'].startswith('principal:')+ and value['transport_family'] in ('local-api', 'remote-api'))+++def _request_browser_control():+ """The authenticated request's browser-controller identity, as the profile-prefix+ middleware derived it from the served profile and its API key; never client JSON."""+ from gateway.platforms.api_server import (+ _api_request_browser_control_principal, _api_request_browser_control_transport_family)+ bound = {'principal': _api_request_browser_control_principal.get(),+ 'transport_family': _api_request_browser_control_transport_family.get()}+ return bound if _valid_browser_control(bound) else None+++def _rebind_browser_control(adapter, data):+ """Re-derive the admitted principal from the profile's current API key before it is bound+ for execution (also after recovery). A rotated key no longer authorizes the old principal,+ so that turn runs unbound, like a request the middleware stamped nothing for."""+ bound = (data or {}).get('browser_control')+ if bound is None:+ return None+ from gateway.platforms.api_server import _api_request_profile+ profile = bound['principal'][len('principal:'):].rpartition(':')[0]+ token = _api_request_profile.set(None if profile == 'default' else profile)+ try:+ expected = adapter._derive_browser_control_principal(profile)+ finally:+ _api_request_profile.reset(token)+ return bound if hmac.compare_digest(bound['principal'], expected) else None+++def api_session_vars():+ """Session-context fields an executing API admission binds beyond the shared source:+ #98619 history-delivery provenance and the rebound browser-controller identity. ``{}``+ when no API admission is executing."""+ current = api_execution.get()+ if current is None:+ return {}+ bound = current.get('browser_control') or {}+ return {'session_history_delivery': current['settings'].get('session_history_delivery') or '',+ 'browser_control_principal': bound.get('principal', ''),+ 'browser_control_transport_family': bound.get('transport_family', '')}++def check_api_settings(adapter, settings):dispatch = settings.get('room_dispatch')if dispatch is not None:@@ -119,6 +166,11 @@ def admit_api_turn(adapter, **kwargs):# This opaque namespace is persisted in the same row/transaction as# admission. It is never a bearer credential or execution input.payload['api_turn_v1']['run_owner_scope'] = run_owner_scope+ browser_control = _request_browser_control()+ if browser_control is not None:+ # Server-derived like the owner scope: the admission keeps the identity the legacy+ # path bound for its executor, so execution and recovery can rebind it.+ payload['api_turn_v1']['browser_control'] = browser_control# Refuse a foreign-surface target before committing any media for it (a refused# admission otherwise retains its image bytes under native-inputs/ forever).existing = authority.db.get_session(sid)@@ -318,7 +370,8 @@ def prepare_api_execution(authority, ref, payload):from gateway.session_api_media import restore_api_imagescontent = restore_api_images(content, data.get('media') or [])return {'adapter': adapter, 'settings': settings, 'history': data['history'] if data else None,- 'content': content, 'turn_author': data.get('turn_author') if data else None}+ 'content': content, 'turn_author': data.get('turn_author') if data else None,+ 'browser_control': _rebind_browser_control(adapter, data)}def _api_observers(authority, session_id):diff --git a/tests/gateway/test_api_canonical_projection.py b/tests/gateway/test_api_canonical_projection.pyindex 91efe677a01..db142e3000b 100644--- a/tests/gateway/test_api_canonical_projection.py+++ b/tests/gateway/test_api_canonical_projection.py@@ -327,3 +327,54 @@ async def test_canonical_sse_projects_the_turn_reasoning(api, owner, path, body,text = await response.text()assert response.status == 200, textassert marker in text and 'THINKING' in text, text++[email protected]('path', ['legacy', 'canonical'])+async def test_api_turn_selects_the_requests_registered_browser_controller(api, owner, monkeypatch, path):+ """The extension controller registered for the API session's server-derived principal is the+ one the turn selects, on the legacy executor and under the authority alike."""+ from gateway import browser_control_broker as broker_mod+ from gateway.config import PlatformConfig+ from gateway.run import GatewayRunner+ from gateway.session import SessionContext+ from gateway.session_context import clear_session_vars+ from tools.browser_extension_router import extension_controller_available+ monkeypatch.setattr(broker_mod, 'browser_control_enabled', lambda *a: True)+ adapter = api if path == 'canonical' else _api_server.APIServerAdapter(PlatformConfig(enabled=True))+ adapter._api_key = 'controller-selection-key'+ broker = broker_mod.get_browser_control_broker()+ broker.attach(broker_mod.ControllerScope(+ principal_id=adapter._derive_browser_control_principal('default'), profile_id='default',+ session_id='browser-sel', controller_id='ext-1', transport_family='local-api',+ capabilities=frozenset({'browser_navigate'})), lambda frame: None)+ selected = []+ if path == 'canonical':+ async def handle(event):+ from gateway.session_results import execution_result+ context = SessionContext(source=event.source, connected_platforms=[], home_channels={},+ session_key='k', session_id=event.source.chat_id)+ tokens = GatewayRunner._set_session_env(owner.runner, context)+ try:+ selected.append(extension_controller_available('browser_navigate'))+ finally:+ clear_session_vars(tokens)+ execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}+ return 'ok'+ owner.runner._handle_message = handle+ else:+ def run_conversation(**kwargs):+ selected.append(extension_controller_available('browser_navigate'))+ return {'final_response': 'ok', 'messages': []}+ monkeypatch.setattr(adapter, '_create_agent', lambda **kw: SimpleNamespace(run_conversation=run_conversation))+ app = web.Application(middlewares=[adapter._make_profile_prefix_middleware()])+ app.router.add_post('/v1/chat/completions', adapter._handle_chat_completions)+ try:+ async with TestClient(TestServer(app)) as client:+ response = await client.post('/v1/chat/completions', json={'messages': [{'role': 'user', 'content': 'hi'}]},+ headers={'Authorization': 'Bearer controller-selection-key',+ 'X-Hermes-Session-Id': 'browser-sel'})+ assert response.status == 200, await response.text()+ finally:+ broker.reset()+ assert selected == [True]