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

+1 -1
View File
@@ -480,7 +480,7 @@ The Tasks tab (key 4, `#tasks/list`, `#tasks/board`, `#tasks/rasci`) shows the `
Without reinstalling the skills, `make orchestrator-install` installs, builds and starts only the hub, `make orchestrator-check` checks the installed hub (image, container, logs, HTTP, pinned keys, hook, runner, tree timer, disk; exit 1 on a failure), `make orchestrator-pin CREDENTIAL=<blob>` pins the passkey that "Register passkey" shows, `make orchestrator-runner` enables the runner service, and `make orchestrator-hook` registers the PermissionRequest hook in `~/.claude/settings.json`, replacing an earlier Agent Orchestrator entry and keeping the file mode, after a copy to `settings.json.before-kvb-orchestrator-hook` (Claude Code reads `~/.claude/settings.local.json` only in sessions started in the home directory). Agents that reach the Docker socket are root-equivalent: until the agent VMs of core requirement 093 isolate them, the signatures do not hold against such an agent. `make watch-check` shows whether the resource watch hook is stuck (running hooks, holders of the kept queue history, age of the stored stage).
For approvals the hub is only a relay: every approval of an ask, a staged commit or an operator command is signed end to end with a WebAuthn passkey held in KeePassXC (through KeePassXC-Browser, relying party `localhost`, origin `http://localhost:<port>`; ES256, EdDSA and RS256, so a hardware key can be pinned beside it). To register, open the hub at `http://localhost:<port>/` (WebAuthn needs the domain; on `127.0.0.1` the page links there), choose "Register passkey" in the settings and run the host command the page shows, `python3 ~/.local/share/kvb-orchestrator/client/approval.py pin --port <port> --approvers ~/.config/kvb-orchestrator/approvers.json --credential '<blob>'`, in a terminal outside every sandbox: it pins the key in `~/.config/kvb-orchestrator/approvers.json` with mode 0600, a file no sandboxed agent can write and the hub mounts read-only; the hub never pins. Each approval, or one bulk selection, is one signature over the hashes of every item, a nonce and an expiry; each auto-approval rule is signed once. In the inbox, an operator command run with "Run" shows the runner's output in a console under its row until "Close". "Deny" on an ask, an operator row or a rule request signs the denial with its channel and optional reason (a hash no approval shares) and, after the 3 s undo, tells the requesting agent by post or by the radio class picked, never mayday; the hub verifies that signature against the pinned keys before it stores or sends anything, the hook passes the reason on only when it verifies the signature too, and a denied operator row ends as `stopped`. Agents ask for an auto-approval rule with the MCP tool `rule_request` (the rules form's limits; a request stays open for the ask lifetime of one hour, at most 20 in all, and 3 per agent name, which only spreads the queue since MCP names no caller); its row shows a dry run over the last 7 days, and only "Accept" with the passkey stores it. The hub stores no rule, of any kind, whose passkey assertion it cannot verify. The executors verify it themselves against the pinned keys and fail closed: the runner (`client/runner.py`, the `kvb-orchestrator-runner` user service) runs only signed commands, each signature once, recorded in `~/.local/state/kvb-orchestrator-approvals/runner.json`; the PermissionRequest hook (`client/permission_hook.py --port <port> --timeout <seconds> --approvers ~/.config/kvb-orchestrator/approvers.json --replay ~/.local/state/kvb-orchestrator-approvals/hook.json`) allows only a signed item that matches its own tool, command, cwd and session, else it leaves the decision to Claude Code's own prompt; the commit skills run `approval.py verify` on the staged tree before committing, else they ask in the terminal. With no key pinned, every executor refuses; review rejections and a decision a rule takes stay unsigned. A signed rule never covers a command holding `;`, `&`, `|`, a backtick, `$`, `<`, `>`, parentheses or a line break: such a command always asks. The hub page is trusted while it asks for a signature or shows the blob to pin: whoever controls the hub container can show one item and have another signed, or hand over a key of its own. Any local process, sandboxed agents included, can also send the unsigned operator actions (the bare decision choice `/api/decisions/<id>/choose`, which sends no answer, the priority order, settings that add no stream origin, review rejections, the bare ask denial `/api/asks/<id>/deny`, console dismissals) with the hub's guard headers, and the container reads the review pages from `pages/` of the council root, which every sandboxed agent can write; it mounts the council root at its host path and no longer reads the host `/tmp`. All three close with the agent VMs of core requirement 093, like the Docker-socket gap.
For approvals the hub is only a relay: every approval of an ask, a staged commit or an operator command is signed end to end with a WebAuthn passkey held in KeePassXC (through KeePassXC-Browser, relying party `localhost`, origin `http://localhost:<port>`; ES256, EdDSA and RS256, so a hardware key can be pinned beside it). To register, open the hub at `http://localhost:<port>/` (WebAuthn needs the domain; on `127.0.0.1` the page links there), choose "Register passkey" in the settings and run the host command the page shows, `python3 ~/.local/share/kvb-orchestrator/client/approval.py pin --port <port> --approvers ~/.config/kvb-orchestrator/approvers.json --credential '<blob>'`, in a terminal outside every sandbox: it pins the key in `~/.config/kvb-orchestrator/approvers.json` with mode 0600, a file no sandboxed agent can write and the hub mounts read-only; the hub never pins. Each approval, or one bulk selection, is one signature over the hashes of every item, a nonce and an expiry; each auto-approval rule is signed once. In the inbox, an operator command run with "Run" shows the runner's output in a console under its row until "Close". "Deny" on an ask, an operator row or a rule request signs the denial with its channel and optional reason (a hash no approval shares) and, after the 3 s undo, tells the requesting agent by post or by the radio class picked, never mayday; the hub verifies that signature against the pinned keys before it stores or sends anything, the hook passes the reason on only when it verifies the signature too, and a denied operator row ends as `stopped`. Agents ask for an auto-approval rule with the MCP tool `rule_request` (the rules form's limits; a request stays open for the ask lifetime of one hour, at most 20 in all, and 3 per agent name, which only spreads the queue since MCP names no caller); its row shows a dry run over the last 7 days, and only "Accept" with the passkey stores it. The hub stores no rule, of any kind, whose passkey assertion it cannot verify. The executors verify it themselves against the pinned keys and fail closed: the runner (`client/runner.py`, the `kvb-orchestrator-runner` user service) runs only signed commands, each signature once, recorded in `~/.local/state/kvb-orchestrator-approvals/runner.json`; the PermissionRequest hook (`client/permission_hook.py --port <port> --timeout <seconds> --approvers ~/.config/kvb-orchestrator/approvers.json --replay ~/.local/state/kvb-orchestrator-approvals/hook.json`) allows only a signed item that matches its own tool, command, cwd and session, else it leaves the decision to Claude Code's own prompt, and turns each question of an AskUserQuestion call into a decision card that expires with its timeout, answering the call only once a pinned key signed the pick of every question (a multi-select card toggles options and sends them with one signature, and every such card also takes one signed line of "Other" text); the commit skills run `approval.py verify` on the staged tree before committing, else they ask in the terminal. With no key pinned, every executor refuses; review rejections and a decision a rule takes stay unsigned. A signed rule never covers a command holding `;`, `&`, `|`, a backtick, `$`, `<`, `>`, parentheses or a line break: such a command always asks. The hub page is trusted while it asks for a signature or shows the blob to pin: whoever controls the hub container can show one item and have another signed, or hand over a key of its own. Any local process, sandboxed agents included, can also send the unsigned operator actions (the bare decision choice `/api/decisions/<id>/choose`, which sends no answer, the priority order, settings that add no stream origin, review rejections, the bare ask denial `/api/asks/<id>/deny`, console dismissals) with the hub's guard headers, and the container reads the review pages from `pages/` of the council root, which every sandboxed agent can write; it mounts the council root at its host path and no longer reads the host `/tmp`. All three close with the agent VMs of core requirement 093, like the Docker-socket gap.
Restart your agent afterwards so it loads the new skills.
+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));
+4 -2
View File
@@ -88,7 +88,7 @@ mode = path.stat().st_mode & 0o777 if path.exists() else 0o600
entries = settings.setdefault("hooks", {}).setdefault("PermissionRequest", [])
entries[:] = [entry for entry in entries if not any(marker in hook.get("command", "") for hook in entry.get("hooks", []))]
if added:
entries.append({"matcher": "Bash", "hooks": [{"type": "command", "command": added[0], "timeout": int(added[1])}]})
entries.append({"matcher": "Bash|AskUserQuestion", "hooks":[{"type": "command", "command": added[0], "timeout": int(added[1])}]})
temporary = path.with_name(f"{path.name}.{os.getpid()}")
temporary.write_text(json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
temporary.chmod(mode)
@@ -389,7 +389,9 @@ check() {
code="$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:${port}/" || true)"
if [[ "${code}" == "200" ]]; then ok "http://localhost:${port}/ answers 200"; else fail "http://localhost:${port}/ answers ${code}"; fi
check_keys
if grep -qs "${NAME}/client/permission_hook.py" "${SETTINGS}" "${LOCAL_SETTINGS}"; then
if grep -qs "${NAME}/client/permission_hook.py" "${SETTINGS}" "${LOCAL_SETTINGS}" && ! grep -qs '"Bash|AskUserQuestion"' "${SETTINGS}" "${LOCAL_SETTINGS}"; then
todo "PermissionRequest hook misses AskUserQuestion: make orchestrator-hook"
elif grep -qs "${NAME}/client/permission_hook.py" "${SETTINGS}" "${LOCAL_SETTINGS}"; then
ok "PermissionRequest hook registered"
else
todo "PermissionRequest hook missing: make orchestrator-hook"
+174
View File
@@ -0,0 +1,174 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
from unittest import mock
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
from hub_support import iso
from kvb_orchestrator import batches
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-question-multi-shots"))
SENT_AT = 1366
GROUPS = ["Scratch (Recommended)", "Logs", "Worktrees (Recommended)"]
QUESTION = "Which groups go?"
PICKED = f"{GROUPS[0]}\n{GROUPS[2]}"
CAPTURE = """
const posted = [];
const send = window.fetch.bind(window);
window.fetch = async (path, init) => {
if (String(path) === "/api/inbox/approve") {
posted.push(JSON.parse(init.body).items.map((item) => [item.kind, item.id, item.verb, item.label]));
}
return send(path, init);
};
const look = (options, submit) => ({pressed: options.map((option) => option.getAttribute("aria-pressed")), recommended: options.map((option) => option.classList.contains("recommended")), disabled: submit ? submit.disabled : null});
const wide = () => document.documentElement.scrollWidth > window.innerWidth + 1;
"""
MATCH = """(async () => {@HELPERS@@CAPTURE@
const card = await until(() => document.querySelector('#main .match-card.front[data-card="@CARD@"]'), 8000);
if (!card) {
return {error: text(document.getElementById("main"))};
}
const options = () => all(".match-options .option", card);
const pick = card.querySelector(".match-pick");
const before = look(options(), pick);
[0, 2, 1, 1].forEach((index) => options()[index].click());
const toggled = {...look(options(), pick), front: document.querySelector("#main .match-card.front") === card, other: Boolean(card.querySelector(`.match-other input[maxlength="1000"]`))};
pick.click();
const overview = await until(() => document.querySelector("#main .match-overview"), 3000);
const found = {before, toggled, rows: overview ? all("#main .match-decision").map((item) => [item.dataset.card, text(item.querySelector(".match-verdict"))]) : [], wide: wide()};
if (@SEND@) {
document.querySelector("#main .match-release").click();
found.toast = await until(() => all("#toasts .toast").map(text).find((entry) => entry.startsWith("Release")), 15000);
found.posted = posted;
}
return found;
})()"""
INBOX = """(async () => {@HELPERS@@CAPTURE@
const row = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@QUESTION@")), 8000);
if (!row) {
return {error: text(document.getElementById("main"))};
}
const options = all(".options button.option", row);
const submit = row.querySelector(".choice-send");
const before = look(options, submit);
[0, 2].forEach((index) => options[index].click());
const found = {before, toggled: look(options, submit), wide: wide()};
if (@SEND@) {
const shown = new Set(all("#toasts .toast"));
submit.click();
found.toast = await until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith("Choice:")), 20000);
found.gone = Boolean(await until(() => !all("#main .inbox-list > li").some((li) => li.textContent.includes("@QUESTION@")), 20000));
found.posted = posted;
}
return found;
})()"""
OTHER = """(async () => {@HELPERS@@CAPTURE@
const row = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@QUESTION@")), 8000);
if (!row) {
return {error: text(document.getElementById("main"))};
}
const field = row.querySelector(".option.other input");
const found = {field: field ? [field.maxLength, field.getAttribute("aria-label").startsWith("Other answer to ")] : null, wide: wide()};
if (@SEND@) {
field.value = " @TYPED@ ";
const shown = new Set(all("#toasts .toast"));
row.querySelector(".option.other button[type=submit]").click();
found.toast = await until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith("Choice:")), 20000);
found.posted = posted;
}
return found;
})()"""
TYPED = "Keep the old one"
UNTOUCHED = {"pressed": ["false"] * 3, "recommended": [True, False, True], "disabled": True}
TOGGLED = {"pressed": ["true", "false", "true"], "recommended": [True, False, True], "disabled": False}
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestQuestionMulti(HubCase):
drive = base.OrchestratorE2ECase.drive
authenticator = base.OrchestratorE2ECase.authenticator
def setUp(self):
super().setUp()
now = time.time()
self.write_council({"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills session", "since": iso(now - 86400), "beat": now, "work": "questions"}})
self.decision = self.question(QUESTION, GROUPS, True)
OUT.mkdir(parents=True, exist_ok=True)
def question(self, text: str, labels: list[str], multi: bool) -> str:
body = {"question": text, "options": [{"label": label, "description": ""} for label in labels], "session": "s1", "timeout": 600, "multi": multi}
status, _, answer = self.post_json("/api/decisions", body, self.local())
self.assertEqual(status, 201, answer)
return json.loads(answer)["id"]
def steps(self, probe: str, view: str, fills: dict[str, str]) -> list[dict]:
found = []
for width, height in sorted(base.WIDTHS, key=lambda size: size[0] == SENT_AT):
script = probe.replace("@HELPERS@", base.HELPERS).replace("@CAPTURE@", CAPTURE).replace("@SEND@", "true" if width == SENT_AT else "false")
for name, value in fills.items():
script = script.replace(f"@{name}@", value)
found.append({"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}{view}", "wait": 1500, "probe": script, "shot": str(OUT / f"chromium-{width}-{view.rsplit('/', 1)[-1]}.png")})
return found
def run_steps(self, probe: str, view: str, decision_id: str, expected: str, question: str = QUESTION) -> list[dict]:
"""Args:
decision_id: the decision the last step answers.
expected: the choice it holds afterwards.
question: the question whose row or card the probe drives.
"""
with mock.patch.object(batches, "UNDO", 0.3):
steps = self.steps(probe, view, {"CARD": f"decision:{decision_id}", "QUESTION": question, "TYPED": TYPED})
data = self.drive(steps, self.authenticator(), "cdp.mjs", os.environ.get("CHROMIUM", "chromium"))
self.settle(lambda: self.httpd.hub.decisions.get(decision_id)["status"] == "decided")
(OUT / f"chromium-{view.rsplit('/', 1)[-1]}.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
self.assertEqual(self.httpd.hub.decisions.get(decision_id)["choice"], expected)
return data["results"]
def test_chromium_match_toggles_a_multi_question_and_releases_the_picked_labels_in_option_order(self):
results = self.run_steps(MATCH, "#tasks/match", self.decision, PICKED)
for found in results:
with self.subTest(sent="posted" in found):
self.assertNotIn("error", found, found)
self.assertEqual((found["before"], found["toggled"]), (UNTOUCHED, {**TOGGLED, "front": True, "other": True}), found)
self.assertEqual(found["rows"], [[f"decision:{self.decision}", f"Accept: {GROUPS[0]}, {GROUPS[2]}"]], found)
self.assertFalse(found["wide"], found)
self.assertTrue(results[-1]["toast"].startswith("Release: 1 decision"), results[-1])
self.assertEqual(results[-1]["posted"], [[["decision", self.decision, "approve", PICKED]]])
def test_chromium_inbox_toggles_a_multi_question_and_sends_the_picked_labels_with_one_signature(self):
results = self.run_steps(INBOX, "#stream/inbox", self.decision, PICKED)
for found in results:
with self.subTest(sent="posted" in found):
self.assertNotIn("error", found, found)
self.assertEqual((found["before"], found["toggled"]), (UNTOUCHED, TOGGLED), found)
self.assertFalse(found["wide"], found)
self.assertTrue(results[-1]["toast"].startswith(f"Choice: {GROUPS[0]}, {GROUPS[2]}") and results[-1]["gone"], results[-1])
self.assertEqual(results[-1]["posted"], [[["decision", self.decision, "approve", PICKED]]])
def test_chromium_inbox_sends_one_trimmed_line_of_other_text_for_a_hook_question(self):
branch = "Name the branch?"
single = self.question(branch, ["main", "dev"], False)
results = self.run_steps(OTHER, "#stream/inbox", single, TYPED, branch)
for found in results:
with self.subTest(sent="posted" in found):
self.assertNotIn("error", found, found)
self.assertEqual(found["field"], [1000, True], found)
self.assertFalse(found["wide"], found)
self.assertTrue(results[-1]["toast"].startswith(f"Choice: {TYPED}"), results[-1])
self.assertEqual(results[-1]["posted"], [[["decision", single, "approve", TYPED]]])
if __name__ == "__main__":
unittest.main()
+210
View File
@@ -0,0 +1,210 @@
from __future__ import annotations
import json
import subprocess
import sys
import time
import unittest
from unittest import mock
from hub_case import HubCase
from hub_support import CLIENT, HOOK, PRESENT, Key, key
from kvb_orchestrator import batches
PICK = "Execute (Recommended)"
QUESTION = {
"question": "Clean up the two worktrees?",
"header": "Cleanup",
"options": [{"label": PICK, "description": "Both are merged"}, {"label": "Keep", "description": "Nothing changes", "preview": "a\nb"}],
"multiSelect": False,
}
SECOND = {"question": "Post the report?", "header": "Report", "options": [{"label": "Post", "description": ""}, {"label": "Skip", "description": ""}], "multiSelect": False}
GROUPS = ["Scratch (Recommended)", "Logs", "Worktrees (Recommended)"]
MULTI = {"question": "Which groups go?", "header": "Groups", "options": [{"label": label, "description": ""} for label in GROUPS], "multiSelect": True}
ASKED = {**HOOK, "tool_name": "AskUserQuestion", "tool_input": {"questions": [QUESTION, SECOND]}}
BODY = {"question": QUESTION["question"], "options": [{"label": PICK, "description": "Both are merged"}], "session": "s1", "timeout": 60, "multi": False}
MULTI_BODY = {**BODY, "question": MULTI["question"], "options": MULTI["options"], "multi": True}
class TestHubQuestions(HubCase):
def ask_question(self, payload: dict) -> str:
status, _, body = self.post_json("/api/decisions", payload, self.local())
self.assertEqual(status, 201, body)
return json.loads(body)["id"]
def state(self, decision_id: str) -> dict:
status, _, body = self.get(f"/api/decisions/{decision_id}?wait=0")
self.assertEqual(status, 200, body)
return json.loads(body)
def pick(self, decision_id: str, label: str, signer: Key) -> None:
self.counted(decision_id, label, signer, 0)
def counted(self, decision_id: str, label: str, signer: Key, count: int) -> None:
"""Args:
count: the signature counter the authenticator reports.
"""
items = [self.entry("decision", decision_id, label, "")]
payload = self.prepare(items)["payload"]
proof = {"payload": payload, "assertion": signer.assertion(payload, self.origin, "localhost", PRESENT, count)}
with mock.patch.object(batches, "UNDO", 0.05):
status, _, body = self.approve(items, proof)
self.assertEqual(status, 202, body)
self.settle(lambda: self.state(decision_id)["status"] == "decided")
def hook(self, payload: dict, timeout: str) -> subprocess.Popen:
trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json")]
process = subprocess.Popen([sys.executable, str(CLIENT), "--port", str(self.port), "--timeout", timeout, *trust], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
process.stdin.write(json.dumps(payload))
process.stdin.close()
self.addCleanup(process.stdout.close)
self.addCleanup(process.stderr.close)
return process
def waiting(self, count: int) -> list[dict]:
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
found = [item for item in self.snapshot()["inbox"] if item["kind"] == "decision"]
if len(found) >= count:
return sorted(found, key=lambda item: item["ts"])
time.sleep(0.05)
self.fail("the questions did not arrive")
def test_a_question_is_a_local_expiring_decision_card_in_the_inbox_and_on_match(self):
self.claim("s1", "Skills session")
for headers in ({"Host": self.host}, {**self.local(), "Origin": "http://evil.example"}):
with self.subTest(headers=headers):
self.assertEqual(self.post_json("/api/decisions", BODY, headers)[0], 403)
for payload in ({**BODY, "extra": 1}, {**BODY, "session": " "}, {**BODY, "options": []}, {**BODY, "timeout": -1}, {**BODY, "multi": "yes"}, {name: value for name, value in BODY.items() if name != "session"}):
with self.subTest(payload=payload):
self.assertEqual(self.post_json("/api/decisions", payload, self.local())[0], 400)
decision_id = self.ask_question(BODY)
self.assertEqual(self.state(decision_id), {"id": decision_id, "status": "pending", "choice": None, "proof": None, "to": "Skills"})
item = next(item for item in self.snapshot()["inbox"] if item["id"] == decision_id)
self.assertEqual((item["kind"], item["agent"], item["recommended"]), ("decision", "Skills", PICK))
cards = json.loads(self.get("/api/match")[2])["cards"]
self.assertEqual([card["kind"] for card in cards if card["ref"] == decision_id], ["decision"])
self.assertEqual(self.get(f"/api/decisions/{self.decision('')}?wait=0")[0], 404)
self.assertEqual(self.get("/api/decisions/0123456789abcdef?wait=0")[0], 404)
expired = self.ask_question({**BODY, "timeout": 0})
self.assertEqual(self.state(expired)["status"], "expired")
self.assertNotIn(expired, [item["id"] for item in self.snapshot()["inbox"]])
self.assertNotIn(f"decision:{expired}", [card["id"] for card in json.loads(self.get("/api/match")[2])["cards"]])
self.assertNotIn(expired, [row["id"] for row in self.snapshot()["decisions"]])
self.assertEqual(self.approve([self.entry("decision", expired, PICK, "")], None)[0], 409)
def test_a_signed_pick_is_kept_for_the_hook_and_posts_nothing(self):
self.claim("s1", "Skills session")
signer = self.pin()
decision_id = self.ask_question(BODY)
self.pick(decision_id, PICK, signer)
state = self.state(decision_id)
self.assertEqual((state["status"], state["choice"], state["to"]), ("decided", PICK, "Skills"))
self.assertEqual(set(state["proof"]), {"payload", "assertion"})
self.assertEqual(self.scripts.calls, [])
self.assertEqual(self.snapshot()["messages"], [])
def test_a_multi_question_takes_one_or_more_labels_in_option_order_and_recommends_every_marked_one(self):
self.claim("s1", "Skills session")
signer = self.pin()
decision_id = self.ask_question(MULTI_BODY)
item = next(item for item in self.snapshot()["inbox"] if item["id"] == decision_id)
self.assertEqual((item["multi"], item["recommended"]), (True, f"{GROUPS[0]}\n{GROUPS[2]}"))
card = next(card for card in json.loads(self.get("/api/match")[2])["cards"] if card["ref"] == decision_id)
self.assertEqual((card["multi"], card["recommended"]), (True, item["recommended"]))
for label in ("", f"{GROUPS[2]}\n{GROUPS[0]}", f"{GROUPS[0]}\n{GROUPS[0]}", f"{GROUPS[0]}\nOther", f"{GROUPS[0]}\n"):
with self.subTest(label=label):
self.assertEqual(self.approve([self.entry("decision", decision_id, label, "")], None)[0], 400)
self.pick(decision_id, f"{GROUPS[1]}\n{GROUPS[2]}", signer)
self.assertEqual(self.state(decision_id)["choice"], f"{GROUPS[1]}\n{GROUPS[2]}")
single = self.ask_question(BODY)
self.assertEqual(self.approve([self.entry("decision", single, f"{PICK}\n{PICK}", "")], None)[0], 400)
def test_a_hook_question_also_takes_one_trimmed_line_of_other_text_and_an_mcp_decision_does_not(self):
self.claim("s1", "Skills session")
signer = self.pin()
single, multi, mcp = self.ask_question(BODY), self.ask_question(MULTI_BODY), self.decision("")
item = next(item for item in self.snapshot()["inbox"] if item["id"] == mcp)
self.assertFalse(item["other"])
self.assertTrue(next(item for item in self.snapshot()["inbox"] if item["id"] == single)["other"])
for decision_id, label in ((single, " padded"), (single, "x" * 1001), (single, "tab\there"), (mcp, "free text")):
with self.subTest(label=label[:20]):
self.assertEqual(self.approve([self.entry("decision", decision_id, label, "")], None)[0], 400)
self.pick(single, "Keep the old one", signer)
self.pick(multi, "None of these", signer)
self.assertEqual((self.state(single)["choice"], self.state(multi)["choice"]), ("Keep the old one", "None of these"))
def test_the_hook_passes_a_signed_other_text_on_as_the_answer(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook({**ASKED, "tool_input": {"questions": [QUESTION, MULTI]}}, "20")
first, second = self.waiting(2)
self.pick(first["id"], "Only the first one", signer)
self.pick(second["id"], "Logs only, keep the rest", signer)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision["updatedInput"]["answers"], {QUESTION["question"]: "Only the first one", MULTI["question"]: "Logs only, keep the rest"})
def test_the_hook_answers_a_multi_select_question_with_the_picked_labels_joined_by_commas(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook({**ASKED, "tool_input": {"questions": [MULTI]}}, "20")
card = self.waiting(1)[0]
self.assertTrue(card["multi"])
self.pick(card["id"], f"{GROUPS[0]}\n{GROUPS[2]}", signer)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision["updatedInput"]["answers"], {MULTI["question"]: f"{GROUPS[0]}, {GROUPS[2]}"})
def test_the_hook_answers_every_question_with_the_signed_picks(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook(ASKED, "20")
first, second = self.waiting(2)
self.assertEqual([option["label"] for option in first["options"]], [PICK, "Keep"])
self.assertEqual(first["options"][1]["preview"], "a\nb")
self.pick(first["id"], PICK, signer)
self.pick(second["id"], "Skip", signer)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision, {"behavior": "allow", "updatedInput": {"questions": [QUESTION, SECOND], "answers": {QUESTION["question"]: PICK, SECOND["question"]: "Skip"}}})
def test_the_hook_takes_the_picks_of_a_counting_authenticator_signed_out_of_question_order(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook(ASKED, "20")
first, second = self.waiting(2)
self.counted(second["id"], "Skip", signer, 1)
self.counted(first["id"], PICK, signer, 2)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision["updatedInput"]["answers"], {QUESTION["question"]: PICK, SECOND["question"]: "Skip"})
def test_the_hook_leaves_the_question_to_the_terminal_without_a_pinned_signature_over_the_pick(self):
self.claim("s1", "Skills session")
signer = self.pin()
single = {**ASKED, "tool_input": {"questions": [QUESTION]}}
relayed = {
"unpinned key": lambda card: (PICK, self.signed([self.entry("decision", card, PICK, "")], key(-8, "stranger"))),
"no proof": lambda card: (PICK, None),
"other label": lambda card: (PICK, self.signed([self.entry("decision", card, "Keep", "")], signer)),
}
for case, relay in relayed.items():
with self.subTest(case=case):
process = self.hook(single, "20")
card = self.waiting(1)[0]["id"]
choice, proof = relay(card)
self.httpd.hub.decisions.decide(card, {"status": "decided", "choice": choice, "proof": proof})
process.wait(30)
self.assertEqual((process.returncode, process.stdout.read()), (0, ""))
process = self.hook({**ASKED, "tool_input": {"questions": [{**QUESTION, "options": "Keep"}]}}, "20")
process.wait(30)
self.assertEqual((process.returncode, process.stdout.read()), (0, ""))
self.assertEqual(len(self.httpd.hub.decisions.listed()), len(relayed))
process = self.hook(single, "0.5")
process.wait(30)
self.assertEqual((process.returncode, process.stdout.read()), (0, ""))
if __name__ == "__main__":
unittest.main()