hermes_time.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. """Timezone-aware clock for Hermes.
  2. ``now()`` returns a tz-aware datetime in the user's configured IANA timezone. Resolution order:
  3. ``HERMES_TIMEZONE`` env var, then ``timezone`` in ``~/.hermes/config.yaml``, else server-local
  4. time. Invalid timezone values log a warning and fall back — never crash.
  5. """
  6. import locale
  7. import logging
  8. import os
  9. import re
  10. import threading
  11. from datetime import datetime
  12. from typing import Dict, Optional, Tuple
  13. from zoneinfo import ZoneInfo
  14. from hermes_constants import get_config_path
  15. logger = logging.getLogger(__name__)
  16. # Cache keyed by timezone *source* identity. This process can multiplex profiles by switching
  17. # HERMES_HOME, so one unkeyed global would leak the first profile's timezone into later
  18. # profile-scoped work (e.g. the desktop multiplex cron ticker persisting another profile's
  19. # ``next_run_at``). Entries are published atomically under ``_cache_lock`` as one
  20. # ``identity -> (name, ZoneInfo | None)`` value, so racing resolvers can never publish a mixed
  21. # identity/value pair. Call reset_cache() after in-place config changes.
  22. _cache_lock = threading.Lock()
  23. _tz_cache: dict[tuple[str, str], tuple[str, Optional[ZoneInfo]]] = {}
  24. _SURROGATE_RE = re.compile(r"[\ud800-\udfff]")
  25. # ASCII plus surrogateescape'd bytes only: the shape of native text decoded with the wrong codec.
  26. _ESCAPED_BYTES_RE = re.compile(r"[\x00-\x7f\udc80-\udcff]*")
  27. def _repair_surrogates(text: str, encoding: Optional[str] = None) -> str:
  28. """Make locale text JSON/UTF-8 safe; a no-op (same object) on valid text.
  29. Windows hands back zone names in the ANSI code page (``heure d'\\xe9t\\xe9``) but a UTF-8
  30. ``LC_CTYPE`` (UTF-8 mode, or a library flipping the process locale mid-run) decodes those
  31. bytes with ``surrogateescape`` into lone surrogates. Recover the bytes and decode them with
  32. the ANSI code page; when that is not possible, replace each surrogate with U+FFFD."""
  33. if text.isascii() or not _SURROGATE_RE.search(text):
  34. return text
  35. if _ESCAPED_BYTES_RE.fullmatch(text):
  36. try:
  37. return text.encode("ascii", "surrogateescape").decode(encoding or locale.getencoding())
  38. except (LookupError, UnicodeError):
  39. pass
  40. return _SURROGATE_RE.sub("\ufffd", text)
  41. def safe_strftime(value: datetime, fmt: str) -> str:
  42. """``value.strftime(fmt)`` that never raises or returns lone surrogates over locale text.
  43. ``datetime.strftime`` splices ``tzname()`` into the format as UTF-8, so a zone name carrying
  44. surrogates (see ``_repair_surrogates``) raises ``UnicodeEncodeError`` before any string exists
  45. (#102910). On that failure ``%Z`` is rendered from the repaired name instead. Output for valid
  46. locale text is byte-identical to ``strftime`` (the system prompt must stay cache-stable)."""
  47. try:
  48. return _repair_surrogates(value.strftime(fmt))
  49. except UnicodeEncodeError:
  50. zone = _repair_surrogates(value.tzname() or "").replace("%", "%%")
  51. return _repair_surrogates(value.strftime(
  52. re.sub(r"%([%Z])", lambda m: zone if m.group(1) == "Z" else "%%", fmt)))
  53. def _env_timezone() -> str:
  54. """``HERMES_TIMEZONE`` when it may speak for the active profile. Under the multiplexed
  55. gateway the env var holds only the DEFAULT profile's value (bridged from its config.yaml at
  56. startup), so every routed profile must read its own config.yaml instead."""
  57. from agent.secret_scope import is_multiplex_active # lazy: secret_scope pulls in more than a clock needs
  58. if is_multiplex_active():
  59. return ""
  60. return os.getenv("HERMES_TIMEZONE", "").strip()
  61. def _timezone_cache_identity() -> tuple[str, str]:
  62. tz_env = _env_timezone()
  63. return ("environment", tz_env) if tz_env else ("config", str(get_config_path()))
  64. def _resolve_timezone_name() -> str:
  65. """Read the configured IANA timezone string (or ``""``). Does file I/O — callers cache."""
  66. tz_env = _env_timezone()
  67. if tz_env:
  68. return tz_env
  69. try:
  70. # Prefer the shared cached effective-config loader (mtime-keyed + libyaml, managed overlay
  71. # included so an administrator can pin ``timezone``): a direct safe_load of a large
  72. # config.yaml costs ~100 ms and this ran inside the FIRST system prompt build. The bare
  73. # parse through the config backend is the fallback when the effective loader cannot be
  74. # imported (any failure there lands in the outer except: no configured timezone).
  75. try:
  76. from hermes_cli.config_effective import load_user_config_effective
  77. cfg = load_user_config_effective(get_config_path())
  78. except Exception:
  79. from hermes_cli.config_backend import config_exists, read_config_doc
  80. config_path = get_config_path()
  81. cfg = (read_config_doc(config_path) or {}) if config_exists(config_path) else {}
  82. if cfg:
  83. tz_cfg = cfg.get("timezone", "")
  84. if isinstance(tz_cfg, str) and tz_cfg.strip():
  85. return tz_cfg.strip()
  86. except Exception:
  87. pass
  88. return ""
  89. def _timezone_entry() -> tuple[str, Optional[ZoneInfo]]:
  90. """Cached ``(configured name, ZoneInfo | None)`` for the active profile."""
  91. cache_identity = _timezone_cache_identity()
  92. with _cache_lock:
  93. entry = _tz_cache.get(cache_identity)
  94. if entry is not None:
  95. return entry
  96. # Resolve outside the lock (config file I/O); first writer wins so concurrent resolvers of the
  97. # same identity converge on one ZoneInfo object.
  98. name = _resolve_timezone_name()
  99. tz = None
  100. if name:
  101. try:
  102. tz = ZoneInfo(name)
  103. except Exception as exc:
  104. logger.warning("Invalid timezone '%s': %s. Falling back to server local time.", name, exc)
  105. with _cache_lock:
  106. return _tz_cache.setdefault(cache_identity, (name, tz))
  107. def get_timezone() -> Optional[ZoneInfo]:
  108. """Return the active profile's configured ZoneInfo, or None (server-local)."""
  109. return _timezone_entry()[1]
  110. def get_timezone_name() -> str:
  111. """The active profile's configured IANA timezone string, or ``""`` (server-local). Same
  112. resolution and cache as :func:`get_timezone`; for handing ``TZ`` to sandboxed children."""
  113. return _timezone_entry()[0]
  114. def reset_cache() -> None:
  115. """Clear the cached timezone so the next call re-resolves it (after config/env changes)."""
  116. with _cache_lock:
  117. _tz_cache.clear()
  118. def now() -> datetime:
  119. """Current time as a tz-aware datetime: configured zone, else server-local."""
  120. tz = get_timezone()
  121. return datetime.now(tz) if tz is not None else datetime.now().astimezone()