The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): offload handoff secret scope loading
fangliquanflqf069ffd471a1
diff --git a/gateway/run.py b/gateway/run.pyindex 2c546c01264..37c3c69379f 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2423,7 +2423,10 @@ def _current_max_iterations() -> int:return _resolve_turn_limit(os.getenv("HERMES_MAX_ITERATIONS"))-from contextlib import contextmanager as _contextmanager+from contextlib import (+ asynccontextmanager as _asynccontextmanager,+ contextmanager as _contextmanager,+)# Platforms that bind a host TCP port (HTTP/webhook listeners). In a profile@@ -2559,8 +2562,24 @@ def _terminal_scope_cwd(default: str = "") -> str:return _ts_env("TERMINAL_CWD", default)+def _load_profile_secret_scope(profile_home: "Path") -> dict:+ """Hydrate and load one profile's secrets under its home override."""+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override+ from agent.secret_scope import build_profile_secret_scope+ from hermes_cli.env_loader import hydrate_profile_secret_sources++ home_token = set_hermes_home_override(str(profile_home))+ try:+ hydrate_profile_secret_sources(Path(profile_home))+ return build_profile_secret_scope(Path(profile_home))+ finally:+ reset_hermes_home_override(home_token)++@_contextmanager-def _profile_runtime_scope(profile_home: "Path"):+def _profile_runtime_scope(+ profile_home: "Path", prepared_secret_scope: Optional[dict] = None,+):"""Scope config/skills/memory AND credentials to a profile for one turn.Combines the two seams the multiplexer needs:@@ -2580,15 +2599,17 @@ def _profile_runtime_scope(profile_home: "Path"):"""from hermes_constants import set_hermes_home_override, reset_hermes_home_overridefrom agent.secret_scope import (- build_profile_secret_scope,set_secret_scope,reset_secret_scope,)- from hermes_cli.env_loader import hydrate_profile_secret_sourceshome_token = set_hermes_home_override(str(profile_home))- hydrate_profile_secret_sources(Path(profile_home))- secret_token = set_secret_scope(build_profile_secret_scope(Path(profile_home)))+ secrets = (+ prepared_secret_scope+ if prepared_secret_scope is not None+ else _load_profile_secret_scope(Path(profile_home))+ )+ secret_token = set_secret_scope(secrets)# Per-turn terminal scope (third seam of the profile boundary): installs# the routed profile's COMPLETE terminal policy — never ambient env — via# tools.terminal_scope. Without it terminal_tool reads the process-global@@ -2604,6 +2625,14 @@ def _profile_runtime_scope(profile_home: "Path"):reset_hermes_home_override(home_token)+@_asynccontextmanager+async def _async_profile_runtime_scope(profile_home: "Path"):+ """Enter a profile scope without loading secret files on the event loop."""+ secrets = await asyncio.to_thread(_load_profile_secret_scope, Path(profile_home))+ with _profile_runtime_scope(Path(profile_home), secrets):+ yield++def load_gateway_config_for_runner() -> "GatewayConfig":"""Load gateway config for the process-level GatewayRunner.@@ -14874,7 +14903,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif _phome is None:await _reclaim_stale(self)else:- with _profile_runtime_scope(_phome):+ async with _async_profile_runtime_scope(_phome):await _reclaim_stale(self)except Exception:logger.debug("Stale-handoff reclaim failed", exc_info=True)@@ -14886,7 +14915,7 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewif profile_home is None:await _tick(profile_name)else:- with _profile_runtime_scope(profile_home):+ async with _async_profile_runtime_scope(profile_home):await _tick(profile_name)except asyncio.CancelledError:raisediff --git a/tests/gateway/test_handoff_watcher_multiprofile.py b/tests/gateway/test_handoff_watcher_multiprofile.pyindex 08bcf95710e..bea32bc7bce 100644--- a/tests/gateway/test_handoff_watcher_multiprofile.py+++ b/tests/gateway/test_handoff_watcher_multiprofile.py@@ -15,6 +15,7 @@ These tests pin the two halves of the fix:"""import asyncio+import threadingimport typesfrom pathlib import Path@@ -111,14 +112,14 @@ async def test_watcher_enters_profile_scope_for_each_home(monkeypatch):def __init__(self, home):self.home = home- def __enter__(self):+ async def __aenter__(self):entered.append(self.home)return self- def __exit__(self, *exc):+ async def __aexit__(self, *exc):return False- monkeypatch.setattr(run, "_profile_runtime_scope", _SpyScope)+ monkeypatch.setattr(run, "_async_profile_runtime_scope", _SpyScope)async def _no_sleep(_seconds):return None@@ -159,6 +160,68 @@ async def test_watcher_enters_profile_scope_for_each_home(monkeypatch):assert db.polls == 3, "root + both profiles polled once each per tick"+async def test_slow_profile_secret_load_does_not_block_event_loop(monkeypatch, tmp_path):+ """A slow profile ``.env`` read must not stall unrelated loop work."""+ profile_home = tmp_path / "profiles" / "slow"+ profile_home.mkdir(parents=True)+ monkeypatch.setattr(+ run,+ "_handoff_watch_scopes",+ lambda _runner: [(None, None), ("slow", profile_home)],+ )++ from agent import secret_scope++ load_started = threading.Event()+ ticker_progressed = threading.Event()+ ticker_progressed_while_loading = []++ def _slow_build(_home):+ load_started.set()+ ticker_progressed_while_loading.append(+ ticker_progressed.wait(timeout=2)+ )+ return {}++ monkeypatch.setattr(secret_scope, "build_profile_secret_scope", _slow_build)++ class _DB:+ async def list_pending_handoffs(self):+ return []++ fake = types.SimpleNamespace(+ _session_db=_DB(),+ _running=False,+ )++ async def _process_handoff(_row, _profile_name=None):+ return None++ fake._process_handoff = _process_handoff++ real_sleep = asyncio.sleep++ async def _skip_initial_delay(seconds):+ await real_sleep(0 if seconds == 5 else seconds)++ monkeypatch.setattr(run.asyncio, "sleep", _skip_initial_delay)+ async def _ticker():+ assert await asyncio.to_thread(load_started.wait, 5)+ ticker_progressed.set()++ watcher = asyncio.create_task(+ run.GatewayRunner._handoff_watcher(fake, interval=0.0)+ )+ ticker = asyncio.create_task(_ticker())+ await asyncio.wait_for(asyncio.gather(watcher, ticker), timeout=5)++ assert ticker_progressed_while_loading == [True], (+ "profile secret loading blocked the asyncio event loop until the "+ "filesystem operation completed"+ )++@pytest.mark.asyncioasync def test_each_scope_resolves_its_own_store_and_profile(monkeypatch):"""The whole point: a DIFFERENT ``state.db`` per scope, and the profile@@ -183,15 +246,15 @@ async def test_each_scope_resolves_its_own_store_and_profile(monkeypatch):def __init__(self, home):self.home = home- def __enter__(self):+ async def __aenter__(self):active["home"] = self.homereturn self- def __exit__(self, *exc):+ async def __aexit__(self, *exc):active["home"] = Nonereturn False- monkeypatch.setattr(run, "_profile_runtime_scope", _SpyScope)+ monkeypatch.setattr(run, "_async_profile_runtime_scope", _SpyScope)async def _no_sleep(_seconds):return Nonediff --git a/tests/gateway/test_handoff_watcher_resilience.py b/tests/gateway/test_handoff_watcher_resilience.pyindex cfe672b784c..b7b4e25d73a 100644--- a/tests/gateway/test_handoff_watcher_resilience.py+++ b/tests/gateway/test_handoff_watcher_resilience.py@@ -219,13 +219,13 @@ async def test_reclaim_runs_per_profile_store(monkeypatch):def __init__(self, home):self.home = home- def __enter__(self):+ async def __aenter__(self):return self- def __exit__(self, *exc):+ async def __aexit__(self, *exc):return False- monkeypatch.setattr(run, "_profile_runtime_scope", _Scope)+ monkeypatch.setattr(run, "_async_profile_runtime_scope", _Scope)async def _no_sleep(_seconds):return None