The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/turn): unify compression-attempt helpers, collapse verdict boilerplate, dedupe persist-lock wrappers
Tekniume7d4b2123ede
diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 6c0542daf37..666ce022397 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -1,23 +1,22 @@"""Per-turn setup for ``run_conversation`` (the turn prologue).``build_turn_context`` runs the once-per-turn setup (stdio guard, sanitization, prompt-restore-or-build, session row, idle/preflight compaction — see-``turn_context_compaction`` — pre_llm_call hook, prefetch, persistence), mutating-``agent`` as the loop expects, and returns a ``TurnContext`` carrying only the locals-the loop reads back. ``build_api_messages`` builds the wire copy for one API call."""+restore-or-build, session row, idle/preflight compaction via ``turn_context_compaction``,+pre_llm_call hook, prefetch, persistence), mutating ``agent`` as the loop expects, and+returns a ``TurnContext`` with only the locals the loop reads back.+``build_api_messages`` builds the wire copy for one API call."""from __future__ import annotationsimport logging+import sysimport threadingimport timeimport uuidfrom dataclasses import dataclassfrom typing import Any, Dict, List, Mapping, Optional, Tuple-from agent.conversation_compression import (- recover_rotated_compression_session,-)+from agent.conversation_compression import recover_rotated_compression_sessionfrom agent.iteration_budget import IterationBudgetfrom agent.memory_manager import build_memory_context_blockfrom agent.memory_provider import is_trivial_prompt@@ -32,20 +31,14 @@ logger = logging.getLogger(__name__)def _preflight_request_tokens(agent: Any, messages: List[Dict[str, Any]], system_prompt: str) -> int:- """Token estimate for automatic preflight compression.-- Prefers a valid provider usage anchor; on native-compaction-eligible requests counts- the checkpoint-pruned wire payload; otherwise uses the generic estimator."""- anchored = anchored_context_tokens(- messages, getattr(agent, "_usage_anchor", None)- )+ """Token estimate for automatic preflight compression: a valid provider usage anchor,+ else the checkpoint-pruned native wire payload, else the generic estimator."""+ anchored = anchored_context_tokens(messages, getattr(agent, "_usage_anchor", None))if anchored is not None:return anchoredtools = getattr(agent, "tools", None) or Nonetry:- from agent.codex_responses_adapter import (- estimate_native_responses_preflight_tokens,- )+ from agent.codex_responses_adapter import estimate_native_responses_preflight_tokensnative = estimate_native_responses_preflight_tokens(agent, messages, system_prompt=system_prompt or "", tools=tools@@ -65,9 +58,8 @@ def _preflight_request_tokens(def _agent_stale_thinking_on_wire(agent: Any) -> bool:- """Whether the agent's active route replays stale thinking text (#84371).-- Returns ``True`` (conservative full charge) when route facts are unavailable."""+ """Whether the active route replays stale thinking text; ``True`` (conservative full+ charge) when route facts are unavailable."""try:from agent.message_sanitization import stale_thinking_reaches_wire@@ -84,40 +76,29 @@ def compose_user_api_content() -> Optional[str]:"""Compose the API-bound content of the current turn's user message.- Single source for the ``api_content`` sidecar and the wire bytes, so they never- drift — the prompt-cache invariant: what turn N sends is what turn N+1 replays.- Returns ``None`` when nothing is injected (message is sent as-is)."""+ Single source for the ``api_content`` sidecar and the wire bytes so they never drift+ (what turn N sends is what turn N+1 replays). ``None`` when nothing is injected."""if not isinstance(content, str):return None- injections = []- if ext_prefetch_cache:- fenced = build_memory_context_block(ext_prefetch_cache)- if fenced:- injections.append(fenced)- if plugin_user_context:- injections.append(plugin_user_context)+ fenced = build_memory_context_block(ext_prefetch_cache) if ext_prefetch_cache else ""+ injections = [part for part in (fenced, plugin_user_context) if part]if not injections:return Nonereturn content + "\n\n" + "\n\n".join(injections)def substitute_api_content(api_msg: Dict[str, Any]) -> Optional[str]:- """Pop the ``api_content`` sidecar and substitute it into ``content``.-- Keeps the provider prompt-cache prefix byte-stable across turns.- Returns the popped sidecar string, or ``None`` when absent."""+ """Pop the ``api_content`` sidecar and substitute it into ``content`` (keeps the+ prompt-cache prefix byte-stable). Returns the popped sidecar, or ``None``."""sidecar = api_msg.pop("api_content", None)- if (- isinstance(sidecar, str) and sidecar and api_msg.get("role") in ("user", "assistant")- ):+ if isinstance(sidecar, str) and sidecar and api_msg.get("role") in ("user", "assistant"):api_msg["content"] = sidecarreturn sidecardef drop_stale_api_content(msg: Dict[str, Any]) -> None:- """Drop the ``api_content`` sidecar from a message whose content was rewritten.-- Replaying it would resend what the rewrite removed; cost is one cache miss."""+ """Drop the ``api_content`` sidecar from a message whose content was rewritten+ (replaying it would resend what the rewrite removed; cost is one cache miss)."""msg.pop("api_content", None)@@ -140,10 +121,8 @@ def consume_gateway_turn_context_notes(agent: Any) -> str:def append_notes_to_multimodal_content(content: Any, notes: str) -> bool:- """Deliver must-deliver notes on a multimodal (list) user message.-- Appends a durable text part in place, since the sidecar path returns ``None``- for non-string content. Returns ``True`` when a part was appended."""+ """Append must-deliver notes as a durable text part on a multimodal (list) user+ message (the sidecar path returns ``None`` for non-string content)."""if not notes or not isinstance(content, list):return Falsetry:@@ -164,10 +143,8 @@ def _maybe_title_session_at_turn_start(agent: Any, messages: List[Any]) -> None:session_id = getattr(agent, "session_id", None)if not session_db or not session_id:return-if str(getattr(agent, "platform", "") or "").lower() in _UNTITLED_PLATFORMS:return-try:from agent.message_content import flatten_message_textfrom agent.title_generator import maybe_auto_title@@ -180,8 +157,7 @@ def _maybe_title_session_at_turn_start(agent: Any, messages: List[Any]) -> None:breakif not user_text:return-- # Session row is created lazily later; force it now or the title write matches+ # The session row is created lazily; force it now or the title write matches# zero rows.if not getattr(agent, "_session_db_created", False):ensure = getattr(agent, "_ensure_db_session", None)@@ -189,12 +165,10 @@ def _maybe_title_session_at_turn_start(agent: Any, messages: List[Any]) -> None:ensure()if not getattr(agent, "_session_db_created", False):return-# Snapshot runtime identity so the background titler can skip if the user- # switches models before it fires (#19027).+ # switches models before it fires._model = getattr(agent, "model", None)_provider = getattr(agent, "provider", None)-maybe_auto_title(session_db,session_id,@@ -225,7 +199,7 @@ def reanchor_current_turn_user_idx(messages: List[Any], user_message: Any) -> in"""Locate this turn's user message after compaction rebuilt ``messages``.Prefers the LAST user message whose content exactly matches this turn's text, else- the last user-originated turn; compaction handoffs are never the fallback (#80622).+ the last user-originated turn; compaction handoffs are never the fallback.Returns -1 when there is no user-originated message."""from agent.context_compressor import user_originated_turn_view@@ -243,8 +217,8 @@ def reanchor_current_turn_user_idx(messages: List[Any], user_message: Any) -> incontinueif live_view.get("content") == user_message:return i- # Prefer a real human turn over a synthetic handoff / continuation- # marker when the exact content was rewritten by merge-into-tail.+ # Prefer a real human turn over a synthetic handoff / continuation marker+ # when the exact content was rewritten by merge-into-tail.if fallback < 0:fallback = ireturn fallback@@ -253,17 +227,12 @@ def reanchor_current_turn_user_idx(messages: List[Any], user_message: Any) -> indef compression_made_progress(orig_len: int, new_len: int, orig_tokens: int, new_tokens: int) -> bool:- """Return ``True`` if a compression pass materially reduced the request.-- Counts a >5% token reduction as progress even when the row count is unchanged- (size-only wins, #39548); same floor as the overflow-handler retry path."""- if new_len < orig_len:- return True- return orig_tokens > 0 and new_tokens < orig_tokens * 0.95+ """``True`` if a compression pass materially reduced the request: fewer rows, or a+ >5% token cut with the same rows (same floor as the overflow-handler retry)."""+ return new_len < orig_len or (orig_tokens > 0 and new_tokens < orig_tokens * 0.95)-# Back-compat alias: gateway callers and tests patch ``_compression_made_progress``-# (#79624).+# Back-compat alias: gateway callers and tests patch ``_compression_made_progress``._compression_made_progress = compression_made_progress@@ -285,10 +254,9 @@ def _fail_closed_after_preflight_timeout(agent, request_tokens: int) -> None:def _review_fork_first_request_pending(agent: Any) -> bool:- """Whether a detached review fork has yet to send its first provider request.-- The fork replays the parent's FULL snapshot as a warm cache read, so compaction must- wait until that first response arrives. Dormant without the attribute (#93057)."""+ """Whether a detached review fork has yet to send its first provider request: it+ replays the parent's FULL snapshot as a warm cache read, so compaction must wait+ for that first response. Dormant without the attribute."""return bool(getattr(agent, "_review_defer_compaction_before_first_response", False)and not getattr(agent, "_turn_received_provider_response", False)@@ -298,44 +266,38 @@ def _review_fork_first_request_pending(agent: Any) -> bool:def _compression_warrants_another_preflight_pass(orig_tokens: int, new_tokens: int, threshold_tokens: int) -> bool:- """Whether an over-threshold request merits another immediate summary.-- Continue only if still over threshold AND the previous pass cut tokens by >5%."""- return (- new_tokens >= threshold_tokens and orig_tokens > 0 and new_tokens < orig_tokens * 0.95- )+ """Another immediate summary only if still over threshold AND the previous pass cut+ tokens by >5%."""+ return new_tokens >= threshold_tokens and orig_tokens > 0 and new_tokens < orig_tokens * 0.95def _should_run_preflight_estimate(messages: List[Dict[str, Any]], protect_first_n: int, protect_last_n: int, threshold_tokens: int) -> bool:- """Cheap gate for the (expensive) full preflight token estimate.-- ``True`` when message count exceeds the protected ranges OR a rough char-based- estimate crosses the threshold — the few-but-huge case (#27405). The estimator- undercounts by design (omits system/tools) so one large base64 image is not- mistaken for ~250K tokens."""- if len(messages) > protect_first_n + protect_last_n + 1:- return True- return estimate_messages_tokens_rough(messages) >= threshold_tokens+ """Cheap gate for the (expensive) full preflight estimate: message count exceeds the+ protected ranges OR a rough char-based estimate crosses the threshold (few-but-huge+ case). The estimator undercounts by design (omits system/tools) so one large base64+ image is not mistaken for ~250K tokens."""+ return (+ len(messages) > protect_first_n + protect_last_n + 1+ or estimate_messages_tokens_rough(messages) >= threshold_tokens+ )def _should_idle_compact(*, enabled: bool, idle_after_seconds: int, idle_gap_seconds: float, tokens: int,floor_tokens: int, cooldown_active: bool,) -> bool:- """Decide whether an idle-triggered compaction should run this turn.-- Fires after a wall-clock gap of ``idle_after_seconds`` (opt-in, <= 0 disables),- independent of ``threshold_tokens``; skips at/below ``floor_tokens`` and during a- compression-failure cooldown. Pure predicate."""- if not enabled or idle_after_seconds <= 0:- return False- if idle_gap_seconds < idle_after_seconds:- return False- if cooldown_active:- return False- return tokens > floor_tokens+ """Pure predicate: idle compaction fires after a wall-clock gap of+ ``idle_after_seconds`` (opt-in, <= 0 disables), independent of ``threshold_tokens``;+ never at/below ``floor_tokens`` or during a compression-failure cooldown."""+ return bool(+ enabled+ and idle_after_seconds > 0+ and idle_gap_seconds >= idle_after_seconds+ and not cooldown_active+ and tokens > floor_tokens+ )@dataclass@@ -367,22 +329,23 @@ class TurnContext:preflight_compression_blocked: bool = False--def _with_persist_lock(agent: Any, fn) -> None:- """Run ``fn`` under the session persist lock when the agent has one."""- lock = getattr(agent, "_session_persist_lock", None)- if lock is None:- fn()- else:- with lock:+def _persist_under_lock(agent: Any, fn, failure_msg: str, pending_cli_message: Any) -> None:+ """Run ``fn`` under the session persist lock (when the agent has one), log-and-swallow+ failures, then drop staged CLI input — unless it is an unmarked handoff kept for a+ close retry (once ``_db_persisted`` the close path must not treat it as pre-worker+ UI input). Eager clearing keeps a preflight crash from leaking stale input."""+ try:+ lock = getattr(agent, "_session_persist_lock", None)+ if lock is None:fn()---def _clear_staged_cli_input_if_persisted(agent: Any, pending_cli_message: Any) -> None:- """Drop staged CLI input unless it is an unmarked handoff kept for a close retry;- once marked ``_db_persisted`` the close path must not treat it as pre-worker UI input."""- if not isinstance(pending_cli_message, dict) or pending_cli_message.get("_db_persisted"):- agent._pending_cli_user_message = None+ else:+ with lock:+ fn()+ except Exception:+ logger.warning(failure_msg, agent.session_id or "none", exc_info=True)+ finally:+ if not isinstance(pending_cli_message, dict) or pending_cli_message.get("_db_persisted"):+ agent._pending_cli_user_message = Nonedef _publish_runtime_main(agent: Any) -> None:@@ -392,7 +355,7 @@ def _publish_runtime_main(agent: Any) -> None:from agent.auxiliary_client import set_runtime_mainfrom agent.prompt_cache_scope import resolve_prompt_cache_scope_safe# Rotation-stable prompt-cache scope (lineage root), memoized per segment; a new- # session uses the physical id until build_api_kwargs re-resolves (#79017).+ # session uses the physical id until build_api_kwargs re-resolves._cache_scope = resolve_prompt_cache_scope_safe(agent) or ""set_runtime_main(getattr(agent, "provider", "") or "", getattr(agent, "model", "") or "",@@ -410,18 +373,14 @@ def _publish_runtime_main(agent: Any) -> None:def _refresh_mcp_tools_between_turns(agent: Any) -> None:"""Late-connecting MCP servers land in THIS turn's snapshot, before the first APIcall assembles ``tools=``. ``preserve_prefix`` keeps the tool array append-only so a- flapping ``check_fn`` can't fork the cache (#100336)."""+ flapping ``check_fn`` can't fork the cache."""try:- if not getattr(agent, "_skip_mcp_refresh", False):- # Import-cost gate: MCP tools are only registered by code that already- # imported ``tools.mcp_tool`` (~0.4s); not in sys.modules => nothing to do.- import sys as _sys- if "tools.mcp_tool" in _sys.modules:- from tools.mcp_tool import has_registered_mcp_tools, refresh_agent_mcp_tools- if has_registered_mcp_tools():- refresh_agent_mcp_tools(- agent, quiet_mode=True, preserve_prefix=True,- )+ # Import-cost gate: MCP tools are only registered by code that already imported+ # ``tools.mcp_tool`` (~0.4s); not in sys.modules => nothing to do.+ if not getattr(agent, "_skip_mcp_refresh", False) and "tools.mcp_tool" in sys.modules:+ from tools.mcp_tool import has_registered_mcp_tools, refresh_agent_mcp_tools+ if has_registered_mcp_tools():+ refresh_agent_mcp_tools(agent, quiet_mode=True, preserve_prefix=True)except Exception:logger.debug("between-turns MCP tool refresh skipped", exc_info=True)@@ -432,20 +391,17 @@ def _bind_turn_identity() -> Tuple[str, str]:"""Stage callback/persist overrides on the agent and bind this turn's task and turnids. Returns ``(effective_task_id, turn_id)``."""- # Store stream callback for _interruptible_api_call to pick up.- agent._stream_callback = stream_callback+ agent._stream_callback = stream_callback # picked up by _interruptible_api_callagent._persist_user_message_idx = Noneagent._persist_user_message_override = persist_user_messageagent._persist_user_message_timestamp = persist_user_timestampagent._persist_user_message_platform_id = persist_user_platform_id- # Generate unique task_id if not provided to isolate VMs between tasks.+ # Unique task_id when not provided isolates VMs between tasks.effective_task_id = task_id or str(uuid.uuid4())agent._current_task_id = effective_task_id- turn_id = str(getattr(agent, "_relay_pending_turn_id", "") or "")- if not turn_id:- turn_id = (- f"{agent.session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}"- )+ turn_id = str(getattr(agent, "_relay_pending_turn_id", "") or "") or (+ f"{agent.session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}"+ )agent._relay_pending_turn_id = Noneagent._current_turn_id = turn_idagent._current_api_request_id = ""@@ -497,10 +453,9 @@ def _reset_per_turn_agent_state(agent: Any) -> None:# Wall-clock run budget: stamped only when configured; the wrap-up latch resets per# turn (one notice per run).- if getattr(agent, "run_budget_seconds", None):- agent._run_budget_started_at = time.time()- else:- agent._run_budget_started_at = None+ agent._run_budget_started_at = (+ time.time() if getattr(agent, "run_budget_seconds", None) else None+ )agent._run_budget_wrapup_injected = False# Per-turn file-mutation verifier state.@@ -538,12 +493,10 @@ def _stage_turn_user_message(# prefix) on the same dict, keeping any close-path durable marker.user_msg["content"] = user_messageelse:- user_msg = stamp_message_timestamp(- {"role": "user", "content": user_message}, timestamp=persist_user_timestamp- )+ user_msg = {"role": "user", "content": user_message}if isinstance(pending_cli_message, dict):agent._pending_cli_user_message = None- # CLI input is stamped when staged. Gateway input may carry the platform event+ # CLI input is stamped when staged; gateway input may carry the platform event# time. Preserve either value and cover any legacy unstamped handoff.stamp_message_timestamp(user_msg, timestamp=persist_user_timestamp)@@ -553,8 +506,8 @@ def _stage_turn_user_message(user_msg["display_kind"] = persist_user_display_kindif persist_user_display_metadata:user_msg["display_metadata"] = persist_user_display_metadata- # Stamp the platform message id so it survives the turn-start flush; restart- # drain-window recovery dedups via ``has_platform_message_id`` against this row.+ # The platform message id survives the turn-start flush; restart drain-window+ # recovery dedups via ``has_platform_message_id`` against this row.if persist_user_platform_id is not None:user_msg["platform_message_id"] = persist_user_platform_idreturn user_msg, pending_cli_message@@ -566,11 +519,8 @@ def _hydrate_from_history(agent: Any, conversation_history: Optional[List[Any]])returnif not agent._todo_store.has_items():agent._hydrate_todo_store(conversation_history)- # Hydrate per-session nudge counters from persisted history (issue #22357).if agent._user_turn_count == 0:- prior_user_turns = sum(- 1 for m in conversation_history if m.get("role") == "user"- )+ prior_user_turns = sum(1 for m in conversation_history if m.get("role") == "user")if prior_user_turns > 0:agent._user_turn_count = prior_user_turnsif agent._memory_nudge_interval > 0 and agent._turns_since_memory == 0:@@ -606,21 +556,13 @@ def _emit_reaction(agent: Any, original_user_message: Any) -> None:def _ensure_session_row(agent: Any, pending_cli_message: Any) -> None:- """Create the DB row now (system prompt populated => non-NULL, #45499) and BEFORE- preflight compression: compaction/rotation INSERTs reference this row under- PRAGMA foreign_keys=ON. Idempotent; the user-turn crash persist runs later."""- try:- _with_persist_lock(agent, agent._ensure_db_session)- except Exception:- logger.warning(- "Turn-start session row creation failed for session=%s",- agent.session_id or "none",- exc_info=True,- )- finally:- # Clear staged CLI input eagerly so a crash in preflight compression doesn't- # leave a stale _pending_cli_user_message for the next turn.- _clear_staged_cli_input_if_persisted(agent, pending_cli_message)+ """Create the DB row now (system prompt populated => non-NULL) and BEFORE preflight+ compression: compaction/rotation INSERTs reference this row under PRAGMA+ foreign_keys=ON. Idempotent; the user-turn crash persist runs later."""+ _persist_under_lock(+ agent, agent._ensure_db_session,+ "Turn-start session row creation failed for session=%s", pending_cli_message,+ )def _collect_pre_llm_call_context(@@ -695,9 +637,7 @@ def _merge_gateway_notes(if isinstance(_gw_turn_content, list):append_notes_to_multimodal_content(_gw_turn_content, _gateway_notes)return plugin_user_context- return (- plugin_user_context + "\n\n" + _gateway_notes if plugin_user_context else _gateway_notes- )+ return plugin_user_context + "\n\n" + _gateway_notes if plugin_user_context else _gateway_notesdef _bind_interrupt_scope(agent: Any, ra) -> None:@@ -717,7 +657,7 @@ def _bind_interrupt_scope(agent: Any, ra) -> None:def _memory_turn_start_and_prefetch(agent: Any, original_user_message: Any) -> str:"""Notify memory providers of the new turn, then prefetch external memory once- before the tool loop (skipped on trivial prompts that carry no semantic signal).+ before the tool loop (skipped on trivial prompts with no semantic signal).Returns the prefetch text (``""`` when nothing was injected)."""if not agent._memory_manager:return ""@@ -732,8 +672,8 @@ def _memory_turn_start_and_prefetch(agent: Any, original_user_message: Any) -> sext_prefetch_cache = agent._memory_manager.prefetch_all(_query) or ""except Exception:pass- # Deterministic recall indicator: rendered by Hermes via _emit_status when memory- # was injected, so the model can't silently drop it.+ # Deterministic recall indicator via _emit_status so the model can't silently+ # drop injected memory.if ext_prefetch_cache:try:_recall_indicator = agent._memory_manager.describe_recall()@@ -748,9 +688,8 @@ def _stamp_api_content_sidecar(agent: Any, messages: List[Any], current_turn_user_idx: int, ext_prefetch_cache: str,plugin_user_context: str, *, preflight_compressed: bool,) -> None:- """api_content sidecar — persist what you send. Injected context lives only in the- API copy; stamp the exact sent bytes on the live dict so replay reproduces the- prefix."""+ """api_content sidecar — persist what you send: injected context lives only in the+ API copy, so stamp the exact sent bytes on the live dict for replay."""_turn_user_msg = messages[current_turn_user_idx]_api_content = compose_user_api_content(_turn_user_msg.get("content", ""), ext_prefetch_cache, plugin_user_context@@ -761,20 +700,21 @@ def _stamp_api_content_sidecar(# In-place preflight compaction already inserted this turn's user row and the# crash persist identity-skips compacted dicts, so backfill the stamp onto the row# directly. Rotation mode flushes to the child session later.- if preflight_compressed and bool(getattr(agent, "_last_compaction_in_place", False)):- _db = getattr(agent, "_session_db", None)- if _db is not None:- try:- _db.set_latest_user_api_content(- agent.session_id, _turn_user_msg.get("content"), _api_content- )- except Exception:- logger.warning(- "in-place compaction api_content backfill failed "- "for session=%s",- agent.session_id or "none",- exc_info=True,- )+ if not (preflight_compressed and getattr(agent, "_last_compaction_in_place", False)):+ return+ _db = getattr(agent, "_session_db", None)+ if _db is not None:+ try:+ _db.set_latest_user_api_content(+ agent.session_id, _turn_user_msg.get("content"), _api_content+ )+ except Exception:+ logger.warning(+ "in-place compaction api_content backfill failed "+ "for session=%s",+ agent.session_id or "none",+ exc_info=True,+ )def _persist_turn_start(@@ -788,16 +728,10 @@ def _persist_turn_start(agent._ensure_db_session()agent._persist_session(messages, conversation_history)- try:- _with_persist_lock(agent, _ensure_and_persist)- except Exception:- logger.warning(- "Early turn-start session persistence failed for session=%s",- agent.session_id or "none",- exc_info=True,- )- finally:- _clear_staged_cli_input_if_persisted(agent, pending_cli_message)+ _persist_under_lock(+ agent, _ensure_and_persist,+ "Early turn-start session persistence failed for session=%s", pending_cli_message,+ )def build_turn_context(@@ -813,8 +747,8 @@ def build_turn_context(Helpers are passed in to avoid an import cycle with ``agent.conversation_loop``.Order matters: the DB session row is created only AFTER the system prompt is built- (else it persists system_prompt=NULL and costs a cache miss, #45499) and BEFORE- preflight compression."""+ (else it persists system_prompt=NULL and costs a cache miss) and BEFORE preflight+ compression."""from agent.turn_context_compaction import run_turn_start_compaction# Guard stdio against OSError from broken pipes (systemd/headless/daemon).@@ -826,16 +760,14 @@ def build_turn_context(if recovered_history is not None:conversation_history = recovered_history- # Tag log records on this thread with the session ID for ``hermes logs``.+ # Tag log records on this thread with the session ID for ``hermes logs``; bind the+ # skill write-origin ContextVar; restore the primary runtime after a fallback turn.set_session_context(agent.session_id)- # Bind the skill write-origin ContextVar for this thread.set_current_write_origin(getattr(agent, "_memory_write_origin", "assistant_tool"))- # Restore the primary runtime if the previous turn activated fallback.agent._restore_primary_runtime()_publish_runtime_main(agent)_refresh_mcp_tools_between_turns(agent)- # Sanitize surrogate characters from user input.if isinstance(user_message, str):user_message = sanitize_surrogates(user_message)if isinstance(persist_user_message, str):@@ -847,7 +779,6 @@ def build_turn_context()_reset_per_turn_agent_state(agent)- # Log conversation turn start for debugging/observability._preview_text = summarize_user_message_for_log(user_message)_msg_preview = (_preview_text[:80] + "...") if len(_preview_text) > 80 else _preview_textlogger.info(@@ -857,7 +788,7 @@ def build_turn_context(_msg_preview.replace("\n", " "),)- # Initialize conversation (copy to avoid mutating the caller's list).+ # Copy so the caller's list is never mutated.messages = list(conversation_history) if conversation_history else []user_msg, pending_cli_message = _stage_turn_user_message(agent, user_message, persist_user_message, persist_user_timestamp,@@ -869,10 +800,9 @@ def build_turn_context(current_turn_user_idx = len(messages) - 1agent._persist_user_message_idx = current_turn_user_idx- # Track user turns for memory flush and periodic nudge logic.agent._user_turn_count += 1# Copilot x-initiator: the first API call of this user turn is user-initiated;- # tool-loop follow-ups revert to "agent" (#3040).+ # tool-loop follow-ups revert to "agent".agent._is_user_initiated_turn = True# Preserve the original user message (no nudge injection).@@ -886,7 +816,7 @@ def build_turn_context(f"{'...' if len(_preview_text) > 60 else ''}'")- # ── System prompt (cached per session for prefix caching) ──+ # System prompt is cached per session for prefix caching.if agent._cached_system_prompt is None:restore_or_build_system_prompt(agent, system_message, conversation_history)active_system_prompt = agent._cached_system_prompt@@ -902,7 +832,6 @@ def build_turn_context(_ensure_session_row(agent, pending_cli_message)- # ── Idle compaction + preflight compression (or the uncompressed guard) ──compaction = run_turn_start_compaction(agent, messages=messages, system_message=system_message,active_system_prompt=active_system_prompt, conversation_history=conversation_history,@@ -954,6 +883,24 @@ def build_turn_context()+def _sanitize_model_for(agent: Any, moa_config: Any) -> Any:+ """Model name for strict-API tool-call sanitization. In MoA mode ``agent.model`` is+ the virtual preset name; use the resolved aggregator so Gemini keeps+ thought_signature (extra_content)."""+ _sanitize_model = agent.model+ if agent.provider == "moa":+ if moa_config:+ _agg = moa_config.get("aggregator") or {}+ if _agg.get("model"):+ _sanitize_model = _agg["model"]+ if _sanitize_model == agent.model:+ # Virtual-provider mode: no moa_config is threaded through; ask the facade+ # for the aggregator slot from the previous create().+ _agg_slot = getattr(getattr(agent, "client", None), "last_aggregator_slot", None)+ if _agg_slot and _agg_slot.get("model"):+ _sanitize_model = _agg_slot["model"]+ return _sanitize_model+def build_api_messages(agent: Any, messages: List[Dict[str, Any]], *, current_turn_user_idx: Any,@@ -965,31 +912,25 @@ def build_api_messages(Prompt-cache invariant: historical user/assistant rows replay their ``api_content``sidecar (the exact bytes sent live) so the prefix stays byte-stable; the currentuser turn reuses the prologue's stamp (or composes live when a caller bypassed the- prologue). Ephemeral context (prefetch, ``pre_llm_call`` hooks, ``ephemeral_system_prompt``)- is added at API time only — ``messages`` stays untouched beyond the sidecar stamp,- and the system prompt is built ONCE per session and replayed verbatim."""+ prologue). Ephemeral context (prefetch, ``pre_llm_call`` hooks,+ ``ephemeral_system_prompt``) is added at API time only — ``messages`` stays untouched+ beyond the sidecar stamp, and the system prompt is built ONCE per session and+ replayed verbatim."""from agent.agent_runtime_helpers import fill_empty_non_final_wire_payloadfrom agent.conversation_loop import _clone_message_for_sendapi_messages = []for idx, msg in enumerate(messages):-# Structural clone, NOT msg.copy(): in-place transforms below must not reach# persisted history via nested containers; see _clone_message_for_send.api_msg = _clone_message_for_send(msg)-- # api_content is the persistence sidecar of the exact bytes sent to the API;- # bookkeeping, never a provider field — pop it from EVERY outgoing copy.+ # api_content is bookkeeping (exact bytes sent), never a provider field — pop+ # it from EVERY outgoing copy. display_* is display-only timeline metadata+ # (strict OpenAI backends reject unknown keys); _row_id is the durable row id+ # from _rows_to_conversation and only chat-completions strips underscore keys._api_content = api_msg.pop("api_content", None)-- # Display-only timeline metadata, never a provider field: strict OpenAI- # backends reject unknown keys once a typed event row enters live history.- api_msg.pop("display_kind", None)- api_msg.pop("display_metadata", None)-- # Durable row id from _rows_to_conversation (desktop reactions); only the- # chat-completions transport strips underscore keys, so drop it centrally.- api_msg.pop("_row_id", None)+ for key in ("display_kind", "display_metadata", "_row_id"):+ api_msg.pop(key, None)# Inject ephemeral context (memory prefetch + pre_llm_call user hooks)# at API time only; `messages` is untouched beyond the api_content stamp.@@ -1005,30 +946,23 @@ def build_api_messages()if _composed is not None:api_msg["content"] = _composed- elif (- isinstance(_api_content, str)- and _api_content- and msg.get("role") in ("user", "assistant")- ):+ elif isinstance(_api_content, str) and _api_content and msg.get("role") in ("user", "assistant"):# Historical row: replay the exact bytes sent live so the prompt-cache# prefix stays byte-stable. User rows carry the injection sidecar; user# and assistant rows may carry a sanitize-divergence sidecar.api_msg["content"] = _api_content- # For ALL assistant messages, pass reasoning back to the API- # This ensures multi-turn reasoning context is preserved+ # Pass reasoning back to the API for ALL assistant messages so multi-turn+ # reasoning context is preserved.agent._copy_reasoning_content_for_api(msg, api_msg)-# 'reasoning' is trajectory-only (copied to 'reasoning_content' above);# finish_reason is rejected by strict APIs (e.g. Mistral).api_msg.pop("reasoning", None)api_msg.pop("finish_reason", None)# Fill empty non-final user/assistant wire copies so the pre-call sanitizer# stops re-healing and flooding errors.log; durable history is untouched.- # After the reasoning copy so thinking-only turns keep payload (#96870).- fill_empty_non_final_wire_payload(- api_msg, is_final=(idx == len(messages) - 1)- )+ # After the reasoning copy so thinking-only turns keep payload.+ fill_empty_non_final_wire_payload(api_msg, is_final=(idx == len(messages) - 1))# _thinking_prefill survives intentionally: the drop pass below needs it.# Strip length-continuation marks; some transports keep underscore keys.api_msg.pop("_length_continuation_fragment", None)@@ -1036,24 +970,11 @@ def build_api_messages(# Strip Codex Responses fields (call_id, response_item_id): strict providers# reject unknown fields. New dicts keep the internal list intact for Codex.if agent._should_sanitize_tool_calls():- # In MoA mode agent.model is the virtual preset name; use the resolved- # aggregator so Gemini keeps thought_signature (extra_content).- _sanitize_model = agent.model- if agent.provider == "moa":- if moa_config:- _agg = moa_config.get("aggregator") or {}- if _agg.get("model"):- _sanitize_model = _agg["model"]- if _sanitize_model == agent.model:- # Virtual-provider mode: no moa_config is threaded through; ask- # the facade for the aggregator slot from the previous create().- _moa_client = getattr(agent, "client", None)- _agg_slot = getattr(_moa_client, "last_aggregator_slot", None)- if _agg_slot and _agg_slot.get("model"):- _sanitize_model = _agg_slot["model"]- agent._sanitize_tool_calls_for_strict_api(api_msg, model=_sanitize_model)- # Keep 'reasoning_details' - OpenRouter uses this for multi-turn reasoning context- # The signature field helps maintain reasoning continuity+ agent._sanitize_tool_calls_for_strict_api(+ api_msg, model=_sanitize_model_for(agent, moa_config)+ )+ # 'reasoning_details' is kept: OpenRouter uses it for multi-turn reasoning+ # continuity.api_messages.append(api_msg)# Final system message = cached prompt + ephemeral additions (API-time only).diff --git a/agent/turn_context_compaction.py b/agent/turn_context_compaction.pyindex ccd3ce050fe..e77d422a8c7 100644--- a/agent/turn_context_compaction.py+++ b/agent/turn_context_compaction.py@@ -1,12 +1,11 @@-"""Turn-start compaction for ``build_turn_context``.+"""Turn-start compaction for ``build_turn_context`` plus the small compression-attempt+helpers shared with the pre-API / post-tool sites in ``turn_preflight``.Three passes, in order: idle-triggered compaction (opt-in, wall-clock gap), preflightcontext compression (token threshold), and the uncompressed-session overflow-warningre-arm. ``run_turn_start_compaction`` mutates ``agent`` exactly as the inline prologue-did and returns a ``CompactionOutcome`` with the rebuilt locals.--Predicates and estimators that tests patch on ``agent.turn_context`` are imported-lazily through that module so the patches keep intercepting."""+did and returns a ``CompactionOutcome``. Predicates/estimators that tests patch on+``agent.turn_context`` are imported lazily through that module so patches intercept."""from __future__ import annotations@@ -38,15 +37,18 @@ class CompactionOutcome:blocked: bool = False+# ── Helpers shared by every compression-attempt site ──────────────────────────++def _clear_overflow_warn(agent: Any) -> None:- """Re-arm the context-overflow warning dedup. getattr guard: ``object.__new__``- test doubles lack the method."""+ """Re-arm the context-overflow warning dedup (test doubles may lack the method)."""_clear_warn = getattr(agent, "_clear_context_overflow_warn", None)if callable(_clear_warn):_clear_warn()def _reset_retry_state_after_compaction(agent: Any) -> None:+ """Give the compacted request a fresh chance: clear retry/empty-response state."""agent._empty_content_retries = 0agent._thinking_prefill_retries = 0agent._last_content_with_tools = None@@ -54,6 +56,40 @@ def _reset_retry_state_after_compaction(agent: Any) -> None:agent._mute_post_response = False+def _blocked_compress_reason(compressor: Any, tokens: int) -> Optional[str]:+ """Why an over-threshold request is blocked (``None`` below threshold or when the+ engine lacks ``should_compress_info`` / raises)."""+ _info = getattr(compressor, "should_compress_info", None)+ if not callable(_info):+ return None+ try:+ return _info(tokens)[1]+ except Exception:+ return None+++def _apply_grown_window(agent: Any, compressor: Any, grown: int) -> None:+ """A managed local runtime granted a bigger window: recalibrate the compressor."""+ compressor.update_model(+ agent.model, grown, base_url=getattr(agent, "base_url", "") or "",+ api_key=getattr(agent, "api_key", "") or "",+ provider=getattr(agent, "provider", "") or "",+ api_mode=getattr(agent, "api_mode", "") or "",+ )+ agent._buffer_status(+ f"📈 Context window grown to {grown // 1024}K "+ f"(local model; conversation continues uncompressed)"+ )+++def _refund_api_call(agent: Any, api_call_count: int) -> int:+ """A pass that never reached the provider refunds the call count and budget."""+ api_call_count -= 1+ agent._api_call_count = api_call_count+ agent.iteration_budget.refund()+ return api_call_count++def _reanchor(agent: Any, messages: List[Any], user_message: Any) -> int:"""Compaction rebuilt ``messages``: re-anchor this turn's user index so theapi_content stamp, injection site and persist-override row hit the same dict."""@@ -64,6 +100,9 @@ def _reanchor(agent: Any, messages: List[Any], user_message: Any) -> int:return idx+# ── Turn-start passes ─────────────────────────────────────────────────────────++def run_turn_start_compaction(agent: Any, *, messages: List[Dict[str, Any]], system_message: Optional[str],active_system_prompt: Optional[str], conversation_history: Optional[List[Dict[str, Any]]],@@ -83,10 +122,8 @@ def _idle_compaction(agent: Any, out: CompactionOutcome, system_message: Optional[str], user_message: Any,effective_task_id: str,) -> None:- """Idle-triggered compaction (opt-in; ``idle_compact_after_seconds``).-- Fires on the wall-clock gap since ``_last_activity_ts``, complementing the token- gate; a cheap gap check gates the estimate (cf. ``_should_run_preflight_estimate``)."""+ """Idle-triggered compaction (opt-in; ``idle_compact_after_seconds``): fires on the+ wall-clock gap since ``_last_activity_ts``; a cheap gap check gates the estimate."""from agent import turn_context as _tcmessages = out.messages@@ -98,12 +135,11 @@ def _idle_compaction(return_compressor = agent.context_compressor# Route-aware pressure: on compacted native-Codex sessions the durable figure- # overstates the wire; reuse the preflight estimator (#96995).+ # overstates the wire, so reuse the preflight estimator._idle_tokens = _tc._preflight_request_tokens(agent, messages, out.active_system_prompt or "")- # Post-compression target size: don't summarise a thread already below what- # compaction would reduce it to.+ # Don't summarise a thread already below the post-compression target size._idle_floor = int(_compressor.threshold_tokens * _compressor.summary_target_ratio)_idle_cooldown = getattr(_compressor, "get_active_compression_failure_cooldown", lambda: None@@ -145,7 +181,7 @@ def _idle_compaction(def _codex_native_auto_compaction(agent: Any) -> bool:"""Codex app-server threads are compacted by the codex agent itself; Hermes only- initiates compaction in "hermes" mode (#36801)."""+ initiates compaction in "hermes" mode."""return (getattr(agent, "api_mode", None) == "codex_app_server"and str(@@ -160,7 +196,7 @@ def _preflight_compression(effective_task_id: str,) -> None:"""Preflight context compression; the cheap pre-check gates the full estimate- (see ``_should_run_preflight_estimate`` for the OR semantics, #27405)."""+ (see ``_should_run_preflight_estimate`` for the OR semantics)."""from agent import turn_context as _tcagent._turn_received_provider_response = False@@ -168,17 +204,16 @@ def _preflight_compression(if not agent.compression_enabled:_rearm_uncompressed_overflow_warn(agent, out.messages, out.active_system_prompt)return+ _compressor = agent.context_compressorif _tc._review_fork_first_request_pending(agent) or not _tc._should_run_preflight_estimate(- out.messages, agent.context_compressor.protect_first_n,- agent.context_compressor.protect_last_n, agent.context_compressor.threshold_tokens,+ out.messages, _compressor.protect_first_n, _compressor.protect_last_n,+ _compressor.threshold_tokens,):return- messages = out.messages_preflight_tokens = _tc._preflight_request_tokens(- agent, messages, out.active_system_prompt or ""+ agent, out.messages, out.active_system_prompt or "")- _compressor = agent.context_compressor# getattr guard: compressor doubles and plugin engines lack this method — absence# means no snapshot and the finalizer's rollback stays disarmed._snapshot_fn = getattr(_compressor, "snapshot_preflight_display_tokens", None)@@ -188,15 +223,14 @@ def _preflight_compression(# snapshot may arm the interrupted-turn rollback.if isinstance(_snapshot_val, int) and not isinstance(_snapshot_val, bool):agent._turn_preflight_display_snapshot = _snapshot_val- _defer_preflight = getattr(+ _preflight_deferred = getattr(_compressor, "should_defer_preflight_to_real_usage", lambda _tokens: False- )- _preflight_deferred = _defer_preflight(_preflight_tokens)+ )(_preflight_tokens)_codex_native_auto = _codex_native_auto_compaction(agent)if not _preflight_deferred:# Display-only seed: a real provider reading wins and the -1 sentinel stays- # protected (#36718). Also feeds the tool-loop gate on usage-less responses.+ # protected. Also feeds the tool-loop gate on usage-less responses._maybe_seed = getattr(_compressor, "maybe_seed_preflight_display_tokens", None)if callable(_maybe_seed):_maybe_seed(_preflight_tokens)@@ -234,14 +268,7 @@ def _preflight_compression(else:_should_compress_now = _compressor.should_compress(_preflight_tokens)if not _should_compress_now:- # Over threshold but blocked: ask should_compress_info for the reason to- # surface below. getattr guard: doubles/older engines lack it.- _info = getattr(_compressor, "should_compress_info", None)- if callable(_info):- try:- _compress_block_reason = _info(_preflight_tokens)[1]- except Exception:- _compress_block_reason = None+ _compress_block_reason = _blocked_compress_reason(_compressor, _preflight_tokens)if _should_compress_now:# Managed local runtime: growing the window beats compressing (ladder order;# same seam as _maybe_grow_local_window in the loop).@@ -252,16 +279,7 @@ def _preflight_compression(except Exception:_grown = Noneif _grown:- _compressor.update_model(- agent.model, _grown, base_url=getattr(agent, "base_url", "") or "",- api_key=getattr(agent, "api_key", "") or "",- provider=getattr(agent, "provider", "") or "",- api_mode=getattr(agent, "api_mode", "") or "",- )- agent._buffer_status(- f"📈 Context window grown to {_grown // 1024}K "- f"(local model; conversation continues uncompressed)"- )+ _apply_grown_window(agent, _compressor, _grown)_should_compress_now = _compressor.should_compress(_preflight_tokens)if _should_compress_now:_run_preflight_passes(@@ -277,7 +295,7 @@ def _preflight_compression(# Sub-threshold and unblocked — re-arm the overflow warning._clear_overflow_warn(agent)# Engine maintenance only when NO skip-branch fired: cooldown, deferred- # estimate, or codex-native route keep the engine hook unconsulted (#20316).+ # estimate, or codex-native route keep the engine hook unconsulted.if not (_compression_cooldown or _preflight_deferred or _codex_native_auto):_engine_preflight_maintenance(agent, out, _compressor, _preflight_tokens, system_message, effective_task_id@@ -329,8 +347,8 @@ def _run_preflight_passes(task_id=effective_task_id,)if out.messages is _preflight_input and compression_skipped_due_to_lock(agent):- # Lock-skip (#69870): another path holds the lock, so this is a DEFER, not- # proof of incompressibility — don't arm the blocker; stop passes this turn.+ # Lock-skip: another path holds the lock, so this is a DEFER, not proof of+ # incompressibility — don't arm the blocker; stop passes this turn.logger.info("Preflight compression deferred: compression lock ""held by another path (session %s)",@@ -338,7 +356,7 @@ def _run_preflight_passes()break# Re-estimate so size-only compression (same rows, fewer tokens) counts as- # progress (#39548).+ # progress._preflight_tokens = _tc._preflight_request_tokens(agent, out.messages, out.active_system_prompt or "")@@ -370,7 +388,7 @@ def _engine_preflight_maintenance(agent: Any, out: CompactionOutcome, _compressor: Any, _preflight_tokens: int,system_message: Optional[str], effective_task_id: str,) -> None:- """Engine-driven sub-threshold preflight maintenance (#20316): engines overriding+ """Engine-driven sub-threshold preflight maintenance: engines overriding``should_compress_preflight()`` get exactly ONE ``compress()`` pass; a no-op nevertouches ``blocked``."""_engine_preflight = getattr(_compressor, "should_compress_preflight", None)@@ -379,8 +397,7 @@ def _engine_preflight_maintenance(try:_wants_engine_preflight = bool(_engine_preflight(out.messages))except Exception as _preflight_exc:- # A buggy engine must never break an otherwise-healthy turn: swallow at debug- # level and skip maintenance.+ # A buggy engine must never break an otherwise-healthy turn.logger.debug("should_compress_preflight raised %s; skipping ""engine-driven preflight maintenance",@@ -412,8 +429,8 @@ def _engine_preflight_maintenance(def _rearm_uncompressed_overflow_warn(agent: Any, messages: List[Any], active_system_prompt: Optional[str]) -> None:- """Uncompressed session guard (#89297): the warning fires from the loop's pre-API- site; here we only RE-ARM the dedup once back under the window."""+ """Uncompressed session guard: the warning fires from the loop's pre-API site;+ here we only RE-ARM the dedup once back under the window."""from agent import turn_context as _tc_ctx_len = getattr(getattr(agent, "context_compressor", None), "context_length", None)@@ -427,18 +444,17 @@ def _rearm_uncompressed_overflow_warn(if isinstance(_c, str):_raw_chars += len(_c)elif _c:- # Non-string, non-empty content defeats a char count — force the real- # estimate. None/"" contribute nothing.+ # Non-string, non-empty (multimodal) content defeats a char count — force+ # the real estimate. None/"" contribute nothing._raw_chars = _ctx_len + 1break- # Cheap gate: raw text under ~1/4 of the window (4 chars/token) cannot be over it;- # non-string (multimodal) content forces the real estimate.+ # Cheap gate: raw text under ~1/4 of the window (4 chars/token) cannot be over it.if _raw_chars <= _ctx_len:_clear_overflow_warn(agent)return# Re-arm with the same route-aware (checkpoint-pruned wire) figure the warn site# measures, else a compacted session never clears the dedup and genuine overflow- # warnings stay suppressed (#96995/#97602).+ # warnings stay suppressed._uncompressed_tokens = _tc._preflight_request_tokens(agent, messages, active_system_prompt or "")diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex 210ae3da740..5b6953aecc3 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -1,24 +1,22 @@"""Outer-iteration bookkeeping for the conversation turn loop, in call order:-``begin_iteration`` (pending redirect, interrupt / review-budget / iteration-budget exits),``prepare_iteration`` (``agent:step`` callback, skill-nudge counter, pre-API ``/steer`` drain-into the newest tool result — never a user message, alternation — run-budget wrap-up notice,-tool_call argument sanitization, legacy interrupt-scaffold ghost-row drop, role-alternation-repair), ``announce_api_call`` (verbose summary / quiet thinking spinner) and, after the retry-loop, ``apply_retry_restarts`` (consumes the ``TurnRetryState`` restart flags). Extracted from-``run_conversation``; nothing here imports ``agent.conversation_loop`` at module level (cycle).-"""+into the newest tool result — never a user message —, run-budget wrap-up notice, tool_call+argument sanitization, interrupt-scaffold ghost-row drop, role-alternation repair),+``announce_api_call`` (verbose summary / quiet spinner) and, after the retry loop,+``apply_retry_restarts`` (consumes the ``TurnRetryState`` restart flags). Nothing here+imports ``agent.conversation_loop`` at module level (cycle)."""from __future__ import annotations-from dataclasses import dataclassimport loggingimport random-from typing import Any, Dict, Optional+from dataclasses import dataclass+from typing import Any, Dictfrom agent.display import KawaiiSpinner-from agent.turn_context import reanchor_current_turn_user_idx+logger = logging.getLogger("agent.conversation_loop")@@ -40,97 +38,28 @@ def prepare_iteration(agent: Any,*, messages: Any, api_call_count: Any) -> Itera_INTERRUPT_SCAFFOLD_MARKER, _maybe_inject_run_budget_wrapup)- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> IterationPrep:- return IterationPrep(- action=action,- messages=messages,- request_logger=request_logger,-- )-- # Fire step_callback for gateway hooks (agent:step event)+ # Fire step_callback for gateway hooks (agent:step event).if agent.step_callback is not None:try:- prev_tools = []- for _idx, _m in enumerate(reversed(messages)):- if _m.get("role") == "assistant" and _m.get("tool_calls"):- _fwd_start = len(messages) - _idx- _results_by_id = {}- for _tm in messages[_fwd_start:]:- if _tm.get("role") != "tool":- break- _tcid = _tm.get("tool_call_id")- if _tcid:- _results_by_id[_tcid] = _tm.get("content", "")- prev_tools = [- {- "name": tc["function"]["name"],- "result": _results_by_id.get(tc.get("id")),- "arguments": tc["function"].get("arguments"),- }- for tc in _m["tool_calls"]- if isinstance(tc, dict)- ]- break- agent.step_callback(api_call_count, prev_tools)+ agent.step_callback(api_call_count, _previous_tool_round(messages))except Exception as _step_err:logger.debug("step_callback error (iteration %s): %s", api_call_count, _step_err)- # Track tool-calling iterations for skill nudge.- # Counter resets whenever skill_manage is actually used.- if (agent._skill_nudge_interval > 0- and "skill_manage" in agent.valid_tool_names):+ # Tool-calling iterations for the skill nudge; resets whenever skill_manage is used.+ if agent._skill_nudge_interval > 0 and "skill_manage" in agent.valid_tool_names:agent._iters_since_skill += 1- # ── Pre-API-call /steer drain ──────────────────────────────────# Drain a /steer sent during the last API call into the newest tool message so# it lands THIS iteration. Never put in a user message (breaks alternation)._pre_api_steer = agent._drain_pending_steer()if _pre_api_steer:- _injected = False- for _si in range(len(messages) - 1, -1, -1):- _sm = messages[_si]- if isinstance(_sm, dict) and _sm.get("role") == "tool":- from agent.prompt_builder import format_steer_marker- marker = format_steer_marker(_pre_api_steer)- existing = _sm.get("content", "")- if isinstance(existing, str):- _sm["content"] = existing + marker- else:- # Multimodal content blocks — append text block- try:- blocks = list(existing) if existing else []- blocks.append({"type": "text", "text": marker})- _sm["content"] = blocks- except Exception:- pass- _injected = True- logger.debug(- "Pre-API-call steer drain: injected into tool msg at index %d", _si- )- break- if not _injected:- # No tool message to inject into — put it back so- # the post-tool-execution drain picks it up later.- _lock = getattr(agent, "_pending_steer_lock", None)- if _lock is not None:- with _lock:- if agent._pending_steer:- agent._pending_steer = agent._pending_steer + "\n" + _pre_api_steer- else:- agent._pending_steer = _pre_api_steer- else:- existing = getattr(agent, "_pending_steer", None)- agent._pending_steer = (existing + "\n" + _pre_api_steer) if existing else _pre_api_steer+ _inject_steer_into_newest_tool_result(agent, messages, _pre_api_steer)- # ── Wall-clock run-budget wrap-up notice ───────────────────────- # One-shot at 80% of agent.run_budget_seconds: ask the model to wrap up via the+ # One-shot run-budget wrap-up notice at 80% of agent.run_budget_seconds, via the# same cache-safe channel as /steer (newest tool result); off with no budget.if getattr(agent, "run_budget_seconds", None):_maybe_inject_run_budget_wrapup(agent, messages)- # Reasoning lives in content via <think> tags for trajectory storage, but some- # providers (Moonshot) also need a 'reasoning_content' field; handle both here.request_logger = getattr(agent, "logger", None) or logger # same name as the origin module# Per-agent validation cursor skips re-parsing tool_call args already validated.# Identity-keyed; a rewritten list breaks the prefix match and forces a re-scan.@@ -152,28 +81,22 @@ def prepare_iteration(agent: Any,*, messages: Any, api_call_count: Any) -> Itera)# Drop legacy hidden assistant placeholders carrying the raw interrupt scaffold- # before repair: replayed, the model echoes/self-replicates (#81841).- messages = [- msg for msg in messages- if not (+ # before repair: replayed, the model echoes/self-replicates.+ def _is_scaffold_ghost(msg: Dict[str, Any]) -> bool:+ return (msg.get("display_kind") == "hidden"and msg.get("role") == "assistant"- and (- (- isinstance(msg.get("content"), str)- and msg["content"].strip() == _INTERRUPT_SCAFFOLD_MARKER- )- or (- isinstance(msg.get("api_content"), str)- and msg["api_content"].strip() == _INTERRUPT_SCAFFOLD_MARKER- )+ and any(+ isinstance(msg.get(k), str) and msg[k].strip() == _INTERRUPT_SCAFFOLD_MARKER+ for k in ("content", "api_content")))- ]++ messages = [msg for msg in messages if not _is_scaffold_ghost(msg)]# Repair malformed role alternation (tool→user / user→user tails): providers# return empty content on them and the empty-retry loop spins. The _with_cursor- # variant also recomputes the SessionDB flush cursor after compaction (#44837).+ # variant also recomputes the SessionDB flush cursor after compaction.from agent.agent_runtime_helpers import repair_message_sequence_with_cursorrepaired_seq = repair_message_sequence_with_cursor(agent, messages)if repaired_seq > 0:@@ -182,7 +105,65 @@ def prepare_iteration(agent: Any,*, messages: Any, api_call_count: Any) -> Iterarepaired_seq,agent.session_id or "-",)- return _verdict("fallthrough")+ return IterationPrep(action="fallthrough", messages=messages, request_logger=request_logger)+++def _previous_tool_round(messages: Any) -> list:+ """The newest assistant tool_calls batch with each call's result, for ``agent:step``."""+ for _idx, _m in enumerate(reversed(messages)):+ if _m.get("role") == "assistant" and _m.get("tool_calls"):+ _results_by_id = {}+ for _tm in messages[len(messages) - _idx:]:+ if _tm.get("role") != "tool":+ break+ _tcid = _tm.get("tool_call_id")+ if _tcid:+ _results_by_id[_tcid] = _tm.get("content", "")+ return [+ {+ "name": tc["function"]["name"],+ "result": _results_by_id.get(tc.get("id")),+ "arguments": tc["function"].get("arguments"),+ }+ for tc in _m["tool_calls"]+ if isinstance(tc, dict)+ ]+ return []+++def _inject_steer_into_newest_tool_result(agent: Any, messages: Any, steer_text: str) -> None:+ """Append the steer marker to the newest tool message; with no tool message, put the+ text back so the post-tool-execution drain delivers it later."""+ for _si in range(len(messages) - 1, -1, -1):+ _sm = messages[_si]+ if isinstance(_sm, dict) and _sm.get("role") == "tool":+ from agent.prompt_builder import format_steer_marker+ marker = format_steer_marker(steer_text)+ existing = _sm.get("content", "")+ if isinstance(existing, str):+ _sm["content"] = existing + marker+ else:+ # Multimodal content blocks — append a text block.+ try:+ blocks = list(existing) if existing else []+ blocks.append({"type": "text", "text": marker})+ _sm["content"] = blocks+ except Exception:+ pass+ logger.debug(+ "Pre-API-call steer drain: injected into tool msg at index %d", _si+ )+ return+ _lock = getattr(agent, "_pending_steer_lock", None)+ if _lock is not None:+ with _lock:+ if agent._pending_steer:+ agent._pending_steer = agent._pending_steer + "\n" + steer_text+ else:+ agent._pending_steer = steer_text+ else:+ existing = getattr(agent, "_pending_steer", None)+ agent._pending_steer = (existing + "\n" + steer_text) if existing else steer_text@dataclass@@ -199,18 +180,7 @@ def announce_api_call(total_chars: Any,) -> ApiCallAnnouncement:"""Print the request summary (verbose) or start the quiet-mode thinking indicator."""--- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> ApiCallAnnouncement:- return ApiCallAnnouncement(- action=action,- thinking_spinner=thinking_spinner,-- )-- # Thinking spinner for quiet mode (animated during API call)thinking_spinner = None-if not agent.quiet_mode:agent._vprint(f"\n{agent.log_prefix}🔄 Making API call #{api_call_count}/{agent.max_iterations}...")agent._vprint(f"{agent.log_prefix} 📊 Request size: {len(api_messages)} messages, ~{approx_tokens:,} tokens (~{total_chars:,} chars)")@@ -235,7 +205,7 @@ def announce_api_call(logging.debug(f"API Request - Model: {agent.model}, Messages: {len(messages)}, Tools: {len(agent.tools) if agent.tools else 0}")logging.debug(f"Last message role: {messages[-1]['role'] if messages else 'none'}")logging.debug(f"Total message size: ~{approx_tokens:,} tokens")- return _verdict("fallthrough")+ return ApiCallAnnouncement(action="fallthrough", thinking_spinner=thinking_spinner)@dataclass@@ -261,14 +231,11 @@ def begin_iteration(_apply_active_turn_redirect, _review_input_budget_exhausted)- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> IterationStart:+ def _verdict(action: str) -> IterationStart:return IterationStart(- action=action,- original_user_message=original_user_message,- api_call_count=api_call_count,- interrupted=interrupted,+ action=action, original_user_message=original_user_message,+ api_call_count=api_call_count, interrupted=interrupted,_turn_exit_reason=_turn_exit_reason,-)_redirect_text = agent._drain_pending_redirect()@@ -280,10 +247,9 @@ def begin_iteration()agent._persist_session(messages, conversation_history)- # Reset per-turn checkpoint dedup so each iteration can take one snapshot+ # Reset per-turn checkpoint dedup so each iteration can take one snapshot.agent._checkpoint_mgr.new_turn()- # Check for interrupt request (e.g., user sent new message)if agent._interrupt_requested:interrupted = True_turn_exit_reason = "interrupted_by_user"@@ -291,9 +257,8 @@ def begin_iteration(agent._safe_print("\n⚡ Breaking out of tool loop due to interrupt...")return _verdict("break")- # Aggregate input budget for detached auxiliary forks: bounds the whole review,- # not each request. Checked between iterations so the crossing request's writes- # have landed, mirroring the iteration-budget exit (#93057).+ # Aggregate input budget for detached auxiliary forks bounds the whole review, not+ # each request; checked between iterations so the crossing request's writes landed.if _review_input_budget_exhausted(agent):_turn_exit_reason = "review_input_budget_exhausted"if not agent.quiet_mode:@@ -350,16 +315,12 @@ def apply_retry_restarts(_HANDOFF_SKIP_FINAL_RESPONSE, _should_skip_model_call_for_reference_handoff)- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> RetryRestartVerdict:+ def _verdict(action: str) -> RetryRestartVerdict:return RetryRestartVerdict(- action=action,- current_turn_user_idx=current_turn_user_idx,- final_response=final_response,- retry_count=retry_count,- api_call_count=api_call_count,+ action=action, current_turn_user_idx=current_turn_user_idx,+ final_response=final_response, retry_count=retry_count, api_call_count=api_call_count,_preflight_compression_blocked=_preflight_compression_blocked,_turn_exit_reason=_turn_exit_reason,-)if _retry.restart_with_redirected_messages:@@ -370,7 +331,6 @@ def apply_retry_restarts(_retry.restart_with_redirected_messages = Falsereturn _verdict("continue")- # If the API call was interrupted, skip response processingif interrupted:_turn_exit_reason = "interrupted_during_api_call"return _verdict("break")@@ -396,9 +356,7 @@ def apply_retry_restarts(# In-loop compression rebuilt `messages`; re-anchor the current-turn index# like the prologue, AFTER the handoff guard (it may re-append this turn's# ask). A stale anchor injects prefetch into a historical row.- current_turn_user_idx = reanchor_current_turn_user_idx(- messages, user_message- )+ current_turn_user_idx = reanchor_current_turn_user_idx(messages, user_message)agent._persist_user_message_idx = current_turn_user_idxreturn _verdict("continue")@@ -409,8 +367,7 @@ def apply_retry_restarts(agent.iteration_budget.refund()_retry.restart_with_rebuilt_messages = False# Failover shrank the compressor window: clear the preflight block so- # preflight re-runs before the first fallback call. Hoisted to the single- # consumer. (#84733)+ # preflight re-runs before the first fallback call (single consumer)._preflight_compression_blocked = Falsereturn _verdict("continue")@@ -418,8 +375,7 @@ def apply_retry_restarts(# Boost output budget per retry: 2×, 4×, 8×, 16× base, capped at 32 768, via# _ephemeral_max_output_tokens. Keep a larger original provider/model# default as the floor so retries never downshift.- _boost_base = agent.max_tokens if agent.max_tokens else 4096- _boost = _boost_base * (2 ** length_continue_retries)+ _boost = (agent.max_tokens or 4096) * (2 ** length_continue_retries)_requested_cap = agent._requested_output_cap_from_api_kwargs(api_kwargs)if _requested_cap is not None:_boost = max(_boost, _requested_cap)diff --git a/agent/turn_preflight.py b/agent/turn_preflight.pyindex ec2185e9b49..a1096f788db 100644--- a/agent/turn_preflight.py+++ b/agent/turn_preflight.py@@ -1,12 +1,11 @@-"""Pre-API preflight compression gate for the conversation turn loop.+"""Pre-API preflight compression gate and post-tool compression for the turn loop.-Extracted from ``run_conversation``. Runs once per API call after the request pressure-is measured: grow a managed llama.cpp window (last resort), or compress when over-threshold (deferring on noisy estimates, in failure cooldown, or when the review fork's-first request is pending), handle the provider-proven overflow re-check fail-closed,-and emit the deduped blocked/uncompressed overflow warnings. Nothing here imports-``agent.conversation_loop`` at module level (cycle); loop-internal helpers resolve lazily.-"""+Runs once per API call after the request pressure is measured: grow a managed llama.cpp+window (last resort), or compress when over threshold (deferring on noisy estimates, in+failure cooldown, or while the review fork's first request is pending), handle the+provider-proven overflow re-check fail-closed, and emit the deduped blocked/uncompressed+overflow warnings. Nothing here imports ``agent.conversation_loop`` at module level+(cycle); loop-internal helpers resolve lazily."""from __future__ import annotations@@ -21,281 +20,212 @@ from agent.conversation_compression import (conversation_history_after_compression,)from agent.turn_context import _review_fork_first_request_pending+from agent.turn_context_compaction import (+ _apply_grown_window, _blocked_compress_reason, _clear_overflow_warn, _refund_api_call,+ _reset_retry_state_after_compaction,+)logger = logging.getLogger("agent.conversation_loop")@dataclass-class PreflightVerdict:- """Outcome of ``run_preflight_compression``.-- ``action``: ``"proceed"`` (make the API call), ``"continue"`` (window grown or+class PreflightGateVerdict:+ """``action``: ``"fallthrough"`` (make the API call), ``"continue"`` (window grown orhistory compacted — the call/budget was refunded, re-enter the turn loop and- re-measure), ``"break"`` (turn ends: compression timeout or non-actionable- compaction handoff — ``final_response``/``failed``/``turn_exit_reason`` set) or- ``"return"`` (typed deferred/exhausted result in ``result``). The remaining fields- are the loop locals the gate may have rebound."""+ re-measure), ``"break"`` (turn ends: compression timeout or non-actionable compaction+ handoff — ``final_response``/``failed``/``_turn_exit_reason`` set) or ``"return"``+ (``result`` is the turn's result dict). The other fields are the loop locals the gate+ rebinds; ``_last_preflight_pressure`` is re-armed only by a compression pass."""action: str- result: Optional[Dict[str, Any]]- messages: List[Dict[str, Any]]+ pending_moa_prepared_request: Any+ messages: Anyactive_system_prompt: Anyconversation_history: Any- api_call_count: int- compression_attempts: int- pending_moa_prepared_request: Any- last_preflight_pressure: Optional[int]+ api_call_count: Any+ compression_attempts: Anyfinal_response: Any- failed: bool- compression_timeout_exhausted: bool- turn_exit_reason: Any+ failed: Any+ _turn_exit_reason: Any+ _compression_timeout_exhausted: Any+ _preflight_compression_blocked: Any+ _provider_overflow_recovery_pending: Any+ _last_preflight_pressure: Any+ result: Optional[Dict[str, Any]] = Nonedef run_preflight_compression(- agent: Any, *, compressor: Any, request_pressure_tokens: int, provider_overflow_preflight: bool,- preflight_compression_blocked: bool, defer_preflight: Any, moa_prepared_request: Any,- pending_moa_prepared_request: Any, messages: List[Dict[str, Any]], system_message: Any,- user_message: Any, active_system_prompt: Any, conversation_history: Any, api_call_count: int,- compression_attempts: int, max_compression_attempts: int, effective_task_id: Any,- final_response: Any, failed: bool, compression_timeout_exhausted: bool, turn_exit_reason: Any,-) -> PreflightVerdict:+ agent: Any, v: PreflightGateVerdict, *, compressor: Any, request_pressure_tokens: int,+ provider_overflow_preflight: bool, defer_preflight: Any, moa_prepared_request: Any,+ system_message: Any, user_message: Any, max_compression_attempts: int, effective_task_id: Any,+) -> PreflightGateVerdict:"""Mirror of the turn-prologue guard chain (defer on noisy estimate → skip in failure- cooldown → ``should_compress``), #11529. A compression pass that never reaches the- provider refunds the call/budget in every branch (skip, re-run, timeout) so- ``api_call_count`` never over-reports; a lock/transient skip refunds the attempt and- leaves the progress blocker unarmed (#69870, #97488). A forced provider-overflow- preflight that any gate blocks fails closed (llama.cpp may silently truncate)."""+ cooldown → ``should_compress``), rebinding the loop locals on ``v`` and setting+ ``v.action``. A compression pass that never reaches the provider refunds the+ call/budget in every branch (skip, re-run, timeout) so ``api_call_count`` never+ over-reports; a lock/transient skip refunds the attempt and leaves the progress+ blocker unarmed. A forced provider-overflow preflight that any gate blocks fails+ closed (llama.cpp may silently truncate)."""from agent.conversation_loop import (_COMPRESSION_TIMEOUT_FINAL_RESPONSE, _HANDOFF_SKIP_FINAL_RESPONSE,_compression_deferred_result, _maybe_grow_local_window, _provider_overflow_exhausted_result,_should_skip_model_call_for_reference_handoff,)- _compressor = compressor- _provider_overflow_preflight = provider_overflow_preflight- _preflight_compression_blocked = preflight_compression_blocked- _defer_preflight = defer_preflight- _moa_prepared_request = moa_prepared_request- _last_preflight_pressure = None- _compression_timeout_exhausted = compression_timeout_exhausted- _turn_exit_reason = turn_exit_reason+ def _done(action: str, result: Optional[Dict[str, Any]] = None) -> PreflightGateVerdict:+ v.action, v.result = action, result+ return v- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> PreflightVerdict:- return PreflightVerdict(- action=action, result=result, messages=messages,- active_system_prompt=active_system_prompt, conversation_history=conversation_history,- api_call_count=api_call_count, compression_attempts=compression_attempts,- pending_moa_prepared_request=pending_moa_prepared_request,- last_preflight_pressure=_last_preflight_pressure, final_response=final_response,- failed=failed, compression_timeout_exhausted=_compression_timeout_exhausted,- turn_exit_reason=_turn_exit_reason,+ def _exhausted_result() -> Dict[str, Any]:+ return _provider_overflow_exhausted_result(+ agent, v.messages, v.conversation_history, v.api_call_count, request_pressure_tokens,+ max_compression_attempts,)_compression_cooldown = getattr(- _compressor, "get_active_compression_failure_cooldown", lambda: None+ compressor, "get_active_compression_failure_cooldown", lambda: None)()- if (+ _eligible = (agent.compression_enabled+ and len(v.messages) > 1+ and v.compression_attempts < max_compression_attempts+ )+ if (+ _eligibleand not _review_fork_first_request_pending(agent)- and len(messages) > 1- and compression_attempts < max_compression_attempts- and (- not _preflight_compression_blocked or _provider_overflow_preflight- )- and (- not _defer_preflight(request_pressure_tokens) or _provider_overflow_preflight- )+ and (not v._preflight_compression_blocked or provider_overflow_preflight)+ and (not defer_preflight(request_pressure_tokens) or provider_overflow_preflight)and not _compression_cooldown- and _compressor.should_compress(request_pressure_tokens)+ and compressor.should_compress(request_pressure_tokens)):# Managed local runtime: grow the context window before compressing (last# resort). Only for a llamacpp provider at the supervised base_url.- _grown_window = _maybe_grow_local_window(- agent, _compressor, request_pressure_tokens- )+ _grown_window = _maybe_grow_local_window(agent, compressor, request_pressure_tokens)if _grown_window:- # Bigger window granted: recalibrate the compressor and skip compression- # this pass.- _compressor.update_model(- agent.model, _grown_window, base_url=getattr(agent, "base_url", "") or "",- api_key=getattr(agent, "api_key", "") or "",- provider=getattr(agent, "provider", "") or "",- api_mode=getattr(agent, "api_mode", "") or "",- )- agent._buffer_status(- f"📈 Context window grown to {_grown_window // 1024}K "- f"(local model; conversation continues uncompressed)"- )- # Never reached the provider — refund the call/budget like the- # compression path does before its continue.- api_call_count -= 1- agent._api_call_count = api_call_count- agent.iteration_budget.refund()- return _verdict("continue")- if _moa_prepared_request is not None:- pending_moa_prepared_request = _moa_prepared_request- compression_attempts += 1+ # Bigger window granted: recalibrate and skip compression this pass. Never+ # reached the provider — refund like the compression path does.+ _apply_grown_window(agent, compressor, _grown_window)+ v.api_call_count = _refund_api_call(agent, v.api_call_count)+ return _done("continue")+ if moa_prepared_request is not None:+ v.pending_moa_prepared_request = moa_prepared_request+ v.compression_attempts += 1# Compression is running: reset the blocked-overflow warning dedup so a- # later blocked turn warns again (#62625). getattr: test doubles lack it.- _clear_warn = getattr(agent, "_clear_context_overflow_warn", None)- if callable(_clear_warn):- _clear_warn()+ # later blocked turn warns again.+ _clear_overflow_warn(agent)+ _threshold = int(getattr(compressor, "threshold_tokens", 0) or 0)+ _context_length = int(getattr(compressor, "context_length", 0) or 0)logger.info("Pre-API compression: ~%s request tokens >= %s threshold ""(context=%s, attempt=%s/%s)",f"{request_pressure_tokens:,}",- f"{int(getattr(_compressor, 'threshold_tokens', 0) or 0):,}",- f"{int(getattr(_compressor, 'context_length', 0) or 0):,}"- if getattr(_compressor, "context_length", 0) else "unknown",- compression_attempts,+ f"{_threshold:,}",+ f"{_context_length:,}" if getattr(compressor, "context_length", 0) else "unknown",+ v.compression_attempts,max_compression_attempts,)_pre_api_status = automatic_compaction_status_message(- _compressor,+ compressor,phase="pre_api",default_message=PRE_API_COMPRESSION_STATUS_TEMPLATE.format(tokens=request_pressure_tokens),approx_tokens=request_pressure_tokens,- threshold_tokens=int(- getattr(_compressor, "threshold_tokens", 0) or 0- ),- context_length=int(- getattr(_compressor, "context_length", 0) or 0- ),+ threshold_tokens=_threshold,+ context_length=_context_length,model=agent.model,- attempt=compression_attempts,+ attempt=v.compression_attempts,max_attempts=max_compression_attempts,)if _pre_api_status:agent._emit_status(_pre_api_status)- _last_preflight_pressure = request_pressure_tokens- _pre_api_input = messages- messages, active_system_prompt = agent._compress_context(- messages, system_message, approx_tokens=request_pressure_tokens,+ v._last_preflight_pressure = request_pressure_tokens+ _pre_api_input = v.messages+ v.messages, v.active_system_prompt = agent._compress_context(+ v.messages, system_message, approx_tokens=request_pressure_tokens,task_id=effective_task_id,)if context_compression_timed_out(agent):- # Progress-aware timeout (#98722): never reached the provider — refund- # the call/budget and stop; an overflow retry would only re-compress.- api_call_count -= 1- agent._api_call_count = api_call_count- agent.iteration_budget.refund()- final_response = _COMPRESSION_TIMEOUT_FINAL_RESPONSE- failed = True- _compression_timeout_exhausted = True- _turn_exit_reason = "context_compression_timeout"- return _verdict("break")- if messages is _pre_api_input and (+ # Progress-aware timeout: never reached the provider — refund the+ # call/budget and stop; an overflow retry would only re-compress.+ v.api_call_count = _refund_api_call(agent, v.api_call_count)+ v.final_response = _COMPRESSION_TIMEOUT_FINAL_RESPONSE+ v.failed = True+ v._compression_timeout_exhausted = True+ v._turn_exit_reason = "context_compression_timeout"+ return _done("break")+ if v.messages is _pre_api_input and (compression_skipped_due_to_lock(agent) or compression_blocked_transiently(agent)):- # Temporary DEFER (lock held / cooldown), not evidence about- # compressibility: refund the attempt, leave the progress blocker- # unarmed and proceed (#69870, #97488).- compression_attempts -= 1- _last_preflight_pressure = None- if pending_moa_prepared_request is _moa_prepared_request:- pending_moa_prepared_request = None+ # Temporary DEFER (lock held / cooldown), not evidence about compressibility:+ # refund the attempt, leave the progress blocker unarmed and proceed.+ v.compression_attempts -= 1+ v._last_preflight_pressure = None+ if v.pending_moa_prepared_request is moa_prepared_request:+ v.pending_moa_prepared_request = Noneelse:- # Reset retry/empty-response state so the compacted request gets a fresh- # chance.- agent._empty_content_retries = 0- agent._thinking_prefill_retries = 0- agent._last_content_with_tools = None- agent._last_content_tools_all_housekeeping = False- agent._mute_post_response = False+ _reset_retry_state_after_compaction(agent)# Re-baseline the flush cursor: rotation returns None (child flushes# whole); in-place returns list(messages) — None would re-append# persisted rows. See conversation_history_after_compression().- conversation_history = conversation_history_after_compression(- agent, messages, conversation_history+ v.conversation_history = conversation_history_after_compression(+ agent, v.messages, v.conversation_history)# Never reaches the provider on skip or re-run — refund the call/budget# in BOTH cases, else budget leaks and api_call_count over-reports.- api_call_count -= 1- agent._api_call_count = api_call_count- agent.iteration_budget.refund()- if _should_skip_model_call_for_reference_handoff(- messages, user_message- ):- # Reference-only handoff must not become the active turn- # after a completed assistant response (#80622).+ v.api_call_count = _refund_api_call(agent, v.api_call_count)+ if _should_skip_model_call_for_reference_handoff(v.messages, user_message):+ # Reference-only handoff must not become the active turn after a+ # completed assistant response.logger.info("Skipping post-compaction model call: reference-only ""handoff would be the sole active user turn (#80622)")- if not final_response:- final_response = _HANDOFF_SKIP_FINAL_RESPONSE- _turn_exit_reason = "compaction_handoff_not_actionable"- return _verdict("break")- return _verdict("continue")- elif _provider_overflow_preflight and _compression_cooldown:+ if not v.final_response:+ v.final_response = _HANDOFF_SKIP_FINAL_RESPONSE+ v._turn_exit_reason = "compaction_handoff_not_actionable"+ return _done("break")+ return _done("continue")+ elif provider_overflow_preflight and _compression_cooldown:# Provider proved the request cannot fit and the compressor is unavailable:# don't resend; let the next user turn retry after cooldown.- agent._persist_session(messages, conversation_history)- return _verdict("return", _compression_deferred_result(- agent, messages, api_call_count, reason="transient_block"+ agent._persist_session(v.messages, v.conversation_history)+ return _done("return", _compression_deferred_result(+ agent, v.messages, v.api_call_count, reason="transient_block"))- elif (- _provider_overflow_preflight and compression_attempts >= max_compression_attempts- ):+ elif provider_overflow_preflight and v.compression_attempts >= max_compression_attempts:# All recovery passes consumed and still over threshold: fail closed —# llama.cpp may silently truncate an oversized retry.- return _verdict("return", _provider_overflow_exhausted_result(- agent, messages, conversation_history, api_call_count, request_pressure_tokens,- max_compression_attempts,- ))- elif (- agent.compression_enabled- and len(messages) > 1- and compression_attempts < max_compression_attempts- and not _defer_preflight(request_pressure_tokens)- and _compression_cooldown- ):+ return _done("return", _exhausted_result())+ elif _eligible and not defer_preflight(request_pressure_tokens) and _compression_cooldown:# Summary-LLM cooldown blocks compression: deduped warning only when over- # threshold (should_compress_info reason is None below it) (#62625).- _block_reason = None- try:- _block_reason = _compressor.should_compress_info(- request_pressure_tokens- )[1]- except Exception:- _block_reason = None+ # threshold (should_compress_info reason is None below it).+ _block_reason = _blocked_compress_reason(compressor, request_pressure_tokens)if _block_reason:agent._warn_context_overflow_blocked(_block_reason, request_pressure_tokens,- int(getattr(_compressor, "threshold_tokens", 0) or 0),- )- elif not agent.compression_enabled and len(messages) > 1:- # Uncompressed session guard (#89297): compression is disabled, so warn- # (deduped) when the request exceeds the context window; the turn-context- # preflight re-arms the dedup.- _ctx_len = getattr(- getattr(agent, "context_compressor", None), "context_length", None- )- if (- isinstance(_ctx_len, int) and _ctx_len > 0 and request_pressure_tokens > _ctx_len- ):- _warn_fn = getattr(- agent, "_warn_uncompressed_context_overflow", None+ int(getattr(compressor, "threshold_tokens", 0) or 0),)+ elif not agent.compression_enabled and len(v.messages) > 1:+ # Uncompressed session guard: compression is disabled, so warn (deduped) when+ # the request exceeds the context window; the turn-context preflight re-arms.+ _ctx_len = getattr(getattr(agent, "context_compressor", None), "context_length", None)+ if isinstance(_ctx_len, int) and _ctx_len > 0 and request_pressure_tokens > _ctx_len:+ _warn_fn = getattr(agent, "_warn_uncompressed_context_overflow", None)if callable(_warn_fn):_warn_fn(request_pressure_tokens, _ctx_len)- if _provider_overflow_preflight:+ if provider_overflow_preflight:# Any other gate blocking the forced preflight (e.g. uncompressible one-# message request) must fail closed: the request is proven not to fit.- return _verdict("return", _provider_overflow_exhausted_result(- agent, messages, conversation_history, api_call_count, request_pressure_tokens,- max_compression_attempts,- ))- return _verdict("proceed")+ return _done("return", _exhausted_result())+ return _done("fallthrough")@dataclassclass PostToolCompressionVerdict:"""``end_turn`` True → a reference-only compaction handoff would be the sole active- user turn (#80622): stop without another model call (``final_response`` /+ user turn: stop without another model call (``final_response`` /``turn_exit_reason`` set)."""end_turn: bool@@ -314,48 +244,39 @@ def compress_after_tool_results(turn_exit_reason: Any,) -> PostToolCompressionVerdict:"""Post-tool-call compression decision. Pressure comes from API-reported- ``prompt_tokens`` (a tight lower bound; thinking models inflate completion tokens,- #12026), ``0`` right after compression (no real count yet), else the route-aware- overhead-inclusive estimate (#14695). Over threshold but blocked → deduped warning- (#62625) plus the deterministic tool-result-only prune, committed only when the- engine returns a NEW list (never rebuild ``conversation_history`` for it)."""+ ``prompt_tokens`` (a tight lower bound; thinking models inflate completion tokens),+ ``0`` right after compression (no real count yet), else the route-aware+ overhead-inclusive estimate. Over threshold but blocked → deduped warning plus the+ deterministic tool-result-only prune, committed only when the engine returns a NEW+ list (never rebuild ``conversation_history`` for it)."""from agent.conversation_loop import (_HANDOFF_SKIP_FINAL_RESPONSE, _midturn_request_pressure_tokens,_should_skip_model_call_for_reference_handoff, estimate_request_tokens_rough,)- _turn_exit_reason = turn_exit_reason-def _verdict(end_turn: bool) -> PostToolCompressionVerdict:return PostToolCompressionVerdict(end_turn=end_turn, messages=messages, active_system_prompt=active_system_prompt,conversation_history=conversation_history, compression_attempts=compression_attempts,- final_response=final_response, turn_exit_reason=_turn_exit_reason,+ final_response=final_response, turn_exit_reason=turn_exit_reason,)- # Decide compression from API-reported prompt tokens (tight lower bound;- # tool results get counted on the next call). If last_prompt_tokens is 0- # (disconnect / no usage data) fall back to a rough estimate. (#2153)_compressor = agent.context_compressorif _compressor.last_prompt_tokens > 0:# Only prompt_tokens: thinking models inflate completion_tokens with- # reasoning that uses no context → premature compression. (#12026)+ # reasoning that uses no context → premature compression._real_tokens = _compressor.last_prompt_tokenselif _compressor.last_prompt_tokens == -1:# Compression just ran, no API prompt count yet: don't treat a rough# schema-heavy post-compression estimate as real context pressure._real_tokens = 0else:- # Include tool schemas (20-30K tokens the messages-only estimate- # misses) and stay route-aware: on a compacted native-Codex session- # the generic durable-history figure would false-trigger. (#14695)+ # Include tool schemas (20-30K tokens the messages-only estimate misses) and+ # stay route-aware: on a compacted native-Codex session the generic+ # durable-history figure would false-trigger._real_tokens = _midturn_request_pressure_tokens(- agent,- messages,- active_system_prompt or "",- estimate_request_tokens_rough(- messages, tools=agent.tools or None- ),+ agent, messages, active_system_prompt or "",+ estimate_request_tokens_rough(messages, tools=agent.tools or None),)if (@@ -365,31 +286,24 @@ def compress_after_tool_results():compression_attempts += 1# Compression is running: reset blocked-overflow warning dedup so a- # future blocked turn can warn again. getattr: test doubles lack it.- _clear_warn = getattr(agent, "_clear_context_overflow_warn", None)- if callable(_clear_warn):- _clear_warn()+ # future blocked turn can warn again.+ _clear_overflow_warn(agent)agent._safe_print(" ⟳ compacting context…")_post_tool_input = messages- # Pass overhead-aware _real_tokens, not last_prompt_tokens (0 in- # the no-usage fallback), so the overflow guard sees the true size.+ # Pass overhead-aware _real_tokens, not last_prompt_tokens (0 in the+ # no-usage fallback), so the overflow guard sees the true size.messages, active_system_prompt = agent._compress_context(messages, system_message, approx_tokens=_real_tokens, task_id=effective_task_id)- if (- messages is _post_tool_input and compression_skipped_due_to_lock(agent)- ):- # Lock-skip no-op is a temporary defer, not evidence about- # compressibility: refund so a lock-loser loop doesn't burn the- # budget toward compression_exhausted. (#69870)+ if messages is _post_tool_input and compression_skipped_due_to_lock(agent):+ # Lock-skip no-op is a temporary defer, not evidence about compressibility:+ # refund so a lock-loser loop doesn't burn the budget toward exhausted.compression_attempts -= 1else:conversation_history = conversation_history_after_compression(agent, messages, conversation_history)- if _should_skip_model_call_for_reference_handoff(- messages, user_message- ):+ if _should_skip_model_call_for_reference_handoff(messages, user_message):logger.info("Skipping post-tool compaction model call: ""reference-only handoff would be the sole "@@ -397,41 +311,30 @@ def compress_after_tool_results()if not final_response:final_response = _HANDOFF_SKIP_FINAL_RESPONSE- _turn_exit_reason = "compaction_handoff_not_actionable"+ turn_exit_reason = "compaction_handoff_not_actionable"return _verdict(True)elif agent.compression_enabled:- # Over threshold but compression blocked (cooldown/anti-thrash):- # deduped warning so context can't silently overflow. (#62625)- _block_reason = None- _info = getattr(_compressor, "should_compress_info", None)- if _info is not None:- try:- _block_reason = _info(_real_tokens)[1]- except Exception:- _block_reason = None+ # Over threshold but compression blocked (cooldown/anti-thrash): deduped+ # warning so context can't silently overflow.+ _block_reason = _blocked_compress_reason(_compressor, _real_tokens)if _block_reason:agent._warn_context_overflow_blocked(_block_reason, _real_tokens, int(getattr(_compressor, "threshold_tokens", 0) or 0))- # Proactive tool-result prune (deterministic, no LLM, keeps tail):- # no-op unless proactive_prune_tokens is exceeded; commits only past+ # Proactive tool-result prune (deterministic, no LLM, keeps tail): no-op unless+ # proactive_prune_tokens is exceeded; commits only past# proactive_prune_min_reclaim_tokens so cache breaks stay episodic._prune = getattr(_compressor, "prune_tool_results_only", None)if callable(_prune):try:- _pruned_msgs, _pruned_n = _prune(- messages, current_tokens=_real_tokens- )+ _pruned_msgs, _pruned_n = _prune(messages, current_tokens=_real_tokens)except Exception:- logger.debug(- "proactive tool-result prune failed; skipping", exc_info=True- )+ logger.debug("proactive tool-result prune failed; skipping", exc_info=True)_pruned_msgs, _pruned_n = messages, 0- # Standard no-op caller contract: only commit when the- # engine returned a NEW list object with a non-zero count.+ # Standard no-op caller contract: only commit when the engine returned a+ # NEW list object with a non-zero count. Do NOT rebuild+ # conversation_history: rows already carry _DB_PERSISTED_MARKER, and on a+ # stale in-place flag the helper could seed unpersisted rows.if _pruned_n and _pruned_msgs is not messages:- # Do NOT rebuild conversation_history: rows already carry- # _DB_PERSISTED_MARKER, and on a stale in-place flag the- # helper could seed unpersisted rows into history_ids.messages = _pruned_msgsreturn _verdict(False)diff --git a/agent/turn_preflight_gate.py b/agent/turn_preflight_gate.pyindex 77560cb653c..f3525bf5f19 100644--- a/agent/turn_preflight_gate.py+++ b/agent/turn_preflight_gate.py@@ -1,46 +1,21 @@"""Pre-API pressure gate for the conversation turn loop: the Ollama runtime-context floor,the provider-overflow re-check arming, the insufficient-progress blocker (compares fullyassembled requests, not raw ``messages``) and the call into-``turn_preflight.run_preflight_compression``. Extracted from ``run_conversation``; nothing-here imports ``agent.conversation_loop`` at module level (cycle).-"""+``turn_preflight.run_preflight_compression``. Nothing here imports+``agent.conversation_loop`` at module level (cycle)."""from __future__ import annotations-from dataclasses import dataclassimport logging-from typing import Any, Dict, Optional+from typing import Anyfrom agent.message_metadata import append_messagefrom agent.turn_context import _compression_warrants_another_preflight_pass-from agent.turn_preflight import run_preflight_compression+from agent.turn_preflight import PreflightGateVerdict, run_preflight_compressionlogger = logging.getLogger("agent.conversation_loop")-@dataclass-class PreflightGateVerdict:- """``action``: ``"fallthrough"`` (make the API call), ``"continue"`` (compaction/window- growth — re-measure), ``"break"`` (turn ends) or ``"return"`` (``result`` is the turn's- result dict). The other fields are the loop locals the gate rebinds."""-- action: str- pending_moa_prepared_request: Any- messages: Any- active_system_prompt: Any- conversation_history: Any- api_call_count: Any- compression_attempts: Any- final_response: Any- failed: Any- _turn_exit_reason: Any- _compression_timeout_exhausted: Any- _preflight_compression_blocked: Any- _provider_overflow_recovery_pending: Any- _last_preflight_pressure: Any- result: Optional[Dict[str, Any]] = None--def run_preflight_gate(agent: Any, *, request_pressure_tokens: Any, _moa_prepared_request: Any,pending_moa_prepared_request: Any, messages: Any, system_message: Any, user_message: Any,@@ -50,115 +25,76 @@ def run_preflight_gate(_preflight_compression_blocked: Any, _provider_overflow_recovery_pending: Any,_last_preflight_pressure: Any,) -> PreflightGateVerdict:- """Run the pre-API guard chain in the original order (#11529). ``_last_preflight_pressure``- is consumed here (set to None) and re-armed only by a compression pass, so a blocked+ """Run the pre-API guard chain in the original order. ``_last_preflight_pressure`` is+ consumed here (set to None) and re-armed only by a compression pass, so a blockedpreflight never compares against a stale figure."""- from agent.conversation_loop import (- _ollama_context_limit_error,- )-- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> PreflightGateVerdict:- return PreflightGateVerdict(- action=action, pending_moa_prepared_request=pending_moa_prepared_request,- messages=messages, active_system_prompt=active_system_prompt,- conversation_history=conversation_history, api_call_count=api_call_count,- compression_attempts=compression_attempts, final_response=final_response, failed=failed,- _turn_exit_reason=_turn_exit_reason,- _compression_timeout_exhausted=_compression_timeout_exhausted,- _preflight_compression_blocked=_preflight_compression_blocked,- _provider_overflow_recovery_pending=_provider_overflow_recovery_pending,- _last_preflight_pressure=_last_preflight_pressure, result=result,- )+ from agent.conversation_loop import _ollama_context_limit_error- _runtime_context_error = _ollama_context_limit_error(- agent, request_pressure_tokens+ v = PreflightGateVerdict(+ action="fallthrough", pending_moa_prepared_request=pending_moa_prepared_request,+ messages=messages, active_system_prompt=active_system_prompt,+ conversation_history=conversation_history, api_call_count=api_call_count,+ compression_attempts=compression_attempts, final_response=final_response, failed=failed,+ _turn_exit_reason=_turn_exit_reason,+ _compression_timeout_exhausted=_compression_timeout_exhausted,+ _preflight_compression_blocked=_preflight_compression_blocked,+ _provider_overflow_recovery_pending=_provider_overflow_recovery_pending,+ _last_preflight_pressure=None,)++ _runtime_context_error = _ollama_context_limit_error(agent, request_pressure_tokens)if _runtime_context_error:- final_response = _runtime_context_error- failed = True- _turn_exit_reason = "ollama_runtime_context_too_small"- append_message(messages, {"role": "assistant", "content": final_response})+ v.final_response = _runtime_context_error+ v.failed = True+ v._turn_exit_reason = "ollama_runtime_context_too_small"+ append_message(messages, {"role": "assistant", "content": v.final_response})agent._emit_status("❌ Ollama runtime context is too small for Hermes tool use")- api_call_count -= 1- agent._api_call_count = api_call_count+ v.api_call_count -= 1+ agent._api_call_count = v.api_call_counttry:agent.iteration_budget.refund()except Exception:pass- return _verdict("break")+ v.action = "break"+ return v# Pre-API pressure check: tool results grow a turn and last_prompt_tokens lags# them. Mirror the turn-prologue guard chain: defer on noisy estimate, skip in- # failure cooldown, then should_compress() (#11529).+ # failure cooldown, then should_compress()._compressor = agent.context_compressor- _preflight_threshold = int(- getattr(_compressor, "threshold_tokens", 0) or 0- )- _provider_overflow_preflight = (- _provider_overflow_recovery_pending- and (- _preflight_threshold <= 0 or request_pressure_tokens >= _preflight_threshold- )+ _preflight_threshold = int(getattr(_compressor, "threshold_tokens", 0) or 0)+ _provider_overflow_preflight = _provider_overflow_recovery_pending and (+ _preflight_threshold <= 0 or request_pressure_tokens >= _preflight_threshold)- if (- _provider_overflow_recovery_pending and not _provider_overflow_preflight- ):+ if _provider_overflow_recovery_pending and not _provider_overflow_preflight:# The outer-loop rebuild includes system prompt, request-only injections and# tool schemas; only that full request with output runway may be sent.- _provider_overflow_recovery_pending = False+ v._provider_overflow_recovery_pending = False# Compare fully assembled requests, not raw ``messages`` (which omit# api_content, plugin injections, prefills, MoA context, ephemeral system text).- _previous_preflight_pressure = _last_preflight_pressure- _last_preflight_pressure = Noneif (- _previous_preflight_pressure is not None+ _last_preflight_pressure is not Noneand request_pressure_tokens >= _preflight_thresholdand not _compression_warrants_another_preflight_pass(- _previous_preflight_pressure, request_pressure_tokens, _preflight_threshold+ _last_preflight_pressure, request_pressure_tokens, _preflight_threshold)):# Stop proactive retries this turn without consuming the shared overflow-# recovery budget; the provider's error handler may still compact.- _preflight_compression_blocked = True+ v._preflight_compression_blocked = Truelogger.warning("Pre-API compression made insufficient progress: ~%s -> ""~%s request tokens; skipping additional preflight passes",- f"{_previous_preflight_pressure:,}",+ f"{_last_preflight_pressure:,}",f"{request_pressure_tokens:,}",)- _defer_preflight = getattr(- _compressor, "should_defer_preflight_to_real_usage", lambda _t: False- )- _pf = run_preflight_compression(- agent, compressor=_compressor, request_pressure_tokens=request_pressure_tokens,+ return run_preflight_compression(+ agent, v, compressor=_compressor, request_pressure_tokens=request_pressure_tokens,provider_overflow_preflight=_provider_overflow_preflight,- preflight_compression_blocked=_preflight_compression_blocked,- defer_preflight=_defer_preflight, moa_prepared_request=_moa_prepared_request,- pending_moa_prepared_request=pending_moa_prepared_request, messages=messages,- system_message=system_message, user_message=user_message,- active_system_prompt=active_system_prompt, conversation_history=conversation_history,- api_call_count=api_call_count, compression_attempts=compression_attempts,- max_compression_attempts=max_compression_attempts, effective_task_id=effective_task_id,- final_response=final_response, failed=failed,- compression_timeout_exhausted=_compression_timeout_exhausted,- turn_exit_reason=_turn_exit_reason,+ defer_preflight=getattr(+ _compressor, "should_defer_preflight_to_real_usage", lambda _t: False+ ),+ moa_prepared_request=_moa_prepared_request, system_message=system_message,+ user_message=user_message, max_compression_attempts=max_compression_attempts,+ effective_task_id=effective_task_id,)- messages = _pf.messages- active_system_prompt = _pf.active_system_prompt- conversation_history = _pf.conversation_history- api_call_count = _pf.api_call_count- compression_attempts = _pf.compression_attempts- pending_moa_prepared_request = _pf.pending_moa_prepared_request- final_response = _pf.final_response- failed = _pf.failed- _compression_timeout_exhausted = _pf.compression_timeout_exhausted- _turn_exit_reason = _pf.turn_exit_reason- if _pf.last_preflight_pressure is not None:- _last_preflight_pressure = _pf.last_preflight_pressure- if _pf.action == "return":- return _verdict("return", _pf.result)- if _pf.action == "break":- return _verdict("break")- if _pf.action == "continue":- return _verdict("continue")- return _verdict("fallthrough")