Skip to content

The agent that grows with you

fix(time): repair surrogate-bearing locale zone names at every strftime site

brooklyn!58694737e214
diff --git a/agent/auxiliary_unavailable.py b/agent/auxiliary_unavailable.py
index 81b5759e47c..bf8ee5ddbff 100644
--- a/agent/auxiliary_unavailable.py
+++ b/agent/auxiliary_unavailable.py
@@ -11,8 +11,11 @@ import contextlib
import logging
import threading
import time
+from datetime import datetime
from typing import Optional
+from hermes_time import safe_strftime
+
logger = logging.getLogger(__name__)
@@ -78,7 +81,7 @@ def pool_cooldown_message(provider_id: str) -> Optional[str]:
if until is not None and until > now]
if len(resets) != len(live):
return None
- when = time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(min(resets)))
+ when = safe_strftime(datetime.fromtimestamp(min(resets)).astimezone(), "%Y-%m-%d %H:%M %Z")
which = ("its only credential is" if len(live) == 1
else f"all {len(live)} credentials are")
return (f"Provider '{provider_id}' is set in config.yaml but {which} cooling down after a "
diff --git a/agent/billing_usage.py b/agent/billing_usage.py
index 3801a926ec6..e3fc1ba7af0 100644
--- a/agent/billing_usage.py
+++ b/agent/billing_usage.py
@@ -16,6 +16,8 @@ import os
from dataclasses import dataclass
from typing import Any, Optional
+from hermes_time import safe_strftime
+
logger = logging.getLogger(__name__)
# Below this TOTAL spendable ($) a paid account is flagged "low" — the alert state
@@ -70,7 +72,7 @@ def format_renews(value: Optional[str]) -> Optional[str]:
except ValueError:
return text
# %-d isn't portable to Windows; build the day without a leading zero.
- return f"{dt.strftime('%b')} {dt.day}, {dt.year}"
+ return f"{safe_strftime(dt, '%b')} {dt.day}, {dt.year}"
@dataclass(frozen=True)
diff --git a/agent/insights.py b/agent/insights.py
index 568dee0e4ce..53ac36a7c9a 100644
--- a/agent/insights.py
+++ b/agent/insights.py
@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Optional
from agent.usage_pricing import CanonicalUsage, estimate_usage_cost, format_cost_label, format_duration_compact, has_known_pricing
from hermes_cli.timefmt import coerce_epoch
+from hermes_time import safe_strftime
_TOKEN_KEYS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens")
_SKILL_TOOLS = {"skill_view", "skill_manage"}
@@ -72,7 +73,7 @@ def _hour12(hr: int) -> str:
def _day(ts: Any) -> str:
- return datetime.fromtimestamp(ts).strftime("%b %d") if ts and (ts := coerce_epoch(ts)) else "?"
+ return safe_strftime(datetime.fromtimestamp(ts), "%b %d") if ts and (ts := coerce_epoch(ts)) else "?"
def _scoped(before: str, after: str = "", *, src: str = " AND s.source = ?") -> tuple[str, str]:
@@ -488,8 +489,8 @@ class InsightsEngine:
"",
]
if (start := coerce_epoch(o.get("date_range_start"))) is not None and (end := coerce_epoch(o.get("date_range_end"))) is not None:
- start_str = datetime.fromtimestamp(start).strftime("%b %d, %Y")
- end_str = datetime.fromtimestamp(end).strftime("%b %d, %Y")
+ start_str = safe_strftime(datetime.fromtimestamp(start), "%b %d, %Y")
+ end_str = safe_strftime(datetime.fromtimestamp(end), "%b %d, %Y")
lines += [f" Period: {start_str} — {end_str}", ""]
lines += self._section("📋 Overview") + [
f" Sessions: {o['total_sessions']:<12} Messages: {o['total_messages']:,}",
diff --git a/agent/learning_graph_render.py b/agent/learning_graph_render.py
index 7bbed7d2370..cc735abfc95 100644
--- a/agent/learning_graph_render.py
+++ b/agent/learning_graph_render.py
@@ -11,6 +11,8 @@ from collections import Counter
from datetime import datetime, timezone
from typing import Any, Iterable, Optional
+from hermes_time import safe_strftime
+
LEAD_IN = 0.06 # time-axis.ts LEAD_IN: the oldest node sits just off recency 0.
# constants.ts AGE_GRADIENT — old quiet, recent bright.
AGE_OLD_INK, AGE_MID_INK, AGE_NEW_INK, AGE_MID = 0.42, 0.74, 0.95, 0.52
@@ -78,7 +80,7 @@ def format_date(ts: Optional[float]) -> str:
dt = _utc(float(ts)) if ts else None
except (ValueError, OSError, OverflowError):
dt = None
- return f"{dt.day} {dt.strftime('%b %Y')}" if dt else "unknown"
+ return f"{dt.day} {safe_strftime(dt, '%b %Y')}" if dt else "unknown"
def compute_recency(nodes: list[dict[str, Any]]) -> dict[str, Any]:
@@ -204,8 +206,8 @@ class _ChartBucket:
# granularity → (period key, row label) from a UTC datetime.
_PERIODS: dict[str, tuple] = {
- "day": (lambda dt: (dt.year, dt.month, dt.day), lambda dt: f"{dt.day} {dt.strftime('%b')}"),
- "month": (lambda dt: (dt.year, dt.month), lambda dt: dt.strftime("%b %Y")),
+ "day": (lambda dt: (dt.year, dt.month, dt.day), lambda dt: f"{dt.day} {safe_strftime(dt, '%b')}"),
+ "month": (lambda dt: (dt.year, dt.month), lambda dt: safe_strftime(dt, "%b %Y")),
"year": (lambda dt: (dt.year,), lambda dt: dt.strftime("%Y")),
}
diff --git a/cron/quota_hold.py b/cron/quota_hold.py
index f4c7a690d2d..6069cc1328b 100644
--- a/cron/quota_hold.py
+++ b/cron/quota_hold.py
@@ -19,7 +19,7 @@ import re
from datetime import datetime
from typing import Any, Dict, Optional
-from hermes_time import now as _hermes_now
+from hermes_time import now as _hermes_now, safe_strftime
logger = logging.getLogger("cron.scheduler")
@@ -110,6 +110,6 @@ def hold_notice(job: Dict[str, Any], hold_seconds: Optional[float]) -> str:
hours = float(hold_seconds) / 3600.0
return (
f"\nThe provider's usage window is closed for about {hours:.1f}h. This job is held "
- f"until its first scheduled run after {window_end.strftime('%Y-%m-%d %H:%M %Z')} — "
+ f"until its first scheduled run after {safe_strftime(window_end, '%Y-%m-%d %H:%M %Z')} — "
"no further alerts until then."
)
diff --git a/cron/scheduler.py b/cron/scheduler.py
index f1c41948f69..9e16f57c955 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -41,7 +41,7 @@ from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.config import (
load_config, load_config_readonly)
from hermes_cli.fallback_config import get_fallback_chain, scoped_fallback_chain
-from hermes_time import now as _hermes_now
+from hermes_time import now as _hermes_now, safe_strftime
from agent.interrupt_compat import request_hard_interrupt
from agent.delegation_context import (
enter_non_dispatcher_owned_context, exit_non_dispatcher_owned_context)
@@ -2093,7 +2093,7 @@ def _finalize_cron_session(session_db, agent, job_id: str, job_name: str, cron_s
# Title the cron session from the job (name -> id) and PERSIST it BEFORE end_session()/close() tear
# the connection down, so the close can never run over an in-flight title write (#50536).
_title_base = " ".join(job_name.split())[:60].strip() or f"cron {job_id}"
- _cron_title = f"{_title_base} · {_hermes_now().strftime('%b %d %H:%M')}"
+ _cron_title = f"{_title_base} · {safe_strftime(_hermes_now(), '%b %d %H:%M')}"
if not _set_cron_session_title(_session_db, _final_cron_session_id, _cron_title):
_set_cron_session_title(_session_db, _final_cron_session_id, f"cron {job_id}")
except (Exception, KeyboardInterrupt) as e:
diff --git a/hermes_time.py b/hermes_time.py
index e8ab599089a..a71f2206294 100644
--- a/hermes_time.py
+++ b/hermes_time.py
@@ -5,6 +5,7 @@
time. Invalid timezone values log a warning and fall back — never crash.
"""
+import locale
import logging
import os
import re
@@ -15,9 +16,6 @@ from zoneinfo import ZoneInfo
from hermes_constants import get_config_path
-from agent.message_sanitization import _sanitize_surrogates
-from hermes_constants import get_config_path
-
logger = logging.getLogger(__name__)
# Cache keyed by timezone *source* identity. This process can multiplex profiles by switching
@@ -29,98 +27,41 @@ logger = logging.getLogger(__name__)
_cache_lock = threading.Lock()
_tz_cache: Dict[Tuple[str, str], Tuple[str, Optional[ZoneInfo]]] = {}
-_WEEKDAY_NAMES = (
- ("Monday", "Mon"),
- ("Tuesday", "Tue"),
- ("Wednesday", "Wed"),
- ("Thursday", "Thu"),
- ("Friday", "Fri"),
- ("Saturday", "Sat"),
- ("Sunday", "Sun"),
-)
-_MONTH_NAMES = (
- ("January", "Jan"),
- ("February", "Feb"),
- ("March", "Mar"),
- ("April", "Apr"),
- ("May", "May"),
- ("June", "Jun"),
- ("July", "Jul"),
- ("August", "Aug"),
- ("September", "Sep"),
- ("October", "Oct"),
- ("November", "Nov"),
- ("December", "Dec"),
-)
-_LOCALE_DIRECTIVE_RE = re.compile(r"(?<!%)%(?:[EO])?([aAbBchpXxZz])")
-
-
-def _numeric_utc_offset(value: datetime) -> str:
- offset = value.utcoffset()
- if offset is None:
- return ""
- total_seconds = int(offset.total_seconds())
- sign = "+" if total_seconds >= 0 else "-"
- total_seconds = abs(total_seconds)
- hours, remainder = divmod(total_seconds, 3600)
- minutes, seconds = divmod(remainder, 60)
- suffix = f"{seconds:02d}" if seconds else ""
- return f"{sign}{hours:02d}{minutes:02d}{suffix}"
-
-
-def _portable_directive(value: datetime, directive: str) -> str:
- weekday_long, weekday_short = _WEEKDAY_NAMES[value.weekday()]
- month_long, month_short = _MONTH_NAMES[value.month - 1]
- hour = getattr(value, "hour", 0)
- minute = getattr(value, "minute", 0)
- second = getattr(value, "second", 0)
- replacements = {
- "a": weekday_short,
- "A": weekday_long,
- "b": month_short,
- "h": month_short,
- "B": month_long,
- "c": (
- f"{weekday_short} {month_short} {value.day:02d} "
- f"{hour:02d}:{minute:02d}:{second:02d} {value.year:04d}"
- ),
- "p": "AM" if hour < 12 else "PM",
- "X": f"{hour:02d}:{minute:02d}:{second:02d}",
- "x": f"{value.year:04d}-{value.month:02d}-{value.day:02d}",
- "z": _numeric_utc_offset(value),
- }
- if directive == "Z":
+_SURROGATE_RE = re.compile(r"[\ud800-\udfff]")
+# ASCII plus surrogateescape'd bytes only: the shape of native text decoded with the wrong codec.
+_ESCAPED_BYTES_RE = re.compile(r"[\x00-\x7f\udc80-\udcff]*")
+
+
+def _repair_surrogates(text: str, encoding: Optional[str] = None) -> str:
+ """Make locale text JSON/UTF-8 safe; a no-op (same object) on valid text.
+
+ Windows hands back zone names in the ANSI code page (``heure d'\\xe9t\\xe9``) but a UTF-8
+ ``LC_CTYPE`` (UTF-8 mode, or a library flipping the process locale mid-run) decodes those
+ bytes with ``surrogateescape`` into lone surrogates. Recover the bytes and decode them with
+ the ANSI code page; when that is not possible, replace each surrogate with U+FFFD."""
+ if text.isascii() or not _SURROGATE_RE.search(text):
+ return text
+ if _ESCAPED_BYTES_RE.fullmatch(text):
try:
- return value.tzname() or ""
- except UnicodeEncodeError:
- return ""
- return replacements[directive]
+ return text.encode("ascii", "surrogateescape").decode(encoding or locale.getencoding())
+ except (LookupError, UnicodeError):
+ pass
+ return _SURROGATE_RE.sub("\ufffd", text)
def safe_strftime(value: datetime, fmt: str) -> str:
- """Format a datetime without leaking invalid locale surrogates.
+ """``value.strftime(fmt)`` that never raises or returns lone surrogates over locale text.
- Some Windows locale/code-page combinations raise ``UnicodeEncodeError``
- inside ``strftime`` before Python receives a string. Retry with portable
- replacements for locale-sensitive directives, then scrub any surrogate
- code points returned by the platform or ``tzname()``.
- """
+ ``datetime.strftime`` splices ``tzname()`` into the format as UTF-8, so a zone name carrying
+ surrogates (see ``_repair_surrogates``) raises ``UnicodeEncodeError`` before any string exists
+ (#102910). On that failure ``%Z`` is rendered from the repaired name instead. Output for valid
+ locale text is byte-identical to ``strftime`` (the system prompt must stay cache-stable)."""
try:
- rendered = value.strftime(fmt)
+ return _repair_surrogates(value.strftime(fmt))
except UnicodeEncodeError:
- replacements: Dict[str, str] = {}
-
- def replace_directive(match: re.Match[str]) -> str:
- token = f"__HERMES_TIME_{len(replacements)}__"
- replacements[token] = _sanitize_surrogates(
- _portable_directive(value, match.group(1))
- )
- return token
-
- rendered = value.strftime(_LOCALE_DIRECTIVE_RE.sub(replace_directive, fmt))
- for token, replacement in replacements.items():
- rendered = rendered.replace(token, replacement)
- return _sanitize_surrogates(rendered)
+ zone = _repair_surrogates(value.tzname() or "").replace("%", "%%")
+ return _repair_surrogates(value.strftime(
+ re.sub(r"%([%Z])", lambda m: zone if m.group(1) == "Z" else "%%", fmt)))
def _env_timezone() -> str:
diff --git a/tests/agent/test_system_prompt.py b/tests/agent/test_system_prompt.py
index 2b30f449bd5..b14f0384b5f 100644
--- a/tests/agent/test_system_prompt.py
+++ b/tests/agent/test_system_prompt.py
@@ -1,5 +1,6 @@
"""Tests for agent/system_prompt.py — context-file cwd wiring."""
+import json
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
@@ -849,27 +850,16 @@ class TestConversationStartedTwoLine:
assert "Conversation started:" in vol
assert "as of the last context rebuild" not in vol
- def test_windows_locale_strftime_error_does_not_abort_prompt(self):
- class _UnicodeFailingDateTime(datetime):
- def strftime(self, fmt):
- if "%Z" in fmt:
- raise UnicodeEncodeError(
- "utf-8", "\udce9", 0, 1, "surrogates not allowed"
- )
- return super().strftime(fmt)
-
- def tzname(self):
- return "Paris \udce9"
-
- current = _UnicodeFailingDateTime(
- 2026, 7, 14, 13, 5, tzinfo=ZoneInfo("Europe/Paris")
- )
+ def test_surrogate_zone_name_does_not_abort_prompt(self):
+ # Windows cp1252 zone name decoded under a UTF-8 LC_CTYPE; strftime("%Z") raised (#102910).
+ from datetime import timedelta, timezone
+ current = datetime(2026, 7, 14, 13, 5, tzinfo=timezone(timedelta(hours=2), "Paris, Madrid (heure d'\udce9t\udce9)"))
with patch("hermes_time.now", return_value=current):
vol = self._volatile(self._agent("20260714_090000_fresh"))
+ json.dumps(vol, ensure_ascii=False).encode("utf-8")
assert "Conversation started: Tuesday, July 14, 2026" in vol
- assert "Paris �" in vol
- vol.encode("utf-8")
+ assert "Paris, Madrid (heure d'" in vol and "UTC+02:00" in vol
def test_timeless_bot_chat_unaffected(self):
agent = self._agent("20200110_090000_old")
diff --git a/tests/cron/test_timezone.py b/tests/cron/test_timezone.py
index ba0ff7eef28..85e18bd9fd5 100644
--- a/tests/cron/test_timezone.py
+++ b/tests/cron/test_timezone.py
@@ -47,41 +47,31 @@ class TestHermesTimeNow:
assert offset == timedelta(hours=5, minutes=30)
-
-
-class _UnicodeFailingDateTime(datetime):
- """Model Windows strftime failing before it can return locale text."""
-
- def strftime(self, fmt):
- if any(code in fmt for code in ("%A", "%B", "%Z", "%z")):
- raise UnicodeEncodeError("utf-8", "\udce9", 0, 1, "surrogates not allowed")
- return super().strftime(fmt)
-
- def tzname(self):
- return "Paris \udce9"
+# Windows zone name in cp1252 bytes, decoded under a UTF-8 LC_CTYPE with surrogateescape (#102910).
+_ESCAPED_ZONE = "Paris, Madrid (heure d'\udce9t\udce9)"
class TestSafeStrftime:
- def test_sanitizes_surrogates_returned_by_platform(self):
- class _ReturningSurrogate:
- def strftime(self, _fmt):
- return "Paris \udce9"
-
- assert hermes_time.safe_strftime(_ReturningSurrogate(), "%Z") == "Paris �"
-
- def test_recovers_when_windows_locale_formatting_raises(self):
- value = _UnicodeFailingDateTime(
- 2026, 7, 14, 13, 5, tzinfo=timezone(timedelta(hours=2))
- )
-
- rendered = hermes_time.safe_strftime(value, "%A, %B %d, %Y %H:%M %Z %z")
-
- assert rendered == "Tuesday, July 14, 2026 13:05 Paris � +0200"
- rendered.encode("utf-8")
-
-
-
-
+ def test_valid_locale_text_is_byte_identical_to_strftime(self):
+ """The system prompt embeds this output, so healthy locales must not change a byte."""
+ from zoneinfo import ZoneInfo
+ fmt = "%a %A %b %B %d %Y %H:%M:%S %Z %z %%Z"
+ for value in (
+ datetime(2026, 7, 14, 13, 5),
+ datetime(2026, 7, 14, 13, 5, tzinfo=ZoneInfo("Europe/Paris")),
+ datetime(2026, 7, 14, 13, 5, tzinfo=timezone(timedelta(hours=-3), "Hora estándar de Argentina")),
+ ):
+ assert hermes_time.safe_strftime(value, fmt) == value.strftime(fmt)
+
+ def test_surrogate_zone_name_renders_json_safe(self):
+ import json
+ value = datetime(2026, 7, 14, 13, 5, tzinfo=timezone(timedelta(hours=2), _ESCAPED_ZONE))
+ rendered = hermes_time.safe_strftime(value, "%a %Y-%m-%d %H:%M %Z %z %%Z")
+ json.dumps(rendered, ensure_ascii=False).encode("utf-8")
+ assert rendered.startswith("Tue 2026-07-14 13:05 Paris, Madrid (heure d'")
+ assert rendered.endswith(") +0200 %Z")
+ # The escaped bytes decode back through the Windows ANSI code page.
+ assert hermes_time._repair_surrogates(_ESCAPED_ZONE, "cp1252") == "Paris, Madrid (heure d'été)"
class TestGetTimezone:
diff --git a/tools/session_search_tool.py b/tools/session_search_tool.py
index f5c0e78a831..fd73bd3fc58 100644
--- a/tools/session_search_tool.py
+++ b/tools/session_search_tool.py
@@ -16,6 +16,7 @@ from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Union
from hermes_state_common import _BOUNDARY_END_REASONS
+from hermes_time import safe_strftime
# Hidden from browsing/searching — integrations (HERMES_SESSION_SOURCE=tool), delegate
# subagent runs, kanban workers are not the user's history.
@@ -80,7 +81,7 @@ def _format_timestamp(ts: Union[int, float, str, None]) -> str:
return "unknown"
if isinstance(ts, str) and not ts.replace(".", "").replace("-", "").isdigit():
return ts
- return _quiet(lambda: datetime.fromtimestamp(float(ts)).strftime("%B %d, %Y at %I:%M %p"), str(ts),
+ return _quiet(lambda: safe_strftime(datetime.fromtimestamp(float(ts)), "%B %d, %Y at %I:%M %p"), str(ts),
"Failed to format timestamp %s: %s", ts, with_exc=True)