add basic clock functions (timer, alarm, date, current time)

This commit is contained in:
gabby committed 2026-10-05 05:30:15 +00:00
1 parent 780c9592ed
commit 07b0e2ff7e
28 files changed
+979 -8

No files matched your search

+20
View File
@@ -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 <text> | idle | status | skills | dream | "
+9
View File
@@ -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):
+5
View File
@@ -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:
+11 -1
View File
@@ -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)
+1 -1
View File
@@ -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:
+6
View File
@@ -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."
),
}
+36 -1
View File
@@ -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();
}
+4
View File
@@ -56,6 +56,10 @@
<button id="relabel-btn" type="button" class="small" disabled>relabel…</button>
</div>
<div id="inspector" class="inspector"></div>
<div class="panel-head">
<h2>Timers</h2>
</div>
<div id="timers" class="status"></div>
<div class="panel-head">
<h2>Skill tree</h2>
</div>
+252
View File
@@ -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})."