The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): the first-token window honours providers.<id>.stale_timeout_seconds
Teknium1e866e34bf82
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 9e0cabefe1d..8728a4377a9 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -2631,8 +2631,11 @@ def _relay_sync_completion(kwargs = prepare_chat_messages(client, kwargs)# The progress hook is installed per TASK, so every attempt (retries, recovery rungs, fallbacks)# must stream through _create_with_progress or the compression watchdog sees silence (#98466).- # Recovery rungs / credential retries keep the task's ``no_progress_timeout`` window.- task = (_RELAY_AUX_CALL_CONTEXT.get() or {}).get("task")+ # Recovery rungs / credential retries keep the task's ``no_progress_timeout`` window; the+ # first-token window uses this attempt's provider (fallbacks name theirs) for its stale timeout.+ relay_context = _RELAY_AUX_CALL_CONTEXT.get() or {}+ task = relay_context.get("task")+ relay_context["stream_provider"] = provider or relay_context.get("provider")callback = create or (lambda request: _create_with_progress(client, request, task))route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode)# Isolate only the provider callback so the owning thread can unwind its lease/DBdiff --git a/agent/auxiliary_stream_watchdog.py b/agent/auxiliary_stream_watchdog.pyindex 5f5f3a5d815..bc25a1e1e77 100644--- a/agent/auxiliary_stream_watchdog.py+++ b/agent/auxiliary_stream_watchdog.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport inspectimport threadingimport time+from types import SimpleNamespacefrom typing import Any, Optional@@ -134,16 +135,20 @@ class ChatStreamWatchdog:def chat_stream_windows(client: Any, kwargs: dict, task: Optional[str]) -> "tuple[float, Optional[float]]":"""(inter-chunk window, first-token window) for a streamed chat-completions attempt. Betweenchunks: the Codex guard's window (``auxiliary.<task>.no_progress_timeout``, 60s default). Before- the first token: the main loop's cloud stale patience (context-scaled, reasoning-model floor), so+ the first token: the main loop's cloud stale patience for the routed provider (its explicit+ ``providers.<id>.stale_timeout_seconds``, else context-scaled with the reasoning-model floor), soa model thinking silently on a large prompt is not cut; local servers keep their silent prefillon the request timeout (None). Both are capped at the request timeout."""- from agent.auxiliary_client import _AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS, _get_task_no_progress_timeout- from agent.chat_completion_helpers import _cloud_stale_timeout, _stream_env_stale_base+ from agent.auxiliary_client import (+ _AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDS, _RELAY_AUX_CALL_CONTEXT, _get_task_no_progress_timeout)+ from agent.chat_completion_helpers import _cloud_stale_timeout_forfrom agent.model_metadata import is_local_endpointwindow = _get_task_no_progress_timeout(task or "") or _AUX_STREAM_NO_PROGRESS_TIMEOUT_SECONDSfirst = Noneif not is_local_endpoint(str(getattr(client, "base_url", "") or "")):- first = max(window, _cloud_stale_timeout(_stream_env_stale_base()[0], kwargs))+ route = SimpleNamespace(provider=(_RELAY_AUX_CALL_CONTEXT.get() or {}).get("stream_provider") or "",+ model=kwargs.get("model"))+ first = max(window, _cloud_stale_timeout_for(route, kwargs))timeout = kwargs.get("timeout")if isinstance(timeout, (int, float)) and timeout > 0:window = min(window, float(timeout))diff --git a/tests/agent/test_aux_progress_streaming.py b/tests/agent/test_aux_progress_streaming.pyindex 0e796e97879..94b063d4010 100644--- a/tests/agent/test_aux_progress_streaming.py+++ b/tests/agent/test_aux_progress_streaming.py@@ -296,7 +296,7 @@ class TestAggregateChatStream:self.end_headers()self.wfile.flush()try:- if script == "openai/o3": # silent reasoning before the first token+ if script in ("openai/o3", "slow"): # silent reasoning before the first tokentime.sleep(2.0)if script == "b":gates["b_started"].set()@@ -332,14 +332,14 @@ class TestAggregateChatStream:monkeypatch.setattr("agent.model_metadata.is_local_endpoint", lambda _url: False)client = openai.OpenAI(api_key="k", base_url=f"http://127.0.0.1:{server.server_port}/v1", max_retries=0)- def call(model, task, *, via_relay_seam=False):+ def call(model, task, *, via_relay_seam=False, provider=None):from agent.auxiliary_client import _relay_aux_call_scope, _relay_sync_completionrequest = {"model": model, "messages": [], "timeout": 20.0}with aux_progress_hook(lambda: None):if via_relay_seam: # a recovery rung / credential retry: the default relay callbackwith _relay_aux_call_scope((task,), {}):- return _relay_sync_completion(client, request)+ return _relay_sync_completion(client, request, provider=provider)return _create_with_progress(client, request, task)try:@@ -365,11 +365,12 @@ class TestAggregateChatStream:assert "stalled: no new output for 0.4s" in str(excinfo.value)assert _should_skip_same_provider_retry("compression", excinfo.value)- @pytest.mark.parametrize("case", ["reasoning_before_first_token", "stall_after_terminal_usage",- "late_timer_after_pool_reuse"])- def test_watchdog_only_cuts_its_own_unfinished_stream(self, sse, case):- """The no-progress watchdog must not cut (a) a reasoning model thinking silently before its- first token for 5x the inter-chunk window (main-loop reasoning floor applies), (b) a response+ @pytest.mark.parametrize("case", ["reasoning_before_first_token", "provider_stale_timeout_before_first_token",+ "stall_after_terminal_usage", "late_timer_after_pool_reuse"])+ def test_watchdog_only_cuts_its_own_unfinished_stream(self, sse, case, monkeypatch):+ """The no-progress watchdog must not cut (a) a model thinking silently before its first token+ for 5x the inter-chunk window (main-loop reasoning floor, or the routed provider's explicit+ ``providers.<id>.stale_timeout_seconds`` over a shorter env stale timeout), (b) a responsewhose terminal chunk and billed usage already arrived, nor (c) a later request that reusedthe keepalive connection after a stalled attempt's timer had already woken."""gates, call = sse@@ -377,6 +378,14 @@ class TestAggregateChatStream:gates["release"].set() # the stream ends right after its first chunkassert call("openai/o3", "compression").choices[0].message.content == "partial"return+ if case == "provider_stale_timeout_before_first_token":+ gates["release"].set()+ monkeypatch.setenv("HERMES_STREAM_STALE_TIMEOUT", "0.5")+ monkeypatch.setattr("hermes_cli.config.load_config_readonly",+ lambda: {"providers": {"openrouter": {"stale_timeout_seconds": 900}}})+ result = call("slow", "compression", via_relay_seam=True, provider="openrouter")+ assert result.choices[0].message.content == "partial"+ returnif case == "stall_after_terminal_usage":result = call("usage", "compression")assert result.choices[0].message.content == "partial"diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 8517d75731e..f6abb7aca02 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1104,7 +1104,7 @@ Points at a custom OpenAI-compatible endpoint. Uses `OPENAI_API_KEY` for auth.When the summary streams (compression always streams over chat-completions and Responses routes, e.g. `openai-codex` or a custom OpenAI-compatible endpoint), two timeouts apply, and they are independent:- `auxiliary.compression.timeout` — the overall request budget (default 120s).-- `auxiliary.compression.no_progress_timeout` — how long the stream may go without a **substantive** event (a text/reasoning delta or a completed output item) before the attempt aborts (`... stream stalled: no new output for Ns`) and the normal retry / fallback chain takes over. Default **60s** when unset. On a chat-completions stream the window starts at the first token. Before it, a remote endpoint gets the main loop's stale patience (180s, raised for large prompts and to 600s for reasoning models such as o3 or DeepSeek R1, capped at `timeout`), so a model thinking silently is not cut. On a local endpoint (localhost, LAN, Tailscale) a silent prefill is bounded only by `timeout`. The same rule applies to every streamed auxiliary task, including MoA reference calls. Keepalive and lifecycle frames (`response.in_progress`, pings) do not count as progress; every substantive event re-arms the window, so a slow but progressing summary is never cut off by it.+- `auxiliary.compression.no_progress_timeout` — how long the stream may go without a **substantive** event (a text/reasoning delta or a completed output item) before the attempt aborts (`... stream stalled: no new output for Ns`) and the normal retry / fallback chain takes over. Default **60s** when unset. On a chat-completions stream the window starts at the first token. Before it, a remote endpoint gets the main loop's stale patience (the provider's `providers.<id>.stale_timeout_seconds` when set, else 180s raised for large prompts and to 600s for reasoning models such as o3 or DeepSeek R1; capped at `timeout`), so a model thinking silently is not cut. On a local endpoint (localhost, LAN, Tailscale) a silent prefill is bounded only by `timeout`. The same rule applies to every streamed auxiliary task, including MoA reference calls. Keepalive and lifecycle frames (`response.in_progress`, pings) do not count as progress; every substantive event re-arms the window, so a slow but progressing summary is never cut off by it.Raising `timeout` alone does **not** widen the progress window — a request configured for 600s still aborts after a 60s gap. Set `no_progress_timeout` to change that gap; the effective window is capped at `timeout`, and the host's hard deadline / cancellation still win. The host's own inactivity budget is the outer cap here: in-agent compaction gives up on a silent summariser after `compression.context_timeout_seconds` (default 120s, floored at the effective `auxiliary.compression.timeout`, itself at least 300s) and gateway hygiene after `compression.hygiene_timeout_seconds` (default 30s), so a `no_progress_timeout` larger than the applicable host budget is silently cut short by it. The key is per task (`auxiliary.<task>.no_progress_timeout`), so widening it for compression does not change other auxiliary tasks. A value that is not a positive number is ignored with a warning in the log and the 60s default applies.