diff --git a/AGENTS.md b/AGENTS.md index 32cd418..c65e4c4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -736,7 +736,13 @@ CLI, unit tests (24) + integration tests (2). bridge) and `simplex.connect_link` (show/create the forwarding bot's contact link) are the messenger seeds; `time.now`, `time.date`, `time.set_timer`, and `time.set_alarm` are the local time utilities (`compute` transport, empty - contract) — they read the host clock and schedule on `ctx.timers`; + contract) — they read the host clock and schedule on `ctx.timers`. Local time + is the top-level `timezone` config value (an IANA name such as + `America/Chicago`; `timers.local_now`/`resolve_timezone` resolve it via + `zoneinfo`), falling back to the host's own timezone when it is empty or + unknown; `TimerService` formats due/fired times in that zone too. The calendar + seeds derive "now" the same way, so a request time is parsed in the user's + zone rather than the host's; `tests/test_seed_skills.py` keeps them honest. - **Contract provenance.** Each authored body records the CODEGEN.md revision it was written against. `skill_contract_ref()` (`codegen.py`) returns diff --git a/config.example.json b/config.example.json index 06e24ea..ff12a46 100644 --- a/config.example.json +++ b/config.example.json @@ -1,8 +1,9 @@ { - "_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json.", + "_comment": "Per-machine config. config.json is gitignored. bootstrap.sh seeds config.json from this file only when config.json does not exist, and NOTHING writes config.json afterwards — only a human edits it. Pinned engine/tokenizer/GGUF/simplex-chat refs live in the committed pins.json, not here. Every machine keeps its own config.json. Top-level `timezone` is the IANA zone (e.g. America/Chicago) the agent reports local time in; empty means the host's local timezone.", "tau": 0.6, "max_reentries": 3, "creation_approval": false, + "timezone": "", "navigation": { "_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. Leaf: the softmax offers only existing skills; confirm_skill_fit then compares the winner's action to the request (phase navigate:intent, P(same) >= intent_tau) and a mismatch authors a new leaf. All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category check is deliberately permissive: with real descriptions in-scope requests score 0.9-1.0, so a borderline over-cover routes into a plausible category and the leaf guard catches it.", "intent_tau": 0.6, diff --git a/seeds/calendar/create_event/skill.py b/seeds/calendar/create_event/skill.py index 6b66b9f..fa797cb 100644 --- a/seeds/calendar/create_event/skill.py +++ b/seeds/calendar/create_event/skill.py @@ -37,6 +37,7 @@ from datetime import datetime, time, timedelta, timezone from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult +from semif_agent.timers import local_now INTEGRATION = { "service": "nextcloud_calendar", @@ -125,9 +126,10 @@ class BridgeError(Exception): """A real failure talking to the local LLM bridge.""" -def _now(): - """Current local time (aware). A test seam; the body never freezes time.""" - return datetime.now().astimezone() +def _now(ctx): + """Current time (aware) in the user's timezone: the top-level `timezone` + config value when set, else host local. A test seam; never freezes time.""" + return local_now(ctx.config) # ---- transport ---- @@ -531,7 +533,7 @@ def act(ctx, request): title = fields["title"] description = fields["description"] - now = _now() + now = _now(ctx) parsed = _parse_when(request.text, now) if answers.get("title"): diff --git a/seeds/calendar/create_event/skill.test.py b/seeds/calendar/create_event/skill.test.py index 3a016d8..fef9ea6 100644 --- a/seeds/calendar/create_event/skill.test.py +++ b/seeds/calendar/create_event/skill.test.py @@ -25,7 +25,7 @@ from semif_agent.skills import ActionContext import skill FIXED_NOW = datetime(2026, 10, 7, 10, 0, tzinfo=timezone.utc) -skill._now = lambda: FIXED_NOW +skill._now = lambda ctx: FIXED_NOW DEFAULT_LLM_REPLY = {"title": "event", "description": ""} diff --git a/seeds/calendar/next_event/skill.py b/seeds/calendar/next_event/skill.py index 6d1eeef..f56c64b 100644 --- a/seeds/calendar/next_event/skill.py +++ b/seeds/calendar/next_event/skill.py @@ -30,6 +30,7 @@ from zoneinfo import ZoneInfo from semif_agent.decisions import DecisionRequest, Option from semif_agent.skills import ActionResult +from semif_agent.timers import local_now INTEGRATION = { "service": "nextcloud_calendar", @@ -76,9 +77,10 @@ class CalDavError(Exception): """A real failure talking to the calendar service.""" -def _now(): - """Current local time (aware). A test seam; the body never freezes time.""" - return datetime.now().astimezone() +def _now(ctx): + """Current time (aware) in the user's timezone: the top-level `timezone` + config value when set, else host local. A test seam; never freezes time.""" + return local_now(ctx.config) # ---- transport ---- @@ -378,7 +380,7 @@ def act(ctx, request): decisions=decisions, ) - now = _now() + now = _now(ctx) local_tz = now.tzinfo or timezone.utc window_start = now - timedelta(days=1) window_end = now + timedelta(days=LOOKAHEAD_DAYS) diff --git a/seeds/time/date/skill.py b/seeds/time/date/skill.py index bbe4138..7be03cc 100644 --- a/seeds/time/date/skill.py +++ b/seeds/time/date/skill.py @@ -1,14 +1,14 @@ """Report today's date. -Real local compute: reads the host clock and formats the local calendar date. -No external service and no configuration. +Real local compute: reads the host clock and formats the calendar date in the +user's timezone — the top-level `timezone` config value (an IANA name) when set, +otherwise the host's local timezone. No external service. """ from __future__ import annotations -from datetime import datetime - from semif_agent.skills import ActionResult +from semif_agent.timers import local_now INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} @@ -16,6 +16,6 @@ CONTRACT = {} def act(ctx, request): - today = datetime.now().astimezone().date() + today = local_now(ctx.config).date() message = f"Today is {today.strftime('%A, %B %d, %Y')} ({today.isoformat()})." return ActionResult(action_log=f"time.date: {message}", new_state=message) diff --git a/seeds/time/now/skill.py b/seeds/time/now/skill.py index bfca32e..681eaea 100644 --- a/seeds/time/now/skill.py +++ b/seeds/time/now/skill.py @@ -1,8 +1,10 @@ """Report the current local time. -Real local compute: reads the host clock and formats it in the host's local -timezone. No external service and no configuration — the `compute` transport is -the codebase's home for a body that acts on the machine itself. +Real local compute: reads the host clock and formats it in the user's +timezone — the top-level `timezone` config value (an IANA name such as +`America/Chicago`) when set, otherwise the host's local timezone. No external +service; the `compute` transport is the codebase's home for a body that acts on +the machine itself. """ from __future__ import annotations @@ -10,6 +12,7 @@ from __future__ import annotations from datetime import datetime from semif_agent.skills import ActionResult +from semif_agent.timers import local_now INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} @@ -24,7 +27,7 @@ def _offset_text(now: datetime) -> str: def act(ctx, request): - now = datetime.now().astimezone() + now = local_now(ctx.config) zone = now.tzname() or "local" message = ( f"It is {now.strftime('%H:%M')} " diff --git a/seeds/time/set_alarm/skill.py b/seeds/time/set_alarm/skill.py index cc19c89..70a234b 100644 --- a/seeds/time/set_alarm/skill.py +++ b/seeds/time/set_alarm/skill.py @@ -1,8 +1,10 @@ """Set an alarm for a specific time of day that notifies when it goes off. Real local compute: parses a wall-clock time out of the request and schedules it -on the in-process timer service (`ctx.timers`). A time already past rolls to the -next day. When it fires, the front end that set it notifies the user. +on the in-process timer service (`ctx.timers`). The wall-clock time is read in +the user's timezone — the top-level `timezone` config value when set, otherwise +the host's local timezone. A time already past rolls to the next day. When it +fires, the front end that set it notifies the user. If no time can be parsed the body pauses and asks for one, stashing the answer in `request.meta` so the single-phase `act` re-run does not ask again. @@ -14,6 +16,7 @@ import re from datetime import datetime, time, timedelta from semif_agent.skills import ActionResult +from semif_agent.timers import local_now INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} @@ -63,7 +66,7 @@ def act(ctx, request): request.meta.pop("alarm_awaiting", None) text = request.meta.get("alarm_time_text") or request.text - now = datetime.now().astimezone() + now = local_now(ctx.config) when = _parse_time(text, now) if when is None: request.meta["alarm_awaiting"] = True diff --git a/seeds/time/set_timer/skill.py b/seeds/time/set_timer/skill.py index c3b2a0b..63e9ecc 100644 --- a/seeds/time/set_timer/skill.py +++ b/seeds/time/set_timer/skill.py @@ -3,8 +3,9 @@ Real local compute: parses a duration out of the request (digits or words) and schedules it on the in-process timer service (`ctx.timers`). When it fires, the front end that set it notifies the user — the REPL prints it, the gateway sends -it back to the originating chat, the dashboard shows it. A timer lives in the -process that set it and does not survive a restart. +it back to the originating chat, the dashboard shows it. The due time is shown +in the user's timezone (the top-level `timezone` config value, else host local). +A timer lives in the process that set it and does not survive a restart. If no duration can be parsed the body pauses and asks for one, stashing the answer in `request.meta` so the single-phase `act` re-run does not ask again. diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 4070fb8..4c8d650 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -283,7 +283,7 @@ class Scheduler: merge_seed_store(self.tree, self.seed_store, self.body_store) merge_skill_store(self.tree, self.body_store, self.registry.read()) apply_tombstones(self.tree, self.deleted) - self.timers = TimerService(trace=self.trace) + self.timers = TimerService(trace=self.trace, timezone=config.get("timezone")) self.ctx = ActionContext( engine=self.engine, config=config, timers=self.timers, admin=self ) diff --git a/semif_agent/timers.py b/semif_agent/timers.py index ac82b0a..5de9e48 100644 --- a/semif_agent/timers.py +++ b/semif_agent/timers.py @@ -19,7 +19,31 @@ import threading import time import uuid from dataclasses import dataclass, field -from datetime import datetime +from datetime import datetime, tzinfo +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + + +def resolve_timezone(config) -> tzinfo | None: + """The tzinfo named by `config["timezone"]`, or None for host local. + + An empty/absent name or an unknown zone falls back to the host's local + timezone (None), so a misconfigured value never breaks a run. + """ + name = str((config or {}).get("timezone", "") or "").strip() + if not name: + return None + try: + return ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError, KeyError): + return None + + +def local_now(config=None) -> datetime: + """Current time, aware: the configured timezone, else the host's local zone.""" + tz = resolve_timezone(config) + if tz is None: + return datetime.now().astimezone() + return datetime.now(tz) def format_duration(seconds: float) -> str: @@ -51,8 +75,12 @@ class Timer: source: str due_at: float # epoch seconds created_at: float = field(default_factory=time.time) + # tzinfo used to format the due time for the user (None = host local). + tz: tzinfo | None = None def due_datetime(self) -> datetime: + if self.tz is not None: + return datetime.fromtimestamp(self.due_at, tz=self.tz) return datetime.fromtimestamp(self.due_at).astimezone() def as_dict(self) -> dict: @@ -102,9 +130,10 @@ class TimerService: `fired()` keeps a bounded history for the dashboard. """ - def __init__(self, trace=None, history: int = 50): + def __init__(self, trace=None, history: int = 50, timezone: str | None = None): self.trace = trace self._history_limit = int(history) + self._tz = resolve_timezone({"timezone": timezone}) self._lock = threading.RLock() self._cv = threading.Condition(self._lock) self._heap: list[tuple[float, int, Timer]] = [] @@ -140,6 +169,7 @@ class TimerService: label=str(label or ""), source=str(source or ""), due_at=float(due_at), + tz=self._tz, ) with self._cv: self._seq += 1 @@ -243,8 +273,13 @@ class TimerService: except Exception: pass + def _to_local(self, ts: float) -> datetime: + if self._tz is not None: + return datetime.fromtimestamp(ts, tz=self._tz) + return datetime.fromtimestamp(ts).astimezone() + def _message(self, timer: Timer, fired_at: float) -> str: - when = datetime.fromtimestamp(fired_at).astimezone().strftime("%H:%M") + when = self._to_local(fired_at).strftime("%H:%M") if timer.kind == "alarm": body = timer.label or "Alarm" return f"Alarm: {body} — it's {when}." diff --git a/tests/test_timers.py b/tests/test_timers.py index 17b96d0..51f5594 100644 --- a/tests/test_timers.py +++ b/tests/test_timers.py @@ -94,3 +94,41 @@ def test_non_positive_duration_rejected(): raise AssertionError("expected ValueError for a non-positive duration") finally: service.stop() + + +def test_resolve_timezone_falls_back_to_host_local(): + from zoneinfo import ZoneInfo + + from semif_agent.timers import resolve_timezone + + assert resolve_timezone(None) is None + assert resolve_timezone({}) is None + assert resolve_timezone({"timezone": ""}) is None + assert resolve_timezone({"timezone": " "}) is None + assert resolve_timezone({"timezone": "Not/AZone"}) is None + assert resolve_timezone({"timezone": "America/Chicago"}) == ZoneInfo("America/Chicago") + + +def test_local_now_uses_configured_timezone(): + from semif_agent.timers import local_now + + now = local_now({"timezone": "America/Chicago"}) + assert now.tzinfo is not None + assert now.utcoffset() in (timedelta(hours=-5), timedelta(hours=-6)) + # No configured zone -> an aware host-local time, never naive. + assert local_now({}).tzinfo is not None + + +def test_timer_due_and_fired_time_use_configured_timezone(): + from zoneinfo import ZoneInfo + + service = TimerService(timezone="America/Chicago") + try: + timer = service.set_timer(3600, "1 hour") + assert timer.due_datetime().tzinfo == ZoneInfo("America/Chicago") + # 1700000000 == 2023-11-14 22:13:20 UTC == 16:13:20 in Chicago (CST). + message = service._message(timer, 1700000000) + expected = datetime.fromtimestamp(1700000000, tz=ZoneInfo("America/Chicago")).strftime("%H:%M") + assert expected in message, message + finally: + service.stop()