Skip to content

The agent that grows with you

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.py
index 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 everyth
def _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_TOKEN
def _skills_block(stable: str) -> str:
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 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_error
from agent.micro_compaction import MicroCompactionMixin
from agent.prompt_builder import STEER_DISPLAY_KIND
from 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.py
index 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 0
text = 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_TOKEN
stripped = _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.py
index 8707cc91afc..dbc2062e5e3 100644
--- a/agent/native_compaction.py
+++ b/agent/native_compaction.py
@@ -135,8 +135,9 @@ RETAINED_SUMMARY_TOKEN_BUDGET = 32_000
def _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.py
index 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_TOKEN
from agent.runtime_cwd import resolve_agent_cwd
from 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_000
CONTEXT_TRUNCATE_HEAD_RATIO = 0.7
CONTEXT_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.py
index 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, field
from 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.15
diff --git a/tools/transcription_command.py b/tools/transcription_command.py
index 2b3b6efce6f..422b8c3a13a 100644
--- a/tools/transcription_command.py
+++ b/tools/transcription_command.py
@@ -15,6 +15,7 @@ from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
+from agent.model_metadata import CHARS_PER_TOKEN
from 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"})