tool_output_truncate.py 1.4 KB

1234567891011121314151617181920212223242526272829303132
  1. """Head/tail truncation for oversized tool output (terminal, execute_code, MCP results).
  2. One algorithm and one notice wording: 40% head (errors surface early) / 60% tail (the most
  3. recent lines matter most) around a single ``... [<LABEL> TRUNCATED - N <unit> omitted out of
  4. T total] ...`` marker, so downstream code that recognises the marker sees one shape. Limits
  5. live in ``tools/tool_output_limits.py``; line-snapped, path-bearing footers (web/browser,
  6. read_file pagination) are different products and stay separate.
  7. """
  8. from __future__ import annotations
  9. HEAD_RATIO = 0.4
  10. def truncation_notice(omitted: int, total: int, *, label: str = "OUTPUT", unit: str = "chars") -> str:
  11. return f"\n\n... [{label} TRUNCATED - {omitted:,} {unit} omitted out of {total:,} total] ...\n\n"
  12. def head_tail_split(budget: int) -> tuple[int, int]:
  13. """``(head, tail)`` character budgets for ``budget`` total."""
  14. head = int(budget * HEAD_RATIO)
  15. return head, budget - head
  16. def truncate_head_tail(text: str, max_chars: int, *, label: str = "OUTPUT") -> str:
  17. """``text`` unchanged when it fits ``max_chars``; otherwise head + notice + tail (the kept
  18. text is exactly ``max_chars`` long, the notice rides on top)."""
  19. if len(text) <= max_chars:
  20. return text
  21. head, tail = head_tail_split(max_chars)
  22. omitted = len(text) - head - tail
  23. return text[:head] + truncation_notice(omitted, len(text), label=label) + text[-tail:]