The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(compression): plan the compaction window in context_compressor_window
kshitijk4poorb03d642fef58
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 514de85ec71..948b1ccb81b 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -32,6 +32,7 @@ from agent.auxiliary_client import ()from agent.context_engine import ContextEngine, sanitize_memory_contextfrom agent.context_compressor_prellm import PreLlmSkipMixin+from agent.context_compressor_window import CompactionWindowMixinfrom agent.context_compressor_prune import ProactivePruneMixinfrom agent.context_compressor_summary import SummaryDispatchMixinfrom agent.context_compressor_retry import retryable_user_text@@ -2147,14 +2148,11 @@ Describe agent/tool work only as completed actions, state, or historical work.]"class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, CompressionTelemetryMixin, MicroCompactionMixin,- ProactivePruneMixin, ContextEngine,+ ProactivePruneMixin, CompactionWindowMixin, ContextEngine,):"""Default context engine: prune tool results, protect head/tail, summarize the middlewith an LLM, and iteratively update the previous summary on later compactions."""- # agent/prepared_compaction.PreparedCompaction when compression.prepare_ahead is on, else None.- prepared_compaction: Any = None-@propertydef name(self) -> str:return "compressor"@@ -3945,7 +3943,7 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb_raise_if_stale_attempt(self)self._record_summary_success(summary)return self._with_summary_prefix(summary)- except Exception as e:+ except Exception as e: # health: allow BLE001 -- unchanged summary boundary: every failure goes to _on_summary_failurereturn self._on_summary_failure(e, turns_to_summarize, focus_topic, memory_context)def _record_summary_success(self, summary: str) -> None:@@ -5208,34 +5206,6 @@ Write only the summary body. Do not include any preamble or prefix."""blank = self._blank_echo_indices_after(messages, self._find_last_user_message_idx(messages, 0))return [m for idx, m in enumerate(messages) if idx not in blank] if blank else messages- def _compress_window(self, messages: list[dict[str, Any]]) -> tuple[int, int]:- """Return ``(compress_start, compress_end)`` for the summarizable middle."""- compress_start = self._align_boundary_forward(messages, self._protect_head_size(messages))- compress_end = self._find_tail_cut_by_tokens(messages, compress_start)- # A role collision can merge the summary into the first tail row; keep an actionable user- # event out of that slot by retaining an older assistant/tool bridge.- latest_actionable_idx = self._find_last_user_message_idx(messages, 0)- if compress_end == latest_actionable_idx:- bridge_idx = latest_actionable_idx - 1- bridge_role = messages[bridge_idx].get("role") if bridge_idx >= 0 else None- if bridge_role == "tool":- bridge_idx = self._align_boundary_backward(messages, latest_actionable_idx)- elif bridge_role != "assistant":- bridge_idx = -1- if bridge_idx > compress_start:- compress_end = bridge_idx- return compress_start, compress_end-- def _plan_compaction_window(self, messages: List[Dict[str, Any]]) -> tuple[List[Dict[str, Any]], int, int, int]:- """Phases 1-2 of compress(): ``(working, pruned_count, compress_start, compress_end)``.- ``working`` is a pruned copy without blank echoes; the boundaries index into it."""- working, pruned_count = self._prune_old_tool_results(- messages, protect_tail_count=self.protect_last_n, protect_tail_tokens=self.tail_token_budget,- )- working = self._drop_blank_echoes(working)- compress_start, compress_end = self._compress_window(working)- return working, pruned_count, compress_start, compress_end-def _log_compression_start(self, display_tokens: int, compress_start: int, compress_end: int, n_turns: int, tail_msgs: int,) -> None:@@ -5516,13 +5486,8 @@ Write only the summary body. Do not include any preamble or prefix."""n_messages,)return canonical_messages- # Opt-in: an automatic compaction may splice a summary prepared in the background at ITS- # boundary; newer messages (at most one more tail budget) stay outside the summary, in the- # tail (agent/prepared_compaction.py).- prepared = self.prepared_compaction and self.prepared_compaction.take(- messages, self._session_id, compress_start, compress_end,- eligible=not (force or focus_topic or bypass_cooldown or memory_context.strip()),- max_gap_tokens=self.tail_token_budget,+ prepared = self._take_prepared_summary(+ messages, compress_start, compress_end, fresh=bool(force or focus_topic or bypass_cooldown or memory_context.strip()),)if prepared:compress_end = prepared.compress_enddiff --git a/agent/context_compressor_window.py b/agent/context_compressor_window.pynew file mode 100644index 00000000000..ecbfcf20515--- /dev/null+++ b/agent/context_compressor_window.py@@ -0,0 +1,57 @@+"""Compaction window planning for ContextCompressor: the head/middle/tail boundaries that compress() and+the opt-in prepared-compaction pass (agent/prepared_compaction.py) both plan, and the splice of a prepared+summary into that window."""++from __future__ import annotations++from typing import Any, Optional++from agent.prepared_compaction import PreparedCompaction, PreparedSummary+++class CompactionWindowMixin:+ """Window planning shared by compress() and the background pass."""++ # Set by agent_init when compression.prepare_ahead is on; None leaves compress() inline as before.+ prepared_compaction: Optional[PreparedCompaction] = None++ def _compress_window(self, messages: list[dict[str, Any]]) -> tuple[int, int]:+ """Return ``(compress_start, compress_end)`` for the summarizable middle."""+ compress_start = self._align_boundary_forward(messages, self._protect_head_size(messages))+ compress_end = self._find_tail_cut_by_tokens(messages, compress_start)+ # A role collision can merge the summary into the first tail row; keep an actionable user+ # event out of that slot by retaining an older assistant/tool bridge.+ latest_actionable_idx = self._find_last_user_message_idx(messages, 0)+ if compress_end == latest_actionable_idx:+ bridge_idx = latest_actionable_idx - 1+ bridge_role = messages[bridge_idx].get("role") if bridge_idx >= 0 else None+ if bridge_role == "tool":+ bridge_idx = self._align_boundary_backward(messages, latest_actionable_idx)+ elif bridge_role != "assistant":+ bridge_idx = -1+ if bridge_idx > compress_start:+ compress_end = bridge_idx+ return compress_start, compress_end++ def _plan_compaction_window(self, messages: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int, int, int]:+ """Phases 1-2 of compress(): ``(working, pruned_count, compress_start, compress_end)``.+ ``working`` is a pruned copy without blank echoes; the boundaries index into it."""+ working, pruned_count = self._prune_old_tool_results(+ messages, protect_tail_count=self.protect_last_n, protect_tail_tokens=self.tail_token_budget,+ )+ working = self._drop_blank_echoes(working)+ compress_start, compress_end = self._compress_window(working)+ return working, pruned_count, compress_start, compress_end++ def _take_prepared_summary(+ self, messages: list[dict[str, Any]], compress_start: int, compress_end: int, *, fresh: bool,+ ) -> Optional[PreparedSummary]:+ """The summary prepared in the background for this window, which an automatic compaction splices at+ ITS boundary; newer messages (at most one more tail budget) stay outside the summary, in the tail.+ ``fresh`` compactions (manual, focus, overflow recovery, memory-provider context) summarize anew."""+ if self.prepared_compaction is None:+ return None+ return self.prepared_compaction.take(+ messages, self._session_id, compress_start, compress_end, eligible=not fresh,+ max_gap_tokens=self.tail_token_budget,+ )diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 69836fd8568..f07b764367f 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -678,24 +678,20 @@ DEFAULT_CONFIG = {# safety margin; explicit values only clamp downward so the server goes first."codex_responses_compact_threshold": None,# in_place: compaction rewrites the message list and system prompt WITHOUT rotating the- # session id (no parent_session_id chain, no `name #N` renumbering), avoiding the- # session-rotation bug cluster. Pre-compaction turns are soft-archived under the same id- # (active=0, compacted=1) — still session_search-able. False = legacy rotating-compaction- # path.+ # session id (no parent_session_id chain, no `name #N` renumbering), avoiding the session-rotation+ # bug cluster. Pre-compaction turns are soft-archived under the same id (active=0, compacted=1) —+ # still session_search-able. False = legacy rotating-compaction path."in_place": True,# Per-model threshold overrides: keys substring-match the model name (longest wins), values# replace the global `threshold`, e.g. {"glm-5.2": 0.40}. Prefix a key with "<provider>:" to# scope it to one route ({"openai-codex:astra": 0.85} leaves Astra on OpenRouter/Nous at the# global value). The <512K floor (0.75) still applies raise-only on top."model_thresholds": {},- # Opt-in idle compaction (0 = off): a session resuming after this many idle seconds compacts- # up front, before the first reply. Time-based complement to `threshold`; skipped when- # already at/below threshold × target_ratio; honors the same cooldown/ anti-thrash/lock- # guards. Example: 1800 = 30 min.+ # Opt-in idle compaction (0 = off): a session resuming after this many idle seconds compacts up+ # front, before the first reply. Time-based complement to `threshold`; skipped when already at/below+ # threshold × target_ratio; honors the same cooldown/anti-thrash/lock guards. Example: 1800 = 30 min."idle_compact_after_seconds": 0,- # Opt-in: near the trigger, write the next compaction summary in the background (during- # tool execution and between turns). Automatic compaction splices it only when the- # summarized messages are unchanged; otherwise it summarizes inline as usual.+ # Opt-in: write the next summary in the background near the trigger; used only if the summarized turns are unchanged."prepare_ahead": False,},# Anthropic prompt caching (Claude via OpenRouter or native API). cache_ttl: "5m" | "1h" | "auto"