The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): report independent configuration-reader failures
Youngseok Oh438f19ee9bfd
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex fa0bee784f0..454035e37fd 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -687,7 +687,7 @@ def _init_prompt_cache_config(agent):# subscription users where cache writes bill against "extra usage" or for third-party proxies that# inject their own cache_control markers (#13477).agent._cache_ttl = "5m"- with suppress(Exception):+ try:from hermes_cli.config import load_config_readonly as _load_pc_cfgfrom agent.agent_runtime_helpers import cache_ttl_means_disabledfrom agent.prompt_caching import AUTO_CACHE_TTL, auto_cache_ttl_for_source@@ -705,6 +705,15 @@ def _init_prompt_cache_config(agent):agent._use_native_cache_layout = Falseagent._cache_ttl = Noneagent._cache_disabled = True+ except Exception as exc:+ # Config values and traceback frames may contain credentials.+ logger.warning(+ "Agent configuration for prompt_caching.cache_ttl could not be loaded (%s); "+ "using default prompt caching settings. Check the active Hermes Python "+ "environment and dependencies; run 'hermes config check' after "+ "configuration imports work again.",+ type(exc).__name__,+ )def _init_turn_state(agent, run_budget_seconds):@@ -2345,6 +2354,9 @@ def init_agent(_set_defaults(agent, _CONTROL_STATE)+ # Early config readers must reach the file handlers on first initialization.+ _setup_logging(agent)+# reasoning_content echo opt-in; switch_model / fallback / restore keep it in sync.agent._reasoning_echo_flag = agent._read_reasoning_echo_from_config()agent.request_overrides = dict(request_overrides or {})@@ -2359,7 +2371,6 @@ def init_agent(_init_prompt_cache_config(agent)_init_turn_state(agent, run_budget_seconds)- _setup_logging(agent)_set_defaults(agent, _STREAM_STATE)_build_client(agent, api_key, base_url, fallback_model)_init_fallback_chain(agent, fallback_model)@@ -2379,7 +2390,8 @@ def init_agent(logger.warning("Agent configuration could not be loaded (%s); using defaults for ""memory, skills, compression and related settings. Check the active "- "Hermes Python environment and dependencies, then run 'hermes config check'.",+ "Hermes Python environment and dependencies; run 'hermes config check' "+ "after configuration imports work again.",type(exc).__name__,)_agent_cfg = {}diff --git a/agent/reasoning_params.py b/agent/reasoning_params.pyindex cdb57a8d58c..30f724a3f8d 100644--- a/agent/reasoning_params.py+++ b/agent/reasoning_params.py@@ -4,6 +4,7 @@ When ``reasoning`` extra_body is safe to send, LM Studio / Ollama / GitHub Model``reasoning_content`` echo families, and strict-API tool-call sanitising.Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO unchanged."""+import loggingimport timefrom agent.lazy_forward import forward as _forward, forward_static as _forward_static@@ -192,7 +193,15 @@ class ReasoningParamsMixin:try:from hermes_cli.config import load_config_readonlyreturn bool((load_config_readonly().get("model") or {}).get("reasoning_echo"))- except Exception:+ except Exception as exc:+ # Log the class, never the config value or exception traceback.+ logging.getLogger("run_agent").warning(+ "Agent configuration for model.reasoning_echo could not be loaded (%s); "+ "using the default reasoning echo setting. Check the active Hermes Python "+ "environment and dependencies; run 'hermes config check' after "+ "configuration imports work again.",+ type(exc).__name__,+ )return False# Echo families are host/provider-driven, not model-name-driven: aggregators re-exporting Kimi reject thediff --git a/tests/agent/test_config_load_warning.py b/tests/agent/test_config_load_warning.pyindex f86e24d6cfa..b7be449a3e8 100644--- a/tests/agent/test_config_load_warning.py+++ b/tests/agent/test_config_load_warning.py@@ -54,68 +54,129 @@ def make_agent(monkeypatch):agent.close()- ("failure_at", "error_type"),- [("import", ModuleNotFoundError), ("load", RuntimeError)],-)[email protected]("failure_at", ["import", "load"])[email protected]("reader", ["cache", "reasoning", "sections", "all"])def test_config_failure_warns_without_exposing_values_and_preserves_defaults(- make_agent, monkeypatch, caplog, failure_at, error_type,+ make_agent, monkeypatch, caplog, failure_at, reader,):from hermes_cli import config+ from hermes_constants import get_hermes_home+ import sys- reference = make_agent()+ home = get_hermes_home()+ configured = (+ "prompt_caching:\n cache_ttl: 1h\n"+ "model:\n reasoning_echo: true\n"+ "compression:\n enabled: false\n"+ "skills:\n creation_nudge_interval: 99\n"+ )+ config_path = home / "config.yaml"+ config_path.write_text(configured, encoding="utf-8")+ reader_functions = {+ "cache": "_init_prompt_cache_config",+ "reasoning": "_read_reasoning_echo_from_config",+ "sections": "init_agent",+ }+ affected = set(reader_functions) if reader == "all" else {reader}+ targets = {reader_functions[name] for name in affected}secret = "private-config-value-do-not-log"+ error_type = ModuleNotFoundError if failure_at == "import" else RuntimeErrorerror = error_type(f"Could not load config.yaml: api_key: {secret}")- caplog.clear()+ intercepted = set()with monkeypatch.context() as failure:if failure_at == "import":real_import = builtins.__import__def import_with_failure(name, globals=None, locals=None, fromlist=(), level=0):+ caller = sys._getframe(1).f_code.co_nameif (name == "hermes_cli.config"- and (globals or {}).get("__name__") == "agent.agent_init"- and fromlist == ("load_config_readonly",)+ and "load_config_readonly" in fromlist+ and (globals or {}).get("__name__")+ in {"agent.agent_init", "agent.reasoning_params"}+ and caller in targets):+ intercepted.add(caller)raise errorreturn real_import(name, globals, locals, fromlist, level)failure.setattr(builtins, "__import__", import_with_failure)else:- def load_with_failure():- raise error+ real_load = config.load_config_readonly++ def load_with_failure(*args, **kwargs):+ caller = sys._getframe(1).f_code.co_name+ if caller in targets:+ intercepted.add(caller)+ raise error+ return real_load(*args, **kwargs)failure.setattr(config, "load_config_readonly", load_with_failure)+ # The failing object is the first construction, so an early diagnostic+ # must reach the real file handler, not one initialized by a reference.with caplog.at_level(logging.WARNING, logger="run_agent"):fallback = make_agent()+ assert intercepted == targets+ assert config_path.read_text(encoding="utf-8-sig") == configuredwarnings = [record for record in caplog.recordsif record.name == "run_agent" and record.levelno >= logging.WARNINGand "config" in record.getMessage().lower()and "default" in record.getMessage().lower()]- assert len(warnings) == 1- message = warnings[0].getMessage()- assert error_type.__name__ in message- assert all(section in message.lower() for section in ("memory", "skills", "compression"))- # Format the whole record: exc_info can leak values even when getMessage() is safe.- assert secret not in logging.Formatter().format(warnings[0])-- assert fallback._memory_manager is reference._memory_manager is None- assert fallback._memory_store is not None- assert fallback._memory_store.memory_entries == reference._memory_store.memory_entries+ assert len(warnings) == len(affected)+ expected_sections = {+ "cache": "prompt_caching.cache_ttl",+ "reasoning": "model.reasoning_echo",+ "sections": "memory",+ }+ messages = [record.getMessage() for record in warnings]+ persisted = (home / "logs" / "errors.log").read_text(encoding="utf-8-sig")+ for scope in affected:+ assert any(expected_sections[scope] in message for message in messages)+ assert expected_sections[scope] in persisted+ assert all(error_type.__name__ in message for message in messages)+ assert secret not in caplog.text+ assert secret not in persisted+ assert all(secret not in logging.Formatter().format(record) for record in warnings)++ caplog.clear()+ healthy = make_agent()+ config_path.write_text("", encoding="utf-8")+ defaults = make_agent()+ assert healthy._cache_ttl != defaults._cache_ttl+ assert healthy._reasoning_echo_flag is not defaults._reasoning_echo_flag+ assert healthy.compression_enabled is not defaults.compression_enabled+ assert healthy._skill_nudge_interval != defaults._skill_nudge_interval+ for scope, attrs in {+ "cache": ("_cache_ttl", "_cache_disabled", "_use_prompt_caching"),+ "reasoning": ("_reasoning_echo_flag",),+ "sections": ("compression_enabled", "_skill_nudge_interval"),+ }.items():+ reference = defaults if scope in affected else healthy+ for attr in attrs:+ assert getattr(fallback, attr) == getattr(reference, attr), attr+ assert fallback._memory_manager is healthy._memory_manager is defaults._memory_manager is Nonefor attr in ("_memory_enabled", "_user_profile_enabled", "_memory_nudge_interval",- "_skill_nudge_interval", "compression_enabled", "compression_in_place",- "max_compression_attempts",+ "compression_in_place", "max_compression_attempts",):- assert getattr(fallback, attr) == getattr(reference, attr), attr+ assert getattr(fallback, attr) == getattr(healthy, attr) == getattr(defaults, attr), attrassert (fallback.context_compressor.threshold_percent- == reference.context_compressor.threshold_percent+ == healthy.context_compressor.threshold_percent+ == defaults.context_compressor.threshold_percent+ )+ assert fallback._memory_store.memory_entries == healthy._memory_store.memory_entries+ assert fallback._memory_store.memory_entries == defaults._memory_store.memory_entries+ assert not any(+ record.name == "run_agent" and record.levelno >= logging.WARNING+ and "config" in record.getMessage().lower()+ and "default" in record.getMessage().lower()+ for record in caplog.records)