fix: reuse token truncation helper

Maintainer edit: make token truncation include the suffix within the budget and route the consolidator through the shared helper so recent-history and archive truncation keep the same semantics.
This commit is contained in:
chengyongru authored and Xubin Ren committed 2026-06-17 00:47:52 +08:00
1 parent 21d9072190
commit 072921893f
5 files changed
+21 -17

No files matched your search

+16 -3
View File
@@ -218,6 +218,7 @@ _TOOL_RESULT_PREVIEW_CHARS = 1200
_TOOL_RESULTS_DIR = ".nanobot/tool-results"
_TOOL_RESULT_RETENTION_SECS = 7 * 24 * 60 * 60
_TOOL_RESULT_MAX_BUCKETS = 32
_TRUNCATED_SUFFIX = "\n... (truncated)"
def safe_filename(name: str) -> str:
@@ -234,7 +235,7 @@ def truncate_text(text: str, max_chars: int) -> str:
"""Truncate text with a stable suffix."""
if max_chars <= 0 or len(text) <= max_chars:
return text
return text[:max_chars] + "\n... (truncated)"
return text[:max_chars] + _TRUNCATED_SUFFIX
def truncate_text_to_tokens(text: str, max_tokens: int) -> str:
@@ -252,9 +253,21 @@ def truncate_text_to_tokens(text: str, max_tokens: int) -> str:
tokens = enc.encode(text)
if len(tokens) <= max_tokens:
return text
return enc.decode(tokens[:max_tokens]) + "\n... (truncated)"
suffix_tokens = enc.encode(_TRUNCATED_SUFFIX)
body_budget = max_tokens - len(suffix_tokens)
if body_budget <= 0:
return enc.decode(tokens[:max_tokens])
result = enc.decode(tokens[:body_budget]) + _TRUNCATED_SUFFIX
while len(enc.encode(result)) > max_tokens and body_budget > 0:
body_budget -= 1
result = enc.decode(tokens[:body_budget]) + _TRUNCATED_SUFFIX
return result
except Exception:
return truncate_text(text, max_tokens * 4)
max_chars = max_tokens * 4
suffix_chars = len(_TRUNCATED_SUFFIX)
if max_chars <= suffix_chars:
return text[:max_chars]
return truncate_text(text, max_chars - suffix_chars)
def find_legal_message_start(messages: list[dict[str, Any]]) -> int: