Skip to content

The agent that grows with you

fix(gateway): a changed auxiliary secret returns that task to the primary route

Teknium41f8a5a7ac11
diff --git a/agent/auxiliary_task_config.py b/agent/auxiliary_task_config.py
index d6730533529..65d028eb0e8 100644
--- a/agent/auxiliary_task_config.py
+++ b/agent/auxiliary_task_config.py
@@ -7,11 +7,26 @@ under the user's block and may inherit another slot via ``inherit_from``.
from __future__ import annotations
+import contextlib
import logging
+from contextvars import ContextVar
from typing import Any, Dict
logger = logging.getLogger(__name__)
+# A gateway session's frozen effective ``auxiliary:`` section (recovered secrets applied, a task whose
+# secret changed returned to the primary route). Set for the turn; never the live config.yaml.
+_SESSION_AUXILIARY: ContextVar = ContextVar("session_auxiliary", default=None)
+
+
+def session_auxiliary_scope(auxiliary):
+ token = _SESSION_AUXILIARY.set(auxiliary if isinstance(auxiliary, dict) else {})
+ try:
+ yield
+ finally:
+ _SESSION_AUXILIARY.reset(token)
+
def _get_auxiliary_task_config(task: str, _seen: frozenset = frozenset()) -> dict[str, Any]:
"""Config dict for auxiliary.<task>, or {} when unavailable. Plugin-registered tasks get their
@@ -21,12 +36,14 @@ def _get_auxiliary_task_config(task: str, _seen: frozenset = frozenset()) -> dic
until the user pins a route on the task itself. ``_seen`` guards re-registration cycles."""
if not task:
return {}
- try:
- from hermes_cli.config import load_config_readonly
- config = load_config_readonly()
- except ImportError:
- return {}
- aux = config.get("auxiliary", {}) if isinstance(config, dict) else {}
+ aux = _SESSION_AUXILIARY.get()
+ if aux is None:
+ try:
+ from hermes_cli.config import load_config_readonly
+ config = load_config_readonly()
+ except ImportError:
+ return {}
+ aux = config.get("auxiliary", {}) if isinstance(config, dict) else {}
task_config = aux.get(task, {}) if isinstance(aux, dict) else {}
if not isinstance(task_config, dict):
task_config = {}
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 51fce7a285c..581869b8f5a 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -2,6 +2,7 @@
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
+import contextlib
import json
import logging
from pathlib import Path
@@ -768,8 +769,12 @@ def policy_scope(policy, *, authority=None):
policy_token = _ACTIVE_POLICY.set(active)
from gateway.session_local_editor import editor_scope
try:
+ from agent.auxiliary_task_config import session_auxiliary_scope
from gateway.session_local_mcp import editor_mcp_scope
- with editor_scope(policy), editor_mcp_scope(authority, policy):
+ # Auxiliary tasks read the session's frozen section, never live config.yaml (a rotated key there).
+ auxiliary = policy.config(authority).get('auxiliary') if authority is not None else None
+ aux_scope = session_auxiliary_scope(auxiliary) if authority is not None else contextlib.nullcontext()
+ with editor_scope(policy), editor_mcp_scope(authority, policy), aux_scope:
yield
finally:
_ACTIVE_POLICY.reset(policy_token)
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index 1404b314662..ab7f672786c 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -149,9 +149,20 @@ def _entry_owner_path(entry, config):
def disable_dropped_secrets(config, dropped, session=None):
"""Disable, in the session's effective *config*, whatever authenticated with a *dropped* frozen
secret, instead of leaving it with a null key (null means 'resolve another credential' and would
- send another account's key). A fallback using it is removed from the chain. Never substitutes."""
+ send another account's key). A fallback using it is removed from the chain; an ``auxiliary.<task>``
+ override using it is replaced by the session's primary route (``provider: main``). Never substitutes."""
if not dropped:
return config
+ from agent.auxiliary_task_config import _AUX_ROUTE_KEYS
+ auxiliary = config.get('auxiliary') if isinstance(config.get('auxiliary'), dict) else {}
+ for task in sorted({path[1] for path in dropped if path[0] == 'auxiliary' and len(path) > 2}, key=str):
+ block = auxiliary.get(task)
+ if isinstance(block, dict):
+ # The task's own route is gone with its key: the session's primary route, its own credential.
+ auxiliary[task] = {**{k: v for k, v in block.items() if k not in _AUX_ROUTE_KEYS
+ and k != 'fallback_chain'}, 'provider': 'main'}
+ logger.warning('Session %s: auxiliary task %s returned to the primary route: its credential '
+ 'changed in config.yaml since this session started', session, task)
owners = {path[:2] for path in dropped if path[0] in ('providers', 'custom_providers') and len(path) > 2}
for section in ('fallback_providers', 'fallback_model'):
raw = config.get(section)
diff --git a/tests/gateway/test_config_policy_recovery.py b/tests/gateway/test_config_policy_recovery.py
index 96d2f4a375b..2f184edea8b 100644
--- a/tests/gateway/test_config_policy_recovery.py
+++ b/tests/gateway/test_config_policy_recovery.py
@@ -304,3 +304,41 @@ def test_a_changed_fallback_secret_removes_that_fallback(tmp_path, monkeypatch,
assert not any('sk-different-account' in a or 'sk-rotated' in a for a in sent), sent
assert backup.requests == []
assert any('fallback' in r.getMessage() and 'removed' in r.getMessage() for r in caplog.records)
+
+
+def test_a_changed_auxiliary_secret_returns_that_task_to_the_primary_route(tmp_path, monkeypatch, caplog):
+ """A frozen ``auxiliary.compression`` key rotated in config.yaml used to be dropped while the
+ auxiliary client read live YAML and sent the ROTATED key. The task's override now leaves the
+ session's effective policy: compression runs on the session's primary route with its own key."""
+ from agent.auxiliary_client import get_text_auxiliary_client, reset_runtime_main, set_runtime_main
+ from gateway.session_policy import policy_scope
+ from tests.fakes.fake_llm_provider import FakeLLMServer
+ with FakeLLMServer() as main, FakeLLMServer() as aux:
+ cfg = {'model': {'provider': 'custom', 'default': 'primary-model', 'base_url': main.base_url,
+ 'api_key': 'sk-main-route'},
+ 'auxiliary': {'compression': {'provider': 'custom', 'model': 'aux-model',
+ 'base_url': aux.base_url, 'api_key': 'sk-original-aux'}}}
+ policy, owner, config_path = _bound_session(tmp_path, monkeypatch, cfg)
+
+ def compress():
+ authority = owner()
+ with policy_scope(policy, authority=authority):
+ _model, runtime = _policy_runtime(policy, owner)
+ token = set_runtime_main(runtime['provider'], 'primary-model', base_url=runtime['base_url'],
+ api_key=runtime['api_key'], api_mode=runtime.get('api_mode') or '')
+ try:
+ client, model = get_text_auxiliary_client('compression')
+ client.chat.completions.create(model=model, messages=[{'role': 'user', 'content': 'hi'}])
+ finally:
+ reset_runtime_main(token)
+ compress() # unchanged: the frozen auxiliary route serves with its frozen key
+ assert [r['auth'] for r in aux.requests] == ['Bearer sk-original-aux']
+
+ cfg['auxiliary']['compression']['api_key'] = 'sk-rotated-aux'
+ config_path.write_text(json.dumps(cfg))
+ compress()
+ sent = [r['auth'] for r in main.requests + aux.requests]
+ assert not any('sk-rotated-aux' in a for a in sent), sent
+ assert len(aux.requests) == 1 # nothing more reached the auxiliary endpoint
+ assert main.requests[-1]['auth'] == 'Bearer sk-main-route'
+ assert any('auxiliary' in r.getMessage() and 'primary route' in r.getMessage() for r in caplog.records)