The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): keep retained non-ASCII user text within budget
FroRaut1f75ef513788
diff --git a/agent/native_compaction.py b/agent/native_compaction.pyindex 44c721d397a..919931d09f3 100644--- a/agent/native_compaction.py+++ b/agent/native_compaction.py@@ -152,6 +152,19 @@ def _approx_tokens(text: str) -> int:return max(1, estimate_tokens_rough(text))+def _head_within_budget(text: str, budget: int) -> str:+ """Longest prefix of ``text`` whose ``_approx_tokens`` fits ``budget``. A plain ``budget * 4`` char+ slice would keep ~2x the budget of Cyrillic and ~4x of CJK; ASCII still gets ``budget * 4`` chars."""+ lo, hi = 0, min(len(text), budget * 4) # every char costs >= 1/4 token+ while lo < hi:+ mid = (lo + hi + 1) // 2+ if _approx_tokens(text[:mid]) <= budget:+ lo = mid+ else:+ hi = mid - 1+ return text[:lo]++def _extract_item_text(item: Any) -> Optional[str]:"""Measurable text from a Responses item (string/multipart/metadata), or None."""if not isinstance(item, dict):@@ -338,7 +351,7 @@ def prune_pre_checkpoint_items(else:content = item.get("content")if isinstance(content, str):- head = content[: user_remaining * 4]+ head = _head_within_budget(content, user_remaining)keep = bool(head.strip())elif parts_cost is not None:head = _truncate_input_text_parts(content, user_remaining)diff --git a/tests/agent/test_native_compaction.py b/tests/agent/test_native_compaction.pyindex bb5733a71b8..7edef5ec446 100644--- a/tests/agent/test_native_compaction.py+++ b/tests/agent/test_native_compaction.py@@ -551,6 +551,23 @@ class TestPrunePreCheckpointItems:assert users[0] == "x" * 400 # (600-500)*4 charsassert out[0]["type"] == "compaction"+ @pytest.mark.parametrize(+ ("char", "kept_chars"),+ [("ж", 200), ("中", 100)], # Cyrillic 2 bytes/char; CJK 1 token/char+ )+ def test_boundary_truncation_fits_byte_aware_budget(self, char, kept_chars):+ from agent.model_metadata import estimate_tokens_rough+ from agent.native_compaction import prune_pre_checkpoint_items++ items = [{"role": "user", "content": char * 4000},+ {"type": "compaction", "encrypted_content": "b"}]+ out = prune_pre_checkpoint_items(items, retained_user_token_budget=100)+ users = [i["content"] for i in out if i.get("role") == "user"]+ # The kept head is costed with the same estimator as the budget, not+ # sliced at budget*4 chars (which kept 2x/4x the budget here).+ assert estimate_tokens_rough(users[0]) == 100+ assert users == [char * kept_chars]+def test_zero_budget_keeps_only_post_tail(self):from agent.native_compaction import prune_pre_checkpoint_items