config_value_checks.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. """Value checks for single config sections (voice, timezone, web backends), run by
  2. ``hermes_cli.config.validate_config_structure`` for doctor and the startup warnings."""
  3. from typing import Any
  4. from hermes_cli.config_issues import ConfigIssue, _issue
  5. def _validate_voice(config: dict[str, Any], issues: list[ConfigIssue]) -> None:
  6. voice_cfg = config.get("voice")
  7. if not (isinstance(voice_cfg, dict) and "submit_mode" in voice_cfg):
  8. return
  9. submit_mode = voice_cfg.get("submit_mode")
  10. normalized = submit_mode.strip().lower() if isinstance(submit_mode, str) else None
  11. if normalized not in {"direct", "draft"}:
  12. _issue(issues, "error", f"voice.submit_mode must be 'direct' or 'draft', got {submit_mode!r}",
  13. "Set voice.submit_mode to direct (submit immediately) or draft (edit before sending)")
  14. def _validate_timezone(config: dict[str, Any], issues: list[ConfigIssue]) -> None:
  15. """``timezone`` must be an IANA name the runtime can load.
  16. ``hermes_time._get_zoneinfo()`` swallows an invalid name behind a single WARNING in the
  17. gateway log, then runs the agent clock AND every cron schedule on server-local time.
  18. Surface it here, where doctor and the startup check both look. Silent when the
  19. interpreter has no tz database at all (bare Windows without ``tzdata``) — nothing can be
  20. judged there.
  21. """
  22. if "timezone" not in config:
  23. return
  24. tz = config.get("timezone")
  25. hint = ("Use an IANA zone name such as America/New_York or Asia/Tokyo (see "
  26. "`timedatectl list-timezones`). With an invalid value the agent clock and cron "
  27. "schedules silently fall back to server-local time. HERMES_TIMEZONE overrides "
  28. "this key when set.")
  29. if tz is not None and not isinstance(tz, str):
  30. _issue(issues, "error", f"timezone must be an IANA zone name string, got {tz!r}", hint)
  31. return
  32. if not (isinstance(tz, str) and tz.strip()):
  33. return
  34. name = tz.strip()
  35. try:
  36. import zoneinfo
  37. zoneinfo.ZoneInfo("UTC") # is a tz database available at all?
  38. except Exception:
  39. return
  40. try:
  41. zoneinfo.ZoneInfo(name)
  42. except Exception:
  43. _issue(issues, "error", f"timezone {name!r} is not a valid IANA zone name", hint)
  44. def _validate_web_backends(config: dict[str, Any], issues: list[ConfigIssue]) -> None:
  45. """A stale web backend selection otherwise fails only at the first web_search/web_extract
  46. call with a generic "no registered provider" error; warn at startup instead."""
  47. # See #99199.
  48. web_cfg = config.get("web")
  49. if not isinstance(web_cfg, dict):
  50. return
  51. try:
  52. from tools.tool_backend_helpers import removed_backend_note
  53. except Exception:
  54. return
  55. seen: set = set()
  56. for _key in ("backend", "search_backend", "extract_backend"):
  57. _val = str(web_cfg.get(_key) or "").strip().lower()
  58. if not _val or _val in seen:
  59. continue
  60. seen.add(_val)
  61. note = removed_backend_note("web", _val)
  62. if note:
  63. _issue(issues, "warning",
  64. f"web.{_key} is set to '{_val}', but {note} — "
  65. "web_search/web_extract will fail until it is changed",
  66. "Run 'hermes tools' and pick a different Web Search & Extract provider")
  67. def _container_slots() -> dict[str, str]:
  68. """Dotted key -> ``"list"``/``"mapping"`` for every slot the schema fixes to a container:
  69. ``DEFAULT_CONFIG`` (sections included) plus the known-container table for roots it omits."""
  70. from hermes_cli.config import _KNOWN_CONTAINER_TYPES, DEFAULT_CONFIG # late: the facade imports this module
  71. slots: dict[str, str] = {}
  72. def walk(node: dict[str, Any], prefix: str) -> None:
  73. for key, value in node.items():
  74. path = f"{prefix}.{key}" if prefix else key
  75. if isinstance(value, dict):
  76. slots[path] = "mapping"
  77. walk(value, path)
  78. elif isinstance(value, list):
  79. slots[path] = "list"
  80. walk(DEFAULT_CONFIG, "")
  81. slots.update(_KNOWN_CONTAINER_TYPES)
  82. return slots
  83. def _validate_quoted_containers(config: dict[str, Any], issues: list[ConfigIssue]) -> None:
  84. """A container slot holding ONE quoted string (``enabled: '["a","b"]'``) is skipped by every
  85. isinstance-gated reader while ``config get`` echoes it back, so plugins silently unmount and
  86. exclusions silently lapse (#83308, #105706). Finding only — the file is never rewritten."""
  87. import shlex
  88. import hermes_yaml as yaml
  89. from hermes_cli.config import _SCALAR_AS_ONE_ITEM_LIST_KEYS, _looks_structured_value, cfg_get
  90. for key, kind in _container_slots().items():
  91. # ``parse_config_string_list`` readers accept the quoted form; nothing is ignored there.
  92. if key in _SCALAR_AS_ONE_ITEM_LIST_KEYS:
  93. continue
  94. value = cfg_get(config, *key.split("."))
  95. if not isinstance(value, str) or not _looks_structured_value(value):
  96. continue
  97. try:
  98. parsed = yaml.safe_load(value)
  99. except yaml.YAMLError:
  100. continue
  101. if isinstance(parsed, (list, dict)):
  102. _issue(issues, "warning",
  103. f"{key} is the quoted string {value!r} — Hermes expects a YAML {kind} here "
  104. "and every reader ignores the string",
  105. f"Run: hermes config set {key} {shlex.quote(value)} (stores a real {kind}), "
  106. "or remove the quotes in config.yaml")