scheduler/gateway: carry skill identity structurally, not in action_log

Skill bodies prefixed their own `category.name` into `ActionResult.action_log`,
which duplicated the runner's deterministic summary prefix and leaked the name
into the text the gateways speak. Identity is not data for the output string.

- bodies (seeds, canned replies, housekeeping meta skills) write only the real
  result; the runner already owns the `category.name:` summary prefix
- `run_queue`/`submit_request`/`answer` now return a structured `SchedulerReply`
  (status, text, run_id, skill_ref, result); the gateway reads `skill_ref` and
  `result` from it instead of regex-parsing them back out of the summary
- drop the gateway's `_SKILL_REF`/`_LEADING_RUN_ID` parsing helpers
- fix a latent double-prefix when a failed run had an empty action_log
- CODEGEN.md: generated bodies must not prefix the skill name
This commit is contained in:
gabby committed 2026-10-07 00:30:37 +00:00
1 parent d0c1dccffd
commit e9a7fc73ee
22 files changed
+248 -200

No files matched your search

+11 -4
View File
@@ -92,7 +92,10 @@ scheduler.py no up-front gate: every input is dispatched
housekeeping meta skills (delete/clear-config/regen/cancel-build)
operate on the tree via `ctx.admin`; per-category new-skill locks
(`locks.new_skill` in the category config) gate creation, with
`housekeeping`/`response` hard-locked in code
`housekeeping`/`response` hard-locked in code; front ends get a
structured `SchedulerReply` (status, text, run_id, skill_ref,
result) from `submit_request`/`answer`/`run_queue` so they never
parse the run id or skill ref back out of the summary
queue.py bounded FIFO request queue (arrival order, max depth)
skills.py tree + registry (hardcoded built-ins: the closed `response` canned
tree plus the `housekeeping` meta skills), navigation = SemIf
@@ -127,7 +130,8 @@ skill.py loop: observe -> act -> observe -> assess; the body is a single
assess is a SemIf decision (`assess:outcome` success/failure at
tau; on failure `assess:requeue` complete/retry) and the run
summary is deterministic (no generation), built from
category.skill + ok/failed + action_log; the assess state carries
category.skill + ok/failed + action_log — the body writes only the
result, the runner adds the `category.name:` ref; the assess state carries
the resolved inputs (secrets redacted); a `DETERMINISTIC_CATEGORIES`
run (housekeeping) skips assessment/repair — it is an internal
mechanical action with a known result, not an external run;
@@ -1103,8 +1107,11 @@ CLI, unit tests (24) + integration tests (2).
bool/`{enabled}` overrides it. A **skill's own recorded config**
(`data/skills/<category>/<name>/config.json` -> `{"humanize": bool}`) wins
over both, so a skill whose result is already speakable (e.g. `time.now`)
skips the rewrite while a mechanical one keeps it; the gateway resolves the
skill ref from the summary prefix (`category.name:`). Only `kind == "result"`
skips the rewrite while a mechanical one keeps it; the gateway reads the
skill ref from the structured `SchedulerReply.skill_ref` (the scheduler's
`run_queue`/`submit_request`/`answer` carry `run_id`, `skill_ref`, and the
unwrapped `result` alongside the human-facing `text` — no parsing it back out
of the summary). Only `kind == "result"`
lines are touched
(questions, repair/approval notices, and status chatter pass through); like
`result_only`, an enabled platform unwraps the result detail before cleaning.
+4
View File
@@ -418,6 +418,10 @@ happened:
Rules:
- **Do not prefix the skill name to `action_log` or `new_state`.** The runner
wraps the result in the deterministic summary (`category.name: ok — <detail>`)
and carries the skill ref structurally, so a body writes only the result text
— never `"<category>.<name>: ..."`.
- **Return the real result.** A read/query skill returns the data it fetched; an
action skill reports the service's real response. A generic "done" that omits
the result is a broken output.
+6 -6
View File
@@ -506,7 +506,7 @@ def _build_ics(uid, summary, start, end, all_day, stamp, description=""):
def _ask(request, field, question):
request.meta["create_event_awaiting"] = field
return ActionResult(
action_log=f"calendar.create_event: waiting for {field}",
action_log=f"waiting for {field}",
new_state=request.text,
needs_input=question,
)
@@ -526,7 +526,7 @@ def act(ctx, request):
fields = _extract_fields(ctx, request)
except BridgeError as exc:
return ActionResult(
action_log=f"calendar.create_event: {exc}",
action_log=str(exc),
new_state=request.text,
)
request.meta["create_event_fields"] = fields
@@ -576,12 +576,12 @@ def act(ctx, request):
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.create_event: calendar discovery failed: {exc}",
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar.create_event: no calendars found on the account",
action_log="no calendars found on the account",
new_state=request.text,
)
@@ -606,7 +606,7 @@ def act(ctx, request):
except CalDavError as exc:
return ActionResult(
action_log=(
f"calendar.create_event: could not create {title!r} on "
f"could not create {title!r} on "
f"{calendar!r}: {exc}"
),
new_state=request.text,
@@ -622,7 +622,7 @@ def act(ctx, request):
)
report = f"Created {title!r} on calendar {calendar!r}: {when_text} (UID {uid})."
return ActionResult(
action_log=f"calendar.create_event: {report}",
action_log=report,
new_state=report,
decisions=decisions,
)
+1 -1
View File
@@ -422,7 +422,7 @@ def test_unreachable_server_fails_honestly():
action, request, _engine = run(
None, "http://127.0.0.1:1", "add standup on 2026-11-10 at 9am"
)
assert action.action_log.startswith("calendar.create_event:"), action.action_log
assert action.action_log and "calendar.create_event" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
+4 -4
View File
@@ -362,12 +362,12 @@ def act(ctx, request):
calendars = _discover_calendars(ctx)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.next_event: calendar discovery failed: {exc}",
action_log=f"calendar discovery failed: {exc}",
new_state=request.text,
)
if not calendars:
return ActionResult(
action_log="calendar.next_event: calendar discovery failed: no calendars found",
action_log="calendar discovery failed: no calendars found",
new_state=request.text,
)
@@ -375,7 +375,7 @@ def act(ctx, request):
calendar = _resolve_calendar(ctx, request, calendars, decisions)
if not calendar:
return ActionResult(
action_log="calendar.next_event aborted: no calendar resolved.",
action_log="aborted: no calendar resolved.",
new_state=request.text,
decisions=decisions,
)
@@ -395,7 +395,7 @@ def act(ctx, request):
events = _parse_events(_calendar_payloads(body), local_tz)
except CalDavError as exc:
return ActionResult(
action_log=f"calendar.next_event failed on {calendar!r}: {exc}",
action_log=f"failed on {calendar!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
+4 -6
View File
@@ -73,19 +73,17 @@ def act(ctx, request):
try:
payload = _get(ctx, "/health")
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.connect_link: {exc}", new_state=request.text
)
return ActionResult(action_log=str(exc), new_state=request.text)
if not payload.get("ok"):
return ActionResult(
action_log="simplex.connect_link: simplex forwarding bridge is not healthy",
action_log="simplex forwarding bridge is not healthy",
new_state=request.text,
)
try:
payload = _get(ctx, "/address")
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.connect_link failed: {exc}",
action_log=f"reading the contact link failed: {exc}",
new_state=request.text,
)
short = str(payload.get("short_link") or "").strip()
@@ -93,7 +91,7 @@ def act(ctx, request):
if not (short or full):
return ActionResult(
action_log=(
"simplex.connect_link: the bridge returned no SimpleX "
"the bridge returned no SimpleX "
"contact link; the bot has no address yet."
),
new_state=request.text,
+1 -1
View File
@@ -135,7 +135,7 @@ def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=None, config=config("http://127.0.0.1:1"))
request = Request("give me your simplex link")
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.connect_link:"), action.action_log
assert action.action_log and "simplex.connect_link" not in action.action_log, action.action_log
assert action.new_state == request.text
print(action.action_log)
+4 -4
View File
@@ -140,11 +140,11 @@ def act(ctx, request):
try:
payload = _get(ctx, "/inbox")
except BridgeError as exc:
return ActionResult(action_log=f"simplex.next_message: {exc}", new_state=request.text)
return ActionResult(action_log=str(exc), new_state=request.text)
senders = _senders(payload.get("messages") or [])
if not senders:
return ActionResult(
action_log="simplex.next_message: no unread SimpleX messages.",
action_log="no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
decisions = []
@@ -155,14 +155,14 @@ def act(ctx, request):
)
except BridgeError as exc:
return ActionResult(
action_log=f"simplex.next_message failed reading {contact!r}: {exc}",
action_log=f"failed reading {contact!r}: {exc}",
new_state=request.text,
decisions=decisions,
)
message = payload.get("message")
if not message:
return ActionResult(
action_log=f"simplex.next_message: no unread message from {contact!r}.",
action_log=f"no unread message from {contact!r}.",
new_state="no unread SimpleX messages",
decisions=decisions,
)
+1 -1
View File
@@ -237,7 +237,7 @@ def test_unreachable_bridge_fails_honestly():
ctx = ActionContext(engine=engine, config=config("http://127.0.0.1:1"))
request = Request("read my next simplex message")
action = skill.act(ctx, request)
assert action.action_log.startswith("simplex.next_message:"), action.action_log
assert action.action_log and "simplex.next_message" not in action.action_log, action.action_log
assert action.new_state == request.text, "a failed read must not fake a result"
print(action.action_log)
+1 -1
View File
@@ -18,4 +18,4 @@ CONTRACT = {}
def act(ctx, request):
today = local_now(ctx.config).date()
message = f"Today is {today.strftime('%A, %B %d, %Y')} ({today.isoformat()})."
return ActionResult(action_log=f"time.date: {message}", new_state=message)
return ActionResult(action_log=message, new_state=message)
+1 -1
View File
@@ -33,4 +33,4 @@ def act(ctx, request):
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)
return ActionResult(action_log=message, new_state=message)
+3 -3
View File
@@ -71,17 +71,17 @@ def act(ctx, request):
if when is None:
request.meta["alarm_awaiting"] = True
return ActionResult(
action_log="time.set_alarm: waiting for a time",
action_log="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",
action_log="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)
return ActionResult(action_log=message, new_state=message)
+3 -3
View File
@@ -111,13 +111,13 @@ def act(ctx, request):
if seconds is None:
request.meta["timer_awaiting"] = True
return ActionResult(
action_log="time.set_timer: waiting for a duration",
action_log="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",
action_log="no timer service is available in this front end",
new_state=request.text,
)
@@ -125,4 +125,4 @@ def act(ctx, request):
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)
return ActionResult(action_log=message, new_state=message)
+20 -12
View File
@@ -435,6 +435,18 @@ def _print_approvals(scheduler: Scheduler) -> None:
print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}")
def _print_reply(reply, show_run_id: bool = False) -> None:
"""Print a scheduler reply, optionally keeping its run id visible."""
label = f"[{reply.run_id}] " if (show_run_id and reply.run_id) else ""
print(f"[{reply.status}] {label}{reply.text}")
def _drain_queue(scheduler: Scheduler) -> None:
"""Run queued work, printing each outcome with its run id."""
for reply in scheduler.run_queue():
_print_reply(reply, show_run_id=True)
def _fatal_exit(scheduler: Scheduler) -> int | None:
"""If the scheduler hit a fatal engine failure, print it and return non-zero.
@@ -518,8 +530,7 @@ def repl(scheduler: Scheduler, config: dict) -> int:
print(f"[{status}] {detail}")
_answer_questions(scheduler)
_answer_approvals(scheduler)
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
continue
if lower.startswith("relabel "):
parts = line.split()
@@ -587,19 +598,16 @@ def repl(scheduler: Scheduler, config: dict) -> int:
scheduler.busy(line[5:].strip())
print("current process set (busy).")
continue
status, detail = scheduler.submit(line)
print(f"[{status}] {detail}")
_print_reply(scheduler.submit(line))
if _fatal_exit(scheduler) is not None:
return 1
while scheduler.pending is not None:
hint = "" if scheduler.pending.pre_act else " [leave empty to skip]"
answer = input(f"{scheduler.pending.question}{hint} ")
status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}")
_print_reply(scheduler.answer(answer))
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
if _fatal_exit(scheduler) is not None:
return 1
_answer_questions(scheduler)
@@ -612,12 +620,12 @@ def scripted(scheduler: Scheduler, path: str) -> int:
print(try_warm(scheduler))
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
for row in rows:
status, detail = scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
print(f"[{status}] {detail}")
_print_reply(
scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
)
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
return _fatal_exit(scheduler) or 0
+4 -4
View File
@@ -255,13 +255,13 @@ class DashboardHandler(BaseHTTPRequestHandler):
with self.lock:
try:
body = self._read_json()
status, detail, request_id = self.scheduler.submit_request(
reply = self.scheduler.submit_request(
str(body.get("text", "")), source=str(body.get("source", "dashboard"))
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail, "request_id": request_id})
self._send(200, {"status": reply.status, "detail": reply.text, "request_id": reply.run_id})
return
if path == "/api/relabel":
with self.lock:
@@ -277,11 +277,11 @@ class DashboardHandler(BaseHTTPRequestHandler):
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.answer(str(body.get("text", "")))
reply = self.scheduler.answer(str(body.get("text", "")))
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
self._send(200, {"status": reply.status, "detail": reply.text})
return
if path == "/api/restart":
with self.lock:
+33 -45
View File
@@ -22,25 +22,16 @@ reaches the right chat.
from __future__ import annotations
import queue
import re
import threading
import time
from .base import InboundMessage, OutboundMessage
from .humanize import Humanizer
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
#: A result summary starts with the skill ref (`category.name:`), optionally
#: preceded by a `[resumed]` marker. Used to look up a skill's own config
#: (`data/skills/<cat>/<name>/config.json`) for a per-skill humanize override.
_SKILL_REF = re.compile(
r"^(?:\[resumed\]\s*)?([A-Za-z0-9_][A-Za-z0-9_-]*\.[A-Za-z0-9_][A-Za-z0-9_-]*):\s"
)
#: The scheduler's run summary wraps the real result as
#: `"<skill>: <ok|failed> — <detail>"`. A result-only platform (the voice
#: gateway) speaks just `<detail>`.
#: gateway) speaks just `<detail>`. Kept as a fallback for callers that hand
#: `_reply` a raw summary; the scheduler itself passes the unwrapped `result`.
_RESULT_SEP = " — "
_REPAIR_ACTIONS = {
@@ -69,21 +60,6 @@ _APPROVAL_ACTIONS = {
Target = tuple[str, str]
def _strip_run_id(text: str) -> str:
return _LEADING_RUN_ID.sub("", text or "")
def _skill_ref(text: str) -> str | None:
"""The `category.name` a result summary belongs to, or None."""
match = _SKILL_REF.match(text or "")
return match.group(1) if match else None
def _leading_run_id(text: str) -> str:
match = _LEADING_RUN_ID.match(text or "")
return match.group(0)[1:-2] if match else ""
def _result_detail(text: str) -> str:
"""Unwrap the scheduler's `"<skill>: <ok|failed> — <detail>"` summary.
@@ -311,10 +287,13 @@ class GatewayService:
if pending is not None and pending.request.source == self.source_for(
platform, msg.chat_id
):
status, detail = self.scheduler.answer(msg.text)
reply = self.scheduler.answer(msg.text)
if self.scheduler.pending is None:
self._pending_owner = None
self._reply(*reply_to, detail, kind=_reply_kind(status))
self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
elif pending is not None and self._pending_owner not in (None, reply_to):
self._reply(
*reply_to,
@@ -339,14 +318,17 @@ class GatewayService:
self._surfaced.add(approval_id)
self._reply(*reply_to, detail, kind="notice")
else:
status, detail, run_id = self.scheduler.submit_request(
reply = self.scheduler.submit_request(
msg.text, source=self.source_for(platform, msg.chat_id)
)
if run_id:
self._owners[run_id] = reply_to
if status == "needs_input":
if reply.run_id:
self._owners[reply.run_id] = reply_to
if reply.status == "needs_input":
self._pending_owner = reply_to
self._reply(*reply_to, detail, kind=_reply_kind(status))
self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
self.drain()
self.surface(origin=reply_to)
@@ -356,15 +338,16 @@ class GatewayService:
results = self.scheduler.run_queue()
if not results:
break
for status, detail in results:
run_id = _leading_run_id(detail)
owner = self._owner_of(run_id)
text = _strip_run_id(detail)
if status == "needs_input" and owner:
for reply in results:
owner = self._owner_of(reply.run_id)
if reply.status == "needs_input" and owner:
self._pending_owner = owner
target = owner or self._fallback_target()
if target:
self._reply(*target, text, kind=_reply_kind(status))
self._reply(
*target, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
def surface(self, origin: Target | None = None) -> None:
"""Send any newly posted authoring questions / repair offers."""
@@ -474,11 +457,15 @@ class GatewayService:
trace.append(kind, "?", **fields)
def _reply(
self, platform: str, chat_id: str, text: str, kind: str = "reply"
self,
platform: str,
chat_id: str,
text: str,
kind: str = "reply",
skill_ref: str | None = None,
result: str | None = None,
) -> None:
text = _strip_run_id(text)
result_only = self._result_only(platform)
skill_ref = _skill_ref(text) if kind == "result" else None
humanize = kind == "result" and self._humanize_enabled(platform, skill_ref)
if result_only:
# A spoken front end says the skill's result, not the scheduler's
@@ -486,9 +473,10 @@ class GatewayService:
if kind == "status":
return
if kind == "result" and (result_only or humanize):
# Unwrap `<skill>: <ok|failed> — <detail>` to the skill's own
# result before optionally cleaning it up.
text = _result_detail(text)
# The scheduler hands us the skill's own unwrapped detail; fall back
# to unwrapping `<skill>: <ok|failed> — <detail>` for raw-string
# callers.
text = result if result is not None else _result_detail(text)
if humanize:
started = time.time()
text = self.humanizer.humanize(text)
+72 -30
View File
@@ -196,6 +196,29 @@ class DispatchResult:
skill: str | None = None
decisions_logged: int = 0
needs_input: str | None = None
#: `category.name` when a skill produced the outcome, else None. Carried
#: structurally so front ends never parse it back out of `summary`.
skill_ref: str | None = None
#: The skill's own detail (its `action_log`, or `new_state` when empty) —
#: the unwrapped result a `result_only` front end speaks.
result: str | None = None
@dataclass
class SchedulerReply:
"""One scheduler outcome as a structured reply.
`text` is the human-facing summary (e.g. ``"time.now: ok — 12:00"``). The
machine-readable fields a front end needs — the run id, the skill ref, and
the skill's own unwrapped detail — ride alongside it instead of being
parsed back out of `text`.
"""
status: str
text: str
run_id: str = ""
skill_ref: str | None = None
result: str | None = None
class Scheduler:
@@ -320,15 +343,12 @@ class Scheduler:
# ---- intake ----
def submit(self, text: str, source: str = "typed") -> tuple[str, str]:
"""Feed one input. Returns (status, detail)."""
status, detail, _ = self.submit_request(text, source)
return status, detail
def submit(self, text: str, source: str = "typed") -> SchedulerReply:
"""Feed one input. Returns the structured reply."""
return self.submit_request(text, source)
def submit_request(
self, text: str, source: str = "typed"
) -> tuple[str, str, str]:
"""Feed one input, also returning the request id.
def submit_request(self, text: str, source: str = "typed") -> SchedulerReply:
"""Feed one input, returning the request id on the reply.
The id lets out-of-band interfaces (the messenger gateway) map a run
back to the chat that originated it. The decision engine is real, so an
@@ -337,13 +357,13 @@ class Scheduler:
try:
return self._submit(text, source)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc), ""
return SchedulerReply("fatal", self._mark_fatal(exc))
def _submit(self, text: str, source: str = "typed") -> tuple[str, str, str]:
def _submit(self, text: str, source: str = "typed") -> SchedulerReply:
with self._lock:
return self._submit_locked(text, source)
def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str, str]:
def _submit_locked(self, text: str, source: str = "typed") -> SchedulerReply:
request = Request(text, source=source)
self.trace.append("submit", request.id, text=text, source=source)
@@ -355,16 +375,22 @@ class Scheduler:
if self.pending is None:
self.current = None
if outcome.kind == "needs_input":
return "needs_input", outcome.summary, request.id
return SchedulerReply(
"needs_input", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary)
return "running", outcome.summary, request.id
return SchedulerReply(
"running", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
ok = self.queue.push(request)
if not ok:
self.trace.append("rejected", request.id, reason="queue is full")
return "rejected", "queue is full", request.id
return SchedulerReply("rejected", "queue is full", request.id)
self.trace.append("queued", request.id)
return "queued", "queued", request.id
return SchedulerReply("queued", "queued", request.id)
def busy(self, text: str, skill: str = "(driving)") -> None:
"""Set a fake in-progress process so the queue path is exercised."""
@@ -381,8 +407,8 @@ class Scheduler:
self.pending = None
self.current = None
def run_queue(self) -> list[tuple[str, str]]:
"""Process the queue while idle. Returns the outcomes.
def run_queue(self) -> list[SchedulerReply]:
"""Process the queue while idle. Returns the structured outcomes.
Safe to call from any thread: guarded by the scheduler lock (RLock, so
the async codegen worker can drain the queue from its completion path).
@@ -390,7 +416,7 @@ class Scheduler:
with self._lock:
return self._run_queue_locked()
def _run_queue_locked(self) -> list[tuple[str, str]]:
def _run_queue_locked(self) -> list[SchedulerReply]:
results = []
while self.current is None and len(self.queue) > 0:
if self._fatal is not None:
@@ -402,7 +428,7 @@ class Scheduler:
outcome = self._dispatch(request)
except EngineUnavailable as exc:
self._mark_fatal(exc)
results.append(("fatal", self._fatal))
results.append(SchedulerReply("fatal", self._fatal))
break
except Exception as exc:
self.trace.append("error", request.id, phase="dispatch", message=str(exc))
@@ -411,10 +437,20 @@ class Scheduler:
if self.pending is None:
self.current = None
if outcome.kind == "needs_input":
results.append(("needs_input", f"[{request.id}] {outcome.summary}"))
results.append(
SchedulerReply(
"needs_input", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
)
continue
self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary)
results.append(("ran", f"[{request.id}] {outcome.summary}"))
results.append(
SchedulerReply(
"ran", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
)
return results
# ---- dispatch ----
@@ -595,7 +631,7 @@ class Scheduler:
outcome = self.runner.run(skill, request)
return self._finish_run(skill, request, outcome)
def answer(self, text: str) -> tuple[str, str]:
def answer(self, text: str) -> SchedulerReply:
"""Feed the human's answer to a run paused for input.
Routed directly to the pending run — no gate, score, or navigation —
@@ -606,7 +642,7 @@ class Scheduler:
"""
with self._lock:
if self.pending is None:
return "error", "no run is waiting for input"
return SchedulerReply("error", "no run is waiting for input")
pending = self.pending
self.pending = None
pending.request.user_input = text
@@ -621,10 +657,16 @@ class Scheduler:
)
result = self._finish_run(pending.skill, pending.request, outcome)
if result.kind == "needs_input":
return "needs_input", result.summary
return SchedulerReply(
"needs_input", result.summary, pending.request.id,
result.skill_ref, result.result,
)
self.current = None
self.trace.append("ran", pending.request.id, skill=result.skill, summary=result.summary)
return "ran", f"[resumed] {result.summary}"
return SchedulerReply(
"ran", f"[resumed] {result.summary}", pending.request.id,
result.skill_ref, result.result,
)
def _finish_run(self, skill: Skill, request: Request, outcome) -> DispatchResult:
if outcome.error:
@@ -649,6 +691,8 @@ class Scheduler:
summary=outcome.needs_input,
skill=skill.name,
needs_input=outcome.needs_input,
skill_ref=f"{skill.category}.{skill.name}",
result=outcome.action_log or outcome.new_state or None,
)
self.trace.append(
"assessed",
@@ -672,13 +716,11 @@ class Scheduler:
self._propose_repair(skill, request, outcome)
return DispatchResult(
kind="ran",
summary=(
f"{skill.category}.{skill.name}: "
f"{'ok' if outcome.success else 'failed'} — "
f"{outcome.action_log or outcome.summary}"
),
summary=outcome.summary,
skill=skill.name,
decisions_logged=outcome.decisions_logged,
skill_ref=f"{skill.category}.{skill.name}",
result=(outcome.action_log or outcome.new_state or None),
)
# ---- repair loop ----
+23 -23
View File
@@ -586,7 +586,7 @@ def _canned_response(name: str, message: str):
"""An act that returns a fixed line. No transport, no generation, no config."""
def act(ctx: ActionContext, request: Request) -> ActionResult:
return ActionResult(action_log=f"{name}: {message}", new_state=message)
return ActionResult(action_log=message, new_state=message)
return act
@@ -799,7 +799,7 @@ def _resolve_target(admin, request: Request):
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping: several skills match ({names}); "
f"several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
@@ -807,7 +807,7 @@ def _resolve_target(admin, request: Request):
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping: awaiting skill name",
action_log="awaiting skill name",
new_state="awaiting target",
needs_input=_TARGET_QUESTION,
)
@@ -819,11 +819,11 @@ def _resolve_target(admin, request: Request):
if isinstance(ref, list):
names = ", ".join(f"{c}.{n}" for c, n in ref)
return ActionResult(
action_log=f"housekeeping: several skills match ({names}); be specific",
action_log=f"several skills match ({names}); be specific",
new_state="ambiguous",
)
return ActionResult(
action_log=f"housekeeping: no skill matches {answer!r}",
action_log=f"no skill matches {answer!r}",
new_state="not found",
)
@@ -831,7 +831,7 @@ def _resolve_target(admin, request: Request):
def _delete_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.delete_skill: no admin available", "error")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
@@ -840,35 +840,35 @@ def _delete_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.delete_skill: awaiting confirmation for {ref}",
action_log=f"awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=f"Delete {ref} and all its files? Reply yes to confirm.",
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.delete_skill: cancelled by user for {ref}",
action_log=f"cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.delete_skill(category, name)
return ActionResult(f"housekeeping.delete_skill: {detail}", detail)
return ActionResult(detail, detail)
def _clear_config_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.clear_config: no admin available", "error")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
category, name = target
_status, detail = admin.clear_skill_config(category, name)
return ActionResult(f"housekeeping.clear_config: {detail}", detail)
return ActionResult(detail, detail)
def _regen_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.regen_skill: no admin available", "error")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
@@ -877,19 +877,19 @@ def _regen_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_regen") != ref:
request.meta["housekeeping_regen"] = ref
return ActionResult(
action_log=f"housekeeping.regen_skill: awaiting guidance for {ref}",
action_log=f"awaiting guidance for {ref}",
new_state="awaiting guidance",
needs_input="What needs to be fixed?",
)
guidance = (request.user_input or "").strip()
_status, detail = admin.regen_skill(category, name, guidance)
return ActionResult(f"housekeeping.regen_skill: {detail}", detail)
return ActionResult(detail, detail)
def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.cancel_build: no admin available", "error")
return ActionResult("no admin available", "error")
writing = [
(category, skill.name)
for category, skills in admin.tree.items()
@@ -905,7 +905,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping.cancel_build: several skills match ({names}); "
f"several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
@@ -915,7 +915,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
category, name = resolved
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build is in progress for "
f"no build is in progress for "
f"{category}.{name}"
),
new_state="no build",
@@ -925,14 +925,14 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
category, name = writing[0]
elif not writing:
return ActionResult(
action_log="housekeeping.cancel_build: no skill build is in progress",
action_log="no skill build is in progress",
new_state="no build",
)
else:
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping.cancel_build: awaiting skill name",
action_log="awaiting skill name",
new_state="awaiting target",
needs_input="Which skill build should I cancel? Reply with its name.",
)
@@ -943,7 +943,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
else:
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build in progress matching "
f"no build in progress matching "
f"{answer!r}"
),
new_state="no build",
@@ -953,7 +953,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.cancel_build: awaiting confirmation for {ref}",
action_log=f"awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=(
f"Cancel the build for {ref} and delete its half-built leaf? "
@@ -962,11 +962,11 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.cancel_build: cancelled by user for {ref}",
action_log=f"cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.cancel_skill_build(category, name)
return ActionResult(f"housekeeping.cancel_build: {detail}", detail)
return ActionResult(detail, detail)
def build_housekeeping_skills() -> list[Skill]:
+19 -19
View File
@@ -109,9 +109,9 @@ def test_pipeline_end_to_end(tmp_path):
"what is the delivery status of my parcel",
]
for text in inputs:
status, detail = scheduler.submit(text)
print(f"[{status}] {detail}")
assert status in ("running", "queued", "rejected")
reply = scheduler.submit(text)
print(f"[{reply.status}] {reply.text}")
assert reply.status in ("running", "queued", "rejected")
scheduler.run_queue()
@@ -295,9 +295,9 @@ def test_busy_queue_path(tmp_path):
_install_tracking_fixture(scheduler)
scheduler.busy("driving on the freeway", skill="driving")
status, detail = scheduler.submit("tell me if my package was delivered")
print(f"[{status}] {detail}")
assert status == "queued"
reply = scheduler.submit("tell me if my package was delivered")
print(f"[{reply.status}] {reply.text}")
assert reply.status == "queued"
scheduler.idle()
@@ -499,13 +499,13 @@ def test_create_skill_empty_category_does_not_wedge(tmp_path):
scheduler.tree["travel_planning"] = []
for _ in range(2):
status, detail = scheduler.submit("look up flights to japan for february")
print(f"[{status}] {detail}")
assert status in ("running", "queued", "rejected", "error")
reply = scheduler.submit("look up flights to japan for february")
print(f"[{reply.status}] {reply.text}")
assert reply.status in ("running", "queued", "rejected", "error")
assert scheduler.current is None, "scheduler must never stay wedged after a submit"
status, detail = scheduler.submit("tell me if my package was delivered")
print(f"[{status}] {detail}")
reply = scheduler.submit("tell me if my package was delivered")
print(f"[{reply.status}] {reply.text}")
assert scheduler.current is None
@@ -533,10 +533,10 @@ def test_create_simplex_send_skill(tmp_path):
f"the simplex seeds must be loaded, got {seeded}"
)
status, detail = scheduler.submit("send a simplex message to pepper saying hi")
print(f"[{status}] {detail}")
assert status in ("running", "queued", "rejected")
assert "new skill for simplex" in detail, (
reply = scheduler.submit("send a simplex message to pepper saying hi")
print(f"[{reply.status}] {reply.text}")
assert reply.status in ("running", "queued", "rejected")
assert "new skill for simplex" in reply.text, (
"a send request must route to create_skill for simplex"
)
assert scheduler.current is None, "gate must be free again right after the draft is queued"
@@ -627,9 +627,9 @@ def test_skill_pauses_for_input_and_resumes(tmp_path):
assert scheduler.pending is not None
assert scheduler.current is not None
status, detail = scheduler.answer("AB123")
print(f"[{status}] {detail}")
assert status == "ran"
reply = scheduler.answer("AB123")
print(f"[{reply.status}] {reply.text}")
assert reply.status == "ran"
assert seen == ["AB123"]
assert scheduler.pending is None
assert scheduler.current is None
@@ -653,7 +653,7 @@ def test_empty_result_is_assessed_as_success(tmp_path):
def act(ctx, request):
return ActionResult(
action_log="simplex.next_message: no unread SimpleX messages.",
action_log="no unread SimpleX messages.",
new_state="no unread SimpleX messages",
)
+12 -11
View File
@@ -176,7 +176,10 @@ def test_gateway_skill_config_disables_humanize():
service = build_service_with_store(
llm, {"humanize": {"enabled": True}, "simplex": {}}, store
)
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
service._reply(
"simplex", "c", "time.now: ok — 12:00", kind="result",
skill_ref="time.now", result="12:00",
)
assert service.outbound["simplex"].get_nowait().text == "time.now: ok — 12:00"
assert llm.calls == []
@@ -190,7 +193,10 @@ def test_gateway_skill_config_enables_humanize_over_platform():
{"humanize": {"enabled": False}, "simplex": {"humanize": False}},
store,
)
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
service._reply(
"simplex", "c", "time.now: ok — 12:00", kind="result",
skill_ref="time.now", result="12:00",
)
assert service.outbound["simplex"].get_nowait().text == "It is 12:00."
@@ -201,13 +207,8 @@ def test_gateway_skill_config_absent_falls_back_to_platform():
service = build_service_with_store(
llm, {"humanize": {"enabled": True}, "simplex": {}}, store
)
service._reply("simplex", "c", "time.now: ok — 12:00", kind="result")
service._reply(
"simplex", "c", "time.now: ok — 12:00", kind="result",
skill_ref="time.now", result="12:00",
)
assert service.outbound["simplex"].get_nowait().text == "It is 12:00."
def test_skill_ref_parses_summary_and_resumed_marker():
from semif_agent.gateway.service import _skill_ref
assert _skill_ref("time.now: ok — 12:00") == "time.now"
assert _skill_ref("[resumed] track.manual: ok — sent") == "track.manual"
assert _skill_ref("queued") is None
+11 -11
View File
@@ -67,8 +67,8 @@ def test_skill_pause_and_answer(tmp_path):
assert scheduler.current.skill == "track.manual"
assert scheduler.log.read() == [], "sub-decisions must be deferred until completion"
status, detail = scheduler.answer("AB123")
assert status == "ran"
reply = scheduler.answer("AB123")
assert reply.status == "ran"
assert seen == ["AB123"]
assert scheduler.pending is None
assert scheduler.current is None
@@ -82,9 +82,9 @@ def test_skill_pause_and_answer(tmp_path):
def test_answer_without_pending_is_error(tmp_path):
scheduler = build_scheduler(tmp_path)
status, detail = scheduler.answer("hello")
assert status == "error"
assert "waiting for input" in detail
reply = scheduler.answer("hello")
assert reply.status == "error"
assert "waiting for input" in reply.text
def test_act_decisions_logged_on_completion(tmp_path):
@@ -164,13 +164,13 @@ def test_resume_can_ask_again(tmp_path):
scheduler = build_scheduler(tmp_path)
scheduler._run_skill(skill, Request("track"))
status, detail = scheduler.answer("XYZ")
assert status == "needs_input"
reply = scheduler.answer("XYZ")
assert reply.status == "needs_input"
assert seen == ["XYZ"]
assert scheduler.pending is not None
status, detail = scheduler.answer("AB123")
assert status == "ran"
reply = scheduler.answer("AB123")
assert reply.status == "ran"
assert scheduler.pending is None
assert scheduler.current is None
@@ -196,8 +196,8 @@ def test_empty_answer_is_accepted_and_forwarded(tmp_path):
result = scheduler._run_skill(skill, Request("track my package"))
assert result.kind == "needs_input"
status, detail = scheduler.answer("")
assert status == "ran", detail
reply = scheduler.answer("")
assert reply.status == "ran", reply.text
assert seen == [None, ""], "the empty answer must reach act"
assert scheduler.pending is None
assert scheduler.current is None
+10 -10
View File
@@ -1591,15 +1591,15 @@ def test_skill_pre_act_contract_pause_and_resume(tmp_path):
assert scheduler.pending is not None
assert scheduler.pending.pre_act is True
status, detail = scheduler.answer("AB123")
assert status == "needs_input"
reply = scheduler.answer("AB123")
assert reply.status == "needs_input"
assert scheduler.pending is not None
assert scheduler.pending.pre_act is False
assert scheduler.pending.request.meta["config_answers"]["token"] == "AB123"
assert "Confirm?" in scheduler.pending.question
status, detail = scheduler.answer("yes")
assert status == "ran"
reply = scheduler.answer("yes")
assert reply.status == "ran"
assert scheduler.pending is None
@@ -1631,8 +1631,8 @@ def test_pre_act_skip_leaves_variable_unset_and_does_not_reask(tmp_path):
assert result.kind == "needs_input"
assert scheduler.pending is not None and scheduler.pending.pre_act is True
status, detail = scheduler.answer("")
assert status == "ran", detail
reply = scheduler.answer("")
assert reply.status == "ran", reply.text
assert scheduler.pending is None
assert "token" not in seen, "a skipped variable must stay unset"
@@ -1664,13 +1664,13 @@ def test_pre_act_skip_advances_to_next_missing_variable(tmp_path):
assert result.kind == "needs_input"
assert "`alpha`" in result.summary
status, detail = scheduler.answer("")
assert status == "needs_input"
reply = scheduler.answer("")
assert reply.status == "needs_input"
assert scheduler.pending is not None
assert "`beta`" in scheduler.pending.question
status, detail = scheduler.answer("")
assert status == "ran", detail
reply = scheduler.answer("")
assert reply.status == "ran", reply.text
assert "alpha" not in seen and "beta" not in seen