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 base 2754568 onto f95196c: the scan copy's diff against 2aea6d1 would 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:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-22 15:02:23 +00:00
1 parent f95196ca82
commit a6eee78165
18 files changed
+763 -64

No files matched your search

+110 -1
View File
@@ -30,7 +30,10 @@ Returns:
Any other Bash command that may run git commit (-a, --all, -i, -o,
-p, a pathspec, a chain, a wrapper) is not approvable: no ask
reaches the hub, stderr gets WORKTREE and Claude Code shows its own
dialog.
dialog. An AskUserQuestion call becomes one hub decision per
question; once a pinned passkey signed the pick of every question,
the allow carries updatedInput with the questions and their
answers, the labels of a multi-select pick joined by ", ".
"""
from __future__ import annotations
@@ -45,6 +48,7 @@ from pathlib import Path
import hub_api
import hub_limits
import passkey
import signing
import staged_diff
import verifier
@@ -61,6 +65,8 @@ WORKTREE = "commit reads the working tree; stage the files and commit the index"
ALLOW = {"behavior": "allow"}
REASON_LIMIT = 2000
FAILURES = (OSError, ValueError, staged_diff.DiffError)
QUESTION_TOOL = "AskUserQuestion"
OPTION_KEYS = ("label", "description", "preview")
def summary(tool_input: object) -> str:
@@ -228,6 +234,103 @@ def decision(answer: dict, item: dict, trust: verifier.Trust) -> dict | None:
return {"behavior": "allow"}
def asked_questions(hook: dict) -> list[dict] | None:
"""Returns:
The questions of an AskUserQuestion call, None for any other tool
call and for input of another shape.
"""
if hook.get("tool_name") != QUESTION_TOOL or not isinstance(hook.get("tool_input"), dict):
return None
questions = hook["tool_input"].get("questions")
if not isinstance(questions, list) or not questions:
return None
if not all(isinstance(question, dict) and isinstance(question.get("question"), str) and isinstance(question.get("options"), list) for question in questions):
print("kvb-orchestrator: a malformed question stays in the terminal", file=sys.stderr)
return None
return questions
def ask_question(base: str, question: dict, session: str, timeout: float) -> str:
options = [{key: option[key] for key in OPTION_KEYS if key in option} if isinstance(option, dict) else option for option in question["options"]]
data = encoded({"question": question["question"], "options": options, "session": session, "timeout": timeout, "multi": question.get("multiSelect") is True})
request = urllib.request.Request(f"{base}/api/decisions", data=data, headers={"Content-Type": "application/json", **hub_api.GUARD}, method="POST")
decision_id = hub_api.call(request, hub_api.SLACK)["id"]
if not isinstance(decision_id, str) or not signing.ID.fullmatch(decision_id):
raise ValueError("the hub answered no decision id")
return decision_id
def picked(base: str, decision_id: str, question: dict, deadline: float) -> tuple[dict, str] | None:
"""Returns:
The hub's decided answer for the decision decision_id and the answer
to the question it holds, its signature not yet checked: the
option's label, for a multi-select question the picked labels in
option order joined by ", ", or the one line of other text that
names no option; None when the decision expires, the deadline
passes or a multi-line pick holds a line that is no option of the
question.
"""
answer = {"status": "pending"}
while answer["status"] == "pending" and (left := deadline - time.monotonic()) > 0:
wait = min(left, POLL)
answer = hub_api.call(urllib.request.Request(f"{base}/api/decisions/{decision_id}?wait={wait:.1f}"), wait + hub_api.SLACK)
if not isinstance(answer.get("status"), str):
raise TypeError("the hub answered no status")
choice, to = answer.get("choice"), answer.get("to")
if answer["status"] != "decided" or not isinstance(choice, str) or not isinstance(to, str):
return None
labels = [option["label"] for option in question["options"] if isinstance(option, dict) and isinstance(option.get("label"), str)]
parts = choice.split(signing.PICKED) if question.get("multiSelect") is True else [choice]
chosen = [label for label in labels if label.strip() in parts]
other = signing.PICKED not in choice and not chosen
if [label.strip() for label in chosen] != parts and not other:
return None
return answer, choice if other else ", ".join(chosen)
def counter_of(answer: dict) -> int:
"""Returns:
The signature counter the pick's assertion claims, unchecked: it only
orders the signature checks, so the picks of an authenticator that
counts up pass in the order they were signed; 0 when it cannot be read.
"""
try:
data = passkey.b64decode(answer["proof"]["assertion"]["authenticatorData"], "authenticatorData")
except (signing.Refused, KeyError, TypeError):
return 0
return int.from_bytes(data[33:37], "big")
def signed(answer: dict, decision_id: str, question: dict, trust: verifier.Trust) -> bool:
try:
verifier.check(answer.get("proof"), signing.choice_item(answer["to"], decision_id, question["question"], answer["choice"]), "", trust, time.time())
except (signing.Refused, OSError) as error:
print(f"kvb-orchestrator: the pick is not signed, Claude Code asks instead: {error}", file=sys.stderr)
return False
return True
def answers_of(base: str, hook: dict, questions: list[dict], timeout: float, trust: verifier.Trust, deadline: float) -> dict | None:
"""Returns:
The PermissionRequest allow that answers every question with the
option the operator picked and signed in the Agent Orchestrator;
None as soon as one question goes unanswered or one signature does
not hold.
"""
session = str(hook.get("session_id") or "")
asked = [(ask_question(base, question, session, timeout), question) for question in questions]
picks = []
for decision_id, question in asked:
pick = picked(base, decision_id, question, deadline)
if pick is None:
return None
picks.append((decision_id, question, *pick))
for decision_id, question, answer, _ in sorted(picks, key=lambda pick: counter_of(pick[2])):
if not signed(answer, decision_id, question, trust):
return None
return {"behavior": "allow", "updatedInput": {**hook["tool_input"], "answers": {question["question"]: label for _, question, _, label in picks}}}
def main() -> int:
parser = argparse.ArgumentParser(prog="permission_hook")
parser.add_argument("--port", type=int, required=True)
@@ -240,6 +343,12 @@ def main() -> int:
deadline = time.monotonic() + args.timeout
try:
hook = json.load(sys.stdin)
questions = asked_questions(hook)
if questions is not None:
chosen = answers_of(base, hook, questions, args.timeout, trust, deadline)
if chosen is not None:
print(json.dumps({"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": chosen}}))
return 0
ask = facts(hook)
too_long = [name for name, limit in LIMITS.items() if len(ask[name]) > limit]
if too_long:
+19
View File
@@ -28,6 +28,9 @@ TASK = re.compile(r"[a-z0-9][a-z0-9._-]{0,99}(?:/[a-z0-9][a-z0-9._-]{0,99}){0,7}
PRIO = re.compile(r"[1-9][0-9]{0,2}")
FIBONACCI = ("1", "2", "3", "5", "8", "13", "21", "34", "55", "89")
ESTIMATOR = "Operator"
CHOICE_CLASS = "post"
QUESTION_SHOWN = 200
PICKED = "\n"
COMMANDS = "operator/"
STATUSES = ("queued", "running", "blocked", "done", "stopped")
GATE_LEVELS = ("none", "quick", "test", "quality-high", "e2e")
@@ -179,6 +182,22 @@ def message_item(to: str, cls: str, text: str, upload: str, voice: str, voice_sh
return {"kind": "message", "to": to, "class": cls, "text": text, "upload": upload, "voice": voice, "voice_sha256": voice_sha256}
def choice_text(decision_id: str, question: str, label: str) -> str:
shown = " ".join(question.split())[:QUESTION_SHOWN]
return f"Choice for decision {decision_id} ({shown}): {label}"
def choice_item(to: str, decision_id: str, question: str, label: str) -> dict:
"""Args:
to: the asking agent the answer is posted to.
Returns:
The post that a pick of the option label of the decision decision_id
signs, its question on one line and cut at QUESTION_SHOWN.
"""
return message_item(to, CHOICE_CLASS, choice_text(decision_id, question, label), "", "", "")
def board_item(action: str, agents: list[str]) -> dict:
"""Args:
action: the board action.
+12 -4
View File
@@ -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"]))
+63 -9
View File
@@ -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")
+43 -8
View File
@@ -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:
+6 -6
View File
@@ -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
+4 -4
View File
@@ -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()
+1 -1
View File
@@ -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:
+5 -3
View File
@@ -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)
+2 -1
View File
@@ -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),
+1
View File
@@ -364,6 +364,7 @@ textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
.option { display: grid; gap: 2px; padding: 8px 11px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); text-align: left; cursor: pointer; }
.option:hover { background: var(--accent-soft); border-color: var(--accent); }
.option.recommended { border-color: var(--ok); box-shadow: inset 3px 0 0 var(--ok); }
.option[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent); }
.option span { color: var(--muted); font-size: var(--fs-sm); }
.option:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.option.other { display: flex; gap: 6px; align-items: center; cursor: default; }
+3
View File
@@ -27,6 +27,9 @@
const short = (text) => (text.length > 80 ? `${text.slice(0, 80)}…` : text);
const btn = (label, cls, run) => h("button", {type: "button", class: cls, on: {click: run}}, label);
const nowSeconds = () => Date.now() / 1000;
const PICKED = "\n";
const OTHER_LIMIT = 1000;
const shownPick = (label) => label.split(PICKED).join(", ");
function ago(ts) {
const diff = ts - nowSeconds();
+51 -17
View File
@@ -99,12 +99,12 @@
openItem(item);
return null;
}
return submit([entryOf(item, "approve", item.recommended)], `Choice: ${item.recommended}`);
return submit([entryOf(item, "approve", item.recommended)], `Choice: ${shownPick(item.recommended)}`);
}
return submit([entryOf(item, "approve", "")], `${item.kind === "operator" ? "Run" : "Grant"}: ${short(item.title)}`);
}
const chooseOne = (item, label) => submit([entryOf(item, "approve", label)], `Choice: ${label}`);
const chooseOne = (item, label) => submit([entryOf(item, "approve", label)], `Choice: ${shownPick(label)}`);
const asked = (item) => item.kind === "operator" && item.check === "decision";
const answers = new Map();
const answerOf = (item) => answers.get(keyOf(item)) || item.answered || "";
@@ -120,39 +120,73 @@
}
}
function otherAnswer(item) {
const input = h("input", {class: "field", type: "text", placeholder: "Other answer …", "aria-label": `Other answer to ${item.id}`, disabled: answers.has(keyOf(item))});
/**
* @param {Object} item a decision row, or a decision the permission hook asked.
* @param {Function} send called with the trimmed text once it is not empty.
* @returns {HTMLElement} the free-text answer form.
*/
function otherAnswer(item, send) {
const done = answers.has(keyOf(item));
const input = h("input", {class: "field", type: "text", placeholder: "Other answer …", "aria-label": `Other answer to ${item.id}`, maxlength: item.kind === "decision" ? OTHER_LIMIT : null, disabled: done});
const form = h("form", {class: "option other"}, input,
h("button", {type: "submit", class: "btn small", disabled: answers.has(keyOf(item)), ...named("Send", revealed(`Send: your passkey signs this answer, a post to ${item.agent}`))}, icon("bi-send"), "Send"));
h("button", {type: "submit", class: "btn small", disabled: done, ...named("Send", revealed(`Send: your passkey signs this answer for ${item.agent}`))}, icon("bi-send"), "Send"));
form.addEventListener("submit", (event) => {
event.preventDefault();
if (input.value.trim()) {
answerRow(item, input.value.trim());
send(input.value.trim());
}
});
return form;
}
/**
* @param {Object} item a decision or a decision row; a multi decision takes several options, toggled until Send.
* @param {Function} pick called with the answer: one label, or the toggled labels in option order joined by PICKED.
* @param {HTMLElement} [other] a free-text answer form.
* @returns {HTMLElement} the option buttons with their preview pane.
*/
function choicePanel(item, pick, other) {
const done = Boolean(answerOf(item));
const recommended = item.recommended.split(PICKED);
const toggled = new Set();
const pane = item.options.some((option) => option.preview) ? h("pre", {class: "choice-preview", "aria-label": "Preview"}) : null;
const show = (option) => {
if (pane) {
pane.textContent = revealedLines(option.preview || "");
}
};
const buttons = item.options.map((option) => h("button", {
type: "button", class: `option${option.label === item.recommended ? " recommended" : ""}`, title: revealed(`${option.label}: your passkey signs this answer, a post to ${item.agent}`), disabled: item.held || done,
on: {click: () => pick(option.label), focus: () => show(option), mouseenter: () => show(option)},
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null));
show(item.options.find((option) => option.label === item.recommended) || item.options[0] || {});
const list = h("div", {class: "options"}, buttons, other || null);
const send = item.multi ? h("button", {type: "button", class: "btn small primary choice-send", disabled: true, ...named("Send", revealed(`Send the toggled options: your passkey signs this answer for ${item.agent}`))}, icon("bi-send"), "Send") : null;
const buttons = item.options.map((option) => {
const button = h("button", {
type: "button", class: `option${recommended.includes(option.label) ? " recommended" : ""}`, title: revealed(`${option.label}: your passkey signs this answer, a post to ${item.agent}`), disabled: item.held || done,
"aria-pressed": item.multi ? "false" : null,
on: {click: () => {
if (!item.multi) {
pick(option.label);
return;
}
toggled.has(option.label) ? toggled.delete(option.label) : toggled.add(option.label);
button.setAttribute("aria-pressed", String(toggled.has(option.label)));
send.disabled = !toggled.size;
}, focus: () => show(option), mouseenter: () => show(option)},
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null);
return button;
});
if (send) {
send.addEventListener("click", () => pick(item.options.filter((option) => toggled.has(option.label)).map((option) => option.label).join(PICKED)));
}
show(item.options.find((option) => recommended.includes(option.label)) || item.options[0] || {});
const list = h("div", {class: "options"}, buttons, other || null, send);
return pane ? h("div", {class: "choice"}, list, pane) : list;
}
const choiceOf = (item, after) => item.kind === "decision"
? choicePanel(item, (label) => { after(); chooseOne(item, label); })
: asked(item) ? [answerTo(item), choicePanel(item, (label) => { after(); answerRow(item, label); }, otherAnswer(item))] : null;
const choiceOf = (item, after) => {
if (item.kind === "decision") {
const choose = (label) => { after(); chooseOne(item, label); };
return choicePanel(item, choose, item.other ? otherAnswer(item, choose) : null);
}
return asked(item) ? [answerTo(item), choicePanel(item, (label) => { after(); answerRow(item, label); }, otherAnswer(item, (text) => answerRow(item, text)))] : null;
};
/**
* @param {Object} item a decision row of the register.
@@ -171,7 +205,7 @@
return;
}
const rows = usable.map((item) => h("li", {},
h("div", {class: "row"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.kind === "decision" && !deny ? h("span", {class: "muted"}, revealed(`→ ${item.recommended}`)) : null),
h("div", {class: "row"}, pill(ITEM_LABELS[item.kind], KIND_TONES[item.kind]), item.kind === "decision" && !deny ? h("span", {class: "muted"}, revealed(`→ ${shownPick(item.recommended)}`)) : null),
h("strong", {}, revealed(item.title)),
item.kind === "operator" ? h("div", {class: "command"}, h("code", {}, revealed(item.command))) : null,
item.kind === "operator" ? h("span", {class: "muted"}, revealed(`in ${item.directory}`)) : null,
@@ -252,7 +286,7 @@
} else if (item.kind === "ask") {
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
} else if (item.kind === "decision" && item.recommended) {
grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${item.recommended}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(item.recommended)));
grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${shownPick(item.recommended)}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(shownPick(item.recommended))));
} else if (item.kind === "operator" && item.runnable) {
grant(iconBtn("bi-play-fill", "Run", "btn small primary", () => approveOne(item)));
} else if (item.kind === "rule") {
+54 -7
View File
@@ -11,7 +11,7 @@
const CONFETTI = 28;
const COMMENTS_KEPT = 5;
const PATTERNS = ["dots", "stripes", "waves", "grid", "rings"];
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), overview: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0, epoch: 0};
const matchView = {cards: null, order: [], marks: new Map(), opened: new Map(), decisions: new Map(), toggles: new Map(), overview: false, front: null, drag: null, dom: null, sig: "", fetched: 0, loading: false, press: null, flying: false, openBefore: 0, epoch: 0};
/**
* @returns {Promise<void>} settled when this read ends, at once while another runs; a response requested before
@@ -274,12 +274,59 @@
card.stale ? h("p", {class: "match-stale"}, icon("bi-exclamation-triangle"), revealed(card.stale_reason)) : null);
}
/**
* @param {Object} card a decision card; a multi one takes several options, toggled here and kept in matchView.toggles across redraws until Pick.
* @returns {HTMLElement} its option buttons, and Pick for a multi card.
*/
function matchOptions(card) {
const kept = matchView.decisions.get(cardKey(card));
return h("div", {class: "options match-options", role: "group", "aria-label": "Options"}, card.options.map((option) => h("button", {
type: "button", class: `option${option.label === card.recommended ? " recommended" : ""}`, "aria-pressed": String(Boolean(kept && kept.label === option.label)),
title: revealed(`${option.label}: picked now, sent to ${card.agent || "its agent"} as a post at the release`), on: {click: () => decide(card, "accept", "", option.label)},
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null)));
const recommended = card.recommended.split(PICKED);
const toggled = matchView.toggles.get(cardKey(card)) || new Set(kept ? kept.label.split(PICKED) : []);
const pick = card.multi ? h("button", {type: "button", class: "btn small primary match-pick", disabled: !toggled.size, title: revealed(`Pick: the toggled options, sent to ${card.agent || "its agent"} at the release`)}, icon("bi-check2-square"), "Pick") : null;
const buttons = card.options.map((option) => {
const button = h("button", {
type: "button", class: `option${recommended.includes(option.label) ? " recommended" : ""}`, "aria-pressed": String(toggled.has(option.label)),
title: revealed(`${option.label}: ${card.multi ? "toggled now" : "picked now"}, sent to ${card.agent || "its agent"} at the release`),
on: {click: () => {
if (!card.multi) {
decide(card, "accept", "", option.label);
return;
}
toggled.has(option.label) ? toggled.delete(option.label) : toggled.add(option.label);
matchView.toggles.set(cardKey(card), toggled);
button.setAttribute("aria-pressed", String(toggled.has(option.label)));
pick.disabled = !toggled.size;
}},
}, h("strong", {}, revealed(option.label)), option.description ? h("span", {}, revealed(option.description)) : null);
return button;
});
if (pick) {
pick.addEventListener("click", () => {
matchView.toggles.delete(cardKey(card));
decide(card, "accept", "", card.options.filter((option) => toggled.has(option.label)).map((option) => option.label).join(PICKED));
});
}
return h("div", {class: "options match-options", role: "group", "aria-label": "Options"}, buttons, pick, card.other ? matchOther(card, kept) : null);
}
/**
* @param {Object} card a decision card of a question the permission hook asked.
* @param {Object} [kept] its decision so far; a free-text one fills the field.
* @returns {HTMLElement} the one-line free-text answer, picked like an option.
*/
function matchOther(card, kept) {
const free = kept && kept.label && !kept.label.split(PICKED).some((label) => card.options.some((option) => option.label === label));
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: "Other answer …", "aria-label": "Other answer", value: free ? kept.label : null});
const form = h("form", {class: "option other match-other"}, input,
h("button", {type: "submit", class: "btn small", ...named("Pick", revealed(`Pick: this text, sent to ${card.agent || "its agent"} at the release`))}, icon("bi-send"), "Pick"));
form.addEventListener("submit", (event) => {
event.preventDefault();
if (input.value.trim()) {
matchView.toggles.delete(cardKey(card));
decide(card, "accept", "", input.value.trim());
}
});
return form;
}
function matchPayload(card) {
@@ -559,7 +606,7 @@
});
return h("li", {class: "match-decision", "data-card": card.id, "data-verdict": decision.verdict},
h("div", {class: "row"}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, icon(kindIcon), kindName), h("strong", {class: "match-decision-title"}, revealed(card.title)), h("span", {class: "spacer"}),
h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), decision.label ? revealed(`${word}: ${decision.label}`) : word), decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
h("span", {class: "pill match-verdict", "data-tone": tone}, icon(mark), decision.label ? revealed(`${word}: ${shownPick(decision.label)}`) : word), decision.verdict === "reject" ? iconBtn("bi-pencil", "Edit feedback", "btn small ghost match-edit", () => rejectCard(card)) : null, flip, back),
decision.verdict === "reject" ? h("pre", {class: "match-decision-feedback"}, revealedLines(decision.feedback === "" ? "no feedback text" : decision.feedback)) : null);
}
@@ -687,7 +734,7 @@
matchView.front = front;
const act = (cls, iconName, word, hint, disabled, run) => h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}},
h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word));
const hint = front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (front.recommended ? `Accept: ${front.recommended} (right arrow, swipe right)` : "Accept: pick one of its options") : "Accept (right arrow, swipe right)";
const hint = front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (front.recommended ? `Accept: ${shownPick(front.recommended)} (right arrow, swipe right)` : "Accept: pick one of its options") : "Accept (right arrow, swipe right)";
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.stale) || (front.kind === "decision" && !front.recommended), () => acceptCard(front));
const reject = act("match-reject", "bi-x-lg", "Reject", pickOnly(front) ? "Reject: a choice is answered with one of its options" : "Reject with feedback (left arrow, swipe left)", pickOnly(front), () => rejectCard(front));
const later = act("match-later", "bi-arrow-up", "Later", "Later: to the back of the stack (up arrow, swipe up)", !rest.length, () => laterCard(front));