From 07b0e2ff7e894af52daf86c29d4feb79110824fb Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Mon, 5 Oct 2026 05:30:15 +0000 Subject: [PATCH] add basic clock functions (timer, alarm, date, current time) --- AGENTS.md | 13 +- seeds/time/date/contract.json | 1 + seeds/time/date/manifest.json | 3 + seeds/time/date/skill.py | 21 +++ seeds/time/date/skill.test.py | 29 ++++ seeds/time/now/contract.json | 1 + seeds/time/now/manifest.json | 3 + seeds/time/now/skill.py | 33 ++++ seeds/time/now/skill.test.py | 31 ++++ seeds/time/set_alarm/contract.json | 1 + seeds/time/set_alarm/manifest.json | 3 + seeds/time/set_alarm/skill.py | 84 ++++++++++ seeds/time/set_alarm/skill.test.py | 84 ++++++++++ seeds/time/set_timer/contract.json | 1 + seeds/time/set_timer/manifest.json | 3 + seeds/time/set_timer/skill.py | 127 +++++++++++++++ seeds/time/set_timer/skill.test.py | 90 +++++++++++ semif_agent/cli.py | 20 +++ semif_agent/dashboard.py | 9 ++ semif_agent/gateway/service.py | 5 + semif_agent/scheduler.py | 12 +- semif_agent/skill.py | 2 +- semif_agent/skills.py | 6 + semif_agent/static/app.js | 37 ++++- semif_agent/static/index.html | 4 + semif_agent/timers.py | 252 +++++++++++++++++++++++++++++ tests/test_seed_skills.py | 16 +- tests/test_timers.py | 96 +++++++++++ 28 files changed, 979 insertions(+), 8 deletions(-) create mode 100644 seeds/time/date/contract.json create mode 100644 seeds/time/date/manifest.json create mode 100644 seeds/time/date/skill.py create mode 100644 seeds/time/date/skill.test.py create mode 100644 seeds/time/now/contract.json create mode 100644 seeds/time/now/manifest.json create mode 100644 seeds/time/now/skill.py create mode 100644 seeds/time/now/skill.test.py create mode 100644 seeds/time/set_alarm/contract.json create mode 100644 seeds/time/set_alarm/manifest.json create mode 100644 seeds/time/set_alarm/skill.py create mode 100644 seeds/time/set_alarm/skill.test.py create mode 100644 seeds/time/set_timer/contract.json create mode 100644 seeds/time/set_timer/manifest.json create mode 100644 seeds/time/set_timer/skill.py create mode 100644 seeds/time/set_timer/skill.test.py create mode 100644 semif_agent/timers.py create mode 100644 tests/test_timers.py diff --git a/AGENTS.md b/AGENTS.md index 33e0dbc..5e7151d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -120,6 +120,14 @@ skill.py loop: observe -> act -> observe -> assess; the body is a single answer on request.user_input; a contract variable the runner cannot satisfy pauses BEFORE act (pre_act), collects it, and re-runs the full path +timers.py in-process timer/alarm service (TimerService) owned by the + scheduler and exposed on ActionContext.timers: a single + background thread fires scheduled timers on the host clock, + records a `timer_fired` trace event, and queues the + notification for the front end that set it (the REPL prints it, + the gateway routes it to the originating chat, the dashboard + shows pending/fired). Real local compute (`compute` transport), + per-process, and deliberately NOT persisted across restarts. engine.py SemIfEngine -> semif_phase1.llamacpp_backend (lazy import) codegen.py CodegenClient (OpenAI-compatible) writes real-integration skill bodies against CODEGEN.md (real actions via stdlib transports, @@ -594,7 +602,10 @@ CLI, unit tests (24) + integration tests (2). `calendar.next_event` is the read counterpart (Nextcloud CalDAV, recurring events expanded server-side); `simplex.next_message` (read via the forwarding bridge) and `simplex.connect_link` (show/create the forwarding bot's contact - link) are the messenger seeds; `tests/test_seed_skills.py` keeps them honest. + 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`; + `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 `{"ref", "dirty"}`: `ref` is the short git commit sha the contract was read diff --git a/seeds/time/date/contract.json b/seeds/time/date/contract.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/seeds/time/date/contract.json @@ -0,0 +1 @@ +{} diff --git a/seeds/time/date/manifest.json b/seeds/time/date/manifest.json new file mode 100644 index 0000000..03b0498 --- /dev/null +++ b/seeds/time/date/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Report today's date." +} diff --git a/seeds/time/date/skill.py b/seeds/time/date/skill.py new file mode 100644 index 0000000..bbe4138 --- /dev/null +++ b/seeds/time/date/skill.py @@ -0,0 +1,21 @@ +"""Report today's date. + +Real local compute: reads the host clock and formats the local calendar date. +No external service and no configuration. +""" + +from __future__ import annotations + +from datetime import datetime + +from semif_agent.skills import ActionResult + +INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} + +CONTRACT = {} + + +def act(ctx, request): + today = datetime.now().astimezone().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/date/skill.test.py b/seeds/time/date/skill.test.py new file mode 100644 index 0000000..43868aa --- /dev/null +++ b/seeds/time/date/skill.test.py @@ -0,0 +1,29 @@ +"""Hermetic mechanics test for time.date. + +Run from this folder: `python skill.test.py`. No external network, no config. +""" + +import sys + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +def main(): + ctx = ActionContext(engine=None, config={}) + action = skill.act(ctx, Request("what is today's date?")) + assert action.new_state, "act must report the date" + assert "Today is" in action.action_log, action.action_log + assert action.needs_input is None + print(action.action_log) + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/seeds/time/now/contract.json b/seeds/time/now/contract.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/seeds/time/now/contract.json @@ -0,0 +1 @@ +{} diff --git a/seeds/time/now/manifest.json b/seeds/time/now/manifest.json new file mode 100644 index 0000000..7a9194b --- /dev/null +++ b/seeds/time/now/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Report the current local time of day." +} diff --git a/seeds/time/now/skill.py b/seeds/time/now/skill.py new file mode 100644 index 0000000..bfca32e --- /dev/null +++ b/seeds/time/now/skill.py @@ -0,0 +1,33 @@ +"""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. +""" + +from __future__ import annotations + +from datetime import datetime + +from semif_agent.skills import ActionResult + +INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} + +CONTRACT = {} + + +def _offset_text(now: datetime) -> str: + offset = now.strftime("%z") + if not offset: + return "" + return f" UTC{offset[:3]}:{offset[3:]}" + + +def act(ctx, request): + now = datetime.now().astimezone() + zone = now.tzname() or "local" + message = ( + f"It is {now.strftime('%H:%M')} " + f"({now.strftime('%I:%M %p').lstrip('0')} {zone}{_offset_text(now)})." + ) + return ActionResult(action_log=f"time.now: {message}", new_state=message) diff --git a/seeds/time/now/skill.test.py b/seeds/time/now/skill.test.py new file mode 100644 index 0000000..e13f95b --- /dev/null +++ b/seeds/time/now/skill.test.py @@ -0,0 +1,31 @@ +"""Hermetic mechanics test for time.now. + +Run from this folder: `python skill.test.py`. No external network, no config. +This proves the body reads the host clock and reports a real local time; it +does NOT prove anything about the host's timezone correctness. +""" + +import sys + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +def main(): + ctx = ActionContext(engine=None, config={}) + action = skill.act(ctx, Request("what time is it?")) + assert action.new_state, "act must report the time" + assert "It is" in action.action_log, action.action_log + assert action.needs_input is None + print(action.action_log) + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/seeds/time/set_alarm/contract.json b/seeds/time/set_alarm/contract.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/seeds/time/set_alarm/contract.json @@ -0,0 +1 @@ +{} diff --git a/seeds/time/set_alarm/manifest.json b/seeds/time/set_alarm/manifest.json new file mode 100644 index 0000000..77285e6 --- /dev/null +++ b/seeds/time/set_alarm/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Set an alarm for a specific time of day that notifies when it goes off." +} diff --git a/seeds/time/set_alarm/skill.py b/seeds/time/set_alarm/skill.py new file mode 100644 index 0000000..cc19c89 --- /dev/null +++ b/seeds/time/set_alarm/skill.py @@ -0,0 +1,84 @@ +"""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. + +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. +""" + +from __future__ import annotations + +import re +from datetime import datetime, time, timedelta + +from semif_agent.skills import ActionResult + +INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} + +CONTRACT = {} + + +def _parse_time(text, now): + """The next datetime matching a wall-clock time in `text`, or None.""" + text = text or "" + parsed = None + if re.search(r"\bnoon\b", text, re.I): + parsed = time(12, 0) + elif re.search(r"\bmidnight\b", text, re.I): + parsed = time(0, 0) + else: + match = re.search(r"\b(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?\b", text, re.I) + if match: + hour = int(match.group(1)) % 12 + minute = int(match.group(2) or 0) + if match.group(3).lower() == "p": + hour += 12 + if hour < 24 and minute < 60: + parsed = time(hour, minute) + else: + match = re.search(r"\b(\d{1,2}):(\d{2})\b", text) + if match: + hour, minute = int(match.group(1)), int(match.group(2)) + if hour < 24 and minute < 60: + parsed = time(hour, minute) + else: + # A bare hour is only accepted when unambiguous (24-hour). + match = re.search(r"\bat\s+(\d{1,2})\b", text, re.I) + if match and 13 <= int(match.group(1)) < 24: + parsed = time(int(match.group(1)), 0) + if parsed is None: + return None + candidate = datetime.combine(now.date(), parsed, tzinfo=now.tzinfo) + if candidate <= now: + candidate += timedelta(days=1) + return candidate + + +def act(ctx, request): + if request.user_input is not None and request.meta.get("alarm_awaiting"): + if request.user_input.strip(): + request.meta["alarm_time_text"] = request.user_input.strip() + request.meta.pop("alarm_awaiting", None) + + text = request.meta.get("alarm_time_text") or request.text + now = datetime.now().astimezone() + when = _parse_time(text, now) + if when is None: + request.meta["alarm_awaiting"] = True + return ActionResult( + action_log="time.set_alarm: waiting for a time", + new_state=request.text, + needs_input="What time should the alarm go off? (e.g. '5pm')", + ) + if ctx.timers is None: + return ActionResult( + action_log="time.set_alarm: no timer service is available in this front end", + new_state=request.text, + ) + + label = when.strftime("%H:%M") + ctx.timers.set_alarm(when, label, run_id=request.id, source=request.source) + message = f"Alarm set for {when.strftime('%H:%M')} on {when.strftime('%A')}." + return ActionResult(action_log=f"time.set_alarm: {message}", new_state=message) diff --git a/seeds/time/set_alarm/skill.test.py b/seeds/time/set_alarm/skill.test.py new file mode 100644 index 0000000..0e15d65 --- /dev/null +++ b/seeds/time/set_alarm/skill.test.py @@ -0,0 +1,84 @@ +"""Hermetic mechanics test for time.set_alarm. + +Run from this folder: `python skill.test.py`. No external network, no real +sleeping: a fake timer service records what the body schedules. This proves the +body parses wall-clock times (am/pm, 24-hour, noon/midnight), rolls a past time +to the next day, and pauses for input when no time is present. +""" + +import sys +from datetime import datetime, timedelta +from types import SimpleNamespace + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeTimers: + def __init__(self): + self.alarms = [] + + def set_alarm(self, at, label, run_id="", source=""): + self.alarms.append((at, label)) + return SimpleNamespace(id="a1", due_at=at.timestamp()) + + +def ctx_with_timers(): + timers = FakeTimers() + return ActionContext(engine=None, config={}, timers=timers), timers + + +def main(): + now = datetime.now().astimezone() + + ctx, timers = ctx_with_timers() + action = skill.act(ctx, Request("set an alarm for 5pm")) + assert action.needs_input is None, action.needs_input + assert len(timers.alarms) == 1, timers.alarms + at, label = timers.alarms[0] + assert (at.hour, at.minute) == (17, 0), at + assert label == "17:00" + assert at > now, "an alarm must be in the future" + assert at <= now + timedelta(days=1) + print(action.action_log) + + ctx, timers = ctx_with_timers() + skill.act(ctx, Request("set an alarm for 17:30")) + assert timers.alarms[0][0].strftime("%H:%M") == "17:30", timers.alarms + + ctx, timers = ctx_with_timers() + skill.act(ctx, Request("wake me at noon")) + assert timers.alarms[0][0].strftime("%H:%M") == "12:00", timers.alarms + + ctx, timers = ctx_with_timers() + skill.act(ctx, Request("alarm at midnight")) + assert timers.alarms[0][0].strftime("%H:%M") == "00:00", timers.alarms + + # An unparseable request pauses, then the answer is used on the re-run. + ctx, timers = ctx_with_timers() + request = Request("set an alarm") + action = skill.act(ctx, request) + assert action.needs_input, "an alarm with no time must ask for one" + assert timers.alarms == [] + request.user_input = "6:15am" + action = skill.act(ctx, request) + assert action.needs_input is None + assert timers.alarms[0][0].strftime("%H:%M") == "06:15", timers.alarms + print(action.action_log) + + # No timer service fails honestly. + ctx = ActionContext(engine=None, config={}, timers=None) + action = skill.act(ctx, Request("set an alarm for 5pm")) + assert "no timer service" in action.action_log, action.action_log + + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/seeds/time/set_timer/contract.json b/seeds/time/set_timer/contract.json new file mode 100644 index 0000000..0967ef4 --- /dev/null +++ b/seeds/time/set_timer/contract.json @@ -0,0 +1 @@ +{} diff --git a/seeds/time/set_timer/manifest.json b/seeds/time/set_timer/manifest.json new file mode 100644 index 0000000..638af60 --- /dev/null +++ b/seeds/time/set_timer/manifest.json @@ -0,0 +1,3 @@ +{ + "description": "Set a countdown timer that notifies when it finishes." +} diff --git a/seeds/time/set_timer/skill.py b/seeds/time/set_timer/skill.py new file mode 100644 index 0000000..c3b2a0b --- /dev/null +++ b/seeds/time/set_timer/skill.py @@ -0,0 +1,127 @@ +"""Set a countdown timer that notifies the user when it finishes. + +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. + +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. +""" + +from __future__ import annotations + +import re + +from semif_agent.skills import ActionResult +from semif_agent.timers import format_duration + +INTEGRATION = {"service": "local_clock", "transport": "compute", "config_vars": []} + +CONTRACT = {} + +_DURATION_WORDS = { + "a": 1, + "an": 1, + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, + "ten": 10, + "eleven": 11, + "twelve": 12, + "fifteen": 15, + "twenty": 20, + "thirty": 30, + "forty": 40, + "fortyfive": 45, + "sixty": 60, + "ninety": 90, +} + +_UNIT_SECONDS = { + "second": 1, + "seconds": 1, + "sec": 1, + "secs": 1, + "s": 1, + "minute": 60, + "minutes": 60, + "min": 60, + "mins": 60, + "m": 60, + "hour": 3600, + "hours": 3600, + "hr": 3600, + "hrs": 3600, + "h": 3600, +} + +_DIGIT_DURATION = re.compile( + r"\b(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b", + re.I, +) +_WORD_DURATION = re.compile( + r"\b(" + "|".join(sorted(_DURATION_WORDS, key=len, reverse=True)) + r")\s+" + r"(seconds?|secs?|minutes?|mins?|hours?|hrs?)\b", + re.I, +) + + +def _parse_duration(text): + """Seconds for a duration phrase, or None when none is present.""" + text = text or "" + if re.search(r"\bhalf\s+an?\s+hour\b", text, re.I): + return 1800 + if re.search(r"\bquarter\s+(?:of\s+)?an?\s+hour\b", text, re.I): + return 900 + if re.search(r"\ba\s+couple\s+of\s+(?:minutes?|mins?)\b", text, re.I): + return 120 + if re.search(r"\ba\s+few\s+(?:minutes?|mins?)\b", text, re.I): + return 180 + match = _DIGIT_DURATION.search(text) + if match: + unit = _UNIT_SECONDS.get(match.group(2).lower()) + if unit: + return int(round(float(match.group(1)) * unit)) + match = _WORD_DURATION.search(text) + if match: + value = _DURATION_WORDS.get(match.group(1).lower()) + unit = _UNIT_SECONDS.get(match.group(2).lower()) + if value and unit: + return value * unit + return None + + +def act(ctx, request): + if request.user_input is not None and request.meta.get("timer_awaiting"): + if request.user_input.strip(): + request.meta["timer_duration_text"] = request.user_input.strip() + request.meta.pop("timer_awaiting", None) + + text = request.meta.get("timer_duration_text") or request.text + seconds = _parse_duration(text) + if seconds is None: + request.meta["timer_awaiting"] = True + return ActionResult( + action_log="time.set_timer: waiting for a duration", + new_state=request.text, + needs_input="How long should the timer run? (e.g. '5 minutes')", + ) + if ctx.timers is None: + return ActionResult( + action_log="time.set_timer: no timer service is available in this front end", + new_state=request.text, + ) + + label = format_duration(seconds) + timer = ctx.timers.set_timer(seconds, label, run_id=request.id, source=request.source) + due = timer.due_datetime().strftime("%H:%M") + message = f"Timer set for {label}; it will fire at {due}." + return ActionResult(action_log=f"time.set_timer: {message}", new_state=message) diff --git a/seeds/time/set_timer/skill.test.py b/seeds/time/set_timer/skill.test.py new file mode 100644 index 0000000..c636737 --- /dev/null +++ b/seeds/time/set_timer/skill.test.py @@ -0,0 +1,90 @@ +"""Hermetic mechanics test for time.set_timer. + +Run from this folder: `python skill.test.py`. No external network, no real +sleeping: a fake timer service records what the body schedules. This proves the +body parses durations (digits and words) and schedules the right number of +seconds, and that an unparseable request pauses for input; it does NOT prove +the in-process timer actually fires (tests/test_timers.py covers the service). +""" + +import sys +import time +from datetime import datetime +from types import SimpleNamespace + +from semif_agent.decisions import Request +from semif_agent.skills import ActionContext + +import skill + + +class FakeTimer: + def __init__(self, seconds): + self.due_at = time.time() + seconds + + def due_datetime(self): + return datetime.fromtimestamp(self.due_at).astimezone() + + +class FakeTimers: + def __init__(self): + self.timers = [] + + def set_timer(self, seconds, label, run_id="", source=""): + self.timers.append((seconds, label)) + return FakeTimer(seconds) + + +def ctx_with_timers(): + timers = FakeTimers() + return ActionContext(engine=None, config={}, timers=timers), timers + + +def main(): + ctx, timers = ctx_with_timers() + action = skill.act(ctx, Request("please set a timer for five minutes")) + assert action.needs_input is None, action.needs_input + assert timers.timers == [(300, "5 minutes")], timers.timers + assert "300" not in action.action_log and "5 minutes" in action.action_log + print(action.action_log) + + ctx, timers = ctx_with_timers() + action = skill.act(ctx, Request("set a timer for 90 seconds")) + assert timers.timers == [(90, "1 minute 30 seconds")], timers.timers + print(action.action_log) + + ctx, timers = ctx_with_timers() + skill.act(ctx, Request("timer for 1.5 hours")) + assert timers.timers == [(5400, "1 hour 30 minutes")], timers.timers + + ctx, timers = ctx_with_timers() + skill.act(ctx, Request("set a timer for half an hour")) + assert timers.timers == [(1800, "30 minutes")], timers.timers + + # An unparseable request pauses, then the answer is used on the re-run. + ctx, timers = ctx_with_timers() + request = Request("set a timer") + action = skill.act(ctx, request) + assert action.needs_input, "a timer with no duration must ask for one" + assert timers.timers == [] + request.user_input = "ten minutes" + action = skill.act(ctx, request) + assert action.needs_input is None + assert timers.timers == [(600, "10 minutes")], timers.timers + print(action.action_log) + + # No timer service (e.g. a front end without one) fails honestly. + ctx = ActionContext(engine=None, config={}, timers=None) + action = skill.act(ctx, Request("set a timer for 5 minutes")) + assert action.needs_input is None + assert "no timer service" in action.action_log, action.action_log + + print("ok") + + +if __name__ == "__main__": + try: + main() + except AssertionError as exc: + print(f"FAILED: {exc}") + sys.exit(1) diff --git a/semif_agent/cli.py b/semif_agent/cli.py index ff735f9..74472f7 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -16,6 +16,8 @@ import argparse import json import os import sys +import threading +import time from pathlib import Path from .dream import dream as run_dream @@ -418,8 +420,26 @@ def _fatal_exit(scheduler: Scheduler) -> int | None: return 1 +def _start_timer_printer(scheduler: Scheduler) -> None: + """Print fired timers/alarms while the REPL is blocked on `input()`. + + A background daemon thread polls the scheduler's timer service and prints + each fired notification, so a timer set during a session is delivered even + when the prompt is idle. Timers are in-process: they die with this process. + """ + + def loop() -> None: + while True: + time.sleep(0.5) + for fired in scheduler.timers.drain(): + print(f"\n[timer] {fired.message}") + + threading.Thread(target=loop, name="timer-printer", daemon=True).start() + + def repl(scheduler: Scheduler, config: dict) -> int: scheduler.defer_questions = True + _start_timer_printer(scheduler) print(try_warm(scheduler)) print( "type a request, or one of: busy | idle | status | skills | dream | " diff --git a/semif_agent/dashboard.py b/semif_agent/dashboard.py index a64eb6c..1536055 100644 --- a/semif_agent/dashboard.py +++ b/semif_agent/dashboard.py @@ -233,6 +233,15 @@ class DashboardHandler(BaseHTTPRequestHandler): if path == "/api/approvals": self._send(200, {"approvals": self.scheduler.pending_approvals()}) return + if path == "/api/timers": + self._send( + 200, + { + "pending": self.scheduler.timers.pending(), + "fired": self.scheduler.timers.fired(), + }, + ) + return self._send_error(404, "no such endpoint") def do_POST(self): diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index a1d191b..3051e8d 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -242,6 +242,11 @@ class GatewayService: ), ) + for fired in self.scheduler.timers.drain(): + chat = self._owner_of(fired.run_id) or origin or self.home_channel + if chat: + self._reply(chat, fired.message) + # ---- scheduler requeue hook (called under the scheduler lock) ---- def on_request_requeued(self, parent_id: str, child_id: str) -> None: diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 765e6da..3bb9a79 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -37,6 +37,7 @@ from .log import DecisionLog from .provider import ProviderError from .queue import UrgencyQueue from .skill import SkillRunner +from .timers import TimerService from .skills import ( CANNED_CATEGORIES, RESPONSE_FALLBACK, @@ -262,7 +263,8 @@ class Scheduler: merge_registry(self.tree, self.registry.read()) merge_seed_store(self.tree, self.seed_store, self.body_store) merge_skill_store(self.tree, self.body_store, self.registry.read()) - self.ctx = ActionContext(engine=self.engine, config=config) + self.timers = TimerService(trace=self.trace) + self.ctx = ActionContext(engine=self.engine, config=config, timers=self.timers) self.runner = SkillRunner( self.ctx, self.log, store=self.body_store, tau=self.tau ) @@ -1826,6 +1828,14 @@ class Scheduler: lines.append(f"queue: {len(self.queue)} pending") for weight, request in self.queue.items(): lines.append(f" {request.id} w={weight:.2f} {request.text[:60]}") + pending_timers = self.timers.pending() + if pending_timers: + lines.append(f"timers: {len(pending_timers)} scheduled") + for timer in pending_timers: + lines.append( + f" {timer['kind']} {timer['id']} due {timer['due_at_local'][:16]} " + f"({timer['label']})" + ) return "\n".join(lines) diff --git a/semif_agent/skill.py b/semif_agent/skill.py index a0d743e..c7e8911 100644 --- a/semif_agent/skill.py +++ b/semif_agent/skill.py @@ -118,7 +118,7 @@ class SkillRunner: merged = {**self.ctx.config} merged.update(skill.config or {}) merged.update(answered) - return ActionContext(engine=self.ctx.engine, config=merged) + return ActionContext(engine=self.ctx.engine, config=merged, timers=self.ctx.timers) def _unresolved(self, skill: Skill, request: Request) -> list[str]: if not skill.contract: diff --git a/semif_agent/skills.py b/semif_agent/skills.py index b3875a9..c545ab9 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -24,6 +24,7 @@ from .decisions import DecisionRequest, Option, Request from .engine import SemIfEngine from .llm import LLMClient from .log import DecisionLog +from .timers import TimerService from .trace import TraceLog @@ -41,6 +42,7 @@ class ActionResult: class ActionContext: engine: SemIfEngine config: dict + timers: TimerService | None = None def _noop_act(ctx: ActionContext, request: Request) -> ActionResult: @@ -552,6 +554,10 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = { "SimpleX messaging: reading incoming messages, sending messages to " "contacts, and showing the user's contact link." ), + "time": ( + "Time and date utilities: telling the current time or date, setting " + "countdown timers, and setting alarms." + ), } diff --git a/semif_agent/static/app.js b/semif_agent/static/app.js index fbfd456..1412fc6 100644 --- a/semif_agent/static/app.js +++ b/semif_agent/static/app.js @@ -7,6 +7,7 @@ const state = { tree: { categories: {} }, status: { current: null, pending: null, queue: [], tau: 0.6 }, dream: {}, + timers: { pending: [], fired: [] }, selectedRunId: null, selectedDecisionId: null, phaseFilter: "", @@ -23,16 +24,18 @@ async function getJSON(url, opts) { } async function refreshAll() { - const [trace, tree, status, dream] = await Promise.all([ + const [trace, tree, status, dream, timers] = await Promise.all([ getJSON("/api/trace"), getJSON("/api/tree"), getJSON("/api/status"), getJSON("/api/dream"), + getJSON("/api/timers"), ]); state.runs = trace.runs; state.tree = tree; state.status = status; state.dream = dream; + state.timers = timers; if (state.selectedRunId && !state.runs.some((r) => r.run_id === state.selectedRunId)) { state.selectedRunId = null; state.selectedDecisionId = null; @@ -159,6 +162,8 @@ function eventRow(evt) { div.textContent = `answered: ${evt.text || ""}`; } else if (evt.kind === "pending_abandoned") { div.textContent = "pending input abandoned"; + } else if (evt.kind === "timer_fired") { + div.textContent = `${evt.timer_kind} fired: ${evt.label}`; } return div; } @@ -499,6 +504,9 @@ function eventNode(evt) { body.textContent = `answered: ${evt.text || ""}`; } else if (evt.kind === "pending_abandoned") { body.textContent = "pending input abandoned"; + } else if (evt.kind === "timer_fired") { + node.classList.add("ok"); + body.textContent = `${evt.timer_kind} fired: ${evt.label}`; } else { body.textContent = evt.summary || evt.text || ""; } @@ -665,6 +673,32 @@ function renderTree() { /* ---------------- status / dream ---------------- */ +function renderTimers() { + const el = $("#timers"); + el.innerHTML = ""; + const pending = state.timers.pending || []; + const fired = state.timers.fired || []; + if (!pending.length && !fired.length) { + const empty = document.createElement("div"); + empty.className = "muted"; + empty.textContent = "no timers (in-process; not kept across restarts)"; + el.appendChild(empty); + return; + } + for (const t of pending) { + const row = document.createElement("div"); + row.className = "pending-line"; + row.textContent = `⏳ ${t.kind} ${t.label} → ${t.due_at_local.slice(0, 16).replace("T", " ")}`; + el.appendChild(row); + } + for (const f of fired.slice(-5).reverse()) { + const row = document.createElement("div"); + row.className = "pending-line"; + row.textContent = `⏰ ${f.message}`; + el.appendChild(row); + } +} + function renderStatus() { const el = $("#status"); el.innerHTML = ""; @@ -951,6 +985,7 @@ function render() { renderFlow(); renderInspector(); renderTree(); + renderTimers(); renderStatus(); } diff --git a/semif_agent/static/index.html b/semif_agent/static/index.html index bf6f922..b1afd41 100644 --- a/semif_agent/static/index.html +++ b/semif_agent/static/index.html @@ -56,6 +56,10 @@
+
+

Timers

+
+

Skill tree

diff --git a/semif_agent/timers.py b/semif_agent/timers.py new file mode 100644 index 0000000..ac82b0a --- /dev/null +++ b/semif_agent/timers.py @@ -0,0 +1,252 @@ +"""In-process timer and alarm service. + +A skill body schedules a timer or alarm through `ctx.timers`. One background +daemon thread wakes at the earliest due time, records a `timer_fired` trace +event, and exposes the fired timer so a front end can notify the user (the REPL +prints it, the gateway routes it to the originating chat, the dashboard shows +it). Timers live in the process that set them and do **not** survive a restart +(persistence is future work) — so the agent never claims a timer outlived a +shutdown it did not. + +This is real local compute, not a simulation: the thread fires on the host +clock and the notification carries the real due/fired times. +""" + +from __future__ import annotations + +import heapq +import threading +import time +import uuid +from dataclasses import dataclass, field +from datetime import datetime + + +def format_duration(seconds: float) -> str: + """Human text for a duration, e.g. 300 -> '5 minutes', 5400 -> '1 hour 30 minutes'.""" + total = int(round(float(seconds))) + if total < 60: + return f"{total} second" + ("s" if total != 1 else "") + minutes, secs = divmod(total, 60) + if minutes < 60: + text = f"{minutes} minute" + ("s" if minutes != 1 else "") + if secs: + text += f" {secs} second" + ("s" if secs != 1 else "") + return text + hours, minutes = divmod(minutes, 60) + text = f"{hours} hour" + ("s" if hours != 1 else "") + if minutes: + text += f" {minutes} minute" + ("s" if minutes != 1 else "") + return text + + +@dataclass +class Timer: + """One scheduled timer or alarm.""" + + id: str + run_id: str + kind: str # "timer" | "alarm" + label: str + source: str + due_at: float # epoch seconds + created_at: float = field(default_factory=time.time) + + def due_datetime(self) -> datetime: + return datetime.fromtimestamp(self.due_at).astimezone() + + def as_dict(self) -> dict: + return { + "id": self.id, + "run_id": self.run_id, + "kind": self.kind, + "label": self.label, + "source": self.source, + "due_at": self.due_at, + "due_at_local": self.due_datetime().isoformat(), + "created_at": self.created_at, + } + + +@dataclass +class FiredTimer: + """A timer that has fired; the notification a front end delivers.""" + + id: str + run_id: str + kind: str + label: str + source: str + due_at: float + fired_at: float + message: str + + def as_dict(self) -> dict: + return { + "id": self.id, + "run_id": self.run_id, + "kind": self.kind, + "label": self.label, + "source": self.source, + "due_at": self.due_at, + "fired_at": self.fired_at, + "message": self.message, + } + + +class TimerService: + """Owns scheduled timers/alarms and the single firing thread. + + Thread-safe: bodies schedule from the scheduler thread while the firing + thread delivers. `drain()` hands fired timers to the active front end once; + `fired()` keeps a bounded history for the dashboard. + """ + + def __init__(self, trace=None, history: int = 50): + self.trace = trace + self._history_limit = int(history) + self._lock = threading.RLock() + self._cv = threading.Condition(self._lock) + self._heap: list[tuple[float, int, Timer]] = [] + self._seq = 0 + self._timers: dict[str, Timer] = {} + self._fired: list[FiredTimer] = [] + self._undrained: list[FiredTimer] = [] + self._thread: threading.Thread | None = None + self._stop = False + + # ---- scheduling ---- + + def set_timer(self, seconds: float, label: str, run_id: str = "", source: str = "") -> Timer: + """Schedule a countdown timer that fires `seconds` from now.""" + seconds = float(seconds) + if seconds <= 0: + raise ValueError("timer duration must be positive") + return self._schedule("timer", time.time() + seconds, label, run_id, source) + + def set_alarm(self, at: datetime, label: str, run_id: str = "", source: str = "") -> Timer: + """Schedule an alarm for a wall-clock moment. + + A naive `at` is interpreted in the host's local timezone; an aware one is + converted to epoch directly. + """ + return self._schedule("alarm", at.timestamp(), label, run_id, source) + + def _schedule(self, kind: str, due_at: float, label: str, run_id: str, source: str) -> Timer: + timer = Timer( + id=uuid.uuid4().hex[:12], + run_id=str(run_id or ""), + kind=kind, + label=str(label or ""), + source=str(source or ""), + due_at=float(due_at), + ) + with self._cv: + self._seq += 1 + heapq.heappush(self._heap, (timer.due_at, self._seq, timer)) + self._timers[timer.id] = timer + self._ensure_thread() + self._cv.notify_all() + return timer + + def cancel(self, timer_id: str) -> bool: + """Cancel a scheduled timer. Returns False when it already fired/gone.""" + with self._lock: + return self._timers.pop(timer_id, None) is not None + + # ---- inspection ---- + + def pending(self) -> list[dict]: + with self._lock: + timers = sorted(self._timers.values(), key=lambda t: t.due_at) + return [t.as_dict() for t in timers] + + def fired(self) -> list[dict]: + """Bounded history of fired timers, oldest first.""" + with self._lock: + return [f.as_dict() for f in self._fired] + + def drain(self) -> list[FiredTimer]: + """Pop and return timers fired since the last drain (for push front ends).""" + with self._lock: + fired = self._undrained + self._undrained = [] + return fired + + def stop(self) -> None: + """Stop the firing thread (does not cancel scheduled timers).""" + with self._cv: + self._stop = True + self._cv.notify_all() + thread = self._thread + if thread is not None: + thread.join(timeout=2.0) + + # ---- firing thread ---- + + def _ensure_thread(self) -> None: + if self._thread is None or not self._thread.is_alive(): + self._stop = False + self._thread = threading.Thread(target=self._run, name="timers", daemon=True) + self._thread.start() + + def _run(self) -> None: + while True: + with self._cv: + if self._stop: + return + # Drop cancelled timers from the head of the heap. + while self._heap and self._heap[0][2].id not in self._timers: + heapq.heappop(self._heap) + if not self._heap: + self._cv.wait() + continue + due_at, _seq, timer = self._heap[0] + remaining = due_at - time.time() + if remaining > 0: + self._cv.wait(timeout=remaining) + continue + heapq.heappop(self._heap) + if self._timers.pop(timer.id, None) is None: + continue + self._fire(timer) + + def _fire(self, timer: Timer) -> None: + fired_at = time.time() + fired = FiredTimer( + id=timer.id, + run_id=timer.run_id, + kind=timer.kind, + label=timer.label, + source=timer.source, + due_at=timer.due_at, + fired_at=fired_at, + message=self._message(timer, fired_at), + ) + with self._lock: + self._fired.append(fired) + if len(self._fired) > self._history_limit: + self._fired = self._fired[-self._history_limit:] + self._undrained.append(fired) + if self.trace is not None: + try: + self.trace.append( + "timer_fired", + timer.run_id, + timer_id=timer.id, + timer_kind=timer.kind, + label=timer.label, + source=timer.source, + due_at=timer.due_at, + fired_at=fired_at, + ) + except Exception: + pass + + def _message(self, timer: Timer, fired_at: float) -> str: + when = datetime.fromtimestamp(fired_at).astimezone().strftime("%H:%M") + if timer.kind == "alarm": + body = timer.label or "Alarm" + return f"Alarm: {body} — it's {when}." + body = timer.label or "Timer" + return f"Timer finished: {body} ({when})." diff --git a/tests/test_seed_skills.py b/tests/test_seed_skills.py index bb0b9cb..b35ddc7 100644 --- a/tests/test_seed_skills.py +++ b/tests/test_seed_skills.py @@ -34,6 +34,10 @@ def test_expected_seeds_exist(): assert "calendar.create_event" in ids assert "simplex.next_message" in ids assert "simplex.connect_link" in ids + assert "time.now" in ids + assert "time.date" in ids + assert "time.set_timer" in ids + assert "time.set_alarm" in ids @pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) @@ -49,14 +53,18 @@ def test_seed_declares_a_real_integration(seed): def test_seed_contract_is_flat_and_covered_by_declaration(seed): code = (seed / "skill.py").read_text() contract = parse_contract(code) - assert contract, "the seed must declare a CONTRACT constant" - for name, description in contract.items(): - assert name.islower() and " " not in name, name - assert isinstance(description, str) and description.strip() integration = parse_integration(code) assert set(integration["config_vars"]) == set(contract) mirror = json.loads((seed / "contract.json").read_text()) assert mirror == contract, "contract.json must mirror the CONTRACT constant" + if integration["transport"] == "compute": + # A local compute skill acts on the machine itself and needs no + # configuration; an empty contract is legitimate. + return + assert contract, "an external-integration seed must declare a CONTRACT constant" + for name, description in contract.items(): + assert name.islower() and " " not in name, name + assert isinstance(description, str) and description.strip() @pytest.mark.parametrize("seed", SEED_DIRS, ids=[seed_id(s) for s in SEED_DIRS]) diff --git a/tests/test_timers.py b/tests/test_timers.py new file mode 100644 index 0000000..17b96d0 --- /dev/null +++ b/tests/test_timers.py @@ -0,0 +1,96 @@ +"""Pure-stdlib tests for the in-process timer/alarm service. + +The service is real local compute: a background thread fires on the host clock. +These tests use sub-second durations so they stay fast, and they assert the +mechanics (fire, drain, cancel, trace, honest message) rather than any external +service. Skill bodies that schedule timers are covered by the seed tests. +""" + +import time +from datetime import datetime, timedelta, timezone + +from semif_agent.timers import TimerService, format_duration +from semif_agent.trace import TraceLog + + +def wait_for(predicate, timeout=3.0): + deadline = time.time() + timeout + while time.time() < deadline: + if predicate(): + return True + time.sleep(0.02) + return predicate() + + +def test_format_duration(): + assert format_duration(1) == "1 second" + assert format_duration(30) == "30 seconds" + assert format_duration(60) == "1 minute" + assert format_duration(90) == "1 minute 30 seconds" + assert format_duration(3600) == "1 hour" + assert format_duration(5400) == "1 hour 30 minutes" + + +def test_timer_fires_and_drains_once(tmp_path): + trace = TraceLog(str(tmp_path / "runs.jsonl")) + service = TimerService(trace=trace) + try: + timer = service.set_timer(0.1, "0.1 seconds", run_id="r1", source="typed") + assert [t["id"] for t in service.pending()] == [timer.id] + + assert wait_for(lambda: service.fired()), "the timer must fire" + fired = service.drain() + assert len(fired) == 1 + assert fired[0].run_id == "r1" + assert fired[0].kind == "timer" + assert "0.1 seconds" in fired[0].message + + assert service.drain() == [], "drain is one-shot" + assert service.pending() == [] + + events = [e for e in trace.read() if e["kind"] == "timer_fired"] + assert events, "firing must be traced" + assert events[0]["timer_id"] == timer.id + assert events[0]["timer_kind"] == "timer" + assert events[0]["run_id"] == "r1" + finally: + service.stop() + + +def test_alarm_fires(): + service = TimerService() + try: + at = datetime.now(timezone.utc) + timedelta(seconds=0.1) + service.set_alarm(at, "5:00", run_id="r2") + assert wait_for(lambda: service.fired()), "the alarm must fire" + fired = service.fired() + assert fired[0]["kind"] == "alarm" + assert "Alarm" in fired[0]["message"] + finally: + service.stop() + + +def test_cancel_prevents_firing(): + service = TimerService() + try: + timer = service.set_timer(0.2, "cancel me") + assert service.cancel(timer.id) is True + assert service.cancel(timer.id) is False + time.sleep(0.3) + assert service.drain() == [] + assert service.pending() == [] + finally: + service.stop() + + +def test_non_positive_duration_rejected(): + service = TimerService() + try: + try: + service.set_timer(0, "nope") + except ValueError: + pass + else: + raise AssertionError("expected ValueError for a non-positive duration") + finally: + service.stop()