The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): never run an external secret command inside the exit-flush budget
teknium1cbeedffc9079
diff --git a/tests/tui_gateway/test_reaper_flush_profile_scope.py b/tests/tui_gateway/test_reaper_flush_profile_scope.pyindex f804cf1e738..14afd853ae6 100644--- a/tests/tui_gateway/test_reaper_flush_profile_scope.py+++ b/tests/tui_gateway/test_reaper_flush_profile_scope.py@@ -1,11 +1,18 @@-"""The idle reaper's incremental transcript flush must land in the SESSION's profile home.+"""The reaper/exit-flush transcript persistence: right home, no external-secret hydration.``session_reaper._flush_session_messages`` runs on the reaper tick and on the exit-flush worker —-threads with no turn on the stack. Unscoped, ``agent._persist_session`` resolved-``get_hermes_home()`` to the LAUNCH profile, so a served profile's transcript was written into-another tenant's state.db. ``_finalize_session`` binds the same session at the same chokepoint.+threads with no turn on the stack. The transcript ROWS were never at risk (a profile session gets a+dedicated ``SessionDB`` whose ``db_path`` is frozen at construction), but everything+``agent._persist_session`` resolves at CALL time — config.yaml, the token ledger, memory/provider+lookups — resolved against the LAUNCH profile for a served profile's flush. ``_finalize_session``+binds the same session at the same chokepoint.++Binding that scope must stay CHEAP: it happens inside a 5s total exit-flush budget, and hydrating+the profile's external secret sources shells out to the operator's secret command (30s CLI budget)+— persisting a transcript needs no external credential."""import threading+import timeimport pytest@@ -31,14 +38,47 @@ def homes(tmp_path, monkeypatch):return launch, served-def test_incremental_flush_persists_into_the_sessions_own_home(homes, monkeypatch):- launch, served = homes- seen: list[str] = []- session = {"agent": _Agent(seen), "profile_home": str(served)}+def _install_session(monkeypatch, session):monkeypatch.setattr(tui_server, "_sessions", {"sid": session}, raising=False)monkeypatch.setattr(tui_server, "_sessions_lock", threading.RLock(), raising=False)monkeypatch.setattr(tui_server, "_INCREMENTAL_FLUSH_INTERVAL_S", 30.0, raising=False)++def test_incremental_flush_persists_into_the_sessions_own_home(homes, monkeypatch):+ launch, served = homes+ seen: list[str] = []+ _install_session(monkeypatch, {"agent": _Agent(seen), "profile_home": str(served)})+assert tui_server._flush_dirty_sessions(now=1000.0) == 1assert seen == [str(served)], f"transcript flushed into {seen} instead of the served home"assert str(launch) not in seen+++def test_exit_flush_never_waits_on_an_external_secret_source(homes, monkeypatch):+ """A slow ``op run`` / ``bws`` source must not cost the transcript the exit flush exists to save."""+ _launch, served = homes+ from hermes_cli import env_loader++ def _slow_source(_home):+ time.sleep(2.0) # a real secret CLI gets a 30s budget; this whole flush gets 1s+ return {}++ monkeypatch.setattr(env_loader, "hydrate_profile_secret_sources", _slow_source)+ _install_session(monkeypatch, {"agent": _Agent([]), "profile_home": str(served)})++ assert tui_server._flush_sessions_before_exit(budget_s=1.0) == 1+++def test_exit_flush_warns_when_it_loses_a_transcript(homes, monkeypatch, caplog):+ """Both callers discard the return value, so an overrun is invisible without this line."""+ _launch, served = homes++ class _Stuck(_Agent):+ def _persist_session(self, _messages):+ time.sleep(2.0)++ _install_session(monkeypatch, {"agent": _Stuck([]), "profile_home": str(served)})++ with caplog.at_level("WARNING"):+ assert tui_server._flush_sessions_before_exit(budget_s=0.2) == 0+ assert any("Exit flush persisted 0 of 1" in r.getMessage() for r in caplog.records), caplog.textdiff --git a/tui_gateway/model_switch.py b/tui_gateway/model_switch.pyindex ce6ac65abc3..8e62abccdb6 100644--- a/tui_gateway/model_switch.py+++ b/tui_gateway/model_switch.py@@ -51,7 +51,7 @@ def _restore_agent_model_runtime(agent, snapshot: dict | None) -> None:agent.reasoning_config = snapshot["reasoning_config"]-def _profile_runtime_scope_tokens(profile_home) -> "_TurnScopes":+def _profile_runtime_scope_tokens(profile_home, *, hydrate_secrets: bool = True) -> "_TurnScopes":"""Bind HERMES_HOME + secret + terminal scope for ``profile_home`` (None = launch profile) andreturn the reset tokens. The launch profile's SECRET scope is always bound — its ``.env`` overthe launch env (live while single-profile, frozen at activation afterwards; never live@@ -59,14 +59,21 @@ def _profile_runtime_scope_tokens(profile_home) -> "_TurnScopes":source is fixed at entry and an in-flight launch body survives a concurrent first-secondaryactivation instead of hitting ``UnscopedSecretError`` mid-request. Its terminal policy is boundonly once multiplexing is active: single-profile terminal execution keeps the standalone- ``os.environ`` bridge."""+ ``os.environ`` bridge.++ ``hydrate_secrets=False`` skips resolving the profile's EXTERNAL secret sources (``op run``,+ ``bws``, ``sh -c`` — a subprocess with a 30s CLI budget holding a process-global lock). Pass it+ from any body that persists state rather than calls a provider: the exit-flush worker has a 5s+ TOTAL budget, and one slow source there costs the transcript the flush exists to save.+ """from agent.secret_scope import is_multiplex_activescopes = _TurnScopes()if profile_home:home = Path(profile_home)# External sources first: the requested profile may never have been served in this process.- from hermes_cli.env_loader import hydrate_profile_secret_sources- hydrate_profile_secret_sources(home)+ if hydrate_secrets:+ from hermes_cli.env_loader import hydrate_profile_secret_sources+ hydrate_profile_secret_sources(home)secrets = build_profile_secret_scope(home)overlay = Nonescopes.home = set_hermes_home_override(str(home))@@ -111,10 +118,10 @@ def _release_profile_runtime_scope_tokens(scopes: "_TurnScopes | None") -> None:@contextlib.contextmanager-def _session_profile_runtime_scope(session: dict):+def _session_profile_runtime_scope(session: dict, *, hydrate_secrets: bool = True):"""Bind model resolution to the session's profile config and secrets (launch profile includedonce the process multiplexes; see ``_profile_runtime_scope_tokens``)."""- scopes = _profile_runtime_scope_tokens(session.get("profile_home"))+ scopes = _profile_runtime_scope_tokens(session.get("profile_home"), hydrate_secrets=hydrate_secrets)try:yieldfinally:diff --git a/tui_gateway/session_reaper.py b/tui_gateway/session_reaper.pyindex e872816585f..6c24492960a 100644--- a/tui_gateway/session_reaper.py+++ b/tui_gateway/session_reaper.py@@ -20,6 +20,13 @@ from .method_ctx import bind_module# (b) the idle-reaper scan piggybacks an incremental flush so a SIGKILL loses at most one interval.+def _session_has_pending_flush(session: dict | None) -> bool:+ """Would :func:`_flush_session_messages` write anything for this session? (The exit flush counts+ these to tell a complete flush from a budget overrun.)"""+ agent = session.get("agent") if isinstance(session, dict) else None+ return bool(hasattr(agent, "_persist_session") and getattr(agent, "_session_messages", None))++def _flush_session_messages(session: dict | None) -> bool:"""Best-effort durable flush of one session's transcript via ``agent._persist_session`` (same marker-dedupedcontract as ``_finalize_session``: repeated calls never duplicate rows).@@ -30,12 +37,18 @@ def _flush_session_messages(session: dict | None) -> bool:snapshot = getattr(agent, "_session_messages", None) if hasattr(agent, "_persist_session") else Noneif not snapshot:return False- # state.db, config and the token ledger are resolved at CALL time, and every caller of this helper- # is an unscoped reaper / exit-flush thread with no turn on the stack. Without the session's own- # binding a SERVED profile's transcript is written into the LAUNCH profile's home — the same class- # as _finalize_session, which binds it at the identical chokepoint (session_lifecycle.py).+ # config.yaml, the token ledger and the memory/provider lookups ``_persist_session`` touches are+ # resolved at CALL time, and every caller of this helper is an unscoped reaper / exit-flush thread+ # with no turn on the stack — so a SERVED profile's flush resolved them against the LAUNCH home.+ # (The transcript ROWS were never at risk: a profile session gets its own SessionDB whose db_path+ # is frozen at construction, tui_gateway/server.py::_open_profile_session_db). Same binding+ # _finalize_session makes at the identical chokepoint (session_lifecycle.py).+ #+ # hydrate_secrets=False: persisting a transcript needs no external credential, and hydration+ # shells out to the operator's secret command (30s CLI budget, process-global lock) inside a+ # worker whose whole budget is 5s — one slow source silently lost the transcript.try:- with _session_profile_runtime_scope(session or {}):+ with _session_profile_runtime_scope(session or {}, hydrate_secrets=False):agent._persist_session(snapshot)return Trueexcept Exception:@@ -76,10 +89,12 @@ def _flush_sessions_before_exit(budget_s: float | None = None) -> int:if budget <= 0:return 0result = {"flushed": 0}+ sessions = _reaper_session_snapshot()+ flushable = sum(1 for s in sessions if _session_has_pending_flush(s))def _run() -> None:deadline = time.monotonic() + budget- for session in _reaper_session_snapshot():+ for session in sessions:if time.monotonic() >= deadline:breakresult["flushed"] += _flush_session_messages(session)@@ -87,6 +102,14 @@ def _flush_sessions_before_exit(budget_s: float | None = None) -> int:worker = threading.Thread(target=_run, daemon=True, name="hermes-exit-flush")worker.start()worker.join(budget)+ # Silent loss is the failure mode this guard exists to prevent: both callers discard the return+ # value, so a budget overrun (a slow state.db write, a scope binding that shells out) looks+ # exactly like a clean exit.+ if result["flushed"] < flushable:+ logger.warning(+ "Exit flush persisted %d of %d in-memory session transcript(s) within %.1fs; the rest "+ "may have been lost (HERMES_TUI_EXIT_FLUSH_BUDGET_S)",+ result["flushed"], flushable, budget)return result["flushed"]