The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): run a new session with its own provider_routing
unsupportedpastels9e1c961c2654
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex d1483a4f798..254000b15ee 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1213,7 +1213,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# 'custom' resolved without credentials ...") is the diagnosis; /login is not.return _unresolved(f"⚠️ {exc}")return _unresolved(t("gateway.errors.no_credentials"))- pr = runner._provider_routing+ from gateway.session_authorities import active_authority+ from gateway.session_worker_construct import session_routing+ pr = session_routing(active_authority(runner), policy) if policy else runner._provider_routingreasoning_config = (policy.current_reasoning_config(runner, ctx.session_key) if policy elserunner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))runner._service_tier = (policy.current_service_tier(runner, ctx.session_key) if policy elsediff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.pyindex a012b87f248..a20ebd65278 100644--- a/gateway/session_tui_side.py+++ b/gateway/session_tui_side.py@@ -82,7 +82,8 @@ def _side_agent(authority, policy, live, task_id, **overrides):runner = authority.runnermodel, runtime = _resolve_runtime(authority, policy)config = policy.config(authority)- pr = getattr(runner, '_provider_routing', None) or {}+ from gateway.session_worker_construct import session_routing+ pr = session_routing(authority, policy)refresh_fallback = getattr(runner, '_refresh_fallback_model', None)kwargs = dict(model=model, **{key: runtime.get(key) for key in _RUNTIME_KEYS if key in runtime},diff --git a/gateway/session_worker_construct.py b/gateway/session_worker_construct.pyindex 0fd825f2e00..14c51d58bee 100644--- a/gateway/session_worker_construct.py+++ b/gateway/session_worker_construct.py@@ -53,6 +53,13 @@ def _prefill(authority, policy):return getattr(authority.runner, '_prefill_messages', None) or None+def session_routing(authority, policy):+ """The session's ``provider_routing``: its own profile's, as of its creation (main's CLI read it+ once at startup). Never the runner's daemon-start copy."""+ routing = policy.config(authority, secrets=False).get('provider_routing')+ return routing if isinstance(routing, dict) else {}++def construct_kwargs(frame):"""Child side: the validated ``AIAgent`` keyword arguments; a frame without the object(older owner) constructs exactly as before."""diff --git a/tests/gateway/test_session_config_loaders.py b/tests/gateway/test_session_config_loaders.pynew file mode 100644index 00000000000..6e784b5c16e--- /dev/null+++ b/tests/gateway/test_session_config_loaders.py@@ -0,0 +1,101 @@+"""A gateway-owned session runs with ``provider_routing`` from its own+profile's config as of its creation, as a new ``hermes chat`` process read it once at startup on+pre-merge main (CFG-6). The daemon-start snapshot on the runner never reaches it; a managed+worker already builds from the same frozen config."""+from types import SimpleNamespace++import pytest++LAUNCH = {'model': 'm', 'provider': 'custom', 'base_url': 'http://127.0.0.1:9/v1'}+++class _Built(Exception):+ pass+++def test_in_process_turn_routes_with_the_sessions_own_provider_routing(tmp_path, monkeypatch):+ """The routing the in-process turn hands its agent is the session's, not the runner's+ daemon-start ``_provider_routing``."""+ from gateway import session_policy+ from gateway.config import Platform+ from gateway.run_turn_runner import TurnRunner+ from gateway.session_policy import build_policy+ policy = build_policy({'cwd': str(tmp_path), **LAUNCH}, {'provider_routing': {'only': ['Fresh'], 'sort': 'price'}})+ monkeypatch.setattr(session_policy, 'policy_for_source', lambda runner, source: policy)+ runner = SimpleNamespace(+ _provider_routing={'only': ['DaemonStart']}, _peek_session_state=lambda key: None,+ session_authority=SimpleNamespace(profile_id=str(tmp_path)),+ _resolve_session_agent_runtime=lambda **kw: ('m', {'provider': 'custom'}),+ _resolve_turn_agent_config=lambda message, model, runtime: {'model': model, 'runtime': runtime})+ turn = TurnRunner.__new__(TurnRunner)+ turn._runner = runner+ turn._ctx = SimpleNamespace(source=SimpleNamespace(platform=Platform.LOCAL, chat_id='c'), session_key='k',+ user_config={}, message='hi', inbound_message_id=None, enabled_toolsets=[])+ turn._combined_ephemeral_prompt = lambda: None+ turn._setup_stream_consumer = lambda platform_key: (None, None, None, False)++ def built(route, platform_key, ephemeral, max_iterations, reasoning, pr):+ raise _Built(pr)+ turn._resolve_turn_agent = built+ with pytest.raises(_Built) as caught:+ turn._run_sync_scoped()+ assert caught.value.args[0] == {'only': ['Fresh'], 'sort': 'price'}+++def test_bg_side_agent_uses_the_sessions_provider_routing(tmp_path):+ """``/bg`` through its handler: the side agent it constructs routes with the session's+ ``provider_routing``, not the runner's daemon-start copy."""+ import asyncio+ import run_agent+ from gateway import session_tui_side+ from gateway.session_contract import SessionRef+ from tests.gateway.test_local_create_env_refs import _owner+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(CONFIG + 'provider_routing: {only: [Fresh], sort: price}\n')+ built = {}++ class Agent:+ def __init__(self, **kwargs):+ built.update(kwargs)++ def run_conversation(self, **kwargs):+ return {'final_response': 'done'}++ def close(self):+ pass++ async def probe(monkeypatch):+ monkeypatch.setattr(run_agent, 'AIAgent', Agent)+ owner, connection = await _owner(home, monkeypatch)+ owner.runner._provider_routing = {'only': ['DaemonStart']}+ owner.runner._peek_session_state = lambda key: None+ owner.runner._adapter_for_source = lambda source: owner.runner.adapters.get(source.platform)+ try:+ ref, _policy = _create(owner, connection, home, 'bg')+ connection.subscriptions[ref.session_id] = 'sub'+ reply = await session_tui_side.background(connection, SessionRef(owner.profile_id, ref.session_id),+ {'session_id': ref.session_id, 'text': 'BG'})+ assert reply['task_id'].startswith('bg_')+ for thread in list(session_tui_side._RUNNING):+ thread.join(30)+ finally:+ connection.subscriptions.clear()+ await connection.close()+ owner.db.close()+ with pytest.MonkeyPatch.context() as monkeypatch:+ asyncio.run(probe(monkeypatch))+ assert (built['providers_allowed'], built['provider_sort']) == (['Fresh'], 'price'), built+++CONFIG = ('platform_toolsets: {cli: []}\n'+ 'model: {provider: custom, default: m, base_url: "http://127.0.0.1:9/v1"}\n')+++def _create(owner, connection, home, request_id):+ from gateway.session_local import create_local_session+ from gateway.session_policy import restore_policy+ from hermes_state_local import local_receipt+ ref = create_local_session(owner, connection.actor, {'request_id': request_id, 'source': 'cli',+ 'cwd': str(home), 'toolsets': []})+ return ref, restore_policy(local_receipt(owner.db, ref.session_id)['policy'])