The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/turn): facade outcome ternary + suppress, summary pluralize table, liveness/finalizer docstring trims
Teknium8e923c8ea1a6
diff --git a/agent/turn_facade.py b/agent/turn_facade.pyindex 0cde391deff..17a3d32bbe8 100644--- a/agent/turn_facade.py+++ b/agent/turn_facade.py@@ -7,6 +7,7 @@ MRO unchanged."""import loggingimport uuid+from contextlib import suppressfrom typing import Any, Dict, List, Optionalfrom agent.lazy_forward import forward as _forward@@ -130,12 +131,11 @@ class TurnFacadeMixin:if lease is not None:lease.stop_refresher()terminal = result if isinstance(result, dict) else {}- if terminal.get("interrupted") is True:- relay_outcome = "cancelled"- elif terminal.get("failed") is True:- relay_outcome = "failed"- else:- relay_outcome = "success"+ relay_outcome = (+ "cancelled" if terminal.get("interrupted") is True+ else "failed" if terminal.get("failed") is True+ else "success"+ )relay_runtime.SESSION_COORDINATOR.finish_logical_calls(relay_turn, outcome=relay_outcome)if task_started:task_finished = True@@ -173,10 +173,8 @@ class TurnFacadeMixin:lease.release()# Always clear mid-turn labels when the turn exits — including interrupted early# returns that skip finalize_turn. Keep ts.- try:+ with suppress(Exception):self._reset_activity_labels_after_turn()- except Exception:- passif getattr(self, "_relay_pending_turn_id", None) == relay_turn_id:self._relay_pending_turn_id = Noneif acct_token is not None:@@ -187,10 +185,8 @@ class TurnFacadeMixin:reset_affinity_scope(affinity_token)# Balance note_turn_started on every exit so the idle queue's live-turn count# cannot leak.- try:+ with suppress(Exception):_review_queue.note_turn_finished()- except Exception:- passdef chat(self, message: str, stream_callback: Optional[callable] = None) -> str:"""Final response string of one turn; ``stream_callback`` receives each text delta."""diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 7baae201e4a..0bfda861ab5 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -239,19 +239,17 @@ def _micro_compact_after_turn(agent, messages, final_response, logger) -> None:rolling summary before persist, amortizing compression across turns."""try:_compressor = getattr(agent, "context_compressor", None)- # Strict `is True` + isinstance gates: plugin context engines and MagicMock- # compressors pass duck checks and would wipe the transcript.+ # Strict `is True` + callable gates: plugin context engines and MagicMock+ # compressors pass duck checks and would wipe the transcript. Never run while+ # compression.checkpoint_required is armed (no checkpoint hook here), nor for+ # persistence-isolated agents (background review fork): that burns an aux-LLM+ # call on a throwaway transcript and could compact the CANONICAL session rows.if (_compressorand getattr(_compressor, '_micro_compact_enabled', False) is Trueand callable(getattr(_compressor, '_micro_compact', None))and final_response- # No checkpoint hook, so never run while compression.checkpoint_required- # is armed.and getattr(agent, "compression_checkpoint_required", False) is not True- # Persistence-isolated agents (background review fork) must not- # micro-compact: it burns an aux-LLM call on a throwaway transcript and- # could archive_and_compact the CANONICAL session rows.and not getattr(agent, "_persist_disabled", False)):_before = len(messages)@@ -264,9 +262,8 @@ def _micro_compact_after_turn(agent, messages, final_response, logger) -> None:agent._db_flush_scan_prefix = Noneif isinstance(_compacted, list) and _compacted:messages[:] = _compacted- _after = len(messages)- if _before != _after:- logger.info("Micro-compaction: %d -> %d messages", _before, _after)+ if _before != len(messages):+ logger.info("Micro-compaction: %d -> %d messages", _before, len(messages))except Exception as _mc_err:logger.info("Micro-compaction failed: %s", _mc_err)@@ -311,9 +308,8 @@ def _log_turn_exit(agent, messages, final_response, api_call_count, _turn_exit_rdef _append_file_mutation_footer(agent, final_response, logger):- """If ``write_file`` / ``patch`` calls failed and were never superseded by a- successful write to the same path, append an advisory so over-claiming is- surfaced."""+ """Append the verifier advisory when ``write_file`` / ``patch`` calls failed and were+ never superseded by a successful write to the same path (surfaces over-claiming)."""try:_failed = getattr(agent, "_turn_failed_file_mutations", None) or {}if _failed and agent._file_mutation_verifier_enabled():@@ -333,7 +329,7 @@ def _explain_abnormal_exit(agent, final_response, _turn_exit_reason, preserved_vif not agent._turn_completion_explainer_enabled():return final_response_stripped = (final_response or "").strip()- _is_empty_terminal = _stripped == "" or _stripped == "(empty)"+ _is_empty_terminal = _stripped in ("", "(empty)")# A short fragment not from a text_response exit and lacking sentence-ending# punctuation is treated as a truncated partial (#34452)._is_partial_fragment = (@@ -343,11 +339,7 @@ def _explain_abnormal_exit(agent, final_response, _turn_exit_reason, preserved_vand len(_stripped) <= 24and _stripped[-1:] not in _SENTENCE_END)- if (- _is_empty_terminal- or _is_partial_fragment- or str(_turn_exit_reason) == "partial_stream_recovery"- ):+ if _is_empty_terminal or _is_partial_fragment or str(_turn_exit_reason) == "partial_stream_recovery":_explanation = agent._format_turn_completion_explanation(_turn_exit_reason, getattr(agent, "_last_persistence_error_cause", None))diff --git a/agent/turn_liveness.py b/agent/turn_liveness.pyindex 24f7df2384a..7a006938f25 100644--- a/agent/turn_liveness.py+++ b/agent/turn_liveness.py@@ -1,20 +1,11 @@"""Turn liveness watchdog: force-abort turns that stall silently.-A turn can wedge mid-flight with no error and its durable lease still-renewing, so nothing ever frees the session. This module owns the policy:-config resolution (``agent.turn_liveness`` in config.yaml, validated — a typo,-NaN or Inf warns and falls back rather than disabling the timeout or freezing-the poll), the sampling state machine, and the watcher thread.-``AIAgent.run_conversation`` supplies the commit/deactivate callbacks that own-turn-lease state.--Race safety: the watchdog binds its abort decision to the observed-``(generation, timestamp)`` pair; the commit callback revalidates that pair-under the same lock ``_touch_activity`` stamps with, so a turn that resumed-while the stall was being surfaced is never hard-cancelled. The revalidated-generation flows into ``AIAgent.interrupt`` (``require_generation``) as a-claim consumed at the final mutation edge, in ONE activity-lock critical-section with the first interrupt-state publish.+A turn can wedge mid-flight with no error and its durable lease still renewing, so nothing+ever frees the session. This module owns config resolution (``agent.turn_liveness``,+validated — a typo, NaN or Inf warns and falls back), the sampling state machine, and the+watcher thread. Race safety: the abort decision is bound to the observed+``(generation, timestamp)``; the commit callback revalidates it under the same lock+``_touch_activity`` stamps with, so a turn that resumed is never hard-cancelled."""from __future__ import annotationsdiff --git a/agent/turn_summary.py b/agent/turn_summary.pyindex 8574c3d15fc..eada53ff2c5 100644--- a/agent/turn_summary.py+++ b/agent/turn_summary.py@@ -13,6 +13,7 @@ is the spinner-side cumulative token readout (``↓ 1.2k tok``).from __future__ import annotations+import jsonfrom dataclasses import dataclass, fieldfrom typing import Any@@ -94,8 +95,6 @@ def _extract_line_deltas(tool_name: str, result: Any) -> tuple[int, int] | None:if not text.startswith("{"):return Nonetry:- import json-# strict=False tolerates raw control chars inside an embedded diff.payload = json.loads(text, strict=False)except Exception:@@ -169,12 +168,9 @@ def _pluralize(count: int, plural_noun: str) -> str:"""``"1 file"`` / ``"3 files"`` from a plural noun form."""if count != 1:return f"{count} {plural_noun}"- if plural_noun.endswith("ies"):- return f"1 {plural_noun[:-3]}y"- if plural_noun.endswith("ses"):- return f"1 {plural_noun[:-2]}"- if plural_noun.endswith("s"):- return f"1 {plural_noun[:-1]}"+ for suffix, singular_tail in (("ies", "y"), ("ses", "s"), ("s", "")):+ if plural_noun.endswith(suffix):+ return f"1 {plural_noun[:-len(suffix)]}{singular_tail}"return f"1 {plural_noun}"