The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): hydrate an admitted turn's profile secrets off the owner loop
Tekniuma3e89a1d8791
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 4a4ba6deec8..97440c7529b 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -214,7 +214,6 @@ async def execute_admission(authority, ref, row):if provenance is not None:from gateway.session_ingress_context import restore_provenancehome = restore_provenance(authority.runner, event.source, provenance)- scope = _execution_scope(authority, home)from gateway.config import Platformfrom gateway.session_api_turn import api_execution, prepare_api_executionfrom gateway.session_results import execution_result@@ -229,7 +228,7 @@ async def execute_admission(authority, ref, row):event._turn_marker_handoff = Truehanded = Falsetry:- with scope:+ with await _execution_scope(authority, home):if is_api:# Committed media resolves under the owning profile's home, like admission did.prepared = prepare_api_execution(authority, ref, row['payload'])@@ -281,17 +280,19 @@ async def execute_admission(authority, ref, row):admission_author.reset(author_token)-def _execution_scope(authority, home):+async def _execution_scope(authority, home):"""Under multiplex, owner-side execution runs under the OWNING profile's home (agent build,config, secrets, state.db), never the launch profile's ambient scope; native provenance- (``home``) refines it. A single-profile gateway keeps its ambient scope byte-for-byte."""- if home is not None:- from gateway.run import _profile_runtime_scope- return _profile_runtime_scope(home)- if getattr(getattr(authority.runner, 'config', None), 'multiplex_profiles', False):- from gateway.session_authorities import owner_scope- return owner_scope(authority, hydrate_secrets=True)- return nullcontext()+ (``home``) refines it. A single-profile gateway keeps its ambient scope byte-for-byte.+ Secret sources (external CLIs) hydrate off the loop, as main's per-message scope does (#99519)."""+ if home is None and getattr(getattr(authority.runner, 'config', None), 'multiplex_profiles', False):+ from pathlib import Path+ owner = Path(str(authority.profile_id)) # owner_scope's home: symbolic test ids keep ambient+ home = owner if owner.is_absolute() and owner.is_dir() else None+ if home is None:+ return nullcontext()+ from gateway.run import _load_profile_secret_scope, _profile_runtime_scope+ return _profile_runtime_scope(home, await asyncio.to_thread(_load_profile_secret_scope, home))async def deliver_settled(authority, admission_id):@@ -316,7 +317,7 @@ async def deliver_settled(authority, admission_id):returnadapter, event, session_key, response, home = deliverytry:- with _execution_scope(authority, home):+ with await _execution_scope(authority, home):await deliver_response(adapter, event, session_key, response)except Exception:logger.exception('Delivery of settled admission %s failed', admission_id)diff --git a/tests/gateway/test_native_execution_secret_scope_off_loop.py b/tests/gateway/test_native_execution_secret_scope_off_loop.pynew file mode 100644index 00000000000..3c3e8516c8a--- /dev/null+++ b/tests/gateway/test_native_execution_secret_scope_off_loop.py@@ -0,0 +1,62 @@+"""Admitted native turns hydrate profile secret sources off the owner loop (main #99519 parity)."""+import threading++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.base import SendResult+from gateway.run import GatewayRunner+from gateway.session_authority import initialize_session_authority+from gateway.session_results import execution_result+from tests.waiting import async_wait_until++CHAT = '[email protected]'+++async def test_native_execution_and_settled_delivery_hydrate_secrets_off_loop(tmp_path, monkeypatch):+ import hermes_cli.env_loader as env_loader+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter+ monkeypatch.setenv('WHATSAPP_ALLOWED_USERS', '15551234567')+ hydrations = []+ real_hydrate = env_loader.hydrate_profile_secret_sources++ def hydrate(home, *args, **kwargs):+ # An external secret CLI (1Password, vault) blocks here; the turn's scope must never run it on+ # the loop thread. The authorization check's own scope is main's code (same on main).+ import traceback+ stack = ''.join(traceback.format_stack())+ if '_under_authorization_profile' not in stack:+ hydrations.append(threading.current_thread() is loop_thread)+ return real_hydrate(home, *args, **kwargs)++ monkeypatch.setattr(env_loader, 'hydrate_profile_secret_sources', hydrate)+ loop_thread = threading.current_thread()+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={+ 'text_batch_delay_seconds': 0, 'session_path': str(tmp_path / 'wa')}))+ adapter.gateway_runner, runner.adapters = runner, {Platform.WHATSAPP: adapter}+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='secrets')+ runner._wire_adapter_handlers(adapter)+ sent = []++ async def send(chat_id, content, **_):+ sent.append(content)+ return SendResult(success=True, message_id='s')++ async def turn(event, *_args, **_kwargs):+ execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}+ return 'ok'++ monkeypatch.setattr(adapter, 'send', send)+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)+ try:+ event = await adapter._build_message_event({'messageId': 'm1', 'chatId': CHAT, 'senderId': CHAT,+ 'body': 'hello', 'nativeType': 'conversation'})+ hydrations.clear() # admission-side scope (_async_profile_runtime_scope) is already off-loop+ adapter._enqueue_text_event(event)+ await async_wait_until(lambda: sent and not adapter._background_tasks, timeout=20, what='the reply')+ assert sent == ['ok']+ assert hydrations and True not in hydrations, hydrations+ finally:+ authority.db.close()