The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: resolve configured local routes from frozen provider policy
Tekniume02cc03a337f
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 4ae445fdfef..8e6d0ab793f 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -58,9 +58,17 @@ class GatewayTurnPrepareMixin:from hermes_cli.runtime_provider import resolve_runtime_providerfrom gateway.run import _runtime_agent_kwargsfrom gateway.session_policy import launch_key- runtime = resolve_runtime_provider(requested=policy.provider,- explicit_api_key=launch_key(self.session_authority, policy),- explicit_base_url=policy.base_url, target_model=policy.model)+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime+ frozen = policy.config(self.session_authority)+ key = launch_key(self.session_authority, policy)+ if key is None:+ key = frozen.get('model', {}).get('api_key')+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,+ explicit_api_key=key, explicit_base_url=policy.base_url,+ target_model=policy.model, config=frozen)+ if runtime is None:+ runtime = resolve_runtime_provider(requested=policy.provider,+ explicit_api_key=key, explicit_base_url=policy.base_url, target_model=policy.model)return policy.model, _runtime_agent_kwargs(runtime)skey = self._resolve_session_key_or_none(source, session_key)diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.pyindex b42d6537a4a..60942a18a7e 100644--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@ -159,12 +159,12 @@ def _match_legacy_custom_provider(requested_norm: str, custom_providers) -> Optireturn None-def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, Any]]:+def _get_named_custom_provider(requested_provider: str, *, config=None) -> Optional[Dict[str, Any]]:requested_norm = _normalize_custom_provider_name(requested_provider or "")if not requested_norm or requested_norm == "auto" or _shadowed_by_builtin(requested_norm):return Nonerp = _rp()- config = rp.load_config()+ config = rp.load_config() if config is None else configproviders = config.get("providers")found = _match_new_style_provider(requested_norm, providers) if isinstance(providers, dict) else Noneif found:@@ -446,7 +446,7 @@ def _opencode_family_for_custom(requested_provider: str, base_url: str) -> Optiodef _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key: Optional[str] = None,explicit_base_url: Optional[str] = None,- target_model: Optional[str] = None) -> Optional[Dict[str, Any]]:+ target_model: Optional[str] = None, config=None) -> Optional[Dict[str, Any]]:"""Runtime for a llamacpp alias, a bare-custom direct alias, or a configured custom entry.Aliases resolving to "custom" (ollama, vllm, llamacpp, …) are treated like bare ``custom``. Allamacpp alias with no explicit base_url resolves to the managed server first; an explicit@@ -464,7 +464,8 @@ def _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key:requested_norm = "custom"if requested_norm == "custom" and explicit_base_url:return _resolve_direct_alias_runtime(requested_provider, explicit_api_key, explicit_base_url)- custom_provider = rp._get_named_custom_provider(requested_provider)+ custom_provider = (rp._get_named_custom_provider(requested_provider) if config is None+ else _get_named_custom_provider(requested_provider, config=config))if not custom_provider:return Nonebase_url = ((explicit_base_url or "").strip() or custom_provider.get("base_url", "")).rstrip("/")@@ -473,7 +474,7 @@ def _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key:pool_result = rp._try_resolve_from_custom_pool(base_url, "custom", custom_provider.get("api_mode"),provider_name=custom_provider.get("provider_key") or custom_provider.get("name"),- )+ ) if config is None else Noneif pool_result:# The pool doesn't know the custom_providers fields — propagate them here too._apply_custom_provider_extras(custom_provider, target_model, pool_result)diff --git a/tests/gateway/fixtures/config_policy_recovery_probe.py b/tests/gateway/fixtures/config_policy_recovery_probe.pynew file mode 100644index 00000000000..c4652b39a1c--- /dev/null+++ b/tests/gateway/fixtures/config_policy_recovery_probe.py@@ -0,0 +1,107 @@+"""Unmodified daemon/config-source restart over actual loopback inference."""+import asyncio+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++from tests.gateway.fixtures.cli_launch_policy_probe import Model+from tests.gateway.fixtures.local_recovery_probe import daemon, websocket, rpc+++def probe(tmp_path):+ root = Path(__file__).resolve().parents[3]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests, peer.lock, peer.barrier = [], threading.Lock(), threading.Barrier(2)+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ origin = f'http://127.0.0.1:{peer.server_port}'+ keys = {side: 'config-private-' + side for side in ('left', 'right')}+ cfg = {'model': {'provider': 'custom', 'default': 'fixture'},+ 'providers': {s: {'base_url': origin + '/' + s + '/v1', 'api_key': k} for s, k in keys.items()},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': []}}+ config = home / 'config.yaml'+ config.write_text(json.dumps(cfg))+ before = config.read_bytes()+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'SYSTEMROOT') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root))+ sessions, pids, snapshots = {}, [], {}+ params = {s: dict(request_id=s, cwd=str(home), model='gpt-5-' + s, provider='custom:' + s,+ toolsets=[]) for s in keys}++ def policies():+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:+ return dict(db.execute("SELECT key,value FROM state_meta WHERE key LIKE 'gateway.local_policy.v1:%'"))++ async def turn(desc, side, phase):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', **params[side])+ assert 'result' in created, created+ sid = created['result']['session_id']+ if side in sessions:+ assert sid == sessions[side]+ sessions[side] = sid+ resumed = await rpc(ws, 'session.resume', session_id=sid)+ epoch = resumed['result']['replay_epoch']+ accepted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=phase + side, text=phase + side)+ assert 'result' in accepted, accepted+ async with asyncio.timeout(30):+ while True:+ receipt = await rpc(ws, 'prompt.receipt', session_id=sid,+ admission_id=accepted['result']['admission_id'])+ if receipt['result']['status'] == 'terminal':+ break+ await asyncio.sleep(.03)+ events = await rpc(ws, 'session.events.since', session_id=sid, last_sequence=0, replay_epoch=epoch)+ if phase == 'denied':+ # This baseline's pre-agent display failure has generic public+ # delivery; the worker lane owns settlement/error projection.+ failure = json.dumps(events) + (home / 'restart.log').read_text()+ assert 'launch_credentials_unavailable' in failure, failure+ else:+ assert 'LAUNCH_POLICY_OK' in json.dumps(events), events+ assert not any(k in json.dumps([created, resumed, events]) for k in keys.values())++ async def pair(desc, phase):+ await asyncio.gather(*(turn(desc, s, phase) for s in keys))+ try:+ with daemon(root, home, env, barrier=False) as (proc, desc):+ pids.append(proc.pid)+ asyncio.run(pair(desc, 'first'))+ snapshots = policies()+ assert config.read_bytes() == before+ # Current routing changes must not retarget either frozen key.+ for entry in cfg['providers'].values():+ entry['base_url'] = origin + '/wrong/v1'+ config.write_text(json.dumps(cfg))+ with daemon(root, home, env, barrier=False) as (proc, desc):+ pids.append(proc.pid)+ asyncio.run(pair(desc, 'restart'))+ assert policies() == snapshots+ assert len(peer.requests) == 4, peer.requests+ for side, key in keys.items():+ requests = [r for r in peer.requests if r['body']['model'] == 'gpt-5-' + side]+ assert len(requests) == 2+ assert all(r['auth'] == 'Bearer ' + key and r['path'] == '/' + side + '/v1/chat/completions' for r in requests), requests+ cfg['providers']['left']['api_key'] = 'changed-wrong-credential'+ config.write_text(json.dumps(cfg))+ with daemon(root, home, env, barrier=False) as (proc, desc):+ pids.append(proc.pid)+ asyncio.run(pair(desc, 'denied'))+ assert policies() == snapshots+ assert len(peer.requests) == 4+ leaks = [str(p.relative_to(home)) for p in home.rglob('*') if p.is_file() and p != config+ and any(k.encode() in p.read_bytes() for k in keys.values())]+ assert not leaks, leaks+ return {'pids': pids, 'requests': 4, 'concurrent_inline_keys': True, 'restart_actual_inference': True,+ 'frozen_endpoint_key': True, 'creation_retry_identity': True, 'changed_key_refused': True,+ 'durable_policy_redacted': True, 'original_config_unchanged_by_daemon': True}+ finally:+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/gateway/test_config_policy_daemon.py b/tests/gateway/test_config_policy_daemon.pynew file mode 100644index 00000000000..5070e4e855c--- /dev/null+++ b/tests/gateway/test_config_policy_daemon.py@@ -0,0 +1,6 @@+import json+++def test_config_policy_recovery_on_ordinary_daemon(tmp_path):+ from tests.gateway.fixtures.config_policy_recovery_probe import probe+ print(json.dumps(probe(tmp_path)))