The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(codex): make the post-terminal drain budget a config key (agent.stream_drain_timeout)
teknium1b949348c27c4
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.pyindex fc31170cebc..ee26c89b477 100644--- a/agent/codex_runtime.py+++ b/agent/codex_runtime.py@@ -24,7 +24,26 @@ _codex_watchdog_state_var: contextvars.ContextVar[Any | None] = contextvars.Cont"codex_watchdog_state", default=None)-_CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS = 2.0+_DEFAULT_STREAM_DRAIN_TIMEOUT = 2.0+++def _stream_drain_timeout() -> float:+ """``agent.stream_drain_timeout`` (seconds) — how long the post-terminal SSE drain may block.++ The drain is a courtesy to Relay's finalizer, never a correctness requirement: ``final`` is fully+ assembled before it starts. A relay that never closes the socket after ``response.completed`` would+ otherwise wedge the turn until the idle watchdog discards the already-billed response (#103864).+ ``0`` skips the drain entirely.+ """+ try:+ from hermes_cli.config import load_config_readonly+ agent_cfg = load_config_readonly().get("agent")+ value = agent_cfg.get("stream_drain_timeout") if isinstance(agent_cfg, dict) else None+ if isinstance(value, (int, float)) and not isinstance(value, bool):+ return max(0.0, float(value))+ except Exception:+ pass+ return _DEFAULT_STREAM_DRAIN_TIMEOUTdef _call_guarded(fn: Callable | None, fail_msg: str, *fail_args: Any, args: tuple = (), kwargs: dict | None = None):@@ -934,6 +953,9 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltadef _drain_for_finalizer(event_stream: Any) -> None:# ``final`` is already assembled; draining only lets Relay run its finalizer. A transport error# here must NOT discard the completed, already-billed response.+ budget = _stream_drain_timeout()+ if budget <= 0:+ return # the ``finally`` below closes the streamdrained = threading.Event()def _drain() -> None:@@ -952,12 +974,12 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltadrained.set()threading.Thread(target=_drain, name="codex-post-terminal-drain", daemon=True).start()- if drained.wait(_CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS):+ if drained.wait(budget):returnlogger.warning(- "Codex Responses stream remained open %.1fs after a terminal response; closing it and returning the "- "completed response instead of retrying. %s",- _CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS, agent._client_log_context(),+ "Codex Responses stream remained open %.1fs after a terminal response (agent.stream_drain_timeout); "+ "closing it and returning the completed response instead of retrying. %s",+ budget, agent._client_log_context(),)_close_event_stream(event_stream)diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 5f0970c3936..7fe162cf85d 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -107,6 +107,11 @@ DEFAULT_CONFIG = {# whole call; the OpenAI SDK also retries transient errors (max_retries=2). Set 1 for fast# failover to fallback providers; raise to tolerate longer provider hiccups."api_max_retries": 3,+ # Seconds the Codex/Responses stream may keep reading after its terminal frame so the relay+ # finalizer can run. Relays that never close the SSE socket after response.completed would+ # otherwise wedge the turn until the idle watchdog discards the already-billed response+ # (#103864). 0 skips the drain. Well-behaved endpoints close immediately and never wait this long.+ "stream_drain_timeout": 2.0,# Empty-response retry guard. Empty retries re-send the full input at full price; this stops# re-billing deterministic empties (unsignaled refusals, zero output tokens) while failing# open on ambiguous evidence (missing usage, any tokens, model/provider change).diff --git a/tests/agent/test_run_agent_codex_responses.py b/tests/agent/test_run_agent_codex_responses.pyindex 49a66f6045b..4d0f0d176f1 100644--- a/tests/agent/test_run_agent_codex_responses.py+++ b/tests/agent/test_run_agent_codex_responses.py@@ -1128,7 +1128,7 @@ def test_run_codex_stream_bounds_post_terminal_drain(monkeypatch):return _HeldOpenAfterTerminalStream()agent.client = SimpleNamespace(responses=SimpleNamespace(create=_fake_create))- monkeypatch.setattr(codex_runtime, "_CODEX_POST_TERMINAL_DRAIN_TIMEOUT_SECONDS", 0.01)+ monkeypatch.setattr(codex_runtime, "_stream_drain_timeout", lambda: 0.01)started = time.monotonic()response = agent._run_codex_stream(_codex_request_kwargs())diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 4c8e471466a..4fe8832080b 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1250,6 +1250,7 @@ Hermes has separate timeout layers for streaming, plus a stale detector for non-| Stale stream detection | 180s | Raised to a 900s ceiling (`agent.local_stream_stale_timeout`) | `HERMES_STREAM_STALE_TIMEOUT` || Stale non-stream detection | 90s | Auto-disabled when left implicit | `providers.<id>.stale_timeout_seconds` or `HERMES_API_CALL_STALE_TIMEOUT` || API call (non-streaming) | 1800s | Unchanged | `providers.<id>.request_timeout_seconds` / `timeout_seconds` or `HERMES_API_TIMEOUT` |+| Post-terminal stream drain (Codex/Responses) | 2s | Unchanged | `agent.stream_drain_timeout` |The **socket read timeout** controls how long httpx waits for the next chunk of data from the provider. Local LLMs can take minutes for prefill on large contexts before producing the first token, so Hermes raises this to 30 minutes when it detects a local endpoint. If you explicitly set `HERMES_STREAM_READ_TIMEOUT`, that value is always used regardless of endpoint detection.@@ -1257,6 +1258,8 @@ The **stale stream detection** kills connections that receive SSE keep-alive pinThe **stale non-stream detection** kills non-streaming calls that produce no response for too long. By default Hermes disables this on local endpoints to avoid false positives during long prefills. If you explicitly set `providers.<id>.stale_timeout_seconds`, `providers.<id>.models.<model>.stale_timeout_seconds`, or `HERMES_API_CALL_STALE_TIMEOUT`, that explicit value is honored even on local endpoints.+The **post-terminal stream drain** bounds how long a Codex/Responses stream keeps reading after its terminal `response.completed` frame (a courtesy so the relay finalizer can run). Some relays never close the SSE socket after the terminal frame; without a bound the turn wedged until the stale-stream watchdog fired and discarded the already-billed response, then retried. After `agent.stream_drain_timeout` seconds the stream is closed and the completed response is returned. Endpoints that close the connection normally finish the drain immediately and never wait this long; set `0` to skip the drain entirely.+This budget bounds every non-streaming call. A provider that accepts a request and then goes silent — connection held open, no bytes, no error — is aborted at the stale timeout and retried, rather than hanging until the much longer socket read timeout (or, for an unattended cron run, until something external kills the process).The periodic provider-wait notice appears only after at least **60 seconds of silence**. The Codex Responses **waiting status** describes silence, not total generation time: active stream events (including reasoning) keep it quiet. If events stop, it reports time without stream events instead of claiming no response has arrived; the notice clears when events resume. When a reconnect starts a fresh first-event watchdog phase, the waiting status follows that phase. This display behavior does not extend the separate wall-clock stale-call budget or change watchdog timeouts. Chat-completion streams likewise clear their silence warning promptly when chunks resume, without replacing a local model-loading status.