display_config.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """Per-platform display/verbosity resolver (``resolve_display_setting``).
  2. Resolution order, first non-None wins: ``display.platforms.<platform>.<key>`` →
  3. ``display.<key>`` → ``_PLATFORM_DEFAULTS[platform][key]`` (a plugin platform: its registered
  4. ``display_tier`` + ``display_overrides``) → ``_GLOBAL_DEFAULTS[key]``.
  5. Exception: ``display.streaming`` is CLI-only; gateway streaming follows the top-level
  6. ``streaming`` config unless a per-platform override sets it. Legacy
  7. ``display.tool_progress_overrides`` is still read as a ``tool_progress`` fallback.
  8. """
  9. from __future__ import annotations
  10. from typing import Any
  11. # Settings configurable per-platform; other display settings are CLI-only.
  12. _GLOBAL_DEFAULTS: dict[str, Any] = {
  13. "tool_progress": "all",
  14. "tool_progress_grouping": "accumulate", # "accumulate" = edit one bubble; "separate" = one msg per tool
  15. "show_reasoning": False,
  16. "reasoning_style": "code", # "code" (💭 **Reasoning:** + fence), "blockquote" ("> "), "subtext" ("-# " Discord)
  17. "tool_preview_length": 0,
  18. "streaming": None, # None = follow top-level streaming config
  19. # Gateway-only assistant/status chatter; mobile platforms opt down to final-answer-first.
  20. "interim_assistant_messages": True,
  21. "suppress_warning_notifications": False,
  22. "long_running_notifications": True,
  23. "busy_ack_detail": True,
  24. "busy_steer_ack_enabled": True, # busy_input_mode=steer echo; the text still lands in the run
  25. # Delete tool-progress / "⏳ Working" bubbles after a SUCCESSFUL final response where deletion is
  26. # supported (Telegram); failed runs keep them as breadcrumbs.
  27. "cleanup_progress": False,
  28. # Working-state text on text-rendering indicators (Slack assistant status): "full"/true = verb +
  29. # argument preview, "verb" = verb only (keeps paths out of shared channels), "off"/false = static.
  30. "live_status": "full",
  31. }
  32. # Tiers: HIGH = editing, personal/team use; MEDIUM = editing but customer-facing;
  33. # LOW = no edit support (progress messages are permanent); MINIMAL = batch delivery.
  34. _TIER_HIGH = {
  35. "tool_progress": "all", "show_reasoning": False, "tool_preview_length": 40,
  36. "streaming": None, # follow global
  37. "interim_assistant_messages": True, "long_running_notifications": True, "busy_ack_detail": True,
  38. }
  39. _TIER_MEDIUM = {**_TIER_HIGH, "tool_progress": "new"}
  40. _TIER_LOW = {
  41. **_TIER_HIGH, "tool_progress": "off", "streaming": False,
  42. "interim_assistant_messages": False, "long_running_notifications": False, "busy_ack_detail": False,
  43. }
  44. _TIER_MINIMAL = {**_TIER_LOW, "tool_preview_length": 0}
  45. # Core-only surfaces. A plugin platform declares ``display_tier`` (+ optional ``display_overrides``)
  46. # on its ``PlatformEntry``; _platform_defaults() reads it from the registry.
  47. _PLATFORM_DEFAULTS: dict[str, dict[str, Any]] = {
  48. "webhook": _TIER_MINIMAL,
  49. "api_server": {**_TIER_HIGH, "tool_preview_length": 0},
  50. }
  51. _TIERS = {"high": _TIER_HIGH, "medium": _TIER_MEDIUM, "low": _TIER_LOW, "minimal": _TIER_MINIMAL}
  52. def _platform_defaults(platform_key: str) -> dict[str, Any]:
  53. """Built-in defaults for *platform_key*: the table above, else the ``display_tier`` a plugin
  54. platform registered (``PlatformEntry.display_tier``) with its ``display_overrides`` on top."""
  55. if platform_key in _PLATFORM_DEFAULTS:
  56. return _PLATFORM_DEFAULTS[platform_key]
  57. try:
  58. from gateway.platform_registry import platform_registry
  59. entry = platform_registry.get(platform_key)
  60. except Exception:
  61. return {}
  62. tier = _TIERS.get(str(getattr(entry, "display_tier", "") or "").lower(), {})
  63. overrides = getattr(entry, "display_overrides", None)
  64. return {**tier, **overrides} if overrides else tier
  65. # Canonical set of per-platform overrideable keys (for validation).
  66. OVERRIDEABLE_KEYS = frozenset(_GLOBAL_DEFAULTS.keys())
  67. def resolve_display_setting(user_config: dict, platform_key: str, setting: str, fallback: Any = None) -> Any:
  68. """Resolve a display setting with per-platform override support (see module docstring for order).
  69. ``platform_key`` is the platform config key (``"telegram"``; see ``_platform_config_key`` in
  70. gateway/run.py). Returns *fallback* when nothing is configured.
  71. """
  72. configured = _configured_display_value(user_config, platform_key, setting)
  73. if configured is not None:
  74. return _normalise(setting, configured)
  75. val = _platform_defaults(platform_key).get(setting)
  76. if val is None:
  77. val = _GLOBAL_DEFAULTS.get(setting)
  78. return fallback if val is None else val
  79. def _configured_display_value(user_config: dict, platform_key: str, setting: str) -> Any:
  80. """First non-None operator value, without introducing tier defaults."""
  81. display_cfg = user_config.get("display")
  82. if not isinstance(display_cfg, dict):
  83. return None
  84. platforms = display_cfg.get("platforms")
  85. plat_overrides = platforms.get(platform_key) if isinstance(platforms, dict) else None
  86. if isinstance(plat_overrides, dict) and plat_overrides.get(setting) is not None:
  87. return plat_overrides[setting]
  88. if setting == "tool_progress":
  89. legacy = display_cfg.get("tool_progress_overrides")
  90. if isinstance(legacy, dict) and legacy.get(platform_key) is not None:
  91. return legacy[platform_key]
  92. if setting != "streaming": # display.streaming is CLI-only
  93. return display_cfg.get(setting)
  94. return None
  95. def resolve_tool_progress(user_config: dict, platform_key: str, env_mode: str | None = None) -> tuple[str, bool]:
  96. """Return (mode, explicit intent) from the same winning source.
  97. Non-None YAML wins over the legacy env bridge. Null inherits through to env,
  98. then tier defaults. A tier's off is not an operator request to disable cards.
  99. """
  100. configured = _configured_display_value(user_config, platform_key, "tool_progress")
  101. if configured is not None:
  102. return _normalise("tool_progress", configured), True
  103. if env_mode:
  104. return _normalise("tool_progress", env_mode), True
  105. return resolve_display_setting(user_config, platform_key, "tool_progress"), False
  106. # --- Normalisation of YAML quirks (bare ``off`` → False in YAML 1.1, etc.) ---
  107. _TRUTHY = {"true", "1", "yes", "on"}
  108. _FALSY = {"false", "0", "no"}
  109. def _norm_tristate(on: str, off: str, choices: set, extra_truthy: set = frozenset()):
  110. """Normaliser for bool-or-keyword settings: bools/truthy tokens → *on*, falsy → *off*, else a known choice or *on*."""
  111. def norm(value: Any) -> str:
  112. if isinstance(value, bool):
  113. return on if value else off
  114. val = str(value).strip().lower()
  115. if val in _FALSY:
  116. return off
  117. if val in _TRUTHY | extra_truthy:
  118. return on
  119. return val if val in choices else on
  120. return norm
  121. def _norm_bool(value: Any) -> bool:
  122. return value.strip().lower() in _TRUTHY | {"raw", "verbose"} if isinstance(value, str) else bool(value)
  123. def _norm_long_running(value: Any) -> Any:
  124. return "generic" if isinstance(value, str) and value.strip().lower() == "generic" else _norm_bool(value)
  125. def _norm_suppress_warning_notifications(value: Any) -> bool:
  126. # Only an explicit, recognized opt-in may hide engine diagnostics.
  127. if isinstance(value, bool):
  128. return value
  129. if isinstance(value, str):
  130. return value.strip().lower() in _TRUTHY
  131. return False
  132. def _norm_cleanup_progress(value: Any) -> bool:
  133. return value.lower() in _TRUTHY if isinstance(value, str) else bool(value)
  134. def _norm_choice(choices: tuple[str, ...]) -> Any:
  135. def norm(value: Any) -> str:
  136. val = str(value).lower()
  137. return val if val in choices else choices[0]
  138. return norm
  139. def _norm_int(value: Any) -> int:
  140. try:
  141. return int(value)
  142. except (TypeError, ValueError):
  143. return 0
  144. _NORMALISERS: dict[str, Any] = {
  145. "tool_progress": _norm_tristate("all", "off", {"off", "new", "all", "verbose", "log"}),
  146. "show_reasoning": _norm_bool,
  147. "streaming": _norm_bool,
  148. "interim_assistant_messages": _norm_bool,
  149. "suppress_warning_notifications": _norm_suppress_warning_notifications,
  150. "long_running_notifications": _norm_long_running,
  151. "busy_ack_detail": _norm_bool,
  152. "busy_steer_ack_enabled": _norm_bool,
  153. "thinking_progress": _norm_bool,
  154. "cleanup_progress": _norm_cleanup_progress,
  155. "live_status": _norm_tristate("full", "off", {"full", "verb", "off"}, extra_truthy={"all"}),
  156. "tool_progress_grouping": _norm_choice(("accumulate", "separate")),
  157. "reasoning_style": _norm_choice(("code", "blockquote", "subtext")),
  158. "tool_preview_length": _norm_int,
  159. }
  160. def _normalise(setting: str, value: Any) -> Any:
  161. """Normalise a user-supplied value for *setting*; unknown settings pass through."""
  162. norm = _NORMALISERS.get(setting)
  163. return norm(value) if norm else value
  164. # LOCAL's per-platform config key (``_platform_config_key(Platform.LOCAL)``): where a local session's
  165. # ``/reasoning show|hide`` and ``/footer`` save, and what every local surface reads.
  166. LOCAL_DISPLAY_KEY = "cli"
  167. # The per-platform display settings a local surface takes from the local key over the global one.
  168. _LOCAL_OVERLAY_KEYS = ("show_reasoning", "runtime_footer")
  169. def local_display_config(display: Any) -> dict[str, Any]:
  170. """*display* (a ``config.yaml`` ``display`` block) as a local surface (classic CLI, Ink, Desktop,
  171. a local turn) resolves it: ``display.platforms.cli.<key>`` over ``display.<key>`` for the settings
  172. the local commands save there. No second key is written; the block is returned copied."""
  173. display = dict(display) if isinstance(display, dict) else {}
  174. platforms = display.get("platforms")
  175. local = platforms.get(LOCAL_DISPLAY_KEY) if isinstance(platforms, dict) else None
  176. if not isinstance(local, dict):
  177. return display
  178. for key in _LOCAL_OVERLAY_KEYS:
  179. value = local.get(key)
  180. if value is None:
  181. continue
  182. if isinstance(value, dict) and isinstance(display.get(key), dict):
  183. value = {**display[key], **value}
  184. display[key] = _normalise(key, value)
  185. return display