The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/stream_delivery): unify callback fan-out and plugin hook enqueue into two helpers
Teknium53895ae69f3c
diff --git a/agent/stream_delivery.py b/agent/stream_delivery.pyindex f1388afda98..78a60fa77b7 100644--- a/agent/stream_delivery.py+++ b/agent/stream_delivery.py@@ -19,44 +19,59 @@ logger = logging.getLogger("run_agent")class StreamDeliveryMixin:"""Stream ownership, delta/reasoning hook fan-out and interim-text dedup (see module docstring)."""+ # ── stream text delivery ──++ def _deliver_to_stream_callbacks(self, text: str) -> bool:+ """Send ``text`` to the display + TTS delta callbacks; True if at least one accepted it."""+ delivered = False+ for cb in (self.stream_delta_callback, self._stream_callback):+ if cb is None:+ continue+ try:+ cb(text)+ delivered = True+ except Exception:+ pass+ return delivered++ def _enqueue_stream_hook(self, event: str, *, label: str | None = None, **fields: Any) -> None:+ """Best-effort plugin stream hook enqueue; never raises into the stream path."""+ try:+ from agent.plugin_stream_hooks import enqueue_plugin_stream_hook++ enqueue_plugin_stream_hook(event, **self._stream_hook_base_payload(), **fields)+ except Exception:+ logger.debug("%s plugin hook enqueue failed", label or event, exc_info=True)+def _reset_stream_delivery_tracking(self) -> None:- """Reset tracking for text delivered during the current model response."""- # Flush the think scrubber's benign partial-tag tail first (#17924), then the context scrubber —- # order matters, the think output feeds the context scrubber.+ """Reset tracking for text delivered during the current model response.++ Flushes the think scrubber's benign partial-tag tail first, routed through the+ context scrubber (a span straddling the boundary must still be caught), then the+ context scrubber's own tail. Mid-span, ``flush()`` drops orphaned content.+ """think_scrubber = getattr(self, "_stream_think_scrubber", None)+ ctx_scrubber = getattr(self, "_stream_context_scrubber", None)if think_scrubber is not None:think_tail = think_scrubber.flush()+ if think_tail and ctx_scrubber is not None:+ think_tail = ctx_scrubber.feed(think_tail)if think_tail:- # Route the tail through the context scrubber so a span straddling the boundary is caught.- ctx_scrubber = getattr(self, "_stream_context_scrubber", None)- if ctx_scrubber is not None:- think_tail = ctx_scrubber.feed(think_tail)- if think_tail:- callbacks = [cb for cb in (self.stream_delta_callback, self._stream_callback) if cb is not None]- for cb in callbacks:- try:- cb(think_tail)- except Exception:- pass- self._record_streamed_assistant_text(think_tail)- # Flush the context scrubber's benign tail before clearing; mid-span, flush() drops orphaned content.- scrubber = getattr(self, "_stream_context_scrubber", None)- if scrubber is not None:- tail = scrubber.flush()+ self._deliver_to_stream_callbacks(think_tail)+ self._record_streamed_assistant_text(think_tail)+ if ctx_scrubber is not None:+ tail = ctx_scrubber.flush()if tail:- callbacks = [cb for cb in (self.stream_delta_callback, self._stream_callback) if cb is not None]- for cb in callbacks:- try:- cb(tail)- except Exception:- pass+ self._deliver_to_stream_callbacks(tail)self._record_streamed_assistant_text(tail)self._current_streamed_assistant_text = ""def _record_streamed_assistant_text(self, text: str) -> None:- """Accumulate visible assistant text emitted through stream callbacks."""- # Single-writer guard (#65991): a superseded stream must not pollute the accumulated text, even- # when reached directly via the tool-suppressed path.+ """Accumulate visible assistant text emitted through stream callbacks.++ A superseded stream writer must not pollute the accumulated text, even via the+ tool-suppressed path.+ """if self._stream_writer_superseded():returnif isinstance(text, str) and text:@@ -64,6 +79,8 @@ class StreamDeliveryMixin:getattr(self, "_current_streamed_assistant_text", "") + text)+ # ── interim assistant text ──+@staticmethoddef _normalize_interim_visible_text(text: str) -> str:if not isinstance(text, str):@@ -71,31 +88,24 @@ class StreamDeliveryMixin:return re.sub(r"\s+", " ", text).strip()def _interim_content_was_streamed(self, content: str) -> bool:- visible_content = self._normalize_interim_visible_text(- self._strip_think_blocks(content or "")- )+ visible_content = self._normalize_interim_visible_text(self._strip_think_blocks(content or ""))if not visible_content:return Falsestreamed = self._normalize_interim_visible_text(self._strip_think_blocks(getattr(self, "_current_streamed_assistant_text", "") or ""))- # Prefix match, not equality: the final may be streamed text plus a trailing delta, or the stream- # partial. The reverse (streamed longer) is NOT matched — it could suppress a needed resend (#65919).+ # Prefix match, not equality: the final may be streamed text plus a trailing delta. The+ # reverse (streamed longer) is NOT matched — it could suppress a needed resend.return bool(streamed) and visible_content.startswith(streamed)- def _extract_codex_interim_visible_parts(- self,- assistant_msg: Dict[str, Any],- ) -> List[str]:- """Extract visible Codex commentary as one string per message item.+ def _extract_codex_interim_visible_parts(self, assistant_msg: Dict[str, Any]) -> List[str]:+ """Visible Codex commentary, one string per message item.- Codex keeps mid-turn narration as ``phase=commentary`` items while the final answer stays in- ``content``;- non-streaming gateways need it via the interim callback. ``phase=analysis`` stays hidden (scratchpad).+ Codex keeps mid-turn narration as ``phase=commentary`` items while the final answer+ stays in ``content``; ``phase=analysis`` stays hidden (scratchpad). With+ ``display.show_commentary=false`` commentary stays on the reasoning channel."""if not getattr(self, "show_commentary", True):- # display.show_commentary=false — commentary stays on the- # reasoning channel (pre-commentary-channel behavior).return []items = assistant_msg.get("codex_message_items")if not isinstance(items, list):@@ -103,9 +113,7 @@ class StreamDeliveryMixin:messages: List[str] = []for item in items:- if not isinstance(item, dict):- continue- if item.get("type") != "message":+ if not isinstance(item, dict) or item.get("type") != "message":continuephase = item.get("phase")if not isinstance(phase, str) or phase.strip().lower() != "commentary":@@ -113,47 +121,36 @@ class StreamDeliveryMixin:content_parts = item.get("content")if not isinstance(content_parts, list):continue- item_parts: List[str] = []- for part in content_parts:- if not isinstance(part, dict):- continue- if part.get("type") != "output_text":- continue- text = part.get("text")- if isinstance(text, str) and text.strip():- item_parts.append(text)- visible = "".join(item_parts).strip()+ visible = "".join(+ part["text"] for part in content_parts+ if isinstance(part, dict) and part.get("type") == "output_text"+ and isinstance(part.get("text"), str) and part["text"].strip()+ ).strip()if visible:- visible = self._strip_think_blocks(visible).strip()- visible = redact_sensitive_text(visible)+ visible = redact_sensitive_text(self._strip_think_blocks(visible).strip())if visible:messages.append(visible)return messagesdef _extract_codex_interim_visible_text(self, assistant_msg: Dict[str, Any]) -> str:- """Extract all visible Codex commentary for comparison/fallback."""- return "\n\n".join(- self._extract_codex_interim_visible_parts(assistant_msg)- ).strip()+ """All visible Codex commentary joined, for comparison/fallback."""+ return "\n\n".join(self._extract_codex_interim_visible_parts(assistant_msg)).strip()def _interim_assistant_visible_text(self, assistant_msg: Dict[str, Any]) -> str:- """Return the exact assistant text eligible for interim delivery.+ """The exact assistant text eligible for interim delivery.- Prefers structured Codex commentary over top-level content — a response can hold commentary AND a- partial final answer while tools are pending, and treating content as progress leaks the answer early.- Content may be a parts list, so flatten before stripping reasoning.+ Prefers structured Codex commentary over top-level content — a response can hold+ commentary AND a partial final answer while tools are pending, and treating content+ as progress leaks the answer early. Content may be a parts list."""visible = self._extract_codex_interim_visible_text(assistant_msg)if visible:return visible- content = assistant_msg.get("content")- return self._strip_think_blocks(flatten_message_text(content)).strip()+ return self._strip_think_blocks(flatten_message_text(assistant_msg.get("content"))).strip()def _interim_text_was_delivered(self, text: str) -> bool:normalized = self._normalize_interim_visible_text(text)- if not normalized:- return False- return normalized in getattr(self, "_delivered_interim_texts", set())+ return bool(normalized) and normalized in getattr(self, "_delivered_interim_texts", set())def _record_delivered_interim_text(self, text: str) -> None:normalized = self._normalize_interim_visible_text(text)@@ -180,13 +177,11 @@ class StreamDeliveryMixin:except Exception:logger.debug("interim_assistant_callback error", exc_info=True)- def _emit_interim_assistant_message(- self, assistant_msg: Dict[str, Any]- ) -> None:+ def _emit_interim_assistant_message(self, assistant_msg: Dict[str, Any]) -> None:"""Surface a real mid-turn assistant commentary message to the UI layer.- Does NOT set ``_response_was_previewed`` — that means "the final response was shown"; setting it for- narration would make the CLI suppress a different final summary (response-loss blocker).+ Does NOT set ``_response_was_previewed`` — that means "the final response was shown";+ setting it for narration would make the CLI suppress a different final summary."""if not isinstance(assistant_msg, dict):return@@ -195,11 +190,7 @@ class StreamDeliveryMixin:pending_keys: set[str] = set()for part in commentary_parts:key = self._normalize_interim_visible_text(part)- if (- not key- or key in pending_keys- or self._interim_text_was_delivered(part)- ):+ if not key or key in pending_keys or self._interim_text_was_delivered(part):continuepending_keys.add(key)undelivered_parts.append(part)@@ -208,47 +199,24 @@ class StreamDeliveryMixin:if commentary_partselse self._interim_assistant_visible_text(assistant_msg))- if (- not visible- or visible == "(empty)"- or self._interim_text_was_delivered(visible)- ):+ if not visible or visible == "(empty)" or self._interim_text_was_delivered(visible):returnalready_streamed = self._interim_content_was_streamed(visible)- try:- from agent.plugin_stream_hooks import enqueue_plugin_stream_hook-- enqueue_plugin_stream_hook(- "on_interim_message",- turn_id=getattr(self, "_current_turn_id", "") or "",- iteration=int(getattr(self, "_api_call_count", 0) or 0),- session_id=self.session_id or "",- model=self.model or "",- provider=self.provider or "",- surface=self.platform or "cli",- text=visible,- already_streamed=already_streamed,- )- except Exception:- logger.debug("on_interim_message plugin hook enqueue failed", exc_info=True)+ self._enqueue_stream_hook("on_interim_message", text=visible, already_streamed=already_streamed)cb = getattr(self, "interim_assistant_callback", None)if cb is None:returntry:cb(visible, already_streamed=already_streamed)- if undelivered_parts:- for part in undelivered_parts:- self._record_delivered_interim_text(part)- else:- self._record_delivered_interim_text(visible)+ for part in undelivered_parts or [visible]:+ self._record_delivered_interim_text(part)except Exception:logger.debug("interim_assistant_callback error", exc_info=True)- def _ensure_stream_writer_state(self) -> None:- """Lazily create the single-writer guard fields.+ # ── single-writer stream fence ──- Normally set in ``agent_init``; ``AIAgent.__new__``-built instances skip that path and must not crash.- """+ 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:self._stream_writer_lock = threading.Lock()if not hasattr(self, "_stream_writer_token"):@@ -259,12 +227,12 @@ class StreamDeliveryMixin:self._stream_writer_dropped = 0def _claim_stream_writer(self) -> int:- """Claim exclusive ownership of the streaming delta sink for this stream attempt; returns its writer- token.+ """Claim exclusive ownership of the delta sink for this stream attempt; returns its writer token.- Every attempt (each provider path, each retry) claims right before consuming. Claiming bumps the- shared token, so an earlier attempt still alive on another thread is superseded and its late chunks- fenced out. Stored per-thread: a thread that never claimed is never a writer and can never be fenced.+ Every attempt (each provider path, each retry) claims right before consuming. Claiming+ bumps the shared token, so an earlier attempt still alive on another thread is+ superseded and its late chunks fenced out. Stored per-thread: a thread that never+ claimed is never a writer and can never be fenced."""self._ensure_stream_writer_state()with self._stream_writer_lock:@@ -274,15 +242,11 @@ class StreamDeliveryMixin:return tokendef _stream_writer_is_current(self, token: int) -> bool:- """True when ``token`` is still the active writer (no newer attempt claimed since).-- Lets a stream loop bail out the instant it is superseded.- """+ """True when ``token`` is still the active writer, so a stream loop can bail the instant it is superseded."""return token == getattr(self, "_stream_writer_token", token)def _stream_writer_superseded(self) -> bool:- """True when this thread claimed the sink but a newer attempt has since claimed it (stale writer, drop- chunks).+ """True when this thread claimed the sink but a newer attempt has since claimed it.A thread that never claimed (``token is None``) is never reported superseded."""@@ -308,6 +272,8 @@ 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 "",@@ -319,92 +285,43 @@ class StreamDeliveryMixin:}def _emit_stream_start(self) -> None:- try:- from agent.plugin_stream_hooks import enqueue_plugin_stream_hook-- enqueue_plugin_stream_hook("on_stream_start", **self._stream_hook_base_payload())- except Exception:- logger.debug("on_stream_start plugin hook enqueue failed", exc_info=True)+ self._enqueue_stream_hook("on_stream_start")def _emit_stream_end(self, *, final_text: str, finished: bool, error: str | None) -> None:- try:- from agent.plugin_stream_hooks import enqueue_plugin_stream_hook-- enqueue_plugin_stream_hook(- "on_stream_end",- **self._stream_hook_base_payload(),- final_text=final_text,- finished=finished,- error=error,- )- except Exception:- logger.debug("on_stream_end plugin hook enqueue failed", exc_info=True)+ self._enqueue_stream_hook("on_stream_end", final_text=final_text, finished=finished, error=error)def _fire_stream_delta(self, text: str) -> None:"""Fire all registered stream delta callbacks (display + TTS)."""- # Single-writer guard (#65991): a superseded stream must not interleave- # its tokens into the turn alongside the retry that replaced it.+ # A superseded stream must not interleave its tokens alongside the retry that replaced it.if self._stream_writer_superseded():self._note_dropped_stream_writer("_fire_stream_delta")return- # Prepend one paragraph break before the first text delta after a tool iteration, without+ # One paragraph break before the first text delta after a tool iteration, without# stacking blank lines across back-to-back tool iterations.- if getattr(self, "_stream_needs_break", False) and text and text.strip():+ prepended_break = bool(getattr(self, "_stream_needs_break", False) and text and text.strip())+ if prepended_break:self._stream_needs_break = Falsetext = "\n\n" + text- prepended_break = True- else:- prepended_break = Falseif isinstance(text, str):- # Stateful scrubber (#17924): per-delta regex stripping destroyed downstream state machines when a- # tag was split across deltas (MiniMax-M2.7 sends '<think>' separately).+ # Stateful scrubbers: per-delta regex stripping destroyed downstream state machines+ # when a tag was split across deltas ('<think>' sent alone); memory-context spans+ # split across chunks must not leak to the UI. Legacy callers lack the attributes.think_scrubber = getattr(self, "_stream_think_scrubber", None)- if think_scrubber is not None:- text = think_scrubber.feed(text or "")- else:- # Defensive: legacy callers without the scrubber attribute.- text = self._strip_think_blocks(text or "")- # Then feed through the stateful context scrubber so memory-context- # spans split across chunks cannot leak to the UI (#5719).+ text = think_scrubber.feed(text or "") if think_scrubber is not None else self._strip_think_blocks(text or "")scrubber = getattr(self, "_stream_context_scrubber", None)- if scrubber is not None:- text = scrubber.feed(text)- else:- # Defensive: legacy callers without the scrubber attribute.- text = sanitize_context(text)+ text = scrubber.feed(text) if scrubber is not None else sanitize_context(text)# Only strip leading newlines on the first delta — mid-stream "\n" is legitimate markdown.- if not prepended_break and not getattr(- self, "_current_streamed_assistant_text", ""- ):+ if not prepended_break and not getattr(self, "_current_streamed_assistant_text", ""):text = text.lstrip("\n")if not text:return- callbacks = [cb for cb in (self.stream_delta_callback, self._stream_callback) if cb is not None]- delivered = False- for cb in callbacks:- try:- cb(text)- delivered = True- except Exception:- pass- try:- from agent.plugin_stream_hooks import enqueue_plugin_stream_hook-- enqueue_plugin_stream_hook(- "on_stream_delta",- **self._stream_hook_base_payload(),- delta=text,- kind="text",- )- except Exception:- logger.debug("on_stream_delta plugin hook enqueue failed", exc_info=True)+ delivered = self._deliver_to_stream_callbacks(text)+ self._enqueue_stream_hook("on_stream_delta", delta=text, kind="text")if delivered:self._record_streamed_assistant_text(text)def _fire_reasoning_delta(self, text: str) -> None:- """Fire reasoning callback if registered."""- # Single-writer guard (#65991): fence out a superseded stream's- # reasoning deltas the same way as content deltas.+ """Fire reasoning callback if registered; superseded writers are fenced like content deltas."""if self._stream_writer_superseded():self._note_dropped_stream_writer("_fire_reasoning_delta")return@@ -415,24 +332,17 @@ class StreamDeliveryMixin:except Exception:passtry:- from agent.plugin_stream_hooks import enqueue_plugin_stream_hook, stream_reasoning_deltas_enabled-- if stream_reasoning_deltas_enabled():- enqueue_plugin_stream_hook(- "on_stream_delta",- **self._stream_hook_base_payload(),- delta=text,- kind="reasoning",- )+ from agent.plugin_stream_hooks import stream_reasoning_deltas_enabled++ enabled = stream_reasoning_deltas_enabled()except Exception:logger.debug("reasoning on_stream_delta plugin hook enqueue failed", exc_info=True)+ return+ if enabled:+ self._enqueue_stream_hook("on_stream_delta", label="reasoning on_stream_delta", delta=text, kind="reasoning")def _fire_tool_gen_started(self, tool_name: str) -> None:- """Notify the display layer that the model is generating tool call arguments.-- Fires once per tool name so the TUI can show a spinner while a large payload (e.g. a 45 KB write_file)- streams.- """+ """Notify the display layer that the model is generating tool call arguments (spinner for large payloads)."""cb = self.tool_gen_callbackif cb is not None:try: