Skip to content

The agent that grows with you

feat(streaming): opt-in cap on a streaming response's total lifetime

Tekniumac8037c05bae
diff --git a/agent/chat_completion_stream_monitor.py b/agent/chat_completion_stream_monitor.py
index 47d309e1b10..c6c45670c26 100644
--- a/agent/chat_completion_stream_monitor.py
+++ b/agent/chat_completion_stream_monitor.py
@@ -5,6 +5,7 @@ for a wedged inline call) and the shared "no visible text was delivered" check
(``_forget_invisible_deltas``) used by the error and abandon paths.
"""
+import contextlib
import logging
import time
from types import SimpleNamespace
@@ -14,6 +15,7 @@ from agent import chat_completion_wait_notice as wn
from agent.model_metadata import is_local_endpoint
from agent.proxy_bypass import is_loopback_host
from agent.sleep_clock import SleepWatch
+from agent.stream_max_lifetime import StreamLifetime, resolve_stream_max_lifetime
logger = logging.getLogger(__name__)
# Kills of one dispatched attempt whose worker never unwinds before the monitor gives up on it.
@@ -29,6 +31,7 @@ class StreamingWaitMonitor:
# Inline call wedged past the limit: the stale-timer re-arm time after which activity touches
# are withheld (None = claim liveness as usual). A real chunk after it lifts the hold.
_liveness_withheld_at = None
+ _lifetime = StreamLifetime(0.0) # opt-in agent.stream_max_lifetime; real clock set when the monitor starts
def _claims_liveness(self) -> bool:
since = self._liveness_withheld_at
@@ -186,6 +189,32 @@ class StreamingWaitMonitor:
# Chunks are flowing — keep the tracker fresh, leave the display alone.
self.agent._touch_activity(f"waiting for stream response ({waiting_secs}s, no chunks yet)")
+ def _check_stream_lifetime(self) -> None:
+ """Opt-in ``agent.stream_max_lifetime``: a stream that keeps sending chunks but never
+ finishes never trips the stale check. Kill it like a stale kill (cancel the attempt,
+ abort the request-local client, count it in the cross-turn breaker) so the retry loop
+ or the partial-delivery continuation takes over."""
+ if not self._lifetime.cap: # off (the default): no per-tick work
+ return
+ with self.stream_attempt_lock:
+ attempt = int(self.stream_attempt_state["current"])
+ elapsed = self._lifetime.exceeded(attempt) if attempt else None
+ if elapsed is None:
+ return
+ model = self.api_kwargs.get("model", "unknown")
+ logger.warning("Stream still running after %.0fs (stream_max_lifetime %.0fs) — killing connection. "
+ "model=%s", elapsed, self._lifetime.cap, model)
+ self.agent._buffer_diagnostic_status(
+ f"⚠️ Response still streaming after {int(elapsed)}s (stream_max_lifetime "
+ f"{int(self._lifetime.cap)}s, model: {model}). Aborting...")
+ killed = self._attempt_stream_response
+ with contextlib.suppress(Exception):
+ self._cancel_current_stream_attempt("stream_max_lifetime_kill")
+ self.clients.close_once("stream_max_lifetime_kill")
+ self._shutdown_stale_attempt_socket(killed)
+ self._count_stale_attempt()
+ self.last_chunk_time["t"] = time.time() # the stale timer restarts with the kill
+
def _monitor_loop(self) -> None:
_HEARTBEAT_INTERVAL = 30.0 # seconds between gateway activity touches
self._mon = SimpleNamespace(
@@ -197,6 +226,7 @@ class StreamingWaitMonitor:
# Only a server on this machine sleeps with it; a remote one kept working (or died).
sleep_watch = (SleepWatch(interval=0.3) if self.agent.base_url
and is_loopback_host(urlsplit(self.agent.base_url).hostname) else None)
+ self._lifetime = StreamLifetime(resolve_stream_max_lifetime(self._stream_stale_timeout))
while not self._call_done.is_set():
self._call_done.wait(timeout=0.3)
if sleep_watch is not None:
@@ -219,6 +249,7 @@ class StreamingWaitMonitor:
self._mon.wait_notice_started_ts = None # Reconnect status has its own owner.
self._mon.wait_notice.reset()
self._kill_stale_stream(_stale_elapsed)
+ self._check_stream_lifetime()
if self.agent._interrupt_requested:
self._abort_for_interrupt(_stale_elapsed)
return
diff --git a/agent/stream_max_lifetime.py b/agent/stream_max_lifetime.py
new file mode 100644
index 00000000000..1b0c8d45d7d
--- /dev/null
+++ b/agent/stream_max_lifetime.py
@@ -0,0 +1,65 @@
+"""Opt-in total-lifetime cap for one streaming response attempt.
+
+The stale-stream detector bounds the gap BETWEEN chunks and resets on every
+chunk, so a stream that keeps yielding data but never finishes (a gateway
+trickling chunks, a runaway generation) is never cut. ``agent.stream_max_lifetime``
+(env ``HERMES_STREAM_MAX_LIFETIME``) caps the wall-clock time since the current
+attempt started; it never resets on chunk arrival. Default ``0`` = off, so a
+legitimately long reasoning stream is never cut unless the user asks for it.
+"""
+
+from __future__ import annotations
+
+import logging
+import math
+import time
+
+from utils import env_float
+
+logger = logging.getLogger(__name__)
+
+
+def resolve_stream_max_lifetime(stale_timeout: float | None) -> float:
+ """Cap in seconds, ``0`` when disabled. Floored at a finite stale timeout so the
+ cap can never cut a stream the stale detector would still be waiting on."""
+ configured = 0.0
+ try:
+ from hermes_cli.config import load_config_readonly
+
+ agent_cfg = (load_config_readonly() or {}).get("agent")
+ value = agent_cfg.get("stream_max_lifetime") if isinstance(agent_cfg, dict) else None
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ configured = float(value)
+ except Exception: # unreadable config = the documented default (off)
+ logger.debug("stream_max_lifetime: config unreadable, cap off", exc_info=True)
+ cap = env_float("HERMES_STREAM_MAX_LIFETIME", configured)
+ if not cap or cap <= 0 or not math.isfinite(cap):
+ return 0.0
+ if stale_timeout is not None and math.isfinite(stale_timeout):
+ cap = max(cap, stale_timeout)
+ return cap
+
+
+class StreamLifetime:
+ """Per-call clock: restarts whenever a new stream attempt is dispatched, so each
+ retry gets the full cap, and after each kill (the killed attempt may unwind slowly)."""
+
+ def __init__(self, cap: float):
+ self.cap = cap
+ self.attempt = None
+ self.started = time.time()
+
+ def exceeded(self, attempt) -> float | None:
+ """Elapsed seconds when the cap is exceeded for ``attempt``, else ``None``."""
+ if not self.cap:
+ return None
+ now = time.time()
+ if attempt != self.attempt:
+ self.attempt, self.started = attempt, now
+ return None
+ elapsed = now - self.started
+ if elapsed <= self.cap:
+ return None
+ self.started = now
+ return elapsed
+
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 6a8f238d042..66e8bb530c8 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -253,11 +253,11 @@ DEFAULT_CONFIG = {
# message isn't served with a skeleton system prompt. On timeout the gate opens and warm-up
# finishes in the background. 0 = disable warm-up (lazy init).
"gateway_startup_warmup_timeout": 20,
- # Stale-stream ceiling (seconds) for local providers (Ollama, oMLX, llama-cpp). Applied when
- # the base stale timeout is at its 180s default and a local endpoint is detected, so a
- # wedged local server eventually trips the detector instead of hanging forever. Env
- # HERMES_LOCAL_STREAM_STALE_TIMEOUT overrides.
+ # Stale-stream ceiling (s) for local providers (Ollama, oMLX, llama-cpp) when the base stale
+ # timeout is at its 180s default, so a wedged local server eventually trips the detector
+ # instead of hanging forever. Env HERMES_LOCAL_STREAM_STALE_TIMEOUT overrides.
"local_stream_stale_timeout": 900,
+ "stream_max_lifetime": 0, # opt-in whole-stream cap in s, 0 = off (agent/stream_max_lifetime.py)
# How user-attached images reach the main model (gateway, TUI, CLI /attach). "auto" = native
# when the model reports supports_vision=True AND auxiliary.vision.provider is not
# explicitly set, else text; "native" = always attach (non-vision models error at the
diff --git a/tests/agent/test_stream_max_lifetime.py b/tests/agent/test_stream_max_lifetime.py
new file mode 100644
index 00000000000..ec59bd3096f
--- /dev/null
+++ b/tests/agent/test_stream_max_lifetime.py
@@ -0,0 +1,86 @@
+"""Opt-in ``agent.stream_max_lifetime``: a stream that keeps sending chunks but
+never finishes is cut at the cap (the stale detector resets on every chunk and
+never fires). Off by default."""
+
+import json
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import httpx
+import pytest
+
+import run_agent
+from agent.chat_completion_helpers import interruptible_streaming_api_call
+from agent.stream_max_lifetime import resolve_stream_max_lifetime
+from hermes_cli.config_defaults import DEFAULT_CONFIG
+
+
+class _DripWire:
+ """Real OpenAI-wire SSE server: one content chunk every 50 ms for ~8 s, then a clean finish."""
+
+ def __init__(self):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_a):
+ pass
+
+ def do_POST(self):
+ self.rfile.read(int(self.headers.get("content-length", 0)))
+ if not self.path.endswith("/chat/completions"):
+ self.send_response(404)
+ self.end_headers()
+ return
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.end_headers()
+ chunk = {"id": "c1", "object": "chat.completion.chunk", "created": 1, "model": "m",
+ "choices": [{"index": 0, "delta": {"content": "."}, "finish_reason": None}]}
+ fin = {**chunk, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
+ try:
+ for _ in range(160):
+ self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())
+ self.wfile.flush()
+ time.sleep(0.05) # health: allow HX013 -- the drip cadence is the behaviour under test
+ self.wfile.write(f"data: {json.dumps(fin)}\n\ndata: [DONE]\n\n".encode())
+ self.wfile.flush()
+ except OSError:
+ pass
+
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.base_url = f"http://127.0.0.1:{self.server.server_address[1]}/v1"
+
+
+def drip_wire():
+ w = _DripWire()
+ yield w
+ w.server.shutdown()
+ w.server.server_close()
+
+
+def test_cap_cuts_a_stream_that_never_goes_quiet(drip_wire, monkeypatch):
+ monkeypatch.setenv("HERMES_STREAM_STALE_TIMEOUT", "1.0")
+ monkeypatch.setenv("HERMES_STREAM_MAX_LIFETIME", "1.5")
+ monkeypatch.setenv("HERMES_STREAM_RETRIES", "0")
+ agent = run_agent.AIAgent(
+ api_key="test-key", base_url=drip_wire.base_url, model="m", provider="custom",
+ platform="cli", quiet_mode=True, skip_context_files=True, skip_memory=True,
+ enabled_toolsets=[], max_iterations=1,
+ )
+ started = time.time()
+ # Without the cap the drip completes normally after ~8 s; with it the call ends early.
+ # Killed like a stale kill: the undelivered stream surfaces the transport error to the loop.
+ with pytest.raises(httpx.RemoteProtocolError):
+ interruptible_streaming_api_call(agent, {"model": "m", "messages": [{"role": "user", "content": "hi"}]})
+ assert time.time() - started < 5.0
+
+
+def test_cap_is_off_by_default_and_never_undercuts_the_stale_timeout(monkeypatch):
+ monkeypatch.delenv("HERMES_STREAM_MAX_LIFETIME", raising=False)
+ assert DEFAULT_CONFIG["agent"]["stream_max_lifetime"] == 0
+ monkeypatch.setenv("HERMES_STREAM_MAX_LIFETIME", "60")
+ assert resolve_stream_max_lifetime(180.0) == 180.0
+ assert resolve_stream_max_lifetime(float("inf")) == 60.0
+ monkeypatch.setenv("HERMES_STREAM_MAX_LIFETIME", "0")
+ assert resolve_stream_max_lifetime(180.0) == 0.0
diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md
index 736aeba849a..a98e075efb8 100644
--- a/website/docs/reference/environment-variables.md
+++ b/website/docs/reference/environment-variables.md
@@ -830,6 +830,7 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us
| `HERMES_STREAM_READ_TIMEOUT` | Streaming socket read timeout in seconds (default: `120`). Auto-increased to `HERMES_API_TIMEOUT` for local providers. Increase if local LLMs time out during long code generation. |
| `HERMES_STREAM_STALE_TIMEOUT` | Stale stream detection timeout in seconds (default: `180`). Auto-disabled for local providers. Triggers connection kill if no chunks arrive within this window. |
| `HERMES_LOCAL_STREAM_STALE_TIMEOUT` | Stale stream ceiling for local providers (Ollama, oMLX, llama-cpp) in seconds (default: `900`). When the base stale timeout is at its default and a local endpoint is detected, this finite ceiling replaces the former infinite disable so a wedged local server eventually trips the detector instead of hanging forever. Also configurable via `agent.local_stream_stale_timeout` in `config.yaml`. |
+| `HERMES_STREAM_MAX_LIFETIME` | Opt-in total wall-clock cap in seconds for one streaming response attempt (default: `0`, off). Unlike the stale-stream detector it never resets on chunk arrival, so it stops a stream that keeps sending data but never finishes. Never fires before the effective stale-stream timeout. Also configurable via `agent.stream_max_lifetime` in `config.yaml`. |
| `HERMES_STREAM_RETRIES` | Number of mid-stream reconnect attempts on transient network errors (default: `3`). |
| `HERMES_STREAM_STALE_GIVEUP` | Cross-turn circuit breaker: after this many consecutive stale kills (streaming or non-streaming) with no completed response, abort each call immediately with an actionable error instead of re-waiting out the stale timeout (default: `5`, `0` disables). Resets on any completed response, `/model` switch, fallback activation, or turn-start primary restore. |
| `HERMES_AGENT_TIMEOUT` | Gateway inactivity timeout for a running agent in seconds (default: `1800`, 30 minutes). Resets on every tool call and streamed token. Set to `0` to disable. |
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 4fc9743e639..7c4685b5e99 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1368,6 +1368,7 @@ Hermes has separate timeout layers for streaming, plus a stale detector for non-
|---------|---------|----------------|--------------|
| Socket read timeout | 120s | Auto-raised to 1800s | `HERMES_STREAM_READ_TIMEOUT` |
| Stale stream detection | 180s | Raised to a 900s ceiling (`agent.local_stream_stale_timeout`) | `HERMES_STREAM_STALE_TIMEOUT` |
+| Stream max lifetime (opt-in) | Off (`0`) | Same | `agent.stream_max_lifetime` or `HERMES_STREAM_MAX_LIFETIME` |
| Stale non-stream detection | 90s | Auto-disabled when left implicit | `providers.<id>.stale_timeout_seconds` or `HERMES_API_CALL_STALE_TIMEOUT` |
| Responses first-event watchdog | 120s | Raised to the 900s ceiling (`agent.local_stream_stale_timeout`) | `HERMES_CODEX_TTFB_TIMEOUT_SECONDS` |
| API call (non-streaming) | 1800s | Unchanged | `providers.<id>.request_timeout_seconds` / `timeout_seconds` or `HERMES_API_TIMEOUT` |
@@ -1379,6 +1380,8 @@ The **stale stream detection** kills connections that receive SSE keep-alive pin
The **Responses first-event watchdog** (Codex / `codex_responses` transport, including custom providers declared with the Responses transport) aborts and reconnects a request that accepts the connection but emits no stream event within 120 seconds. A local server prefilling a large context legitimately stays silent longer than that, so on local endpoints the implicit default is raised to the same ceiling as the stale stream detector (`agent.local_stream_stale_timeout` / `HERMES_LOCAL_STREAM_STALE_TIMEOUT`, 900s). An explicit `HERMES_CODEX_TTFB_TIMEOUT_SECONDS` is always used as-is (`0` disables the watchdog).
+The **stream max lifetime** is an opt-in cap on the total wall-clock time of one streaming response. The stale detector resets on every chunk, so a stream that keeps sending data but never finishes (a gateway trickling chunks, a runaway generation) is never cut. Set `agent.stream_max_lifetime` (seconds) to cut such a stream; the connection is killed the same way a stale kill is, and the retry or partial-response continuation takes over. It never fires before the effective stale-stream timeout. Leave it at `0` (the default) if you run long reasoning turns that legitimately stream for a long time.
+
The **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.