|
| 1 | +"""Lightweight internationalization (i18n) for Hermes static user-facing messages. |
| 2 | +
|
| 3 | +Scope (thin slice, by design): only the highest-impact static strings shown |
| 4 | +to the user by Hermes itself -- approval prompts, a handful of gateway slash |
| 5 | +command replies, restart-drain notices. Agent-generated output, log lines, |
| 6 | +error tracebacks, tool outputs, and slash-command descriptions all stay in |
| 7 | +English. |
| 8 | +
|
| 9 | +Catalog files live under ``locales/<lang>.yaml`` at the repo root. Each |
| 10 | +catalog is a flat dict keyed by dotted paths (e.g. ``approval.choose`` or |
| 11 | +``gateway.approval_expired``). Missing keys fall back to English; if English |
| 12 | +is missing too, the key path itself is returned so a broken catalog never |
| 13 | +crashes the agent. |
| 14 | +
|
| 15 | +Usage:: |
| 16 | +
|
| 17 | + from agent.i18n import t |
| 18 | + print(t("approval.choose_long")) # current lang |
| 19 | + print(t("gateway.draining", count=3)) # {count} formatted |
| 20 | + print(t("approval.choose_long", lang="zh")) # explicit override |
| 21 | +
|
| 22 | +Language resolution order: |
| 23 | + 1. Explicit ``lang=`` argument passed to :func:`t` |
| 24 | + 2. ``HERMES_LANGUAGE`` environment variable (for tests / quick override) |
| 25 | + 3. ``display.language`` from config.yaml |
| 26 | + 4. ``"en"`` (baseline) |
| 27 | +
|
| 28 | +Supported languages: en, zh, ja, de, es. Unknown values fall back to en. |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import logging |
| 34 | +import os |
| 35 | +import threading |
| 36 | +from functools import lru_cache |
| 37 | +from pathlib import Path |
| 38 | +from typing import Any |
| 39 | + |
| 40 | +logger = logging.getLogger(__name__) |
| 41 | + |
| 42 | +SUPPORTED_LANGUAGES: tuple[str, ...] = ("en", "zh", "ja", "de", "es") |
| 43 | +DEFAULT_LANGUAGE = "en" |
| 44 | + |
| 45 | +# Accept a few natural aliases so users who type "chinese" / "zh-CN" / "jp" |
| 46 | +# get the right catalog instead of silently falling back to English. |
| 47 | +_LANGUAGE_ALIASES: dict[str, str] = { |
| 48 | + "english": "en", "en-us": "en", "en-gb": "en", |
| 49 | + "chinese": "zh", "mandarin": "zh", "zh-cn": "zh", "zh-tw": "zh", "zh-hans": "zh", "zh-hant": "zh", |
| 50 | + "japanese": "ja", "jp": "ja", "ja-jp": "ja", |
| 51 | + "german": "de", "deutsch": "de", "de-de": "de", |
| 52 | + "spanish": "es", "español": "es", "espanol": "es", "es-es": "es", "es-mx": "es", |
| 53 | +} |
| 54 | + |
| 55 | +_catalog_cache: dict[str, dict[str, str]] = {} |
| 56 | +_catalog_lock = threading.Lock() |
| 57 | + |
| 58 | + |
| 59 | +def _locales_dir() -> Path: |
| 60 | + """Return the directory containing locale YAML files. |
| 61 | +
|
| 62 | + Lives next to the repo root so both the bundled install and editable |
| 63 | + checkouts find it without PYTHONPATH gymnastics. |
| 64 | + """ |
| 65 | + # agent/i18n.py -> agent/ -> repo root |
| 66 | + return Path(__file__).resolve().parent.parent / "locales" |
| 67 | + |
| 68 | + |
| 69 | +def _normalize_lang(value: Any) -> str: |
| 70 | + """Normalize a user-supplied language value to a supported code. |
| 71 | +
|
| 72 | + Accepts supported codes directly, common aliases (``chinese`` -> ``zh``), |
| 73 | + and case-insensitive regional tags (``zh-CN`` -> ``zh``). Returns the |
| 74 | + default language for unknown values. |
| 75 | + """ |
| 76 | + if not isinstance(value, str): |
| 77 | + return DEFAULT_LANGUAGE |
| 78 | + key = value.strip().lower() |
| 79 | + if not key: |
| 80 | + return DEFAULT_LANGUAGE |
| 81 | + if key in SUPPORTED_LANGUAGES: |
| 82 | + return key |
| 83 | + if key in _LANGUAGE_ALIASES: |
| 84 | + return _LANGUAGE_ALIASES[key] |
| 85 | + # Try stripping a region suffix (e.g. "pt-br" -> "pt" won't be supported, |
| 86 | + # but "zh-CN" -> "zh" will). |
| 87 | + base = key.split("-", 1)[0] |
| 88 | + if base in SUPPORTED_LANGUAGES: |
| 89 | + return base |
| 90 | + return DEFAULT_LANGUAGE |
| 91 | + |
| 92 | + |
| 93 | +def _load_catalog(lang: str) -> dict[str, str]: |
| 94 | + """Load and flatten one locale YAML file into a dotted-key dict. |
| 95 | +
|
| 96 | + YAML files can be nested for human readability; this produces the flat |
| 97 | + key space :func:`t` expects. Cached per-language for the process. |
| 98 | + """ |
| 99 | + with _catalog_lock: |
| 100 | + cached = _catalog_cache.get(lang) |
| 101 | + if cached is not None: |
| 102 | + return cached |
| 103 | + |
| 104 | + path = _locales_dir() / f"{lang}.yaml" |
| 105 | + if not path.is_file(): |
| 106 | + logger.debug("i18n catalog missing for %s at %s", lang, path) |
| 107 | + with _catalog_lock: |
| 108 | + _catalog_cache[lang] = {} |
| 109 | + return {} |
| 110 | + |
| 111 | + try: |
| 112 | + import yaml # PyYAML is already a hermes dependency |
| 113 | + with path.open("r", encoding="utf-8") as f: |
| 114 | + raw = yaml.safe_load(f) or {} |
| 115 | + except Exception as exc: |
| 116 | + logger.warning("Failed to load i18n catalog %s: %s", path, exc) |
| 117 | + with _catalog_lock: |
| 118 | + _catalog_cache[lang] = {} |
| 119 | + return {} |
| 120 | + |
| 121 | + flat: dict[str, str] = {} |
| 122 | + _flatten_into(raw, "", flat) |
| 123 | + with _catalog_lock: |
| 124 | + _catalog_cache[lang] = flat |
| 125 | + return flat |
| 126 | + |
| 127 | + |
| 128 | +def _flatten_into(node: Any, prefix: str, out: dict[str, str]) -> None: |
| 129 | + if isinstance(node, dict): |
| 130 | + for key, value in node.items(): |
| 131 | + child_key = f"{prefix}.{key}" if prefix else str(key) |
| 132 | + _flatten_into(value, child_key, out) |
| 133 | + elif isinstance(node, str): |
| 134 | + out[prefix] = node |
| 135 | + # Non-string, non-dict leaves are ignored -- catalogs are text-only. |
| 136 | + |
| 137 | + |
| 138 | +@lru_cache(maxsize=1) |
| 139 | +def _config_language_cached() -> str | None: |
| 140 | + """Read ``display.language`` from config.yaml once per process. |
| 141 | +
|
| 142 | + Cached because ``t()`` is called in hot paths (every approval prompt, |
| 143 | + every gateway reply) and re-reading YAML each call would be wasteful. |
| 144 | + ``reset_language_cache()`` clears this when config changes at runtime |
| 145 | + (e.g. after the setup wizard). |
| 146 | + """ |
| 147 | + try: |
| 148 | + from hermes_cli.config import load_config |
| 149 | + cfg = load_config() |
| 150 | + lang = (cfg.get("display") or {}).get("language") |
| 151 | + if lang: |
| 152 | + return _normalize_lang(lang) |
| 153 | + except Exception as exc: |
| 154 | + logger.debug("Could not read display.language from config: %s", exc) |
| 155 | + return None |
| 156 | + |
| 157 | + |
| 158 | +def reset_language_cache() -> None: |
| 159 | + """Invalidate cached language resolution and catalogs. |
| 160 | +
|
| 161 | + Call after :func:`hermes_cli.config.save_config` if a running process |
| 162 | + needs to pick up a changed ``display.language`` without restart. |
| 163 | + """ |
| 164 | + _config_language_cached.cache_clear() |
| 165 | + with _catalog_lock: |
| 166 | + _catalog_cache.clear() |
| 167 | + |
| 168 | + |
| 169 | +def get_language() -> str: |
| 170 | + """Resolve the active language using env > config > default order.""" |
| 171 | + env_lang = os.environ.get("HERMES_LANGUAGE") |
| 172 | + if env_lang: |
| 173 | + return _normalize_lang(env_lang) |
| 174 | + cfg_lang = _config_language_cached() |
| 175 | + if cfg_lang: |
| 176 | + return cfg_lang |
| 177 | + return DEFAULT_LANGUAGE |
| 178 | + |
| 179 | + |
| 180 | +def t(key: str, lang: str | None = None, **format_kwargs: Any) -> str: |
| 181 | + """Translate a dotted key to the active language. |
| 182 | +
|
| 183 | + Parameters |
| 184 | + ---------- |
| 185 | + key |
| 186 | + Dotted path into the catalog, e.g. ``"approval.choose_long"``. |
| 187 | + lang |
| 188 | + Explicit language override. Takes precedence over env + config. |
| 189 | + **format_kwargs |
| 190 | + ``str.format`` substitution arguments (``t("gateway.drain", count=3)`` |
| 191 | + expects a catalog entry with a ``{count}`` placeholder). |
| 192 | +
|
| 193 | + Returns |
| 194 | + ------- |
| 195 | + The translated string, or the English fallback if the key is missing in |
| 196 | + the target language, or the bare key if English is also missing. |
| 197 | + """ |
| 198 | + target = _normalize_lang(lang) if lang else get_language() |
| 199 | + catalog = _load_catalog(target) |
| 200 | + value = catalog.get(key) |
| 201 | + |
| 202 | + if value is None and target != DEFAULT_LANGUAGE: |
| 203 | + # Fall through to English rather than showing a key path to the user. |
| 204 | + value = _load_catalog(DEFAULT_LANGUAGE).get(key) |
| 205 | + |
| 206 | + if value is None: |
| 207 | + # Last-ditch: return the key itself. A broken catalog should not |
| 208 | + # crash anything; it just looks ugly until someone fixes it. |
| 209 | + logger.debug("i18n miss: key=%r lang=%r", key, target) |
| 210 | + value = key |
| 211 | + |
| 212 | + if format_kwargs: |
| 213 | + try: |
| 214 | + return value.format(**format_kwargs) |
| 215 | + except (KeyError, IndexError, ValueError) as exc: |
| 216 | + logger.warning( |
| 217 | + "i18n format failed for key=%r lang=%r kwargs=%r: %s", |
| 218 | + key, target, format_kwargs, exc, |
| 219 | + ) |
| 220 | + return value |
| 221 | + return value |
| 222 | + |
| 223 | + |
| 224 | +__all__ = [ |
| 225 | + "SUPPORTED_LANGUAGES", |
| 226 | + "DEFAULT_LANGUAGE", |
| 227 | + "t", |
| 228 | + "get_language", |
| 229 | + "reset_language_cache", |
| 230 | +] |
0 commit comments