tool_output_limits.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Configurable tool-output truncation limits (``tool_output`` in config.yaml):
  2. ``max_bytes`` (terminal output cap), ``max_lines`` (read_file pagination cap),
  3. ``max_line_length`` (per-line cap before '... [truncated]'). Defaults equal the
  4. constants once hardcoded in terminal_tool / file_operations and the reader never
  5. raises, so behaviour is unchanged when the section is absent or malformed."""
  6. from __future__ import annotations
  7. from typing import Any, Dict
  8. from hermes_constants import hermes_home_key
  9. DEFAULT_MAX_BYTES = 50_000 # terminal_tool.MAX_OUTPUT_CHARS
  10. DEFAULT_MAX_LINES = 2000 # file_operations.MAX_LINES
  11. DEFAULT_MAX_LINE_LENGTH = 2000 # file_operations.MAX_LINE_LENGTH
  12. # Keyed by profile home: the multiplexed gateway serves every profile from one process, so a
  13. # single slot would hand the launch profile's limits to every other profile.
  14. _cached_limits: dict[str, dict[str, int]] = {}
  15. def _coerce_int(value: Any, default: int, minimum: int) -> int:
  16. """Return ``value`` as an int >= ``minimum``, or ``default`` on any issue."""
  17. try:
  18. iv = int(value)
  19. except (TypeError, ValueError):
  20. return default
  21. return default if iv < minimum else iv
  22. def _coerce_positive_int(value: Any, default: int) -> int:
  23. return _coerce_int(value, default, 1) # positive int, or ``default`` on any issue
  24. def get_tool_output_limits() -> dict[str, int]:
  25. """Resolved ``{max_bytes, max_lines, max_line_length}``; never raises. Cached per profile
  26. home for the process — ``_reset_tool_output_limits_cache()`` forces a fresh read."""
  27. key = hermes_home_key()
  28. cached = _cached_limits.get(key)
  29. if cached is not None:
  30. return cached
  31. try:
  32. from hermes_cli.config import load_config
  33. cfg = load_config() or {}
  34. section = cfg.get("tool_output") if isinstance(cfg, dict) else None
  35. except Exception:
  36. section = None
  37. if not isinstance(section, dict):
  38. section = {}
  39. _cached_limits[key] = limits = {
  40. "max_bytes": _coerce_positive_int(section.get("max_bytes"), DEFAULT_MAX_BYTES),
  41. "max_lines": _coerce_positive_int(section.get("max_lines"), DEFAULT_MAX_LINES),
  42. "max_line_length": _coerce_positive_int(
  43. section.get("max_line_length"), DEFAULT_MAX_LINE_LENGTH)}
  44. return limits
  45. def _reset_tool_output_limits_cache() -> None:
  46. """Reset the cached limits — for tests or after config hot-reload."""
  47. _cached_limits.clear()
  48. def get_max_bytes() -> int: return get_tool_output_limits()["max_bytes"]
  49. def get_max_lines() -> int: return get_tool_output_limits()["max_lines"]
  50. def get_max_line_length() -> int: return get_tool_output_limits()["max_line_length"]