The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): /context breakdown and native-compaction retention use the canonical token estimator
teknium13f59b5c59400
diff --git a/agent/context_breakdown.py b/agent/context_breakdown.pyindex 9f8c57163a1..9fa22d6786e 100644--- a/agent/context_breakdown.py+++ b/agent/context_breakdown.py@@ -32,7 +32,8 @@ _DETAILS_TABLE_LIMIT = 15 # display cap only; the underlying data keeps everythdef _chars_to_tokens(text: str) -> int:- return (len(text) + 3) // 4+ from agent.model_metadata import estimate_tokens_rough+ return estimate_tokens_rough(text)def _json_tokens(value: Any) -> int:@@ -40,7 +41,8 @@ def _json_tokens(value: Any) -> int:def _bytes_to_tokens(size: Optional[int]) -> Optional[int]:- return None if size is None else (int(size) + 3) // 4+ from agent.model_metadata import CHARS_PER_TOKEN+ return None if size is None else (int(size) + 3) // CHARS_PER_TOKENdef _skills_block(stable: str) -> str:diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 56f4447841a..41d92dee2b9 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -27,7 +27,7 @@ from agent.error_classifier import FailoverReason, classify_api_errorfrom agent.micro_compaction import MicroCompactionMixinfrom agent.prompt_builder import STEER_DISPLAY_KINDfrom agent.model_metadata import (- MINIMUM_CONTEXT_LENGTH, get_model_context_length, estimate_messages_tokens_rough, estimate_tokens_rough,+ CHARS_PER_TOKEN, MINIMUM_CONTEXT_LENGTH, get_model_context_length, estimate_messages_tokens_rough, estimate_tokens_rough,strip_opaque_replay_items,)from agent.redact import redact_sensitive_text@@ -955,7 +955,7 @@ def _collect_protected_skill_names(messages: List[Dict[str, Any]], prune_boundar}-_CHARS_PER_TOKEN = 4+_CHARS_PER_TOKEN = CHARS_PER_TOKEN_SUMMARY_FAILURE_COOLDOWN_SECONDS = 600# Fallback handoff preserves continuity anchors only, not a transcript copy.diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex 3808833a50c..a255063e94c 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -2037,6 +2037,10 @@ async def get_model_context_length_async(model: str, base_url: str = "", api_key# CJK/Hangul/Kana codepoints (~1 token each), counted in one C-level regex pass: Hangul# Jamo (+Ext-A), CJK radicals/ideographs (+compat), Hangul syllables, fullwidth/halfwidth.+# Rough chars-per-token ratio for ASCII text; the single source for every "N tokens ≈ N*4 chars"+# budget conversion (context files, tool-output budgets, whisper prompt cap, compressor metadata).+CHARS_PER_TOKEN = 4+_CJK_DENSE_RE = re.compile("[\u1100-\u11ff\u2e80-\u9fff\ua960-\ua97f\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]")@@ -2058,10 +2062,10 @@ def estimate_tokens_rough(text: str) -> int:return 0text = str(text)if text.isascii(): # flag check on CPython; ASCII cannot contain token-dense CJK- return (len(text) + 3) // 4+ return (len(text) + 3) // CHARS_PER_TOKENstripped = _CJK_DENSE_RE.sub("", text)dense = len(text) - len(stripped)- return dense + ((len(stripped.encode("utf-8", "replace")) + 3) // 4)+ return dense + ((len(stripped.encode("utf-8", "replace")) + 3) // CHARS_PER_TOKEN)def estimate_messages_tokens_rough(messages: List[Dict[str, Any]], *, charge_stale_thinking: bool = True) -> int:diff --git a/agent/native_compaction.py b/agent/native_compaction.pyindex 8707cc91afc..dbc2062e5e3 100644--- a/agent/native_compaction.py+++ b/agent/native_compaction.py@@ -135,8 +135,9 @@ RETAINED_SUMMARY_TOKEN_BUDGET = 32_000def _approx_tokens(text: str) -> int:- """Cheap chars//4 token estimate — same shape Codex uses for retention."""- return max(1, len(text) // 4)+ """Retention cost of one carried-over text; never 0 so an empty item still consumes budget."""+ from agent.model_metadata import estimate_tokens_rough+ return max(1, estimate_tokens_rough(text))def _extract_item_text(item: Any) -> Optional[str]:diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 7913cf1025b..8b621743104 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -19,6 +19,7 @@ from hermes_constants import (get_hermes_home, get_skills_dir, is_wsl, reset_hermes_home_override, set_hermes_home_override,)+from agent.model_metadata import CHARS_PER_TOKENfrom agent.runtime_cwd import resolve_agent_cwdfrom agent.skill_utils import (EXCLUDED_SKILL_DIRS, ORG_ACTIVE_MARKER, ORG_MIRROR_DIR_NAME, ORG_PROVENANCE_FILE, SKILL_SUPPORT_DIRS,@@ -1026,9 +1027,8 @@ CONTEXT_FILE_MAX_CHARS = 20_000CONTEXT_TRUNCATE_HEAD_RATIO = 0.7CONTEXT_TRUNCATE_TAIL_RATIO = 0.2-# Dynamic cap (no explicit context_file_max_chars): ~4 chars/token, a small slice of the window since-# context files share the cached prefix; small models stay at the floor.-_CONTEXT_FILE_CHARS_PER_TOKEN = 4+# Dynamic cap (no explicit context_file_max_chars): a small slice of the window since context files+# share the cached prefix; small models stay at the floor._CONTEXT_FILE_WINDOW_FRACTION = 0.06_CONTEXT_FILE_DYNAMIC_CEILING = 500_000@@ -1037,7 +1037,7 @@ def _dynamic_context_file_max_chars(context_length: Optional[int]) -> int:"""Char cap from the model's window, clamped to [20K floor, 500K ceiling]; flat default when unknown."""if not isinstance(context_length, int) or context_length <= 0:return CONTEXT_FILE_MAX_CHARS- budget = int(context_length * _CONTEXT_FILE_CHARS_PER_TOKEN * _CONTEXT_FILE_WINDOW_FRACTION)+ budget = int(context_length * CHARS_PER_TOKEN * _CONTEXT_FILE_WINDOW_FRACTION)return max(CONTEXT_FILE_MAX_CHARS, min(budget, _CONTEXT_FILE_DYNAMIC_CEILING))diff --git a/tools/budget_config.py b/tools/budget_config.pyindex bf19c0b9df9..95c17661814 100644--- a/tools/budget_config.py+++ b/tools/budget_config.py@@ -4,6 +4,8 @@ Per-tool resolution: pinned > config overrides > registry > default."""from dataclasses import dataclass, fieldfrom typing import Dict+from agent.model_metadata import CHARS_PER_TOKEN+# Never overridden; read_file=inf prevents infinite persist->read->persist loops.PINNED_THRESHOLDS: Dict[str, float] = {"read_file": float("inf")}@@ -76,9 +78,8 @@ class BudgetConfig:# Default config -- matches the historical hardcoded behavior exactly.DEFAULT_BUDGET = BudgetConfig()-# Same rough 4-chars-per-token the estimator uses (agent/model_metadata.py);-# a smaller divisor would UNDER-protect small models.-_CHARS_PER_TOKEN: int = 4+# Same rough chars-per-token the estimator uses; a smaller divisor would UNDER-protect small models.+_CHARS_PER_TOKEN: int = CHARS_PER_TOKEN# Window fraction ONE result / the WHOLE turn's tool output may occupy — well# under 1.0 since system prompt, schemas, history and the reply all compete._PER_RESULT_WINDOW_FRACTION: float = 0.15diff --git a/tools/transcription_command.py b/tools/transcription_command.pyindex 2b3b6efce6f..422b8c3a13a 100644--- a/tools/transcription_command.py+++ b/tools/transcription_command.py@@ -15,6 +15,7 @@ from functools import partialfrom pathlib import Pathfrom typing import Any, Dict, Optional+from agent.model_metadata import CHARS_PER_TOKENfrom tools.tts_command_provider import (_command_output_format, _command_timeout, _is_command_provider_config as _is_command_stt_provider_config,_named_provider_config, _resolve_command_config, command_env_passthrough as _command_stt_env_passthrough,@@ -195,7 +196,7 @@ _PRE_TRANSCRIPTION_MUTABLE_FIELDS = ("prompt", "language", "model")# waste upload bytes and can trip stricter OpenAI-compatible servers. Enforced# client-side (truncate with a warning, never error), ~4 chars/token._WHISPER_PROMPT_TOKEN_CAP = 224-_PROMPT_CHARS_PER_TOKEN = 4+_PROMPT_CHARS_PER_TOKEN = CHARS_PER_TOKEN_WHISPER_PROMPT_CAPPED_PROVIDERS = frozenset({"local", "openai", "groq", "deepinfra"})