The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(turn): split build_turn_context into helpers; extract turn-start compaction to turn_context_compaction.py
Teknium84c2e326f28a
diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 655d668281a..507670380f3 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -15,13 +15,8 @@ from dataclasses import dataclassfrom typing import Any, Dict, List, Mapping, Optional, Tuplefrom agent.conversation_compression import (- IDLE_COMPACTION_STATUS_TEMPLATE,- PREFLIGHT_COMPRESSION_STATUS_TEMPLATE,- compression_skipped_due_to_lock,- conversation_history_after_compression,recover_rotated_compression_session,)-from agent.context_engine import automatic_compaction_status_messagefrom agent.iteration_budget import IterationBudgetfrom agent.memory_manager import build_memory_context_blockfrom agent.memory_provider import is_trivial_prompt@@ -404,60 +399,32 @@ class TurnContext:preflight_compression_blocked: bool = False-def build_turn_context(- agent,- user_message: Any,- system_message: Optional[str],- conversation_history: Optional[List[Dict[str, Any]]],- task_id: Optional[str],- stream_callback,- persist_user_message: Optional[Any],- persist_user_timestamp: Optional[float] = None,- persist_user_platform_id: Optional[str] = None,- *,- persist_user_display_kind: Optional[str] = None,- persist_user_display_metadata: Optional[Dict[str, Any]] = None,- restore_or_build_system_prompt,- install_safe_stdio,- sanitize_surrogates,- summarize_user_message_for_log,- set_session_context,- set_current_write_origin,- ra,- moa_active: bool = False,-) -> TurnContext:- """Run the once-per-turn setup and return the loop's input context.-- Helpers are passed in to avoid an import cycle with ``agent.conversation_loop``."""- # Guard stdio against OSError from broken pipes (systemd/headless/daemon).- install_safe_stdio()-- # Recover a rotated session before binding log/turn ids or copying client history so- # everything in this turn belongs to the canonical child.- recovered_history = recover_rotated_compression_session(agent)- if recovered_history is not None:- conversation_history = recovered_history- # NOTE: the DB session row is created later, after the system prompt is built;- # creating it now would persist system_prompt=NULL and cost a cache miss (#45499).+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:+ fn()- # Tag log records on this thread with the session ID for ``hermes logs``.- 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"))+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- # Restore the primary runtime if the previous turn activated fallback.- agent._restore_primary_runtime()- # Tell auxiliary_client what the live main provider/model are for this turn- # after primary restoration has settled the runtime.+def _publish_runtime_main(agent: Any) -> None:+ """Tell auxiliary_client the live main provider/model for this turn (after primary+ restoration settled the runtime). Never raises: failure loses only the scope."""try: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).- # Never-raising variant, outside the argument list: failure loses only scope.+ # Rotation-stable prompt-cache scope (lineage root), memoized per segment; a new+ # session uses the physical id until build_api_kwargs re-resolves (#79017)._cache_scope = resolve_prompt_cache_scope_safe(agent) or ""set_runtime_main(getattr(agent, "provider", "") or "",@@ -473,9 +440,11 @@ def build_turn_context(except Exception:pass- # Between-turns MCP refresh: late-connecting servers land in THIS turn's snapshot,- # before the first API call assembles ``tools=``. ``preserve_prefix`` keeps the- # tool array append-only so a flapping ``check_fn`` can't fork the cache (#100336).++def _refresh_mcp_tools_between_turns(agent: Any) -> None:+ """Late-connecting MCP servers land in THIS turn's snapshot, before the first API+ call assembles ``tools=``. ``preserve_prefix`` keeps the tool array append-only so a+ flapping ``check_fn`` can't fork the cache (#100336)."""try:if not getattr(agent, "_skip_mcp_refresh", False):# Import-cost gate: MCP tools are only registered by code that already@@ -490,12 +459,17 @@ def build_turn_context(except Exception:logger.debug("between-turns MCP tool refresh skipped", exc_info=True)- # Sanitize surrogate characters from user input.- if isinstance(user_message, str):- user_message = sanitize_surrogates(user_message)- if isinstance(persist_user_message, str):- persist_user_message = sanitize_surrogates(persist_user_message)+def _bind_turn_identity(+ agent: Any,+ task_id: Optional[str],+ stream_callback,+ persist_user_message: Any,+ persist_user_timestamp: Optional[float],+ persist_user_platform_id: Optional[str],+) -> Tuple[str, str]:+ """Stage callback/persist overrides on the agent and bind this turn's task and turn+ ids. Returns ``(effective_task_id, turn_id)``."""# Store stream callback for _interruptible_api_call to pick up.agent._stream_callback = stream_callbackagent._persist_user_message_idx = None@@ -517,8 +491,12 @@ def build_turn_context(# (concurrent turns interleave transcript writes). Cleared in _persist_session.from agent.agent_runtime_helpers import note_turn_startnote_turn_start(agent, turn_id)+ return effective_task_id, turn_id- # Reset retry counters and iteration budget at the start of each turn.++def _reset_per_turn_agent_state(agent: Any) -> None:+ """Reset retry counters, guardrails, iteration and run budgets at turn start.+ ``_turns_since_memory`` / ``_iters_since_skill`` are deliberately NOT reset."""agent._invalid_tool_retries = 0agent._invalid_json_retries = 0agent._empty_content_retries = 0@@ -553,7 +531,6 @@ def build_turn_context(agent._replay_compression_warning()agent._compression_warning = None # send once- # NOTE: _turns_since_memory and _iters_since_skill are NOT reset here.agent.iteration_budget = IterationBudget(agent.max_iterations)# Wall-clock run budget: stamped only when configured; the wrap-up latch resets per@@ -564,22 +541,31 @@ def build_turn_context(agent._run_budget_started_at = Noneagent._run_budget_wrapup_injected = False- # 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_text- _msg_preview = _msg_preview.replace("\n", " ")- logger.info(- "conversation turn: session=%s model=%s provider=%s platform=%s history=%d msg=%r",- agent.session_id or "none", agent.model, agent.provider or "unknown",- agent.platform or "unknown", len(conversation_history or []),- _msg_preview,- )+ # Per-turn file-mutation verifier state.+ agent._turn_failed_file_mutations = {}+ agent._turn_file_mutation_paths = set()+ agent._verification_stop_nudges = 0+ agent._pre_verify_nudges = 0++ # Reset the streaming context / think scrubbers at the top of each turn.+ for name in ("_stream_context_scrubber", "_stream_think_scrubber"):+ scrubber = getattr(agent, name, None)+ if scrubber is not None:+ scrubber.reset()- # Initialize conversation (copy to avoid mutating the caller's list).- messages = list(conversation_history) if conversation_history else []- # Reuse CLI-staged input only when its clean text matches this turn; a stale- # handoff must not replace later input. Voice turns compare the clean override.+def _stage_turn_user_message(+ agent: Any,+ user_message: Any,+ persist_user_message: Any,+ persist_user_timestamp: Optional[float],+ persist_user_platform_id: Optional[str],+ persist_user_display_kind: Optional[str],+ persist_user_display_metadata: Optional[Dict[str, Any]],+) -> Tuple[Dict[str, Any], Any]:+ """Build this turn's user dict, reusing CLI-staged input only when its clean text+ matches this turn (a stale handoff must not replace later input; voice turns+ compare the clean override). Returns ``(user_msg, pending_cli_message)``."""pending_cli_message = getattr(agent, "_pending_cli_user_message", None)expected_persist_content = (persist_user_message if persist_user_message is not None else user_message@@ -599,113 +585,74 @@ def build_turn_context()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 time. Preserve either value and cover any legacy unstamped handoff.+ # 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)- # Hydrate todo store from conversation history.- if conversation_history and not agent._todo_store.has_items():- agent._hydrate_todo_store(conversation_history)-- # Hydrate per-session nudge counters from persisted history (issue #22357).- if conversation_history and agent._user_turn_count == 0:- 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_turns- if agent._memory_nudge_interval > 0 and agent._turns_since_memory == 0:- agent._turns_since_memory = prior_user_turns % agent._memory_nudge_interval-- # Append the user message now that close persistence is safe. Synthesized turns- # stamp their transcript type so the crash persist writes a typed row; the model- # still receives role/content unchanged (api_messages strips both fields).+ # Synthesized turns stamp their transcript type so the crash persist writes a typed+ # row; the model still receives role/content unchanged (api_messages strips both).if persist_user_display_kind: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.if persist_user_platform_id is not None:user_msg["platform_message_id"] = persist_user_platform_id- append_message(messages, user_msg)- current_turn_user_idx = len(messages) - 1- agent._persist_user_message_idx = current_turn_user_idx+ return user_msg, pending_cli_message- # 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).- agent._is_user_initiated_turn = True- # Reset the streaming context scrubber at the top of each turn.- scrubber = getattr(agent, "_stream_context_scrubber", None)- if scrubber is not None:- scrubber.reset()- # Reset the think scrubber for the same reason.- think_scrubber = getattr(agent, "_stream_think_scrubber", None)- if think_scrubber is not None:- think_scrubber.reset()+def _hydrate_from_history(agent: Any, conversation_history: Optional[List[Any]]) -> None:+ """Hydrate the todo store and per-session nudge counters from persisted history."""+ if not conversation_history:+ return+ if 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"+ )+ if prior_user_turns > 0:+ agent._user_turn_count = prior_user_turns+ if agent._memory_nudge_interval > 0 and agent._turns_since_memory == 0:+ agent._turns_since_memory = prior_user_turns % agent._memory_nudge_interval- # Preserve the original user message (no nudge injection).- original_user_message = persist_user_message if persist_user_message is not None else user_message- # Track memory nudge trigger (turn-based, checked here).- should_review_memory = False+def _tick_memory_nudge(agent: Any) -> bool:+ """Advance the turn-based memory nudge counter; ``True`` when the review should fire."""if (agent._memory_nudge_interval > 0and "memory" in agent.valid_tool_namesand agent._memory_store):agent._turns_since_memory += 1if agent._turns_since_memory >= agent._memory_nudge_interval:- should_review_memory = Trueagent._turns_since_memory = 0+ return True+ return False- # Cosmetic side-signal: detect an affection reaction so the host can play hearts.- # Token-free, never touches the conversation, never fatal.- reaction_callback = getattr(agent, "reaction_callback", None)- if reaction_callback is not None:- try:- from agent.reactions import detect_reaction-- kind = detect_reaction(original_user_message)- if kind:- reaction_callback(kind)- except Exception:- pass-- if not agent.quiet_mode:- _print_preview = summarize_user_message_for_log(user_message)- agent._safe_print(- f"π¬ Starting conversation: '{_print_preview[:60]}"- f"{'...' if len(_print_preview) > 60 else ''}'"- )-- # ββ System prompt (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-- # Bot Mode DM tool β injected ONLY into a bot's canonical "Bot Chat" session- # (same gate as the protocol section); gate is session-stable, so cache-safe.+def _emit_reaction(agent: Any, original_user_message: Any) -> None:+ """Cosmetic side-signal: detect an affection reaction so the host can play hearts.+ Token-free, never touches the conversation, never fatal."""+ reaction_callback = getattr(agent, "reaction_callback", None)+ if reaction_callback is None:+ returntry:- from tools.bot_mode_dm import ensure_message_agent_tool+ from agent.reactions import detect_reaction- ensure_message_agent_tool(agent)+ kind = detect_reaction(original_user_message)+ if kind:+ reaction_callback(kind)except Exception:- logger.debug("message_agent injection skipped", exc_info=True)+ pass+- # 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.- persist_lock = getattr(agent, "_session_persist_lock", 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:- if persist_lock is None:- agent._ensure_db_session()- else:- with persist_lock:- agent._ensure_db_session()+ _with_persist_lock(agent, agent._ensure_db_session)except Exception:logger.warning("Turn-start session row creation failed for session=%s",@@ -715,424 +662,21 @@ def build_turn_context(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.- if not isinstance(pending_cli_message, dict) or pending_cli_message.get("_db_persisted"):- agent._pending_cli_user_message = None-- # ββ Idle-triggered compaction (opt-in; ``idle_compact_after_seconds``) ββ- # Fires on wall-clock gap since ``_last_activity_ts``, complementing the token- # gate; a cheap gap check gates the estimate (cf. _should_run_preflight_estimate).- _idle_after = getattr(agent, "compression_idle_compact_after_seconds", 0)- if agent.compression_enabled and _idle_after > 0 and messages:- _idle_gap = time.time() - getattr(agent, "_last_activity_ts", time.time())- if _idle_gap >= _idle_after:- _compressor = agent.context_compressor- # Route-aware pressure: on compacted native-Codex sessions the durable- # figure overstates the wire; reuse the preflight estimator (#96995).- _idle_tokens = _preflight_request_tokens(- agent,- messages,- active_system_prompt or "",- )- # Post-compression target size: don't summarise a thread already- # below what compaction would reduce it to.- _idle_floor = int(- _compressor.threshold_tokens * _compressor.summary_target_ratio- )- _idle_cooldown = getattr(- _compressor, "get_active_compression_failure_cooldown", lambda: None- )()- if _should_idle_compact(- enabled=agent.compression_enabled,- idle_after_seconds=_idle_after,- idle_gap_seconds=_idle_gap,- tokens=_idle_tokens,- floor_tokens=_idle_floor,- cooldown_active=bool(_idle_cooldown),- ):- logger.info(- "Idle compaction: %ss idle >= %ss, ~%s tokens > %s floor "- "(session %s)",- int(_idle_gap),- _idle_after,- f"{_idle_tokens:,}",- f"{_idle_floor:,}",- agent.session_id or "none",- )- _idle_status = automatic_compaction_status_message(- _compressor,- phase="idle",- default_message=IDLE_COMPACTION_STATUS_TEMPLATE.format(- idle_seconds=int(_idle_gap), tokens=_idle_tokens- ),- approx_tokens=_idle_tokens,- idle_seconds=int(_idle_gap),- model=agent.model,- )- if _idle_status:- agent._emit_status(_idle_status)- _idle_input = messages- messages, active_system_prompt = agent._compress_context(- messages, system_message, approx_tokens=_idle_tokens,- task_id=effective_task_id,- )- # ``_compress_context`` returns the INPUT list object when it skips;- # only re-baseline and re-anchor after a real compaction.- if messages is not _idle_input:- conversation_history = conversation_history_after_compression(- agent, messages, conversation_history- )- # Compaction rebuilt the list; re-anchor this turn's user index.- current_turn_user_idx = reanchor_current_turn_user_idx(- messages, user_message- )- agent._persist_user_message_idx = current_turn_user_idx-- # ββ Preflight context compression ββ- # Cheap pre-check gates the full estimate; see ``_should_run_preflight_estimate``- # for the OR semantics (#27405).- _preflight_compressed = False- _preflight_compression_blocked = False- agent._turn_received_provider_response = False- agent._turn_preflight_display_snapshot = None- if (- agent.compression_enabled- and not _review_fork_first_request_pending(agent)- and _should_run_preflight_estimate(- messages,- agent.context_compressor.protect_first_n,- agent.context_compressor.protect_last_n,- agent.context_compressor.threshold_tokens,- )- ):- _preflight_tokens = _preflight_request_tokens(- agent,- messages,- 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- )- if callable(_snapshot_fn):- _snapshot_val = _snapshot_fn()- # Type pin: MagicMock compressors return truthy Mock objects β- # only a real int 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(- _compressor,- "should_defer_preflight_to_real_usage",- lambda _tokens: False,- )- _preflight_deferred = _defer_preflight(_preflight_tokens)- # Codex app-server threads are compacted by the codex agent itself;- # Hermes only initiates compaction in "hermes" mode (#36801).- _codex_native_auto = (- getattr(agent, "api_mode", None) == "codex_app_server"- and str(- getattr(- agent,- "codex_app_server_auto_compaction",- "native",- )- or "native"- ).lower()- in {"native", "off"}- )+ _clear_staged_cli_input_if_persisted(agent, pending_cli_message)- 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.- _maybe_seed = getattr(- _compressor, "maybe_seed_preflight_display_tokens", None- )- if callable(_maybe_seed):- _maybe_seed(_preflight_tokens)-- _compression_cooldown = getattr(- _compressor,- "get_active_compression_failure_cooldown",- lambda: None,- )()-- _should_compress_now = False- _compress_block_reason = None- if _preflight_deferred:- logger.info(- "Skipping preflight compression: rough estimate ~%s >= %s, "- "but last real provider prompt was %s after compression",- f"{_preflight_tokens:,}",- f"{_compressor.threshold_tokens:,}",- f"{_compressor.last_real_prompt_tokens:,}",- )- elif _compression_cooldown:- logger.info(- "Skipping preflight compression: same-session cooldown active "- "(~%s seconds remaining, session %s)",- int(_compression_cooldown.get("remaining_seconds", 0.0)),- agent.session_id or "none",- )- if _preflight_tokens >= _compressor.threshold_tokens:- # Context is over threshold but compression is blocked by the- # summary-LLM cooldown β surface a warning (see block below).- _cooldown_secs = _compression_cooldown.get("remaining_seconds", 0.0)- _compress_block_reason = f"cooldown:{_cooldown_secs:.0f}"- elif _codex_native_auto:- logger.info(- "Skipping Hermes preflight compression for codex app-server "- "(mode=%s); Hermes will not start thread compaction here.",- getattr(agent, "codex_app_server_auto_compaction", "native"),- )- 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- if _should_compress_now:- # Managed local runtime: growing the window beats compressing (ladder- # order; same seam as _maybe_grow_local_window in the loop).- try:- from agent.conversation_loop import _maybe_grow_local_window- _grown = _maybe_grow_local_window(- agent, _compressor, _preflight_tokens- )- except Exception:- _grown = None- if _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)"- )- _should_compress_now = _compressor.should_compress(- _preflight_tokens- )- if _should_compress_now:- _preflight_compressed = True- # Compression is actually running β reset the dedup so a future blocked- # turn can warn again. getattr guard: object.__new__ doubles lack it.- _clear_warn = getattr(agent, "_clear_context_overflow_warn", None)- if callable(_clear_warn):- _clear_warn()- logger.info(- "Preflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)",- f"{_preflight_tokens:,}",- f"{_compressor.threshold_tokens:,}",- agent.model,- f"{_compressor.context_length:,}",- )- _preflight_status = automatic_compaction_status_message(- _compressor,- phase="preflight",- default_message=PREFLIGHT_COMPRESSION_STATUS_TEMPLATE.format(- tokens=_preflight_tokens,- threshold=_compressor.threshold_tokens,- ),- approx_tokens=_preflight_tokens,- threshold_tokens=_compressor.threshold_tokens,- context_length=_compressor.context_length,- model=agent.model,- )- if _preflight_status:- agent._emit_status(_preflight_status)- # Preflight passes honor compression.max_attempts like the loop's sites- # (default 3).- _max_preflight_passes = max(- 1, int(getattr(agent, "max_compression_attempts", 3) or 3)- )- for _pass in range(_max_preflight_passes):- _orig_len = len(messages)- _orig_tokens = _preflight_tokens- _preflight_input = messages- messages, active_system_prompt = agent._compress_context(- messages, system_message, approx_tokens=_preflight_tokens,- task_id=effective_task_id,- )- if (- 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 preflight passes for this turn.- logger.info(- "Preflight compression deferred: compression lock "- "held by another path (session %s)",- agent.session_id or "none",- )- break- # Re-estimate so size-only compression (same rows, fewer tokens)- # counts as progress (#39548).- _preflight_tokens = _preflight_request_tokens(- agent,- messages,- active_system_prompt or "",- )- if not _compression_made_progress(- _orig_len, len(messages), _orig_tokens, _preflight_tokens- ):- _fail_closed_after_preflight_timeout(agent, _preflight_tokens)- _preflight_compression_blocked = True- break # Cannot compress further: neither rows nor tokens moved- conversation_history = conversation_history_after_compression(- agent, messages, conversation_history- )- 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- if not _compressor.should_compress(_preflight_tokens):- break- if not _compression_warrants_another_preflight_pass(- _orig_tokens,- _preflight_tokens,- _compressor.threshold_tokens,- ):- _preflight_compression_blocked = True- logger.warning(- "Preflight compression made insufficient progress: "- "~%s -> ~%s request tokens; skipping additional passes",- f"{_orig_tokens:,}",- f"{_preflight_tokens:,}",- )- break- elif _compress_block_reason:- # Over threshold but compression blocked: surface a deduped warning so- # the user can /new or /compress instead of a silent provider limit.- agent._warn_context_overflow_blocked(- _compress_block_reason,- _preflight_tokens,- _compressor.threshold_tokens,- )- else:- # Sub-threshold and unblocked β re-arm the overflow warning. getattr guard:- # object.__new__ test doubles lack the method.- _clear_warn = getattr(agent, "_clear_context_overflow_warn", None)- if callable(_clear_warn):- _clear_warn()- # Engine maintenance only when NO skip-branch fired: cooldown, deferred- # estimate, or codex-native route keep the engine hook unconsulted (#20316).- if _compression_cooldown or _preflight_deferred or _codex_native_auto:- _engine_preflight = None- else:- _engine_preflight = getattr(- _compressor, "should_compress_preflight", None- )- # ββ Engine-driven sub-threshold preflight maintenance (#20316) ββ- # Engines overriding ``should_compress_preflight()`` get exactly ONE- # ``compress()`` pass; a no-op never touches _preflight_compression_blocked.- _wants_engine_preflight = False- if callable(_engine_preflight):- try:- _wants_engine_preflight = bool(_engine_preflight(messages))- except Exception as _preflight_exc:- # A buggy engine must never break an otherwise-healthy- # turn: swallow at debug level and skip maintenance.- logger.debug(- "should_compress_preflight raised %s; skipping "- "engine-driven preflight maintenance",- _preflight_exc,- )- _wants_engine_preflight = False- if _wants_engine_preflight:- logger.info(- "Engine-driven preflight maintenance: %s requested "- "compress() at ~%s tokens (below %s threshold)",- getattr(_compressor, "name", type(_compressor).__name__),- f"{_preflight_tokens:,}",- f"{getattr(_compressor, 'threshold_tokens', 0):,}",- )- _engine_input = messages- messages, active_system_prompt = agent._compress_context(- messages, system_message, approx_tokens=_preflight_tokens,- task_id=effective_task_id,- )- # ``_compress_context`` returns the INPUT list on every skip path and an- # engine may no-op; re-baseline/re-anchor only after a REAL compaction.- if messages is not _engine_input:- _preflight_compressed = True- conversation_history = conversation_history_after_compression(- agent, messages- )- 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- elif not agent.compression_enabled:- # 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.- _ctx_len = getattr(- getattr(agent, "context_compressor", None), "context_length", None- )- if isinstance(_ctx_len, int) and _ctx_len > 0:- _raw_chars = 0- for _m in messages:- if not isinstance(_m, dict):- continue- _c = _m.get("content")- 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.- _raw_chars = _ctx_len + 1- break- # 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.- if _raw_chars <= _ctx_len:- _clear_warn = getattr(- agent, "_clear_context_overflow_warn", None- )- if callable(_clear_warn):- _clear_warn()- else:- # 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).- _uncompressed_tokens = _preflight_request_tokens(- agent,- messages,- active_system_prompt or "",- )- if _uncompressed_tokens <= _ctx_len:- _clear_warn = getattr(- agent, "_clear_context_overflow_warn", None- )- if callable(_clear_warn):- _clear_warn()-- if _preflight_compressed:- # Compression rebuilt the list, so the pre-compression user index is stale.- # Re-anchor so the api_content stamp, injection site, and persist-override row- # hit the same dict; exact-content match first so a todo-snapshot can't steal it- current_turn_user_idx = reanchor_current_turn_user_idx(- messages, user_message- )- agent._persist_user_message_idx = current_turn_user_idx-- # Plugin hook: pre_llm_call (context injected into user message, not system prompt).- plugin_user_context = ""+def _collect_pre_llm_call_context(+ agent: Any,+ *,+ effective_task_id: str,+ turn_id: str,+ original_user_message: Any,+ messages: List[Any],+ conversation_history: Optional[List[Any]],+) -> str:+ """Run ``pre_llm_call`` plugins; their context is injected into the user message+ (never the system prompt). Oversized per-hook context is spilled to disk so a+ runaway plugin can't inflate every subsequent turn's prompt."""try:from hermes_cli.lifecycle import invoke_hook as _invoke_hook_pre_results = _invoke_hook(@@ -1149,8 +693,6 @@ def build_turn_context(sender_id=getattr(agent, "_user_id", None) or "",)_ctx_parts: list[str] = []- # Spill oversized per-hook context to disk so a runaway plugin can't inflate- # every subsequent turn's prompt.try:from tools.hook_output_spill import (get_spill_config as _spill_cfg,@@ -1161,7 +703,6 @@ def build_turn_context(_spill_if_oversized = None # type: ignore[assignment]_spill_config_cached = Nonefor r in _pre_results:- _piece: str = ""if isinstance(r, dict) and r.get("context"):_piece = str(r["context"])elif isinstance(r, str) and r.strip():@@ -1180,41 +721,41 @@ def build_turn_context(logger.warning("hook context spill failed: %s", _spill_exc)_ctx_parts.append(_piece)if _ctx_parts:- plugin_user_context = "\n\n".join(_ctx_parts)+ return "\n\n".join(_ctx_parts)except Exception as exc:logger.warning("pre_llm_call hook failed: %s", exc)+ return ""+- # Gateway must-deliver notes ride the user-message injection channel (one-shot,- # gateway-staged) so the ephemeral system prompt stays byte-stable. Multimodal- # (list) content can't take the string sidecar β append a durable text part.+def _merge_gateway_notes(+ agent: Any, messages: List[Any], current_turn_user_idx: int, plugin_user_context: str+) -> str:+ """Gateway must-deliver notes ride the user-message injection channel (one-shot,+ gateway-staged) so the ephemeral system prompt stays byte-stable. Multimodal (list)+ content can't take the string sidecar β append a durable text part instead."""_gateway_notes = consume_gateway_turn_context_notes(agent)- if _gateway_notes:- _gw_turn_content = (- messages[current_turn_user_idx].get("content")- if 0 <= current_turn_user_idx < len(messages)- and isinstance(messages[current_turn_user_idx], dict)- else None- )- if isinstance(_gw_turn_content, list):- append_notes_to_multimodal_content(_gw_turn_content, _gateway_notes)- else:- plugin_user_context = (- plugin_user_context + "\n\n" + _gateway_notes- if plugin_user_context- else _gateway_notes- )+ if not _gateway_notes:+ return plugin_user_context+ _gw_turn_content = (+ messages[current_turn_user_idx].get("content")+ if 0 <= current_turn_user_idx < len(messages)+ and isinstance(messages[current_turn_user_idx], dict)+ else None+ )+ 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+ )- # Per-turn file-mutation verifier state.- agent._turn_failed_file_mutations = {}- agent._turn_file_mutation_paths = set()- agent._verification_stop_nudges = 0- agent._pre_verify_nudges = 0- # Record the execution thread so interrupt()/clear_interrupt() can scope- # the tool-level interrupt signal to THIS agent's thread only.+def _bind_interrupt_scope(agent: Any, ra) -> None:+ """Record the execution thread so interrupt()/clear_interrupt() scope the tool-level+ signal to THIS agent's thread; clear stale state, preserving a pending interrupt."""agent._execution_thread_id = threading.current_thread().ident-- # Clear stale per-thread interrupt state, preserving a pending interrupt.ra()._set_interrupt(False, agent._execution_thread_id)if agent._interrupt_requested:ra()._set_interrupt(@@ -1222,90 +763,96 @@ def build_turn_context(agent._execution_thread_id,reason=getattr(agent, "_tool_interrupt_reason", None),)- agent._interrupt_thread_signal_pending = Falseelse:agent._interrupt_message = Noneagent._tool_interrupt_reason = None- agent._interrupt_thread_signal_pending = False+ agent._interrupt_thread_signal_pending = False- # Notify memory providers of the new turn (BEFORE prefetch_all).- if agent._memory_manager:- try:- _turn_msg = original_user_message if isinstance(original_user_message, str) else ""- agent._memory_manager.on_turn_start(agent._user_turn_count, _turn_msg)- except Exception:- pass- # External memory provider: prefetch once before the tool loop. Skipped on- # trivial prompts (greetings, acks) that carry no semantic signal.+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).+ Returns the prefetch text (``""`` when nothing was injected)."""+ if not agent._memory_manager:+ return ""+ _query = original_user_message if isinstance(original_user_message, str) else ""+ try:+ agent._memory_manager.on_turn_start(agent._user_turn_count, _query)+ except Exception:+ passext_prefetch_cache = ""- if agent._memory_manager:+ try:+ if not is_trivial_prompt(_query):+ ext_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.+ if ext_prefetch_cache:try:- _query = original_user_message if isinstance(original_user_message, str) else ""- if not is_trivial_prompt(_query):- ext_prefetch_cache = agent._memory_manager.prefetch_all(_query) or ""+ _recall_indicator = agent._memory_manager.describe_recall()+ if _recall_indicator:+ agent._emit_status(_recall_indicator)except Exception:pass- # Deterministic recall indicator: rendered by Hermes via _emit_status when- # memory was injected, so the model can't silently drop it.- if ext_prefetch_cache:+ return ext_prefetch_cache+++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."""+ _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+ )+ if _api_content is None or _api_content == _turn_user_msg.get("content"):+ return+ _turn_user_msg["api_content"] = _api_content+ # 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:- _recall_indicator = agent._memory_manager.describe_recall()- if _recall_indicator:- agent._emit_status(_recall_indicator)+ _db.set_latest_user_api_content(+ agent.session_id,+ _turn_user_msg.get("content"),+ _api_content,+ )except Exception:- pass+ logger.warning(+ "in-place compaction api_content backfill failed "+ "for session=%s",+ agent.session_id or "none",+ exc_info=True,+ )- # ββ 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. Skipped for codex_app_server/MoA.- if (- not moa_active- and getattr(agent, "api_mode", None) != "codex_app_server"- and 0 <= current_turn_user_idx < len(messages)- and messages[current_turn_user_idx].get("role") == "user"- ):- _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- )- if _api_content is not None and _api_content != _turn_user_msg.get("content"):- _turn_user_msg["api_content"] = _api_content- # 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,- )-- # Crash-resilience: persist the inbound user turn once, with final api_content,- # before the first LLM call. Same critical section as CLI close persistence;- # retries the row create if the pre-compression attempt failed transiently.++def _persist_turn_start(+ agent: Any,+ messages: List[Any],+ conversation_history: Optional[List[Any]],+ pending_cli_message: Any,+) -> None:+ """Crash-resilience: persist the inbound user turn once, with final api_content,+ before the first LLM call. Same critical section as CLI close persistence; retries+ the row create if the pre-compression attempt failed transiently."""def _ensure_and_persist() -> None:agent._ensure_db_session()agent._persist_session(messages, conversation_history)try:- if persist_lock is None:- _ensure_and_persist()- else:- with persist_lock:- _ensure_and_persist()+ _with_persist_lock(agent, _ensure_and_persist)except Exception:logger.warning("Early turn-start session persistence failed for session=%s",@@ -1313,13 +860,171 @@ def build_turn_context(exc_info=True,)finally:- # Keep an unmarked staged input for a later close retry if persistence failed;- # once marked, the close path must not treat it as a pre-worker UI input.- if not isinstance(pending_cli_message, dict) or pending_cli_message.get("_db_persisted"):- agent._pending_cli_user_message = None+ _clear_staged_cli_input_if_persisted(agent, pending_cli_message)+++def build_turn_context(+ agent,+ user_message: Any,+ system_message: Optional[str],+ conversation_history: Optional[List[Dict[str, Any]]],+ task_id: Optional[str],+ stream_callback,+ persist_user_message: Optional[Any],+ persist_user_timestamp: Optional[float] = None,+ persist_user_platform_id: Optional[str] = None,+ *,+ persist_user_display_kind: Optional[str] = None,+ persist_user_display_metadata: Optional[Dict[str, Any]] = None,+ restore_or_build_system_prompt,+ install_safe_stdio,+ sanitize_surrogates,+ summarize_user_message_for_log,+ set_session_context,+ set_current_write_origin,+ ra,+ moa_active: bool = False,+) -> TurnContext:+ """Run the once-per-turn setup and return the loop's input 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."""+ from agent.turn_context_compaction import run_turn_start_compaction++ # Guard stdio against OSError from broken pipes (systemd/headless/daemon).+ install_safe_stdio()- # Title the session now: the row exists and titling depends only on the user's- # ask, so it runs concurrently with the turn. Daemon thread, no-op once titled.+ # Recover a rotated session before binding log/turn ids or copying client history so+ # everything in this turn belongs to the canonical child.+ recovered_history = recover_rotated_compression_session(agent)+ if recovered_history is not None:+ conversation_history = recovered_history++ # Tag log records on this thread with the session ID for ``hermes logs``.+ 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):+ persist_user_message = sanitize_surrogates(persist_user_message)++ effective_task_id, turn_id = _bind_turn_identity(+ agent, task_id, stream_callback, persist_user_message,+ persist_user_timestamp, persist_user_platform_id,+ )+ _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_text+ logger.info(+ "conversation turn: session=%s model=%s provider=%s platform=%s history=%d msg=%r",+ agent.session_id or "none", agent.model, agent.provider or "unknown",+ agent.platform or "unknown", len(conversation_history or []),+ _msg_preview.replace("\n", " "),+ )++ # Initialize conversation (copy to avoid mutating the caller's list).+ 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,+ persist_user_platform_id, persist_user_display_kind, persist_user_display_metadata,+ )+ _hydrate_from_history(agent, conversation_history)+ # Append the user message now that close persistence is safe.+ append_message(messages, user_msg)+ current_turn_user_idx = len(messages) - 1+ agent._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).+ agent._is_user_initiated_turn = True++ # Preserve the original user message (no nudge injection).+ original_user_message = persist_user_message if persist_user_message is not None else user_message+ should_review_memory = _tick_memory_nudge(agent)+ _emit_reaction(agent, original_user_message)++ if not agent.quiet_mode:+ agent._safe_print(+ f"π¬ Starting conversation: '{_preview_text[:60]}"+ f"{'...' if len(_preview_text) > 60 else ''}'"+ )++ # ββ System prompt (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++ # Bot Mode DM tool β injected ONLY into a bot's canonical "Bot Chat" session (same+ # gate as the protocol section); gate is session-stable, so cache-safe.+ try:+ from tools.bot_mode_dm import ensure_message_agent_tool++ ensure_message_agent_tool(agent)+ except Exception:+ logger.debug("message_agent injection skipped", exc_info=True)++ _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,+ current_turn_user_idx=current_turn_user_idx,+ user_message=user_message,+ effective_task_id=effective_task_id,+ )+ messages = compaction.messages+ active_system_prompt = compaction.active_system_prompt+ conversation_history = compaction.conversation_history+ current_turn_user_idx = compaction.current_turn_user_idx++ plugin_user_context = _collect_pre_llm_call_context(+ agent,+ effective_task_id=effective_task_id,+ turn_id=turn_id,+ original_user_message=original_user_message,+ messages=messages,+ conversation_history=conversation_history,+ )+ plugin_user_context = _merge_gateway_notes(+ agent, messages, current_turn_user_idx, plugin_user_context+ )++ _bind_interrupt_scope(agent, ra)+ ext_prefetch_cache = _memory_turn_start_and_prefetch(agent, original_user_message)++ # Sidecar skipped for codex_app_server/MoA.+ if (+ not moa_active+ and getattr(agent, "api_mode", None) != "codex_app_server"+ and 0 <= current_turn_user_idx < len(messages)+ and messages[current_turn_user_idx].get("role") == "user"+ ):+ _stamp_api_content_sidecar(+ agent, messages, current_turn_user_idx, ext_prefetch_cache,+ plugin_user_context, preflight_compressed=compaction.compressed,+ )++ _persist_turn_start(agent, messages, conversation_history, pending_cli_message)++ # Title the session now: the row exists and titling depends only on the user's ask,+ # so it runs concurrently with the turn. Daemon thread, no-op once titled._maybe_title_session_at_turn_start(agent, messages)return TurnContext(@@ -1334,10 +1039,11 @@ def build_turn_context(should_review_memory=should_review_memory,plugin_user_context=plugin_user_context,ext_prefetch_cache=ext_prefetch_cache,- preflight_compression_blocked=_preflight_compression_blocked,+ preflight_compression_blocked=compaction.blocked,)+def build_api_messages(agent: Any,messages: List[Dict[str, Any]],diff --git a/agent/turn_context_compaction.py b/agent/turn_context_compaction.pynew file mode 100644index 00000000000..19c98e3c579--- /dev/null+++ b/agent/turn_context_compaction.py@@ -0,0 +1,487 @@+"""Turn-start compaction for ``build_turn_context``.++Three passes, in order: idle-triggered compaction (opt-in, wall-clock gap), preflight+context compression (token threshold), and the uncompressed-session overflow-warning+re-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."""++from __future__ import annotations++import logging+import time+from dataclasses import dataclass+from typing import Any, Dict, List, Optional++from agent.context_engine import automatic_compaction_status_message+from agent.conversation_compression import (+ IDLE_COMPACTION_STATUS_TEMPLATE,+ PREFLIGHT_COMPRESSION_STATUS_TEMPLATE,+ compression_skipped_due_to_lock,+ conversation_history_after_compression,+)++logger = logging.getLogger("agent.turn_context")+++@dataclass+class CompactionOutcome:+ """Locals rebuilt by turn-start compaction (``build_turn_context`` reads them back)."""++ messages: List[Dict[str, Any]]+ active_system_prompt: Optional[str]+ conversation_history: Optional[List[Dict[str, Any]]]+ current_turn_user_idx: int+ # A preflight pass (threshold or engine-driven) actually rebuilt ``messages``.+ compressed: bool = False+ # Preflight proved an immediate retry ineffective (no progress / insufficient).+ blocked: bool = False+++def _clear_overflow_warn(agent: Any) -> None:+ """Re-arm the context-overflow warning dedup. getattr guard: ``object.__new__``+ test doubles 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:+ 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+++def _reanchor(agent: Any, messages: List[Any], user_message: Any) -> int:+ """Compaction rebuilt ``messages``: re-anchor this turn's user index so the+ api_content stamp, injection site and persist-override row hit the same dict."""+ from agent.turn_context import reanchor_current_turn_user_idx++ idx = reanchor_current_turn_user_idx(messages, user_message)+ agent._persist_user_message_idx = idx+ return idx+++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]]],+ current_turn_user_idx: int,+ user_message: Any,+ effective_task_id: str,+) -> CompactionOutcome:+ """Idle compaction, then preflight compression (or the uncompressed guard)."""+ out = CompactionOutcome(+ messages=messages,+ active_system_prompt=active_system_prompt,+ conversation_history=conversation_history,+ current_turn_user_idx=current_turn_user_idx,+ )+ _idle_compaction(agent, out, system_message, user_message, effective_task_id)+ _preflight_compression(agent, out, system_message, user_message, effective_task_id)+ return out+++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``)."""+ from agent import turn_context as _tc++ messages = out.messages+ _idle_after = getattr(agent, "compression_idle_compact_after_seconds", 0)+ if not (agent.compression_enabled and _idle_after > 0 and messages):+ return+ _idle_gap = time.time() - getattr(agent, "_last_activity_ts", time.time())+ if _idle_gap < _idle_after:+ return+ _compressor = agent.context_compressor+ # Route-aware pressure: on compacted native-Codex sessions the durable figure+ # overstates the wire; reuse the preflight estimator (#96995).+ _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.+ _idle_floor = int(_compressor.threshold_tokens * _compressor.summary_target_ratio)+ _idle_cooldown = getattr(+ _compressor, "get_active_compression_failure_cooldown", lambda: None+ )()+ if not _tc._should_idle_compact(+ enabled=agent.compression_enabled,+ idle_after_seconds=_idle_after,+ idle_gap_seconds=_idle_gap,+ tokens=_idle_tokens,+ floor_tokens=_idle_floor,+ cooldown_active=bool(_idle_cooldown),+ ):+ return+ logger.info(+ "Idle compaction: %ss idle >= %ss, ~%s tokens > %s floor (session %s)",+ int(_idle_gap),+ _idle_after,+ f"{_idle_tokens:,}",+ f"{_idle_floor:,}",+ agent.session_id or "none",+ )+ _idle_status = automatic_compaction_status_message(+ _compressor,+ phase="idle",+ default_message=IDLE_COMPACTION_STATUS_TEMPLATE.format(+ idle_seconds=int(_idle_gap), tokens=_idle_tokens+ ),+ approx_tokens=_idle_tokens,+ idle_seconds=int(_idle_gap),+ model=agent.model,+ )+ if _idle_status:+ agent._emit_status(_idle_status)+ out.messages, out.active_system_prompt = agent._compress_context(+ messages, system_message, approx_tokens=_idle_tokens,+ task_id=effective_task_id,+ )+ # ``_compress_context`` returns the INPUT list object when it skips; only+ # re-baseline and re-anchor after a real compaction.+ if out.messages is not messages:+ out.conversation_history = conversation_history_after_compression(+ agent, out.messages, out.conversation_history+ )+ out.current_turn_user_idx = _reanchor(agent, out.messages, user_message)+++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)."""+ return (+ getattr(agent, "api_mode", None) == "codex_app_server"+ and str(+ getattr(agent, "codex_app_server_auto_compaction", "native") or "native"+ ).lower()+ in {"native", "off"}+ )+++def _preflight_compression(+ agent: Any,+ out: CompactionOutcome,+ system_message: Optional[str],+ user_message: Any,+ 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)."""+ from agent import turn_context as _tc++ agent._turn_received_provider_response = False+ agent._turn_preflight_display_snapshot = None+ if not agent.compression_enabled:+ _rearm_uncompressed_overflow_warn(agent, out.messages, out.active_system_prompt)+ return+ if _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,+ ):+ return++ messages = out.messages+ _preflight_tokens = _tc._preflight_request_tokens(+ agent, 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)+ if callable(_snapshot_fn):+ _snapshot_val = _snapshot_fn()+ # Type pin: MagicMock compressors return truthy Mock objects β only a real int+ # 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(+ _compressor, "should_defer_preflight_to_real_usage", lambda _tokens: False+ )+ _preflight_deferred = _defer_preflight(_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.+ _maybe_seed = getattr(_compressor, "maybe_seed_preflight_display_tokens", None)+ if callable(_maybe_seed):+ _maybe_seed(_preflight_tokens)++ _compression_cooldown = getattr(+ _compressor, "get_active_compression_failure_cooldown", lambda: None+ )()++ _should_compress_now = False+ _compress_block_reason = None+ if _preflight_deferred:+ logger.info(+ "Skipping preflight compression: rough estimate ~%s >= %s, "+ "but last real provider prompt was %s after compression",+ f"{_preflight_tokens:,}",+ f"{_compressor.threshold_tokens:,}",+ f"{_compressor.last_real_prompt_tokens:,}",+ )+ elif _compression_cooldown:+ logger.info(+ "Skipping preflight compression: same-session cooldown active "+ "(~%s seconds remaining, session %s)",+ int(_compression_cooldown.get("remaining_seconds", 0.0)),+ agent.session_id or "none",+ )+ if _preflight_tokens >= _compressor.threshold_tokens:+ # Over threshold but blocked by the summary-LLM cooldown β surface a warning.+ _cooldown_secs = _compression_cooldown.get("remaining_seconds", 0.0)+ _compress_block_reason = f"cooldown:{_cooldown_secs:.0f}"+ elif _codex_native_auto:+ logger.info(+ "Skipping Hermes preflight compression for codex app-server "+ "(mode=%s); Hermes will not start thread compaction here.",+ getattr(agent, "codex_app_server_auto_compaction", "native"),+ )+ 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+ if _should_compress_now:+ # Managed local runtime: growing the window beats compressing (ladder order;+ # same seam as _maybe_grow_local_window in the loop).+ try:+ from agent.conversation_loop import _maybe_grow_local_window++ _grown = _maybe_grow_local_window(agent, _compressor, _preflight_tokens)+ except Exception:+ _grown = None+ if _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)"+ )+ _should_compress_now = _compressor.should_compress(_preflight_tokens)+ if _should_compress_now:+ _run_preflight_passes(+ agent, out, _compressor, _preflight_tokens, system_message, effective_task_id+ )+ elif _compress_block_reason:+ # Over threshold but compression blocked: surface a deduped warning so the+ # user can /new or /compress instead of a silent provider limit.+ agent._warn_context_overflow_blocked(+ _compress_block_reason, _preflight_tokens, _compressor.threshold_tokens+ )+ else:+ # 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).+ if not (_compression_cooldown or _preflight_deferred or _codex_native_auto):+ _engine_preflight_maintenance(+ agent, out, _compressor, _preflight_tokens, system_message, effective_task_id+ )++ if out.compressed:+ # Compression rebuilt the list, so the pre-compression user index is stale.+ # Exact-content match first so a todo-snapshot can't steal it.+ out.current_turn_user_idx = _reanchor(agent, out.messages, user_message)+++def _run_preflight_passes(+ agent: Any,+ out: CompactionOutcome,+ _compressor: Any,+ _preflight_tokens: int,+ system_message: Optional[str],+ effective_task_id: str,+) -> None:+ """Threshold-triggered preflight passes (honor ``compression.max_attempts`` like+ the loop's sites, default 3)."""+ from agent import turn_context as _tc++ out.compressed = True+ # Compression is actually running β reset the dedup so a future blocked turn can+ # warn again.+ _clear_overflow_warn(agent)+ logger.info(+ "Preflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)",+ f"{_preflight_tokens:,}",+ f"{_compressor.threshold_tokens:,}",+ agent.model,+ f"{_compressor.context_length:,}",+ )+ _preflight_status = automatic_compaction_status_message(+ _compressor,+ phase="preflight",+ default_message=PREFLIGHT_COMPRESSION_STATUS_TEMPLATE.format(+ tokens=_preflight_tokens, threshold=_compressor.threshold_tokens+ ),+ approx_tokens=_preflight_tokens,+ threshold_tokens=_compressor.threshold_tokens,+ context_length=_compressor.context_length,+ model=agent.model,+ )+ if _preflight_status:+ agent._emit_status(_preflight_status)+ _max_preflight_passes = max(1, int(getattr(agent, "max_compression_attempts", 3) or 3))+ for _pass in range(_max_preflight_passes):+ _preflight_input = out.messages+ _orig_len = len(_preflight_input)+ _orig_tokens = _preflight_tokens+ out.messages, out.active_system_prompt = agent._compress_context(+ _preflight_input, system_message, approx_tokens=_preflight_tokens,+ 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.+ logger.info(+ "Preflight compression deferred: compression lock "+ "held by another path (session %s)",+ agent.session_id or "none",+ )+ break+ # Re-estimate so size-only compression (same rows, fewer tokens) counts as+ # progress (#39548).+ _preflight_tokens = _tc._preflight_request_tokens(+ agent, out.messages, out.active_system_prompt or ""+ )+ if not _tc._compression_made_progress(+ _orig_len, len(out.messages), _orig_tokens, _preflight_tokens+ ):+ _tc._fail_closed_after_preflight_timeout(agent, _preflight_tokens)+ out.blocked = True+ break # Cannot compress further: neither rows nor tokens moved+ out.conversation_history = conversation_history_after_compression(+ agent, out.messages, out.conversation_history+ )+ _reset_retry_state_after_compaction(agent)+ if not _compressor.should_compress(_preflight_tokens):+ break+ if not _tc._compression_warrants_another_preflight_pass(+ _orig_tokens, _preflight_tokens, _compressor.threshold_tokens+ ):+ out.blocked = True+ logger.warning(+ "Preflight compression made insufficient progress: "+ "~%s -> ~%s request tokens; skipping additional passes",+ f"{_orig_tokens:,}",+ f"{_preflight_tokens:,}",+ )+ break+++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+ ``should_compress_preflight()`` get exactly ONE ``compress()`` pass; a no-op never+ touches ``blocked``."""+ _engine_preflight = getattr(_compressor, "should_compress_preflight", None)+ if not callable(_engine_preflight):+ return+ 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.+ logger.debug(+ "should_compress_preflight raised %s; skipping "+ "engine-driven preflight maintenance",+ _preflight_exc,+ )+ return+ if not _wants_engine_preflight:+ return+ logger.info(+ "Engine-driven preflight maintenance: %s requested "+ "compress() at ~%s tokens (below %s threshold)",+ getattr(_compressor, "name", type(_compressor).__name__),+ f"{_preflight_tokens:,}",+ f"{getattr(_compressor, 'threshold_tokens', 0):,}",+ )+ _engine_input = out.messages+ out.messages, out.active_system_prompt = agent._compress_context(+ _engine_input, system_message, approx_tokens=_preflight_tokens,+ task_id=effective_task_id,+ )+ # ``_compress_context`` returns the INPUT list on every skip path and an engine+ # may no-op; re-baseline/re-anchor only after a REAL compaction.+ if out.messages is not _engine_input:+ out.compressed = True+ out.conversation_history = conversation_history_after_compression(+ agent, out.messages+ )+ _reset_retry_state_after_compaction(agent)+++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."""+ from agent import turn_context as _tc++ _ctx_len = getattr(getattr(agent, "context_compressor", None), "context_length", None)+ if not (isinstance(_ctx_len, int) and _ctx_len > 0):+ return+ _raw_chars = 0+ for _m in messages:+ if not isinstance(_m, dict):+ continue+ _c = _m.get("content")+ 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.+ _raw_chars = _ctx_len + 1+ break+ # 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.+ 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).+ _uncompressed_tokens = _tc._preflight_request_tokens(+ agent, messages, active_system_prompt or ""+ )+ if _uncompressed_tokens <= _ctx_len:+ _clear_overflow_warn(agent)