Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 52 additions & 30 deletions agent/agent_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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": <old_ratio>, "to": <new_ratio>}`` 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 ""
Expand Down Expand Up @@ -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
Expand Down
25 changes: 18 additions & 7 deletions agent/auxiliary_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down
120 changes: 112 additions & 8 deletions agent/context_compressor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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`'\")\]}<>]+")

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand All @@ -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

Expand Down Expand Up @@ -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] = []
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
Loading