feat(hub): answer AskUserQuestion in the hub with a signed pick
The permission hook mirrors every question of an AskUserQuestion call as one hub decision (POST /api/decisions, hooked, multi for multiSelect, recommended from the (Recommended) labels) and waits for its pick. Once the operator's pinned passkey signed the pick of every question, checked locally in signature-counter order, the allow carries updatedInput with the answers, multi picks joined by ', '. A hub that does not answer, an expired decision or a pick whose signature fails leaves the terminal dialog untouched. choosing.picks accepts one label, ordered multi labels joined by a newline, or for a hooked decision one trimmed line of other text; decision_status expires a hooked decision whose wait ran out, and the state view and Match drop expired ones. decision_request shares choice_of with the hook; the answer text moves to signing.choice_text unchanged. Rebased from its lane base2754568ontof95196c: the scan copy's diff against2aea6d1would have reverted the release-flash fix, so the bundle was re-exported against 2754568; conflicts in view.py (reasons next to the decision_status filter) and page-match.js (toggles next to epoch and the ux constants) keep both sides. ruff and node --check pass. Tests: test_hub_questions (210 lines) and test_question_multi_e2e. Written, not run: the full suite runs once on master after all bundles (operator order). Security: MEDUSA over the staged tree on master: 100, no findings over 17 files; index.html.j2 is not covered and was read by hand (one style rule). 🎯 Fix: 90 % 💥 Break: 5 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 86 🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f95196ca82
commit
a6eee78165
18 files changed
+763
-64
No files matched your search
@@ -4,7 +4,14 @@ import secrets
|
||||
import time
|
||||
|
||||
from .asking import ask_state
|
||||
from .choosing import answer_signed, answered, row_answer_signed
|
||||
from .choosing import (
|
||||
PICKED,
|
||||
answer_signed,
|
||||
answered,
|
||||
decision_status,
|
||||
picks,
|
||||
row_answer_signed,
|
||||
)
|
||||
from .cleanup import cleanup_request
|
||||
from .denying import (
|
||||
DENIABLE,
|
||||
@@ -268,13 +275,14 @@ class Approving:
|
||||
record = {"review": self.reviews, "ask": self.asks, "decision": self.decisions, "rule": self.rule_requests}[kind_name].get(item_id)
|
||||
if record is None:
|
||||
raise Missing(item_id)
|
||||
status = ask_state(record, time.time())["status"] if kind_name == "ask" else request_status(record, time.time()) if kind_name == "rule" else record["status"]
|
||||
status = ask_state(record, time.time())["status"] if kind_name == "ask" else request_status(record, time.time()) if kind_name == "rule" else decision_status(record, time.time()) if kind_name == "decision" else record["status"]
|
||||
if status != "pending":
|
||||
raise Conflict({"id": item_id, "status": status})
|
||||
label = ""
|
||||
if kind_name == "decision":
|
||||
if verb != "approve" or raw["label"] not in [option["label"] for option in record["options"]]:
|
||||
raise ToolError("a decision is approved with one of its option labels")
|
||||
if verb != "approve" or not picks(record, raw["label"]):
|
||||
raise ToolError("a decision is approved with one of its option labels, a multi decision with one or more of them in option order, a hook question also with one line of other text")
|
||||
visible([{"label": part} for part in raw["label"].split(PICKED)])
|
||||
label = raw["label"]
|
||||
if kind_name == "rule":
|
||||
return inbox_item(raw, "", f"Rule {request_words(record)}", "", request_signed(record), self.requester(raw, record["agent"]))
|
||||
|
||||
@@ -2,7 +2,8 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from .choosing import EVERYONE, answer_text
|
||||
from .choosing import EVERYONE, PICKED, answer_text, decision_status
|
||||
from .council import agent, read_claims
|
||||
from .diffs import sealed_file, store_diff, store_sealed, valid_diff, valid_sealed
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import (
|
||||
@@ -26,6 +27,7 @@ ASK_LIFETIME = 3600
|
||||
PREVIEW_LIMIT = 4000
|
||||
ASK_TEXTS = {"command": COMMAND_LIMIT, "cwd": PATH_LIMIT, "session": 200, "agent": 200}
|
||||
ANSWERS = {"allow": "allowed", "deny": "denied"}
|
||||
RECOMMENDED = "(Recommended)"
|
||||
|
||||
|
||||
def ask_state(ask: dict, now: float) -> dict:
|
||||
@@ -71,6 +73,22 @@ def option_of(option: object) -> dict:
|
||||
return {"label": label, "description": description, **({"preview": preview} if preview.strip() else {})}
|
||||
|
||||
|
||||
def choice_of(arguments: dict) -> tuple[str, list[dict]]:
|
||||
"""Returns:
|
||||
The question and the options of a decision, each passed by
|
||||
option_of(), once the labels are distinct.
|
||||
"""
|
||||
question = message_text(arguments, "question")
|
||||
visible({"question": question})
|
||||
options = arguments["options"]
|
||||
if not isinstance(options, list) or not 1 <= len(options) <= OPTION_LIMIT:
|
||||
raise ToolError(f"options must be a list of 1 to {OPTION_LIMIT} objects")
|
||||
parsed = [option_of(option) for option in options]
|
||||
if len({option["label"] for option in parsed}) != len(parsed):
|
||||
raise ToolError("option labels must be distinct")
|
||||
return question, parsed
|
||||
|
||||
|
||||
class Asking:
|
||||
def ask(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
@@ -122,16 +140,52 @@ class Asking:
|
||||
return ask_state(decided, time.time())
|
||||
raise Missing(verb)
|
||||
|
||||
def question(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"question", "options", "session", "timeout", "multi"}: one
|
||||
question of an AskUserQuestion call the permission hook
|
||||
mirrors as a decision; it expires after timeout seconds, a
|
||||
multi one takes several options as a pick (choosing.picks),
|
||||
its recommendation is the options labelled RECOMMENDED
|
||||
(the first of them for a single one), and a signed pick is
|
||||
kept for the hook instead of being posted.
|
||||
"""
|
||||
payload = decode(body)
|
||||
expect(payload, ("question", "options", "session", "timeout", "multi"))
|
||||
question, parsed = choice_of(payload)
|
||||
multi = payload["multi"]
|
||||
if not isinstance(multi, bool):
|
||||
raise ToolError("multi must be true or false")
|
||||
session = bounded(payload, "session", ASK_TEXTS["session"]).strip()
|
||||
if not session:
|
||||
raise ToolError("session must not be empty")
|
||||
visible({"session": session})
|
||||
created = time.time()
|
||||
asker = self.directory(read_claims(self.council), [], created).now(session) or session
|
||||
if EVERYONE in asker:
|
||||
raise ToolError(f"the asking session's name holds {EVERYONE}")
|
||||
marked = [option["label"] for option in parsed if option["label"].endswith(RECOMMENDED)]
|
||||
recommended = PICKED.join(marked) if multi else next(iter(marked), "")
|
||||
fields = {"question": question, "options": parsed, "agent": asker, "recommended": recommended, "session": session, "hooked": True, "multi": multi}
|
||||
record = self.decisions.add({**fields, "status": "pending", "choice": None, "decided": None, "proof": None, "created_ts": created, "expires": created + seconds(payload, "timeout", ASK_LIFETIME)})
|
||||
return {"id": record["id"], "status": record["status"]}
|
||||
|
||||
def question_wait(self, decision_id: str, query: dict[str, list[str]]) -> dict:
|
||||
"""Returns:
|
||||
The state of a decision the permission hook asked: status
|
||||
(pending, decided or expired), the choice, the operator's
|
||||
signature over the pick and the to it was signed for.
|
||||
"""
|
||||
wait = instant(query, "wait")
|
||||
record = self.decisions.get(decision_id)
|
||||
if record is None or not record.get("hooked"):
|
||||
raise Missing(decision_id)
|
||||
record = self.decisions.wait(decision_id, min(wait or 0.0, WAIT_CAP, max(record["expires"] - time.time(), 0.0)))
|
||||
return {"id": decision_id, "status": decision_status(record, time.time()), "choice": record["choice"], "proof": record["proof"], "to": agent(record["agent"])}
|
||||
|
||||
def decision_request(self, arguments: dict) -> dict:
|
||||
expect(arguments, ("question", "options", "agent", "recommended"))
|
||||
question = message_text(arguments, "question")
|
||||
visible({"question": question})
|
||||
options = arguments["options"]
|
||||
if not isinstance(options, list) or not 1 <= len(options) <= OPTION_LIMIT:
|
||||
raise ToolError(f"options must be a list of 1 to {OPTION_LIMIT} objects")
|
||||
parsed = [option_of(option) for option in options]
|
||||
if len({option["label"] for option in parsed}) != len(parsed):
|
||||
raise ToolError("option labels must be distinct")
|
||||
question, parsed = choice_of(arguments)
|
||||
recommended = arguments["recommended"]
|
||||
if not isinstance(recommended, str) or recommended.strip() not in ["", *(option["label"] for option in parsed)]:
|
||||
raise ToolError("recommended must be one of the option labels or an empty string")
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from .council import agent
|
||||
from .errors import ToolError
|
||||
from .fields import decode, expect, field
|
||||
@@ -12,23 +14,52 @@ CHOICE_REQUEST = "send me your open decisions as choices"
|
||||
CHANNELS = {**DIRECT, **TO_ALL}
|
||||
CHOICE_KEYS = ("class", "to")
|
||||
RECIPIENT_LIMIT = 40
|
||||
ANSWER_CLASS = "post"
|
||||
QUESTION_SHOWN = 200
|
||||
ANSWER_CLASS = signing.CHOICE_CLASS
|
||||
PICKED = signing.PICKED
|
||||
OTHER_LIMIT = 1000
|
||||
|
||||
|
||||
def picks(decision: dict, label: str) -> bool:
|
||||
"""Args:
|
||||
label: the answer to a decision: one option label, or for a multi
|
||||
decision one or more labels in option order, joined by PICKED,
|
||||
which no label holds; for a decision the permission hook asked
|
||||
also one line of free text up to OTHER_LIMIT characters, trimmed
|
||||
and no option label.
|
||||
|
||||
Returns:
|
||||
Whether label is a valid answer to the decision.
|
||||
"""
|
||||
labels = [option["label"] for option in decision["options"]]
|
||||
if decision.get("hooked") and PICKED not in label and label not in labels:
|
||||
return 0 < len(label) <= OTHER_LIMIT and label == label.strip()
|
||||
if not decision.get("multi"):
|
||||
return label in labels
|
||||
parts = label.split(PICKED)
|
||||
return [found for found in labels if found in parts] == parts
|
||||
|
||||
|
||||
def decision_status(decision: dict, now: float) -> str:
|
||||
"""Returns:
|
||||
The decision's status, expired for a pending one the permission hook
|
||||
asked whose wait ran out.
|
||||
"""
|
||||
return "expired" if decision["status"] == "pending" and decision.get("expires", now + 1) <= now else decision["status"]
|
||||
|
||||
|
||||
def answer_text(decision: dict, label: str) -> str:
|
||||
question = " ".join(decision["question"].split())[:QUESTION_SHOWN]
|
||||
return f"Choice for decision {decision['id']} ({question}): {label}"
|
||||
return signing.choice_text(decision["id"], decision["question"], label)
|
||||
|
||||
|
||||
def answer_signed(decision: dict, label: str) -> dict:
|
||||
"""Returns:
|
||||
The post to the asking agent that a click on the option label
|
||||
signs: the operator's answer operator_message proves.
|
||||
signs: the operator's answer operator_message proves, or for a
|
||||
decision the permission hook asked, the one it verifies itself.
|
||||
"""
|
||||
if EVERYONE in decision["agent"]:
|
||||
raise ToolError(f"a choice answer goes to the asking agent, never to a name with {EVERYONE}")
|
||||
return signing.message_item(agent(decision["agent"]), ANSWER_CLASS, answer_text(decision, label), "", "", "")
|
||||
return signing.choice_item(agent(decision["agent"]), decision["id"], decision["question"], label)
|
||||
|
||||
|
||||
def row_answer_signed(row: dict, to: str, label: str) -> dict:
|
||||
@@ -108,9 +139,13 @@ class Choosing:
|
||||
record = self.decisions.get(item["id"])
|
||||
if record is None:
|
||||
return "unknown"
|
||||
if record["status"] != "pending":
|
||||
return f"already {record['status']}"
|
||||
status = decision_status(record, time.time())
|
||||
if status != "pending":
|
||||
return f"already {status}"
|
||||
self.operator_proven(proof, item["signed"])
|
||||
if record.get("hooked"):
|
||||
decided, changed = self.decisions.decide(item["id"], {"status": "decided", "choice": item["label"], "proof": proof})
|
||||
return "decided · answered through the permission hook" if changed else f"already {decided['status']}"
|
||||
message = self.stored_message(item["signed"], proof, None)
|
||||
decided, changed = self.decisions.decide(item["id"], {"status": "decided", "choice": item["label"], "message": message["id"]})
|
||||
if not changed:
|
||||
|
||||
@@ -29,7 +29,8 @@ UPLOADS = "/api/uploads"
|
||||
MATCH_ROUTE = "/api/match"
|
||||
PREVIEWS_ROUTE = "/api/runner/previews"
|
||||
MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"}
|
||||
POSTS = ("/api/asks", UPLOADS, "/api/messages", *MATCH_POSTS)
|
||||
HOOK_POSTS = {"/api/asks": "ask", "/api/decisions": "question"}
|
||||
POSTS = (*HOOK_POSTS, UPLOADS, "/api/messages", *MATCH_POSTS)
|
||||
STORED = {
|
||||
"page": (".html", "text/html; charset=utf-8", PAGE_CSP),
|
||||
"files": (".json", "application/json", PLAIN_CSP),
|
||||
@@ -155,8 +156,8 @@ class Handler(Exchange):
|
||||
self.send_text(HTTPStatus.FORBIDDEN, "forbidden: the runner calls with the X-Kvb-Orchestrator header and no origin only")
|
||||
elif entry:
|
||||
self.answer(lambda: hub.entry(int(entry.group(1))), HTTPStatus.OK)
|
||||
elif item and item.group(1) == "asks" and item.group(3) is None:
|
||||
self.answer(lambda: hub.ask_wait(item.group(2), self.query()), HTTPStatus.OK)
|
||||
elif item and item.group(3) is None:
|
||||
self.answer(lambda: (hub.ask_wait if item.group(1) == "asks" else hub.question_wait)(item.group(2), self.query()), HTTPStatus.OK)
|
||||
elif route and route.group(2) in STORED:
|
||||
self.stored(route.group(1), route.group(2))
|
||||
elif route or item or path == "/mcp" or path in POSTS or path in ACTION_POSTS or BOARD.fullmatch(path) or self.posted(path):
|
||||
@@ -281,10 +282,9 @@ class Handler(Exchange):
|
||||
"""
|
||||
if path == "/mcp":
|
||||
return self.mcp_receiver(host)
|
||||
if path == "/api/asks" or path in MATCH_POSTS:
|
||||
if path in HOOK_POSTS or path in MATCH_POSTS:
|
||||
if self.local(host):
|
||||
hub = self.server.hub
|
||||
receive = getattr(hub, MATCH_POSTS[path]) if path in MATCH_POSTS else hub.ask
|
||||
receive = getattr(self.server.hub, MATCH_POSTS.get(path) or HOOK_POSTS[path])
|
||||
return lambda body: self.answer(lambda: receive(body), HTTPStatus.OK if path in MATCH_POSTS else HTTPStatus.CREATED)
|
||||
self.send_text(HTTPStatus.FORBIDDEN, "forbidden: local POST with the X-Kvb-Orchestrator header and no foreign origin only")
|
||||
return None
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
import time
|
||||
|
||||
from .approving import INBOX_KINDS
|
||||
from .choosing import answered
|
||||
from .choosing import answered, decision_status
|
||||
from .council import read_claims
|
||||
from .denying import requester_of
|
||||
from .errors import ToolError
|
||||
@@ -21,7 +21,7 @@ SNOOZE_LIMIT = 8 * 86400
|
||||
class Inbox:
|
||||
def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]:
|
||||
claims = read_claims(self.council)
|
||||
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": ""}
|
||||
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "other": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": ""}
|
||||
items = []
|
||||
for review in self.reviews.pending():
|
||||
created = iso_epoch(review["created"]) or now
|
||||
@@ -33,9 +33,9 @@ class Inbox:
|
||||
warnings = signing.warnings(ask["command"])
|
||||
fields = {"title": f"{ask['tool']}: {ask['command'][:200]}", "agent": directory.now(ask["session"]), "to": requester_of(claims, ask["session"])[0], "green": not warnings, "warnings": warnings, "deniable": True, "diff": ask.get("diff_files")}
|
||||
items.append({**base, "kind": "ask", "id": ask["id"], "ts": ask["created_ts"], **fields, "command": ask["command"], "directory": ask["cwd"]})
|
||||
for decision in self.decisions.pending():
|
||||
for decision in (decision for decision in self.decisions.pending() if decision_status(decision, now) == "pending"):
|
||||
recommended = decision.get("recommended", "")
|
||||
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended}
|
||||
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi")), "other": bool(decision.get("hooked"))}
|
||||
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
|
||||
held = self.open_jobs()
|
||||
consoles = self.consoles()
|
||||
|
||||
@@ -147,7 +147,7 @@ class Matching:
|
||||
"born": born, "created_ts": item["ts"], "repo": repo, "branch": branch, "worktree": worktree, "title": item["title"], "score": "",
|
||||
"metrics": metric_chips("\n".join((item["title"], item["command"], item["detail"])), labels, False), "gate": "", "hash": shown, "live_hash": shown, "stale": False, "stale_reason": "",
|
||||
"files": files, "command": item["command"], "directory": item["directory"], "reason": item["detail"], "sha256": item["sha256"], "options": item["options"],
|
||||
"recommended": item["recommended"], "warnings": item["warnings"], "rule": item["rule"], "dry_run": item["dry_run"],
|
||||
"recommended": item["recommended"], "multi": item["multi"], "other": item["other"], "warnings": item["warnings"], "rule": item["rule"], "dry_run": item["dry_run"],
|
||||
}
|
||||
|
||||
def command_card(self, row: dict, agent: str, born: float | None, roots: list[str] | None, scan: dict, labels: dict | None) -> dict:
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import time
|
||||
|
||||
from .asking import ask_state
|
||||
from .choosing import decision_status
|
||||
from .council import MAYDAY_ACTIVE, NEWS, message_rows, read_claims, sessions
|
||||
from .crons import cron_event
|
||||
from .errors import Missing, ToolError
|
||||
@@ -73,12 +74,13 @@ class Timeline:
|
||||
who = {"agent": directory.at(ask["session"], ask["created_ts"]), "now": directory.now(ask["session"]), "session": ask["session"]}
|
||||
rows.append(event({"id": f"ask:{ask['id']}", "ts": ask["created_ts"], "kind": "ask", **who, "title": ask["tool"], "text": ask["command"], "waiting": state["status"] == "pending", "ref": ref}))
|
||||
for decision in self.decisions.listed():
|
||||
if decision["created_ts"] <= end and (decision["status"] == "pending" or decision["created_ts"] >= begin):
|
||||
ref = {key: decision.get(key, "") for key in ("id", "status", "choice", "recommended", "options")}
|
||||
status = decision_status(decision, now)
|
||||
if decision["created_ts"] <= end and (status == "pending" or decision["created_ts"] >= begin):
|
||||
ref = {**{key: decision.get(key, "") for key in ("id", "choice", "recommended", "options")}, "status": status}
|
||||
text = " · ".join(option["label"] for option in decision["options"])
|
||||
source = directory.key(decision["agent"], decision["created_ts"])
|
||||
who = {"agent": directory.at(source, decision["created_ts"]) or decision["agent"], "now": directory.now(source), "session": source}
|
||||
rows.append(event({"id": f"decision:{decision['id']}", "ts": decision["created_ts"], "kind": "decision", **who, "title": decision["question"][:300], "text": text, "waiting": decision["status"] == "pending", "ref": ref}))
|
||||
rows.append(event({"id": f"decision:{decision['id']}", "ts": decision["created_ts"], "kind": "decision", **who, "title": decision["question"][:300], "text": text, "waiting": status == "pending", "ref": ref}))
|
||||
held = self.open_jobs()
|
||||
for row in operator_rows(tasks):
|
||||
first = self.watch.first(row["task"], now)
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import time
|
||||
|
||||
from .asking import ask_row, decision_row
|
||||
from .choosing import decision_status
|
||||
from .council import (
|
||||
MAYDAY_ACTIVE,
|
||||
NEWS,
|
||||
@@ -160,7 +161,7 @@ class View:
|
||||
"alarm_since": end - MAYDAY_ACTIVE,
|
||||
"reviews": [row for row in map(review_row, self.reviews.pending()) if row["created_ts"] <= end],
|
||||
"asks": [ask_row(ask, names) for ask in self.asks.pending() if ask["expires"] > now and ask["created_ts"] <= end],
|
||||
"decisions": [decision_row(decision) for decision in self.decisions.pending() if decision["created_ts"] <= end],
|
||||
"decisions": [decision_row(decision) for decision in self.decisions.pending() if decision_status(decision, now) == "pending" and decision["created_ts"] <= end],
|
||||
"messages": [{**message_row(message), **read_of(inlined, epoch(message.get("relay_ts")))} for message in stored if begin <= message["created_ts"] <= end],
|
||||
"reasons": recent_reasons(stored),
|
||||
"operator": operator_rows(tasks),
|
||||
|
||||
Reference in new issue
Block a user