The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): manual /compress runs through one core with --preview/--aggressive on every surface
teknium17114da3de6dc
diff --git a/acp_adapter/commands.py b/acp_adapter/commands.pyindex d140b2ace64..a9f82f767e4 100644--- a/acp_adapter/commands.py+++ b/acp_adapter/commands.py@@ -226,45 +226,40 @@ class SlashCommandsMixin:return "Conversation history cleared."def _cmd_compress(self, args: str, state: SessionState) -> str:+ """``/compress [here [N] | <focus>] [--preview] [--aggressive]`` through the shared core."""+ from agent.conversation_compression import finalize_context_engine_compression_notification+ from agent.conversation_compression_manual import (+ AGGRESSIVE_UNSUPPORTED, compress_now, parse_compress_args, render_compress_result)+if not state.history:return "Nothing to compress — conversation is empty."+ agent = state.agent+ # No compression_enabled gate: it only disables *automatic* compaction (CLI/gateway parity).+ if not hasattr(agent, "_compress_context"):+ return "Context compression not available for this agent."+ request = parse_compress_args(args)+ if request.aggressive:+ return AGGRESSIVE_UNSUPPORTED+ original_session_db = getattr(agent, "_session_db", None)try:- agent = state.agent- # No compression_enabled gate: it only disables *automatic* compaction (CLI/gateway parity).- if not hasattr(agent, "_compress_context"):- return "Context compression not available for this agent."-- original_count = len(state.history)- # Include system prompt + tool schemas so the figure reflects real request pressure.- # See #6217.- # See #6217.- _sys_prompt = getattr(agent, "_cached_system_prompt", "") or ""- _tools = getattr(agent, "tools", None) or None- approx_tokens = _estimate_tokens(state.history, agent, _sys_prompt, _tools)- original_session_db = getattr(agent, "_session_db", None)-- try:- # Stable ACP session id: suppress _compress_context's SQLite session split.- agent._session_db = None- compressed, _ = agent._compress_context(- state.history, _sys_prompt, approx_tokens=approx_tokens, task_id=state.session_id, force=True,- )- finally:- agent._session_db = original_session_db-- state.history = compressed- self.session_manager.save_session(state.session_id)-- new_tokens = _estimate_tokens(- state.history, agent, getattr(agent, "_cached_system_prompt", "") or _sys_prompt,- getattr(agent, "tools", None) or _tools,- )- return (- f"Context compressed: {original_count} -> {len(state.history)} messages\n"- f"~{approx_tokens:,} -> ~{new_tokens:,} tokens"- )+ # Stable ACP session id: suppress _compress_context's SQLite session split.+ agent._session_db = None+ result = compress_now(+ agent, state.history, request, system_message=getattr(agent, "_cached_system_prompt", "") or "",+ task_id=state.session_id)except Exception as e:return f"Compression failed: {e}"+ finally:+ agent._session_db = original_session_db+ if result.status != "compressed":+ return "\n".join(render_compress_result(result))+ state.history = result.after_messages+ self.session_manager.save_session(state.session_id)+ finalize_context_engine_compression_notification(agent, committed=True)+ return (+ f"Context compressed: {len(result.before_messages)} -> {len(state.history)} messages\n"+ f"~{result.before_tokens:,} -> ~{result.after_tokens:,} tokens"+ )def _cmd_steer(self, args: str, state: SessionState) -> str:steer_text = args.strip()diff --git a/agent/AGENTS.md b/agent/AGENTS.mdindex edd8072bcc6..0aad5c8772c 100644--- a/agent/AGENTS.md+++ b/agent/AGENTS.md@@ -73,6 +73,10 @@ Adding one: register in that table (no `if name == ...` chain); `tools/todo_tool## Compression (`agent/compression_facade.py`, `conversation_compression.py`, `turn_context_compaction.py`)+Manual `/compress` on every surface (CLI, gateway, TUI, ACP) runs through+`agent/conversation_compression_manual.py::compress_now` (one parser for `here [N]` / focus /+`--preview` / `--aggressive`; surfaces only parse their own argv, install `after_messages` and render).+Two layers: gateway session hygiene (85% threshold) and the agent `ContextCompressor` (50%,configurable; per-model overrides; failure cooldown after provider-proven overflow). The algorithmprunes old tool results first (no LLM call), then picks boundaries, then generates a structureddiff --git a/agent/conversation_compression_manual.py b/agent/conversation_compression_manual.pynew file mode 100644index 00000000000..b71086774f4--- /dev/null+++ b/agent/conversation_compression_manual.py@@ -0,0 +1,133 @@+"""Manual ``/compress`` core shared by the CLI, gateway, TUI and ACP surfaces.++Manual compression is the ONE sanctioned history mutation (prompt-cache invariant): each surface parses+its own flags and renders its own text, but the sequence — split for ``here [N]``, estimate, run+``agent._compress_context(force=True)``, detect a lock-skip, rejoin the verbatim tail, summarize — lives+here so ``--preview`` / ``--aggressive`` and the lock-skip wording cannot drift per surface again.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Dict, List, Optional, Sequence++#: Every surface renders the same refusal; hard truncation has no persistence path outside the guarded+#: ``_compress_context`` rotation, so ``--aggressive`` is refused rather than mis-parsed as a focus topic.+AGGRESSIVE_UNSUPPORTED = (+ "--aggressive is not supported; use '/compress here [N]' to keep only recent exchanges, "+ "or /undo to drop turns.")+MIN_MESSAGES = 4+++@dataclass+class CompressRequest:+ """Parsed ``/compress`` arguments (``extract_compress_flags`` + ``parse_partial_compress_args``)."""+ preview: bool = False+ aggressive: bool = False+ partial: bool = False+ keep_last: int = 2+ focus_topic: Optional[str] = None+++@dataclass+class CompressResult:+ status: str # "preview" | "compressed" | "lock_skipped" | "nothing_to_do"+ before_messages: List[Dict[str, Any]]+ after_messages: List[Dict[str, Any]]+ before_tokens: int+ after_tokens: int+ request: CompressRequest+ lines: List[str] = field(default_factory=list) # preview report lines (status == "preview")+ lock_holder: Any = None+ summary: Optional[Dict[str, Any]] = None # ``summarize_manual_compression`` payload when compressed++ @property+ def removed(self) -> int:+ return len(self.before_messages) - len(self.after_messages)+++def parse_compress_args(raw_args: str) -> CompressRequest:+ """One parser for every surface: flags anywhere, then the boundary-aware / focus positional forms."""+ from hermes_cli.partial_compress import extract_compress_flags, parse_partial_compress_args+ rest, preview, aggressive = extract_compress_flags((raw_args or "").strip())+ partial, keep_last, focus_topic = parse_partial_compress_args(rest)+ return CompressRequest(preview=preview, aggressive=aggressive, partial=partial, keep_last=keep_last,+ focus_topic=focus_topic or None)+++def estimate_request_tokens(agent: Any, messages: Sequence[Dict[str, Any]]) -> int:+ """Transcript + system prompt + tool schemas: a transcript-only figure understates real request pressure+ and can even appear to grow after a dense handoff summary replaces many short turns (#6217)."""+ from agent.model_metadata import estimate_request_tokens_rough+ if not messages:+ return 0+ return estimate_request_tokens_rough(+ list(messages), system_prompt=getattr(agent, "_cached_system_prompt", "") or "",+ tools=getattr(agent, "tools", None) or None)+++def compress_now(+ agent: Any, history: Sequence[Dict[str, Any]], request: CompressRequest, *,+ system_message: Any = None, task_id: str = "default",+) -> CompressResult:+ """Run one manual compression of ``history`` on ``agent`` and return the outcome; the caller installs+ ``after_messages`` (and re-anchors session ids) — history is never mutated here.++ ``preview=True`` performs no compression and leaves ``agent`` untouched. A held compression lock+ yields ``lock_skipped`` with the agent's signal cleared and the deferred context-engine notification+ discarded; otherwise the caller must call ``finalize_context_engine_compression_notification(agent,+ committed=True)`` once its own history transaction commits (``committed=False`` on failure).+ ``system_message=None`` makes ``_compress_context`` rebuild the prompt; passing the cached prompt+ duplicated the identity block (#15281)."""+ from agent.conversation_compression import finalize_context_engine_compression_notification+ from agent.manual_compression_feedback import summarize_manual_compression+ from hermes_cli.partial_compress import (+ rejoin_compressed_head_and_tail, split_history_for_partial_compress, summarize_compress_preview)++ before = list(history)+ before_tokens = estimate_request_tokens(agent, before)+ head, tail = before, []+ if request.partial:+ head, tail = split_history_for_partial_compress(before, request.keep_last)+ if not tail: # degenerate split: nothing to keep verbatim → full compression+ head = before+ if request.preview:+ report = summarize_compress_preview(before, request.partial, request.keep_last, request.focus_topic, before_tokens)+ return CompressResult("preview", before, before, before_tokens, before_tokens, request, lines=report["lines"])++ compressor = getattr(agent, "context_compressor", None)+ has_content = getattr(compressor, "has_content_to_compress", None)+ if callable(has_content) and has_content(head) is False:+ return CompressResult("nothing_to_do", before, before, before_tokens, before_tokens, request)+ try:+ compressed, _ = agent._compress_context(+ head, system_message, approx_tokens=before_tokens, focus_topic=request.focus_topic, force=True,+ defer_context_engine_notification=True, **({"task_id": task_id} if task_id != "default" else {}))+ except Exception:+ finalize_context_engine_compression_notification(agent, committed=False)+ raise+ # Type-pinned (is True / str): bare truthiness is fooled by MagicMock auto-attributes on test doubles.+ lock_signal = getattr(agent, "_compression_skipped_due_to_lock", None)+ if lock_signal is True or isinstance(lock_signal, str):+ agent._compression_skipped_due_to_lock = None+ finalize_context_engine_compression_notification(agent, committed=False)+ return CompressResult("lock_skipped", before, before, before_tokens, before_tokens, request,+ lock_holder=lock_signal if isinstance(lock_signal, str) else None)+ if tail:+ compressed = rejoin_compressed_head_and_tail(compressed, tail)+ after_tokens = estimate_request_tokens(agent, compressed)+ summary = summarize_manual_compression(before, compressed, before_tokens, after_tokens, compression_state=compressor)+ return CompressResult("compressed", before, list(compressed), before_tokens, after_tokens, request, summary=summary)+++def render_compress_result(result: CompressResult, *, prefix: str = "") -> List[str]:+ """Surface-neutral text lines for a result (each surface may add its own icon/prefix)."""+ if result.status == "preview":+ return [f"{prefix}{line}" for line in result.lines]+ if result.status == "lock_skipped":+ from agent.manual_compression_feedback import describe_compression_lock_skip+ return [f"{prefix}{describe_compression_lock_skip(result.lock_holder or True)}"]+ if result.status == "nothing_to_do":+ return [f"{prefix}Nothing to compress yet."]+ summary = result.summary or {}+ return [f"{prefix}{line}" for line in (summary.get("headline"), summary.get("token_line"), summary.get("note")) if line]diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex f3a06e38afd..3f967deaf62 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -496,8 +496,8 @@ class GatewaySessionCommandsMixin:async def _handle_compress_command_inner(self, event: MessageEvent) -> str:"""Handle /compress -- manually compress conversation context; ``/compress <focus>`` tells- the summariser what to preserve."""- from hermes_cli.partial_compress import extract_compress_flags, parse_partial_compress_args+ the summariser what to preserve. Flags/positional forms are parsed by the shared core."""+ from agent.conversation_compression_manual import MIN_MESSAGES, parse_compress_argssource = event.sourcesession_entry = await self.async_session_store.get_or_create_session(source)@@ -505,37 +505,25 @@ class GatewaySessionCommandsMixin:history = await self.async_session_store.load_transcript(session_entry.session_id)except TranscriptReadError:return HISTORY_UNREADABLE- if not history or len(history) < 4:+ if not history or len(history) < MIN_MESSAGES:return t("gateway.compress.not_enough")- # Flags are stripped before positional parsing so they coexist with the boundary-aware- # "here [N]" (partial) and focus-topic (full) forms.- _raw_args, _preview, _aggressive = extract_compress_flags((event.get_command_args() or "").strip())- partial, keep_last, focus_topic = parse_partial_compress_args(_raw_args)- _agg_note = ""- if _aggressive:- # LLM-free hard truncation would need its own persistence branch outside the guarded- # _compress_context rotation machinery — unsupported on this surface.- _agg_note = t("gateway.compress.aggressive_unsupported")- if not _preview:- return _agg_note- if _preview:- return _compress_preview_reply(history, partial, keep_last, focus_topic, _agg_note)+ request = parse_compress_args(event.get_command_args() or "")+ _agg_note = t("gateway.compress.aggressive_unsupported") if request.aggressive else ""+ if request.aggressive and not request.preview:+ return _agg_note+ if request.preview:+ return _compress_preview_reply(history, request.partial, request.keep_last, request.focus_topic, _agg_note)try:- return await self._run_manual_compression(source, session_entry, history, partial,- keep_last, focus_topic)+ return await self._run_manual_compression(source, session_entry, history, request)except Exception as e:logger.warning("Manual compress failed: %s", e)return t("gateway.compress.failed", error=e)- async def _run_manual_compression(self, source, session_entry, history: list, partial: bool,- keep_last, focus_topic) -> str:- """Build a temporary agent, compress the transcript, persist, and describe the outcome."""+ async def _run_manual_compression(self, source, session_entry, history: list, request) -> str:+ """Build a temporary agent, run the shared compress core, persist, and describe the outcome."""from agent.conversation_compression import finalize_context_engine_compression_notification- from agent.manual_compression_feedback import summarize_manual_compression- from agent.model_metadata import estimate_request_tokens_rough+ from agent.conversation_compression_manual import compress_now, render_compress_resultfrom gateway.run import _platform_config_key- from hermes_cli.partial_compress import (rejoin_compressed_head_and_tail,- split_history_for_partial_compress)session_key = self._session_key_for_source(source)# Platform + stable gateway session key bind this agent (for external context engines) to@@ -551,13 +539,6 @@ class GatewaySessionCommandsMixin:# FULL transcript (tool results included), like auto-compress: user/assistant-only starves# tool-result pruning and can trip the protect-first/last early-return.msgs = [m for m in history if m.get("role") in {"user", "assistant", "tool"}]- # Partial: only the head is summarized; the tail snaps to a user-turn start so role- # alternation holds after rejoin.- head, tail = msgs, []- if partial:- head, tail = split_history_for_partial_compress(msgs, keep_last)- if not tail: # degenerate split — fall back to full compression- partial, head = False, msgs# Assign, not setdefault (a resolver value would be a stale placeholder); platform only when# known so None -> "cli" holds.if platform_key is not None:@@ -566,39 +547,24 @@ class GatewaySessionCommandsMixin:tmp_agent = await self._build_manual_compression_agent(session_entry.session_id, model, runtime_kwargs)try:- # Estimate with system prompt + tool schemas (real request pressure); needs the built agent.- # Must be computed after tmp_agent is built so _cached_system_prompt/tools are populated. See- # #6217.- _sys_prompt = getattr(tmp_agent, "_cached_system_prompt", "") or ""- _tools = getattr(tmp_agent, "tools", None) or None- approx_tokens = estimate_request_tokens_rough(msgs, system_prompt=_sys_prompt, tools=_tools)- compressor = tmp_agent.context_compressor- if not compressor.has_content_to_compress(head):- return t("gateway.compress.nothing_to_do")# Not a bare run_in_executor: the profile secret scope is a contextvar the default# executor hop would drop, failing aux-client credential resolution closed.- compressed, _ = await self._run_in_executor_with_context(- lambda: tmp_agent._compress_context(- head, "", approx_tokens=approx_tokens, focus_topic=focus_topic, force=True,- defer_context_engine_notification=True))- # A held compression lock returns unchanged; say so instead of the misleading no-op text.- _lock_skipped = getattr(tmp_agent, "_compression_skipped_due_to_lock", None)- if _lock_skipped is True or isinstance(_lock_skipped, str):- from agent.manual_compression_feedback import describe_compression_lock_skip- return describe_compression_lock_skip(_lock_skipped)- if partial and tail:- compressed = rejoin_compressed_head_and_tail(compressed, tail)- await self._persist_manual_compression(tmp_agent, session_entry, source, compressed)+ result = await self._run_in_executor_with_context(+ lambda: compress_now(tmp_agent, msgs, request, system_message=""))+ if result.status == "nothing_to_do":+ return t("gateway.compress.nothing_to_do")+ if result.status != "compressed":+ return "\n".join(render_compress_result(result))+ await self._persist_manual_compression(tmp_agent, session_entry, source, result.after_messages)finalize_context_engine_compression_notification(tmp_agent, committed=True)- new_tokens = estimate_request_tokens_rough(compressed, system_prompt=_sys_prompt, tools=_tools)- summary = summarize_manual_compression(msgs, compressed, approx_tokens, new_tokens,- compression_state=compressor)+ compressor = tmp_agent.context_compressor+ summary = result.summaryfinally:finalize_context_engine_compression_notification(tmp_agent, committed=False)self._evict_cached_agent(session_key) # next turn rebuilds the prompt from current files# Off-loop + bounded: teardown can block on subprocess/network/SQLite.await self._cleanup_agent_resources_off_loop(tmp_agent, context="manual compression")- return "\n".join(_manual_compression_reply_lines(summary, compressor, focus_topic))+ return "\n".join(_manual_compression_reply_lines(summary, compressor, request.focus_topic))async def _build_manual_compression_agent(self, session_id: str, model, runtime_kwargs: dict):"""Build the throwaway AIAgent that performs a manual /compress rewrite of *session_id*."""diff --git a/tests/acp/test_server.py b/tests/acp/test_server.pyindex 047c86e6c98..c6bf6135d64 100644--- a/tests/acp/test_server.py+++ b/tests/acp/test_server.py@@ -549,7 +549,7 @@ class TestSlashCommands:original_session_db = object()state.agent._session_db = original_session_db- def _compress_context(messages, system_prompt, *, approx_tokens, task_id, force):+ def _compress_context(messages, system_prompt, *, approx_tokens, task_id, force, **kwargs):assert state.agent._session_db is Noneassert messages == state.historyassert system_prompt == "system"@@ -582,8 +582,10 @@ class TestSlashCommands:],"system",approx_tokens=40,- task_id=state.session_id,+ focus_topic=None,force=True,+ defer_context_engine_notification=True,+ task_id=state.session_id,)mock_save.assert_called_once_with(state.session_id)diff --git a/tests/agent/test_conversation_compression_manual.py b/tests/agent/test_conversation_compression_manual.pynew file mode 100644index 00000000000..89741f62a5c--- /dev/null+++ b/tests/agent/test_conversation_compression_manual.py@@ -0,0 +1,93 @@+"""Invariants for the shared manual-/compress core (``agent/conversation_compression_manual``)."""++from __future__ import annotations++import copy+import threading+from unittest.mock import MagicMock++import pytest++from agent.conversation_compression_manual import compress_now, parse_compress_args+++def _history():+ return [+ {"role": "user", "content": "one"}, {"role": "assistant", "content": "two"},+ {"role": "user", "content": "three"}, {"role": "assistant", "content": "four"},+ {"role": "user", "content": "five"}, {"role": "assistant", "content": "six"},+ ]+++def _agent():+ agent = MagicMock()+ agent._cached_system_prompt, agent.tools, agent.context_compressor = "sys", None, None+ agent._compression_skipped_due_to_lock = None+ agent._compress_context.return_value = ([{"role": "assistant", "content": "summary"}], "")+ return agent++[email protected]("raw", ["--preview", "here 1 --preview", "--dry-run keep the tests", "--aggressive --preview"])+def test_preview_leaves_history_and_agent_byte_identical(raw):+ agent, history = _agent(), _history()+ frozen = copy.deepcopy(history)+ result = compress_now(agent, history, parse_compress_args(raw))+ assert result.status == "preview" and result.lines+ assert history == frozen and result.after_messages == frozen+ agent._compress_context.assert_not_called()+++def test_compressed_result_rejoins_verbatim_tail_and_never_mutates_input():+ agent, history = _agent(), _history()+ frozen = copy.deepcopy(history)+ result = compress_now(agent, history, parse_compress_args("here 1"))+ assert result.status == "compressed"+ assert agent._compress_context.call_args.args[0] == frozen[:4] # head only+ assert result.after_messages[-2:] == frozen[4:] # last exchange verbatim+ assert history == frozen+ assert agent._compress_context.call_args.kwargs["force"] is True++[email protected]("surface", ["cli", "gateway", "tui", "acp"])+def test_every_surface_honours_preview_without_compressing(surface, monkeypatch):+ """The prompt-cache-breaking mutation must be gated by the same ``--preview`` on all four surfaces."""+ agent, history = _agent(), _history()+ frozen = copy.deepcopy(history)+ if surface == "cli":+ from hermes_cli.cli_session_mixin import CLISessionMixin+ cli = CLISessionMixin.__new__(CLISessionMixin)+ cli.agent, cli.conversation_history = agent, history+ cli._manual_compress("/compress --preview")+ assert cli.conversation_history == frozen+ elif surface == "gateway":+ import asyncio+ from gateway.run import GatewayRunner+ gw = GatewayRunner.__new__(GatewayRunner)+ gw.session_store = MagicMock()+ entry = MagicMock(session_id="sid")+ gw._async_session_store = MagicMock(+ _store=gw.session_store, get_or_create_session=_coro(entry), load_transcript=_coro(history))+ gw._run_manual_compression = MagicMock(side_effect=AssertionError("must not compress"))+ event = MagicMock(); event.get_command_args.return_value = "--preview"+ reply = asyncio.run(gw._handle_compress_command_inner(event))+ assert "Preview" in reply+ elif surface == "tui":+ from tui_gateway.server import _compress_session_history+ session = {"agent": agent, "history": history, "history_lock": threading.Lock(), "history_version": 3}+ assert _compress_session_history(session, "--preview")[0] == 0+ assert session["history"] == frozen and session["history_version"] == 3+ else:+ from acp_adapter.commands import SlashCommandsMixin+ acp = SlashCommandsMixin.__new__(SlashCommandsMixin)+ acp.session_manager = MagicMock()+ state = MagicMock(history=history, agent=agent, session_id="acp-sid")+ assert "Preview" in acp._cmd_compress("--preview", state)+ assert state.history == frozen+ acp.session_manager.save_session.assert_not_called()+ agent._compress_context.assert_not_called()+++def _coro(value):+ async def _inner(*_a, **_k):+ return value+ return _innerdiff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.pyindex 58fa734270d..46e7b4de033 100644--- a/tui_gateway/methods_slash.py+++ b/tui_gateway/methods_slash.py@@ -245,11 +245,18 @@ def _compress_live_with_feedback(sid: str, session: dict, agent, arg: str, *, sn``here [N]`` / ``--keep N``). CompressionLockHeld is a clean no-op (skip note returned);other errors propagate to the caller, which finalizes the context-engine notification."""from agent.conversation_compression import finalize_context_engine_compression_notification+ from agent.conversation_compression_manual import (+ AGGRESSIVE_UNSUPPORTED, compress_now, parse_compress_args, render_compress_result)from agent.manual_compression_feedback import describe_compression_lock_skip, summarize_manual_compressionfrom agent.model_metadata import estimate_request_tokens_roughwith session["history_lock"]:before_messages = list(session.get("history", []))history_version = int(session.get("history_version", 0))+ request = parse_compress_args(arg)+ if request.aggressive:+ return AGGRESSIVE_UNSUPPORTED+ if request.preview: # report only — history, agent and session key untouched+ return "\n".join(render_compress_result(compress_now(agent, before_messages, request)))sys_prompt = getattr(agent, "_cached_system_prompt", "") or ""tools = getattr(agent, "tools", None) or Nonediff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.pyindex 7bf3d6a4144..110836cd4b6 100644--- a/tui_gateway/session_compression.py+++ b/tui_gateway/session_compression.py@@ -202,74 +202,39 @@ def _compress_session_history(before_messages: list | None = None, history_version: int | None = None,) -> tuple[int, dict]:"""Single choke point for all manual-compress routes. ``focus_topic`` is the RAW argument string after- ``/compress``, parsed HERE (not per-route) so boundary forms (``here [N]``, ``up to here``, ``--keep N``)- trigger a partial compress on EVERY route instead of a FULL compress focused on the literal text.-- It is parsed here with :func:`parse_partial_compress_args` so boundary-aware forms (``here [N]``, ``up- to here``, ``--keep N``) trigger a partial compress — head summarized, most recent ``keep_last``- exchanges kept verbatim — on EVERY route, mirroring cli.py's ``_manual_compress`` and- gateway/slash_commands.py (PR #35252).- """+ ``/compress``; the shared core (``agent.conversation_compression_manual``) parses boundary forms+ (``here [N]``, ``up to here``, ``--keep N``) so a partial compress triggers on EVERY route instead of a+ FULL compress focused on the literal text. ``--preview`` returns without touching history."""from agent.conversation_compression import finalize_context_engine_compression_notification- from agent.model_metadata import estimate_request_tokens_rough- from hermes_cli.partial_compress import (- parse_partial_compress_args, rejoin_compressed_head_and_tail, split_history_for_partial_compress,- )+ from agent.conversation_compression_manual import (+ AGGRESSIVE_UNSUPPORTED, MIN_MESSAGES, compress_now, parse_compress_args)agent = session["agent"]# Snapshot under the lock so the LLM-bound compression call does NOT hold history_lock for the# request — otherwise prompt.submit etc. block on the dispatcher loop while compaction runs.if before_messages is None or history_version is None:with session["history_lock"]:before_messages, history_version = list(session.get("history", [])), int(session.get("history_version", 0))- history = before_messages- if len(history) < 4:+ if len(before_messages) < MIN_MESSAGES:+ return 0, _get_usage(agent)+ request = parse_compress_args(focus_topic or "")+ if request.aggressive:+ raise ValueError(AGGRESSIVE_UNSUPPORTED)+ result = compress_now(agent, before_messages, request)+ if result.status == "preview":return 0, _get_usage(agent)- partial, keep_last, focus_topic = parse_partial_compress_args(focus_topic or "")- # Only the head is summarized; the last `keep_last` exchanges ride along verbatim. A degenerate- # split (empty tail) falls back to full compression so the user still gets an action.- head, tail = split_history_for_partial_compress(history, keep_last) if partial else (history, [])- if not tail:- head = history- if approx_tokens is None:- # Include system prompt + tool schemas so the figure reflects real request pressure.- # Include system prompt + tool schemas in the estimate — a transcript-only number understates real- # request pressure and can even appear to grow after compression because a dense handoff summary- # replaces many short turns (#6217).- approx_tokens = estimate_request_tokens_rough(- history, system_prompt=getattr(agent, "_cached_system_prompt", "") or "", tools=getattr(agent, "tools", None) or None- )- # system_message=None: passing the cached prompt (already holding the identity block) would append the- # identity twice. force=True: manual /compress bypasses the summary-failure cooldown like CLI/gateway.- # Pass system_message=None so AIAgent._compress_context rebuilds the system prompt cleanly via- # _build_system_prompt(None). Mirrors the CLI's _manual_compress fix for issue #15281. force=True: every- # caller of this helper is a manual /compress path (session.compress RPC, slash compress/compact,- # slash-worker mirror) — auto-compaction runs inside the agent loop, not here.- try:- compressed, _ = agent._compress_context(- head, None, approx_tokens=approx_tokens, focus_topic=focus_topic or None, force=True,- defer_context_engine_notification=True,- )- except Exception:- finalize_context_engine_compression_notification(agent, committed=False)- raise# Lock-skipped: raise so callers surface a clear message instead of "No changes from compression".- # Type-pinned (is True / str) because bare truthiness is fooled by MagicMock auto-attrs.- _lock_skipped = getattr(agent, "_compression_skipped_due_to_lock", None)- if _lock_skipped is True or isinstance(_lock_skipped, str):- agent._compression_skipped_due_to_lock = None- # No boundary committed; discard the pending deferred notification (exactly-once, no-op safe).- finalize_context_engine_compression_notification(agent, committed=False)- raise CompressionLockHeld(_lock_skipped if isinstance(_lock_skipped, str) else None)- if tail:- compressed = rejoin_compressed_head_and_tail(compressed, tail)+ if result.status == "lock_skipped":+ raise CompressionLockHeld(result.lock_holder)+ if result.status != "compressed":+ return 0, _get_usage(agent)with session["history_lock"]:if int(session.get("history_version", 0)) != history_version:# External mutation during compaction — drop the result so we don't clobber concurrent edits.finalize_context_engine_compression_notification(agent, committed=False)return 0, _get_usage(agent)- session["history"] = compressed+ session["history"] = result.after_messagessession["history_version"] = history_version + 1- return len(history) - len(compressed), _get_usage(agent)+ return result.removed, _get_usage(agent)def _sync_session_key_after_compress(