The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/F_guard_stream): drop redundant outer try in flush, Counter line-repeat, compact module docstrings
Teknium1677fb58819b
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.pyindex ea6f1e27326..e2aa371a27c 100644--- a/agent/repetition_guard.py+++ b/agent/repetition_guard.py@@ -1,17 +1,16 @@"""Cheap content-sanity checks for the truncated-response continuation path.-A model in a degenerate repetition loop can spend its ENTIRE output budget echoing one-fragment; the ``finish_reason=length`` continuation path would then stitch that fragment-into the final response with a "continue" nudge (one incident: a 60k-char turn delivered-as 31 Discord messages). These helpers detect repetition-dominated fragments BEFORE the-nudge so the turn aborts with a clear error. Deliberately conservative: only LONG verbatim-repeats (60+ chars) covering a majority of the fragment trip the guard, so ordinary-truncations (a sentence cut mid-word, a repeated heading, similar code lines) never do.+A model in a degenerate repetition loop can spend its ENTIRE output budget echoing one fragment;+the ``finish_reason=length`` continuation would then stitch it into the final response with a+"continue" nudge (one incident: a 60k-char turn delivered as 31 Discord messages). This detects+repetition-dominated fragments BEFORE the nudge so the turn aborts with a clear error. Deliberately+conservative: only LONG verbatim repeats (60+ chars) covering a majority of the fragment trip it."""from __future__ import annotationsimport math+from collections import Counter# Below this length the check doesn't run: short truncations trivially# contain repeated tokens and are legitimately continued.@@ -54,12 +53,5 @@ def is_repetition_dominated(text: str) -> bool:def _line_repetition_dominated(text: str, n: int) -> bool:"""True when a single normalized line covers half the fragment via repeats."""- counts: dict[str, int] = {}- for line in text.splitlines():- norm = line.strip()- if norm:- counts[norm] = counts.get(norm, 0) + 1- return any(- c >= _MIN_REPEAT_COUNT and c * len(line) >= n * _DOMINANCE_RATIO- for line, c in counts.items()- )+ counts = Counter(norm for norm in (line.strip() for line in text.splitlines()) if norm)+ return any(c >= _MIN_REPEAT_COUNT and c * len(line) >= n * _DOMINANCE_RATIO for line, c in counts.items())diff --git a/agent/status_output.py b/agent/status_output.pyindex c96523f60a3..69c4b2ddc16 100644--- a/agent/status_output.py+++ b/agent/status_output.py@@ -168,23 +168,20 @@ class StatusOutputMixin:def _flush_status_buffer(self) -> None:"""Emit buffered retry messages — call on terminal failure so the user sees what was tried."""- try:- # The buffered trace already carries the switch line; drop the one-shot notice.- self._pending_fallback_notice = None- buf = getattr(self, "_retry_status_buffer", None)- if not buf:- return- # Drain first so a callback exception doesn't double-emit.- messages = list(buf)- buf.clear()- replay = {"status": self._emit_status, "warn": self._emit_warning}- for kind, msg in messages:- try:- if kind in replay:- replay[kind](msg)- else:- self._vprint(f"{self.log_prefix}{msg}", force=True)- except Exception:- pass- except Exception:- pass+ # The buffered trace already carries the switch line; drop the one-shot notice.+ self._pending_fallback_notice = None+ buf = getattr(self, "_retry_status_buffer", None)+ if not buf:+ return+ # Drain first so a callback exception doesn't double-emit.+ messages = list(buf)+ buf.clear()+ replay = {"status": self._emit_status, "warn": self._emit_warning}+ for kind, msg in messages:+ try:+ if kind in replay:+ replay[kind](msg)+ else:+ self._vprint(f"{self.log_prefix}{msg}", force=True)+ except Exception:+ passdiff --git a/agent/stream_delivery.py b/agent/stream_delivery.pyindex ab2b7752e59..d1aa8034d6a 100644--- a/agent/stream_delivery.py+++ b/agent/stream_delivery.py@@ -19,8 +19,6 @@ logger = logging.getLogger("run_agent")class StreamDeliveryMixin:"""Stream ownership, delta/reasoning hook fan-out and interim-text dedup (see module docstring)."""- # ── stream text delivery ──-@staticmethoddef _call_quietly(cb, *args) -> bool:"""Call ``cb(*args)`` if set, swallowing errors; True when it ran without raising."""@@ -72,8 +70,6 @@ class StreamDeliveryMixin:if isinstance(text, str) and text and not self._stream_writer_superseded():self._current_streamed_assistant_text = getattr(self, "_current_streamed_assistant_text", "") + text- # ── interim assistant text ──-@staticmethoddef _normalize_interim_visible_text(text: str) -> str:return re.sub(r"\s+", " ", text).strip() if isinstance(text, str) else ""@@ -194,8 +190,6 @@ class StreamDeliveryMixin:self._enqueue_stream_hook("on_interim_message", text=visible, already_streamed=already_streamed)self._deliver_interim(visible, already_streamed=already_streamed, record=undelivered_parts or [visible])- # ── single-writer stream fence ──-def _ensure_stream_writer_state(self) -> None:"""Lazily create the single-writer guard fields (``AIAgent.__new__``-built instances skip ``agent_init``)."""if getattr(self, "_stream_writer_lock", None) is None:@@ -244,8 +238,6 @@ class StreamDeliveryMixin:where, _n,)- # ── hook fan-out ──-def _stream_hook_base_payload(self) -> Dict[str, Any]:return {"turn_id": getattr(self, "_current_turn_id", "") or "",diff --git a/agent/stream_single_writer.py b/agent/stream_single_writer.pyindex e59ca78e26f..67fc06220a6 100644--- a/agent/stream_single_writer.py+++ b/agent/stream_single_writer.py@@ -1,11 +1,10 @@"""Best-effort accessors for the single-writer stream fence.-The fence lives on ``AIAgent`` (``_claim_stream_writer`` / ``_stream_writer_is_current``)-but is used from other streaming modules. Calling it directly would turn an *additive*-safety net into a fatal AttributeError on a partially-updated checkout, hot-reloaded-gateway, duck-typed agent, or test double (a cron job died this way). The fence may only-drop a *provably* superseded stream, never the sole writer, so when it is unavailable or-raises the correct degradation is "no fence": keep streaming.+The fence lives on ``AIAgent`` (``_claim_stream_writer`` / ``_stream_writer_is_current``) but is+used from other streaming modules. Calling it directly would turn an *additive* safety net into a+fatal AttributeError on a partially-updated checkout, hot-reloaded gateway, duck-typed agent, or+test double (a cron job died this way). The fence may only drop a *provably* superseded stream,+never the sole writer, so when it is unavailable or raises the degradation is "no fence"."""from __future__ import annotationsdiff --git a/agent/think_scrubber.py b/agent/think_scrubber.pyindex b5ff98e1be6..e70ca2cdae6 100644--- a/agent/think_scrubber.py+++ b/agent/think_scrubber.py@@ -1,11 +1,10 @@"""Stateful scrubber for reasoning/thinking blocks in streamed assistant text.-The regex ``_strip_think_blocks`` is correct for a complete string but, run per-delta,-erases an opening ``<think>`` that arrives alone, so downstream state machines leak-reasoning. This class holds partial tags at delta boundaries until resolved; ``flush()``-releases held-back prose that was not a tag. Call ``reset()`` at the top of each turn.-Boundary rule: an open tag only starts a block at a block boundary (stream start, after a-newline, or with only whitespace on the current line), so prose that *mentions*+The regex ``_strip_think_blocks`` is correct for a complete string but, run per-delta, erases an+opening ``<think>`` that arrives alone, so downstream state machines leak reasoning. This class+holds partial tags at delta boundaries until resolved; ``flush()`` releases held-back prose that+was not a tag; ``reset()`` at the top of each turn. An open tag only starts a block at a block+boundary (stream start / after a newline / whitespace-only line so far), so prose that *mentions*``<think>`` is not suppressed; closed pairs are always suppressed (intentional)."""@@ -66,8 +65,7 @@ class StreamingThinkScrubber:close_idx, close_len = self._find_first_tag(buf, self._CLOSE_TAGS)if close_idx == -1:# No close yet: hold back a possible partial close-tag prefix, drop the rest.- held = self._max_partial_suffix(buf, self._CLOSE_TAGS)- self._buf = buf[-held:] if held else ""+ self._hold_partial(buf, self._CLOSE_TAGS)breakbuf = buf[close_idx + close_len:]self._in_block = False@@ -90,13 +88,17 @@ class StreamingThinkScrubber:# No resolvable tag: hold back any partial-tag prefix at the tail# so a tag split across deltas isn't missed, then emit the rest.- held = self._max_partial_suffix(buf, self._ALL_TAGS)- self._emit(out, buf[:-held] if held else buf)- self._buf = buf[-held:] if held else ""+ self._emit(out, self._hold_partial(buf, self._ALL_TAGS))breakreturn "".join(out)+ def _hold_partial(self, buf: str, tags: Tuple[str, ...]) -> str:+ """Move a trailing partial-tag prefix of *buf* into ``_buf``; return the remainder."""+ held = self._max_partial_suffix(buf, tags)+ self._buf = buf[-held:] if held else ""+ return buf[:-held] if held else buf+def flush(self) -> str:"""End-of-stream flush: inside an unterminated block the held-back content is discarded (leakingpartial reasoning is worse than a truncated answer), otherwise the tail is emitted verbatim.@@ -146,16 +148,12 @@ class StreamingThinkScrubber:"""True iff *idx* is a block boundary: position 0 after a newline-terminated (or no) prior emission,or any position whose preceding text on the current line is whitespace-only (when no newlineprecedes it in *buf*, the prior emission must also have ended with a newline)."""- prior_newline = (- already_emitted[-1].endswith("\n") if already_emitted else self._last_emitted_ended_newline- )+ prior_newline = already_emitted[-1].endswith("\n") if already_emitted else self._last_emitted_ended_newlineif idx == 0:return prior_newlinepreceding = buf[:idx]last_nl = preceding.rfind("\n")- if last_nl == -1:- return prior_newline and preceding.strip() == ""- return preceding[last_nl + 1:].strip() == ""+ return (prior_newline if last_nl == -1 else True) and preceding[last_nl + 1:].strip() == ""@classmethoddef _max_partial_suffix(cls, buf: str, tags: Tuple[str, ...]) -> int:@@ -170,6 +168,4 @@ class StreamingThinkScrubber:@classmethoddef _strip_orphan_close_tags(cls, text: str) -> str:"""Remove close tags with no matching open (always noise) plus trailing whitespace."""- if "</" not in text:- return text- return cls._ORPHAN_CLOSE_RE.sub("", text)+ return cls._ORPHAN_CLOSE_RE.sub("", text) if "</" in text else textdiff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.pyindex 39b1e001149..e5857d4c8ac 100644--- a/agent/tool_guardrails.py+++ b/agent/tool_guardrails.py@@ -405,11 +405,10 @@ class ToolCallGuardrailController:) -> IdenticalCallObservation:"""Track consecutive identical calls; return notice + dedupe stub info.- ``notice`` fires from the threshold-th consecutive identical (tool, args, result) call;- observational, pollers exempt. ``stub`` replaces the CURRENT result from the 2nd- byte-identical repeat — the tool still executed, only the context representation is- deduplicated, so polling semantics survive (a changed result resets the streak). Pollers- are NOT exempt from stubbing: an unchanged poll is exactly when it saves most.+ ``notice`` fires from the threshold-th consecutive identical (tool, args, result) call+ (observational, pollers exempt). ``stub`` replaces the CURRENT result from the 2nd byte-identical+ repeat — the tool still executed, only the context representation is deduplicated, so polling+ semantics survive; pollers are NOT exempt here since an unchanged poll is where it saves most."""is_plain_str = isinstance(result, str)signature = ToolCallSignature.from_call(tool_name, _coerce_args(args))@@ -477,11 +476,8 @@ class ToolCallGuardrailController:def _check_loop_cap(self, tool_name: str, args: Mapping[str, Any], signature: ToolCallSignature,) -> ToolGuardrailDecision | None:- """Block once a per-turn cap is reached, else advance the counter and return None.-- Blocking happens BEFORE the call when the count is already at the cap, so the (cap+1)-th- call is refused. delegate_task control actions spawn nothing and keep working after the cap.- """+ """Block once a per-turn cap is reached (BEFORE the call, so the (cap+1)-th is refused), else advance+ the counter and return None. delegate_task control actions spawn nothing and keep working after the cap."""spec = _LOOP_CAPS.get(tool_name)if spec is None:return None