From 86c2882bbb26280f5f825e7d6a3fac1b2b4dd589 Mon Sep 17 00:00:00 2001 From: Jose Naicipa Date: Wed, 10 Jun 2026 04:37:24 +0000 Subject: [PATCH] fix: make context compaction resilient to huge tool logs - digest oversized tool outputs before summarization and fallback handoffs - shrink protected tool logs when auxiliary summarization fails - retune Codex gpt-5.5 compaction floor and compression defaults - preserve user thresholds above the Codex floor - update tests and docs for new compaction defaults --- agent/agent_init.py | 82 +++-- agent/auxiliary_client.py | 25 +- agent/context_compressor.py | 120 ++++++- agent/tool_output_precompaction.py | 279 +++++++++++++++ cli-config.yaml.example | 6 +- hermes_cli/config.py | 30 +- tests/agent/test_arcee_trinity_overrides.py | 89 ++++- tests/agent/test_context_compressor.py | 11 +- tests/agent/test_tool_output_precompaction.py | 322 ++++++++++++++++++ tests/hermes_cli/test_aux_config.py | 6 +- tests/hermes_cli/test_config.py | 38 +++ website/docs/developer-guide/agent-loop.md | 2 +- .../context-compression-and-caching.md | 18 +- .../docs/reference/environment-variables.md | 2 +- website/docs/user-guide/configuration.md | 7 +- .../current/developer-guide/agent-loop.md | 2 +- .../context-compression-and-caching.md | 4 +- .../reference/environment-variables.md | 2 +- .../current/user-guide/configuration.md | 7 +- 19 files changed, 962 insertions(+), 90 deletions(-) create mode 100644 agent/tool_output_precompaction.py create mode 100644 tests/agent/test_tool_output_precompaction.py diff --git a/agent/agent_init.py b/agent/agent_init.py index 96bfe3d873f04..3857395e866c7 100644 --- a/agent/agent_init.py +++ b/agent/agent_init.py @@ -86,6 +86,42 @@ def _build_codex_gpt55_autoraise_notice(autoraise: Dict[str, float]) -> str: ) +def _resolve_compression_threshold( + user_threshold: float, + model: Optional[str], + provider: Optional[str], + *, + codex_gpt55_autoraise: bool = True, +) -> "tuple[float, Optional[Dict[str, float]]]": + """Resolve the effective compaction threshold for a model/route. + + Returns ``(threshold, autoraised)`` where ``autoraised`` is the + ``{"from": , "to": }`` payload for the one-time + Codex gpt-5.5 notice, or ``None`` when nothing changed for the user. + + The Codex gpt-5.5 override is a floor, not a replacement: a user/global + threshold that already meets or exceeds it survives unchanged, and the + notice fires only when the threshold actually went up. The Arcee Trinity + override keeps its long-standing behavior of silently replacing the + global threshold. + """ + from agent.auxiliary_client import ( + _compression_threshold_for_model, + _is_codex_gpt55, + ) + + model_threshold = _compression_threshold_for_model( + model, provider, allow_codex_gpt55_autoraise=codex_gpt55_autoraise + ) + if model_threshold is None: + return user_threshold, None + if _is_codex_gpt55(model, provider): + if model_threshold > user_threshold + 1e-9: + return model_threshold, {"from": user_threshold, "to": model_threshold} + return user_threshold, None + return model_threshold, None + + def _normalized_custom_base_url(value: Any) -> str: if not isinstance(value, str): return "" @@ -1270,46 +1306,32 @@ def init_agent( if not isinstance(_compression_cfg, dict): _compression_cfg = {} compression_threshold = float(_compression_cfg.get("threshold", 0.50)) - # Per-model/route compaction-threshold override. Codex gpt-5.5 raises to - # 85% (the Codex backend caps the window at 272K, so the default 50% would - # compact at ~136K — half the usable context). Gated by an opt-out config - # flag so the user can fall back to the global threshold; when the override - # fires we stash a one-time notification (replayed on the first turn) that - # tells the user what changed and how to revert. + # Per-model/route compaction-threshold override. Codex gpt-5.5 floors the + # threshold at 60% (the Codex backend caps the window at 272K, so the + # default 50% would compact at ~136K — half the usable context) but never + # lowers a user-set threshold that already meets or exceeds it. Gated by + # an opt-out config flag so the user can fall back to the global + # threshold; when a raise actually happens we stash a one-time + # notification (replayed on the first turn) that tells the user what + # changed and how to revert. _codex_gpt55_autoraise = str( _compression_cfg.get("codex_gpt55_autoraise", True) ).lower() in {"true", "1", "yes"} agent._compression_threshold_autoraised = None try: - from agent.auxiliary_client import ( - _compression_threshold_for_model as _cthresh_fn, - _is_codex_gpt55 as _is_codex_gpt55_fn, - ) - _model_cthresh = _cthresh_fn( - agent.model, - agent.provider, - allow_codex_gpt55_autoraise=_codex_gpt55_autoraise, + compression_threshold, agent._compression_threshold_autoraised = ( + _resolve_compression_threshold( + compression_threshold, + agent.model, + agent.provider, + codex_gpt55_autoraise=_codex_gpt55_autoraise, + ) ) - if _model_cthresh is not None: - _prev_threshold = compression_threshold - compression_threshold = _model_cthresh - # Notify only for the Codex gpt-5.5 autoraise (the Arcee Trinity - # override is a long-standing silent default). Skip the notice when - # the user's global threshold already meets/exceeds the raised - # value, since nothing actually changed for them. - if ( - _is_codex_gpt55_fn(agent.model, agent.provider) - and _model_cthresh > _prev_threshold + 1e-9 - ): - agent._compression_threshold_autoraised = { - "from": _prev_threshold, - "to": _model_cthresh, - } except Exception: pass compression_enabled = str(_compression_cfg.get("enabled", True)).lower() in {"true", "1", "yes"} compression_target_ratio = float(_compression_cfg.get("target_ratio", 0.20)) - compression_protect_last = int(_compression_cfg.get("protect_last_n", 20)) + compression_protect_last = int(_compression_cfg.get("protect_last_n", 10)) # protect_first_n is the number of non-system messages to protect at # the head, in addition to the system prompt (which is always # implicitly protected by the compressor). Floor at 0 — a value of diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index c6e00340e7e19..9bfcfa292f2fd 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -209,9 +209,16 @@ def _is_arcee_trinity_thinking(model: Optional[str]) -> bool: # ``context_length_exceeded`` while ~250K succeeds). With a 272K ceiling the # default 50% compaction trigger fires at ~136K — wasteful, since the model # can hold far more raw context before summarization actually buys anything. -# We raise the trigger to 85% (~231K) on this exact route so Codex gpt-5.5 -# sessions use the window they actually have. -_CODEX_GPT55_COMPACTION_THRESHOLD = 0.85 +# We raise the trigger to 60% (~163K) on this exact route so Codex gpt-5.5 +# sessions use more of the window they actually have. +# +# Why 60% and not the 85% this shipped with: at 85% compaction only fired at +# ~231K tokens, which made the summarizer input so large that the auxiliary +# compression model routinely hit its timeout, exhausted its fallbacks, and +# left sessions stuck in preflight compression. 60% keeps a meaningful raise +# over the 50% default while leaving the summarizer a window it can actually +# digest before the hard 272K ceiling is in sight. +_CODEX_GPT55_COMPACTION_THRESHOLD = 0.60 def _is_codex_gpt55(model: Optional[str], provider: Optional[str] = None) -> bool: @@ -267,10 +274,14 @@ def _compression_threshold_for_model( Per-model/route overrides: - Arcee Trinity Large Thinking → 0.75 (preserve reasoning context). - - gpt-5.5 on the Codex OAuth route → 0.85, because Codex caps the window - at 272K and the default 50% trigger would compact at ~136K. Gated by - ``allow_codex_gpt55_autoraise`` so the user can opt back down to the - global default (the caller passes the config flag through here). + - gpt-5.5 on the Codex OAuth route → 0.60, because Codex caps the window + at 272K and the default 50% trigger would compact at ~136K (see + ``_CODEX_GPT55_COMPACTION_THRESHOLD`` for why this is no longer 0.85). + Gated by ``allow_codex_gpt55_autoraise`` so the user can opt back down + to the global default (the caller passes the config flag through here). + The caller treats this value as a floor — it takes + ``max(user_threshold, 0.60)`` so a higher user-set threshold survives + (see ``agent.agent_init._resolve_compression_threshold``). Returns a float in (0, 1] to override the global ``compression.threshold`` config value, or ``None`` to leave the user's config value unchanged. diff --git a/agent/context_compressor.py b/agent/context_compressor.py index 98d226b46af08..bb5b3fd21cd2b 100644 --- a/agent/context_compressor.py +++ b/agent/context_compressor.py @@ -25,6 +25,10 @@ from agent.auxiliary_client import call_llm, _is_connection_error from agent.context_engine import ContextEngine +from agent.tool_output_precompaction import ( + build_tool_output_digest, + extract_failure_lines, +) from agent.model_metadata import ( MINIMUM_CONTEXT_LENGTH, get_model_context_length, @@ -111,6 +115,14 @@ _FALLBACK_SUMMARY_MAX_CHARS = 8_000 _FALLBACK_TURN_MAX_CHARS = 700 +# When the LLM summary fails and the deterministic fallback handoff is used, +# tool outputs that survived in the protected head/tail are themselves shrunk +# to bounded digests. Without this, a single CI/CodeQL log in the tail keeps +# the "compressed" transcript at 100K+ tokens after a summarizer outage. +# Trigger ≈ 2K tokens; each digest is capped at ≈ 1K tokens. +_FALLBACK_TOOL_DIGEST_TRIGGER_CHARS = 8_000 +_FALLBACK_TOOL_DIGEST_MAX_CHARS = 4_000 + _PATH_MENTION_RE = re.compile(r"(?:/|~/?|[A-Za-z]:\\)[^\s`'\")\]}<>]+") @@ -602,7 +614,7 @@ def __init__( model: str, threshold_percent: float = 0.50, protect_first_n: int = 3, - protect_last_n: int = 20, + protect_last_n: int = 10, summary_target_ratio: float = 0.20, quiet_mode: bool = False, summary_model_override: str = None, @@ -969,7 +981,23 @@ def _serialize_for_summary(self, turns: List[Dict[str, Any]]) -> str: All content is redacted before serialization to prevent secrets (API keys, tokens, passwords) from leaking into the summary that gets sent to the auxiliary model and persisted across compactions. + + Oversized tool results are replaced with a deterministic structured + digest (head + tail + matched failure/error lines + stats) instead + of a blind head/tail slice — a naive slice of a 500K-char CI log + loses exactly the failing-test lines the summary needs, and feeding + the raw bulk to the summarizer is what makes aux models time out. """ + # tool_call_id -> tool name, so tool-result digests can be labeled. + call_id_to_name: Dict[str, str] = {} + for msg in turns: + if msg.get("role") == "assistant": + for tc in msg.get("tool_calls") or []: + cid = _extract_tool_call_id(tc) + if cid: + name, _ = _extract_tool_call_name_and_args(tc) + call_id_to_name[cid] = name + parts = [] for msg in turns: role = msg.get("role", "unknown") @@ -979,7 +1007,11 @@ def _serialize_for_summary(self, turns: List[Dict[str, Any]]) -> str: if role == "tool": tool_id = msg.get("tool_call_id", "") if len(content) > self._CONTENT_MAX: - content = content[:self._CONTENT_HEAD] + "\n...[truncated]...\n" + content[-self._CONTENT_TAIL:] + content = build_tool_output_digest( + content, + tool_name=call_id_to_name.get(tool_id, "unknown"), + max_chars=self._CONTENT_MAX, + ) parts.append(f"[TOOL RESULT {tool_id}]: {content}") continue @@ -1118,12 +1150,15 @@ def _collect_paths_from_jsonish(obj: Any) -> None: tool_actions.append( _summarize_tool_result(tool_name, tool_args, text or "") ) - if re.search( - r"\b(error|failed|exception|traceback|timeout|timed out|fatal)\b", - text, - re.I, - ): - blockers.append(text[:500]) + # Extract failure lines from the FULL (redacted) tool output, + # not the 700-char flattened turn — the failing-test line of + # a CI/CodeQL log usually sits deep in the body and would be + # lost to the flattening truncation above. + full_tool_text = redact_sensitive_text( + _content_text_for_contains(msg.get("content")) + ) + for failure_line in extract_failure_lines(full_tool_text, limit=3): + blockers.append(f"[{tool_name}] {failure_line}") def _bullets(items: list[str], limit: int = 8) -> str: unique: list[str] = [] @@ -1203,6 +1238,54 @@ def _bullets(items: list[str], limit: int = 8) -> str: summary = summary[: _FALLBACK_SUMMARY_MAX_CHARS - 42].rstrip() + "\n...[fallback summary truncated]" return summary + def _shrink_tool_outputs_for_fallback( + self, messages: List[Dict[str, Any]] + ) -> tuple[List[Dict[str, Any]], int]: + """Digest oversized tool outputs after a summary-failure fallback. + + When the LLM summarizer fails, the middle window is replaced by the + deterministic fallback handoff — but huge tool outputs in the + *protected* head/tail survive verbatim and can leave the compacted + transcript at 100K+ tokens. This pass keeps every protected message + in place (protect_first_n / protect_last_n semantics are unchanged) + but replaces each oversized tool-result body with a bounded + structured digest that retains the exit code, head/tail lines, and + matched failure/error lines needed for diagnosis. + + Deterministic, no LLM call. Returns ``(messages, shrunk_count)``; + the input list is never mutated. + """ + call_id_to_name: Dict[str, str] = {} + for msg in messages: + if msg.get("role") == "assistant": + for tc in msg.get("tool_calls") or []: + cid = _extract_tool_call_id(tc) + if cid: + name, _ = _extract_tool_call_name_and_args(tc) + call_id_to_name[cid] = name + + shrunk = 0 + result: List[Dict[str, Any]] = [] + for msg in messages: + content = msg.get("content") + if ( + msg.get("role") == "tool" + and isinstance(content, str) + and len(content) > _FALLBACK_TOOL_DIGEST_TRIGGER_CHARS + ): + digest = build_tool_output_digest( + content, + tool_name=call_id_to_name.get( + str(msg.get("tool_call_id") or ""), "unknown" + ), + max_chars=_FALLBACK_TOOL_DIGEST_MAX_CHARS, + ) + result.append({**msg, "content": digest}) + shrunk += 1 + else: + result.append(msg) + return result, shrunk + def _fallback_to_main_for_compression(self, e: Exception, reason: str) -> None: """Switch from a separate ``summary_model`` back to the main model. @@ -2158,6 +2241,27 @@ def compress(self, messages: List[Dict[str, Any]], current_tokens: int = None, f # Port of Kilo-Org/kilocode#9434. compressed = _strip_historical_media(compressed) + # Summary-failure fallback: the LLM handoff is gone, so oversized tool + # outputs that survived in the protected head/tail must be shrunk + # deterministically — otherwise a single CI/test log keeps the + # "compressed" transcript far above the threshold and the next turn + # immediately re-triggers compaction against a failing summarizer. + if self._last_summary_fallback_used: + _pre_shrink_estimate = estimate_messages_tokens_rough(compressed) + compressed, _shrunk_count = self._shrink_tool_outputs_for_fallback(compressed) + if _shrunk_count and not self.quiet_mode: + logger.warning( + "Compression fallback engaged (reason=%s): summary model " + "unavailable — digested %d oversized protected tool " + "output(s) deterministically; ~%d -> ~%d rough tokens " + "across %d messages", + self._last_summary_error or "summary unavailable", + _shrunk_count, + _pre_shrink_estimate, + estimate_messages_tokens_rough(compressed), + len(compressed), + ) + new_estimate = estimate_messages_tokens_rough(compressed) saved_estimate = display_tokens - new_estimate diff --git a/agent/tool_output_precompaction.py b/agent/tool_output_precompaction.py new file mode 100644 index 0000000000000..e1ede7b8ac43a --- /dev/null +++ b/agent/tool_output_precompaction.py @@ -0,0 +1,279 @@ +"""Deterministic structured digests for oversized tool outputs. + +Large tool results (CI logs, test runs, CodeQL scans, long poll output) are +the dominant cause of context-compaction pain: they balloon the summarizer +prompt until the auxiliary model times out, and when the LLM summary fails +they survive in the protected tail and leave the "compressed" transcript at +100K+ tokens. + +This module builds a bounded, deterministic digest of such outputs — no LLM +call required — that preserves what matters for failure diagnosis: + + * tool name and exit code / status when detectable + * the first lines (command echo, headers) + * the last lines (final test summary, exit trailer) + * lines matching failure/error patterns from the omitted middle + * file paths / URLs mentioned on those failure lines + * length statistics (lines / chars / rough tokens) so the model knows how + much bulk was dropped + +The digest is used by the context compressor when serializing tool results +into the summarizer prompt, and as the deterministic shrink applied to +protected tool outputs when the LLM summary fails (fallback compaction). +It never touches the live tool-result path for normal-sized outputs. +""" + +from __future__ import annotations + +import re + +# Outputs at or below this size pass through unchanged — small results carry +# their own context and digesting them would lose more than it saves. +DIGEST_TRIGGER_CHARS = 6_000 + +# Default ceiling for a produced digest. Callers can lower it (summarizer +# prompt serialization) or keep it (fallback shrink of protected outputs). +DIGEST_MAX_CHARS = 4_000 + +_DIGEST_HEADER_PREFIX = "[tool output digest" + +# Per-line clip so a single minified-JS / base64 line can't eat the budget. +_LINE_CLIP_CHARS = 240 + +_HEAD_LINES = 15 +_TAIL_LINES = 25 +_MAX_FAILURE_LINES = 40 + +# Failure/error line matcher. Tuned for CI logs, pytest/jest output, CodeQL +# scan results, compiler output, and shell traces. Deliberately excludes +# bare "warning" — CI logs emit thousands of benign warnings and they would +# crowd out the actual failures. +_FAILURE_LINE_RE = re.compile( + r"(?:\b(?:error|errors|err!|fail|failed|failure|failures|failing|fatal|" + r"exception|traceback|panic(?:ked)?|assert|assertion|denied|refused|" + r"unauthorized|forbidden|timed.?out|timeout|segfault|segmentation fault|" + r"core dumped|killed|oom|out of memory|critical|severity|unreachable|" + r"cannot|could not|unable to|not found|no such file|missing|broken|" + r"rejected|exit code [1-9]|non-zero)\b|✗|✖|❌|FAILED|ERROR)", + re.IGNORECASE, +) + +# Exit code extraction: JSON tool envelopes ({"exit_code": 1, ...}) and +# plain-text trailers ("exit code 1", "exited with code 2", "Exit status 1"). +_EXIT_CODE_RES = ( + re.compile(r'"exit_code"\s*:\s*(-?\d+)'), + re.compile(r"\bexit(?:ed)?(?:\s+with)?(?:\s+(?:code|status))\s*[:=]?\s*(-?\d+)", re.IGNORECASE), +) + +# Path / URL handles worth carrying into the digest. Restricted to failure +# lines so the digest doesn't enumerate every file a build touched. +_PATH_OR_URL_RE = re.compile( + r"(?:https?://[^\s`'\")\]}<>]+|(?:/|~/|[A-Za-z]:\\)[^\s`'\")\]}<>:]+)" +) + + +def is_tool_output_digest(text: str) -> bool: + """True when *text* is already a digest produced by this module.""" + return isinstance(text, str) and text.lstrip().startswith(_DIGEST_HEADER_PREFIX) + + +def extract_exit_code(content: str) -> str | None: + """Best-effort exit code / status extraction from a tool result body.""" + if not content: + return None + for pattern in _EXIT_CODE_RES: + match = pattern.search(content) + if match: + return match.group(1) + return None + + +def extract_failure_lines(content: str, *, limit: int = 10) -> list[str]: + """Return up to *limit* unique failure/error lines from *content*. + + Deterministic: lines are returned in order of first appearance, clipped + to ``_LINE_CLIP_CHARS``, with exact duplicates collapsed. + """ + if not content: + return [] + out: list[str] = [] + seen: set[str] = set() + for line in content.splitlines(): + stripped = line.strip() + if not stripped or stripped in seen: + continue + if _FAILURE_LINE_RE.search(stripped): + seen.add(stripped) + out.append(_clip_line(stripped)) + if len(out) >= limit: + break + return out + + +def _clip_line(line: str) -> str: + if len(line) <= _LINE_CLIP_CHARS: + return line + return line[: _LINE_CLIP_CHARS - 12] + " ...[clipped]" + + +def _collect_failure_matches( + lines: list[str], start_line_no: int +) -> tuple[list[tuple[int, str]], int]: + """Collect unique (1-based line number, clipped text) failure matches. + + Returns ``(unique_matches, total_match_count)``. Duplicate line bodies + (poll loops, repeated retry errors) count toward the total but appear + only once, annotated at first occurrence. + """ + matches: list[tuple[int, str]] = [] + seen: set[str] = set() + total = 0 + for offset, line in enumerate(lines): + stripped = line.strip() + if not stripped: + continue + if not _FAILURE_LINE_RE.search(stripped): + continue + total += 1 + if stripped in seen: + continue + seen.add(stripped) + matches.append((start_line_no + offset, _clip_line(stripped))) + return matches, total + + +def _select_spread(items: list, limit: int) -> list: + """Keep the first and last halves of *items* when over *limit*. + + Compile errors cluster early, test summaries cluster late — keeping both + ends preserves more diagnostic signal than a plain head slice. + """ + if len(items) <= limit: + return items + first = limit // 2 + last = limit - first + return items[:first] + items[-last:] + + +def build_tool_output_digest( + content: str, + *, + tool_name: str = "", + max_chars: int = DIGEST_MAX_CHARS, + head_lines: int = _HEAD_LINES, + tail_lines: int = _TAIL_LINES, + max_failure_lines: int = _MAX_FAILURE_LINES, +) -> str: + """Build a bounded deterministic digest of a large tool output. + + Always returns a string no longer than ``max_chars`` (modulo a tiny + constant for the truncation marker). Same input → same output. + """ + lines = content.splitlines() + total_lines = len(lines) + total_chars = len(content) + rough_tokens = total_chars // 4 + exit_code = extract_exit_code(content) + + def _assemble(n_head: int, n_tail: int, n_matches: int) -> str: + head = [_clip_line(l) for l in lines[:n_head]] + if total_lines > n_head + n_tail: + tail = [_clip_line(l) for l in lines[total_lines - n_tail:]] + middle = lines[n_head: total_lines - n_tail] + middle_start = n_head + 1 + else: + tail = [] + middle = [] + middle_start = n_head + 1 + matches, total_matches = _collect_failure_matches(middle, middle_start) + kept = _select_spread(matches, n_matches) + + # Path/URL handles from failure lines only — keeps the list relevant + # to diagnosis instead of enumerating every artifact the run touched. + handles: list[str] = [] + seen_handles: set[str] = set() + for _, match_line in kept: + for handle in _PATH_OR_URL_RE.findall(match_line): + handle = handle.rstrip(".,:;") + if handle and handle not in seen_handles and len(handles) < 8: + seen_handles.add(handle) + handles.append(handle) + + omitted_lines = max(0, total_lines - len(head) - len(tail)) + header_bits = [ + f"{_DIGEST_HEADER_PREFIX}: {tool_name or 'unknown'}", + f"{total_lines:,} lines / {total_chars:,} chars (~{rough_tokens:,} tokens)", + ] + if exit_code is not None: + header_bits.append(f"exit_code={exit_code}") + header_bits.append( + f"kept first {len(head)} + last {len(tail)} lines" + + (f" + {len(kept)} of {total_matches} failure/error line(s)" if total_matches else "") + + f"; {omitted_lines:,} middle lines omitted" + ) + parts = [" | ".join(header_bits) + "]"] + if head: + parts.append("--- first lines ---") + parts.extend(head) + if kept: + parts.append( + f"--- failure/error lines from omitted middle " + f"({len(kept)} of {total_matches} matches, deduplicated) ---" + ) + parts.extend(f"L{line_no}: {text}" for line_no, text in kept) + if handles: + parts.append("--- paths/urls on failure lines ---") + parts.append(", ".join(handles)) + if tail: + parts.append("--- last lines ---") + parts.extend(tail) + return "\n".join(parts) + + # Progressively tighter layouts; the first one that fits wins. All + # steps are pure functions of the input, so the result is deterministic. + layouts = ( + (head_lines, tail_lines, max_failure_lines), + (max(3, head_lines // 2), max(8, tail_lines // 2), max(10, max_failure_lines // 2)), + (3, 8, 6), + (2, 5, 3), + ) + digest = "" + for layout in layouts: + digest = _assemble(*layout) + if len(digest) <= max_chars: + return digest + # Pathological case (e.g. max_chars very small): hard-truncate but keep + # the header so the stats survive. + return digest[: max(0, max_chars - 22)].rstrip() + "\n...[digest truncated]" + + +def maybe_digest_tool_output( + content, + *, + tool_name: str = "", + trigger_chars: int = DIGEST_TRIGGER_CHARS, + max_chars: int = DIGEST_MAX_CHARS, +): + """Digest *content* when it is a large string; return it unchanged otherwise. + + Non-string content (multimodal lists, dict envelopes) and small outputs + pass through untouched, as do outputs that are already digests. + """ + if not isinstance(content, str): + return content + if len(content) <= trigger_chars: + return content + if is_tool_output_digest(content): + return content + return build_tool_output_digest(content, tool_name=tool_name, max_chars=max_chars) + + +__all__ = [ + "DIGEST_TRIGGER_CHARS", + "DIGEST_MAX_CHARS", + "build_tool_output_digest", + "extract_exit_code", + "extract_failure_lines", + "is_tool_output_digest", + "maybe_digest_tool_output", +] diff --git a/cli-config.yaml.example b/cli-config.yaml.example index 8ce9ad8e19acf..eb690b0d429b3 100644 --- a/cli-config.yaml.example +++ b/cli-config.yaml.example @@ -358,7 +358,7 @@ tool_loop_guardrails: # 1. Tracks actual token usage from API responses (not estimates) # 2. When prompt_tokens >= threshold% of model's context_length, triggers compression # 3. Protects first 3 turns (system prompt, initial request, first response) -# 4. Protects last N turns (default 20 messages = ~10 full turns of recent context) +# 4. Protects last N turns (default 10 messages = ~5 full turns of recent context) # 5. Summarizes middle turns using a fast/cheap model # 6. Inserts summary as a user message, continues conversation seamlessly # @@ -381,10 +381,10 @@ compression: # Range: 0.10 - 0.80 target_ratio: 0.20 - # Number of most-recent messages to always preserve (default: 20 ≈ 10 full turns) + # Number of most-recent messages to always preserve (default: 10 ≈ 5 full turns) # Higher values keep more recent conversation intact at the cost of more aggressive # compression of older turns. - protect_last_n: 20 + protect_last_n: 10 # Number of non-system messages to protect at the head of the transcript, in # ADDITION to the system prompt (which is always implicitly protected). diff --git a/hermes_cli/config.py b/hermes_cli/config.py index 494c5ddfe3ab5..919d867b291fe 100644 --- a/hermes_cli/config.py +++ b/hermes_cli/config.py @@ -1124,7 +1124,11 @@ def _ensure_hermes_home_managed(home: Path): "enabled": True, "threshold": 0.50, # compress when context usage exceeds this ratio "target_ratio": 0.20, # fraction of threshold to preserve as recent tail - "protect_last_n": 20, # minimum recent messages to keep uncompressed + "protect_last_n": 10, # minimum recent messages to keep uncompressed + # (lowered from 20 — a smaller protected tail + # keeps the summarizer payload bounded and + # compaction reliable; raise it back via + # config.yaml if you want a longer verbatim tail) "hygiene_hard_message_limit": 400, # gateway session-hygiene force-compress threshold by message count "protect_first_n": 3, # non-system head messages always preserved # verbatim, in ADDITION to the system prompt @@ -1144,15 +1148,19 @@ def _ensure_hermes_home_managed(home: Path): # True if you'd rather pause than silently lose # context turns when your aux model is flaky. "codex_gpt55_autoraise": True, # When True, gpt-5.5 on the ChatGPT Codex OAuth - # route raises its compaction trigger to 85% (vs the + # route raises its compaction trigger to 60% (vs the # global `threshold` above). Codex hard-caps gpt-5.5 # at a 272K window, so the default 50% would compact - # at ~136K and waste half the usable context. Set to - # False to opt back down to the global threshold - # (e.g. 0.50) for Codex gpt-5.5 sessions. Only this - # exact route is affected — gpt-5.5 on OpenAI's - # direct API, OpenRouter, and Copilot keep the - # global threshold regardless. + # at ~136K and waste usable context. The trigger was + # previously raised all the way to 85% (~231K), but + # summarizing a window that large routinely timed out + # the auxiliary compression model and exhausted its + # fallbacks — 60% (~163K) balances window use against + # compaction reliability. Set to False to opt back + # down to the global threshold (e.g. 0.50) for Codex + # gpt-5.5 sessions. Only this exact route is affected + # — gpt-5.5 on OpenAI's direct API, OpenRouter, and + # Copilot keep the global threshold regardless. }, # Anthropic prompt caching (Claude via OpenRouter or native Anthropic API). @@ -1251,7 +1259,9 @@ def _ensure_hermes_home_managed(home: Path): "model": "", "base_url": "", "api_key": "", - "timeout": 120, # seconds — compression summarises large contexts; increase for local models + "timeout": 300, # seconds — compression summarises large contexts (a + # threshold-sized window can take minutes on slow or + # reasoning aux models; 120s caused timeouts mid-compaction) "extra_body": {}, }, # Note: session_search no longer uses an auxiliary LLM (PR #27590 — @@ -6044,7 +6054,7 @@ def show_config(): if enabled: print(f" Threshold: {compression.get('threshold', 0.50) * 100:.0f}%") print(f" Target ratio: {compression.get('target_ratio', 0.20) * 100:.0f}% of threshold preserved") - print(f" Protect last: {compression.get('protect_last_n', 20)} messages") + print(f" Protect last: {compression.get('protect_last_n', 10)} messages") print(f" Protect first: {compression.get('protect_first_n', 3)} non-system head messages") _aux_comp = config.get('auxiliary', {}).get('compression', {}) _sm = _aux_comp.get('model', '') or '(auto)' diff --git a/tests/agent/test_arcee_trinity_overrides.py b/tests/agent/test_arcee_trinity_overrides.py index 91a5fa743bb58..5f09baba2c0e6 100644 --- a/tests/agent/test_arcee_trinity_overrides.py +++ b/tests/agent/test_arcee_trinity_overrides.py @@ -83,9 +83,11 @@ def test_compression_threshold_default_none_for_other_models() -> None: # ChatGPT's Codex OAuth backend caps gpt-5.5 at a 272K window (verified live: # ~330K-token request rejected with context_length_exceeded, ~250K accepted). # The default 50% compaction trigger would fire at ~136K — half the usable -# window — so this route raises the trigger to 85%. Only the Codex OAuth route -# is affected; the same slug on OpenAI direct / OpenRouter / Copilot exposes a -# larger window and keeps the user's global threshold. +# window — so this route floors the trigger at 60% (lowered from the original +# 85%, which made summarizer payloads too large to digest). Only the Codex +# OAuth route is affected; the same slug on OpenAI direct / OpenRouter / +# Copilot exposes a larger window and keeps the user's global threshold. The +# floor never lowers a user-set threshold that already meets or exceeds it. # --------------------------------------------------------------------------- @@ -125,9 +127,12 @@ def test_is_codex_gpt55_rejects_non_55_models(model) -> None: def test_compression_threshold_for_codex_gpt55() -> None: - assert _compression_threshold_for_model("gpt-5.5", "openai-codex") == 0.85 - assert _compression_threshold_for_model("gpt-5.5-pro", "openai-codex") == 0.85 - assert _compression_threshold_for_model("openai/gpt-5.5", "openai-codex") == 0.85 + # 0.60, lowered from the original 0.85: compacting at ~231K made the + # summarizer input large enough to time out the auxiliary model, so the + # autoraise now stops at ~163K (60% of the 272K Codex window). + assert _compression_threshold_for_model("gpt-5.5", "openai-codex") == 0.60 + assert _compression_threshold_for_model("gpt-5.5-pro", "openai-codex") == 0.60 + assert _compression_threshold_for_model("openai/gpt-5.5", "openai-codex") == 0.60 def test_compression_threshold_codex_gpt55_other_routes_unaffected() -> None: @@ -157,3 +162,75 @@ def test_compression_threshold_opt_out_does_not_disable_trinity() -> None: ) == 0.75 ) + + +# --------------------------------------------------------------------------- +# Effective-threshold resolution (agent_init): the Codex gpt-5.5 autoraise is +# a floor — max(user threshold, 0.60) — never a hard override that could +# silently lower a user-set compression.threshold. +# --------------------------------------------------------------------------- + + +def test_resolve_threshold_codex_gpt55_raises_default_with_notice() -> None: + from agent.agent_init import _resolve_compression_threshold + + threshold, autoraised = _resolve_compression_threshold( + 0.50, "gpt-5.5", "openai-codex", codex_gpt55_autoraise=True + ) + assert threshold == pytest.approx(0.60) + assert autoraised == {"from": 0.50, "to": 0.60} + + +def test_resolve_threshold_codex_gpt55_preserves_higher_user_threshold() -> None: + # A user-set compression.threshold of 0.75 must survive on Codex gpt-5.5 + # with the autoraise enabled — the 0.60 override is a floor, not a cap. + from agent.agent_init import _resolve_compression_threshold + + threshold, autoraised = _resolve_compression_threshold( + 0.75, "gpt-5.5", "openai-codex", codex_gpt55_autoraise=True + ) + assert threshold == pytest.approx(0.75) + # No raise happened, so no "raised" notice either. + assert autoraised is None + + +def test_resolve_threshold_codex_gpt55_equal_user_threshold_no_notice() -> None: + from agent.agent_init import _resolve_compression_threshold + + threshold, autoraised = _resolve_compression_threshold( + 0.60, "gpt-5.5", "openai-codex", codex_gpt55_autoraise=True + ) + assert threshold == pytest.approx(0.60) + assert autoraised is None + + +def test_resolve_threshold_codex_gpt55_opt_out_keeps_user_threshold() -> None: + from agent.agent_init import _resolve_compression_threshold + + threshold, autoraised = _resolve_compression_threshold( + 0.50, "gpt-5.5", "openai-codex", codex_gpt55_autoraise=False + ) + assert threshold == pytest.approx(0.50) + assert autoraised is None + + +def test_resolve_threshold_trinity_still_replaces_silently() -> None: + # Arcee Trinity keeps its long-standing behavior: replace the global + # threshold outright (even downward) with no notice. + from agent.agent_init import _resolve_compression_threshold + + threshold, autoraised = _resolve_compression_threshold( + 0.90, "trinity-large-thinking", "openrouter", codex_gpt55_autoraise=True + ) + assert threshold == pytest.approx(0.75) + assert autoraised is None + + +def test_resolve_threshold_no_override_returns_user_threshold() -> None: + from agent.agent_init import _resolve_compression_threshold + + threshold, autoraised = _resolve_compression_threshold( + 0.50, "claude-sonnet-4.6", "anthropic", codex_gpt55_autoraise=True + ) + assert threshold == pytest.approx(0.50) + assert autoraised is None diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py index 1b4242e0e017b..93c0991305184 100644 --- a/tests/agent/test_context_compressor.py +++ b/tests/agent/test_context_compressor.py @@ -1591,11 +1591,16 @@ def test_threshold_floor_does_not_apply_above_128k(self): # 50% of 200K = 100K, which is above the 64K floor assert c.threshold_tokens == 100_000 - def test_default_protect_last_n_is_20(self): - """Default protect_last_n should be 20.""" + def test_default_protect_last_n_is_10(self): + """Default protect_last_n should be 10. + + Lowered from 20: a smaller protected tail keeps the summarizer + payload bounded so compaction stays reliable on slow aux models. + Users can raise it back via compression.protect_last_n in config. + """ with patch("agent.context_compressor.get_model_context_length", return_value=100_000): c = ContextCompressor(model="test", quiet_mode=True) - assert c.protect_last_n == 20 + assert c.protect_last_n == 10 def test_default_protect_first_n_is_3(self): """Default protect_first_n is 3 (system + 3 extra non-system messages = diff --git a/tests/agent/test_tool_output_precompaction.py b/tests/agent/test_tool_output_precompaction.py new file mode 100644 index 0000000000000..8afd82a69e132 --- /dev/null +++ b/tests/agent/test_tool_output_precompaction.py @@ -0,0 +1,322 @@ +"""Tests for agent/tool_output_precompaction.py — deterministic digests of +oversized tool outputs, and their integration with the context compressor +(summarizer-prompt serialization and the summary-failure fallback shrink).""" + +import pytest +from unittest.mock import MagicMock, patch + +from agent.context_compressor import ContextCompressor +from agent.tool_output_precompaction import ( + DIGEST_MAX_CHARS, + DIGEST_TRIGGER_CHARS, + build_tool_output_digest, + extract_exit_code, + extract_failure_lines, + is_tool_output_digest, + maybe_digest_tool_output, +) + + +def _make_ci_log() -> str: + """A realistic oversized CI/test log: command header, thousands of noise + lines, a few failure lines buried in the middle, and a summary trailer.""" + head = [f"$ pytest tests/ -q --maxfail=0 # header {i}" for i in range(5)] + noise = [f"tests/test_mod_{i}.py::test_case_{i} PASSED" for i in range(3000)] + noise[1200] = ( + "FAILED tests/test_alpha.py::test_compaction - AssertionError: digest mismatch" + ) + noise[1800] = ( + "ERROR tests/test_beta.py::test_timeout - TimeoutError: deadline exceeded" + ) + noise[2200] = "error: cannot open /var/log/ci/build.log: No such file or directory" + tail = [ + "=========== 2 failed, 2998 passed in 61.20s ===========", + "exit code 1", + ] + return "\n".join(head + noise + tail) + + +class TestBuildToolOutputDigest: + def test_digest_shrinks_large_output_and_is_bounded(self): + log = _make_ci_log() + assert len(log) > 100_000 # genuinely large input + + digest = build_tool_output_digest(log, tool_name="terminal", max_chars=4_000) + + assert len(digest) <= 4_000 + assert len(digest) < len(log) * 0.05 + + def test_digest_preserves_first_lines(self): + digest = build_tool_output_digest(_make_ci_log(), tool_name="terminal") + assert "# header 0" in digest + assert "--- first lines ---" in digest + + def test_digest_preserves_tail(self): + digest = build_tool_output_digest(_make_ci_log(), tool_name="terminal") + assert "2 failed, 2998 passed in 61.20s" in digest + assert "--- last lines ---" in digest + + def test_digest_preserves_failure_lines_from_omitted_middle(self): + digest = build_tool_output_digest(_make_ci_log(), tool_name="terminal") + assert "FAILED tests/test_alpha.py::test_compaction" in digest + assert "TimeoutError: deadline exceeded" in digest + assert "/var/log/ci/build.log" in digest + # The benign bulk between head and tail is dropped. + assert "tests/test_mod_1500.py::test_case_1500 PASSED" not in digest + + def test_digest_preserves_exit_status_metadata(self): + digest = build_tool_output_digest(_make_ci_log(), tool_name="terminal") + assert "exit_code=1" in digest + + def test_digest_includes_size_stats_and_tool_name(self): + log = _make_ci_log() + digest = build_tool_output_digest(log, tool_name="terminal") + assert digest.startswith("[tool output digest: terminal") + assert f"{len(log):,} chars" in digest + assert f"{len(log.splitlines()):,} lines" in digest + assert "tokens" in digest + assert "middle lines omitted" in digest + + def test_digest_is_deterministic(self): + log = _make_ci_log() + first = build_tool_output_digest(log, tool_name="terminal") + second = build_tool_output_digest(log, tool_name="terminal") + assert first == second + + def test_digest_is_recognized_by_is_tool_output_digest(self): + digest = build_tool_output_digest(_make_ci_log(), tool_name="terminal") + assert is_tool_output_digest(digest) is True + assert is_tool_output_digest("plain tool output") is False + + def test_digest_bounded_even_for_single_giant_line(self): + # Minified JS / base64 blob: one line, no newlines to slice on. + blob = "error " + ("x" * 50_000) + digest = build_tool_output_digest(blob, tool_name="fetch", max_chars=2_000) + assert len(digest) <= 2_000 + assert digest.startswith("[tool output digest: fetch") + + +class TestMaybeDigestToolOutput: + def test_small_output_passes_through_unchanged(self): + small = "ok: 3 files changed, 1 insertion(+)\nexit code 0" + assert maybe_digest_tool_output(small, tool_name="terminal") is small + + def test_output_at_trigger_size_passes_through_unchanged(self): + at_trigger = "x" * DIGEST_TRIGGER_CHARS + assert maybe_digest_tool_output(at_trigger) is at_trigger + + def test_large_output_is_digested(self): + log = _make_ci_log() + result = maybe_digest_tool_output(log, tool_name="terminal") + assert is_tool_output_digest(result) + assert len(result) <= DIGEST_MAX_CHARS + + def test_non_string_content_passes_through_unchanged(self): + multimodal = [{"type": "image_url", "image_url": {"url": "data:..."}}] + assert maybe_digest_tool_output(multimodal) is multimodal + + def test_existing_digest_is_not_redigested(self): + digest = build_tool_output_digest(_make_ci_log(), tool_name="terminal") + padded = digest + "\n" + ("pad " * 3000) # back over the trigger + # A real digest never exceeds the trigger, but defend against double + # processing: a digest-prefixed body must pass through untouched. + assert maybe_digest_tool_output(padded) is padded + + +class TestExtractHelpers: + def test_extract_exit_code_from_json_envelope(self): + assert extract_exit_code('{"exit_code": 2, "stdout": "..."}') == "2" + + def test_extract_exit_code_from_plain_trailer(self): + assert extract_exit_code("Process exited with code 137") == "137" + assert extract_exit_code("command finished\nexit status: 1\n") == "1" + + def test_extract_exit_code_absent(self): + assert extract_exit_code("all good, nothing numeric here") is None + assert extract_exit_code("") is None + + def test_extract_failure_lines_dedupes_and_limits(self): + content = "\n".join( + ["ok line"] + + ["ConnectionError: connection refused"] * 50 + + [f"FAILED tests/test_{i}.py::t - AssertionError" for i in range(10)] + ) + lines = extract_failure_lines(content, limit=3) + assert len(lines) == 3 + # Order of first appearance, exact duplicates collapsed. + assert lines[0] == "ConnectionError: connection refused" + assert lines[1].startswith("FAILED tests/test_0.py") + assert lines[2].startswith("FAILED tests/test_1.py") + + def test_extract_failure_lines_empty_when_no_failures(self): + assert extract_failure_lines("all 100 tests passed\ndone") == [] + + +def _make_compressor(**kwargs): + with patch( + "agent.context_compressor.get_model_context_length", return_value=100_000 + ): + return ContextCompressor(model="test/model", quiet_mode=True, **kwargs) + + +def _make_giant_tool_log() -> str: + """>8K chars (above the fallback digest trigger) with a buried failure.""" + lines = [ + f"bulk filler line {i} with padding text to inflate the output size" + for i in range(400) + ] + lines[200] = "MIDDLE-MARKER-SHOULD-BE-DROPPED with more padding text here" + lines[210] = "FAILED tests/test_core.py::test_main - RuntimeError: boom" + lines.append("exit code 1") + return "\n".join(lines) + + +class TestSerializeForSummaryUsesDigest: + """The summarizer prompt must receive a structured digest of oversized + tool results — not the raw bulk (aux-model timeouts) and not a blind + head/tail slice (loses the failing-test lines).""" + + def _turns(self, tool_content): + return [ + { + "role": "assistant", + "content": "Running the tests", + "tool_calls": [ + { + "id": "call-9", + "function": {"name": "terminal", "arguments": '{"command":"pytest"}'}, + } + ], + }, + {"role": "tool", "tool_call_id": "call-9", "content": tool_content}, + ] + + def test_oversized_tool_result_serialized_as_labeled_digest(self): + c = _make_compressor() + giant = _make_giant_tool_log() + assert len(giant) > c._CONTENT_MAX + + text = c._serialize_for_summary(self._turns(giant)) + + assert "[tool output digest: terminal" in text + assert "FAILED tests/test_core.py::test_main" in text + assert "exit_code=1" in text + assert "MIDDLE-MARKER-SHOULD-BE-DROPPED" not in text + + def test_small_tool_result_serialized_verbatim(self): + c = _make_compressor() + small = "3 passed in 0.12s\nexit code 0" + text = c._serialize_for_summary(self._turns(small)) + assert small in text + assert "[tool output digest" not in text + + +class TestFallbackShrinksProtectedToolOutputs: + """When the LLM summary fails, oversized tool outputs surviving in the + protected head/tail must be digested deterministically so the fallback + result is bounded — a giant log must not survive compaction verbatim.""" + + def _messages(self, giant): + return [ + {"role": "system", "content": "sys"}, + {"role": "user", "content": "investigate the CI failure"}, + {"role": "assistant", "content": "looking into it"}, + {"role": "user", "content": "any progress?"}, + {"role": "assistant", "content": "narrowing it down"}, + {"role": "user", "content": "run the tests"}, + { + "role": "assistant", + "content": "running", + "tool_calls": [ + { + "id": "call-1", + "function": {"name": "terminal", "arguments": '{"command":"pytest"}'}, + } + ], + }, + {"role": "tool", "tool_call_id": "call-1", "content": giant}, + ] + + def test_summary_failure_digests_giant_tool_output_in_protected_tail(self): + c = _make_compressor(protect_first_n=1, protect_last_n=2) + giant = _make_giant_tool_log() + msgs = self._messages(giant) + + with patch( + "agent.context_compressor.call_llm", + side_effect=Exception("aux model timeout"), + ): + result = c.compress(msgs) + + assert c._last_summary_fallback_used is True + tool_msg = next(m for m in result if m.get("role") == "tool") + # Bounded digest, not the verbatim log. + assert is_tool_output_digest(tool_msg["content"]) + assert len(tool_msg["content"]) < len(giant) // 4 + assert "MIDDLE-MARKER-SHOULD-BE-DROPPED" not in tool_msg["content"] + # Diagnostic signal survives the shrink. + assert "FAILED tests/test_core.py::test_main" in tool_msg["content"] + assert "exit_code=1" in tool_msg["content"] + # The whole fallback transcript is bounded well below the input. + total = sum( + len(m["content"]) for m in result if isinstance(m.get("content"), str) + ) + assert total < len(giant) + + def test_summary_failure_does_not_mutate_input_messages(self): + c = _make_compressor(protect_first_n=1, protect_last_n=2) + giant = _make_giant_tool_log() + msgs = self._messages(giant) + + with patch( + "agent.context_compressor.call_llm", + side_effect=Exception("aux model timeout"), + ): + c.compress(msgs) + + assert msgs[-1]["content"] == giant + + def test_successful_summary_leaves_protected_tool_output_verbatim(self): + # The digest pass is a fallback-only shrink; with a working + # summarizer the protected tail keeps its raw tool output. + c = _make_compressor(protect_first_n=1, protect_last_n=2) + giant = _make_giant_tool_log() + + mock_response = MagicMock() + mock_response.choices = [MagicMock()] + mock_response.choices[0].message.content = "summary text" + with patch( + "agent.context_compressor.call_llm", return_value=mock_response + ): + result = c.compress(self._messages(giant)) + + assert c._last_summary_fallback_used is False + tool_msg = next(m for m in result if m.get("role") == "tool") + assert tool_msg["content"] == giant + + def test_shrink_helper_skips_small_and_non_string_tool_outputs(self): + c = _make_compressor() + msgs = [ + {"role": "tool", "tool_call_id": "a", "content": "short result"}, + {"role": "tool", "tool_call_id": "b", "content": [{"type": "text"}]}, + {"role": "user", "content": "x" * 50_000}, # non-tool: untouched + ] + shrunk_msgs, count = c._shrink_tool_outputs_for_fallback(msgs) + assert count == 0 + assert shrunk_msgs == msgs + + def test_shrink_helper_labels_digest_with_tool_name(self): + c = _make_compressor() + msgs = [ + { + "role": "assistant", + "content": "", + "tool_calls": [ + {"id": "call-7", "function": {"name": "codeql_scan", "arguments": "{}"}} + ], + }, + {"role": "tool", "tool_call_id": "call-7", "content": _make_giant_tool_log()}, + ] + shrunk_msgs, count = c._shrink_tool_outputs_for_fallback(msgs) + assert count == 1 + assert shrunk_msgs[1]["content"].startswith("[tool output digest: codeql_scan") diff --git a/tests/hermes_cli/test_aux_config.py b/tests/hermes_cli/test_aux_config.py index 0bd978f93fcf3..97091529c3eb4 100644 --- a/tests/hermes_cli/test_aux_config.py +++ b/tests/hermes_cli/test_aux_config.py @@ -206,7 +206,7 @@ def test_reset_aux_to_auto_clears_routing_preserves_timeouts(tmp_path, monkeypat from hermes_cli.config import save_config cfg = load_config() - cfg["auxiliary"]["vision"]["timeout"] = 300 # user-tuned + cfg["auxiliary"]["vision"]["timeout"] = 240 # user-tuned (default is 120) save_config(cfg) n = _reset_aux_to_auto() @@ -220,9 +220,9 @@ def test_reset_aux_to_auto_clears_routing_preserves_timeouts(tmp_path, monkeypat assert v["base_url"] == "" assert v["api_key"] == "" # User-tuned timeout survives reset - assert cfg["auxiliary"]["vision"]["timeout"] == 300 + assert cfg["auxiliary"]["vision"]["timeout"] == 240 # Default compression timeout preserved - assert cfg["auxiliary"]["compression"]["timeout"] == 120 + assert cfg["auxiliary"]["compression"]["timeout"] == 300 def test_reset_aux_to_auto_idempotent(tmp_path, monkeypatch): diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.py index 3e3144fdfea7f..1c3475d376143 100644 --- a/tests/hermes_cli/test_config.py +++ b/tests/hermes_cli/test_config.py @@ -1144,3 +1144,41 @@ def test_unset_key_defaults_to_false(self, tmp_path): # gate ends up off and there's no leftover write_mode key. assert raw["memory"].get("write_approval", False) is False assert "write_mode" not in raw.get("memory", {}) + + +class TestCompactionReliabilityDefaults: + """Defaults retuned for compaction reliability. + + A protected tail of 20 messages plus an 85% Codex compaction trigger + produced summarizer payloads large enough to time out the auxiliary + model (120s) and strand sessions in preflight compression. The retuned + defaults: protect_last_n 10, Codex gpt-5.5 autoraise threshold 0.60, + auxiliary compression timeout 300s. + """ + + def test_compression_protect_last_n_default_is_10(self): + assert DEFAULT_CONFIG["compression"]["protect_last_n"] == 10 + + def test_global_compression_threshold_default_is_50_percent(self): + # The global trigger stays at 0.50 — only the Codex gpt-5.5 route + # autoraises (to 0.60, see below). + assert DEFAULT_CONFIG["compression"]["threshold"] == pytest.approx(0.50) + + def test_codex_gpt55_autoraise_compaction_threshold_is_60_percent(self): + # Lowered from 0.85: compacting at ~231K of the 272K Codex window + # made the summarizer input itself too large to digest reliably. + from agent.auxiliary_client import ( + _CODEX_GPT55_COMPACTION_THRESHOLD, + _compression_threshold_for_model, + ) + + assert _CODEX_GPT55_COMPACTION_THRESHOLD == pytest.approx(0.60) + assert _compression_threshold_for_model( + "gpt-5.5", "openai-codex" + ) == pytest.approx(0.60) + + def test_codex_gpt55_autoraise_enabled_by_default(self): + assert DEFAULT_CONFIG["compression"]["codex_gpt55_autoraise"] is True + + def test_auxiliary_compression_timeout_default_is_300(self): + assert DEFAULT_CONFIG["auxiliary"]["compression"]["timeout"] == 300 diff --git a/website/docs/developer-guide/agent-loop.md b/website/docs/developer-guide/agent-loop.md index da904d2ef0ae9..aafdb62ea209a 100644 --- a/website/docs/developer-guide/agent-loop.md +++ b/website/docs/developer-guide/agent-loop.md @@ -207,7 +207,7 @@ The fallback system also covers auxiliary tasks independently — vision, compre 1. Memory is flushed to disk first (preventing data loss) 2. Middle conversation turns are summarized into a compact summary -3. The last N messages are preserved intact (`compression.protect_last_n`, default: 20) +3. The last N messages are preserved intact (`compression.protect_last_n`, default: 10) 4. Tool call/result message pairs are kept together (never split) 5. A new session lineage ID is generated (compression creates a "child" session) diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.md index 93240a486c007..86c5ccec910d7 100644 --- a/website/docs/developer-guide/context-compression-and-caching.md +++ b/website/docs/developer-guide/context-compression-and-caching.md @@ -83,8 +83,8 @@ compression: enabled: true # Enable/disable compression (default: true) threshold: 0.50 # Fraction of context window (default: 0.50 = 50%) target_ratio: 0.20 # How much of threshold to keep as tail (default: 0.20) - protect_last_n: 20 # Minimum protected tail messages (default: 20) - codex_gpt55_autoraise: true # gpt-5.5 on Codex OAuth: raise trigger to 85% (default: true) + protect_last_n: 10 # Minimum protected tail messages (default: 10) + codex_gpt55_autoraise: true # gpt-5.5 on Codex OAuth: floor trigger at 60% (default: true) # Summarization model/provider configured under auxiliary: auxiliary: @@ -100,9 +100,9 @@ auxiliary: |-----------|---------|-------|-------------| | `threshold` | `0.50` | 0.0-1.0 | Compression triggers when prompt tokens ≥ `threshold × context_length` | | `target_ratio` | `0.20` | 0.10-0.80 | Controls tail protection token budget: `threshold_tokens × target_ratio` | -| `protect_last_n` | `20` | ≥1 | Minimum number of recent messages always preserved | +| `protect_last_n` | `10` | ≥1 | Minimum number of recent messages always preserved | | `protect_first_n` | `3` | (hardcoded) | System prompt + first exchange always preserved | -| `codex_gpt55_autoraise` | `true` | bool | Raise the trigger to 85% for gpt-5.5 on the ChatGPT Codex OAuth route (see below). Set `false` to keep the global `threshold` | +| `codex_gpt55_autoraise` | `true` | bool | Floor the trigger at 60% for gpt-5.5 on the ChatGPT Codex OAuth route (see below). Set `false` to keep the global `threshold` | ### Codex gpt-5.5 threshold autoraise @@ -110,10 +110,12 @@ The ChatGPT Codex OAuth backend hard-caps gpt-5.5 at a **272K** context window (the same slug exposes 1.05M on OpenAI's direct API and OpenRouter, and 400K on GitHub Copilot). At the default 50% trigger, compaction would fire at ~136K — half the window the model can actually use. When the active route is Codex -OAuth (`provider: openai-codex`) and the model is gpt-5.5, Hermes raises the -trigger to **85%** (~231K) and prints a one-time notice with the opt-out -command. Only this exact route is affected; gpt-5.5 on any other provider keeps -your global `threshold`. To opt back down to the global value: +OAuth (`provider: openai-codex`) and the model is gpt-5.5, Hermes floors the +trigger at **60%** (~163K) and prints a one-time notice with the opt-out +command. This is a **floor, not a replacement**: if your configured `threshold` +already meets or exceeds 0.60, it is left unchanged and no notice is shown. +Only this exact route is affected; gpt-5.5 on any other provider keeps your +global `threshold`. To opt back down to the global value: ```bash hermes config set compression.codex_gpt55_autoraise false diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md index cfd3001e24770..bf6c27b70f958 100644 --- a/website/docs/reference/environment-variables.md +++ b/website/docs/reference/environment-variables.md @@ -629,7 +629,7 @@ compression: enabled: true threshold: 0.50 target_ratio: 0.20 # fraction of threshold to preserve as recent tail - protect_last_n: 20 # minimum recent messages to keep uncompressed + protect_last_n: 10 # minimum recent messages to keep uncompressed ``` :::info Legacy migration diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md index 4b2d2c40e93f0..c93122a8ed4b3 100644 --- a/website/docs/user-guide/configuration.md +++ b/website/docs/user-guide/configuration.md @@ -645,7 +645,7 @@ compression: enabled: true # Toggle compression on/off threshold: 0.50 # Compress at this % of context limit target_ratio: 0.20 # Fraction of threshold to preserve as recent tail - protect_last_n: 20 # Min recent messages to keep uncompressed + protect_last_n: 10 # Min recent messages to keep uncompressed protect_first_n: 3 # Non-system head messages pinned across compactions (0 = pin nothing) hygiene_hard_message_limit: 400 # Gateway safety valve — see below @@ -922,7 +922,8 @@ auxiliary: # Context compression timeout (separate from compression.* config) compression: - timeout: 120 # seconds — compression summarizes long conversations, needs more time + timeout: 300 # seconds — compression summarizes a threshold-sized window; + # can take minutes on slow or reasoning aux models # Skills hub — skill matching and search skills_hub: @@ -954,7 +955,7 @@ auxiliary: ``` :::tip -Each auxiliary task has a configurable `timeout` (in seconds). Defaults: vision 120s, web_extract 360s, approval 30s, compression 120s. Increase these if you use slow local models for auxiliary tasks. Vision also has a separate `download_timeout` (default 30s) for the HTTP image download — increase this for slow connections or self-hosted image servers. +Each auxiliary task has a configurable `timeout` (in seconds). Defaults: vision 120s, web_extract 360s, approval 30s, compression 300s. Increase these if you use slow local models for auxiliary tasks. Vision also has a separate `download_timeout` (default 30s) for the HTTP image download — increase this for slow connections or self-hosted image servers. ::: :::info diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/agent-loop.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/agent-loop.md index a3f1683891318..02c66ad787e3d 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/agent-loop.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/agent-loop.md @@ -207,7 +207,7 @@ agent 通过 `IterationBudget` 追踪迭代次数: 1. 首先将内存刷写到磁盘(防止数据丢失) 2. 将中间对话轮次摘要为紧凑的摘要内容 -3. 保留最后 N 条消息完整不变(`compression.protect_last_n`,默认:20) +3. 保留最后 N 条消息完整不变(`compression.protect_last_n`,默认:10) 4. 工具调用/结果消息对保持完整(不拆分) 5. 生成新的 session 血缘 ID(压缩会创建一个"子" session) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/context-compression-and-caching.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/context-compression-and-caching.md index b310b7f8e217b..c1ad627dbd62a 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/context-compression-and-caching.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/developer-guide/context-compression-and-caching.md @@ -80,7 +80,7 @@ compression: enabled: true # Enable/disable compression (default: true) threshold: 0.50 # Fraction of context window (default: 0.50 = 50%) target_ratio: 0.20 # How much of threshold to keep as tail (default: 0.20) - protect_last_n: 20 # Minimum protected tail messages (default: 20) + protect_last_n: 10 # Minimum protected tail messages (default: 10) # Summarization model/provider configured under auxiliary: auxiliary: @@ -96,7 +96,7 @@ auxiliary: |-----------|---------|-------|-------------| | `threshold` | `0.50` | 0.0-1.0 | 当 prompt token 数 ≥ `threshold × context_length` 时触发压缩 | | `target_ratio` | `0.20` | 0.10-0.80 | 控制尾部保护 token 预算:`threshold_tokens × target_ratio` | -| `protect_last_n` | `20` | ≥1 | 始终保留的最近消息最小数量 | +| `protect_last_n` | `10` | ≥1 | 始终保留的最近消息最小数量 | | `protect_first_n` | `3` | (硬编码)| 系统提示词 + 首次交互始终保留 | ### 计算值(200K 上下文模型,默认参数) diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md index 52ed671891bf9..875cb330a8248 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md @@ -601,7 +601,7 @@ compression: enabled: true threshold: 0.50 target_ratio: 0.20 # fraction of threshold to preserve as recent tail - protect_last_n: 20 # minimum recent messages to keep uncompressed + protect_last_n: 10 # minimum recent messages to keep uncompressed ``` :::info 旧版迁移 diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/configuration.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/configuration.md index ac7adc3efd7b0..4a717b95825c0 100644 --- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/configuration.md +++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/configuration.md @@ -554,7 +554,7 @@ compression: enabled: true # 开启/关闭压缩 threshold: 0.50 # 在上下文限制的此百分比时压缩 target_ratio: 0.20 # 保留为最近尾部的阈值分数 - protect_last_n: 20 # 保持未压缩的最少最近消息数 + protect_last_n: 10 # 保持未压缩的最少最近消息数 hygiene_hard_message_limit: 400 # Gateway 安全阀 —— 见下文 # 摘要模型/provider 在 auxiliary: 下配置: @@ -819,7 +819,8 @@ auxiliary: # 上下文压缩超时(与 compression.* 配置分开) compression: - timeout: 120 # 秒 —— 压缩摘要长对话,需要更多时间 + timeout: 300 # 秒 —— 压缩需要摘要阈值大小的上下文窗口; + # 慢速或推理类辅助模型可能需要数分钟 # 技能中心 —— 技能匹配和搜索 skills_hub: @@ -851,7 +852,7 @@ auxiliary: ``` :::tip -每个辅助任务都有可配置的 `timeout`(秒)。默认值:vision 120s、web_extract 360s、approval 30s、compression 120s。如果您为辅助任务使用慢速本地模型,请增加这些值。Vision 还有单独的 `download_timeout`(默认 30s)用于 HTTP 图像下载 —— 对于慢速连接或自托管图像服务器,请增加此值。 +每个辅助任务都有可配置的 `timeout`(秒)。默认值:vision 120s、web_extract 360s、approval 30s、compression 300s。如果您为辅助任务使用慢速本地模型,请增加这些值。Vision 还有单独的 `download_timeout`(默认 30s)用于 HTTP 图像下载 —— 对于慢速连接或自托管图像服务器,请增加此值。 ::: :::info