chain multi-step requests across known skills
Add the run-ledger chained-run path and make a compound request run its known skills in order instead of authoring one monolithic skill. - scheduler/skill: `assess:outcome` gains a `continue` verdict; a continued step is re-dispatched with a bounded run ledger (max_reentries + a monotonic-progress guard), and the ledger is rendered into the routing and assessment state. - navigation leaf guard (`confirm_skill_fit`) becomes same/part/different and is ledger-aware, so the first step of a compound request runs instead of being rejected into `create_skill` (a real run picked calculator.calculate at 0.99 and was rejected into create_skill). - results flow forward through `request.run_ledger` (`last_result` helper); `simplex.send_message` sends the prior step's result rather than asking the LLM bridge to recompute it. Documented in CODEGEN.md. - `assess:outcome` stays the sole continuation authority: the guard only decides whether a skill contributes, never forces a continuation (a forced continue on `part` overrode a correct `done` on the final step and authored a spurious category). - verbosity levels, structured SchedulerReply fields, and a send_message hermetic test for the chained-result path.
This commit is contained in:
1 parent
9ba14fdab0
commit
ab0defca1e
20 files changed
+1046
-324
No files matched your search
+17
-6
@@ -485,16 +485,26 @@ 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."""
|
||||
def _print_reply(reply, show_run_id: bool = False, verbosity: str = "result") -> None:
|
||||
"""Print a scheduler reply, honoring the configured verbosity.
|
||||
|
||||
"result" shows only the final answer of a request (an intermediate chain
|
||||
step is hidden); "query" also shows intermediate steps; "decision"
|
||||
additionally prints each SemIf decision phase for the run.
|
||||
"""
|
||||
if getattr(reply, "intermediate", False) and verbosity == "result":
|
||||
return
|
||||
label = f"[{reply.run_id}] " if (show_run_id and reply.run_id) else ""
|
||||
print(f"[{reply.status}] {label}{reply.text}")
|
||||
for line in getattr(reply, "decision_lines", ()) or ():
|
||||
print(f" {line}")
|
||||
|
||||
|
||||
def _drain_queue(scheduler: Scheduler) -> None:
|
||||
"""Run queued work, printing each outcome with its run id."""
|
||||
verbosity = getattr(scheduler, "verbosity", "result")
|
||||
for reply in scheduler.run_queue():
|
||||
_print_reply(reply, show_run_id=True)
|
||||
_print_reply(reply, show_run_id=True, verbosity=verbosity)
|
||||
|
||||
|
||||
def _fatal_exit(scheduler: Scheduler) -> int | None:
|
||||
@@ -646,13 +656,13 @@ def repl(scheduler: Scheduler, config: dict) -> int:
|
||||
scheduler.busy(line[5:].strip())
|
||||
print("current process set (busy).")
|
||||
continue
|
||||
_print_reply(scheduler.submit(line))
|
||||
_print_reply(scheduler.submit(line), verbosity=scheduler.verbosity)
|
||||
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} ")
|
||||
_print_reply(scheduler.answer(answer))
|
||||
_print_reply(scheduler.answer(answer), verbosity=scheduler.verbosity)
|
||||
if _fatal_exit(scheduler) is not None:
|
||||
return 1
|
||||
_drain_queue(scheduler)
|
||||
@@ -669,7 +679,8 @@ def scripted(scheduler: Scheduler, path: str) -> int:
|
||||
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
|
||||
for row in rows:
|
||||
_print_reply(
|
||||
scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
|
||||
scheduler.submit(str(row["text"]), source=row.get("source", "scripted")),
|
||||
verbosity=scheduler.verbosity,
|
||||
)
|
||||
if _fatal_exit(scheduler) is not None:
|
||||
return 1
|
||||
|
||||
@@ -72,6 +72,13 @@ class Request:
|
||||
reentries: int = 0
|
||||
resume: dict[str, Any] = field(default_factory=dict)
|
||||
user_input: str | None = None
|
||||
#: Compact, deterministic record of the chain of skills already run toward
|
||||
#: this request: one ``{query, skill (category.name), outcome}`` entry per
|
||||
#: step. It threads through a continuation so the next step's routing and
|
||||
#: the outcome assessment see what was already done; empty on a first-step
|
||||
#: request. Bounded by construction (each outcome is bounded to the
|
||||
#: speakable budget, and the chain is capped).
|
||||
run_ledger: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
def copy_for_requeue(self) -> "Request":
|
||||
return Request(
|
||||
@@ -83,4 +90,5 @@ class Request:
|
||||
priority=self.priority,
|
||||
reentries=self.reentries + 1,
|
||||
resume=dict(self.resume),
|
||||
run_ledger=[dict(entry) for entry in self.run_ledger],
|
||||
)
|
||||
@@ -313,10 +313,11 @@ class GatewayService:
|
||||
reply = self.scheduler.answer(msg.text)
|
||||
if self.scheduler.pending is None:
|
||||
self._pending_owner = None
|
||||
self._reply(
|
||||
*reply_to, reply.text, kind=_reply_kind(reply.status),
|
||||
skill_ref=reply.skill_ref, result=reply.result,
|
||||
)
|
||||
if not self._hidden(reply):
|
||||
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,
|
||||
@@ -348,10 +349,11 @@ class GatewayService:
|
||||
self._owners[reply.run_id] = reply_to
|
||||
if reply.status == "needs_input":
|
||||
self._pending_owner = reply_to
|
||||
self._reply(
|
||||
*reply_to, reply.text, kind=_reply_kind(reply.status),
|
||||
skill_ref=reply.skill_ref, result=reply.result,
|
||||
)
|
||||
if not self._hidden(reply):
|
||||
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)
|
||||
|
||||
@@ -362,6 +364,8 @@ class GatewayService:
|
||||
if not results:
|
||||
break
|
||||
for reply in results:
|
||||
if self._hidden(reply):
|
||||
continue
|
||||
owner = self._owner_of(reply.run_id)
|
||||
if reply.status == "needs_input" and owner:
|
||||
self._pending_owner = owner
|
||||
@@ -372,6 +376,17 @@ class GatewayService:
|
||||
skill_ref=reply.skill_ref, result=reply.result,
|
||||
)
|
||||
|
||||
def _hidden(self, reply) -> bool:
|
||||
"""Hide an intermediate chain step at `result` verbosity.
|
||||
|
||||
The default end-user view is just the final answer; a chained request's
|
||||
intermediate "continue" steps are only surfaced at `query`/`decision`
|
||||
verbosity.
|
||||
"""
|
||||
if not getattr(reply, "intermediate", False):
|
||||
return False
|
||||
return getattr(self.scheduler, "verbosity", "result") == "result"
|
||||
|
||||
def surface(self, origin: Target | None = None) -> None:
|
||||
"""Send any newly posted authoring questions / repair offers."""
|
||||
questions = self.scheduler.pending_questions()
|
||||
|
||||
+167
-19
@@ -90,6 +90,25 @@ def normalize_new_skill_mode(value) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
#: Output verbosity levels. "result" (default) shows only the final result of a
|
||||
#: request; "query" also shows each intermediate chain step (query + ledger);
|
||||
#: "decision" also shows each SemIf decision phase.
|
||||
VERBOSITY_LEVELS = ("result", "query", "decision")
|
||||
|
||||
|
||||
def normalize_verbosity(value) -> str:
|
||||
"""Coerce a configured verbosity to one of `VERBOSITY_LEVELS`.
|
||||
|
||||
Unrecognized/absent falls back to the "result" default (the end user only
|
||||
wants the answer, not each decision or query).
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
mode = value.strip().lower()
|
||||
if mode in VERBOSITY_LEVELS:
|
||||
return mode
|
||||
return "result"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Process:
|
||||
request: Request
|
||||
@@ -223,6 +242,10 @@ class DispatchResult:
|
||||
#: 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
|
||||
#: True when this step is an intermediate "continue" of a chained request:
|
||||
#: the request is re-dispatched and the *final* step's reply is the answer.
|
||||
#: A `result`-verbosity front end hides intermediates.
|
||||
intermediate: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -240,6 +263,11 @@ class SchedulerReply:
|
||||
run_id: str = ""
|
||||
skill_ref: str | None = None
|
||||
result: str | None = None
|
||||
#: See `DispatchResult.intermediate`.
|
||||
intermediate: bool = False
|
||||
#: At `decision` verbosity only: the SemIf decision phases (with the selected
|
||||
#: option) recorded for this run, for a debugging front end.
|
||||
decision_lines: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
class Scheduler:
|
||||
@@ -275,6 +303,19 @@ class Scheduler:
|
||||
#: option, so its confidence carries no match signal).
|
||||
self.bypass_tau = float(nav_cfg.get("softmax_bypass_tau", 0.5))
|
||||
self.max_reentries = max_reentries
|
||||
#: How much of a completed chain to surface. "result" (default): only the
|
||||
#: final result; "query": also each intermediate step's query + ledger;
|
||||
#: "decision": also each SemIf decision phase (a debugging view).
|
||||
self.verbosity = normalize_verbosity(config.get("verbosity"))
|
||||
#: One shared speakable budget for every skill's output (the result string
|
||||
#: and its run-ledger entry): a result is read in a chat or spoken, so it
|
||||
#: is truncated to this many characters at a word boundary.
|
||||
chain_cfg = config.get("chain", {}) or {}
|
||||
self.result_chars = int(chain_cfg.get("result_chars", 300))
|
||||
#: The `assess:outcome` thresholds (precedence failed > done > continue).
|
||||
assess_cfg = config.get("assess", {}) or {}
|
||||
self.done_tau = float(assess_cfg.get("done_tau", 0.5))
|
||||
self.fail_tau = float(assess_cfg.get("fail_tau", 0.5))
|
||||
self.codegen = codegen
|
||||
self.degeneration_check_factory = degeneration_check_factory
|
||||
self.regen_decision_factory = regen_decision_factory
|
||||
@@ -329,7 +370,13 @@ class Scheduler:
|
||||
engine=self.engine, config=config, timers=self.timers, admin=self
|
||||
)
|
||||
self.runner = SkillRunner(
|
||||
self.ctx, self.log, store=self.body_store, tau=self.tau
|
||||
self.ctx,
|
||||
self.log,
|
||||
store=self.body_store,
|
||||
tau=self.tau,
|
||||
done_tau=self.done_tau,
|
||||
fail_tau=self.fail_tau,
|
||||
result_chars=self.result_chars,
|
||||
)
|
||||
self._fatal: str | None = None
|
||||
self.current: Process | None = None
|
||||
@@ -404,11 +451,14 @@ class Scheduler:
|
||||
return SchedulerReply(
|
||||
"needs_input", outcome.summary, request.id,
|
||||
outcome.skill_ref, outcome.result,
|
||||
decision_lines=self._decision_lines(request.id),
|
||||
)
|
||||
self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary)
|
||||
return SchedulerReply(
|
||||
"running", outcome.summary, request.id,
|
||||
outcome.skill_ref, outcome.result,
|
||||
intermediate=outcome.intermediate,
|
||||
decision_lines=self._decision_lines(request.id),
|
||||
)
|
||||
|
||||
ok = self.queue.push(request)
|
||||
@@ -467,6 +517,7 @@ class Scheduler:
|
||||
SchedulerReply(
|
||||
"needs_input", outcome.summary, request.id,
|
||||
outcome.skill_ref, outcome.result,
|
||||
decision_lines=self._decision_lines(request.id),
|
||||
)
|
||||
)
|
||||
continue
|
||||
@@ -475,10 +526,31 @@ class Scheduler:
|
||||
SchedulerReply(
|
||||
"ran", outcome.summary, request.id,
|
||||
outcome.skill_ref, outcome.result,
|
||||
intermediate=outcome.intermediate,
|
||||
decision_lines=self._decision_lines(request.id),
|
||||
)
|
||||
)
|
||||
return results
|
||||
|
||||
def _decision_lines(self, request_id: str) -> list[str]:
|
||||
"""The SemIf decision phases recorded for one run.
|
||||
|
||||
Only populated at `decision` verbosity (a debugging view); every other
|
||||
level returns an empty list so a normal front end never sees SemIf
|
||||
internals.
|
||||
"""
|
||||
if self.verbosity != "decision":
|
||||
return []
|
||||
lines = []
|
||||
for row in self.log.read():
|
||||
extra = row.get("extra") or {}
|
||||
if extra.get("run_id") != request_id:
|
||||
continue
|
||||
probs = row.get("predicted_probs") or {}
|
||||
rendered = " ".join(f"{k}={v:.2f}" for k, v in probs.items())
|
||||
lines.append(f"{extra.get('phase', '?')}: {row.get('selected', '?')} [{rendered}]")
|
||||
return lines
|
||||
|
||||
# ---- dispatch ----
|
||||
|
||||
def _dispatch(self, request: Request) -> DispatchResult:
|
||||
@@ -510,6 +582,11 @@ class Scheduler:
|
||||
category_tau=self.category_tau,
|
||||
action_tau=self.action_tau,
|
||||
bypass_tau=self.bypass_tau,
|
||||
# A continuation (a request already carrying a run ledger) is the
|
||||
# next step of an in-flight request, so it is actionable by
|
||||
# construction and skips the actionability guard; only a fresh
|
||||
# first-step input is checked against the closed `response` tree.
|
||||
skip_actionability=bool(request.run_ledger),
|
||||
)
|
||||
if isinstance(navigation, CreateCategory):
|
||||
if self.new_skill_mode == "deny":
|
||||
@@ -531,9 +608,10 @@ class Scheduler:
|
||||
# therefore the sole leaf-level create door and is never bypassed: a
|
||||
# confident softmax winner among only-wrong options must still be
|
||||
# checked, or codegen can never be reached for an unmatched request.
|
||||
if not confirm_skill_fit(
|
||||
verdict = confirm_skill_fit(
|
||||
self.engine, self.log, self.trace, request, navigation, self.intent_tau
|
||||
):
|
||||
)
|
||||
if verdict == "different":
|
||||
self.trace.append(
|
||||
"intent_mismatch",
|
||||
request.id,
|
||||
@@ -543,6 +621,10 @@ class Scheduler:
|
||||
if self._category_locked(navigation.category):
|
||||
return self._blocked_create(request, navigation.category)
|
||||
return self._dispatch_skill(request, navigation.category)
|
||||
# `same` or `part` both run the skill: a `part` step is one required part
|
||||
# of a compound request, and whether more work remains is `assess:outcome`'s
|
||||
# call — never the guard's. (Forcing a `continue` here overrode a correct
|
||||
# `done` on the final step and drove the chain into a spurious create.)
|
||||
return self._run_skill(navigation, request)
|
||||
|
||||
def _dispatch_create_category(self, request: Request) -> DispatchResult:
|
||||
@@ -707,12 +789,15 @@ class Scheduler:
|
||||
return SchedulerReply(
|
||||
"needs_input", result.summary, pending.request.id,
|
||||
result.skill_ref, result.result,
|
||||
decision_lines=self._decision_lines(pending.request.id),
|
||||
)
|
||||
self.current = None
|
||||
self.trace.append("ran", pending.request.id, skill=result.skill, summary=result.summary)
|
||||
return SchedulerReply(
|
||||
"ran", f"[resumed] {result.summary}", pending.request.id,
|
||||
result.skill_ref, result.result,
|
||||
intermediate=result.intermediate,
|
||||
decision_lines=self._decision_lines(pending.request.id),
|
||||
)
|
||||
|
||||
def _finish_run(self, skill: Skill, request: Request, outcome) -> DispatchResult:
|
||||
@@ -741,29 +826,67 @@ class Scheduler:
|
||||
skill_ref=f"{skill.category}.{skill.name}",
|
||||
result=outcome.action_log or outcome.new_state or None,
|
||||
)
|
||||
verdict = outcome.outcome or ("done" if outcome.success else "failed")
|
||||
self.trace.append(
|
||||
"assessed",
|
||||
request.id,
|
||||
skill=skill.name,
|
||||
outcome=verdict,
|
||||
success=outcome.success,
|
||||
summary=outcome.summary,
|
||||
assessment_summary=outcome.assessment_summary,
|
||||
action_log=outcome.action_log,
|
||||
updated_request=outcome.updated_request,
|
||||
)
|
||||
requeued = False
|
||||
if outcome.updated_request and request.reentries < self.max_reentries:
|
||||
child = _requeue(request, outcome.updated_request)
|
||||
# Remember what this attempt observed so the next assessment can
|
||||
# tell a genuine retry (the result changed) from a guaranteed
|
||||
# repeat against unchanged state.
|
||||
child.meta["prev_result"] = outcome.action_log or outcome.new_state
|
||||
self.queue.push(child)
|
||||
self.trace.append("requeued", request.id, text=outcome.updated_request)
|
||||
if self.on_request_requeued is not None:
|
||||
self.on_request_requeued(request.id, child.id)
|
||||
requeued = True
|
||||
if not outcome.success and not (outcome.updated_request and requeued):
|
||||
if verdict == "continue":
|
||||
entry = {
|
||||
"query": request.text,
|
||||
"skill": f"{skill.category}.{skill.name}",
|
||||
"outcome": outcome.action_log or outcome.new_state,
|
||||
}
|
||||
repeat = self._would_repeat(request, entry)
|
||||
if request.reentries < self.max_reentries and not repeat:
|
||||
child = _continue(request, entry)
|
||||
self.queue.push(child)
|
||||
self.trace.append(
|
||||
"continued",
|
||||
request.id,
|
||||
skill=entry["skill"],
|
||||
outcome=entry["outcome"],
|
||||
step=len(child.run_ledger),
|
||||
)
|
||||
if self.on_request_requeued is not None:
|
||||
self.on_request_requeued(request.id, child.id)
|
||||
# Intermediate step: the request is re-dispatched, and the final
|
||||
# step's reply is the answer. A `result`-verbosity front end
|
||||
# hides this reply.
|
||||
return DispatchResult(
|
||||
kind="ran",
|
||||
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),
|
||||
intermediate=True,
|
||||
)
|
||||
# The chain stops here: it worked, but either the step budget is
|
||||
# spent or the next step would repeat an identical (skill, outcome).
|
||||
# This is not a failure, so no repair offer — just report what is
|
||||
# still pending.
|
||||
self.trace.append(
|
||||
"chain_halted",
|
||||
request.id,
|
||||
skill=entry["skill"],
|
||||
reason="repeat" if repeat else "budget",
|
||||
)
|
||||
return DispatchResult(
|
||||
kind="ran",
|
||||
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),
|
||||
)
|
||||
if verdict == "failed":
|
||||
self._propose_repair(skill, request, outcome)
|
||||
return DispatchResult(
|
||||
kind="ran",
|
||||
@@ -774,6 +897,21 @@ class Scheduler:
|
||||
result=(outcome.action_log or outcome.new_state or None),
|
||||
)
|
||||
|
||||
def _would_repeat(self, request: Request, entry: dict) -> bool:
|
||||
"""Would entering this step repeat an identical (skill, outcome)?
|
||||
|
||||
The monotonic-progress guard: each chain step must either select a
|
||||
*different* skill or produce a *changed* outcome. A repeated pair means
|
||||
the chain is not making progress (the request and external state are
|
||||
unchanged), so it must stop instead of looping.
|
||||
"""
|
||||
skill = entry.get("skill")
|
||||
outcome = entry.get("outcome")
|
||||
return any(
|
||||
prior.get("skill") == skill and prior.get("outcome") == outcome
|
||||
for prior in request.run_ledger
|
||||
)
|
||||
|
||||
# ---- repair loop ----
|
||||
|
||||
def _propose_repair(self, skill: Skill, request: Request, outcome) -> None:
|
||||
@@ -2305,10 +2443,20 @@ class Scheduler:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _requeue(request: Request, updated_text: str) -> Request:
|
||||
updated = Request(updated_text, source="requeue")
|
||||
def _continue(request: Request, entry: dict) -> Request:
|
||||
"""Build the next-step request for a chained run.
|
||||
|
||||
Deterministic: the *new query* is the original goal re-fed with the run
|
||||
ledger attached (composed in `compose_state`), never a generated utterance.
|
||||
Carries the prior ledger plus this step's entry, bumps the step count, and
|
||||
links the parent run so a front end can route the completion home. `meta` is
|
||||
intentionally not copied (a later step is a different skill, so per-fire
|
||||
config answers must not leak forward).
|
||||
"""
|
||||
updated = Request(request.text, source="continue")
|
||||
updated.reentries = request.reentries + 1
|
||||
updated.meta["parent_run"] = request.id
|
||||
updated.run_ledger = [dict(e) for e in request.run_ledger] + [dict(entry)]
|
||||
return updated
|
||||
|
||||
|
||||
|
||||
+95
-85
@@ -7,11 +7,13 @@ the human for anything unresolved), performs the real action, and returns an
|
||||
`ActionResult.decisions` and are logged by the runner with the run outcome.
|
||||
|
||||
Assessment is a SemIf decision, not generation: `assess:outcome` decides
|
||||
success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides
|
||||
complete/retry. The run summary is deterministic — same inputs, same string —
|
||||
built from the category, skill, outcome flag, and action log. Every SemIf
|
||||
decision made during a run is logged as a training row; the assessment outcome
|
||||
is kept on the row so the dream pass can weigh failed runs.
|
||||
whether there is any additional work to do — `done` (request satisfied),
|
||||
`continue` (the step worked but more work is needed; the scheduler routes the
|
||||
next step), or `failed` (the step errored → the repair path). The run summary is
|
||||
deterministic — same inputs, same string — built from the category, skill,
|
||||
outcome flag, and action log. Every SemIf decision made during a run is logged as
|
||||
a training row; the assessment outcome is kept on the row so the dream pass can
|
||||
weigh failed runs.
|
||||
|
||||
A skill with a data contract may need variables collected from the human before
|
||||
it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered
|
||||
@@ -35,6 +37,8 @@ from .skills import (
|
||||
ActionContext,
|
||||
Skill,
|
||||
SkillStore,
|
||||
bound_output,
|
||||
render_ledger,
|
||||
resolve_skill_config,
|
||||
unresolved_variables,
|
||||
)
|
||||
@@ -87,7 +91,12 @@ class RunResult:
|
||||
summary: str
|
||||
action_log: str
|
||||
new_state: str
|
||||
updated_request: str | None = None
|
||||
#: The three-way outcome for a chained run: "done" (request satisfied),
|
||||
#: "continue" (the step worked but more work is needed → the scheduler routes
|
||||
#: the next step), or "failed" (the step errored → the repair path). None
|
||||
#: only for a pause for input (needs_input/error), which never reaches the
|
||||
#: outcome branch.
|
||||
outcome: str | None = None
|
||||
decisions_logged: int = 0
|
||||
assessment_summary: str = ""
|
||||
error: str | None = None
|
||||
@@ -102,11 +111,25 @@ class SkillRunner:
|
||||
log: DecisionLog,
|
||||
store: SkillStore | None = None,
|
||||
tau: float = 0.6,
|
||||
done_tau: float = 0.5,
|
||||
fail_tau: float = 0.5,
|
||||
result_chars: int = 300,
|
||||
):
|
||||
self.ctx = ctx
|
||||
self.log = log
|
||||
self.store = store
|
||||
self.tau = tau
|
||||
#: Thresholds for the three-way `assess:outcome` decision. Precedence is
|
||||
#: failed > done > continue: a step is only declared "continue" when the
|
||||
#: model is genuinely unsure, so a confident success/failure is honored
|
||||
#: and the chain is not entered needlessly.
|
||||
self.done_tau = done_tau
|
||||
self.fail_tau = fail_tau
|
||||
#: The shared speakable budget: every skill's action_log/new_state is
|
||||
#: truncated to this many characters (the same bound the voice front end
|
||||
#: and the humanizer use), so a result fits one message / ~20s of speech
|
||||
#: and the run ledger stays bounded.
|
||||
self.result_chars = result_chars
|
||||
|
||||
# ---- contract resolution ----
|
||||
|
||||
@@ -288,111 +311,98 @@ class SkillRunner:
|
||||
|
||||
def _assess(
|
||||
self, skill: Skill, request: Request, ctx: ActionContext, action
|
||||
) -> tuple[bool, str | None]:
|
||||
"""SemIf assessment: did the run succeed, and should it run again?
|
||||
) -> str:
|
||||
"""SemIf assessment: is there any *additional work* to be done?
|
||||
|
||||
`assess:outcome` decides success (`P(success) >= tau`); a failure is
|
||||
then offered to `assess:requeue`, which picks complete/retry. On retry
|
||||
the original request text is re-dispatched (the scheduler bounds it by
|
||||
`max_reentries`). Both are real logged decision rows. The state carries
|
||||
the skill's declared action, the goal, and the resolved inputs so the
|
||||
decision sees what the skill was meant to do and how its inputs
|
||||
resolved; the requeue state additionally flags a retry that would
|
||||
reproduce the identical observed result as a no-op. The engine is always
|
||||
real: EngineUnavailable propagates to the scheduler, which marks the app
|
||||
fatal.
|
||||
A single three-way `assess:outcome` decision over the step's own action
|
||||
plus the run ledger so far:
|
||||
|
||||
- ``done`` — the request is satisfied (a definitive "nothing found"
|
||||
counts as done);
|
||||
- ``continue`` — the step worked, but the request is not yet satisfied;
|
||||
the scheduler routes the next step (bounded by ``max_reentries`` and
|
||||
the monotonic-progress guard);
|
||||
- ``failed`` — the step errored / did not work → the repair path.
|
||||
|
||||
The verdict uses thresholds, not argmax, with precedence
|
||||
``failed > done > continue`` (``fail_tau`` then ``done_tau``), so a
|
||||
confident success/failure is honored and ``continue`` — the over-trigger
|
||||
— only wins when the model is genuinely unsure. Real logged decision row
|
||||
(phase `assess:outcome`). The state carries the skill's declared action,
|
||||
the goal, the resolved inputs, the (bounded) action log, and the steps
|
||||
already taken. The engine is always real: EngineUnavailable propagates to
|
||||
the scheduler, which marks the app fatal.
|
||||
"""
|
||||
label = f"{skill.category}.{skill.name}"
|
||||
resolved = _resolved_inputs(skill, ctx.config)
|
||||
outcome = DecisionRequest(
|
||||
state=(
|
||||
f"skill: {label}\n"
|
||||
f"skill action: {skill.description}\n"
|
||||
f"goal: {request.text}\n"
|
||||
f"resolved inputs:\n{resolved}\n"
|
||||
f"action log:\n{action.action_log}"
|
||||
),
|
||||
question="Did the skill achieve the user's goal?",
|
||||
observed = bound_output(action.action_log, self.result_chars)
|
||||
if not observed:
|
||||
observed = bound_output(action.new_state, self.result_chars)
|
||||
state = (
|
||||
f"skill: {label}\n"
|
||||
f"skill action: {skill.description}\n"
|
||||
f"goal: {request.text}\n"
|
||||
f"resolved inputs:\n{resolved}\n"
|
||||
f"action log:\n{observed}"
|
||||
)
|
||||
ledger = render_ledger(request.run_ledger)
|
||||
if ledger:
|
||||
state += f"\nsteps already taken:\n{ledger}"
|
||||
decision = DecisionRequest(
|
||||
state=state,
|
||||
question="Is there any additional work to be done to satisfy the request?",
|
||||
options=[
|
||||
Option(
|
||||
"success",
|
||||
"Yes — the skill carried out the request and produced a "
|
||||
"truthful result. A definitive 'nothing found' or 'nothing "
|
||||
"to do' result (empty inbox, no unread messages, no "
|
||||
"matching event) counts as success.",
|
||||
"done",
|
||||
"No — the request is satisfied. A definitive 'nothing found' "
|
||||
"or 'nothing to do' result (empty inbox, no unread messages, "
|
||||
"no matching event) counts as done.",
|
||||
),
|
||||
Option(
|
||||
"failure",
|
||||
"No — the request was not carried out, or the result is an "
|
||||
"error, a refusal, or an unresolved action.",
|
||||
"continue",
|
||||
"Yes — this step worked, but the request is not yet satisfied; "
|
||||
"another skill should run next toward the same request.",
|
||||
),
|
||||
Option(
|
||||
"failed",
|
||||
"The step did not work: the result is an error, a refusal, or "
|
||||
"an unresolved action.",
|
||||
),
|
||||
],
|
||||
)
|
||||
result = self.ctx.engine.call(outcome)
|
||||
result = self.ctx.engine.call(decision)
|
||||
self.log.append(
|
||||
outcome,
|
||||
decision,
|
||||
result,
|
||||
extra={"phase": "assess:outcome", "run_id": request.id, "skill": label},
|
||||
)
|
||||
success = result.prob("success") >= self.tau
|
||||
if success:
|
||||
return True, None
|
||||
|
||||
# A retry that would reproduce the identical observed result is a
|
||||
# guaranteed no-op run (the request, config, and external state are
|
||||
# unchanged), so the requeue decision is told before it can pick
|
||||
# `retry` again — otherwise a deterministic failure loops through the
|
||||
# reentry ladder and ends in a repair offer for a working skill.
|
||||
observed = action.action_log or action.new_state
|
||||
prev = request.meta.get("prev_result")
|
||||
no_progress = ""
|
||||
if prev is not None and prev == observed:
|
||||
no_progress = (
|
||||
"\nAttempts so far produced the identical result; retrying "
|
||||
"would repeat the same run against unchanged state."
|
||||
)
|
||||
requeue = DecisionRequest(
|
||||
state=(
|
||||
f"skill: {label}\n"
|
||||
f"skill action: {skill.description}\n"
|
||||
f"goal: {request.text}\n"
|
||||
f"resolved inputs:\n{resolved}\n"
|
||||
f"action log:\n{action.action_log}\n"
|
||||
"outcome: failed"
|
||||
f"{no_progress}"
|
||||
),
|
||||
question="Is the request complete, or should it run again?",
|
||||
options=[
|
||||
Option("complete", "It is complete; do nothing further."),
|
||||
Option("retry", "Run the original request again."),
|
||||
],
|
||||
)
|
||||
requeue_result = self.ctx.engine.call(requeue)
|
||||
self.log.append(
|
||||
requeue,
|
||||
requeue_result,
|
||||
extra={"phase": "assess:requeue", "run_id": request.id, "skill": label},
|
||||
)
|
||||
updated = request.text if requeue_result.prob("retry") >= self.tau else None
|
||||
return False, updated
|
||||
probs = result.probs
|
||||
if probs.get("failed", 0.0) >= self.fail_tau:
|
||||
return "failed"
|
||||
if probs.get("done", 0.0) >= self.done_tau:
|
||||
return "done"
|
||||
return "continue"
|
||||
|
||||
def _finish(
|
||||
self, skill: Skill, request: Request, ctx: ActionContext, action
|
||||
) -> RunResult:
|
||||
observed = action.new_state
|
||||
action_log = bound_output(action.action_log, self.result_chars)
|
||||
observed = bound_output(action.new_state, self.result_chars)
|
||||
if skill.category in CANNED_CATEGORIES or skill.category in DETERMINISTIC_CATEGORIES:
|
||||
summary = deterministic_summary(
|
||||
skill.category, skill.name, True, action.action_log, observed
|
||||
skill.category, skill.name, True, action_log, observed
|
||||
)
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
success=True,
|
||||
summary=summary,
|
||||
action_log=action.action_log,
|
||||
action_log=action_log,
|
||||
new_state=observed,
|
||||
assessment_summary=summary,
|
||||
outcome="done",
|
||||
)
|
||||
success, updated_request = self._assess(skill, request, ctx, action)
|
||||
verdict = self._assess(skill, request, ctx, action)
|
||||
success = verdict != "failed"
|
||||
|
||||
decisions = getattr(action, "decisions", [])
|
||||
for decision, result in decisions:
|
||||
@@ -408,15 +418,15 @@ class SkillRunner:
|
||||
)
|
||||
|
||||
summary = deterministic_summary(
|
||||
skill.category, skill.name, success, action.action_log, observed
|
||||
skill.category, skill.name, success, action_log, observed
|
||||
)
|
||||
return RunResult(
|
||||
skill=skill.name,
|
||||
success=success,
|
||||
summary=summary,
|
||||
action_log=action.action_log,
|
||||
action_log=action_log,
|
||||
new_state=observed,
|
||||
updated_request=updated_request,
|
||||
outcome=verdict,
|
||||
decisions_logged=len(decisions),
|
||||
assessment_summary=summary,
|
||||
)
|
||||
+123
-30
@@ -575,11 +575,61 @@ def unresolved_variables(
|
||||
return [name for name in (skill.contract or {}) if name not in merged]
|
||||
|
||||
|
||||
def bound_output(text: str, limit: int) -> str:
|
||||
"""Truncate a skill's output to the speakable budget.
|
||||
|
||||
A skill result is read in a text message or heard as speech, so a long
|
||||
result is a bad result: the budget is the one shared bound (the same one the
|
||||
voice front end and the humanizer use). Truncation is at a word boundary and
|
||||
marked with an ellipsis; a non-positive limit disables it. A long *product*
|
||||
of a skill belongs in a file I/O side effect, not in the result string (see
|
||||
CODEGEN.md / TESTGEN.md).
|
||||
"""
|
||||
if limit <= 0 or len(text) <= limit:
|
||||
return text
|
||||
clipped = text[:limit].rsplit(" ", 1)[0] or text[:limit]
|
||||
return clipped + "…"
|
||||
|
||||
|
||||
def render_ledger(entries: list[dict]) -> str:
|
||||
"""Render the run ledger as a compact, deterministic block.
|
||||
|
||||
One line per step: ``N. <category.skill> -> <outcome>``. Same entries, same
|
||||
string. Threaded into the routing/assessment state so a continuation sees
|
||||
what was already done toward the request.
|
||||
"""
|
||||
lines = []
|
||||
for index, entry in enumerate(entries, 1):
|
||||
skill = entry.get("skill") or "?"
|
||||
outcome = (entry.get("outcome") or "").strip()
|
||||
lines.append(f" {index}. {skill} -> {outcome}" if outcome else f" {index}. {skill}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def last_result(request: Request) -> str:
|
||||
"""The most recent chained step's result, or "" on a first-step request.
|
||||
|
||||
A body that runs as a later step of a chain reads this to use what the
|
||||
previous step produced (e.g. a computed value to send) instead of
|
||||
recomputing or fabricating it. The value is the prior step's bounded outcome
|
||||
(its ``action_log`` or ``new_state``) — the same text the run ledger carries
|
||||
and renders into the routing/assessment state.
|
||||
"""
|
||||
ledger = getattr(request, "run_ledger", None) or []
|
||||
if not ledger:
|
||||
return ""
|
||||
return str(ledger[-1].get("outcome") or "")
|
||||
|
||||
|
||||
def compose_state(request: Request, additional_context: str | None = None) -> str:
|
||||
parts = [request.text]
|
||||
if additional_context:
|
||||
parts.append(f"({additional_context})")
|
||||
return " ".join(parts)
|
||||
state = " ".join(parts)
|
||||
ledger = render_ledger(request.run_ledger)
|
||||
if ledger:
|
||||
state = f"{state}\nsteps already taken:\n{ledger}"
|
||||
return state
|
||||
|
||||
|
||||
def _canned_response(name: str, message: str):
|
||||
@@ -1174,6 +1224,7 @@ def navigate(
|
||||
category_tau: float = 0.75,
|
||||
action_tau: float = 0.5,
|
||||
bypass_tau: float = 0.5,
|
||||
skip_actionability: bool = False,
|
||||
) -> Skill | CreateCategory | CreateSkill:
|
||||
"""Descend the tree one SemIf choice per level. Every choice is logged.
|
||||
|
||||
@@ -1226,7 +1277,7 @@ def navigate(
|
||||
"create_category",
|
||||
request.id,
|
||||
state=compose_state(request),
|
||||
question="Which top-level category handles this request?",
|
||||
question="Which category is the logical next step toward satisfying this request?",
|
||||
options=[],
|
||||
selected="create_category",
|
||||
probs={},
|
||||
@@ -1236,8 +1287,10 @@ def navigate(
|
||||
# Actionability first: is this input a request at all? A non-request goes to
|
||||
# the closed `response` tree (a canned reply) and never reaches the category
|
||||
# softmax; a request always proceeds to category selection, so it can never
|
||||
# be canned.
|
||||
if confirm_non_action(engine, log, trace, request, action_tau):
|
||||
# be canned. A **continuation** (a request already carrying a run ledger) is
|
||||
# actionable by construction — it is the next step of an in-flight request —
|
||||
# so it skips this guard; only a fresh first-step input is checked.
|
||||
if not skip_actionability and confirm_non_action(engine, log, trace, request, action_tau):
|
||||
response_skills = tree.get("response")
|
||||
if response_skills:
|
||||
return _navigate_canned(
|
||||
@@ -1247,7 +1300,7 @@ def navigate(
|
||||
"create_category",
|
||||
request.id,
|
||||
state=compose_state(request),
|
||||
question="Which top-level category handles this request?",
|
||||
question="Which category is the logical next step toward satisfying this request?",
|
||||
options=[],
|
||||
selected="create_category",
|
||||
probs={},
|
||||
@@ -1263,7 +1316,7 @@ def navigate(
|
||||
)
|
||||
top = DecisionRequest(
|
||||
state=compose_state(request),
|
||||
question="Which top-level category handles this request?",
|
||||
question="Which category is the logical next step toward satisfying this request?",
|
||||
options=[Option(c, descriptions.get(c, c)) for c in categories]
|
||||
+ [create_category],
|
||||
)
|
||||
@@ -1338,7 +1391,7 @@ def navigate(
|
||||
request,
|
||||
additional_context=f"all choices are within the {category} category",
|
||||
),
|
||||
question=f"Which {category} skill performs the action this request asks for?",
|
||||
question=f"Which {category} skill should run next to help satisfy this request?",
|
||||
options=[Option(s.name, s.description) for s in skills],
|
||||
)
|
||||
leaf_result = engine.call(leaf)
|
||||
@@ -1482,36 +1535,67 @@ def confirm_skill_fit(
|
||||
request: Request,
|
||||
skill: Skill,
|
||||
tau: float = 0.6,
|
||||
) -> bool:
|
||||
"""Does this skill's action actually match what the request asks for?
|
||||
) -> str:
|
||||
"""What does this skill do for the request? "same" | "part" | "different".
|
||||
|
||||
Navigation picks the closest existing leaf; this guard is now the **sole**
|
||||
Navigation picks the closest existing leaf; this guard is the **sole**
|
||||
leaf-level reuse-vs-create decision (create_skill is no longer an option in
|
||||
the leaf softmax). If the skill's action is not the same action the request
|
||||
asks for, dispatch authors a new leaf instead. The threshold is
|
||||
`navigation.intent_tau` (deliberately separate from the run-assessment
|
||||
`tau`, so tuning reuse-vs-create does not move assessment/fidelity).
|
||||
the leaf softmax). It answers three ways:
|
||||
|
||||
Wording tuned against the real model: comparing the two *actions*
|
||||
("different action") is unambiguous where "can this serve the request" was
|
||||
not — e.g. "message Sam" (an implicit send in instant-messaging syntax)
|
||||
reads as a different action from "read the next message". Do not add an
|
||||
instant-messaging context hint: it over-fires and pulls read phrasings to
|
||||
the send side. The comparison is over-permissive on near-synonyms (read vs
|
||||
send score "same" ~0.74-0.78), so it is paired with the softmax that
|
||||
disambiguates them — the guard only ever sees the softmax winner.
|
||||
- ``same`` — the skill performs the next action the request needs (running it
|
||||
can satisfy the request, or is its final step);
|
||||
- ``part`` — the request needs more than one action and this skill performs
|
||||
one required part of it;
|
||||
- ``different`` — the skill does not do any action the request asks for;
|
||||
dispatch authors a new leaf instead.
|
||||
|
||||
``same``/``part`` run the skill; ``different`` is the create door. The guard
|
||||
only decides whether the skill *contributes* — whether more work remains is
|
||||
``assess:outcome``'s call (the guard must never force a continuation: in a
|
||||
real run it labeled the final send step ``part`` 0.85 while the assessment
|
||||
correctly said ``done`` 0.99, and a forced continue drove the chain into a
|
||||
spurious new category). The **run ledger is part of the state** so a later
|
||||
step judges against the *remaining* work, not the whole request. Without the
|
||||
ledger a compound request has no single skill that is ``same``, so the guard
|
||||
would author a monolithic skill for every one of them — the bug this fixes (a
|
||||
real run picked ``calculator.calculate`` at 0.99 and was rejected into
|
||||
create_skill).
|
||||
|
||||
The threshold is ``navigation.intent_tau`` (deliberately separate from the
|
||||
run-assessment ``tau``, so tuning reuse-vs-create does not move
|
||||
assessment/fidelity). Wording tuned against the real model: comparing the
|
||||
two *actions* is unambiguous where "can this serve the request" was not.
|
||||
Do not add an instant-messaging context hint: it over-fires and pulls read
|
||||
phrasings to the send side.
|
||||
"""
|
||||
state = (
|
||||
f"Requested action: {request.text}\n"
|
||||
f"Action of the existing skill: {skill.description}"
|
||||
)
|
||||
ledger = render_ledger(request.run_ledger)
|
||||
if ledger:
|
||||
state += f"\nsteps already taken:\n{ledger}"
|
||||
decision = DecisionRequest(
|
||||
state=(
|
||||
f"Requested action: {request.text}\n"
|
||||
f"Action of the existing skill: {skill.description}"
|
||||
state=state,
|
||||
question=(
|
||||
"Given the steps already taken, what does this skill do for the "
|
||||
"request?"
|
||||
),
|
||||
question="Compare the requested action and the skill's action. Are they the same action?",
|
||||
options=[
|
||||
Option("same", "Same action."),
|
||||
Option(
|
||||
"same",
|
||||
"It performs the next action the request needs and can satisfy "
|
||||
"the request (or is its final step).",
|
||||
),
|
||||
Option(
|
||||
"part",
|
||||
"The request needs more than one action; this skill performs one "
|
||||
"required part of it, and more steps remain after it.",
|
||||
),
|
||||
Option(
|
||||
"different",
|
||||
"Different action: the skill does not do what the user asks.",
|
||||
"It does not do any action the request asks for; a new skill is "
|
||||
"needed.",
|
||||
),
|
||||
],
|
||||
)
|
||||
@@ -1525,7 +1609,15 @@ def confirm_skill_fit(
|
||||
"skill": f"{skill.category}.{skill.name}",
|
||||
},
|
||||
)
|
||||
fits = result.prob("same") >= tau
|
||||
same = result.prob("same")
|
||||
part = result.prob("part")
|
||||
fits = (same + part) >= tau
|
||||
if not fits:
|
||||
verdict = "different"
|
||||
elif same >= part:
|
||||
verdict = "same"
|
||||
else:
|
||||
verdict = "part"
|
||||
trace.append(
|
||||
"intent_guard",
|
||||
request.id,
|
||||
@@ -1533,9 +1625,10 @@ def confirm_skill_fit(
|
||||
skill=skill.name,
|
||||
selected=result.selected,
|
||||
probs=result.probs,
|
||||
verdict=verdict,
|
||||
fits=fits,
|
||||
)
|
||||
return fits
|
||||
return verdict
|
||||
|
||||
|
||||
def tree_summary(tree: dict[str, list[Skill]]) -> str:
|
||||
|
||||
@@ -413,12 +413,14 @@ function eventNode(evt) {
|
||||
body.className = "node-question";
|
||||
if (evt.kind === "assessed") {
|
||||
body.textContent = evt.summary || "";
|
||||
if (evt.updated_request) {
|
||||
const req = document.createElement("div");
|
||||
req.className = "muted";
|
||||
req.textContent = `→ requeued: ${evt.updated_request}`;
|
||||
node.appendChild(req);
|
||||
}
|
||||
} else if (evt.kind === "continued") {
|
||||
body.textContent = `→ next step: ${evt.skill || ""}`;
|
||||
const outcome = document.createElement("div");
|
||||
outcome.className = "muted";
|
||||
outcome.textContent = `outcome: ${evt.outcome || ""}`;
|
||||
node.appendChild(outcome);
|
||||
} else if (evt.kind === "chain_halted") {
|
||||
body.textContent = `chain halted (${evt.reason || ""})`;
|
||||
} else if (evt.kind === "queued") {
|
||||
body.textContent = "queued";
|
||||
} else if (evt.kind === "dropped") {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
scheduler.
|
||||
|
||||
Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events
|
||||
(submit, dropped, queued, dequeued, assessed, requeued, ...) live here in
|
||||
(submit, dropped, queued, dequeued, assessed, continued, ...) live here in
|
||||
`runs.jsonl`, keyed by `run_id` (the request id) so the dashboard can rebuild
|
||||
each run's flow without touching the decision-log contract. Both files are
|
||||
append-only; replays read them in order.
|
||||
|
||||
Reference in new issue
Block a user