The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): resolve a key-less managed worker's route credential like the in-process turn
unsupportedpastelsda31f318d321
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex 83f8c198137..01a1d6088c2 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -338,7 +338,7 @@ def execute(frame, channel):agent = Nonetry:with policy_scope(policy):- agent = _construct_agent(frame, AIAgent, model=policy.model, provider=policy.provider, base_url=policy.base_url,+ agent = _construct_agent(frame, AIAgent, policy, model=policy.model, provider=policy.provider, base_url=policy.base_url,api_key=frame['api_key'], session_db=store, session_id=scope['session_id'],enabled_toolsets=list(policy.toolsets), max_iterations=policy.max_turns,# A delegated child needs its own owner-registered execution, which this single-turn@@ -399,10 +399,13 @@ def execute(frame, channel):store.close()-def _construct_agent(frame, factory, **kwargs):+def _construct_agent(frame, factory, policy, **kwargs):"""Agent construction resolves the provider credentials; a Kanban attempt that fails herestill books the one-shot exit mapping (quota wall 75, re-login 78) before the crash."""try:+ if kwargs['api_key'] is None:+ from gateway.session_worker_construct import worker_api_key+ kwargs['api_key'] = worker_api_key(policy)return factory(**kwargs)except Exception as exc:from gateway.session_kanban import record_start_failurediff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex d1cee7bfc07..e780514c6e3 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -45,41 +45,13 @@ def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:tests that bind the method onto bare namespaces still reach it."""from gateway.run import _runtime_agent_kwargsfrom 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_worker_construct import route_runtimefrom gateway.session_authorities import active_authorityauthority = active_authority(runner)# A follow_profile_config session's route is the profile's current one, model and endpoint from one read.frozen, model = policy.effective(authority)provider = (frozen.get('model') or {}).get('provider')- key = launch_key(authority, policy)- launch_url = json.loads(policy.request_json).get('base_url')- if launch_url:- # The creation request is immutable identity, not the current selection: once a canonical- # model mutation moved the route off the launch endpoint, the policy's selection wins.- from hermes_cli.route_identity import normalize_route_base_url- if normalize_route_base_url(launch_url) != normalize_route_base_url((frozen.get('model') or {}).get('base_url')):- launch_url = None- # 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=provider,- explicit_api_key=key, explicit_base_url=launch_url,- target_model=model, config=frozen)- if runtime is None:- # Only a bound launch key is explicit: the frozen ``model.api_key`` is config, which the- # resolver already reads from the frozen scope, so a URL-matched credential pool still- # serves (and rotates on) the frozen endpoint.- # 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=provider,- explicit_api_key=key, explicit_base_url=launch_url, target_model=model)- else:- fallback_entry = None+ runtime, fallback_entry = route_runtime(policy, frozen, model, launch_key(authority, policy))if fallback_entry is not None:from hermes_cli.fallback_config import pre_agent_fallback_noticerunner._pre_agent_fallback_notice = pre_agent_fallback_notice(diff --git a/gateway/session_worker_construct.py b/gateway/session_worker_construct.pyindex 6f9f397e43e..8014bb9bdfe 100644--- a/gateway/session_worker_construct.py+++ b/gateway/session_worker_construct.py@@ -70,6 +70,51 @@ def _dict_list(value):return value is None or (isinstance(value, list) and all(isinstance(e, dict) for e in value))+def route_runtime(policy, frozen, model, key):+ """``(runtime, fallback_entry)`` for a launch-policy route: the session's FROZEN config and launch+ credential, walking its own fallback chain on an AuthError. The one resolver an in-process turn+ (``_resolve_policy_agent_runtime``) and a key-less managed worker (``worker_api_key``) share."""+ from hermes_cli.runtime_provider import frozen_runtime_config, resolve_runtime_with_fallback+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime+ provider = (frozen.get('model') or {}).get('provider')+ launch_url = json.loads(policy.request_json).get('base_url')+ if launch_url:+ # The creation request is immutable identity, not the current selection: once a canonical+ # model mutation moved the route off the launch endpoint, the policy's selection wins.+ from hermes_cli.route_identity import normalize_route_base_url+ if normalize_route_base_url(launch_url) != normalize_route_base_url((frozen.get('model') or {}).get('base_url')):+ launch_url = None+ # 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=provider,+ explicit_api_key=key, explicit_base_url=launch_url,+ target_model=model, config=frozen)+ if runtime is not None:+ return runtime, None+ # Only a bound launch key is explicit: the frozen ``model.api_key`` is config, which the+ # resolver already reads from the frozen scope, so a URL-matched credential pool still+ # serves (and rotates on) the frozen endpoint.+ # 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.+ return resolve_runtime_with_fallback(frozen, requested=provider,+ explicit_api_key=key, explicit_base_url=launch_url, target_model=model)+++def worker_api_key(policy):+ """Child side, for a worker launched without a key (every Kanban run): the route's own credential,+ resolved as the in-process turn resolves it, from this process's profile home (its HERMES_HOME and+ ``.env``). A fallback entry's key belongs to another provider and model, so the primary never+ carries it; the agent's own fallback chain switches all three together (#139155)."""+ frozen, model = policy.effective()+ runtime, fallback_entry = route_runtime(policy, frozen, model, None)+ return runtime.get('api_key') if fallback_entry is None else None++def checkpoint_agent_kwargs(config):"""``AIAgent`` checkpoint arguments from a config dict (every turn: the gateway's live config, amanaged worker's frozen session snapshot). The gateway bypasses ``load_config()``, so defaultsdiff --git a/tests/gateway/test_managed_worker_route_key.py b/tests/gateway/test_managed_worker_route_key.pynew file mode 100644index 00000000000..b08baf99d22--- /dev/null+++ b/tests/gateway/test_managed_worker_route_key.py@@ -0,0 +1,117 @@+"""A managed worker without a launch key (every Kanban run) resolves its route's credential the+way the in-process runner does (``_resolve_policy_agent_runtime``), so an ``anthropic_messages``+provider other than Anthropic gets its own key instead of ``Bearer `` (#139155). The key comes from+the worker's own profile home, never the default one, and a bound launch key still wins."""+import json+import secrets+import threading+from types import SimpleNamespace++from tests.gateway.test_managed_turn_contract import assignment++BASE_URL = 'https://api.minimax.io/anthropic'+KEY_ENV = 'KB5_MINIMAX_TEST_KEY'+++def _minimax_frame(tmp_path, monkeypatch, api_key=None):+ frame, _ = assignment(tmp_path, monkeypatch)+ config = json.loads(frame['policy']['config_json'])+ config['model'] = {'default': 'MiniMax-M2.7', 'provider': 'custom:minimax', 'base_url': BASE_URL,+ 'api_mode': 'anthropic_messages'}+ config['custom_providers'] = [{'name': 'minimax', 'base_url': BASE_URL, 'key_env': KEY_ENV,+ 'api_mode': 'anthropic_messages'}]+ request = {k: v for k, v in json.loads(frame['policy']['request_json']).items() if k not in ('provider', 'base_url')}+ policy = {**frame['policy'], 'model': 'MiniMax-M2.7', 'config_json': json.dumps(config),+ 'request_json': json.dumps(request)}+ return {**frame, 'policy': policy, 'api_key': api_key}+++def _execute(frame, monkeypatch):+ from agent import managed_worker as worker+ built = {}++ class Agent:+ def __init__(self, **kwargs):+ built.update(kwargs)+ self.session_prompt_tokens = self.session_completion_tokens = 0+ def run_conversation(self, text, **kwargs):+ return {'final_response': 'ok', 'completed': True}++ class Store:+ def __init__(self, *args): pass+ def get_messages_as_conversation(self, sid): return []+ def flush_token_counts(self): pass+ def finish(self): pass+ def close(self): pass++ class Controls:+ def __init__(self, *args):+ self.stopped, self.finish = threading.Event(), threading.Event()+ self.finish.set()+ def approval(self, data): pass+ def clarify(self, questions): pass++ monkeypatch.setattr(worker, 'bind_worker_policy', lambda frame: None)+ monkeypatch.setattr(worker, 'discover_profile_mcp', lambda policy: None)+ monkeypatch.setattr(worker, 'retire_agent', lambda agent: None)+ monkeypatch.setattr(worker, 'WorkerControls', Controls)+ monkeypatch.setattr('agent.runtime_session_store.WorkerRPC', lambda home: lambda *a, **k: {'owner_epoch': 1})+ monkeypatch.setattr('agent.runtime_session_store.RuntimeSessionStore', Store)+ monkeypatch.setattr('tools.process_registry.process_registry.recover_from_checkpoint', lambda: None)+ monkeypatch.setattr('run_agent.AIAgent', Agent)+ monkeypatch.setattr('agent.title_generator.wait_for_title_upgrades', lambda: None)+ worker.execute(frame, SimpleNamespace(send=lambda kind, **payload: None))+ return built+++def test_keyless_worker_resolves_its_custom_provider_key(tmp_path, monkeypatch):+ key = 'fake-' + secrets.token_hex(8)+ monkeypatch.setenv(KEY_ENV, key)+ built = _execute(_minimax_frame(tmp_path, monkeypatch), monkeypatch)+ assert built['provider'] == 'custom:minimax' and built['base_url'] == BASE_URL+ assert built['api_key'] == key+++def test_keyless_worker_reads_its_own_profile_home_not_the_default(tmp_path, monkeypatch):+ """The owner launches a secondary profile's worker with that profile's env (``_worker_env``);+ the worker's resolution then sees its own key, never the launch (default) profile's."""+ import os+ from gateway.session_managed_worker import _worker_env+ default = tmp_path / '.hermes'+ profile = default / 'profiles' / 'kb5'+ profile.mkdir(parents=True)+ own, other = 'fake-own-' + secrets.token_hex(8), 'fake-default-' + secrets.token_hex(8)+ (default / '.env').write_text(f'{KEY_ENV}={other}\n')+ (profile / '.env').write_text(f'{KEY_ENV}={own}\n')+ monkeypatch.setenv('HOME', str(tmp_path))+ monkeypatch.setenv('HERMES_HOME', str(default))+ monkeypatch.setenv(KEY_ENV, other)+ env = _worker_env(SimpleNamespace(profile_id=str(profile)))+ assert env is not None and env['HERMES_HOME'] == str(profile)+ for name in list(os.environ):+ monkeypatch.delenv(name)+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ built = _execute(_minimax_frame(tmp_path, monkeypatch), monkeypatch)+ assert built['api_key'] == own+++def test_bound_launch_key_wins_over_the_route_key(tmp_path, monkeypatch):+ launch = 'fake-launch-' + secrets.token_hex(8)+ monkeypatch.setenv(KEY_ENV, 'fake-route-' + secrets.token_hex(8))+ built = _execute(_minimax_frame(tmp_path, monkeypatch, api_key=launch), monkeypatch)+ assert built['api_key'] == launch+++def test_primary_auth_failure_never_borrows_a_fallback_providers_key(tmp_path, monkeypatch):+ """A fallback entry's credential belongs to another provider; the worker's primary route never+ carries it (the agent's own fallback chain switches provider, model and key together)."""+ calls = []++ def resolve(config, **kwargs):+ calls.append(kwargs)+ return {'provider': 'openrouter', 'api_key': 'fake-other-provider'}, {'provider': 'openrouter', 'model': 'x'}+ monkeypatch.setattr('hermes_cli.runtime_provider.resolve_runtime_with_fallback', resolve)+ monkeypatch.setattr('hermes_cli.runtime_provider_custom._resolve_named_custom_runtime', lambda **kw: None)+ built = _execute(_minimax_frame(tmp_path, monkeypatch), monkeypatch)+ assert calls and built['api_key'] is None