The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): iteration-progress formatter lives in agent/session_activity, tests trimmed to the invariant bar
Teknium62f353eed56c
diff --git a/agent/session_activity.py b/agent/session_activity.pyindex ddd04c3ab71..1ab19ef9784 100644--- a/agent/session_activity.py+++ b/agent/session_activity.py@@ -4,6 +4,7 @@ only (notification, timeout, kill and retry policy live elsewhere). Provenance ifrom __future__ import annotations+import sysimport timefrom contextlib import suppressfrom enum import Enum@@ -45,6 +46,21 @@ def normalize_activity_provenance(provenance: Optional[ActivityProvenance | str]return ActivityProvenance.UNKNOWN+def format_iteration_progress(api_call_count: Any, max_iterations: Any) -> str:+ """``iteration N/M`` for user-facing status lines, or ``iteration N`` when the cap is unbounded.++ ``AIAgent.max_iterations`` defaults to ``sys.maxsize`` (unlimited), so printing the pair verbatim+ shows ``iteration 3/9223372036854775807`` in busy acks, heartbeats and timeout diagnostics (#102806).+ """+ try:+ cap = int(max_iterations)+ except (TypeError, ValueError):+ cap = sys.maxsize+ if cap >= sys.maxsize:+ return f"iteration {api_call_count}"+ return f"iteration {api_call_count}/{cap}"++def reset_session_activity_persist_window(agent: Any) -> None:"""Clear the persist rate-limit so the next stamp writes through (terminal compression labels must not stick on mid-compress text)."""with suppress(Exception):diff --git a/evals/gateway_status_render/iteration_ceiling_ab.py b/evals/gateway_status_render/iteration_ceiling_ab.pynew file mode 100644index 00000000000..8c4dabcb067--- /dev/null+++ b/evals/gateway_status_render/iteration_ceiling_ab.py@@ -0,0 +1,115 @@+"""A/B probe: what the three user-facing gateway status lines render for the iteration counter.++Drives the REAL render paths (busy-ack, long-running heartbeat, inactivity-timeout diagnostic)+with a REAL ``AIAgent`` constructed with its default (unlimited) ``max_iterations`` and a+stub adapter that records the outbound text. Run on origin/main and on the fix branch:++ HERMES_HOME=$(mktemp -d) python evals/gateway_status_render/iteration_ceiling_ab.py [--finite 250]++Prints one JSON object per render site with the exact text a user would see.+"""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import sys+import time+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMock+++def _agent(max_iterations: int | None):+ from run_agent import AIAgent++ kwargs: dict[str, Any] = dict(base_url="http://127.0.0.1:9/v1", api_key="sk-dummy", model="dummy-model",+ quiet_mode=True, enabled_toolsets=[], disabled_toolsets=["*"])+ if max_iterations is not None:+ kwargs["max_iterations"] = max_iterations+ agent = AIAgent(**kwargs)+ agent._api_call_count = 3+ agent._current_tool = "terminal"+ agent._last_activity_desc = "terminal"+ agent._last_activity_ts = time.time() - 42+ return agent+++async def _busy_ack(agent) -> str:+ import gateway.run as gr+ from gateway.platforms.base import MessageEvent, MessageType, SessionSource, build_session_key++ gr._load_gateway_config = lambda: {"display": {"platforms": {"telegram": {"busy_ack_detail": True}}}}+ runner = object.__new__(gr.GatewayRunner)+ runner._running_agents, runner._running_agents_ts = {}, {}+ runner._pending_messages, runner._busy_ack_ts, runner._queued_events = {}, {}, {}+ runner._draining, runner._busy_text_mode, runner._busy_input_mode = False, "interrupt", "interrupt"+ runner.adapters, runner.config, runner.session_store = {}, MagicMock(), None+ runner.config.group_sessions_per_user, runner.config.thread_sessions_per_user = True, False+ runner.hooks = MagicMock(); runner.hooks.emit = AsyncMock()+ runner.pairing_store = MagicMock(); runner.pairing_store.is_approved.return_value = True+ runner._is_user_authorized = lambda _s: True+ source = SessionSource(platform=MagicMock(value="telegram"), chat_id="123", chat_type="private", user_id="u1")+ event = MessageEvent(text="status?", message_type=MessageType.TEXT, source=source, message_id="m1")+ sk = build_session_key(source)+ adapter = MagicMock()+ adapter._pending_messages, adapter._text_debounce, adapter._busy_text_debounce_seconds = {}, {}, 0.6+ adapter._send_with_retry = AsyncMock()+ adapter.config = MagicMock(); adapter.config.extra = {}+ adapter.platform = MagicMock(value="telegram")+ runner._running_agents[sk] = agent+ runner._running_agents_ts[sk] = time.time() - 600+ runner.adapters[source.platform] = adapter+ await runner._handle_active_session_busy_message(event, sk)+ return adapter._send_with_retry.call_args.kwargs.get("content", "")+++async def _heartbeat(agent) -> str:+ from gateway.run_turn import GatewayTurnMixin+ from gateway.turn_context import TurnContext++ os.environ["HERMES_AGENT_NOTIFY_INTERVAL"] = "0.01"+ mixin = GatewayTurnMixin()+ adapter = MagicMock()+ adapter.send = AsyncMock(return_value=SimpleNamespace(success=True, message_id="hb1"))+ mixin._adapter_for_source = MagicMock(return_value=adapter)+ mixin._should_emit_long_running_notification = MagicMock(side_effect=[True, False])+ disp = MagicMock()+ disp._display_surface_mode.return_value = "on"+ disp.resolve_display_setting.return_value = True+ ctx = TurnContext(source=SimpleNamespace(chat_id="c1", platform="telegram"), session_key="s1", agent_holder=[agent])+ await mixin._run_agent_notify_long_running(disp, ctx, [None])+ return adapter.send.await_args.args[1]+++def _timeout(agent) -> str:+ import gateway.run as gr+ from gateway.run_turn import GatewayTurnMixin+ from gateway.turn_context import TurnContext++ gr.request_hard_interrupt = MagicMock()+ ctx = TurnContext(session_key="s1", agent_holder=[agent])+ return GatewayTurnMixin()._run_agent_timeout_result(SimpleNamespace(agent_timeout=1800.0), ctx)["final_response"]+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("--finite", type=int, default=None, help="use a finite max_iterations instead of the default")+ args = ap.parse_args()+ sys.path.insert(0, os.getcwd())+ agent = _agent(args.finite)+ out = {+ "head": os.popen("git rev-parse --short HEAD").read().strip(),+ "max_iterations": agent.max_iterations,+ "busy_ack": asyncio.run(_busy_ack(agent)),+ "heartbeat": asyncio.run(_heartbeat(agent)),+ "timeout_diag": _timeout(agent),+ }+ out["sentinel_leaks"] = sum(str(sys.maxsize) in v for k, v in out.items() if k in ("busy_ack", "heartbeat", "timeout_diag"))+ print(json.dumps(out, indent=2, ensure_ascii=False))+++if __name__ == "__main__":+ main()diff --git a/gateway/run.py b/gateway/run.pyindex 31f19f2e73e..0a62103a777 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -940,32 +940,6 @@ def _float_env(name: str, default: float) -> float:return float(default)-def _format_iteration_progress(api_call_count: Any, max_iterations: Any) -> str:- """Render an ``iteration N/M`` status fragment for a running turn.-- Shared by every user-facing status line that formats- ``AIAgent.get_activity_summary()``'s ``api_call_count`` / ``max_iterations`` pair: the- long-running heartbeat (``run_turn._run_agent_notify_long_running``), the busy-session- acknowledgment (``run_busy._handle_active_session_busy_message``), and the- gateway-timeout diagnostic message (``run_turn._run_agent_timeout_result``).-- ``AIAgent.max_iterations`` defaults to ``sys.maxsize`` (unlimited tool-calling- iterations — see ``run_agent.py``), so a top-level session almost never has a real- ceiling. Printing that default verbatim renders the literal ``9223372036854775807`` in- a user-facing status line, which reads as a bug rather than "unbounded" (#102806). Omit- the denominator once the configured ceiling is at or above that sentinel; a genuinely- finite budget (e.g. a subagent's ``delegation.max_iterations: 250``) still prints both- numbers.- """- try:- _max = int(max_iterations)- except (TypeError, ValueError):- _max = None- if _max is None or _max >= sys.maxsize:- return f"iteration {api_call_count}"- return f"iteration {api_call_count}/{_max}"--def _stamp_hygiene_compression_provenance(agent: Any, desc: str, provenance: "ActivityProvenance", debug_label: str) -> None:"""Best-effort activity provenance stamp for hygiene compression transitions."""diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex c3b75703b5b..0154fe28052 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -15,6 +15,7 @@ import jsonimport osimport timefrom agent.i18n import t+from agent.session_activity import format_iteration_progressfrom gateway.config import Platformfrom gateway.platforms.base import EphemeralReply, MessageEvent, MessageTypefrom gateway.session import SessionSource@@ -534,8 +535,7 @@ class GatewayBusySessionMixin:demoted_for_subagents: bool, demoted_for_compression: bool,) -> str:from gateway.run import (- _AGENT_PENDING_SENTINEL, _format_iteration_progress, _hermes_home,- _load_gateway_config, _platform_config_key,+ _AGENT_PENDING_SENTINEL, _hermes_home, _load_gateway_config, _platform_config_key)from gateway.display_config import resolve_display_setting@@ -557,7 +557,7 @@ class GatewayBusySessionMixin:status_parts.append(f"{elapsed_min} min elapsed")if summary.get("max_iterations", 0):status_parts.append(- _format_iteration_progress(+ format_iteration_progress(summary.get("api_call_count", 0), summary.get("max_iterations", 0)))diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex d5f5aacd428..53684bf60e2 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -16,6 +16,7 @@ import queueimport threadingimport timefrom agent.i18n import t+from agent.session_activity import format_iteration_progressfrom contextlib import nullcontext, suppressfrom contextvars import copy_contextfrom gateway.config import Platform@@ -3156,9 +3157,7 @@ class GatewayTurnMixin:def _run_agent_timeout_result(self, worker, turn_ctx: TurnContext) -> dict:"""Synthetic failed run dict for an inactivity timeout, with the activity-tracker diagnostic;interrupts the agent if it is still running so the thread pool worker is freed."""- from gateway.run import (- _INTERRUPT_REASON_TIMEOUT, _format_iteration_progress, request_hard_interrupt,- )+ from gateway.run import _INTERRUPT_REASON_TIMEOUT, request_hard_interruptsession_key, result_holder, tools_holder = turn_ctx.session_key, turn_ctx.result_holder, turn_ctx.tools_holder_timed_out_agent = turn_ctx.agent_holder[0]_activity = self._agent_activity_summary(_timed_out_agent)@@ -3167,8 +3166,7 @@ class GatewayTurnMixin:_cur_tool = _activity.get("current_tool")_iter_n = _activity.get("api_call_count", 0)_iter_max = _activity.get("max_iterations", 0)- # Operator-facing log keeps the raw resolved value for diagnostics; only the two- # user-facing _diag_lines below go through _format_iteration_progress (#102806).+ # Operator-facing log keeps the raw resolved value; only the user-facing lines hide the sentinel.logger.error("Agent idle for %.0fs (timeout %.0fs) in session %s ""| last_activity=%s | iteration=%s/%s | tool=%s",@@ -3178,7 +3176,7 @@ class GatewayTurnMixin:if _timed_out_agent:request_hard_interrupt(_timed_out_agent, _INTERRUPT_REASON_TIMEOUT)_timeout_mins = int(worker.agent_timeout // 60) or 1- _iter_progress = _format_iteration_progress(_iter_n, _iter_max)+ _iter_progress = format_iteration_progress(_iter_n, _iter_max)_diag_lines = [f"⏱️ Agent inactive for {_timeout_mins} min — no tool calls or API responses."]@@ -3716,9 +3714,7 @@ class GatewayTurnMixin:Interval: agent.gateway_notify_interval / HERMES_AGENT_NOTIFY_INTERVAL (default 180s; 0 orlong_running_notifications=off disables)."""- from gateway.run import (- _float_env, _format_iteration_progress, _interim_metadata, _non_conversational_metadata,- )+ from gateway.run import _float_env, _interim_metadata, _non_conversational_metadata_notify_start = time.time()_NOTIFY_INTERVAL = _float_env("HERMES_AGENT_NOTIFY_INTERVAL", 180)_long_running_mode = disp._display_surface_mode("long_running_notifications", default=True, allow_generic=True)@@ -3747,9 +3743,7 @@ class GatewayTurnMixin:if _a:_parts = []if _want_iteration_detail:- _parts.append(- _format_iteration_progress(_a["api_call_count"], _a["max_iterations"])- )+ _parts.append(format_iteration_progress(_a["api_call_count"], _a["max_iterations"]))_action = _a.get("current_tool") or _a.get("last_activity_desc")if _action:_parts.append(str(_action))diff --git a/tests/agent/test_session_activity.py b/tests/agent/test_session_activity.pyindex 7d6726a0f1e..0a67442e4c3 100644--- a/tests/agent/test_session_activity.py+++ b/tests/agent/test_session_activity.py@@ -1,17 +1,35 @@"""Unit tests for the shared session activity observation contract."""+import sysfrom types import SimpleNamespace+import pytest+from agent.session_activity import (ACTIVITY_DESCRIPTION_MAX,ActivityProvenance,bound_activity_description,build_activity_snapshot,+ format_iteration_progress,normalize_activity_provenance,reset_session_activity_persist_window,)+ "max_iterations, expected",+ [+ (sys.maxsize, "iteration 3"), # AIAgent's default: unbounded, so no ceiling is shown+ (None, "iteration 3"),+ (250, "iteration 3/250"), # a real budget (e.g. delegation.max_iterations) keeps N/M+ ],+)+def test_format_iteration_progress_hides_unbounded_ceiling(max_iterations, expected):+ out = format_iteration_progress(3, max_iterations)+ assert out == expected+ assert str(sys.maxsize) not in out++def test_bound_activity_description_truncates():long = "x" * (ACTIVITY_DESCRIPTION_MAX + 80)out = bound_activity_description(long)diff --git a/tests/gateway/test_format_iteration_progress.py b/tests/gateway/test_format_iteration_progress.pydeleted file mode 100644index bad9c20b39b..00000000000--- a/tests/gateway/test_format_iteration_progress.py+++ /dev/null@@ -1,47 +0,0 @@-"""Unit tests for gateway.run._format_iteration_progress (#102806).--``AIAgent.max_iterations`` defaults to ``sys.maxsize`` (unlimited-tool-calling iterations for a top-level session — see ``run_agent.py``).-Three user-facing gateway status lines render ``iteration N/M`` from-``AIAgent.get_activity_summary()``'s ``api_call_count`` / ``max_iterations``-pair: the long-running heartbeat, the busy-session acknowledgment, and the-gateway-timeout diagnostic message. All three share this helper; see-``test_busy_session_ack.py`` and ``test_gateway_timeout_iteration_progress.py``-for the call sites' own end-to-end regression tests.-"""--import sys--from gateway.run import _format_iteration_progress---class TestFormatIterationProgress:- def test_unbounded_default_omits_denominator(self):- """sys.maxsize (AIAgent's actual default) prints iteration count alone."""- assert _format_iteration_progress(2, sys.maxsize) == "iteration 2"-- def test_above_sys_maxsize_also_omits_denominator(self):- """Anything at or beyond the sentinel is treated as unbounded too."""- assert _format_iteration_progress(5, sys.maxsize + 1) == "iteration 5"-- def test_finite_budget_still_shows_both_numbers(self):- """A real, finite ceiling (e.g. a subagent's max_iterations: 250)- keeps the existing N/M format — this is not a blanket format change."""- assert _format_iteration_progress(7, 250) == "iteration 7/250"-- def test_small_finite_budget(self):- assert _format_iteration_progress(0, 90) == "iteration 0/90"-- def test_non_numeric_max_iterations_falls_back_to_unbounded_rendering(self):- """get_activity_summary() is a best-effort diagnostics snapshot; a- malformed/missing max_iterations must not raise inside a status-line- formatter (call sites wrap this in try/except, but the helper itself- should degrade gracefully rather than propagate a TypeError)."""- assert _format_iteration_progress(3, None) == "iteration 3"- assert _format_iteration_progress(3, "not-a-number") == "iteration 3"-- def test_api_call_count_is_rendered_verbatim(self):- """Only the denominator's unbounded-ness is special-cased; the- numerator (api_call_count) always prints as given."""- assert _format_iteration_progress(123, 250) == "iteration 123/250"- assert _format_iteration_progress(123, sys.maxsize) == "iteration 123"diff --git a/tests/gateway/test_gateway_timeout_iteration_progress.py b/tests/gateway/test_gateway_timeout_iteration_progress.pydeleted file mode 100644index 5cf5f590ad2..00000000000--- a/tests/gateway/test_gateway_timeout_iteration_progress.py+++ /dev/null@@ -1,116 +0,0 @@-"""#102806: the gateway inactivity-timeout diagnostic message and the-long-running heartbeat -- the two remaining user-facing render sites-alongside the busy-ack (see test_busy_session_ack.py) -- must not print-sys.maxsize as an iteration ceiling either.--``_run_agent_timeout_result`` builds the synthetic ``final_response`` shown-to the user when an agent run is force-timed-out for inactivity. It embeds-``iteration N/M`` twice (the "stuck on tool" branch and the "last activity"-branch). ``_run_agent_notify_long_running`` embeds it once, in the periodic-"still working" heartbeat. All three call sites (this file's two classes,-plus test_busy_session_ack.py's busy-ack test) share the same-``_format_iteration_progress`` helper; see test_format_iteration_progress.py-for the helper's own unit tests.-"""--from __future__ import annotations--import sys-from types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock--import pytest--from gateway.run_turn import GatewayTurnMixin-from gateway.turn_context import TurnContext---def _make_worker(agent_timeout=1800.0):- return SimpleNamespace(agent_timeout=agent_timeout)---def _make_turn_ctx(agent):- return TurnContext(session_key="sess-1", agent_holder=[agent])---class TestTimeoutDiagnosticIterationProgress:- def test_unbounded_max_iterations_omits_denominator_when_stuck_on_tool(self, monkeypatch):- mixin = GatewayTurnMixin()- monkeypatch.setattr("gateway.run.request_hard_interrupt", MagicMock(), raising=False)- agent = MagicMock()- agent.get_activity_summary.return_value = {- "last_activity_desc": "tool_call",- "seconds_since_activity": 42.0,- "current_tool": "terminal",- "api_call_count": 5,- "max_iterations": sys.maxsize,- }- result = mixin._run_agent_timeout_result(_make_worker(), _make_turn_ctx(agent))- assert "iteration 5" in result["final_response"]- assert str(sys.maxsize) not in result["final_response"]-- def test_unbounded_max_iterations_omits_denominator_in_last_activity_branch(self, monkeypatch):- mixin = GatewayTurnMixin()- monkeypatch.setattr("gateway.run.request_hard_interrupt", MagicMock(), raising=False)- agent = MagicMock()- agent.get_activity_summary.return_value = {- "last_activity_desc": "api_call_streaming",- "seconds_since_activity": 12.0,- "current_tool": None,- "api_call_count": 2,- "max_iterations": sys.maxsize,- }- result = mixin._run_agent_timeout_result(_make_worker(), _make_turn_ctx(agent))- assert "iteration 2" in result["final_response"]- assert str(sys.maxsize) not in result["final_response"]-- def test_finite_max_iterations_still_shows_both_numbers(self, monkeypatch):- mixin = GatewayTurnMixin()- monkeypatch.setattr("gateway.run.request_hard_interrupt", MagicMock(), raising=False)- agent = MagicMock()- agent.get_activity_summary.return_value = {- "last_activity_desc": "tool_call",- "seconds_since_activity": 5.0,- "current_tool": "code_exec",- "api_call_count": 7,- "max_iterations": 250,- }- result = mixin._run_agent_timeout_result(_make_worker(), _make_turn_ctx(agent))- assert "iteration 7/250" in result["final_response"]---class TestLongRunningHeartbeatIterationProgress:- """The heartbeat's own render call, exercised end to end through its- async polling loop (one iteration, then the loop is told to stop)."""-- @pytest.mark.asyncio- async def test_heartbeat_omits_denominator_for_unbounded_max_iterations(self, monkeypatch):- monkeypatch.setenv("HERMES_AGENT_NOTIFY_INTERVAL", "0.01")-- mixin = GatewayTurnMixin()- adapter = MagicMock()- adapter.send = AsyncMock(return_value=SimpleNamespace(success=True, message_id="m1"))- mixin._adapter_for_source = MagicMock(return_value=adapter)- mixin._should_emit_long_running_notification = MagicMock(side_effect=[True, False])-- agent = MagicMock()- agent.get_activity_summary.return_value = {- "api_call_count": 4,- "max_iterations": sys.maxsize,- "current_tool": "terminal",- }-- disp = MagicMock()- disp._display_surface_mode.return_value = "on"- disp.resolve_display_setting.return_value = True-- turn_ctx = TurnContext(- source=SimpleNamespace(chat_id="c1", platform="telegram"),- session_key="sess-1", agent_holder=[agent],- )-- await mixin._run_agent_notify_long_running(disp, turn_ctx, [None])-- sent_text = adapter.send.await_args.args[1]- assert "iteration 4" in sent_text- assert str(sys.maxsize) not in sent_text