status_phrases.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. """Human-friendly generic gateway status phrases: short chat-safe lines for the long-running
  2. status surface without relaying raw model scratch text — only configured phrase strings are used;
  3. tool args, commands, previews, and reasoning are never interpolated. Built-in defaults live in
  4. ``gateway/assets/status_phrases.yaml``; users add profile-relative catalogs under ``HERMES_HOME``
  5. via ``status_phrases.yaml`` / ``status_phrases/*.yaml`` or ``display.status_phrases: {path:
  6. <HERMES_HOME-relative>, mode: append|replace}``. Absolute paths and ``..`` escapes are ignored on
  7. purpose so config stays profile-portable and cannot read arbitrary files."""
  8. from __future__ import annotations
  9. import random as _random
  10. from collections.abc import Mapping, MutableSequence
  11. from pathlib import Path
  12. from typing import Any
  13. import hermes_yaml as yaml
  14. from hermes_constants import get_hermes_home
  15. # Hermes UI surfaces, not app/vendor buckets. Long-running-only: regular tool/thinking/interim
  16. # chatter is deliberately not rewritten (too noisy in chat).
  17. _STATUS_SURFACES = ("status", "generic")
  18. _MAX_CUSTOM_PHRASES_PER_SURFACE = 80
  19. _MAX_PHRASE_CHARS = 160
  20. _CONVENTIONAL_RELATIVE_PATHS = ("status_phrases.yaml", "status_phrases")
  21. _YAML_SUFFIXES = {".yaml", ".yml"}
  22. _CONFIG_KEYS = ("generic_status_phrases", "status_phrases") # legacy alias first
  23. _FALLBACK_PHRASES: dict[str, list[str]] = {
  24. "status": ["still on it", "still working through it", "waiting for the result"],
  25. "generic": ["on it", "one sec", "checking that now"],
  26. }
  27. def _clean_phrase_list(value: Any) -> list[str]:
  28. cleaned: list[str] = []
  29. for item in value[:_MAX_CUSTOM_PHRASES_PER_SURFACE] if isinstance(value, list) else ():
  30. phrase = str(item or "").strip()
  31. if phrase and len(phrase) <= _MAX_PHRASE_CHARS and phrase not in cleaned:
  32. cleaned.append(phrase)
  33. return cleaned
  34. def _merge_phrase_mapping(catalog: dict[str, list[str]], section: Mapping[str, Any], *,
  35. inherited_mode: str | None = None) -> None:
  36. replace = str(section.get("mode") or inherited_mode or "append").strip().lower() == "replace"
  37. phrase_map = section.get("phrases") if isinstance(section.get("phrases"), Mapping) else section
  38. for surface in _STATUS_SURFACES:
  39. phrases = _clean_phrase_list(phrase_map.get(surface) if isinstance(phrase_map, Mapping) else None)
  40. if phrases:
  41. catalog[surface] = phrases if replace else [*catalog.get(surface, []), *phrases]
  42. def _merge_phrase_file(catalog: dict[str, list[str]], path: Path, *, inherited_mode: str | None = None) -> None:
  43. try:
  44. loaded = yaml.safe_load(path.read_text(encoding="utf-8-sig"))
  45. except Exception:
  46. return
  47. if isinstance(loaded, Mapping):
  48. _merge_phrase_mapping(catalog, loaded, inherited_mode=inherited_mode)
  49. def _iter_phrase_files(base_dir: Path, raw_path: Any) -> list[Path]:
  50. """YAML files under ``base_dir/raw_path``; [] for absolute / ``..`` / escaping paths."""
  51. raw = str(raw_path or "").strip()
  52. candidate = Path(raw).expanduser()
  53. if not raw or candidate.is_absolute() or ".." in candidate.parts:
  54. return []
  55. base = base_dir.resolve()
  56. path = (base / candidate).resolve()
  57. try:
  58. path.relative_to(base)
  59. except ValueError:
  60. return []
  61. if path.is_file() and path.suffix.lower() in _YAML_SUFFIXES:
  62. return [path]
  63. if path.is_dir():
  64. return sorted(c for c in path.iterdir() if c.is_file() and c.suffix.lower() in _YAML_SUFFIXES)
  65. return []
  66. def _merge_phrase_paths(catalog: dict[str, list[str]], paths: Any, *, base_dir: Path,
  67. inherited_mode: str | None = None) -> None:
  68. if paths is None:
  69. return
  70. for raw_path in paths if isinstance(paths, list) else [paths]:
  71. for phrase_file in _iter_phrase_files(base_dir, raw_path):
  72. _merge_phrase_file(catalog, phrase_file, inherited_mode=inherited_mode)
  73. def _copy_catalog(catalog: Mapping[str, list[str]]) -> dict[str, list[str]]:
  74. return {surface: list(phrases) for surface, phrases in catalog.items()}
  75. _DEFAULT_PHRASES: dict[str, list[str]] = _copy_catalog(_FALLBACK_PHRASES)
  76. _merge_phrase_file(
  77. _DEFAULT_PHRASES, Path(__file__).resolve().parent / "assets" / "status_phrases.yaml", inherited_mode="replace"
  78. )
  79. def _merge_phrase_config(catalog: dict[str, list[str]], section: Any, *, base_dir: Path) -> None:
  80. """Merge one display.status_phrases-style section (files first, then inline phrases)."""
  81. if not isinstance(section, Mapping):
  82. return
  83. mode = str(section.get("mode") or "append").strip().lower()
  84. for key in ("path", "paths"):
  85. _merge_phrase_paths(catalog, section.get(key), base_dir=base_dir, inherited_mode=mode)
  86. _merge_phrase_mapping(catalog, section)
  87. def resolve_status_phrase_catalog(user_config: Mapping[str, Any] | None,
  88. platform_key: str | None = None) -> dict[str, list[str]]:
  89. """Resolve built-in + user-configured generic status phrases. Order mirrors gateway display
  90. settings: built-ins, conventional profile-relative user files, global
  91. ``display.status_phrases`` (or legacy alias ``generic_status_phrases``), then
  92. ``display.platforms.<platform>.status_phrases``."""
  93. catalog = _copy_catalog(_DEFAULT_PHRASES)
  94. hermes_home = get_hermes_home()
  95. _merge_phrase_paths(catalog, list(_CONVENTIONAL_RELATIVE_PATHS), base_dir=hermes_home)
  96. display = (user_config or {}).get("display") if isinstance(user_config, Mapping) else None
  97. if not isinstance(display, Mapping):
  98. return catalog
  99. sections, platforms = [display], display.get("platforms")
  100. if platform_key and isinstance(platforms, Mapping) and isinstance(platforms.get(platform_key), Mapping):
  101. sections.append(platforms[platform_key])
  102. for section in sections:
  103. for key in _CONFIG_KEYS:
  104. _merge_phrase_config(catalog, section.get(key), base_dir=hermes_home)
  105. return catalog
  106. def classify_status_context(kind: str, *, tool_name: str | None = None, preview: str | None = None,
  107. args: Any = None) -> str:
  108. """Classify an internal gateway event into a Hermes UI-surface bucket."""
  109. if str(kind or "").strip().lower() in {"heartbeat", "waiting", "long_running", "status"}:
  110. return "status"
  111. return "generic"
  112. def choose_status_phrase(kind: str, *, tool_name: str | None = None, preview: str | None = None,
  113. args: Any = None, recent: MutableSequence[str] | None = None,
  114. rng: Any = None, catalog: Mapping[str, list[str]] | None = None) -> str:
  115. """Pick a short generic status phrase, avoiding recent repeats. ``preview`` and ``args`` are
  116. accepted for callback compatibility, but their raw contents are never embedded in the result."""
  117. phrase_catalog = catalog or _DEFAULT_PHRASES
  118. category = classify_status_context(kind, tool_name=tool_name, preview=preview, args=args)
  119. candidates = list(phrase_catalog.get(category) or phrase_catalog.get("generic") or _DEFAULT_PHRASES["generic"])
  120. if recent:
  121. recent_set = set(recent)
  122. candidates = [p for p in candidates if p not in recent_set] or candidates
  123. phrase = (rng or _random).choice(candidates)
  124. if recent is not None:
  125. recent.append(phrase)
  126. del recent[:-6]
  127. return phrase