feat(orchestrator): hub requirements 066 to 082 and 084

Radio footer, rules page, schedules editor (System timers and Claude
tasks through signed runner jobs), account usage bar, usage explorer
with a streamed usage.jsonl, queue Controls tab and override, running
tasks on the board, stale task prune with the generic dial, greyed card
stamps, commit-tree diffs from the runner preview, VS Code path links,
expired asks and decisions that stay as EXPIRED cards (asks keyed by a
call digest; an async PostToolUse hook closes those answered in the
terminal), the Match refresh hourglass, attachments by paste, drop and
paperclip in every text field (page CSP gains img-src blob: for the
thumbnails) and the limits board with profiles and a passkey to loosen.
Fixes: one red accept on a red-gate commit and no release while a risk
is open, the send bar footer segments share one height, the mic button
survives a redraw, new Match cards queue before the release card.

E2E specs were still running at commit time (operator order); their
failures follow as separate fixes.

🎯 Fix: 88 %
💥 Break: 8 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 81
🚦 Gate: ⛔ fix 88 % < 90, break 8 % > 5 (committed on the operator's word)

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-27 19:05:38 +00:00
1 parent dc0d578eca
commit f356083a24
149 files changed
+10646 -963

No files matched your search

+22 -3
View File
@@ -5,6 +5,7 @@ import datetime
import re
from pathlib import Path
from .calibration import CALIBRATION, Calibrations, valid_share
from .errors import Missing, ToolError
from .fields import FIELDS, decode, visible
from .ledger import Ledger
@@ -131,15 +132,33 @@ def usage(rows: list[dict], now: float) -> dict[str, dict]:
class Accounts:
def __init__(self, state: Path, kept: Path, council: Path) -> None:
self.ledger = Ledger(state / ACCOUNTS)
self.calibrations = Calibrations(state / CALIBRATION)
self.tokens = kept / RESOURCES / TOKENS
self.sessions = council / SESSION_ACCOUNTS
def view(self, now: float) -> dict:
"""Returns:
{accounts, active, usage}: the stored accounts, the active
account's email or None, and usage() of every token row.
{accounts, active, usage, calibrations}: the stored accounts, the
active account's email or None, usage() of every token row, and
per account id the calibration set since its last reset.
"""
return {"accounts": self.ledger.listed(), "active": active(self.sessions), "usage": usage(rows_between(self.tokens, 0, now, 0), now)}
listed = self.ledger.listed()
return {
"accounts": listed, "active": active(self.sessions), "usage": usage(rows_between(self.tokens, 0, now, 0), now),
"calibrations": self.calibrations.current(listed, now),
}
def calibrate(self, account_id: str, body: bytes, now: float) -> dict:
"""Args:
body: {share}: the percent of the limit the provider shows now.
Returns:
{share, at}: the stored calibration; an unknown id raises
Missing, a share outside 0 to 100 ToolError.
"""
if self.ledger.get(account_id) is None:
raise Missing("no such account")
return self.calibrations.put(account_id, valid_share(body), now)
def save(self, body: bytes) -> dict:
"""Args:
+14 -3
View File
@@ -16,6 +16,7 @@ from .cleanup import cleanup_request
from .denying import (
DENIABLE,
DENY_KEYS,
LAPSING,
NOTED,
denial_note,
request_status,
@@ -26,9 +27,12 @@ from .fields import decode, expect, field, visible
from .firewall import settings_request
from .gating import gate_request
from .offices import office_request
from .prunes import prune_request
from .queueing import queue_request
from .records import digest, shown
from .register import REGISTER, adder, operator_rows, read_register, runnable
from .rules import enable_request, rule_matches, subject_of
from .scheduling import schedule_request
from .signed import (
ask_signed,
operator_signed,
@@ -271,7 +275,7 @@ class Approving:
if not isinstance(raw, dict):
raise ToolError("every item must be an object with kind, id, verb, label and sha256, and a denial also channel, reason and to")
kind_name, verb = raw.get("kind"), raw.get("verb")
noted = verb == "reject" and (kind_name in DENIABLE or kind_name in NOTED and "channel" in raw)
noted = verb == "reject" and (kind_name in DENIABLE or kind_name in (*NOTED, *LAPSING) and "channel" in raw)
shown = ("payload",) if kind_name == "operator" and verb == "approve" and "payload" in raw else ()
expect(raw, (*ITEM_KEYS, *DENY_KEYS) if noted else (*ITEM_KEYS, *shown))
if kind_name not in INBOX_KINDS or verb not in VERBS or not isinstance(raw["label"], str) or not isinstance(raw["sha256"], str):
@@ -285,10 +289,11 @@ class Approving:
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 decision_status(record, time.time()) if kind_name == "decision" else record["status"]
if status != "pending":
lapsed = status == "expired" and noted and kind_name in LAPSING
if status != "pending" and not lapsed:
raise Conflict({"id": item_id, "status": status})
label = ""
if kind_name == "decision":
if kind_name == "decision" and not lapsed:
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, or with one line of other text")
visible([{"label": part} for part in raw["label"].split(PICKED)])
@@ -325,6 +330,12 @@ class Approving:
signed = self.task_changes(raw)
elif gate_request(raw):
signed = self.gate_changes(raw)
elif queue_request(raw):
signed = self.queue_changes(raw)
elif schedule_request(raw):
signed = self.schedule_changes(raw)
elif prune_request(raw):
signed = self.prune_changes(raw)
elif settings_request(raw):
signed = self.settings_changes(raw)
elif enable_request(raw):
+34 -1
View File
@@ -28,6 +28,7 @@ PREVIEW_LIMIT = 4000
ASK_TEXTS = {"command": COMMAND_LIMIT, "cwd": PATH_LIMIT, "session": 200, "agent": 200}
ANSWERS = {"allow": "allowed", "deny": "denied"}
RECOMMENDED = "(Recommended)"
TERMINAL = "terminal"
def ask_state(ask: dict, now: float) -> dict:
@@ -91,15 +92,22 @@ def choice_of(arguments: dict) -> tuple[str, list[dict]]:
class Asking:
def ask(self, body: bytes) -> dict:
"""Args:
body: the hook's ask: tool, ASK_TEXTS, timeout, optionally its diff
and sealed patches, and the call's signing.call_key(), which
an older hook leaves out; ask_ran() closes the ask by it.
"""
payload = decode(body)
diff = valid_diff(payload.pop("diff")) if "diff" in payload else None
sealed = valid_sealed(payload.pop("sealed"), diff) if "sealed" in payload else {}
key = field(payload, "call_key") if "call_key" in payload else ""
payload.pop("call_key", None)
expect(payload, ("tool", *ASK_TEXTS, "timeout"))
values = {name: bounded(payload, name, limit) for name, limit in ASK_TEXTS.items()}
visible(values)
lifetime = seconds(payload, "timeout", ASK_LIFETIME)
created = time.time()
fields = {**values, "tool": field(payload, "tool").strip(), "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)}
fields = {**values, "tool": field(payload, "tool").strip(), "call_key": key, "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)}
with self.asks.changed:
ask_id = self.asks.fresh()
if diff is not None:
@@ -110,6 +118,31 @@ class Asking:
self.automate("ask", record)
return {"id": record["id"], "status": record["status"]}
def ask_ran(self, body: bytes) -> dict:
"""Args:
body: {"call_key", "session"}: the PostToolUse report of a tool
call that ran, keyed by signing.call_key().
Returns:
{"closed"}: the id of the oldest ask of that session and key still
pending and created before the report, now TERMINAL, as answered
in the terminal; null when none is. An ask of another session or
one already decided stays as it is. Nothing is approved or
denied, and no signature is relayed.
"""
payload = decode(body)
expect(payload, ("call_key", "session"))
key = field(payload, "call_key")
session = bounded(payload, "session", ASK_TEXTS["session"])
if not session:
raise ToolError("session must not be empty")
now = time.time()
found = sorted((ask for ask in self.asks.pending() if ask.get("call_key") == key and ask["session"] == session and ask["created_ts"] <= now), key=lambda ask: (ask["created_ts"], ask["id"]))
closed = next((ask["id"] for ask in found if self.asks.decide(ask["id"], {"status": TERMINAL})[1]), None)
if closed is not None:
sealed_file(self.reviews.pages, "ask", closed).unlink(missing_ok=True)
return {"closed": closed}
def ask_wait(self, ask_id: str, query: dict[str, list[str]]) -> dict:
wait = instant(query, "wait")
record = self.asks.get(ask_id)
@@ -0,0 +1,92 @@
from __future__ import annotations
import datetime
import json
import math
import threading
from pathlib import Path
from .fields import decode
from .records import read_json, write_atomic
from .settings import number_in, section
CALIBRATION = "account-calibration.json"
SHARE = (0.0, 100.0)
def last_reset(reset: dict, now: float) -> float:
"""Args:
reset: {day, time}: day 0 for Sunday to 6 for Saturday, time HH:MM,
both in the hub's local time.
now: epoch seconds.
Returns:
The epoch seconds of the latest such moment at or before now; days
step by the calendar, so a DST change keeps the wall clock time, as
Resources.lastMoment counts in the page.
"""
hours, minutes = map(int, reset["time"].split(":"))
at = datetime.datetime.fromtimestamp(now).replace(hour=hours, minute=minutes, second=0, microsecond=0)
at -= datetime.timedelta(days=(at.isoweekday() % 7 - reset["day"]) % 7)
if at.timestamp() > now:
at -= datetime.timedelta(days=7)
return at.timestamp()
def valid_share(body: bytes) -> float:
"""Args:
body: {share}: the percent of the limit the provider shows.
Returns:
The share; another key, a missing one or a share outside 0 to 100
raises ToolError.
"""
low, high = SHARE
return number_in(section(decode(body), "body", ("share",))["share"], "share", low, high)
def well_formed(entry: object) -> bool:
if not isinstance(entry, dict) or set(entry) != {"share", "at"}:
return False
share, at = entry["share"], entry["at"]
numbers = all(isinstance(value, int | float) and not isinstance(value, bool) and math.isfinite(value) for value in (share, at))
return numbers and SHARE[0] <= share <= SHARE[1]
class Calibrations:
def __init__(self, file: Path) -> None:
self.file = file
self.lock = threading.Lock()
data = read_json(file)
self.items: dict[str, dict] = {key: value for key, value in data.items() if well_formed(value)} if isinstance(data, dict) else {}
def write(self, items: dict[str, dict]) -> None:
write_atomic(self.file, json.dumps(items, indent=1, sort_keys=True).encode("utf-8"))
self.items = items
def put(self, account_id: str, share: float, now: float) -> dict:
"""Returns:
{share, at}: the stored calibration, at the epoch second it was
set; tokens of the hours from at on count on top of it.
"""
entry = {"share": share, "at": int(now)}
with self.lock:
self.write({**self.items, account_id: entry})
return dict(entry)
def current(self, accounts: list[dict], now: float) -> dict[str, dict]:
"""Args:
accounts: the stored accounts, each with its id and reset.
now: epoch seconds.
Returns:
Each account's calibration that is not older than its last
reset; a calibration of an account that is gone or reset since
is dropped from the file.
"""
resets = {account["id"]: last_reset(account["reset"], now) for account in accounts}
with self.lock:
fresh = {key: entry for key, entry in self.items.items() if key in resets and entry["at"] >= resets[key]}
if fresh != self.items:
self.write(fresh)
return {key: dict(entry) for key, entry in fresh.items()}
+16 -4
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import time
from .asking import ASK_LIFETIME, ask_state
from .choosing import decision_status
from .council import read_claims
from .errors import ToolError
from .messaging import DIRECT, EVERYONE, TO_ALL
@@ -12,6 +13,8 @@ from .skill_scripts import RASCI
DENIABLE = ("ask", "operator", "rule")
NOTED = ("review",)
LAPSING = ("ask", "decision")
LAPSED = "expired before the operator decided"
DENY_KEYS = ("channel", "reason", "to")
DENY_CHANNELS = {**DIRECT, **{name: words for name, words in TO_ALL.items() if name != "mayday"}}
REASON_LIMIT = 2000
@@ -85,7 +88,9 @@ def request_status(record: dict, now: float) -> str:
class Denying:
def deny(self, item: dict, proof: dict | None) -> str:
"""Args:
item: a checked inbox item with verb reject and its note.
item: a checked inbox item with verb reject and its note; an
expired ask or decision is denied too, its agent told it
expired before the operator decided.
proof: the relayed signature over the denial item.
Returns:
@@ -114,19 +119,26 @@ class Denying:
return f"already {record['status']}"
title, branch = record["title"][:200], record["branch"]
return f"rejected · {self.tell(item, proof, record.get('agent', ''), f'commit {title} on {branch}')}"
ledger = self.asks if item["kind"] == "ask" else self.rule_requests
ledger = {"ask": self.asks, "decision": self.decisions}.get(item["kind"], self.rule_requests)
record = ledger.get(item["id"])
if record is None:
return "unknown"
now = time.time()
if (ask_state(record, now)["status"] if item["kind"] == "ask" else request_status(record, now)) == "expired":
status = ask_state(record, now)["status"] if item["kind"] == "ask" else decision_status(record, now) if item["kind"] == "decision" else request_status(record, now)
if status == "expired" and item["kind"] not in LAPSING:
return "expired"
if status == "pending" and item["kind"] == "decision":
return "refused: only an expired decision is denied"
record, changed = ledger.decide(item["id"], {"status": "denied", "proof": proof, **note})
if not changed:
return f"already {record['status']}"
late = f", {LAPSED}" if status == "expired" else ""
if item["kind"] == "ask":
tool, command = record["tool"], record["command"][:200]
return f"denied · {self.tell(item, proof, record['session'], f'ask {tool}: {command}')}"
return f"denied · {self.tell(item, proof, record['session'], f'ask {tool}: {command}{late}')}"
if item["kind"] == "decision":
question = " ".join(record["question"].split())[:200]
return f"denied · {self.tell(item, proof, record['agent'], f'decision {question}{late}')}"
return f"denied · {self.tell(item, proof, record['agent'], f'rule request {request_words(record)}')}"
def addressee(self, who: str) -> tuple[str, str]:
+4
View File
@@ -9,6 +9,10 @@ class Missing(Exception):
pass
class Unsigned(Exception):
pass
class Conflict(Exception):
def __init__(self, payload: dict) -> None:
super().__init__("conflict")
+11 -1
View File
@@ -9,7 +9,15 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit
from . import NAME
from .errors import Conflict, EngineError, Held, Missing, ToolError, Unavailable
from .errors import (
Conflict,
EngineError,
Held,
Missing,
ToolError,
Unavailable,
Unsigned,
)
from .hub import Hub
GUARD = "X-Kvb-Orchestrator"
@@ -84,6 +92,8 @@ class Exchange(BaseHTTPRequestHandler):
self.send_text(HTTPStatus.BAD_REQUEST, str(error))
except Missing:
self.send_text(HTTPStatus.NOT_FOUND, "not found")
except Unsigned as error:
self.send_text(HTTPStatus.FORBIDDEN, str(error))
except Conflict as error:
self.send_json(HTTPStatus.CONFLICT, error.payload)
except Unavailable as error:
+1
View File
@@ -30,6 +30,7 @@ FIELDS = {
"label": (re.compile(LINE.format(NAME_LIMIT)), f"one line of 1 to {NAME_LIMIT} characters"),
"tool": (re.compile(LINE.format(200)), "one line of 1 to 200 characters"),
"id": (re.compile(r"[0-9a-f]{16}"), "an id the Agent Orchestrator returned"),
"call_key": (re.compile(r"[0-9a-f]{64}"), "the sha256 hex digest signing.call_key() gives the tool call"),
}
+3 -16
View File
@@ -10,7 +10,7 @@ from .errors import Conflict, Missing, ToolError
from .fields import decode, expect, visible
from .ledger import Ledger
from .records import read_json, stamp
from .requesting import RECENT_DAYS, matched
from .requesting import RECENT_DAYS, counted_matches
from .rules import EVERY_AGENT, RULE_KINDS
from .signed import signing
@@ -26,7 +26,6 @@ HASH = re.compile(r"[0-9a-f]{64}")
PERMISSION_LISTS = ("allow", "ask", "deny")
SET_KEYS = ("kind", "tool", "pattern", "scope")
CHAINED = "chains, pipes, redirects or substitutions"
COUNT_ID = "0" * 16
UNSEEN = {"hits": None, "never": ""}
@@ -82,7 +81,7 @@ def hits(rule: dict, asks: list[dict], now: float) -> dict:
never = [*signing.warnings(pattern), *([CHAINED] if signing.CHAINED.search(pattern) else [])]
if never:
return {"hits": None, "never": never[0]}
return {"hits": matched({**rule, "id": COUNT_ID, "expires": now + RECENT_DAYS * 86400}, asks, now), "never": ""}
return {"hits": counted_matches(rule, asks, now), "never": ""}
def counted(groups: list[dict], asks: list[dict], now: float) -> list[dict]:
@@ -97,17 +96,6 @@ def counted(groups: list[dict], asks: list[dict], now: float) -> list[dict]:
return [{**group, "entries": [shown(entry) for entry in group["entries"]]} for group in groups]
def stored_hits(rule: dict, asks: list[dict], now: float) -> dict:
"""Returns:
hits() of a stored ask rule for the agents it is signed for, UNSEEN
for a review or decision rule.
"""
if rule["kind"] != "ask":
return UNSEEN
fields = {key: rule[key] for key in ("kind", "tool", "pattern", "scope")}
return hits({**fields, "agents": rule["agents"]} if "agents" in rule else fields, asks, now)
def grouped(permissions: object) -> list[dict]:
"""Returns:
The allow, ask and deny entries of a permissions section grouped by
@@ -270,8 +258,7 @@ class Firewall:
now = time.time()
asks = self.recent_subjects("ask", now)
listed = [{key: entry[key] for key in ("path", "exists", "folder", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
rules = {rule["id"]: stored_hits(rule, asks, now) for rule in self.rules.listed()}
return {**meta, "files": listed, "lists": list(signing.SETTINGS_LISTS), "patterns": deny_patterns(), "groups": self.groups.listed(), "sets": self.rule_sets.listed(), "days": RECENT_DAYS, "rules": rules}
return {**meta, "files": listed, "lists": list(signing.SETTINGS_LISTS), "patterns": deny_patterns(), "groups": self.groups.listed(), "sets": self.rule_sets.listed(), "days": RECENT_DAYS}
def settings_changes(self, raw: object) -> list[dict]:
"""Args:
+3 -34
View File
@@ -1,22 +1,17 @@
from __future__ import annotations
import sqlite3
import time
from contextlib import closing
from pathlib import Path
from types import ModuleType
from .errors import ToolError
from .fields import decode, expect
from .jobs import GATE_JOB
from .jobs import GATE_JOB, argv_items
from .signed import signing
from .skill_scripts import script_module
GATES_SCRIPT = "kvb-check-gate/scripts/gates.py"
GATES_DB = "gates.db"
GATE_TASK = "gates"
CHANGE_LIMIT = 100
CHANGE_KEYS = ("kind", "argv")
def gate_request(raw: object) -> bool:
@@ -82,33 +77,7 @@ class Gating:
Returns:
The signed items, each with an argv signing.gate_argv() accepts.
"""
if not isinstance(raw, list) or not 1 <= len(raw) <= CHANGE_LIMIT:
raise ToolError(f"items must be a list of 1 to {CHANGE_LIMIT} gate changes")
signed: list[dict] = []
for entry in raw:
if not isinstance(entry, dict):
raise ToolError("every item must be an object with kind and argv")
expect(entry, CHANGE_KEYS)
try:
item = signing.gate_item(signing.gate_argv(entry["argv"]))
except signing.Refused as error:
raise ToolError(f"gate change: {error}") from None
if item in signed:
raise ToolError("items must be distinct")
signed.append(item)
return signed
return argv_items(raw, lambda argv: signing.gate_item(signing.gate_argv(argv)), "gate change")
def change_gates(self, body: bytes) -> dict:
payload = decode(body)
expect(payload, ("items", "proof"))
items = self.gate_changes(payload["items"])
proof = self.covered(payload["proof"], items, time.time())
for item in items:
self.operator_proven(proof, item)
ids = []
for item in items:
fields = {"kind": GATE_JOB, "task": GATE_TASK, "argv": item["argv"], "command": shown_command(item["argv"]), "directory": "", "sha256": "", "status": "queued", "proof": proof}
ids.append(self.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": None, "finished": None})["id"])
commands = [shown_command(item["argv"]) for item in items]
self.log.add({"kind": "run", "title": f"Gate change signed: {len(items)}", "text": "\n".join(commands), "ref": {"jobs": ids, "status": "queued"}})
return {"jobs": ids, "status": "queued"}
return self.signed_jobs(body, self.gate_changes, GATE_JOB, GATE_TASK, shown_command)
+38 -11
View File
@@ -17,6 +17,7 @@ from .rates import rated
from .resources import RESOURCES, sampled
from .scores import scored
from .skillindex import SKILLS_INDEX, served
from .usage import usage_view
BODY_LIMIT = 1 << 20
UPLOAD_LIMIT = 50 << 20
@@ -35,7 +36,9 @@ PREVIEWS_ROUTE = "/api/runner/previews"
RESTART_ROUTE = "/api/runner/restart"
MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"}
HOOK_POSTS = {"/api/asks": "ask", "/api/decisions": "question"}
POSTS = (*HOOK_POSTS, UPLOADS, "/api/messages", *MATCH_POSTS)
ASK_RAN = "/api/asks/ran"
LOCAL_POSTS = {**MATCH_POSTS, ASK_RAN: "ask_ran"}
POSTS = (*HOOK_POSTS, UPLOADS, "/api/messages", *LOCAL_POSTS)
STORED = {
"page": (".html", "text/html; charset=utf-8", PAGE_CSP),
"files": (".json", "application/json", PLAIN_CSP),
@@ -49,14 +52,18 @@ RUNNER_ROUTE = re.compile(r"/api/runner/([0-9a-f]{16})/(claim|report)")
PROOF_ROUTE = re.compile(r"/api/reviews/([0-9a-f]{16})")
SIGN_ROUTE = "/api/sign"
RULE_SIGN_ROUTE = "/api/rules/sign"
RULE_MATCH_ROUTE = "/api/rules/match"
CLEANUP_ROUTE = "/api/cleanup"
CLEANUP_STATE = re.compile(r"/api/cleanup/([0-9a-f]{16})")
OFFICES_ROUTE = "/api/offices"
OFFICE_STATE = re.compile(r"/api/offices/([0-9a-f]{16})")
TASKS_ROUTE = "/api/tasks"
GATES_ROUTE = "/api/gates"
QUEUE_ROUTE = "/api/queue"
PRUNE_ROUTE = "/api/prune"
TOKEN_ROUTE = "/api/cleanup/token"
VIEW_ROUTE = "/api/view"
USAGE_ROUTE = "/api/usage"
ENCODER_ROUTE = "/gibberlink"
VENDOR_ROUTE = re.compile(r"/vendor/([a-z0-9.-]{1,64})")
SCRIPT_TYPE = "text/javascript; charset=utf-8"
@@ -84,11 +91,13 @@ FIREWALL_DROP = re.compile(r"/api/firewall/(groups|sets)/([0-9a-f]{16})/delete")
FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPStatus.ACCEPTED, "add_group": HTTPStatus.CREATED, "add_set": HTTPStatus.CREATED}
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACCOUNTS_ROUTE = "/api/accounts"
ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete")
ACCOUNT_ITEM = re.compile(r"/api/accounts/([0-9a-f]{16})/(delete|calibrate)")
ACCOUNTS_EXPORT = "/api/accounts/export"
ACCOUNTS_IMPORT = {"/api/accounts/import/preview": "preview", "/api/accounts/import/apply": "apply"}
SCHEDULES_ROUTE = "/api/schedules"
ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE,"/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
LIMITS_ROUTE = "/api/limits"
LIMITS_SIGN_ROUTE = "/api/limits/sign"
ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE, LIMITS_SIGN_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, RULE_MATCH_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, QUEUE_ROUTE, PRUNE_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
class Handler(Exchange):
@@ -155,6 +164,10 @@ class Handler(Exchange):
self.attempt(lambda: hub.events(self.query()), self.send_tagged)
elif path == "/api/tree":
self.answer(hub.repositories, HTTPStatus.OK)
elif path == QUEUE_ROUTE:
self.answer(hub.queue_view, HTTPStatus.OK)
elif path == LIMITS_ROUTE:
self.answer(hub.limits_view, HTTPStatus.OK)
elif path == "/api/skills":
self.answer(lambda: served(hub.tree.file.with_name(SKILLS_INDEX)), HTTPStatus.OK)
elif path == MATCH_ROUTE:
@@ -165,6 +178,8 @@ class Handler(Exchange):
self.export_accounts()
elif path == "/api/resources":
self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK)
elif path == USAGE_ROUTE:
self.answer(lambda: usage_view(hub.kept / RESOURCES, self.query(), time.time()), HTTPStatus.OK)
elif path == "/api/scores":
self.answer(lambda: scored(hub.council, hub.scripts.skills, hub.span(self.query(), time.time())), HTTPStatus.OK)
elif path == "/api/rates":
@@ -206,16 +221,22 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.sign_board(body), HTTPStatus.OK)
if board:
return lambda body: self.answer(lambda: hub.board(board.group(1), body), HTTPStatus.OK)
drop = ACCOUNT_DROP.fullmatch(path)
account = ACCOUNT_ITEM.fullmatch(path)
if path == ACCOUNTS_ROUTE:
return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK)
if path in ACCOUNTS_IMPORT:
method = getattr(Transfer(hub.accounts.ledger), ACCOUNTS_IMPORT[path])
return lambda body: self.answer(lambda: method(body), HTTPStatus.OK)
if drop:
return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK)
if account and account.group(2) == "calibrate":
return lambda body: self.answer(lambda: hub.accounts.calibrate(account.group(1), body, time.time()), HTTPStatus.OK)
if account:
return lambda _body: self.answer(lambda: hub.accounts.drop(account.group(1)), HTTPStatus.OK)
if path == SCHEDULES_ROUTE:
return lambda body: self.answer(lambda: hub.schedule_settings.save(body), HTTPStatus.OK)
return lambda body: self.answer(lambda: hub.save_schedule(body), HTTPStatus.OK)
if path == LIMITS_ROUTE:
return lambda body: self.answer(lambda: hub.save_limits(body), HTTPStatus.OK)
if path == LIMITS_SIGN_ROUTE:
return lambda body: self.answer(lambda: hub.sign_limits(body), HTTPStatus.OK)
reveal = REVEAL_ROUTE.fullmatch(path)
if reveal:
method = hub.sign_reveal if reveal.group(3) else hub.reveal
@@ -240,6 +261,8 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.sign(body), HTTPStatus.OK)
if path == RULE_SIGN_ROUTE:
return lambda body: self.answer(lambda: hub.sign_rule(body), HTTPStatus.OK)
if path == RULE_MATCH_ROUTE:
return lambda body: self.answer(lambda: hub.match_rule(body), HTTPStatus.OK)
if path == CLEANUP_ROUTE:
return lambda body: self.answer(lambda: hub.cleanup(body), HTTPStatus.ACCEPTED)
if path == OFFICES_ROUTE:
@@ -248,6 +271,10 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.change_tasks(body), HTTPStatus.ACCEPTED)
if path == GATES_ROUTE:
return lambda body: self.answer(lambda: hub.change_gates(body), HTTPStatus.ACCEPTED)
if path == QUEUE_ROUTE:
return lambda body: self.answer(lambda: hub.change_queue(body), HTTPStatus.ACCEPTED)
if path == PRUNE_ROUTE:
return lambda body: self.answer(lambda: hub.prune(body), HTTPStatus.ACCEPTED)
if path == TOKEN_ROUTE:
return lambda body: self.answer(lambda: hub.token_row(body), HTTPStatus.CREATED)
if inbox:
@@ -297,7 +324,7 @@ class Handler(Exchange):
return None
def posted(self, path: str) -> bool:
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE, ACCOUNT_DROP))
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE, ACCOUNT_ITEM))
def runner(self, path: str, body: bytes) -> None:
hub = self.server.hub
@@ -318,10 +345,10 @@ class Handler(Exchange):
"""
if path == "/mcp":
return self.mcp_receiver(host)
if path in HOOK_POSTS or path in MATCH_POSTS:
if path in HOOK_POSTS or path in LOCAL_POSTS:
if self.local(host):
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)
receive = getattr(self.server.hub, LOCAL_POSTS.get(path) or HOOK_POSTS[path])
return lambda body: self.answer(lambda: receive(body), HTTPStatus.OK if path in LOCAL_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
if RUNNER_ROUTE.fullmatch(path) or path in (PREVIEWS_ROUTE, RESTART_ROUTE):
+8 -1
View File
@@ -29,6 +29,7 @@ from .inbox import Inbox
from .jobs import Jobs
from .language import Language, Model
from .ledger import Ledger, Marks, Reviews, Sealed
from .limiting import Limiting
from .livestate import LiveState
from .matching import Matching
from .mcp import Mcp
@@ -37,7 +38,9 @@ from .names import Names
from .offices import Offices
from .presence import SNAPSHOT
from .previewing import Previewing
from .prunes import Prunes
from .queue_order import QUEUE_SCRIPT, QueueOrder
from .queueing import Queueing
from .receipts import (
NAMES,
READS,
@@ -53,7 +56,9 @@ from .resources import RESOURCES, SAMPLES
from .revealing import Revealing
from .reviewing import Reviewing
from .rules import Offers, Rules
from .running import RUNNER_JOB
from .schedules import Schedules
from .scheduling import Scheduling
from .settings import Settings
from .signed import signing
from .skill_scripts import Runner
@@ -91,7 +96,7 @@ def environment(templates: Path) -> jinja2.Environment:
@dataclass(frozen=True)
class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Firewall, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language):
class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Queueing, Scheduling, Limiting, Prunes, Firewall, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language):
council: Path
pages: Path
public_port: int
@@ -118,6 +123,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
watch: Watch
tree: Tree
agent_sessions: Path
runner_marker: Path
model: Model
timers: Path
kept: Path
@@ -231,6 +237,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
watch=Watch(),
tree=Tree(file=places.tree_file, heartbeat=state / TREE_HEARTBEAT, lock=threading.Lock(), cached=None, stamp=None),
agent_sessions=state / SNAPSHOT,
runner_marker=state / RUNNER_JOB,
model=model,
timers=places.timers,
kept=places.kept,
+50 -9
View File
@@ -16,12 +16,39 @@ from .signed import signing
from .skill_scripts import task_pattern
SNOOZE_LIMIT = 8 * 86400
LAPSE_WINDOW = 86400
def item_base() -> dict:
return {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": ""}
def lapsed_of(records: list[dict], now: float, called: bool) -> list[dict]:
"""Args:
records: asks or decisions; a decision without expires never lapses.
now: the current time in epoch seconds.
called: True for asks, which count only with the call_key of their
call: an ask of an older hook has none, and one whose call ran is
no longer pending (ask_ran()).
Returns:
The records still pending whose expires passed at most LAPSE_WINDOW
ago: what expired before the operator decided it. A decided record
is never among them.
"""
return [record for record in records if record.get("status") == "pending" and now - LAPSE_WINDOW <= record.get("expires", now + 1) <= now and (record.get("call_key") or not called)]
def decision_item(base: dict, decision: dict) -> dict:
recommended = decision.get("recommended", "")
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi"))}
return {**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields}
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": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": ""}
base = item_base()
items = []
for review in self.reviews.pending():
created = iso_epoch(review["created"]) or now
@@ -29,14 +56,8 @@ class Inbox:
agent = review.get("agent", "")
fields = {"title": review["title"], "detail": review["branch"], "green": gate == "pass", "gate": gate, "score": review.get("score", ""), "directory": review["worktree"], "agent": agent, "to": requester_of(claims, agent)[0], "diff": review.get("diff_files")}
items.append({**base, "kind": "review", "id": review["id"], "ts": created, **fields})
for ask in (ask for ask in self.asks.pending() if ask["expires"] > now):
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 (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, "multi": bool(decision.get("multi"))}
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
items += [self.inbox_ask(base, ask, claims, directory) for ask in self.asks.pending() if ask["expires"] > now]
items += [decision_item(base, decision) for decision in self.decisions.pending() if decision_status(decision, now) == "pending"]
held = self.open_jobs()
reasons = self.blocked_rows(now)
consoles = self.consoles()
@@ -54,11 +75,31 @@ class Inbox:
fields = {"title": job["command"], "command": job["command"], "directory": job["directory"], "job": console_of(job), "settled": True}
items.append({**base, "kind": "operator", "id": task, "ts": job["created_ts"], **fields})
items += self.request_items(base, now, claims)
return self.marked_items(items, now)
def marked_items(self, items: list[dict], now: float) -> list[dict]:
for item in items:
mark = self.marks.get(f"{item['kind']}:{item['id']}")
item.update(pinned=mark["pinned"], until=mark["until"] if mark["until"] > now else 0.0, held=self.batches.holds(item["kind"], item["id"]))
return sorted(items, key=lambda item: (not item["pinned"], -item["ts"], item["id"]))
def inbox_ask(self, base: dict, ask: dict, claims: list[dict], directory: Directory) -> dict:
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")}
return {**base, "kind": "ask", "id": ask["id"], "ts": ask["created_ts"], **fields, "command": ask["command"], "directory": ask["cwd"]}
def lapsed_items(self, now: float, directory: Directory) -> list[dict]:
"""Returns:
An item as inbox() builds it, with its expires, of every ask and
decision lapsed_of() keeps; the Inbox lists none of them, Match
keeps each greyed until the operator denies it.
"""
claims = read_claims(self.council)
base = item_base()
asks = [{**self.inbox_ask(base, ask, claims, directory), "expires": ask["expires"]} for ask in lapsed_of(self.asks.pending(), now, True)]
decisions = [{**decision_item(base, decision), "to": requester_of(claims, decision["agent"])[0], "expires": decision["expires"]} for decision in lapsed_of(self.decisions.pending(), now, False)]
return self.marked_items(asks + decisions, now)
def linked(self, command: str) -> list[dict]:
"""Returns:
{"id", "status", "gate"} of each review the approval.py verify
+118 -4
View File
@@ -1,11 +1,12 @@
from __future__ import annotations
import time
from collections.abc import Callable
from .errors import Conflict, Missing, ToolError
from .fields import bounded, decode, expect, field
from .register import OPERATOR, REGISTER, operator_rows, read_register, runnable
from .signed import operator_signed
from .signed import operator_signed, signing
from .skill_scripts import OPERATOR_SCRIPT, OUTPUT_LIMIT
JOB_OPEN = ("queued", "running")
@@ -13,7 +14,12 @@ RUN_OUTPUT = 64 << 10
CONSOLE = ("id", "status", "code", "output", "created_ts", "started", "finished")
TASK_JOB = "task"
GATE_JOB = "gate"
CHANGES = (TASK_JOB, GATE_JOB)
QUEUE_JOB = "queue"
SCHEDULE_JOB = "schedule"
PRUNE_JOB = signing.PRUNE_KIND
CHANGES = (TASK_JOB, GATE_JOB, QUEUE_JOB, SCHEDULE_JOB, PRUNE_JOB)
ARGV_LIMIT = 100
ARGV_KEYS = ("kind", "argv")
UNRUNNABLE = "The hub runner needs a command and an absolute directory, and this row lacks one; run it with operator.py run in a terminal."
RESTARTED = "the runner restarted while this job ran; run the row again"
@@ -22,12 +28,42 @@ def runner_job(job: dict) -> dict:
"""Returns:
What the runner claims: an operator command, with head when a Match
release bound it to a merge preview of that HEAD, or a task or gate
change with kind and argv; a runner that predates such changes
change with kind and argv, and not_before when the signed item
holds the job back until then; a runner that predates such changes
verifies them as an operator command and refuses them.
"""
change = {"kind": job["kind"], "argv": job["argv"]} if job.get("kind") in CHANGES else {}
head = {"head": job["head"]} if job.get("head") else {}
return {**{key: job[key] for key in ("id", "task", "command", "directory", "sha256")}, **change, **head, "proof": job.get("proof")}
held = {"not_before": job["not_before"]} if job.get("not_before") is not None else {}
return {**{key: job[key] for key in ("id", "task", "command", "directory", "sha256")}, **change, **head, **held, "proof": job.get("proof")}
def argv_items(raw: object, item_of: Callable[[object], dict], noun: str) -> list[dict]:
"""Args:
raw: the page's items, each {"kind", "argv"}; the staged changes go
under one passkey assertion.
item_of: the signed item of an argv, raising signing.Refused for an
argv of another shape.
noun: what one change is, for the errors.
Returns:
The distinct signed items, one per change, in page order.
"""
if not isinstance(raw, list) or not 1 <= len(raw) <= ARGV_LIMIT:
raise ToolError(f"items must be a list of 1 to {ARGV_LIMIT} {noun}s")
signed: list[dict] = []
for entry in raw:
if not isinstance(entry, dict):
raise ToolError("every item must be an object with kind and argv")
expect(entry, ARGV_KEYS)
try:
item = item_of(entry["argv"])
except signing.Refused as error:
raise ToolError(f"{noun}: {error}") from None
if item in signed:
raise ToolError("items must be distinct")
signed.append(item)
return signed
def console_of(job: dict | None) -> dict | None:
@@ -59,6 +95,33 @@ def blocked_reasons(jobs: list[dict], now: float) -> dict[str, str]:
return reasons
def blocked_kinds(jobs: list[dict]) -> dict[str, str]:
"""Args:
jobs: every hub job record.
Returns:
Per task with a queued or running hub job its kind, running when
any of its jobs runs, else queued: the stamp of blocked_reasons().
"""
kinds: dict[str, str] = {}
for job in jobs:
if job["status"] in JOB_OPEN and kinds.get(job["task"]) != "running":
kinds[job["task"]] = job["status"]
return kinds
def row_blocked_kind(row: dict, kinds: dict[str, str]) -> str:
"""Args:
row: an open operator row.
kinds: blocked_kinds() of the hub jobs.
Returns:
The kind of row_blocked(): running, queued, unrunnable, or "" when
the row is not blocked.
"""
return kinds.get(row["task"]) or ("" if row["check"] == "decision" or runnable(row) else "unrunnable")
def row_blocked(row: dict, reasons: dict[str, str]) -> str:
"""Args:
row: an open operator row.
@@ -112,6 +175,57 @@ class Jobs:
self.jobs.add({**job, "code": None, "output": "", "created_ts": time.time(), "started": None, "finished": None, "dismissed": False})
return "handed to the runner"
def signed_jobs(self, body: bytes, items_of: Callable[[object], list[dict]], kind: str, task: str,
shown: Callable[[list[str]], str]) -> dict:
"""Args:
body: {"items", "proof"} from the page.
items_of: the signed items of the page's items (argv_items()).
kind: the job kind the runner dispatches on, one of CHANGES.
task: the task the jobs carry.
shown: the command line a job shows for its argv.
Returns:
{"jobs": ids, "status": "queued"}: one runner job per item once a
pinned key signed them all, logged as one run.
"""
payload = decode(body)
expect(payload, ("items", "proof"))
items = items_of(payload["items"])
return self.queued_changes(items, self.proven(payload["proof"], items), kind, task, shown)
def proven(self, proof: object, items: list[dict]) -> dict:
"""Returns:
The proof, once a pinned key signed an unexpired approval
listing every item, each used here for the first time;
ToolError otherwise.
"""
checked = self.covered(proof, items, time.time())
for item in items:
self.operator_proven(checked, item)
return checked
def queued_changes(self, items: list[dict], proof: dict, kind: str, task: str, shown: Callable[[list[str]], str]) -> dict:
"""Args:
items: the signed items, each with an argv and, for a job the
runner holds back, not_before.
proof: their checked proof (proven()).
kind: the job kind the runner dispatches on, one of CHANGES.
task: the task the jobs carry.
shown: the command line a job shows for its argv.
Returns:
{"jobs": ids, "status": "queued"}: one runner job per item,
logged as one run.
"""
ids = []
for item in items:
held = {"not_before": item["not_before"]} if "not_before" in item else {}
fields = {"kind": kind, "task": task, "argv": item["argv"], **held, "command": shown(item["argv"]), "directory": "", "sha256": "", "status": "queued", "proof": proof}
ids.append(self.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": None, "finished": None})["id"])
commands = [shown(item["argv"]) for item in items]
self.log.add({"kind": "run", "title": f"{kind.capitalize()} change signed: {len(items)}", "text": "\n".join(commands), "ref": {"jobs": ids, "status": "queued"}})
return {"jobs": ids, "status": "queued"}
def runner_jobs(self) -> dict:
return {"jobs": [runner_job(job) for job in self.jobs.listed() if job["status"] == "queued"]}
+142
View File
@@ -0,0 +1,142 @@
"""Returns:
LIMITS_SCRIPT: the installed limits.py the hub reads, checks and writes
<council>/limits.json with (requirement 084), so it refuses exactly
what queue.py and watch.py refuse.
TARGET_SCRIPT: the installed aimd.py naming the live target file.
PROFILE_TABLE: the profiles of decision 3, per metric (lower, upper,
stop, mayday); cpu and ram hold the profile's band (Calm 50 to 70,
Balanced 70 to 90, Max 80 to 95), and every value grows from Calm
over Balanced to Max, so a calmer profile is never looser. Balanced
keeps the limits.py example but for the ram band.
"""
from __future__ import annotations
import json
import threading
from pathlib import Path
from types import ModuleType
from .errors import ToolError
from .fields import decode, expect
from .records import read_json
from .signed import signing
from .skill_scripts import script_module
LIMITS_SCRIPT = "kvb-org-organize/scripts/limits.py"
TARGET_SCRIPT = "kvb-org-queue/scripts/aimd.py"
PROFILE_TABLE = {
"calm": {"cpu": (50, 70, 85, 95), "ram": (50, 70, 85, 95), "swap": (10, 40, 75, 90), "disk": (60, 75, 90, 95), "psi": (1, 5, 20, 40)},
"balanced": {"cpu": (70, 90, 95, 99), "ram": (70, 90, 94, 97), "swap": (20, 60, 90, 97), "disk": (70, 85, 95, 98), "psi": (1, 10, 30, 60)},
"max": {"cpu": (80, 95, 98, 99), "ram": (80, 95, 97, 99), "swap": (30, 70, 93, 98), "disk": (75, 90, 96, 99), "psi": (2, 15, 40, 70)},
}
FILE_MODE = 0o600
SAVING = threading.Lock()
def limits_module(skills: Path) -> ModuleType:
"""Returns:
The installed limits.py; ToolError while it is missing or lacks the
reader and the check, so the hub never writes a file it cannot check.
"""
module = script_module(skills / LIMITS_SCRIPT)
if module is None or not all(callable(getattr(module, name, None)) for name in ("problem", "read")):
raise ToolError(f"{LIMITS_SCRIPT} is not installed: the hub checks the limits with it")
return module
def profiles(module: ModuleType) -> dict[str, dict[str, dict[str, float]]]:
return {name: {metric: dict(zip(module.LEVELS, row[metric], strict=True)) for metric in module.METRICS} for name, row in PROFILE_TABLE.items()}
def checked(module: ModuleType, value: object) -> dict:
"""Returns:
value, once limits.py problem() finds no fault in it; ToolError
naming the fault otherwise.
"""
why = module.problem(value)
if why is not None:
raise ToolError(why)
return value
def loosened(module: ModuleType, value: dict, held: dict | None) -> list[str]:
"""Args:
value: checked limits.
held: the limits in force (limits.py read()), None while the config
applies, which the hub cannot compare against.
Returns:
`<metric>.<level>` of every value above the one in force: a higher
lower or upper admits more load, a higher stop or mayday raises an
alarm threshold; every value while none is in force.
"""
pairs = [(metric, level) for metric in module.METRICS for level in module.LEVELS]
return [f"{metric}.{level}" for metric, level in pairs if held is None or value[metric][level] > held[metric][level]]
def live_target(skills: Path, council: Path) -> dict[str, float] | None:
"""Returns:
{cpu, ram}: the AIMD target queue.py last stored, each a finite
number or None; None while aimd.py is missing or no target is stored.
"""
aimd = script_module(skills / TARGET_SCRIPT)
if aimd is None or not isinstance(getattr(aimd, "NAME", None), str) or not callable(getattr(aimd, "number", None)):
return None
stored = read_json(council / aimd.NAME)
if not isinstance(stored, dict):
return None
return {resource: stored[resource] if aimd.number(stored.get(resource)) else None for resource in aimd.RESOURCES}
class Limiting:
def limits_view(self) -> dict:
"""Returns:
{limits, why, target, profiles, metrics, levels}: the limits in
force (None while the config applies), why limits.json was
refused (None when it was not), the live target (live_target()),
the profiles of PROFILE_TABLE and the metric and level names.
"""
module = limits_module(self.scripts.skills)
held, why = module.read(self.council)
return {"limits": held, "why": why, "target": live_target(self.scripts.skills, self.council), "profiles": profiles(module),
"metrics": list(module.METRICS), "levels": list(module.LEVELS)}
def limits_items(self, module: ModuleType, value: dict) -> list[dict]:
held, _ = module.read(self.council)
return [signing.limits_item(value)] if loosened(module, value, held) else []
def sign_limits(self, body: bytes) -> dict:
"""Args:
body: {limits}: the whole limits object the page wants to save.
Returns:
challenge_for() over the limits item when a value loosens, with
payload None when every value stays or tightens.
"""
payload = decode(body)
expect(payload, ("limits",))
module = limits_module(self.scripts.skills)
return self.challenge_for(self.limits_items(module, checked(module, payload["limits"])))
def save_limits(self, body: bytes) -> dict:
"""Args:
body: {limits, proof}: the whole limits object and, when a value
loosens against the limits in force at this save, the
passkey proof over signing.limits_item() of exactly it.
Returns:
limits_view() after the write; ToolError (400) for limits
limits.py refuses or a looser save without a valid proof, which
writes nothing.
"""
payload = decode(body)
expect(payload, ("limits", "proof"))
module = limits_module(self.scripts.skills)
value = checked(module, payload["limits"])
with SAVING:
for item in self.limits_items(module, value):
self.operator_proven(payload["proof"], item)
self.council.mkdir(parents=True, exist_ok=True)
module.nofollow.replace(self.council, self.council / module.NAME, json.dumps(value, indent=1, sort_keys=True) + "\n", FILE_MODE)
return self.limits_view()
+31 -10
View File
@@ -4,13 +4,13 @@ import json
import time
from .council import NEWS, read_claims
from .denying import requester_of
from .denying import LAPSED, requester_of
from .diffs import stored_diff
from .errors import Conflict, Missing, ToolError
from .fields import decode, expect, field
from .jobs import row_blocked
from .jobs import blocked_kinds, row_blocked, row_blocked_kind
from .payloads import denied_roots, payload_files, payload_hash
from .previewing import merge_hash
from .previewing import TREE, merge_hash, preview_line
from .records import digest, iso_epoch, read_jsonl
from .register import REGISTER, adder, operator_rows, read_register
from .scores import metric_chips, score_labels
@@ -19,6 +19,19 @@ from .tree import inside
OPERATOR = "operator/"
WAITING = ("ask", "decision", "rule")
EXPIRED = "expired"
EXPIRED_REASON = f"{LAPSED.capitalize()}: its tool call went back to the terminal, only Reject is left"
def expired_card(card: dict, expires: float) -> dict:
"""Args:
card: the waiting_card() of an ask or decision lapsed_of() keeps.
expires: when it expired, in epoch seconds.
Returns:
The card greyed with blocked_kind EXPIRED and its expires time.
"""
return {**card, "blocked": EXPIRED_REASON, "blocked_kind": EXPIRED, "expires": expires}
def repository_of(common_dir: str) -> str:
@@ -50,7 +63,9 @@ class Matching:
"""Returns:
{"now", "cards"}: every card waiting on the operator, none held
by a release in its undo window or while it applies; a held
command card keeps its snapshot, so an undo shows it unchanged.
command card keeps its snapshot, so an undo shows it unchanged;
an expired ask or decision stays, greyed by expired_card(),
until the operator denies it.
"""
now = time.time()
claims = read_claims(self.council)
@@ -61,6 +76,7 @@ class Matching:
cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"])]
tasks = read_register(self.council / REGISTER)
blocked = self.blocked_rows(now)
kinds = blocked_kinds(self.jobs.listed())
rows = [row for row in operator_rows(tasks) if row["check"] != "decision"]
releasing = {f"operator:{row['task']}" for row in rows if self.batches.holds("operator", row["task"])}
roots = denied_roots(self.settings_files()[0])
@@ -69,9 +85,11 @@ class Matching:
if f"operator:{row['task']}" in releasing:
continue
owner = adder(tasks[row["task"]])
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0], "blocked": row_blocked(row, blocked)})
items = self.inbox(now, tasks, self.directory(claims, read_jsonl(self.council / NEWS), now))
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0], "blocked": row_blocked(row, blocked), "blocked_kind": row_blocked_kind(row, kinds)})
directory = self.directory(claims, read_jsonl(self.council / NEWS), now)
items = self.inbox(now, tasks, directory)
cards += [self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels) for item in items if self.waits(item)]
cards += [expired_card(self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels), item["expires"]) for item in self.lapsed_items(now, directory) if self.waits(item)]
asked = {row["task"] for row in operator_rows(tasks) if row["check"] == "decision"}
for answer in self.answers.listed():
if answer["id"] not in asked:
@@ -117,7 +135,7 @@ class Matching:
def card_payload(self, row: dict, roots: list[str] | None) -> tuple[list[dict], str, dict | None]:
"""Returns:
What a command card shows and is bound to: the runner's merge
preview diff and merge_hash() for a git merge it previewed, else
preview diff and merge_hash() for a git merge or commit-tree it previewed, else
the named payload files and payload_hash(); and the preview.
"""
preview = self.preview_of(row)
@@ -158,6 +176,9 @@ class Matching:
files = stored_diff(self.reviews.pages, "ask", item["id"])["diff"]
except Missing:
files = None
preview = self.ask_preview(item["id"]) if item["kind"] == "ask" and item["diff"] is None else None
if preview is not None:
files = preview.get("diff", [])
repo, branch, worktree = place_of(item["directory"], scan) if item["directory"] else ("", "", "")
shown = digest(json.dumps([item["title"], item["command"], item["detail"], item["options"], item["rule"]], sort_keys=True))
return {
@@ -165,7 +186,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"], "multi": item["multi"], "warnings": item["warnings"], "rule": item["rule"], "dry_run": item["dry_run"],
"recommended": item["recommended"], "multi": item["multi"], "warnings": item["warnings"], "rule": item["rule"], "dry_run": item["dry_run"], "merge": preview_line(preview),
}
def command_card(self, row: dict, agent: str, born: float | None, roots: list[str] | None, scan: dict, labels: dict | None) -> dict:
@@ -176,8 +197,8 @@ class Matching:
self.match_snapshots.remove(card_id)
snapshot = self.match_snapshots.insert(card_id, {"command_sha256": digest(row["command"]), "hash": live, "files": files, "previewed": preview is not None, "taken": time.time()})
stale = snapshot["hash"] != live
moved = "HEAD or the merge base moved since it was added" if preview is not None else "a payload file changed since it was added"
merge = None if preview is None else {key: preview.get(key, "") for key in ("head", "base", "target", "error")}
merge = preview_line(preview)
moved = "a payload file changed since it was added" if merge is None else "its diff changed since it was added" if merge["kind"] == TREE else "HEAD or the merge base moved since it was added"
repo, branch, worktree = place_of(row["directory"], scan)
return {
"id": card_id, "kind": "command", "ref": row["task"], "agent": agent, "born": born, "created_ts": snapshot["taken"], "repo": repo, "branch": branch, "worktree": worktree,
+32 -3
View File
@@ -10,6 +10,7 @@ STALE = 15 * 60
UNANSWERED = 10 * 60
SNAPSHOT = "agent-sessions.json"
SNAPSHOT_STALE = 5 * 60
BUSY = "busy"
def fresh_snapshot(path: Path, now: float) -> dict[str, dict] | None:
@@ -38,6 +39,35 @@ def read_snapshot(path: Path, now: float) -> dict[str, dict]:
return fresh_snapshot(path, now) or {}
def status_time(record: dict) -> float | None:
"""Returns:
The record's statusUpdatedAt, which the host stores in
milliseconds, in epoch seconds; None when it is no valid time.
"""
stamp = record.get("statusUpdatedAt")
return epoch(stamp / 1000) if isinstance(stamp, int | float) and not isinstance(stamp, bool) else None
def beats(sessions: dict[str, dict], claims: list[dict]) -> dict[str, float]:
"""Args:
sessions: the session records of read_snapshot.
claims: the council claims.
Returns:
The latest heartbeat per agent name as agent() reads it, in epoch
seconds: the status_time of each running busy session record and
the beat of each claim an agent other than the Operator holds.
Kanban.marks judges how fresh a beat must be.
"""
stamps = [(agent(record.get("name")), status_time(record)) for record in sessions.values() if record.get("running") is True and record.get("status") == BUSY]
stamps += [(claim["agent"], claim["beat"]) for claim in claims if claim["agent"] != HUMAN]
found: dict[str, float] = {}
for name, beat in stamps:
if name and beat is not None:
found[name] = max(beat, found.get(name, beat))
return found
def unanswered(news: list[dict], now: float) -> list[tuple[str, float]]:
"""Returns:
(callee, call time) of every call older than UNANSWERED without a
@@ -85,9 +115,8 @@ def presence(sessions: dict[str, dict], parts: dict[str, str], mode: str, claims
if record.get("running") is not True:
states[sid] = "dead"
continue
busy = record.get("status") == "busy"
stamp = record.get("statusUpdatedAt")
updated = (epoch(stamp / 1000) if isinstance(stamp, int | float) and not isinstance(stamp, bool) else None) or 0
busy = record.get("status") == BUSY
updated = status_time(record) or 0
called = names.get(sid, set()) | {agent(record.get("name")), sid}
if (busy and now - updated > STALE) or any(name in called and ts > updated for name, ts in late):
states[sid] = "unreachable"
+75 -9
View File
@@ -17,6 +17,12 @@ SHOWN = ("task", "command", "head", "base", "target", "diff")
FAILED = ("task", "command", "head", "error")
REVIEW_SHOWN = ("id", "head", "diff")
REVIEW_FAILED = ("id", "head", "error")
ASK_SHOWN = ("ask", "head", "base", "target", "diff")
ASK_FAILED = ("ask", "head", "error")
MERGE = "merge"
TREE = "commit-tree"
KINDS = (MERGE, TREE)
SHELL = "Bash"
def card_id(task: str) -> str:
@@ -27,6 +33,27 @@ def review_card(review_id: str) -> str:
return f"review:{review_id}"
def ask_card(ask_id: str) -> str:
return f"ask:{ask_id}"
def previewable(ask: dict, now: float) -> bool:
"""Returns:
Whether the runner may preview an ask: a pending, unexpired Bash ask
in an absolute directory whose hook shipped no diff.
"""
return ask["status"] == "pending" and ask["expires"] > now and ask["tool"] == SHELL and ask.get("diff_files") is None and ask["cwd"].startswith("/")
def preview_line(preview: dict | None) -> dict | None:
"""Returns:
What a Match card shows of a runner preview: its kind, MERGE or
TREE, with head, base, target and error, "" for each it lacks; None
without a preview.
"""
return None if preview is None else {"kind": preview.get("kind", MERGE), **{key: preview.get(key, "") for key in ("head", "base", "target", "error")}}
def object_id(payload: dict, name: str, empty: bool) -> str:
value = payload[name]
if not isinstance(value, str) or not (OBJECT_ID.fullmatch(value) or (empty and value == "")):
@@ -36,12 +63,13 @@ def object_id(payload: dict, name: str, empty: bool) -> str:
def merge_hash(row: dict, preview: dict) -> str:
"""Returns:
The sha256 a merge card is bound to: its command, directory, the
HEAD, merge base and target the runner previewed and the digest of
the diff or the error it sent.
The sha256 a merge or commit-tree card is bound to: its kind,
command, directory, the HEAD, merge base and target the runner
previewed (the parent twice and the tree for a commit-tree) and the
digest of the diff or the error it sent.
"""
shown = {key: preview.get(key, "") for key in ("head", "base", "target", "error")}
return signing.item_hash({"kind": "merge", "command": row["command"], "directory": row["directory"], **shown, "diff": digest(json.dumps(preview.get("diff", []), sort_keys=True))})
return signing.item_hash({"kind": preview.get("kind", MERGE), "command": row["command"], "directory": row["directory"], **shown, "diff": digest(json.dumps(preview.get("diff", []), sort_keys=True))})
class Previewing:
@@ -71,6 +99,14 @@ class Previewing:
"""
return None if self.shipped(review_id) else self.merge_previews.get(review_card(review_id))
def ask_preview(self, ask_id: str) -> dict | None:
"""Returns:
The runner's commit-tree preview of an ask whose hook shipped no
diff: {kind, head, base, target, diff} or {kind, head, error};
None before any.
"""
return self.merge_previews.get(ask_card(ask_id))
def preview_rows(self) -> dict:
"""Returns:
{"rows", "reviews"}: every open operator row in an absolute
@@ -78,16 +114,38 @@ class Previewing:
none, for the runner to preview the git merges among them; and
every pending review in an absolute worktree that shipped no
diff, with its tree and the HEAD the hub last saw, for the
runner to diff the tree against HEAD.
runner to diff the tree against HEAD; and "asks", every ask
previewable() keeps, with the parent of the preview the hub
holds, None for none, for the runner to preview the git
commit-trees among them.
"""
now = time.time()
rows = [row for row in self.open_rows() if row["directory"].startswith("/")]
asks = [ask for ask in self.asks.pending() if previewable(ask, now)]
reviews = [review for review in self.reviews.pending() if review["worktree"].startswith("/") and not self.shipped(review["id"])]
seen = {review["id"]: self.merge_previews.get(review_card(review["id"])) or {} for review in reviews}
return {
"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows],
"reviews": [{"id": review["id"], "worktree": review["worktree"], "tree": review["tree"], "head": seen[review["id"]].get("moved") or seen[review["id"]].get("head")} for review in reviews],
"asks": [{"id": ask["id"], "command": ask["command"], "cwd": ask["cwd"], "head": (self.ask_preview(ask["id"]) or {}).get("head")} for ask in asks],
}
def record_ask_preview(self, payload: dict) -> dict:
expect(payload, ASK_FAILED if "error" in payload else ASK_SHOWN)
ask_id = payload["ask"]
ask = self.asks.get(ask_id) if isinstance(ask_id, str) else None
if ask is None or not previewable(ask, time.time()):
raise Missing(str(ask_id))
record = {"kind": TREE, "head": object_id(payload, "head", False), "taken": time.time()}
if "error" in payload:
record["error"] = bounded(payload, "error", ERROR_LIMIT)
else:
record.update(base=object_id(payload, "base", False), target=object_id(payload, "target", False), diff=valid_diff(payload["diff"]))
key = ask_card(ask["id"])
self.merge_previews.remove(key)
self.merge_previews.insert(key, record)
return {"id": key, "head": record["head"]}
def record_review_preview(self, payload: dict) -> dict:
expect(payload, REVIEW_FAILED if "error" in payload else REVIEW_SHOWN)
review_id = field(payload, "id")
@@ -113,13 +171,21 @@ class Previewing:
"""Args:
body: from the runner, {task, command, head, base, target, diff}
for a git merge row, or {task, command, head, error} when it
could not preview it; {id, head, diff} or {id, head, error}
for a review that shipped no diff; head is empty when HEAD is
unreadable.
could not preview it, each with kind TREE for a git
commit-tree row (head and base its parent, target its
tree); {id, head, diff} or {id, head, error} for a review
that shipped no diff; {ask, head, base, target, diff} or
{ask, head, error} for the commit-tree of an ask
previewable() keeps; head is empty when HEAD is unreadable.
"""
payload = decode(body)
if "id" in payload:
return self.record_review_preview(payload)
if "ask" in payload:
return self.record_ask_preview(payload)
kind = payload.pop("kind", MERGE)
if kind not in KINDS:
raise ToolError(f"kind must be one of {', '.join(KINDS)}")
expect(payload, FAILED if "error" in payload else SHOWN)
task = payload["task"]
if not isinstance(task, str) or not task.startswith(OPERATOR) or not signing.TASK.fullmatch(task):
@@ -129,7 +195,7 @@ class Previewing:
raise Missing(task)
if payload["command"] != row["command"]:
raise Conflict({"id": task, "status": "changed"})
record = {"command": row["command"], "head": object_id(payload, "head", "error" in payload), "taken": time.time()}
record = {"command": row["command"], "kind": kind, "head": object_id(payload, "head", "error" in payload), "taken": time.time()}
if "error" in payload:
record["error"] = bounded(payload, "error", ERROR_LIMIT)
else:
+11
View File
@@ -0,0 +1,11 @@
{
"date": "2026-10-06",
"source": "Input and output from the kvb-org-perform skill table (claude-api reference, cached 2026-10-06); cache read 0.1 x input and cache write 1.25 x input, Anthropic's standard 5-minute cache multipliers",
"unit": "USD per million tokens",
"families": {
"haiku": {"model": "Haiku 5.5", "input": 0.1, "output": 0.5, "cache_read": 0.01, "cache_write": 0.125},
"sonnet": {"model": "Sonnet 5.5", "input": 2, "output": 10, "cache_read": 0.2, "cache_write": 2.5},
"opus": {"model": "Opus 5.5", "input": 4, "output": 20, "cache_read": 0.4, "cache_write": 5},
"fable": {"model": "Fable 5.1", "input": 10, "output": 50, "cache_read": 1, "cache_write": 12.5}
}
}
+77
View File
@@ -0,0 +1,77 @@
from __future__ import annotations
import time
from .errors import ToolError
from .fields import expect
from .jobs import PRUNE_JOB
from .register import ENDED, REGISTER, read_register, status_of
from .signed import pruning, signing
PRUNE_TASK = "prune"
ANNOUNCE_KEYS = ("kind", "argv")
APPLY_KEYS = ("kind", "argv", "not_before")
def prune_request(raw: object) -> bool:
return isinstance(raw, list) and bool(raw) and all(isinstance(entry, dict) and entry.get("kind") == PRUNE_JOB for entry in raw)
def shown_command(argv: list[str]) -> str:
if argv[0] == pruning.ANNOUNCE:
return f"radio.py send security {pruning.announcement(argv)}"
return " ".join(["rasci.py", *argv])
def prune_items(raw: object, now: float, open_tasks: set[str]) -> list[dict]:
"""Args:
raw: the page's two items under one passkey assertion: first
{"kind": "prune", "argv"} with the announce argv, then
{"kind": "prune", "argv", "not_before"} with the rasci.py prune
argv and the deadline (pruning.prune_argv()).
now: the current time in epoch seconds.
open_tasks: the register tasks neither done nor stopped.
Returns:
The two signed items, once both name the same tasks, all open in
the register, the apply job's not_before is the announced deadline,
that deadline lies ahead (pruning.timely()) and --since is no older
than one signature lifetime and at most pruning.SKEW ahead.
"""
if not isinstance(raw, list) or len(raw) != 2 or not all(isinstance(entry, dict) for entry in raw):
raise ToolError("a prune is two items: the announce, then the apply job")
announce, apply = raw
expect(announce, ANNOUNCE_KEYS)
expect(apply, APPLY_KEYS)
try:
first = pruning.prune_argv(announce["argv"], None)
second = pruning.prune_argv(apply["argv"], apply["not_before"])
pruning.timely(first, None, now)
except signing.Refused as error:
raise ToolError(f"prune: {error}") from None
if pruning.tasks_of(first) != pruning.tasks_of(second) or pruning.deadline_of(first) != apply["not_before"]:
raise ToolError("the announce and the apply job must name the same tasks and the same deadline")
if not now - signing.LIFETIME <= int(second[2]) <= now + pruning.SKEW:
raise ToolError("--since must be the epoch the page listed the stale tasks at")
closed = [task for task in pruning.tasks_of(first) if task not in open_tasks]
if closed:
raise ToolError(f"not open in the register: {', '.join(closed)[:300]}")
return [pruning.prune_item(first, None), pruning.prune_item(second, apply["not_before"])]
class Prunes:
def prune_changes(self, raw: object) -> list[dict]:
tasks = read_register(self.council / REGISTER)
return prune_items(raw, time.time(), {task for task, row in tasks.items() if status_of(row) not in ENDED})
def prune(self, body: bytes) -> dict:
"""Args:
body: {"items", "proof"}: the two prune items (prune_items())
and the one passkey assertion over both.
Returns:
{"jobs": ids, "status": "queued"}: the announce job, which the
runner runs at once, and the apply job it holds until the
deadline.
"""
return self.signed_jobs(body, self.prune_changes, PRUNE_JOB, PRUNE_TASK, shown_command)
+52 -16
View File
@@ -21,6 +21,9 @@ ORDER_LIMIT = 1 << 20
TRACE_SHOWN = 20
POSITION_SHOWN = 32
CLASSES = ("hotfix", "fix", "feature", "main")
STATUSES = ("waiting", "active")
LEARNED_ARGS = ("learned", "--json")
LEARNED_KEYS = {"kinds": dict, "signatures": list, "budget_percent": dict, "ram_cap_percent": dict, "load_limits": dict, "slot_limits": dict, "history": list}
def amount(value: object) -> float | None:
@@ -59,8 +62,10 @@ def queue_job(raw: object) -> dict | None:
The row as the board shows it, each field of one type and bounded:
position an int or a word such as run, class one of CLASSES, prio an
int, wsjf (a number or {"score"}), waited_s and eta_s non-negative
numbers, each else None; trace at most TRACE_SHOWN strings; agent
falls back to name. None for a row without a string id.
numbers, status one of STATUSES, each else None; trace at most
TRACE_SHOWN strings; agent falls back to name; override true only
for a row queue.py marked overridden. None for a row without a
string id.
"""
if not isinstance(raw, dict) or not isinstance(raw.get("id"), str) or not raw["id"]:
return None
@@ -79,6 +84,8 @@ def queue_job(raw: object) -> dict | None:
"eta_s": amount(raw.get("eta_s")),
"reason": text(raw.get("reason")),
"trace": steps_of(raw.get("trace")),
"status": raw["status"] if raw.get("status") in STATUSES else None,
"override": raw.get("override") is True,
}
@@ -142,6 +149,39 @@ def grant_order(chain: list[tuple[str, bool]], jobs: list[dict] | None) -> list[
return sorted(chain, key=lambda pair: place.get(pair[0], len(place)))
def queue_output(script: Path, args: tuple[str, ...], home: Path, council: Path) -> str | None:
"""Returns:
What the installed queue.py printed for args, run read-only with
script_env(); None when it fails, overruns ORDER_TIMEOUT or prints
more than ORDER_LIMIT bytes.
"""
try:
done = subprocess.run(
[sys.executable, str(script), *args],
capture_output=True,
timeout=ORDER_TIMEOUT,
env=script_env(home, council),
stdin=subprocess.DEVNULL,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return None
if done.returncode != 0 or len(done.stdout) > ORDER_LIMIT:
return None
return done.stdout.decode("utf-8", errors="replace")
def learned_of(stdout: str | None) -> dict | None:
"""Returns:
What `queue.py learned --json` printed when it is an object holding
every key of LEARNED_KEYS with its type, else None.
"""
data = None if stdout is None else parsed(stdout)
if not isinstance(data, dict) or not all(isinstance(data.get(key), kind) for key, kind in LEARNED_KEYS.items()):
return None
return {key: data[key] for key in LEARNED_KEYS}
@dataclass
class QueueOrder:
script: Path
@@ -153,20 +193,16 @@ class QueueOrder:
at: float = 0.0
def run(self) -> list[dict] | None:
try:
done = subprocess.run(
[sys.executable, str(self.script), *ORDER_ARGS],
capture_output=True,
timeout=ORDER_TIMEOUT,
env=script_env(self.home, self.council),
stdin=subprocess.DEVNULL,
check=False,
)
except (OSError, subprocess.TimeoutExpired):
return None
if done.returncode != 0 or len(done.stdout) > ORDER_LIMIT:
return None
return queue_jobs(done.stdout.decode("utf-8", errors="replace"))
stdout = queue_output(self.script, ORDER_ARGS, self.home, self.council)
return None if stdout is None else queue_jobs(stdout)
def learned(self) -> dict:
"""Returns:
{"learned": learned_of() of a `queue.py learned --json` run, None
while the installed queue.py prints none}; the hub never writes
the queue config, the host runner does (`queue.py config set`).
"""
return {"learned": learned_of(queue_output(self.script, LEARNED_ARGS, self.home, self.council))}
def get(self, live: frozenset[str], now: float) -> list[dict] | None:
"""Args:
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
from .jobs import QUEUE_JOB, argv_items
from .signed import signing
QUEUE_TASK = "queue"
def queue_request(raw: object) -> bool:
return isinstance(raw, list) and bool(raw) and all(isinstance(entry, dict) and entry.get("kind") == QUEUE_JOB for entry in raw)
def shown_command(argv: list[str]) -> str:
return " ".join(["queue.py", *argv])
class Queueing:
def queue_view(self) -> dict:
return self.queue_order.learned()
def queue_changes(self, raw: object) -> list[dict]:
"""Args:
raw: the page's items, each {"kind": "queue", "argv"} with the
queue.py arguments of one Start now (`override <id>`) or one
staged setting (`config set <key> <value>`); a batch goes
under one passkey assertion.
Returns:
The signed items, each with an argv signing.queue_argv() accepts.
"""
return argv_items(raw, lambda argv: signing.queue_item(signing.queue_argv(argv)), "queue change")
def change_queue(self, body: bytes) -> dict:
return self.signed_jobs(body, self.queue_changes, QUEUE_JOB, QUEUE_TASK, shown_command)
+61 -2
View File
@@ -14,6 +14,8 @@ AGENT_CAP = 3
TOTAL_CAP = 20
WHY_LIMIT = 1000
RECENT_DAYS = 7
MATCH_WINDOW = 50
COUNT_ID = "0" * 16
RULE_FIELDS = ("kind", "tool", "pattern", "scope", "expires")
REQUEST_STATE = ("id", "status", "rule", "reason", "decided")
@@ -44,6 +46,28 @@ def matched(record: dict, subjects: list[dict], now: float) -> int:
return sum(rule_matches(rule, kind_name, subject, now) for subject in subjects)
def counted_matches(rule: dict, subjects: list[dict], now: float) -> int:
"""Args:
rule: kind, tool, pattern and scope of a stored or draft rule, with
agents when it applies to one agent or group only.
subjects: what a rule of that kind is matched against.
now: the current time in epoch seconds.
Returns:
How many subjects matched() lets the rule approve, on or off,
expired or not.
"""
return matched({**rule, "id": COUNT_ID, "expires": now + RECENT_DAYS * 86400}, subjects, now)
def window_count(rule: dict, subjects: list[dict], now: float) -> dict:
"""Returns:
{"matched": counted_matches() of the rule, "of": how many subjects there
are}, at most MATCH_WINDOW for last_subjects().
"""
return {"matched": counted_matches(rule, subjects, now), "of": len(subjects)}
class Requesting:
def open_requests(self, now: float) -> list[dict]:
return [record for record in self.rule_requests.pending() if request_status(record, now) == "pending"]
@@ -78,14 +102,49 @@ class Requesting:
raise ToolError(f"no rule request {request_id}")
return request_state(record, time.time())
def kind_records(self, kind_name: str) -> list[dict]:
return {"ask": self.asks, "review": self.reviews, "decision": self.decisions}[kind_name].listed()
def subjects_of(self, kind_name: str, records: list[dict]) -> list[dict]:
return [subject_of(kind_name, entry, self.deciders(kind_name, entry)) for entry in records]
def recent_subjects(self, kind_name: str, now: float) -> list[dict]:
"""Returns:
The asks, reviews or decisions of the last RECENT_DAYS as a rule
of that kind is matched against them.
"""
ledger = {"ask": self.asks, "review": self.reviews, "decision": self.decisions}[kind_name]
since = now - RECENT_DAYS * 86400
return [subject_of(kind_name, entry, self.deciders(kind_name, entry)) for entry in ledger.listed() if created_of(entry) >= since]
return self.subjects_of(kind_name, [entry for entry in self.kind_records(kind_name) if created_of(entry) >= since])
def last_subjects(self, kind_name: str) -> list[dict]:
"""Returns:
The newest MATCH_WINDOW asks, reviews or decisions as a rule of
that kind is matched against them.
"""
return self.subjects_of(kind_name, sorted(self.kind_records(kind_name), key=created_of)[-MATCH_WINDOW:])
def rule_counts(self, stored: list[dict], now: float) -> dict[str, dict]:
"""Args:
stored: the stored rules.
now: the current time in epoch seconds.
Returns:
window_count() of each rule by id over the last MATCH_WINDOW
records of its kind.
"""
subjects = {kind_name: self.last_subjects(kind_name) for kind_name in {rule["kind"] for rule in stored}}
return {rule["id"]: window_count(rule, subjects[rule["kind"]], now) for rule in stored}
def match_rule(self, body: bytes) -> dict:
"""Args:
body: a draft rule as POST /api/rules/sign takes it.
Returns:
window_count() of the draft over the last MATCH_WINDOW records of
its kind; it reads only, stores nothing and grants nothing.
"""
fields = self.draft_fields(body)
return window_count(fields, self.last_subjects(fields["kind"]), time.time())
def dry_run(self, record: dict, now: float) -> dict:
"""Returns:
+13 -2
View File
@@ -185,13 +185,24 @@ class Rules:
def store_rule(self, rule: dict, fields: dict, proof: dict, enabled: bool, now: float) -> dict:
return self.rules.insert(rule["id"], {**fields, "expires": float(fields["expires"]), "enabled": enabled, "created_ts": now, "proof": proof})
def sign_rule(self, body: bytes) -> dict:
def draft_fields(self, body: bytes) -> dict:
"""Args:
body: the rules form's draft: RULE_INPUT, with agents when it
applies to one agent or group only.
Returns:
The checked fields of rule_fields() for agents the Agent
Orchestrator knows.
"""
payload = decode(body)
targeted = "agents" in payload
expect(payload, (*RULE_INPUT, "agents") if targeted else RULE_INPUT)
fields = rule_fields(payload, payload["agents"] if targeted else EVERY_AGENT, time.time())
self.known_agents(fields["agents"])
return {**self.rule_offer(fields), "sign": True}
return fields
def sign_rule(self, body: bytes) -> dict:
return {**self.rule_offer(self.draft_fields(body)), "sign": True}
def add_rule(self, body: bytes) -> dict:
payload = decode(body)
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
from pathlib import Path
from .records import epoch, read_json
from .tasks import TEXT_SHOWN
RUNNER_JOB = "runner-job.json"
RUNNING = "running"
def running_job(path: Path, jobs: list[dict]) -> dict | None:
"""Args:
path: runner-job.json in the hub state dir, {pid, job, task,
started}, which client/runner.py keeps while it runs a job.
jobs: the hub's job records.
Returns:
{job, task, started, command} of the job the marker names, started
in epoch seconds and command that job's command, empty when the
hub holds no record of it; None when the marker is missing, a link,
malformed, or names a job the hub records as no longer running.
"""
data = read_json(path)
if not isinstance(data, dict):
return None
job, task, started = data.get("job"), data.get("task"), epoch(data.get("started"))
if not (isinstance(job, str) and job and isinstance(task, str) and task and started is not None):
return None
record = next((row for row in jobs if row.get("id") == job), None)
if record is not None and record.get("status") != RUNNING:
return None
command = record.get("command") if record is not None else ""
return {"job": job[:TEXT_SHOWN], "task": task[:TEXT_SHOWN], "started": started, "command": command[:TEXT_SHOWN] if isinstance(command, str) else ""}
+116 -24
View File
@@ -1,12 +1,13 @@
from __future__ import annotations
import json
import re
from pathlib import Path
from .errors import ToolError
from .fields import decode
from .errors import ToolError, Unsigned
from .records import read_json, write_atomic
from .settings import CLOCK, flag, section
from .signed import signing
SCHEDULES = "schedules.json"
SCHEDULES_VIEW = "schedules-view.json"
@@ -17,41 +18,110 @@ ROWS = {
"queue-cleanup": {"on": True, "at": ["00:00", "12:00"]},
"code-graph": {"on": True},
}
UNITS_KEY = "units"
HUB_UNIT = re.compile(r"kvb-orchestrator-[a-z0-9-]{1,64}\.timer")
HOURS = (1, 24)
TIMES_LIMIT = 6
VIEW_LIMIT = 200
VIEW_LIMIT = 500
VIEW_TEXT = 2000
VIEW_KEYS = ("name", "kind", "owner", "unit", "file", "schedule", "next", "last", "event", "command", "off")
VIEW_KEYS = ("name", "source", "kind", "unit", "file", "task", "schedule", "next", "last", "on", "dropin", "error", "command")
CRON_FIELDS = (("minute", 0, 59), ("hour", 0, 23), ("day of month", 1, 31), ("month", 1, 12), ("day of week", 0, 6))
CRON_PART = re.compile(r"(?:\*|([0-9]{1,2})(?:-([0-9]{1,2}))?)(?:/([0-9]{1,2}))?")
def timing(name: str, row: dict) -> dict:
"""Args:
name: the row or unit, for the errors.
row: a timer row with at (1 to TIMES_LIMIT distinct HH:MM) or
calendar (an OnCalendar expression signing.SCHEDULE_CALENDAR
matches), not both.
Returns:
{at} with the times sorted, or {calendar}.
"""
if "at" in row and "calendar" in row:
raise ToolError(f"{name} takes at or calendar, not both")
if "calendar" in row:
calendar = row["calendar"]
if not isinstance(calendar, str) or not signing.SCHEDULE_CALENDAR.fullmatch(calendar):
raise ToolError(f"{name}.calendar must be an OnCalendar expression of letters, digits, spaces and * : , . / ~ _ + -")
return {"calendar": calendar}
times = row["at"]
if not isinstance(times, list) or not 1 <= len(times) <= TIMES_LIMIT or not all(isinstance(time, str) and CLOCK.fullmatch(time) for time in times):
raise ToolError(f"{name}.at must hold 1 to {TIMES_LIMIT} times like 17:00")
if len(set(times)) != len(times):
raise ToolError(f"{name}.at names a time twice")
return {"at": sorted(times)}
def valid_row(name: object, value: object) -> dict:
"""Args:
name: one of ROWS.
value: the row: on, plus every (hours from 1 to 24) for a reminder
hook or at (1 to TIMES_LIMIT distinct HH:MM) for a timer.
hook, or at or calendar (timing()) for a timer.
Returns:
The row, times sorted.
"""
if not isinstance(name, str) or name not in ROWS:
raise ToolError(f"no such schedule: {name}")
row = section(value, str(name), tuple(ROWS[name]))
default = ROWS[name]
calendar = "at" in default and isinstance(value, dict) and "calendar" in value
row = section(value, name, ("on", "calendar") if calendar else tuple(default))
found = {"on": flag(row["on"], f"{name}.on")}
if "every" in row:
every = row["every"]
if isinstance(every, bool) or not isinstance(every, int) or not HOURS[0] <= every <= HOURS[1]:
raise ToolError(f"{name}.every must be a whole number of hours from {HOURS[0]} to {HOURS[1]}")
found["every"] = every
if "at" in row:
times = row["at"]
if not isinstance(times, list) or not 1 <= len(times) <= TIMES_LIMIT or not all(isinstance(time, str) and CLOCK.fullmatch(time) for time in times):
raise ToolError(f"{name}.at must hold 1 to {TIMES_LIMIT} times like 17:00")
if len(set(times)) != len(times):
raise ToolError(f"{name}.at names a time twice")
found["at"] = sorted(times)
if "at" in default:
found.update(timing(name, row))
return found
def valid_unit(unit: object, value: object) -> dict:
"""Args:
unit: a hub timer HUB_UNIT matches; any other text is a System timer
or a Claude task, which takes the signed route.
value: on, plus at or calendar (timing()) for a retime; without
them the reconciler removes the unit's drop-in.
Returns:
The override, times sorted.
"""
if not isinstance(unit, str):
raise ToolError("unit must be a text")
if not HUB_UNIT.fullmatch(unit):
raise Unsigned(f"{unit} is no kvb-orchestrator- timer: a System timer or a Claude task needs the passkey")
keys = ("on", *(key for key in ("at", "calendar") if isinstance(value, dict) and key in value))
row = section(value, unit, keys)
found = {"on": flag(row["on"], f"{unit}.on")}
return {**found, **timing(unit, row)} if len(keys) > 1 else found
def cron_part(part: str, low: int, high: int) -> bool:
found = CRON_PART.fullmatch(part)
if found is None:
return False
start, end, step = (None if group is None else int(group) for group in found.groups())
first = low if start is None else start
last = high if start is None or (end is None and step is not None) else start if end is None else end
return low <= first <= last <= high and step != 0
def valid_cron(cron: object) -> str:
"""Returns:
cron, five fields of `*`, numbers, ranges, lists and steps within
CRON_FIELDS; ToolError naming the first field out of range.
"""
if not isinstance(cron, str) or not signing.CRON.fullmatch(cron):
raise ToolError("cron must be 5 fields of digits and * , / -, like 0 9 * * 1-5")
for text, (field, low, high) in zip(cron.split(" "), CRON_FIELDS, strict=True):
if not all(cron_part(part, low, high) for part in text.split(",")):
raise ToolError(f"cron {field} field {text} must stay within {low} to {high}")
return cron
def stored_rows(council: Path) -> dict:
"""Returns:
Every row of ROWS from schedules.json; a missing, linked or malformed
@@ -67,11 +137,27 @@ def stored_rows(council: Path) -> dict:
return rows
def stored_units(council: Path) -> dict:
"""Returns:
The hub timer overrides of schedules.json; a malformed one is left
out, as the reconciler leaves it alone.
"""
data = read_json(council / SCHEDULES)
units = data.get(UNITS_KEY) if isinstance(data, dict) else None
kept = {}
for unit, value in units.items() if isinstance(units, dict) else ():
try:
kept[unit] = valid_unit(unit, value)
except (ToolError, Unsigned):
continue
return kept
def view_rows(council: Path) -> dict:
"""Returns:
{at, rows}: what the host reconciler last saw, each row with the
VIEW_KEYS as strings or numbers; {at: None, rows: []} before its first
run or for a malformed file.
VIEW_KEYS as texts, numbers or true/false; {at: None, rows: []}
before its first run or for a malformed file.
"""
data = read_json(council / SCHEDULES_VIEW)
rows = data.get("rows") if isinstance(data, dict) else None
@@ -85,10 +171,10 @@ def view_rows(council: Path) -> dict:
return {"at": at, "rows": kept}
def shown(value: object) -> str | float | None:
def shown(value: object) -> str | float | bool | None:
if isinstance(value, str):
return value[:VIEW_TEXT]
if isinstance(value, int | float) and not isinstance(value, bool):
if isinstance(value, bool | int | float):
return value
return None
@@ -98,15 +184,21 @@ class Schedules:
self.council = council
def view(self) -> dict:
return {"rows": stored_rows(self.council), "host": view_rows(self.council)}
return {"rows": stored_rows(self.council), "units": stored_units(self.council), "host": view_rows(self.council)}
def save(self, body: bytes) -> dict:
def save(self, payload: object) -> dict:
"""Args:
body: {row, value}: one row of ROWS and its new value; every
other row keeps its stored value.
payload: {row, value}: one row of ROWS and its new value, or
{unit, value}: one hub timer and its override (valid_unit());
every other row and override keeps its stored value.
"""
data = section(decode(body), "body", ("row", "value"))
rows = {**stored_rows(self.council), data["row"]: valid_row(data["row"], data["value"])}
if isinstance(payload, dict) and "unit" in payload:
data = section(payload, "body", ("unit", "value"))
changed = {UNITS_KEY: {**stored_units(self.council), data["unit"]: valid_unit(data["unit"], data["value"])}}
else:
data = section(payload, "body", ("row", "value"))
changed = {data["row"]: valid_row(data["row"], data["value"])}
stored = {**stored_rows(self.council), UNITS_KEY: stored_units(self.council), **changed}
self.council.mkdir(parents=True, exist_ok=True)
write_atomic(self.council / SCHEDULES, json.dumps(rows, sort_keys=True).encode())
write_atomic(self.council / SCHEDULES, json.dumps(stored, sort_keys=True).encode())
return self.view()
@@ -0,0 +1,65 @@
from __future__ import annotations
from .errors import ToolError, Unsigned
from .fields import decode, expect
from .jobs import SCHEDULE_JOB, argv_items
from .schedules import valid_cron
from .signed import signing
SCHEDULE_TASK = "schedules"
def schedule_request(raw: object) -> bool:
return isinstance(raw, list) and bool(raw) and all(isinstance(entry, dict) and entry.get("kind") == SCHEDULE_JOB for entry in raw)
def shown_command(argv: list[str]) -> str:
return " ".join(["schedules.py", *argv])
def schedule_item(argv: object) -> dict:
"""Returns:
The signed item of one foreign row change, its argv as
signing.schedule_argv() accepts it; a cron out of range is refused
first, naming its field (valid_cron()).
"""
if isinstance(argv, list) and len(argv) == 5 and argv[0] == "cron" and argv[3] == "--cron":
valid_cron(argv[4])
return signing.schedule_item(signing.schedule_argv(argv))
class Scheduling:
def schedule_changes(self, raw: object) -> list[dict]:
"""Args:
raw: the page's items, each {"kind": "schedule", "argv"} with the
schedules.py arguments of one System timer or Claude task
change; a batch goes under one passkey assertion.
Returns:
The signed items (schedule_item()).
"""
return argv_items(raw, schedule_item, "schedule change")
def save_schedule(self, body: bytes) -> dict:
"""Args:
body: {row, value} or {unit, value} for a Skills or Hub row,
which schedules.json takes without a proof
(Schedules.save()), or {items, proof} for System timers and
Claude tasks, one runner job per item once a pinned key
signed them all.
Returns:
The Schedules view, or {"jobs", "status"} for signed changes;
Unsigned (403) for a foreign change without a valid proof,
which stores nothing.
"""
payload = decode(body)
if not isinstance(payload, dict) or "items" not in payload:
return self.schedule_settings.save(payload)
expect(payload, ("items", "proof"))
items = self.schedule_changes(payload["items"])
try:
proof = self.proven(payload["proof"], items)
except ToolError as error:
raise Unsigned(str(error)) from None
return self.queued_changes(items, proof, SCHEDULE_JOB, SCHEDULE_TASK, shown_command)
+15 -1
View File
@@ -20,10 +20,11 @@ TRENDS = ("off", "regression", "velocity")
TREND_DAYS = (1, 365)
THRESHOLDS = tuple(range(0, ALWAYS + 1, 10))
WPM = (5, 40)
LATE = ("rates", "morse", "undo", "popups", "agents")
LATE = ("rates", "morse", "undo", "popups", "agents", "forecast", "match")
AGENT_SWITCHES = ("sound", "aloud", "bubbles")
AGENTS_LIMIT = 200
UNDO_RANGE = (0, 60)
MATCH_REFRESH = (1, 60)
POPUP_SOURCES = ("resources", "mayday", "dream")
POPUP_UNTIL = 4102444800
NOTIFY = "notify.json"
@@ -59,6 +60,8 @@ SETTINGS = {
"undo": UNDO,
"popups": {source: {"on": True, "until": 0} for source in POPUP_SOURCES},
"agents": {},
"forecast": False,
"match": {"refresh": 2},
}
RATE_CHIP = (2, 9)
SPACE_AXES = ("none", "time", "spawn")
@@ -205,6 +208,15 @@ def undo_setting(raw: object) -> int:
return raw
def match_setting(raw: object) -> dict:
entry = section(raw, "match", tuple(SETTINGS["match"]))
low, high = MATCH_REFRESH
refresh = entry["refresh"]
if isinstance(refresh, bool) or not isinstance(refresh, int) or not low <= refresh <= high:
raise ToolError(f"match.refresh must be whole seconds from {low} to {high}")
return {"refresh": refresh}
def popups_setting(raw: object) -> dict:
data = section(raw, "popups", POPUP_SOURCES)
popups = {}
@@ -274,6 +286,8 @@ def valid_settings(raw: object) -> dict:
"undo": undo_setting(data["undo"]),
"popups": popups_setting(data["popups"]),
"agents": agents_setting(data["agents"]),
"forecast": flag(data["forecast"], "forecast"),
"match": match_setting(data["match"]),
}
+1
View File
@@ -34,6 +34,7 @@ limits = client_module("hub_limits", {})
signing = client_module("signing", {})
passkey = client_module("passkey", {"signing": signing})
verifier = client_module("verifier", {"signing": signing, "passkey": passkey})
pruning = client_module("pruning", {"signing": signing})
def ask_signed(ask: dict) -> dict:
@@ -2,6 +2,7 @@ from __future__ import annotations
import functools
import importlib.util
import os
import re
import subprocess
import sys
@@ -15,6 +16,7 @@ OUTPUT_LIMIT = 4000
FIRST_LINE_LIMIT = 200
ELIDED = "..."
SAFE_PATH = "/usr/local/bin:/usr/bin:/bin"
CONFIG_ENV = "AGENTS_COUNCIL_CONFIG"
RADIO = "kvb-org-radio/scripts/radio.py"
RASCI = "kvb-org-rasci/scripts/rasci.py"
NIGHT = "kvb-org-suspend/scripts/night.py"
@@ -36,7 +38,13 @@ def bounded(stdout: str) -> str:
def script_env(home: Path, council: Path) -> dict[str, str]:
return {"PATH": SAFE_PATH, "HOME": str(home), "AGENTS_COUNCIL_ROOT": str(council), "PYTHONDONTWRITEBYTECODE": "1"}
"""Returns:
The whole environment of a skill script: PATH, HOME, the council
and, when the hub has one, CONFIG_ENV, the read-only mount of the
queue config compose.yml passes; nothing else of the hub's.
"""
config = {CONFIG_ENV: os.environ[CONFIG_ENV]} if CONFIG_ENV in os.environ else {}
return {"PATH": SAFE_PATH, "HOME": str(home), "AGENTS_COUNCIL_ROOT": str(council), "PYTHONDONTWRITEBYTECODE": "1", **config}
def script_module(script: Path) -> ModuleType | None:
+242
View File
@@ -0,0 +1,242 @@
from __future__ import annotations
import functools
import json
import os
import stat
from collections.abc import Iterator
from pathlib import Path
from typing import BinaryIO
from .errors import ToolError
from .fields import instant, single
from .records import epoch, parse_line
from .resources import HOUR, rows_between
CONTEXT = "context.jsonl"
USAGE = "usage.jsonl"
LINE_LIMIT = 1 << 16
DAY = 86400
COUNTS = ("input", "output", "cache_read", "cache_write")
FILTERS = ("skill", "tool", "subagent", "repo", "model", "agent", "account")
GROUPS = (*FILTERS, "hour", "day")
PARAMS = ("group", "since", "until", *FILTERS)
BUCKETS = {"hour": HOUR, "day": DAY}
PRICES = Path(__file__).with_name("prices.json")
MILLION = 1_000_000
KILO = 1000
VALUE_TEXT = 254
QUANTILES = (("median", 1, 2), ("p90", 9, 10))
@functools.cache
def prices() -> dict:
"""Returns:
prices.json: {date, source, unit, families: {family: {model, input,
output, cache_read, cache_write}}}, USD per million tokens.
"""
return json.loads(PRICES.read_text(encoding="utf-8"))
def family(model: str, families: dict) -> dict | None:
"""Returns:
The prices of the first family whose name the model id holds, None
for an unknown model.
"""
lowered = model.lower()
return next((found for name, found in families.items() if name in lowered), None)
def cost(row: dict, families: dict) -> float | None:
found = family(row["model"], families)
return None if found is None else sum(row[name] * found[name] for name in COUNTS) / MILLION
def whole(value: object) -> int:
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
def entry(row: dict) -> dict | None:
"""Returns:
A token row with every dimension of FILTERS, "" where an older row
lacks it, and its counts as whole tokens; None without a number t.
"""
t = row.get("t")
if not isinstance(t, int | float) or isinstance(t, bool):
return None
return {"t": t, **{name: row[name] if isinstance(row.get(name), str) else "" for name in FILTERS}, **{name: whole(row.get(name)) for name in COUNTS}}
def parsed(query: dict[str, list[str]], now: float) -> tuple[str, float, float, dict[str, str]]:
"""Args:
query: group (one of GROUPS), since and until in epoch seconds,
until at most now and now when left out, and a value per
dimension of FILTERS to keep; any other key raises ToolError.
Returns:
(group, since, until, filters).
"""
unknown = sorted(set(query) - set(PARAMS))
if unknown:
raise ToolError(f"unknown parameter {unknown[0]}: use {', '.join(PARAMS)}")
group = single(query, "group")
if group not in GROUPS:
raise ToolError(f"group must be one of {', '.join(GROUPS)}")
since, until = instant(query, "since"), instant(query, "until")
if since is None:
raise ToolError("since must be given in seconds since the epoch")
until = now if until is None else min(until, now)
if since > until:
raise ToolError("since must not lie after until")
filters = {name: single(query, name) or "" for name in FILTERS if name in query}
if any(len(value) > VALUE_TEXT for value in filters.values()):
raise ToolError(f"a filter value must hold at most {VALUE_TEXT} characters")
return group, since, until, filters
def matches(row: dict, filters: dict[str, str]) -> bool:
return all(value in row["tool"].split(",") if name == "tool" else row[name] == value for name, value in filters.items())
def keys_of(row: dict, group: str) -> list:
"""Returns:
The group keys a row counts under: each tool name of its tool set
for tool, the start of its hour or day (UTC) for hour and day, else
its value of the dimension.
"""
if group == "tool":
return row["tool"].split(",")
if group in BUCKETS:
return [int(row["t"] // BUCKETS[group] * BUCKETS[group])]
return [row[group]]
def blank() -> dict:
return {**dict.fromkeys(COUNTS, 0), "cost": 0.0}
def added(total: dict, row: dict, families: dict) -> None:
for name in COUNTS:
total[name] += row[name]
found = cost(row, families)
total["cost"] = None if found is None or total["cost"] is None else total["cost"] + found
def finished(key: object, total: dict, grand: int) -> dict:
"""Returns:
The eight columns of one row: input, output, cache_read,
cache_write, total, share of grand in percent, cost in USD (None
when a row of an unknown model counts in it) and hit_rate, cache read
over input plus cache read (None without either).
"""
tokens = sum(total[name] for name in COUNTS)
read = total["input"] + total["cache_read"]
return {
"key": key, **{name: total[name] for name in COUNTS}, "total": tokens, "share": round(100 * tokens / grand, 1) if grand else None,
"cost": None if total["cost"] is None else round(total["cost"], 6), "hit_rate": round(total["cache_read"] / read, 4) if read else None,
}
def quantile(turns: dict[int, int], numerator: int, denominator: int) -> int | None:
"""Returns:
The nearest-rank quantile numerator / denominator of the histogram
turns (per kilo, the turns of that context) in tokens, to the KILO
below; None without a turn.
"""
rank, seen = -(-sum(turns.values()) * numerator // denominator), 0
for kilo in sorted(turns):
seen += turns[kilo]
if seen >= max(rank, 1):
return kilo * KILO
return None
def context_of(folder: Path, since: float, until: float, agent: str | None) -> list[dict]:
"""Returns:
Per day and agent of context.jsonl within the span (one agent only
when given) {day, agent, turns, median, p90, compactions}, the newest
day first.
"""
merged: dict[tuple, list] = {}
for row in rows_between(folder / CONTEXT, since, until, DAY):
turns = row.get("turns")
if not isinstance(row.get("agent"), str) or not isinstance(turns, dict) or (agent is not None and row["agent"] != agent):
continue
found = merged.setdefault((int(row["t"]), row["agent"]), [{}, 0])
for kilo, number in turns.items():
if kilo.isdigit() and whole(number):
found[0][int(kilo)] = found[0].get(int(kilo), 0) + number
found[1] += whole(row.get("compactions"))
return [
{"day": day, "agent": name, "turns": sum(sizes.values()), **{label: quantile(sizes, top, bottom) for label, top, bottom in QUANTILES}, "compactions": compactions}
for (day, name), (sizes, compactions) in sorted(merged.items(), key=lambda item: (-item[0][0], item[0][1]))
]
def lines_of(handle: BinaryIO) -> Iterator[bytes]:
"""Returns:
The complete lines of handle of at most LINE_LIMIT bytes, read in
chunks of that size; a longer line and an unterminated last line are
skipped.
"""
skipping = False
while chunk := handle.readline(LINE_LIMIT):
ended = chunk.endswith(b"\n")
if ended and not skipping:
yield chunk
skipping = not ended
def streamed(path: Path, since: float, until: float) -> Iterator[dict]:
"""Returns:
The rows of path that reach into since to until, an hourly row by its
hour and a row with a width by that width, read line by line without
following a link, so the file's size meets no read limit; a malformed
line yields nothing, and so does a path that is missing or no
regular file.
"""
try:
handle = os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC), "rb")
except OSError:
return
with handle:
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
return
for raw in lines_of(handle):
row = parse_line(raw.decode("utf-8", "replace"))
t = None if row is None else epoch(row.get("t"))
if t is not None and t <= until and since <= t + max(HOUR, epoch(row.get("width")) or 0):
yield row
def usage_view(folder: Path, query: dict[str, list[str]], now: float) -> dict:
"""Args:
folder: the host sampler's directory, mounted read-only.
query: as parsed() reads it.
now: epoch seconds.
Returns:
{group, since, until, filters, split, rows, total, prices, context}:
rows one finished() row per group key, the most tokens first, total
the finished() sum of every matching usage.jsonl row, each counted
once, streamed() line by line;
split true for group tool, where a row of several tools counts under
each of them, so the shares may sum above 100; prices {date, source}
of prices.json; context as context_of() gives it.
"""
group, since, until, filters = parsed(query, now)
table = prices()
groups: dict[object, dict] = {}
grand = blank()
for row in map(entry, streamed(folder / USAGE, since, until)):
if row is None or not matches(row, filters):
continue
added(grand, row, table["families"])
for key in keys_of(row, group):
added(groups.setdefault(key, blank()), row, table["families"])
tokens = sum(grand[name] for name in COUNTS)
listed = sorted((finished(key, total, tokens) for key, total in groups.items()), key=lambda found: (-found["total"], str(found["key"])))
return {
"group": group, "since": since, "until": until, "filters": filters, "split": group == "tool", "rows": listed, "total": finished(None, grand, tokens),
"prices": {"date": table["date"], "source": table["source"]}, "context": context_of(folder, since, until, filters.get("agent")),
}
+17 -4
View File
@@ -27,7 +27,7 @@ from .jobs import JOB_OPEN
from .messaging import message_row
from .orbits import TRACK_STEPS, track
from .phrasing import phrase_parts
from .presence import presence, read_snapshot
from .presence import beats, presence, read_snapshot
from .queue_order import grant_order, live_ids
from .receipts import inline, read_of
from .records import epoch, iso_epoch, read_jsonl, write_atomic
@@ -40,6 +40,7 @@ from .register import (
stored_order,
)
from .reviewing import review_row
from .running import running_job
from .settings import NOTIFY, completed, media_origins, station_origins, valid_settings
from .signed import signing
from .skill_scripts import OUTPUT_LIMIT
@@ -49,7 +50,7 @@ RADIO_WINDOW = 86400
JOBS_SHOWN = 20
ACTIVE = 900
INDEX_CSP = (
"default-src 'none'; script-src 'nonce-{0}'; style-src 'nonce-{0}'; connect-src 'self'; media-src {1}; frame-src 'self'; "
"default-src 'none'; script-src 'nonce-{0}'; style-src 'nonce-{0}'; connect-src 'self'; media-src {1}; img-src blob:; frame-src 'self'; "
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
)
ENCODER_CSP = (
@@ -147,6 +148,7 @@ class View:
rows = task_rows(tasks, queue, self.tree.get())
chain = grant_order(queue_chain(queue, tasks, order, now), queue_jobs)
stored = self.messages.listed()
snapshot = read_snapshot(self.agent_sessions, now)
return {
"settings": settings,
"schedules": self.schedule_settings.view(),
@@ -156,7 +158,7 @@ class View:
"inbox": inbox,
"badges": badges(self.match_open(inbox), claims, self.jobs.listed(), now),
"pending": self.batches.listed(),
"rules": [{**{key: value for key, value in rule.items() if key != "proof"}, "signed": rule.get("proof") is not None} for rule in self.rules.listed()],
"rules": self.rule_rows(now),
"approvers": self.keys(),
"jobs": jobs,
"views": VIEWS,
@@ -183,11 +185,22 @@ class View:
"grants": grant_rows,
"night": night_mode(self.council),
"night_parts": night_parts(self.council),
"presence": presence(read_snapshot(self.agent_sessions, now), night_parts(self.council), night_mode(self.council), claims, news, now),
"presence": presence(snapshot, night_parts(self.council), night_mode(self.council), claims, news, now),
"beats": beats(snapshot, claims),
"runner": running_job(self.runner_marker, self.jobs.listed()),
"silence": silence_of(self.council, now),
"graph": drawn,
}
def rule_rows(self, now: float) -> list[dict]:
"""Returns:
The stored rules without their proof, each with signed and the
matched and of of rule_counts().
"""
stored = self.rules.listed()
counts = self.rule_counts(stored, now)
return [{**{key: value for key, value in rule.items() if key != "proof"}, "signed": rule.get("proof") is not None, **counts[rule["id"]]} for rule in stored]
def signed_changes(self, settings: dict, saved: dict) -> list[dict]:
"""Args:
settings: valid settings the page wants to save.
+1 -1
View File
@@ -40,7 +40,7 @@ SPAN = (1, 12)
ZOOM = (50, 200, 10)
METRIC = "metric"
CHARTS = ("hardware", "tokens", "combined")
PANELS = (*CHARTS, "accounts")
PANELS = (*CHARTS, "accounts", "usage")
SHOWN_LIMIT = 100
FNV_PRIME = 0x01000193
FNV_SEEDS = (0x811C9DC5, 0x01000193)