Skip to content

The agent that grows with you

fix: frozen LOCAL routes resolve every rung against the frozen config

Teknium3c62c86d1a9c
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index ea59c6da75d..4ac7793f72c 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -60,35 +60,39 @@ class GatewayTurnPrepareMixin:
if policy is not None:
from gateway.run import _runtime_agent_kwargs
from gateway.session_policy import launch_key
+ from hermes_cli.runtime_provider import frozen_runtime_config, resolve_runtime_with_fallback
from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
from gateway.session_authorities import active_authority
authority = active_authority(self)
frozen = policy.config(authority)
key = launch_key(authority, policy)
- import json
- runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,
- explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),
- target_model=policy.model, config=frozen)
- if runtime is None:
- if key is None:
- key = frozen.get('model', {}).get('api_key')
- # Same resolution-time walker the in-process one-shot used (#81209): an AuthError from
- # the frozen primary (expired token, Portal down, exhausted pool) tries the route's own
- # ``fallback_providers`` before the turn is refused.
- from hermes_cli.runtime_provider import resolve_runtime_with_fallback
- # Only a launch-supplied URL is explicit (classic one-shot parity): config's own
- # ``model.base_url`` is resolved by the provider chain, which keeps the credential pool
- # an explicit URL would drop (no pool = no refresh/rotation on a 401).
- runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,
- explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),
- target_model=policy.model)
- if fallback_entry is not None:
- from hermes_cli.fallback_config import pre_agent_fallback_notice
- self._pre_agent_fallback_notice = pre_agent_fallback_notice(
- policy.provider or '', policy.model or '',
- runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
- fallback_entry.get('model') or 'default')
- return fallback_entry['model'], _runtime_agent_kwargs(runtime)
+ launch_url = json.loads(policy.request_json).get('base_url')
+ # Every rung reads the session's FROZEN config, never live config.yaml: a later
+ # ``model.base_url`` edit must not carry this route's frozen credential to the new host
+ # (R2-M2). The auth-store pool is not config, so refresh/rotation still applies.
+ with frozen_runtime_config(frozen):
+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,
+ explicit_api_key=key, explicit_base_url=launch_url,
+ target_model=policy.model, config=frozen)
+ if runtime is None:
+ if key is None:
+ key = frozen.get('model', {}).get('api_key')
+ # Same resolution-time walker the in-process one-shot used (#81209): an AuthError
+ # from the frozen primary (expired token, Portal down, exhausted pool) tries the
+ # route's own ``fallback_providers`` before the turn is refused. Only a launch URL is
+ # explicit (classic one-shot parity): the frozen ``model.base_url`` is resolved by
+ # the provider chain, which keeps the credential pool an explicit URL would drop.
+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=policy.provider,
+ explicit_api_key=key, explicit_base_url=launch_url, target_model=policy.model)
+ else:
+ fallback_entry = None
+ if fallback_entry is not None:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ policy.provider or '', policy.model or '',
+ runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
+ fallback_entry.get('model') or 'default')
+ return fallback_entry['model'], _runtime_agent_kwargs(runtime)
return policy.model, _runtime_agent_kwargs(runtime)
skey = self._resolve_session_key_or_none(source, session_key)
model = _resolve_gateway_model(user_config)
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 2e1f9d26302..e8178d74f45 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -7,8 +7,11 @@ OpenRouter/bare-custom, Bedrock and external-process builders in
from __future__ import annotations
+import copy
import logging
import re
+from contextlib import contextmanager
+from contextvars import ContextVar
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional
@@ -35,11 +38,32 @@ from hermes_cli.providers import determine_api_mode, get_provider, is_actual_rou
from utils import base_url_host_matches, base_url_hostname, base_url_path, env_int
+# A frozen session route's config (``frozen_runtime_config``); None = the live profile config.
+_FROZEN_RUNTIME_CONFIG: ContextVar[Optional[Dict[str, Any]]] = ContextVar("_FROZEN_RUNTIME_CONFIG", default=None)
+
+
+@contextmanager
+def frozen_runtime_config(config: Dict[str, Any]):
+ """Resolve against a session's frozen config instead of the live config.yaml.
+
+ Every rung reads its endpoint through ``load_config``/``_get_model_config``, so a frozen route's
+ credential stays paired with the endpoint it was frozen with after a live ``model.base_url``
+ edit (R2-M2). The auth store (credential pool) is not config and still refreshes/rotates.
+ """
+ merged = _config_mod._deep_merge(copy.deepcopy(_config_mod.DEFAULT_CONFIG), config)
+ token = _FROZEN_RUNTIME_CONFIG.set(merged)
+ try:
+ yield
+ finally:
+ _FROZEN_RUNTIME_CONFIG.reset(token)
+
+
# Late-bound delegates, deliberately NOT module-level from-imports: this module is often imported
# lazily, so its first import can happen while a test has ``hermes_cli.config.load_config`` patched
# — a from-import would bind the MagicMock permanently and poison every later caller.
def load_config():
- return _config_mod.load_config()
+ frozen = _FROZEN_RUNTIME_CONFIG.get()
+ return copy.deepcopy(frozen) if frozen is not None else _config_mod.load_config()
def get_compatible_custom_providers(config=None):
@@ -866,7 +890,7 @@ _LOCAL_BYPASS_CLOUD_HOSTS = ("openrouter.ai", "anthropic.com", "openai.com")
def _raise_if_provider_disabled(requested_provider: str) -> None:
"""Honour ``providers.<name>.enabled: false`` for built-ins too (the custom lookup gate only
covers custom blocks); a typed error lets the fallback chain advance."""
- full_cfg = _config_mod.load_config()
+ full_cfg = load_config()
provs_cfg = full_cfg.get("providers") if isinstance(full_cfg, dict) else None
block = provs_cfg.get(requested_provider) if isinstance(provs_cfg, dict) else None
if isinstance(block, dict) and not _config_mod.is_provider_enabled(block):
diff --git a/tests/gateway/test_session_policy.py b/tests/gateway/test_session_policy.py
index bfe3843cdde..29661acb77f 100644
--- a/tests/gateway/test_session_policy.py
+++ b/tests/gateway/test_session_policy.py
@@ -135,3 +135,31 @@ def test_null_config_sections_read_as_absent(tmp_path):
assert isinstance(legacy, LocalSessionPolicy)
assert legacy.config().get('display', {}).get('busy_input_mode', 'interrupt') == 'interrupt'
+
+
+def test_frozen_route_keeps_its_endpoint_after_live_config_edit(tmp_path, monkeypatch):
+ """R2-M2: the frozen policy's config-derived endpoint is the one its frozen credential
+ belongs to; a later ``model.base_url`` edit must not redirect that credential."""
+ import json
+ from types import SimpleNamespace
+ from gateway.session_policy import build_policy, bind_launch_key
+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin
+ from hermes_cli.config_effective import load_user_config_effective
+ home = tmp_path / 'home'
+ home.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+
+ def write(url, key):
+ (home / 'config.yaml').write_text(json.dumps(
+ {'model': {'provider': 'custom', 'base_url': url, 'api_key': key, 'default': 'm'}}))
+ write('http://127.0.0.1:1/v1', 'sk-frozen-endpoint-one')
+ private = {}
+ policy = build_policy({'cwd': str(tmp_path), 'model': 'm'}, load_user_config_effective(home / 'config.yaml'),
+ private_secrets=private)
+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=None)
+ policy = bind_launch_key(authority, 'sid', policy, None, config_secrets=private)
+ write('http://127.0.0.1:2/v1', 'sk-new-endpoint-two')
+ monkeypatch.setattr('gateway.session_policy.policy_for_source', lambda runner, source: policy)
+ runner = SimpleNamespace(session_authority=authority)
+ _, runtime = GatewayTurnPrepareMixin._resolve_session_agent_runtime(runner, source=SimpleNamespace())
+ assert (runtime['base_url'], runtime['api_key']) == ('http://127.0.0.1:1/v1', 'sk-frozen-endpoint-one')