Skip to content

The agent that grows with you

refactor(agent): move empty-response guard settings from env vars to config.yaml

Shannon Sandsd10f87245e51
diff --git a/agent/agent_init.py b/agent/agent_init.py
index ebfda99fe93..248387b96ab 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1871,6 +1871,16 @@ def init_agent(
_agent_section = {}
agent._tool_use_enforcement = _agent_section.get("tool_use_enforcement", "auto")
+ # Empty-response retry guard config (NS-503): additive
+ # ``agent.empty_response_guard`` subsection. Resolution is tolerant —
+ # a malformed section falls back to the schema defaults (guard on,
+ # $0.25 threshold), matching the guard's overall fail-open posture.
+ from agent.empty_response_guard import resolve_guard_settings
+ (
+ agent._empty_guard_enabled,
+ agent._empty_guard_cost_threshold_usd,
+ ) = resolve_guard_settings(_agent_section.get("empty_response_guard"))
+
# Intent-ack continuation config: "auto" (default — codex_responses only,
# the historical gate), true (all api_modes), false (never), or a list of
# model-name substrings. Resolved against the active api_mode/model in the
diff --git a/agent/empty_response_guard.py b/agent/empty_response_guard.py
index 10c03267187..fbde4b58b04 100644
--- a/agent/empty_response_guard.py
+++ b/agent/empty_response_guard.py
@@ -26,27 +26,37 @@ Two independent guards, both failing OPEN to today's behaviour:
and keep the full retry budget.
2. **Cost-aware retry budget** — when the estimated input cost of a
- single empty attempt exceeds ``HERMES_EMPTY_RETRY_COST_THRESHOLD_USD``
- (default $0.25), the empty-retry budget for this streak drops from 3
- to 1. Unknown pricing, missing usage, or included/subscription routes
+ single empty attempt exceeds the configured threshold (default
+ $0.25), the empty-retry budget for this streak drops from 3 to 1.
+ Unknown pricing, missing usage, or included/subscription routes
leave the budget untouched.
-Set ``HERMES_DETERMINISTIC_EMPTY_GUARD=0`` to disable both guards.
+Configured via the additive ``agent.empty_response_guard`` section in
+``config.yaml`` (resolved once at agent init by ``agent_init``)::
+
+ agent:
+ empty_response_guard:
+ enabled: true # false = legacy fixed 3-retry behaviour
+ cost_threshold_usd: 0.25 # per-attempt cost that halves the budget
+
+Per project policy, no ``HERMES_*`` environment variables are involved —
+``.env`` is reserved for credentials; behavioural settings live in
+``config.yaml``.
"""
from __future__ import annotations
import logging
-import os
from dataclasses import dataclass
from decimal import Decimal
-from typing import Any, List, Optional
+from typing import Any, List, Optional, Tuple
logger = logging.getLogger(__name__)
DEFAULT_EMPTY_RETRY_BUDGET = 3
REDUCED_EMPTY_RETRY_BUDGET = 1
DEFAULT_COST_THRESHOLD_USD = Decimal("0.25")
+DEFAULT_GUARD_ENABLED = True
# Attribute names stashed on the agent object. State is scoped to one
# consecutive empty streak: it is cleared whenever a streak starts
@@ -55,6 +65,8 @@ DEFAULT_COST_THRESHOLD_USD = Decimal("0.25")
# success, fallback activation) without touching them.
_ATTEMPTS_ATTR = "_empty_attempt_history"
_STREAK_COST_ATTR = "_empty_streak_cost_usd"
+_ENABLED_ATTR = "_empty_guard_enabled"
+_THRESHOLD_ATTR = "_empty_guard_cost_threshold_usd"
@dataclass(frozen=True)
@@ -72,26 +84,56 @@ class EmptyAttempt:
return (self.model, self.provider, self.finish_reason)
-def guard_enabled() -> bool:
- return os.environ.get("HERMES_DETERMINISTIC_EMPTY_GUARD", "1").strip().lower() not in (
- "0",
- "false",
- "no",
- "off",
- )
+def resolve_guard_settings(section: Any) -> Tuple[bool, Decimal]:
+ """Resolve ``agent.empty_response_guard`` config into (enabled, threshold).
+ Tolerant of malformed input: anything that isn't a well-formed dict
+ (or well-formed values within it) falls back to the schema defaults.
+ Called once per agent at init; the resolved values are stashed on the
+ agent object so the hot loop never re-reads config.
+ """
+ if not isinstance(section, dict):
+ return (DEFAULT_GUARD_ENABLED, DEFAULT_COST_THRESHOLD_USD)
+
+ enabled_raw = section.get("enabled", DEFAULT_GUARD_ENABLED)
+ if isinstance(enabled_raw, bool):
+ enabled = enabled_raw
+ elif isinstance(enabled_raw, str):
+ # YAML quoting can turn true/false into strings.
+ enabled = enabled_raw.strip().lower() not in ("0", "false", "no", "off")
+ else:
+ enabled = DEFAULT_GUARD_ENABLED
+
+ threshold = DEFAULT_COST_THRESHOLD_USD
+ threshold_raw = section.get("cost_threshold_usd")
+ if threshold_raw is not None and not isinstance(threshold_raw, bool):
+ try:
+ candidate = Decimal(str(threshold_raw))
+ if candidate > 0:
+ threshold = candidate
+ except Exception: # noqa: BLE001 — malformed config must not break init
+ logger.debug(
+ "empty-guard: invalid cost_threshold_usd %r, using default",
+ threshold_raw,
+ )
+ return (enabled, threshold)
+
+
+def guard_enabled(agent: Any) -> bool:
+ """Whether the guard is enabled for this agent (config-resolved).
+
+ Agents built before the config was threaded through (tests, embedded
+ callers) simply get the default: enabled.
+ """
+ value = getattr(agent, _ENABLED_ATTR, DEFAULT_GUARD_ENABLED)
+ return value if isinstance(value, bool) else DEFAULT_GUARD_ENABLED
-def _cost_threshold_usd() -> Decimal:
- raw = os.environ.get("HERMES_EMPTY_RETRY_COST_THRESHOLD_USD", "").strip()
- if not raw:
- return DEFAULT_COST_THRESHOLD_USD
- try:
- value = Decimal(raw)
- except Exception:
- return DEFAULT_COST_THRESHOLD_USD
- if value <= 0:
- return DEFAULT_COST_THRESHOLD_USD
- return value
+
+def _cost_threshold_usd(agent: Any) -> Decimal:
+ value = getattr(agent, _THRESHOLD_ATTR, None)
+ if isinstance(value, Decimal) and value > 0:
+ return value
+ return DEFAULT_COST_THRESHOLD_USD
def _attempts(agent: Any) -> List[EmptyAttempt]:
@@ -197,7 +239,7 @@ def deterministic_empty(agent: Any) -> bool:
signature. Any attempt with missing usage or non-zero output keeps
this False (fail open — transients deserve their retries).
"""
- if not guard_enabled():
+ if not guard_enabled(agent):
return False
attempts = getattr(agent, _ATTEMPTS_ATTR, None) or []
if len(attempts) < 2:
@@ -212,12 +254,12 @@ def deterministic_empty(agent: Any) -> bool:
def empty_retry_budget(agent: Any, response: Any) -> int:
"""Empty-retry budget for the current streak (3, or 1 when a single
attempt is estimated to cost more than the configured threshold)."""
- if not guard_enabled():
+ if not guard_enabled(agent):
return DEFAULT_EMPTY_RETRY_BUDGET
cost = _estimate_attempt_cost(agent, response)
if cost is None:
return DEFAULT_EMPTY_RETRY_BUDGET
- if cost >= _cost_threshold_usd():
+ if cost >= _cost_threshold_usd(agent):
return REDUCED_EMPTY_RETRY_BUDGET
return DEFAULT_EMPTY_RETRY_BUDGET
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index cdfe670a11e..6166718a870 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -123,6 +123,22 @@ DEFAULT_CONFIG = {
# on flaky primaries; raise it if you prefer to tolerate longer
# provider hiccups on a single provider.
"api_max_retries": 3,
+ # Empty-response retry guard (NS-503). The empty-retry loop
+ # re-sends the full conversation input at full price on every
+ # attempt; these settings stop it from re-billing *deterministic*
+ # empties (unsignaled provider refusals with zero output tokens)
+ # while failing open on any ambiguous evidence (missing usage,
+ # any generated tokens, model/provider change mid-streak).
+ "empty_response_guard": {
+ # Master switch for both guards below. False restores the
+ # legacy fixed 3-retry behaviour unconditionally.
+ "enabled": True,
+ # When the estimated input cost of a single empty attempt
+ # meets or exceeds this many USD, the retry budget for the
+ # streak drops from 3 to 1. Unknown pricing or missing usage
+ # leaves the budget untouched.
+ "cost_threshold_usd": 0.25,
+ },
"service_tier": "",
# Tool-use enforcement: injects system prompt guidance that tells the
# model to actually call tools instead of describing intended actions.
diff --git a/tests/agent/test_empty_response_guard.py b/tests/agent/test_empty_response_guard.py
index 17e56836332..cc39649ae41 100644
--- a/tests/agent/test_empty_response_guard.py
+++ b/tests/agent/test_empty_response_guard.py
@@ -8,14 +8,13 @@ Fail-open contract under test:
- Missing usage -> never deterministic, default budget.
- Any generated tokens (output or reasoning) -> never deterministic.
- Different model/provider/finish_reason across attempts -> not deterministic.
-- Guard disabled via env -> everything falls back to defaults.
+- Guard disabled via config (agent.empty_response_guard.enabled: false) ->
+ everything falls back to defaults.
"""
from decimal import Decimal
from types import SimpleNamespace
-import pytest
-
from agent import empty_response_guard as guard
@@ -125,9 +124,8 @@ class TestDeterministicEmpty:
agent._empty_content_retries += 1
assert guard.deterministic_empty(agent) is False
- def test_guard_disabled_via_env(self, monkeypatch):
- monkeypatch.setenv("HERMES_DETERMINISTIC_EMPTY_GUARD", "0")
- agent = _agent()
+ def test_guard_disabled_via_config(self):
+ agent = _agent(_empty_guard_enabled=False)
_record_streak(agent, [_response(), _response()])
assert guard.deterministic_empty(agent) is False
@@ -169,29 +167,41 @@ class TestEmptyRetryBudget:
== guard.DEFAULT_EMPTY_RETRY_BUDGET
)
- def test_custom_threshold_env(self, monkeypatch):
- monkeypatch.setenv("HERMES_EMPTY_RETRY_COST_THRESHOLD_USD", "5.00")
+ def test_custom_threshold_config(self, monkeypatch):
monkeypatch.setattr(
guard, "_estimate_attempt_cost", lambda a, r: Decimal("0.80")
)
assert (
- guard.empty_retry_budget(_agent(), _response())
+ guard.empty_retry_budget(
+ _agent(_empty_guard_cost_threshold_usd=Decimal("5.00")),
+ _response(),
+ )
== guard.DEFAULT_EMPTY_RETRY_BUDGET
)
- def test_bad_threshold_env_falls_back(self, monkeypatch):
- monkeypatch.setenv("HERMES_EMPTY_RETRY_COST_THRESHOLD_USD", "banana")
- assert guard._cost_threshold_usd() == guard.DEFAULT_COST_THRESHOLD_USD
- monkeypatch.setenv("HERMES_EMPTY_RETRY_COST_THRESHOLD_USD", "-1")
- assert guard._cost_threshold_usd() == guard.DEFAULT_COST_THRESHOLD_USD
+ def test_bad_threshold_attr_falls_back(self):
+ # Non-Decimal or non-positive resolved values fall back to default.
+ assert (
+ guard._cost_threshold_usd(_agent(_empty_guard_cost_threshold_usd="banana"))
+ == guard.DEFAULT_COST_THRESHOLD_USD
+ )
+ assert (
+ guard._cost_threshold_usd(
+ _agent(_empty_guard_cost_threshold_usd=Decimal("-1"))
+ )
+ == guard.DEFAULT_COST_THRESHOLD_USD
+ )
+ assert (
+ guard._cost_threshold_usd(_agent()) # attr absent entirely
+ == guard.DEFAULT_COST_THRESHOLD_USD
+ )
def test_guard_disabled_keeps_default_budget(self, monkeypatch):
- monkeypatch.setenv("HERMES_DETERMINISTIC_EMPTY_GUARD", "0")
monkeypatch.setattr(
guard, "_estimate_attempt_cost", lambda a, r: Decimal("9.99")
)
assert (
- guard.empty_retry_budget(_agent(), _response())
+ guard.empty_retry_budget(_agent(_empty_guard_enabled=False), _response())
== guard.DEFAULT_EMPTY_RETRY_BUDGET
)
@@ -278,3 +288,56 @@ class TestZeroOutputExtraction:
present, zero = guard._zero_output(agent, SimpleNamespace(usage=usage))
assert present is False
assert zero is False
+
+
+class TestResolveGuardSettings:
+ """resolve_guard_settings maps the additive agent.empty_response_guard
+ config.yaml section into (enabled, threshold), tolerating malformed
+ input by falling back to schema defaults."""
+
+ def test_missing_section_uses_defaults(self):
+ assert guard.resolve_guard_settings(None) == (
+ guard.DEFAULT_GUARD_ENABLED,
+ guard.DEFAULT_COST_THRESHOLD_USD,
+ )
+
+ def test_non_dict_section_uses_defaults(self):
+ assert guard.resolve_guard_settings("nope") == (
+ guard.DEFAULT_GUARD_ENABLED,
+ guard.DEFAULT_COST_THRESHOLD_USD,
+ )
+
+ def test_disabled(self):
+ enabled, _ = guard.resolve_guard_settings({"enabled": False})
+ assert enabled is False
+
+ def test_yaml_string_bool(self):
+ enabled, _ = guard.resolve_guard_settings({"enabled": "false"})
+ assert enabled is False
+ enabled, _ = guard.resolve_guard_settings({"enabled": "true"})
+ assert enabled is True
+
+ def test_custom_threshold(self):
+ _, threshold = guard.resolve_guard_settings({"cost_threshold_usd": 5})
+ assert threshold == Decimal("5")
+ _, threshold = guard.resolve_guard_settings({"cost_threshold_usd": "1.50"})
+ assert threshold == Decimal("1.50")
+
+ def test_bad_threshold_falls_back(self):
+ _, threshold = guard.resolve_guard_settings({"cost_threshold_usd": "banana"})
+ assert threshold == guard.DEFAULT_COST_THRESHOLD_USD
+ _, threshold = guard.resolve_guard_settings({"cost_threshold_usd": -1})
+ assert threshold == guard.DEFAULT_COST_THRESHOLD_USD
+ _, threshold = guard.resolve_guard_settings({"cost_threshold_usd": True})
+ assert threshold == guard.DEFAULT_COST_THRESHOLD_USD
+
+ def test_default_config_schema_matches(self):
+ """The shipped DEFAULT_CONFIG section resolves to the module
+ defaults — keeps config_defaults.py and this module in sync."""
+ from hermes_cli.config_defaults import DEFAULT_CONFIG
+
+ section = DEFAULT_CONFIG["agent"]["empty_response_guard"]
+ assert guard.resolve_guard_settings(section) == (
+ guard.DEFAULT_GUARD_ENABLED,
+ guard.DEFAULT_COST_THRESHOLD_USD,
+ )
diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.py
index 45f2e01dbba..ddd8702fb72 100644
--- a/tests/run_agent/test_run_agent.py
+++ b/tests/run_agent/test_run_agent.py
@@ -3293,6 +3293,31 @@ class TestRunConversation:
# proves determinism, remaining retries are skipped.
assert result["api_calls"] == 2
+ def test_guard_disabled_via_config_restores_legacy_retries(self, agent):
+ """NS-503: agent.empty_response_guard.enabled: false in config.yaml
+ (resolved to _empty_guard_enabled at init) restores the legacy
+ fixed 3-retry behaviour even for deterministic empties."""
+ self._setup_agent(agent)
+ agent.base_url = "http://127.0.0.1:1234/v1"
+ agent._empty_guard_enabled = False # as set by agent_init from config
+ zero_usage = {
+ "prompt_tokens": 25_900,
+ "completion_tokens": 0,
+ "total_tokens": 25_900,
+ }
+ empty_resp = _mock_response(
+ content=None, finish_reason="stop", usage=zero_usage
+ )
+ agent.client.chat.completions.create.side_effect = [empty_resp] * 6
+ with (
+ patch.object(agent, "_persist_session"),
+ patch.object(agent, "_save_trajectory"),
+ patch.object(agent, "_cleanup_task_resources"),
+ ):
+ result = agent.run_conversation("answer me")
+ assert result["completed"] is True
+ assert result["api_calls"] == 4 # legacy: 1 original + 3 retries
+
def test_empty_without_usage_keeps_full_retry_budget(self, agent):
"""NS-503 fail-open: no usage data means no evidence of a
deterministic empty — legacy 3-retry behaviour must be preserved