The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): scope the proxy key read, split policy runtime resolution, fix run_turn lint
Tekniumcf16bd149c68
diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 546e8f25f2f..e8bd3d2591a 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -166,10 +166,6 @@ def hygiene_no_commit_reason(agent) -> str:return "in-place commit did not complete"-class GatewayTurnMixin:- """Agent-turn execution for GatewayRunner (see module docstring)."""--from gateway.run_turn_prepare import GatewayTurnPrepareMixinfrom gateway.run_turn_hygiene import GatewayTurnHygieneMixinfrom gateway.run_turn_persistence import GatewayTurnPersistenceMixin@@ -845,16 +841,14 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewayif not proxy_url:return self._proxy_error_result(t("gateway.proxy.url_missing"))- # The proxy key is a per-profile credential: honor the installed secret scope under multiplex.- # Only UnscopedSecretError (the unscoped default-profile path) falls back to the env; any- # other get_secret() error propagates (same as BASE) rather than silently degrading to the- # ambient key, which may hold another profile's credential.- from agent.secret_scope import UnscopedSecretError, get_secret+ # The proxy key is a per-profile credential read through the installed secret scope:+ # ``_run_agent`` binds the source profile's scope (or the launch profile's once the process+ # multiplexes), and an unscoped single-profile process reads os.environ inside get_secret.+ # Any get_secret() error propagates rather than degrading to the ambient key, which may hold+ # another profile's credential.+ from agent.secret_scope import get_secret_str- try:- proxy_key = (get_secret("GATEWAY_PROXY_KEY") or "").strip()- except UnscopedSecretError:- proxy_key = os.getenv("GATEWAY_PROXY_KEY", "").strip()+ proxy_key = get_secret_str("GATEWAY_PROXY_KEY").strip()_run_still_current = self._run_still_current_fn(session_key, run_generation)diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex 658d004fe04..551b54bdd68 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -104,7 +104,7 @@ class GatewayTurnPersistenceMixin:try:await self.async_session_store.clear_resume_pending(session_key)except Exception as _e:- logger.debug("clear_resume_pending failed for %s: %s", session_key, _e)+ logger.debug("clear_resume_pending failed for %s: %s", session_key, _e, exc_info=True)# Normalize empty responses: surface errors, partial failures, and work-without-text.# Fix for #18765.diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 78b5b11cd12..270e7f2e6bc 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -39,6 +39,75 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)logger = logging.getLogger("gateway.run")+def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:+ """``_resolve_session_agent_runtime`` for a session bound to a launch policy: the route's FROZEN+ config and launch credential, walking its own fallback chain on an AuthError. Module-level so+ tests that bind the method onto bare namespaces still reach it."""+ 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(runner)+ frozen = policy.config(authority)+ key = launch_key(authority, policy)+ 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:+ # 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=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+ runner._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)+++def _recover_or_remember_model(runner, skey, model):+ """Last step of ``_resolve_session_agent_runtime``: remember a good model, recover an empty one."""+ # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and+ # the session goes silent — reuse the last model resolved for this session, else process-wide.+ if not model:+ _lr_state = runner._peek_session_state(skey) if skey else None+ _lr_star = runner._peek_session_state("*")+ _recovered = (+ (_lr_state.conversation.last_resolved_model if _lr_state else "")+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")+ )+ if _recovered:+ logger.warning(+ "Empty model resolved for session=%s — recovering "+ "last-known-good model %s (config read likely returned "+ "empty; see #35314)", skey or "", _recovered,+ )+ model = _recovered+ else:+ # Cache the good resolution for future recovery turns.+ if skey:+ runner._session_state(skey).conversation.last_resolved_model = model+ runner._session_state("*").conversation.last_resolved_model = model+ return model++class GatewayTurnPrepareMixin:def _resolve_session_agent_runtime(self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,@@ -58,43 +127,7 @@ class GatewayTurnPrepareMixin:self._pre_agent_fallback_notice = Nonepolicy = policy_for_source(self, source) if source is not None else Noneif 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)- 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:- # 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=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)+ return _resolve_policy_agent_runtime(self, policy)skey = self._resolve_session_key_or_none(source, session_key)model = _resolve_gateway_model(user_config)if skey:@@ -144,7 +177,8 @@ class GatewayTurnPrepareMixin:# Layering the override on the default runtime sent its model to the default provider's# endpoint (openai-codex on the Nous URL). Run this turn on the whole default route and say# so; the persisted override is kept, so the next turn retries it.- logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc)+ logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc,+ exc_info=True)unavailable_override, override = override, Noneif runtime_kwargs is None:runtime_kwargs = _resolve_runtime_agent_kwargs()@@ -191,29 +225,7 @@ class GatewayTurnPrepareMixin:"No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],)- # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and- # the session goes silent — reuse the last model resolved for this session, else process-wide.- if not model:- _lr_state = self._peek_session_state(skey) if skey else None- _lr_star = self._peek_session_state("*")- _recovered = (- (_lr_state.conversation.last_resolved_model if _lr_state else "")- or (_lr_star.conversation.last_resolved_model if _lr_star else "")- )- if _recovered:- logger.warning(- "Empty model resolved for session=%s — recovering "- "last-known-good model %s (config read likely returned "- "empty; see #35314)", skey or "", _recovered,- )- model = _recovered- else:- # Cache the good resolution for future recovery turns.- if skey:- self._session_state(skey).conversation.last_resolved_model = model- self._session_state("*").conversation.last_resolved_model = model-- return model, runtime_kwargs+ return _recover_or_remember_model(self, skey, model), runtime_kwargsdef _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:"""Effective model/runtime config for one turn. With `/fast` priority on, fast-mode@@ -550,6 +562,7 @@ class GatewayTurnPrepareMixin:except UnscopedSecretError:home_env = (os.getenv(env_key) or "").strip()except Exception:+ logger.debug("Home-channel secret %s unreadable; treating it as unset", env_key, exc_info=True)home_env = ""# Also honor in-memory / yaml home_channel on this platform.with suppress(Exception):diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex cd49cbc7f57..18cf0f97e94 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -25,6 +25,7 @@ from utils import is_truthy_valueif TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401# Log-record parity with the origin module.logger = logging.getLogger("gateway.run")diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 37c7594eef9..c84203e2231 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1118,13 +1118,14 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# codes) belongs in the log, and the chat gets the commands that fix it. The result is# a FAILED turn: a one-shot client exits non-zero, transcript persistence closes the# turn, and an API receipt reports failure, never a completed turn with an apology.- logger.warning("Model resolution failed for session %s: %s", ctx.session_key or "", exc)+ logger.warning("Model resolution failed for session %s: %s", ctx.session_key or "", exc, exc_info=True)from hermes_state_runtime import RuntimeStoreErrorfrom agent.turn_failure_copy import stamp_failure+ resolution_error = str(exc)def _unresolved(text: str) -> dict:return stamp_failure({"final_response": text, "messages": [], "api_calls": 0, "tools": [],- "failed": True, "completed": False, "error": str(exc)},+ "failed": True, "completed": False, "error": resolution_error},"auth_permanent", False)if isinstance(exc, RuntimeStoreError):# Session-policy refusals carry a stable reason code (e.g. a CLI launch key