The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(nous): adopt a fresh agent key before the one in hand expires, and start the keepalive in every process that routes to Nous
Teknium058ad0329e74
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 3421e26df8c..ae011ff54e4 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -433,6 +433,17 @@ def _finalize_routing(agent, api_mode, credential_pool):with suppress(Exception):agent._get_transport()+ # The Nous agent key lives ~1 h. Without the proactive refresher every agent in the process+ # discovers expiry reactively, on its own next request, all in the same minute: with 200+ # in-process subagents that was a 401 storm each hour (620 in one run) and the credential+ # pool benched the provider for all of them. The gateway and web server start this thread+ # at boot; the CLI process (and everything spawned inside it) never did. Idempotent,+ # process-wide, daemon.+ if agent.provider == "nous":+ with suppress(Exception):+ from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalive+ start_nous_auth_keepalive()+with suppress(Exception):from hermes_cli.model_normalize import (_AGGREGATOR_PROVIDERS, normalize_model_for_providerdiff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.pyindex 57384bb1c16..8e848a70c22 100644--- a/agent/client_lifecycle.py+++ b/agent/client_lifecycle.py@@ -3,6 +3,7 @@ shared primary client, single-slot per-request client caches (owner-thread closecredential refresh/rotation, route-derived default headers. Extracted from ``run_agent.py``, MRO unchanged."""import loggingimport threading+import timefrom contextlib import suppressfrom typing import Any, Optional@@ -542,6 +543,8 @@ class ClientLifecycleMixin:api_key, base_url = creds.get("api_key"), creds.get("base_url")if not _valid_credential_pair(api_key, base_url):return False+ if str(api_key).strip() == str(self.api_key or "").strip():+ return False # store holds the same key: nothing to adopt, no client rebuildif self.api_mode == "anthropic_messages":self.api_key, self.base_url = api_key.strip(), base_url.strip().rstrip("/")self._anthropic_api_key, self._anthropic_base_url = self.api_key, self.base_url@@ -551,6 +554,32 @@ class ClientLifecycleMixin:self._client_kwargs.pop("default_headers", None)return self._adopt_openai_credentials(api_key, base_url, reason="nous_credential_refresh")+ # Adopt a fresh key this many seconds before the one in hand expires. Wider than the store's+ # own refresh skew (120 s) so the keepalive has normally already minted the replacement.+ _NOUS_KEY_ADOPT_SKEW_S = 180++ def _adopt_nous_key_before_expiry(self) -> bool:+ """Swap in a fresh Nous agent key BEFORE the one in hand expires, so the request never 401s.++ The agent key is a JWT; its ``exp`` is read locally (no network). Inside the skew the store+ is re-read under the auth-store lock: the keepalive thread normally holds a fresh key already+ (adopt, no POST), otherwise ONE refresh runs and every peer adopts its result. Before this,+ every agent in a process learned about the hourly expiry from its own 401, all in the same+ minute (620 in one 200-subagent run), and the pool benched the sole credential for all of+ them. Returns True when a new key was adopted.+ """+ if getattr(self, "provider", "") != "nous" or not getattr(self, "api_key", None):+ return False+ try:+ from hermes_cli.auth_constants import _decode_jwt_claims+ exp = _decode_jwt_claims(self.api_key).get("exp")+ except Exception:+ return False+ if not isinstance(exp, (int, float)) or exp - time.time() > self._NOUS_KEY_ADOPT_SKEW_S:+ return False+ return self._try_refresh_nous_client_credentials(force=False)++def _resolve_env_credentials(self) -> Optional[tuple]:"""Current ``.env``-sourced ``(api_key, base_url, default_base)`` for this provider, or ``None``.diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex 1b4917758c4..d287abb59bc 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -50,6 +50,15 @@ def prepare_iteration(agent: Any,*, messages: Any, api_call_count: Any) -> Iteraif agent._skill_nudge_interval > 0 and "skill_manage" in agent.valid_tool_names:agent._iters_since_skill += 1+ # Nous agent keys live ~1 h and a single turn can run for hours: adopt the keepalive's fresh+ # key before the one in hand expires (local JWT exp read; no network unless inside the skew)+ # instead of letting this iteration's request 401. With many agents sharing the hour that+ # 401 was a storm, and the pool benched the sole credential for all of them.+ try:+ agent._adopt_nous_key_before_expiry()+ except Exception:+ logger.debug("Nous key pre-expiry adoption failed", exc_info=True)+# Drain a /steer sent during the last API call into the newest tool message so# it lands THIS iteration. Never put in a user message (breaks alternation)._pre_api_steer = agent._drain_pending_steer()diff --git a/tests/agent/test_nous_key_pre_expiry_adoption.py b/tests/agent/test_nous_key_pre_expiry_adoption.pynew file mode 100644index 00000000000..320d2e31ca9--- /dev/null+++ b/tests/agent/test_nous_key_pre_expiry_adoption.py@@ -0,0 +1,74 @@+"""Nous agent keys live ~1 h. Every agent in a process must not learn about expiry from its own 401.++In a 1,393-subagent run the hourly expiry produced 620 authentication_error 401s (177 in one hour) and+the credential pool benched the sole credential for every worker at once; the CLI process never+started the proactive keepalive, and nothing adopted a fresh key before a request was sent.+"""+import base64+import json+import time+from unittest.mock import patch++from agent.client_lifecycle import ClientLifecycleMixin+++def _jwt(exp: float) -> str:+ def b64(o):+ return base64.urlsafe_b64encode(json.dumps(o).encode()).rstrip(b"=").decode()+ return f"{b64({'alg': 'none'})}.{b64({'exp': exp})}.sig"+++class _Agent(ClientLifecycleMixin):+ def __init__(self, key):+ self.provider, self.api_mode, self.api_key, self.base_url = "nous", "chat_completions", key, "https://inference-api.nousresearch.com/v1"+ self._client_kwargs, self.adopted = {}, []++ def _adopt_openai_credentials(self, api_key, base_url, *, reason):+ self.adopted.append((api_key, reason))+ self.api_key = api_key+ return True+++def test_key_far_from_expiry_is_left_alone_without_touching_the_store():+ agent = _Agent(_jwt(time.time() + 3000))+ with patch("hermes_cli.auth.resolve_nous_runtime_credentials", side_effect=AssertionError("must not hit the store")):+ assert agent._adopt_nous_key_before_expiry() is False+ assert agent.adopted == []+++def test_key_inside_the_skew_adopts_the_stores_fresh_key_without_forcing_a_refresh():+ agent = _Agent(_jwt(time.time() + 60))+ calls = []++ def resolve(**kw):+ calls.append(kw)+ return {"api_key": "fresh-key", "base_url": agent.base_url}++ with patch("hermes_cli.auth.resolve_nous_runtime_credentials", side_effect=resolve):+ assert agent._adopt_nous_key_before_expiry() is True+ assert calls[0]["force_refresh"] is False # the keepalive/peer refresh is adopted, never re-minted+ assert agent.adopted == [("fresh-key", "nous_credential_refresh")]+++def test_same_key_back_from_the_store_is_not_readopted():+ """No client rebuild when the store still holds the key in hand (refresh pending elsewhere)."""+ key = _jwt(time.time() + 60)+ agent = _Agent(key)+ with patch("hermes_cli.auth.resolve_nous_runtime_credentials", return_value={"api_key": key, "base_url": agent.base_url}):+ assert agent._adopt_nous_key_before_expiry() is False+ assert agent.adopted == []+++def test_keepalive_thread_starts_when_an_agent_routes_to_nous(monkeypatch, tmp_path):+ """Real construction path: the CLI process builds agents through AIAgent, never through the gateway boot."""+ from run_agent import AIAgent++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hh"))+ started = []+ monkeypatch.setattr("hermes_cli.nous_auth_keepalive.start_nous_auth_keepalive", lambda: started.append(1))+ AIAgent(api_key="k", base_url="https://inference-api.nousresearch.com/v1", provider="nous",+ model="anthropic/claude-fable-5.1", quiet_mode=True, skip_context_files=True, skip_memory=True)+ assert started == [1]+ AIAgent(api_key="k", base_url="https://openrouter.ai/api/v1", provider="openrouter",+ model="anthropic/claude-fable-5.1", quiet_mode=True, skip_context_files=True, skip_memory=True)+ assert started == [1]