Compare commits

..
2 Commits
Author SHA1 Message Date
gabby 9a135f53ab describe/prescribe semif in codegen.md 2026-10-05 09:03:11 +00:00
gabby 07b0e2ff7e add basic clock functions (timer, alarm, date, current time) 2026-10-05 05:30:15 +00:00
29 changed files with 1125 additions and 8 deletions

No files matched your search

+12 -1
View File
@@ -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
+146
View File
@@ -26,6 +26,152 @@ example** of all three. Read its `manifest.json`, its `skill.py` (which declares
`INTEGRATION` and `CONTRACT`), and its `skill.test.py` alongside this file; a new
body should look and behave like it.
## The decision engine: SemIf
A skill body turns a request into an action, and along the way it must decide
things: which calendar the query means, whether the evidence is enough, what to
call the event. Those decisions are made by **SemIf** — the agent's decision
engine — not by text generation. This section explains what SemIf is, what it
can do, and when a body should reach for it instead of plain code or an LLM.
### What SemIf is
SemIf ("semantic ifs", formerly OpenJev) is a small, pinned, local language
model whose single job is to answer a **typed, runtime-defined decision**
without generating any text. You give it three things:
- a **state** — the unstructured evidence, usually `request.text` (sometimes the
query plus a list of candidates);
- a **question** — the criterion in plain language ("Which calendar is referred
to in the user query?");
- **options** — 2–16 named, described alternatives (`work`, `personal`, ...).
It performs one forward pass and reads the probabilities of the declared answer
tokens directly. It returns a probability for each option — no sentence, no
JSON, no decoding loop, nothing to parse. In effect it is a semantic `if`:
software asks a yes/no/which question in natural language and gets back a typed,
thresholdable number. The `state` may also be a nonempty JSON object or array.
The whole point is that the **question and options arrive with the request**.
Routing, selection, and assessment are not baked into the model or the prompt;
they are supplied at call time. You never fine-tune SemIf to add a new decision —
you just describe a new question.
That is the difference from a chat model: a chat model answers by generating text
that your code immediately parses back into an `if`. SemIf skips the text. On the
reference hardware, reading 21 binary decisions directly took about 1.0 s and
zero output tokens; the same decisions as a generated JSON array took about
5.3 s and 111 tokens. It is decision-native and cheap enough to embed in ordinary
code.
### SemIf's feature set
SemIf (<https://github.com/TheoLeeCJ/SemIf-OpenJev>) is a broader project than
the one call this agent makes. Its full feature set:
- **Runtime-defined decisions** — state, criterion, and option descriptions are
supplied per call; no retraining, no per-decision prompt engineering.
- **Decision-native readout** — one forward pass over the declared option
logits, softmaxed over the allowed answer tokens. No token is sampled, so
there is no generation, no JSON repair, and no decoding loop to get stuck.
- **Typed probabilities** — a probability per option, conditional on exactly the
options you supplied. 2–16 described options per decision.
- **Structured state** — the state can be a string or a nonempty JSON object or
array; direct modes preserve it as structured JSON rather than flattening it.
- **Shared-state awareness** — one long state can be prefetched once and branched
across many criteria: serial prefix reuse (~10.8 decisions/s) and parallel
suffix branches (~20 decisions/s) instead of re-scoring the state per decision.
Best when every decision shares the same state.
- **Multiple backends** — CUDA/PyTorch, Apple Silicon (MLX and PyTorch/MPS), and
a CPU llama.cpp path over a local GGUF. This agent pins the llama.cpp CPU
backend.
- **Reranker mode** — a second readout that scores each candidate as a yes/no
relevance proposition and softmaxes the log-odds across options; strongest for
ranking/retrieval rather than categorical decisions.
- **Auditability** — every row carries the option scores, timing, the exact model
revision, and a `prompt_sha256`, so a decision can be reproduced and compared.
- **Calibration** — optional per-workload temperature scaling fitted on labeled
decisions, which tightens expected calibration error (e.g. WANLI 0.208 → 0.069
out of fold). Calibration does not change the selected option.
- **Batch scoring CLI** (`semif-score`) — reads a JSONL of decisions and writes a
JSONL of typed scores, for offline evaluation.
- **Open, auditable evidence** — owned fixtures, committed runners, raw results,
and known failure modes.
Two caveats shape how the agent uses it: the probabilities are **conditional on
the options you supplied** — not calibrated operational confidence — so treat
them as conditional scores and threshold them rather than believing them; and a
forced typed output can still be semantically wrong. Quality depends on the
model: the pinned 4B reaches ~0.81 balanced accuracy on the project's authored
decision set (a 27B EXL3 bridge reaches ~0.96).
### What a skill body can use
A body does not speak SemIf's wire protocol. It reaches the engine through
**one** interface: the typed decision call.
```python
from semif_agent.decisions import DecisionRequest, Option
decision = DecisionRequest(
state=request.text,
question="Which calendar is referred to in the user query?",
options=[Option(c["name"], c["label"]) for c in calendars],
)
result = ctx.engine.call(decision)
result.selected # option id with the highest probability
result.prob("work") # that option's probability
result.probs # {option_id: probability}
```
The engine is always real (`ctx.engine`); there is no mock path. The runner
serializes calls onto one model, so keep decisions few. Return every
`(DecisionRequest, DecisionResult)` pair on `ActionResult.decisions` so the choice
is logged as a training row with the run outcome.
The shared-state, reranker, batch, and calibration features above are
engine/runtime concerns, not body-level tools: a body makes direct typed
decisions and lets the runner own the model.
Note that the runner's own **assessment** of whether a run succeeded
(`assess:outcome`) is itself a SemIf decision over the body's `action_log`, the
goal, and the resolved inputs. The body does not self-assess; it reports
truthfully and lets SemIf judge.
### Choosing between deterministic code, SemIf, and LLM text
Every value a body produces comes from one of three sources. Pick deliberately;
mixing them up is the most common way a body goes wrong.
| Source | Use it for | Examples |
| ------ | ---------- | -------- |
| **Deterministic code** | Exact, mechanical mappings that are right every time | parsing a date/time or number, formatting output, computing a duration, building a URL, comparing ids, iterating a fetched list, reading a status code, escaping text |
| **SemIf** (`ctx.engine.call`) | A judgment among a known, enumerated set of options, when the right one is semantic rather than an exact match | which calendar/contact/conversation/folder the query means; whether the evidence supports / contradicts / is insufficient; which target to use when several fit |
| **LLM text** (the LLM bridge) | Novel natural-language content that is not chosen from a set | an event title, a subject line, a message body, a summary, a description, a reformulation |
Rules:
- **Deterministic code is the default.** If a rule can decide it, write the rule.
Never spend a model call on something a regex, a dict lookup, or arithmetic
settles.
- **Use SemIf for choices, not for generation.** SemIf returns a probability over
the options you gave it; it cannot write a title or a sentence. Give it the
real candidate set (fetched from the service), include any configured default as
one of the options, and threshold the winner: use it when its probability clears
the skill's confidence threshold, otherwise fall back to the configured default
(see `calendar.create_event` and `simplex.next_message`).
- **Use the LLM bridge for text, not for routing or assessment.** Generated text
goes through the LLM bridge (`llm_bridge_url`, `llm_bridge_token`) — a generic
`POST /chat` — never by speaking a model's protocol directly. Keep the model
extractive and bounded (see how `calendar.create_event` asks only for a title
and description), and report a real failure when the bridge is down rather than
guessing the text.
- **Never blur the boundaries.** SemIf never generates; an LLM never routes,
selects, or assesses; deterministic code never invents a value it cannot
observe. A request input is resolved by SemIf, not by substring matching by
hand; a title is generated by the LLM, not assembled by string concatenation
when it should be written; a date is parsed by code, not asked of a model.
## Manifest schema
Registered in `data/categories.json` (and mirrored in the running tree). Fields:
+1
View File
@@ -0,0 +1 @@
{}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Report today's date."
}
+21
View File
@@ -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)
+29
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
{}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Report the current local time of day."
}
+33
View File
@@ -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)
+31
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
{}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Set an alarm for a specific time of day that notifies when it goes off."
}
+84
View File
@@ -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)
+84
View File
@@ -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)
+1
View File
@@ -0,0 +1 @@
{}
+3
View File
@@ -0,0 +1,3 @@
{
"description": "Set a countdown timer that notifies when it finishes."
}
+127
View File
@@ -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)
+90
View File
@@ -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)
+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})."
+12 -4
View File
@@ -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])
+96
View File
@@ -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()