Skip to content

The agent that grows with you

fix(time): tolerate Windows locale strftime errors

fangliquan85cb540e6dfb
diff --git a/agent/account_usage.py b/agent/account_usage.py
index fde2c29e3c9..e5989e26b92 100644
--- a/agent/account_usage.py
+++ b/agent/account_usage.py
@@ -11,6 +11,7 @@ import httpx
from agent.anthropic_credentials import _is_oauth_token, resolve_anthropic_token
from hermes_cli.auth import AuthError, _read_codex_tokens, resolve_codex_runtime_credentials
from hermes_cli.runtime_provider import resolve_runtime_provider
+from hermes_time import safe_strftime
if TYPE_CHECKING:
from typing import TypeGuard
@@ -78,7 +79,7 @@ def _parse_dt(value: Any) -> Optional[datetime]:
def _format_reset(dt: Optional[datetime]) -> str:
if not dt:
return "unknown"
- stamp = dt.astimezone().strftime("%Y-%m-%d %H:%M %Z")
+ stamp = safe_strftime(dt.astimezone(), "%Y-%m-%d %H:%M %Z")
total_seconds = int((dt - _utc_now()).total_seconds())
if total_seconds <= 0:
return f"now ({stamp})"
diff --git a/agent/system_prompt.py b/agent/system_prompt.py
index 9d5c5e1eccc..77390ce01d4 100644
--- a/agent/system_prompt.py
+++ b/agent/system_prompt.py
@@ -474,8 +474,9 @@ def _zone_bits(now: Any, tz: Any) -> List[str]:
"""IANA key, abbreviation (if different) and UTC offset — all constant for
the day, so the byte-stable date line stays cacheable."""
_iana = getattr(tz, "key", None)
- _abbrev = now.strftime("%Z")
- _offset = now.strftime("%z") # '-0400' -> 'UTC-04:00'
+ from hermes_time import safe_strftime
+ _abbrev = safe_strftime(now, "%Z")
+ _offset = safe_strftime(now, "%z") # '-0400' -> 'UTC-04:00'
bits = [_iana] if _iana else []
if _abbrev and _abbrev != _iana:
bits.append(_abbrev)
@@ -488,12 +489,12 @@ def _timestamp_line(agent: Any) -> str:
"""Date-only so the prompt is byte-stable for the day; zone + offset so
tools needn't guess EST vs EDT. Long-lived sessions get an "as of" line on
rebuild days (the cache prefix is already invalidated at that boundary)."""
- from hermes_time import get_timezone as _hermes_tz, now as _hermes_now
+ from hermes_time import get_timezone as _hermes_tz, now as _hermes_now, safe_strftime
now = _hermes_now()
_bits = _zone_bits(now, _hermes_tz())
_zone_suffix = f" ({', '.join(_bits)})" if _bits else ""
_start = _session_start_like(agent, now)
- timestamp_line = f"Conversation started: {_start.strftime('%A, %B %d, %Y')}{_zone_suffix}"
+ timestamp_line = f"Conversation started: {safe_strftime(_start, '%A, %B %d, %Y')}{_zone_suffix}"
# Second line (maintainer design, salvaging #96224's anchor): long-lived sessions — Bot Mode
# forever-chats, messenger channels people never close — span many days and many compactions. A lone
# birth date leads the model to believe it is still living in that old day. The prompt is rebuilt at
@@ -502,7 +503,7 @@ def _timestamp_line(agent: Any) -> str:
# line costs no extra cache churn. Same-day sessions skip the second line entirely — nothing to correct,
# and the single-line shape stays byte-identical for the day (prefix-cache safe).
if now.strftime("%Y%m%d") != _start.strftime("%Y%m%d"):
- timestamp_line += (f"\nToday's date (as of the last context rebuild): {now.strftime('%A, %B %d, %Y')} "
+ timestamp_line += (f"\nToday's date (as of the last context rebuild): {safe_strftime(now, '%A, %B %d, %Y')} "
"— trust this over the start date for what day it is now; query tools for exact time.")
if getattr(agent, "_bot_chat_timeless_prompt", False):
timestamp_line = f"Timezone: {', '.join(_bits)}" if _bits else ""
diff --git a/gateway/message_timestamps.py b/gateway/message_timestamps.py
index 9f353b60bb2..7f32fc0b94a 100644
--- a/gateway/message_timestamps.py
+++ b/gateway/message_timestamps.py
@@ -11,6 +11,8 @@ import re
from datetime import datetime
from typing import Any, Optional, Tuple
+from hermes_time import safe_strftime
+
# Leading timestamp prefix, either the current human format
# ``[Tue 2026-04-28 13:40:53 CEST]`` or the older ISO one
@@ -82,7 +84,7 @@ def format_message_timestamp(ts_value: Any, tz=None) -> str:
if epoch is None:
return ""
dt = datetime.fromtimestamp(epoch, tz=tz) if tz is not None else datetime.fromtimestamp(epoch).astimezone()
- return f"[{dt.strftime('%a %Y-%m-%d %H:%M:%S %Z')}]"
+ return f"[{safe_strftime(dt, '%a %Y-%m-%d %H:%M:%S %Z')}]"
def strip_leading_message_timestamps(content: str, tz=None) -> Tuple[str, Optional[float]]:
diff --git a/hermes_cli/goals.py b/hermes_cli/goals.py
index 878df174fda..500096ef87c 100644
--- a/hermes_cli/goals.py
+++ b/hermes_cli/goals.py
@@ -22,6 +22,7 @@ from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from hermes_cli._subprocess_compat import noninteractive_git_env
+from hermes_time import safe_strftime
logger = logging.getLogger(__name__)
@@ -905,7 +906,7 @@ def judge_goal(
response=_truncate(last_response, _JUDGE_RESPONSE_SNIPPET_CHARS),
background_block=_render_background_block(background_processes)
+ (JUDGE_DELEGATIONS_BLOCK_TEMPLATE.format(count=active_delegations) if active_delegations > 0 else ""),
- current_time=datetime.now(tz=timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M:%S %Z"),
+ current_time=safe_strftime(datetime.now(tz=timezone.utc).astimezone(), "%Y-%m-%d %H:%M:%S %Z"),
)
if contract is not None and not contract.is_empty():
contract_block = contract.render_block()
diff --git a/hermes_cli/status_auth.py b/hermes_cli/status_auth.py
index 640f305a43b..204af458789 100644
--- a/hermes_cli/status_auth.py
+++ b/hermes_cli/status_auth.py
@@ -10,6 +10,7 @@ from hermes_cli.nous_account import (
from hermes_cli.nous_subscription import get_nous_subscription_features
from tools.tool_backend_helpers import managed_nous_tools_enabled
from hermes_cli import config
+from hermes_time import safe_strftime
def _format_iso_timestamp(value) -> str:
@@ -23,7 +24,7 @@ def _format_iso_timestamp(value) -> str:
return value
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
- return parsed.astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")
+ return safe_strftime(parsed.astimezone(), "%Y-%m-%d %H:%M:%S %Z")
def _qwen_expiry(expires_at_ms) -> str:
diff --git a/hermes_time.py b/hermes_time.py
index a8cab27d478..e8ab599089a 100644
--- a/hermes_time.py
+++ b/hermes_time.py
@@ -7,6 +7,7 @@ time. Invalid timezone values log a warning and fall back — never crash.
import logging
import os
+import re
import threading
from datetime import datetime
from typing import Dict, Optional, Tuple
@@ -14,6 +15,9 @@ 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
@@ -25,6 +29,99 @@ 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":
+ try:
+ return value.tzname() or ""
+ except UnicodeEncodeError:
+ return ""
+ return replacements[directive]
+
+
+def safe_strftime(value: datetime, fmt: str) -> str:
+ """Format a datetime without leaking invalid locale surrogates.
+
+ 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()``.
+ """
+ try:
+ rendered = 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)
+
def _env_timezone() -> str:
"""``HERMES_TIMEZONE`` when it may speak for the active profile. Under the multiplexed
diff --git a/tests/agent/test_system_prompt.py b/tests/agent/test_system_prompt.py
index 51b32455809..2b30f449bd5 100644
--- a/tests/agent/test_system_prompt.py
+++ b/tests/agent/test_system_prompt.py
@@ -849,6 +849,28 @@ 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")
+ )
+ with patch("hermes_time.now", return_value=current):
+ vol = self._volatile(self._agent("20260714_090000_fresh"))
+
+ assert "Conversation started: Tuesday, July 14, 2026" in vol
+ assert "Paris �" in vol
+ vol.encode("utf-8")
+
def test_timeless_bot_chat_unaffected(self):
agent = self._agent("20200110_090000_old")
agent._bot_chat_timeless_prompt = True
diff --git a/tests/cron/test_timezone.py b/tests/cron/test_timezone.py
index 09e0b86593d..ba0ff7eef28 100644
--- a/tests/cron/test_timezone.py
+++ b/tests/cron/test_timezone.py
@@ -49,6 +49,37 @@ class TestHermesTimeNow:
+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"
+
+
+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")
+
+