The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): include timezone and UTC offset in system prompt timestamp
Martin Koistinenda392043a982
diff --git a/agent/system_prompt.py b/agent/system_prompt.pyindex a61ff7668cc..e5b70c8d901 100644--- a/agent/system_prompt.py+++ b/agent/system_prompt.py@@ -769,7 +769,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)_plugin_section_blocks(_frozen_plugin_prompt_sections(agent), "after_memory"))- from hermes_time import now as _hermes_now+ from hermes_time import get_timezone as _hermes_tz, now as _hermes_nownow = _hermes_now()# Date-only (not minute-precision) so the system prompt is byte-stable# for the full day. Minute-precision changes invalidate prefix-cache KV@@ -777,7 +777,31 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)# session resume without a stored prompt). The model can still query the# exact wall-clock time via tools when it actually needs it.# Credit: @iamfoz (PR #20451).- timestamp_line = f"Conversation started: {now.strftime('%A, %B %d, %Y')}"+ #+ # Zone and UTC offset ARE included: tools that accept instants reject naive+ # datetimes and require an explicit offset, and with the bare date the model+ # has to infer EST vs EDT on its own (a coin-flip near a DST boundary, and a+ # wrong guess silently writes the record onto the wrong day). Both values+ # are constant for the whole day -- they shift only at a DST transition --+ # so the byte-stability the comment above depends on is preserved.+ # ``get_timezone()`` returns None when no timezone is configured, in which+ # case we fall back to the abbreviation of the server-local (still tz-aware)+ # time.+ _tz = _hermes_tz()+ _zone_bits = []+ _iana = getattr(_tz, "key", None)+ if _iana:+ _zone_bits.append(_iana)+ _abbrev = now.strftime("%Z")+ if _abbrev and _abbrev != _iana:+ _zone_bits.append(_abbrev)+ _offset = now.strftime("%z")+ if _offset: # '-0400' -> 'UTC-04:00'+ _zone_bits.append(f"UTC{_offset[:3]}:{_offset[3:]}")+ _zone_suffix = f" ({', '.join(_zone_bits)})" if _zone_bits else ""+ timestamp_line = (+ f"Conversation started: {now.strftime('%A, %B %d, %Y')}{_zone_suffix}"+ )if agent.pass_session_id and agent.session_id:timestamp_line += f"\nSession ID: {agent.session_id}"if agent.model:diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex 0fafb0845a9..27cc89bc2f2 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -919,7 +919,13 @@ class TestBuildSystemPrompt:"""Timestamp must be date-only (no HH:MM) so the system promptstays byte-stable for the full day. Minute precision invalidatesprefix-cache KV on every rebuild path (compression, fresh-agent- gateway turns, session resume without a stored prompt)."""+ gateway turns, session resume without a stored prompt).++ The trailing zone parenthetical -- e.g. ``(America/New_York, EDT,+ UTC-04:00)`` -- is exempt from the HH:MM check: a UTC offset is not+ time-of-day and is constant for the whole day (it shifts only at a DST+ transition), so it does not affect cache stability.+ """prompt = agent._build_system_prompt()# Find the line and strip it for inspectionfor line in prompt.splitlines():@@ -929,14 +935,43 @@ class TestBuildSystemPrompt:f"Timestamp line has time-of-day, breaks daily cache stability: {line!r}")# Must NOT contain a colon followed by two digits (HH:MM pattern)+ # in the date portion, i.e. everything before the zone suffix.import re as _re- assert not _re.search(r":\d{2}", line), (+ date_part = line.split(" (")[0]+ assert not _re.search(r":\d{2}", date_part), (f"Timestamp line has HH:MM, breaks daily cache stability: {line!r}")breakelse:assert False, "Expected a 'Conversation started:' line in the system prompt"+ def test_datetime_includes_utc_offset(self, agent):+ """Timestamp must carry an explicit UTC offset.++ Tools that accept instants (e.g. nutrition/calendar MCP servers) reject+ naive datetimes and require an offset. With a bare date the model has to+ infer EST vs EDT on its own, which is a coin-flip near a DST boundary and+ silently writes records onto the wrong day when it guesses wrong.+ """+ prompt = agent._build_system_prompt()+ import re as _re+ for line in prompt.splitlines():+ if line.startswith("Conversation started:"):+ assert _re.search(r"UTC[+-]\d{2}:\d{2}", line), (+ f"Timestamp line is missing a UTC offset: {line!r}"+ )+ break+ else:+ assert False, "Expected a 'Conversation started:' line in the system prompt"++ def test_datetime_line_is_stable_across_rebuilds(self, agent):+ """Two rebuilds within the same day must produce a byte-identical+ timestamp line, or the prefix cache is invalidated on every rebuild."""+ def _line(p):+ return next(ln for ln in p.splitlines()+ if ln.startswith("Conversation started:"))+ assert _line(agent._build_system_prompt()) == _line(agent._build_system_prompt())+def test_includes_nous_subscription_prompt(self, agent, monkeypatch):monkeypatch.setattr(run_agent, "build_nous_subscription_prompt", lambda tool_names: "NOUS SUBSCRIPTION BLOCK")prompt = agent._build_system_prompt()