Items 7-9: per-provider plans, exact provider scoping of constraints and marks, the owner's vouch (relayed counts to 2), allowance probes (key fetched at probe time, never stored, no redirects, owner approval) and provider failure phrases. done / next: owner setup on a copy of the store, real runs, report

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-23 16:06:03 -07:00
1 parent 3a12dccf16
commit a03102aba9
7 files changed
+1310 -45

No files matched your search

+3
View File
@@ -96,6 +96,9 @@ present; nothing here names one. Read on demand: `sisi delegate guide`.
Either way a new worker is unproven: routine work only, a free or flat one tried more
often, every result checked with at least the tests or a read of the diff, until its
judged record decides.
- One tool can carry several providers, each with its own plan, allowance and failure phrases
(`sisi workers plan|allowance|signature`). The owner can vouch for a worker he checked himself
(`sisi workers vouch`): capable up to that difficulty on his word until its own record decides.
- Orchestration legwork is delegable like any other legwork: discovery,
price and benchmark research, routing lookups, first-pass review, and
summarising the record can all go to a fast, cheap worker. The judgement
+9
View File
@@ -116,3 +116,12 @@ A worker that did not exist when sisi was installed becomes routable through ord
- **From PATH.** At session start the executables in the user-level folders on PATH (under the home folder, never system folders; nothing is run) are compared with the stored list. It is looked at again when a folder changed, after `discovery.path_refresh_s` (6 hours) or `discovery.path_every_starts` (25) session starts. The first run only stores the list. New names are announced once, five at most.
- **A driver, learned as data.** `sisi workers learn NAME` prints a delegation contract for a fast, cheap worker: read the tool's own help, write a small JSON file (the fields of the built-in driver table, plus failure phrases and a token pattern). `--check FILE` validates it; `--record FILE` validates, stores it (`worker-drivers.json`, with who learned it and when) and runs ONE read-only smoke task in a temporary folder, with a time limit and no input. Only a passing driver is used; a failure is classified (login, quota, bad template, no answer, timeout) and the driver stays unusable with the reason (`--verify` tries again). The command is an argument list run without a shell; the brief is one argument. A command with a flag that switches off approvals or a sandbox (patterns in the data file) waits for `sisi approve drv-NAME`, which shows the exact command, and never runs, smoke task included, before. `sisi workers forget NAME` removes one.
- **Earning a place.** Such a worker is unproven until it has `MIN_ATTEMPTS` judged attempts: difficulty 1 only, whatever benchmark it has; a free or flat one gets one routine task in `route.explore_free_one_in` (default 3); `sisi route` and `sisi delegate` say to check its result with at least the tests or a read of the diff. Its plan comes from its driver or from a fact; unknown counts as per-use. The missing-facts line at session start names the new workers (five at most) so the research has a target.
## One tool, several providers
A tool can carry several providers (the part of a worker id before the first slash). Each has its own facts in the user store, set by command and shown under the tool by `sisi workers`; a constraint or mark on one never reaches another (a pattern ending in `/`, such as `a-b/`, names one provider exactly; availability marks made for a provider reach its workers only).
- `sisi workers plan PROVIDER flat|free|per-use --source S [--note TEXT]` (`worker-providers.json`). A flat or free plan with allowance left costs nothing extra per task, as routing already treats a flat plan. A price fact on a model of a flat plan is its *relative cost inside the plan* (compared with other flat workers), so routine work goes to the lighter model; a model's own `--plan` fact still wins over the provider's.
- `sisi workers vouch WORKER --up-to 1|2|3 --why "OWNER'S WORDS"` (`worker-vouches.json`): a new worker with no judged record is limited to routine work; the owner can vouch for one he checked himself. Routing then treats it as capable up to that difficulty, with the evidence named "the owner's word", ranked with judged records (proof before benchmark) and still checked a level more carefully. A thick bad record overrides it; once the worker has its own thick record the vouch is ignored. Like `sisi learn`, the command records whether the quoted words appear in a message the owner typed; otherwise it is stored as relayed by an agent and counts only up to difficulty 2.
- `sisi workers allowance PROVIDER --url URL --header 'Name={secret}' --secret-from-command CMD --secret-path PATH --remaining-path PATH --reset-path PATH [--total-path PATH]` (or `--command CMD` for a tool that prints its own allowance). Paths: `a.b`, `[n]`, `[*]`, `[key=value]` (`[integrationID=x][active=true].value.key`), or `re:REGEX` with one group. It is read when `sisi workers` is asked, and when routing needs it and the cached reading is older than `discovery.allowance_cache_s` (300). The key comes from the named command at probe time (an argument list, no shell), goes in one request (https, or this machine; a redirect is never followed; `discovery.allowance_timeout_s`), and is never written to the store, cache, ledger or any output. Several windows: the smallest remaining decides whether the provider is out, and it is down until every exhausted window has reset. A probe that fails changes nothing and says so in `sisi workers` only. A probe waits for the owner (`sisi approve probe-PROVIDER`) unless defined in the owner's terminal. When a run reports a limit and a probe is defined, the reset time comes from the probe.
- `sisi workers signature PROVIDER --match 'TEXT|re:REGEX' --class auth|limit|missing|error [--until-path PATH]`: the provider's own failure phrases, consulted before the built-in ones; an auth failure marks that provider down, not the whole tool.
+662 -26
View File
@@ -16,12 +16,12 @@ checked a level more carefully, and explored more often when it costs nothing ex
Every hook entry point fails open. A driver file is untrusted input written by an agent: validated field by
field and run without a shell.
"""
import json, os, re, time
import json, os, re, shlex, time
from . import paths, store
DEFAULTS = {"path_refresh_s": 6 * 3600, "path_every_starts": 25, "drop_after_listings": 3,
"catalogue_over": 8, "smoke_timeout_s": 120}
"catalogue_over": 8, "smoke_timeout_s": 120, "allowance_cache_s": 300, "allowance_timeout_s": 8}
MAX_NAMED = 5
SMOKE_PROMPT = ("Reply with exactly this one word and nothing else: %s. "
"Do not read, write, create or run anything.")
@@ -582,12 +582,12 @@ def tool_lines(t):
if t.get("learned"):
info = t["learned"]
return [" learned by %s on %s (%s); `sisi workers forget %s` removes it"
% (info.get("by") or "an unknown worker", _day(info.get("at")), info.get("state"), t["name"])]
% (info.get("by") or "an unknown worker", _day(info.get("at")), info.get("state"), t["name"])] + provider_lines(t)
if t.get("host"):
h = t["host"]
return [" reached through the host's cross-provider delegation (first seen %s); new workers are unproven: "
"routine work only until judged" % _day(h.get("first_seen"))]
return []
"routine work only until judged" % _day(h.get("first_seen"))] + provider_lines(t)
return provider_lines(t)
# ---------------------------------------------------------------- running a learned tool once
@@ -789,37 +789,60 @@ def waiting_drivers():
return {n: r for n, r in load_drivers().items() if r.get("state") == "waiting-owner"}
def approve_hook(args):
"""Called first by `sisi approve`. Handles the ids `drv-NAME` and adds the waiting drivers to the
listing. Returns an exit code when it handled the call, None to let the cycle's approvals go on."""
def _owner_may_decide(lines):
"""True when this is the owner's terminal (or the config lets an agent relay a decision); else prints why not."""
import sys
from . import cycle, learning
waiting = waiting_drivers()
from . import cycle
if cycle._stdin_is_tty() or cycle.relay_allowed():
return True
print("\n".join(lines), file=sys.stderr)
print("sisi approve: refused. A decision must be made by the owner in a terminal: this was run without one "
"(an agent, a script, a pipe). Show the owner the text above and give them the line to type.", file=sys.stderr)
return False
def approve_hook(args):
"""Called first by `sisi approve`. Handles the ids `drv-NAME` (a learned driver) and `probe-PROVIDER` (an
allowance probe) and adds both kinds waiting for the owner to the listing. Returns an exit code when it
handled the call, None to let the cycle's approvals go on."""
import sys
from . import learning
waiting, probes = waiting_drivers(), waiting_probes()
if not args:
if not waiting:
if not waiting and not probes:
return None
for n, r in sorted(waiting.items()):
print("\n".join(describe_driver(n, r)))
print()
print("\n".join(describe_driver(n, r)) + "\n")
for n, d in sorted(probes.items()):
print("\n".join(describe_probe(n, d)) + "\n")
if learning.load_pending():
return None
print("The owner decides, in a terminal: sisi approve drv-NAME --yes | --no")
print("The owner decides, in a terminal: sisi approve drv-NAME|probe-PROVIDER --yes | --no")
return 0
if not args[0].startswith("drv-"):
if not (args[0].startswith("drv-") or args[0].startswith("probe-")):
return None
name = args[0][4:]
kind, name = args[0].split("-", 1)
held = waiting if kind == "drv" else probes
yes = "--yes" in args
if name not in waiting:
print("sisi approve: no driver %r waits for a decision" % name, file=sys.stderr)
if name not in held:
print("sisi approve: nothing named %r waits for a decision" % args[0], file=sys.stderr)
return 2
if not yes and "--no" not in args:
print("usage: sisi approve drv-NAME --yes | --no", file=sys.stderr)
print("usage: sisi approve drv-NAME|probe-PROVIDER --yes | --no", file=sys.stderr)
return 2
if not cycle._stdin_is_tty() and not cycle.relay_allowed():
print("\n".join(describe_driver(name, waiting[name])), file=sys.stderr)
print("sisi approve: refused. A decision must be made by the owner in a terminal: this was run without one "
"(an agent, a script, a pipe). Show the owner the command above and give them the line to type.", file=sys.stderr)
if not _owner_may_decide(describe_driver(name, held[name]) if kind == "drv" else describe_probe(name, held[name])):
return 2
if kind == "probe":
provs = load_providers()
if not yes:
provs[name].pop("allowance", None)
save_providers(provs)
print("probe-%s refused; the probe was removed" % name)
return 0
provs[name]["allowance"]["state"] = "usable"
save_providers(provs)
print("probe-%s approved; it is read when `sisi workers` is asked and when routing needs it" % name)
return 0
if not yes:
forget(name)
print("drv-%s refused; the driver was removed" % name)
@@ -963,18 +986,40 @@ def annotate(cands, records, tools):
"""Mark the candidates that came from a learned driver or from the host: unproven until they have
judged attempts (routing.MIN_ATTEMPTS), and a candidate to try (`unproven_ok`) when the tool's own
default model, or when its provider lists no more than discovery.catalogue_over models. An unknown
plan counts as per-use. A host worker is started by the host, so its mechanism says how."""
plan counts as per-use. A host worker is started by the host, so its mechanism says how. Also for every
candidate: the plan its provider has (a provider fact; a model's own price fact still wins), and the
owner's vouch, which lifts an unproven worker to the vouched difficulty until it has its own record."""
marked = {t["name"]: t for t in tools if t.get("learned") or t.get("host")}
if not marked:
providers, vouches = load_providers(), load_vouches()
if not (marked or providers or vouches):
return cands
from . import routing
counts = judged_counts(records)
cap = conf()["catalogue_over"]
prices = None
for c in cands:
n = counts.get(c["worker"].lower(), 0)
prov = routing.provider_of(c["worker"])
pf = providers.get(prov) if prov else None
if pf and pf.get("plan"):
if prices is None:
from . import workers
prices = workers.load_prices()
from . import workers as _w
if not _w._price_for(prices, c.get("tool"), c.get("model"), c["worker"]).get("plan"):
c["plan"] = "per-use" if pf["plan"] == "per-use" else "flat"
if c.get("plan") == "free":
c["plan"] = "flat"
v = vouches.get(c["worker"].lower())
if v and n < routing.MIN_ATTEMPTS: # once it has its own thick record, the record decides
level = min(int(v.get("up_to") or 0), 2 if v.get("relayed") else 3)
if level > 0:
c["vouch"] = {"level": level, "why": v.get("why"), "date": v.get("date"), "relayed": bool(v.get("relayed"))}
c["unproven"] = True
c["unproven_ok"] = True
t = marked.get(c.get("tool"))
if t is None:
continue
n = counts.get(c["worker"].lower(), 0)
c["unproven"] = n < routing.MIN_ATTEMPTS
if c["unproven"]:
c["plan"] = c.get("plan") or "per-use"
@@ -1002,3 +1047,594 @@ UNPROVEN_LINE = ("unproven: check this result with at least the tests or a read
def unproven_lines(cand):
return [UNPROVEN_LINE] if cand and cand.get("unproven") else []
# ---------------------------------------------------------------- providers: plan, allowance, failure phrases; the owner's vouch
# One tool can carry several providers (the part of a worker id before the first slash), each with its own
# plan, allowance and failure phrases. They are facts in the user store, set by command (R-12-1, R-7.2-3).
_PROVIDER = re.compile(r"^[a-z0-9][a-z0-9._-]{0,60}$")
PLANS = ("flat", "free", "per-use")
SIGNATURE_CLASSES = ("auth", "limit", "missing", "error")
def providers_path():
return paths.data_file("worker-providers.json")
def load_providers():
d = _load(providers_path()).get("providers")
return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {}
def save_providers(providers):
_save(providers_path(), {"providers": providers})
def vouches_path():
return paths.data_file("worker-vouches.json")
def load_vouches():
d = _load(vouches_path()).get("vouches")
return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {}
def save_vouches(vouches):
_save(vouches_path(), {"vouches": vouches})
# ---- a small path language over JSON: name, .name, [n], [*], [key=value], or `re:REGEX` over raw text
_PATH_TOKEN = re.compile(r"\.?([A-Za-z_][\w-]*)|\[([^\]]*)\]")
def path_values(obj, path):
"""The values a path finds in parsed JSON (or in raw text, for a path starting `re:`: the first group of every match)."""
path = str(path or "")
if path.startswith("re:"):
text = obj if isinstance(obj, str) else json.dumps(obj)
return [m.group(1) for m in re.finditer(path[3:], text[-200000:]) if m.groups()]
cur, pos = [obj], 0
for m in _PATH_TOKEN.finditer(path):
if m.start() != pos:
raise ValueError("cannot read the path at %r" % path[pos:pos + 10])
pos = m.end()
name, br = m.group(1), m.group(2)
nxt = []
for item in cur:
if name is not None:
if isinstance(item, dict) and name in item:
nxt.append(item[name])
elif br == "*":
nxt.extend(item if isinstance(item, list) else [])
elif br.isdigit():
if isinstance(item, list) and int(br) < len(item):
nxt.append(item[int(br)])
elif "=" in br:
key, want = br.split("=", 1)
for x in (item if isinstance(item, list) else [item]):
got = x.get(key) if isinstance(x, dict) else None
got = "true" if got is True else "false" if got is False else got
if got is not None and str(got) == want:
nxt.append(x)
cur = nxt
if pos != len(path) or not path:
raise ValueError("cannot read the path %r" % path[:40])
return cur
def time_value(v):
"""Epoch seconds from a number (seconds or milliseconds) or a date text, else None."""
if isinstance(v, bool):
return None
if isinstance(v, str) and re.match(r"^\d+(\.\d+)?$", v.strip()):
v = float(v)
if isinstance(v, (int, float)):
return float(v) / 1000.0 if v > 1e11 else float(v)
if isinstance(v, str):
from . import workers
return workers._parse_time(v)
return None
def _json_in(text):
"""The first JSON object a tool's output holds (the whole text, a line, or the outermost braces), or None."""
text = (text or "").strip()
tries = [text] + [ln.strip() for ln in text.splitlines() if ln.strip().startswith("{")]
if "{" in text and "}" in text:
tries.append(text[text.index("{"):text.rindex("}") + 1])
for cand in tries:
try:
d = json.loads(cand)
if isinstance(d, (dict, list)):
return d
except ValueError:
pass
return None
# ---- commands: plan, vouch, allowance, signature
def _flags(args, valued, boolean=()):
"""(positionals, {flag: value}, {boolean flags set}, unknown flags) from an argument list."""
pos, vals, bools, unknown = [], {}, set(), []
i = 0
while i < len(args):
a = args[i]
if a in valued and i + 1 < len(args):
vals[a] = args[i + 1]
i += 2
continue
if a in boolean:
bools.add(a)
elif a.startswith("--"):
unknown.append(a)
else:
pos.append(a)
i += 1
return pos, vals, bools, unknown
PROVIDER_USAGE = (
"usage: sisi workers plan PROVIDER flat|free|per-use --source S [--note TEXT] how routing costs the provider's workers\n"
" sisi workers vouch WORKER --up-to 1|2|3 --why \"TEXT\" | --remove the owner's word that a worker handles up to that difficulty\n"
" sisi workers allowance PROVIDER --url URL --header 'Name={secret}' --secret-from-command CMD --secret-path PATH\n"
" --remaining-path PATH --reset-path PATH [--total-path PATH] (or --command CMD, no secret) | --remove\n"
" sisi workers signature PROVIDER --match 'TEXT or re:REGEX' --class auth|limit|missing|error [--until-path PATH] | --remove")
def cmd_provider(args):
sub, rest = args[0], list(args[1:])
try:
return {"plan": _cmd_plan, "vouch": _cmd_vouch, "allowance": _cmd_allowance, "signature": _cmd_signature}[sub](rest)
except (ValueError, re.error) as e:
print("sisi workers %s: %s" % (sub, e))
return 1
def _need_provider(name):
if not isinstance(name, str) or not _PROVIDER.match(name.lower()):
raise ValueError("a provider is the part of a worker id before its first slash (letters, digits, dot, dash)")
return name.lower()
def _cmd_plan(args):
pos, v, b, bad = _flags(args, ("--note", "--source"), ("--remove",))
if bad or not pos:
print(PROVIDER_USAGE)
return 1
prov = _need_provider(pos[0])
provs = load_providers()
if "--remove" in b:
if prov in provs:
for k in ("plan", "note", "source", "date"):
provs[prov].pop(k, None)
save_providers(provs)
print("plan fact for %s removed" % prov)
return 0
if len(pos) != 2 or pos[1] not in PLANS or not v.get("--source"):
raise ValueError("a plan is flat, free or per-use, and a fact needs its --source (nothing recorded)")
entry = provs.setdefault(prov, {})
entry.update(plan=pos[1], source=v["--source"][:200], date=time.strftime("%Y-%m-%d"))
if v.get("--note"):
entry["note"] = v["--note"][:300]
save_providers(provs)
print("recorded the plan of provider %s: %s%s (from %s). %s" % (
prov, pos[1], " (%s)" % entry["note"] if entry.get("note") else "", entry["source"],
"A flat or free plan with allowance left costs nothing extra per task; a model's own price fact is a "
"relative cost inside the plan." if pos[1] != "per-use" else "Billed per use."))
return 0
def _cmd_vouch(args):
pos, v, b, bad = _flags(args, ("--up-to", "--why"), ("--remove",))
vouches = load_vouches()
if bad or not pos:
for ln in vouch_lines():
print(ln)
if not vouches:
print(PROVIDER_USAGE.split("\n")[1])
return 0 if not bad else 1
worker = pos[0].lower()
if "--remove" in b:
vouches.pop(worker, None)
save_vouches(vouches)
print("vouch for %s removed" % worker)
return 0
up = v.get("--up-to")
if up not in ("1", "2", "3") or not (v.get("--why") or "").strip():
raise ValueError("--up-to wants 1, 2 or 3, and --why wants the owner's own words, quoted")
from . import learning
origin = learning.statement_origin(v["--why"])
relayed = origin != "typed by the owner"
vouches[worker] = {"up_to": int(up), "why": v["--why"].strip()[:400], "origin": origin, "relayed": relayed,
"date": time.strftime("%Y-%m-%d")}
save_vouches(vouches)
print("vouched for %s up to difficulty %s (%s)%s" % (
worker, up, origin, ": counted only up to difficulty 2, because the quoted words were not found in a message "
"the owner typed" if relayed and int(up) > 2 else ""))
print("It is treated as capable up to that difficulty (`sisi route --explain` says \"the owner's word\"), checked a level "
"more carefully, until it has its own judged record; a thick bad record overrides it.")
return 0
def vouch_lines():
out = []
counts = None
for w, v in sorted(load_vouches().items()):
if counts is None:
from . import workers
counts = judged_counts(workers.read_records())
from . import routing
ignored = counts.get(w, 0) >= routing.MIN_ATTEMPTS
out.append("Vouched: %s up to difficulty %s by the owner's word (%s, %s: %s)%s" % (
w, v.get("up_to"), v.get("origin") or "origin unknown", v.get("date") or "no date",
(v.get("why") or "")[:100], "; ignored now: its own record decides" if ignored else
("; counted up to difficulty 2 only" if v.get("relayed") and int(v.get("up_to") or 0) > 2 else "")))
return out
def _url_ok(url):
from urllib.parse import urlsplit
sp = urlsplit(url)
return (sp.scheme == "https" or (sp.scheme == "http" and sp.hostname in ("localhost", "127.0.0.1", "::1"))) \
and bool(sp.hostname) and "{secret}" not in url and not sp.username
def _cmd_allowance(args):
valued = ("--url", "--header", "--secret-from-command", "--secret-path", "--remaining-path", "--reset-path",
"--total-path", "--command")
pos, v, b, bad = _flags(args, valued, ("--remove",))
provs = load_providers()
if bad or not pos:
for p, e in sorted(provs.items()):
if e.get("allowance"):
print("\n".join(describe_probe(p, e["allowance"])))
print(PROVIDER_USAGE.split("\n")[2])
return 0 if not bad else 1
prov = _need_provider(pos[0])
if "--remove" in b:
provs.get(prov, {}).pop("allowance", None)
save_providers(provs)
print("allowance probe for %s removed" % prov)
return 0
for need in ("--remaining-path", "--reset-path"):
if not v.get(need):
raise ValueError("%s is required" % need)
defn = {"remaining_path": v["--remaining-path"], "reset_path": v["--reset-path"]}
paths_to_check = [defn["remaining_path"], defn["reset_path"]]
if v.get("--total-path"):
defn["total_path"] = v["--total-path"]
paths_to_check.append(v["--total-path"])
if v.get("--command"):
if v.get("--url") or v.get("--secret-from-command"):
raise ValueError("--command (a tool that prints its own allowance) takes no --url or secret")
if not shlex.split(v["--command"]):
raise ValueError("--command is empty")
defn["command"] = v["--command"]
else:
if not v.get("--url") or not _url_ok(v["--url"]):
raise ValueError("--url must be an https address (no key inside it); a plain http address only for this machine")
header = v.get("--header") or ""
name, _eq, value = header.partition("=")
if not re.match(r"^[A-Za-z][A-Za-z0-9-]{0,40}$", name) or "{secret}" not in value or "\n" in value:
raise ValueError("--header is Name={secret} (the key is put where {secret} stands, at probe time)")
if not v.get("--secret-from-command") or not shlex.split(v["--secret-from-command"]) or not v.get("--secret-path"):
raise ValueError("--secret-from-command and --secret-path say where the key comes from; it is never stored")
defn.update(url=v["--url"], header=header, secret_command=v["--secret-from-command"], secret_path=v["--secret-path"])
paths_to_check.append(v["--secret-path"])
for pth in paths_to_check:
if pth.startswith("re:"):
re.compile(pth[3:])
else:
path_values({}, pth) # raises ValueError for a path it cannot read
from . import cycle
defn["state"] = "usable" if cycle._stdin_is_tty() else "waiting-owner"
defn["defined"] = time.strftime("%Y-%m-%d")
provs.setdefault(prov, {})["allowance"] = defn
save_providers(provs)
print("\n".join(describe_probe(prov, defn)))
if defn["state"] != "usable":
print("The probe is stored but not used until the owner decides, in a terminal: sisi approve probe-%s --yes | --no" % prov)
return 0
def waiting_probes():
return {p: e["allowance"] for p, e in load_providers().items()
if isinstance(e.get("allowance"), dict) and e["allowance"].get("state") == "waiting-owner"}
def describe_probe(prov, d):
lines = ["%sprobe-%s: an allowance probe for provider %s" % ("" if d.get("state") == "usable" else "WAITING FOR THE OWNER: ", prov, prov)]
if d.get("command"):
lines.append(" runs (an argument list, no shell): %s" % d["command"])
else:
lines += [" sends one GET to %s with the header %s" % (d["url"], d["header"].partition("=")[0]),
" the key is read when the probe runs, by running (no shell): %s, taking %s" % (d["secret_command"], d["secret_path"]),
" the key is used for that one request and is never stored or printed; a redirect is never followed"]
lines.append(" reads remaining from %s and the reset time from %s%s" % (
d["remaining_path"], d["reset_path"], ", total from %s" % d["total_path"] if d.get("total_path") else ""))
return lines
def _cmd_signature(args):
pos, v, b, bad = _flags(args, ("--match", "--class", "--until-path"), ("--remove",))
if bad or not pos:
for p, e in sorted(load_providers().items()):
for sg in e.get("signatures") or []:
print("%s: %r is %s%s" % (p, sg["match"], sg["class"], " (reset from %s)" % sg["until_path"] if sg.get("until_path") else ""))
print(PROVIDER_USAGE.split("\n")[4])
return 0 if not bad else 1
prov = _need_provider(pos[0])
provs = load_providers()
entry = provs.setdefault(prov, {})
sigs = [x for x in entry.get("signatures") or [] if isinstance(x, dict)]
match = (v.get("--match") or "").strip()
if not 4 <= len(match) <= 120:
raise ValueError("--match is a phrase or re:REGEX of 4 to 120 characters")
if "--remove" in b:
entry["signatures"] = [x for x in sigs if x["match"] != match]
save_providers(provs)
print("signature removed")
return 0
if v.get("--class") not in SIGNATURE_CLASSES:
raise ValueError("--class is auth, limit, missing or error")
if match.startswith("re:"):
re.compile(match[3:])
sig = {"match": match, "class": v["--class"]}
if v.get("--until-path"):
if v["--until-path"].startswith("re:"):
re.compile(v["--until-path"][3:])
else:
path_values({}, v["--until-path"])
sig["until_path"] = v["--until-path"]
entry["signatures"] = [x for x in sigs if x["match"] != match] + [sig]
save_providers(provs)
print("provider %s: output matching %r is now classified %s, before the built-in phrases" % (prov, match, sig["class"]))
return 0
# ---- failures by a provider's own phrases
def provider_failure(cand, text):
"""(reason, note, retry_after_s) when one of the worker's provider's recorded phrases is in the output, else None.
Consulted before the built-in classifier: a provider's own error code can be an auth problem and not a limit."""
from . import routing
prov = routing.provider_of(cand.get("worker"))
sigs = (load_providers().get(prov) or {}).get("signatures") if prov else None
low = (text or "").lower()
for sg in sigs or []:
m = sg.get("match") or ""
try:
hit = bool(re.search(m[3:], text or "")) if m.startswith("re:") else m.lower() in low
except re.error:
hit = False
if not hit:
continue
retry = None
if sg.get("until_path"):
try:
found = path_values(_json_in(text) if not sg["until_path"].startswith("re:") else text, sg["until_path"])
at = next((t for t in (time_value(x) for x in found) if t), None)
retry = max(60.0, at - time.time()) if at else None
except ValueError:
pass
return sg["class"], "%s's own failure phrase %r" % (prov, m[:60]), retry
return None
# ---- allowance probes
class ProbeError(Exception):
"""Carries a message that is safe to show: never text from the tool or server, never the key."""
def _secret_of(d):
import subprocess
try:
r = subprocess.run(shlex.split(d["secret_command"]), capture_output=True, text=True, timeout=15, stdin=subprocess.DEVNULL)
except (OSError, ValueError, subprocess.SubprocessError):
raise ProbeError("the secret command could not be run")
if r.returncode != 0:
raise ProbeError("the secret command exited with status %d" % r.returncode)
out = r.stdout or ""
try:
found = path_values(_json_in(out) if not d["secret_path"].startswith("re:") else out, d["secret_path"])
except ValueError:
raise ProbeError("the secret path cannot be read")
key = next((x for x in found if isinstance(x, str) and 8 <= len(x) <= 4096 and x.isprintable()), None)
if key is None:
raise ProbeError("the secret path found no key in the command's output")
return key
def _fetch(d, secret):
"""The text a probe reads: a tool's own output, or one GET (no redirects: the handler's redirect_request answers
None, so a 3xx is an error; a short timeout; a size limit)."""
import subprocess
if d.get("command"):
try:
r = subprocess.run(shlex.split(d["command"]), capture_output=True, text=True, timeout=15, stdin=subprocess.DEVNULL)
except (OSError, ValueError, subprocess.SubprocessError):
raise ProbeError("the allowance command could not be run")
if r.returncode != 0:
raise ProbeError("the allowance command exited with status %d" % r.returncode)
return r.stdout or ""
import urllib.error, urllib.request
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *a, **k):
return None # a redirect would carry the key to a place the owner never named
name, _eq, value = d["header"].partition("=")
req = urllib.request.Request(d["url"], headers={name: value.replace("{secret}", secret), "Accept": "application/json",
"User-Agent": "sisi-allowance-probe"})
try:
with urllib.request.build_opener(NoRedirect).open(req, timeout=conf()["allowance_timeout_s"]) as resp:
return resp.read(1000000).decode("utf-8", "replace")
except urllib.error.HTTPError as e:
raise ProbeError("the server answered HTTP %d%s" % (e.code, " (a redirect, which is never followed)" if 300 <= e.code < 400 else ""))
except (urllib.error.URLError, OSError, ValueError) as e:
raise ProbeError("the request failed (%s)" % type(e).__name__)
def probe_once(d):
"""One reading from a probe definition: [{remaining, reset, total}] windows. Raises ProbeError."""
secret = _secret_of(d) if d.get("secret_command") else ""
text = _fetch(d, secret)
obj = _json_in(text)
src = obj if obj is not None else text
try:
rem = path_values(src, d["remaining_path"])
rst = path_values(src, d["reset_path"])
tot = path_values(src, d["total_path"]) if d.get("total_path") else []
except ValueError:
raise ProbeError("a path of the probe cannot be read")
wins = []
for i, x in enumerate(rem):
try:
left = float(x)
except (TypeError, ValueError):
continue
total = None
if i < len(tot) and isinstance(tot[i], (int, float)) and not isinstance(tot[i], bool) and tot[i] > 0:
total = float(tot[i])
wins.append({"remaining": left, "reset": time_value(rst[i]) if i < len(rst) else None, "total": total})
if not wins:
raise ProbeError("the answer held no number at the remaining path")
return wins
def allowance_cache():
return _state_file("allowance.json")
def read_allowance(prov, d, now, force=False):
"""The cached or fresh reading for a provider: {"at", "ok", "windows", "error"}. A probe that fails changes
nothing: the last good windows stay, with the error beside them."""
cache = _load(allowance_cache())
last = cache.get(prov) if isinstance(cache.get(prov), dict) else {}
if not force and last and now - float(last.get("at") or 0) < conf()["allowance_cache_s"]:
return last
new = {"at": now, "ok": True, "windows": last.get("windows") or []}
try:
new["windows"] = probe_once(d)
except ProbeError as e:
new.update(ok=False, error=str(e))
except Exception as e: # never let a probe hold a command up
new.update(ok=False, error="the probe failed (%s)" % type(e).__name__)
cache[prov] = new
try:
_save(allowance_cache(), cache)
except OSError:
pass
return new
def allowance_state(reading):
"""{"left", "pct", "exhausted", "until"} from a reading's windows: the smallest remaining decides whether
service is out; service returns when every exhausted window has reset, so the latest of those resets."""
wins = reading.get("windows") or []
if not wins:
return None
spent = [w for w in wins if w["remaining"] <= 0]
pcts = [100.0 * w["remaining"] / w["total"] for w in wins if w.get("total")]
until = None
if spent and all(w.get("reset") for w in spent):
until = max(w["reset"] for w in spent)
return {"left": min(w["remaining"] for w in wins), "pct": min(pcts) if pcts else None,
"exhausted": bool(spent), "until": until}
def _probes():
return {p: e["allowance"] for p, e in load_providers().items()
if isinstance(e.get("allowance"), dict) and e["allowance"].get("state") == "usable"}
def routing_provider(c):
from . import routing
return routing.provider_of(c.get("worker"))
def apply_allowances(cands, now=None, force=False):
"""Read each defined probe (when its cached reading is old), set the candidates' allowance, and mark a provider
whose allowance is spent as down until the reset it reports. Returns the set of providers that are spent now."""
probes = _probes()
spent = set()
if not probes:
return spent
from . import workers
now = time.time() if now is None else now
for prov, d in probes.items():
reading = read_allowance(prov, d, now, force)
st = allowance_state(reading) if reading.get("ok") else None
if st is None:
continue
note = "allowance probe: nothing left%s" % (" until %s" % workers._when(st["until"]) if st["until"] else "")
down = workers.read_availability().get(prov)
if st["exhausted"]:
spent.add(prov)
if not (down and float(down.get("retry_at") or 0) > now):
workers.record_down([prov], "limit", note, now=now, until_ts=st["until"] or now + 900, provider=prov)
elif down and str(down.get("note") or "").startswith("allowance probe"):
workers.clear_down(prov)
for c in cands:
if routing_provider(c) == prov:
c["allowance_pct_left"] = 0.0 if st["exhausted"] else st["pct"]
return spent
def refresh_allowances(force=False):
return apply_allowances([], force=force)
def limit_until(cand):
"""When a provider that just reported a limit is back, by its own probe (read now), or None."""
prov = routing_provider(cand)
d = _probes().get(prov) if prov else None
if d is None:
return None
st = allowance_state(read_allowance(prov, d, time.time(), True))
return st["until"] if st and st["exhausted"] else None
def provider_lines(t):
"""`sisi workers` lines under a tool for each of its providers that has a fact: plan, allowance, phrases, models."""
provs = load_providers()
if not provs:
return []
from . import routing
names = {routing.provider_of(m) for m in t.get("models") or [] if routing.provider_of(m)}
out = []
for prov in sorted(names & set(provs)):
e = provs[prov]
bits = []
if e.get("plan"):
bits.append("%s plan%s (%s, %s)" % ("flat-rate" if e["plan"] in ("flat", "free") else "per-use",
" - %s" % e["note"] if e.get("note") else "", e.get("source") or "no source", e.get("date") or "no date"))
out.append(" provider %s: %s" % (prov, "; ".join(bits) or "facts recorded"))
d = e.get("allowance")
if d and d.get("state") == "usable":
r = _load(allowance_cache()).get(prov) or {}
st = allowance_state(r) if r else None
if st:
resets = [w["reset"] for w in r["windows"] if w.get("reset")]
out.append(" allowance left: %s%s%s%s" % (
("%g%% (smallest window)" % st["pct"]) if st["pct"] is not None else ("%g (smallest window)" % st["left"]),
(", NONE LEFT, back %s" % time.strftime("%Y-%m-%d %H:%M", time.localtime(st["until"])) if st["until"] else ", none left")
if st["exhausted"] else "",
"; next reset %s" % time.strftime("%Y-%m-%d %H:%M", time.localtime(min(resets))) if resets else "",
"; the last probe failed, this is the reading before it (%s)" % r["error"] if not r.get("ok") else ""))
elif r.get("error"):
out.append(" allowance: the probe failed (%s); nothing is assumed" % r["error"])
elif d:
out.append(" allowance probe waits for the owner: `sisi approve probe-%s`" % prov)
for sg in e.get("signatures") or []:
out.append(" failure phrase %r is classified %s" % (sg["match"], sg["class"]))
mods = [m.split("/", 1)[1] for m in t.get("models") or [] if routing.provider_of(m) == prov]
out.append(" models: %s" % ", ".join(mods[:12] + (["... and %d more" % (len(mods) - 12)] if len(mods) > 12 else [])))
return out
+1 -1
View File
@@ -31,7 +31,7 @@ LONG = {
'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score)',
'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library',
'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe',
'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)\n sisi workers learn NAME [--check FILE | --record FILE | --verify] a new command-line tool: print the brief a cheap worker follows to write its driver (JSON); --record validates it, stores it and runs ONE smoke task, and only a passing driver is used (one that switches off approvals waits for `sisi approve drv-NAME`)\n sisi workers forget NAME remove a learned driver or a provider the host listed',
'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)\n sisi workers learn NAME [--check FILE | --record FILE | --verify] a new command-line tool: print the brief a cheap worker follows to write its driver (JSON); --record validates it, stores it and runs ONE smoke task, and only a passing driver is used (one that switches off approvals waits for `sisi approve drv-NAME`)\n sisi workers forget NAME remove a learned driver or a provider the host listed\n sisi workers plan PROVIDER flat|free|per-use --source S [--note T] a provider's plan (one tool can carry several providers, each with its own); a flat or free plan with allowance left costs nothing extra per task, a price fact on its models is their relative cost inside the plan\n sisi workers vouch WORKER --up-to 1|2|3 --why \"OWNER'S WORDS\" | --remove the owner's word that a new worker handles up to that difficulty (counted to 2 only when the words were not typed by the owner)\n sisi workers allowance PROVIDER --url URL --header 'Name={secret}' --secret-from-command CMD --secret-path P --remaining-path P --reset-path P | --command CMD read a provider's allowance (the key is fetched at probe time, never stored; waits for `sisi approve probe-PROVIDER`)\n sisi workers signature PROVIDER --match 'TEXT|re:REGEX' --class auth|limit|missing|error [--until-path P] a provider's own failure phrase, consulted before the built-in ones',
'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why',
'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id',
'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only',
+44 -10
View File
@@ -115,14 +115,19 @@ def _floor_pct(floors, difficulty):
def _pattern_match(c, patterns):
"""The (pattern, why) a candidate matches, or None. A pattern matches as a substring of the
worker, model or tool name, case aside."""
worker, model or tool name, case aside; a pattern ending in `/` is a provider and matches only
the workers whose id starts with it (`a-b/` never reaches `a-b-c/x` or a model named `a-b`)."""
hay = " ".join(str(x or "").lower() for x in (c.get("worker"), c.get("model"), c.get("tool")))
worker = str(c.get("worker") or "").lower()
for entry in patterns or []:
if isinstance(entry, dict):
pat, why = str(entry.get("pattern") or ""), str(entry.get("why") or "")
else:
pat, why = str(entry), ""
if pat and pat.lower() in hay:
if pat.endswith("/"): # `provider/` names one provider exactly: the start of the worker id, never a part of another name
if worker.startswith(pat.lower()):
return pat, why
elif pat and pat.lower() in hay:
return pat, why
return None
@@ -144,12 +149,22 @@ def _availability_keys(c):
return keys
def provider_of(worker):
"""The part of a worker id before the first slash, lower case, or None."""
w = str(worker or "")
return w.split("/", 1)[0].lower() if "/" in w else None
def _down_entry(c, availability, now):
keys = _availability_keys(c)
prov = provider_of(c.get("worker"))
for k, e in (availability or {}).items():
if not isinstance(e, dict):
if not isinstance(e, dict) or not float(e.get("retry_at") or 0) > now:
continue
if str(k).lower() in keys and float(e.get("retry_at") or 0) > now:
if e.get("scope") == "provider": # a mark made for one provider reaches that provider's workers only
if str(k).lower() == prov:
return e
elif str(k).lower() in keys:
return e
return None
@@ -191,7 +206,7 @@ def _cell(stats, worker, kind, difficulty):
# ---------------------------------------------------------------- capability evidence
_TIER_RANK = {"a": 0, "b-higher": 1, "b-all": 2} # smaller is closer to the request
_TIER_RANK = {"a": 0, "b-higher": 1, "vouch": 1.5, "b-all": 2} # smaller is closer to the request
_NO_CELL = {"n": 0, "good": 0}
@@ -231,7 +246,7 @@ def _by_difficulty(stats, worker, kind):
return own, pooled
def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None):
def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None, vouch=0):
"""What the evidence says about one worker for a kind and difficulty. Returns a dict:
tier "a", "b-higher", "b-all", "standing", "unknown" or "none"
capable whether the evidence says it is capable enough
@@ -241,7 +256,9 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f
level 3 judged proof, 2 benchmark, 1 weak, 0 nothing, -1 bad: never rises with difficulty
n, good, at the judged cell behind a, b-higher, b-all and the weak tier (and its difficulty)
share, needed, floor for the standing tier: percent of the best, the figure needed, the floor
Standing is compared only with the best standing; a rate only with the bar."""
Standing is compared only with the best standing; a rate only with the bar.
`vouch` is the difficulty up to which the owner vouched for the worker: a judged proof outranks it, a thick bad
record or a thin one with repeated rejections cancels it, and it outranks a benchmark (tier "vouch")."""
d = difficulty
own, pooled = _by_difficulty(stats, worker, kind)
out = {"tier": "none", "capable": False, "bad": False, "weak": False, "contradicted": False,
@@ -275,6 +292,9 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f
tier, at, cell = proof
out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell))
return out
if vouch and isinstance(d, int) and d <= vouch and not out["contradicted"]:
out.update(tier="vouch", capable=True, level=3, at=vouch, measure=0.0)
return out
if standing is not None:
pct = _floor_pct(floors, d)
needed = (best_standing or 0.0) * pct / 100.0
@@ -314,6 +334,13 @@ def _standing_of(c):
# ---------------------------------------------------------------- the pool, then the choice
def vouch_level(c):
"""The difficulty up to which the owner's word makes this candidate capable (0 for none)."""
v = c.get("vouch")
lvl = v.get("level") if isinstance(v, dict) else 0
return lvl if isinstance(lvl, int) and not isinstance(lvl, bool) and lvl > 0 else 0
def _prepare(candidates, records, availability, now, exclude, avoid, review_of, difficulty=None):
"""The workers that may be recommended at all: (eligible, passed, stats, author_maker). An unproven
worker (flagged by workers.build_candidates: new, with fewer than MIN_ATTEMPTS judged attempts) is
@@ -331,7 +358,7 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of,
if "contributor" in str(c.get("model") or w).lower():
passed.append((w, "its id contains 'contributor', a tier that trains on prompts"))
continue
if c.get("unproven") and isinstance(difficulty, int) and difficulty > 1:
if c.get("unproven") and isinstance(difficulty, int) and difficulty > max(1, vouch_level(c)):
passed.append((w, "unproven: a new worker with no judged record is offered routine work (difficulty 1) only"))
continue
down = _down_entry(c, availability, now)
@@ -379,7 +406,7 @@ def _assess_all(eligible, stats, kind, difficulty, floors):
"""({worker: assessment}, best standing among the usable workers)."""
standings = [s for s in (_standing_of(c) for c in eligible) if s is not None]
best = max(standings) if standings else None
return ({c["worker"]: assess(stats, c["worker"], kind, difficulty, _standing_of(c), best, floors)
return ({c["worker"]: assess(stats, c["worker"], kind, difficulty, _standing_of(c), best, floors, vouch_level(c))
for c in eligible}, best)
@@ -419,7 +446,7 @@ def _prefer_judged(capable, assessments, difficulty):
those capable by the judged record across all kinds; failing that, everyone capable."""
if difficulty is None or difficulty < 2:
return list(capable), False
for tiers in (("a", "b-higher"), ("b-all",)):
for tiers in (("a", "b-higher", "vouch"), ("b-all",)):
own = [c for c in capable if assessments[c["worker"]]["tier"] in tiers]
if own:
return own, True
@@ -556,6 +583,8 @@ def _why_not(a, difficulty, basis, cheaper):
if a["tier"] == "b-all":
return (lead + "its only judged proof is across other kinds, and a worker with a judged record "
"for this kind is usable", None)
if a["tier"] == "vouch":
return (lead + "capable by the owner's word, and a worker with a judged record for this kind is usable", None)
return (lead + "capable only by benchmark standing or as an exploration; above difficulty 1 a worker "
"with a judged record is preferred to a benchmark",
("standing %g" % a["standing"]) if a["standing"] is not None else None)
@@ -665,6 +694,11 @@ def evidence_line(a, kind, difficulty, choice, basis):
return ("evidence (c), benchmark standing only: %g (%s, %s), the strongest known; it is under the %g "
"needed for difficulty %d" % (a["standing"], src, choice.get("standing_date") or "no date stated",
a["needed"], difficulty))
if tier == "vouch":
v = choice.get("vouch") or {}
return ("evidence (the owner's word): vouched for up to difficulty %d%s (%s, %s); it ranks with judged proof "
"until its own record is thick" % (a["at"], " (relayed by an agent: counted up to difficulty 2 only)"
if v.get("relayed") else "", _short(v.get("why")), v.get("date") or "no date stated"))
if tier == "unknown":
return "evidence (d): nothing is known about this worker yet; it is an exploration on low-stakes work"
if a.get("weak"):
+34 -8
View File
@@ -401,10 +401,11 @@ def _parse_time(value):
return None
def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts=None):
def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts=None, provider=None):
"""Record unavailability under one or more keys (a worker, its tool, its plan prefix).
Unavailability is kept apart from judged work: it never counts against quality. Without an
explicit `until_ts`, the wait before the next try widens with each repeat failure."""
explicit `until_ts`, the wait before the next try widens with each repeat failure. The key equal to
`provider` is marked as a provider's: it reaches that provider's workers only (routing.provider_of)."""
now = time.time() if now is None else now
avail = read_availability()
for key in keys:
@@ -416,6 +417,8 @@ def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts=
entry["reason"] = reason
if note:
entry["note"] = note
if provider and key == str(provider).strip().lower():
entry["scope"] = "provider"
if until_ts is not None:
entry["retry_at"] = float(until_ts)
else:
@@ -789,7 +792,8 @@ def notes_for(candidates_by_worker, chosen, passed, notes=None, limit=5):
DATA_FILES = ("delegations.jsonl", "worker-availability.json", "worker-prices.json",
"model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-drivers.json")
"model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-drivers.json",
"worker-providers.json", "worker-vouches.json")
def _data_state():
@@ -1153,11 +1157,19 @@ def _append_transcript(path, heading, cmd, out, err, rc):
% (heading, " ".join(str(c)[:200] for c in cmd), rc, out or "", err or ""))
def _down_provider(cand):
"""The provider of a worker (the part of its id before the first slash) when it differs from its tool: a
tool that carries several providers has a login, a plan and an allowance for each."""
prov = routing.provider_of(cand.get("worker"))
return prov if prov and prov != str(cand.get("tool") or "").lower() else None
def _down_keys(cand, reason):
keys = [cand["worker"]]
model = str(cand.get("model") or "")
prov = _down_provider(cand)
if reason == "auth" and cand.get("tool"):
keys.append(cand["tool"])
keys.append(prov or cand["tool"]) # one provider's login, or the tool's own when it has no providers
if reason == "limit" and "/" in model:
keys.append(model.split("/", 1)[0])
return keys
@@ -1229,10 +1241,13 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
% (cand["worker"], timeout, transcript))
return None, None, notes
_append_transcript(transcript, cand["worker"], cmd, out, err, rc)
failure = classify_failure(out + "\n" + err, rc, _D.extra_signatures(driver))
failure = (_D.provider_failure(cand, out + "\n" + err)
or classify_failure(out + "\n" + err, rc, _D.extra_signatures(driver)))
if failure is not None:
reason, note, retry = failure
record_down(_down_keys(cand, reason), reason, note, retry_after_s=retry)
record_down(_down_keys(cand, reason), reason, note, retry_after_s=retry,
until_ts=_D.limit_until(cand) if reason == "limit" else None,
provider=_down_provider(cand) or (str(cand.get("model")).split("/", 1)[0] if "/" in str(cand.get("model")) else None))
mark_discovery_stale()
notes.append("%s is unavailable (%s: %s); trying the next choice" % (cand["worker"], reason, note))
cand = None
@@ -1417,6 +1432,8 @@ def cmd_workers(args=()):
return _cmd_up(args[1:])
if args[:1] == ["import"]:
return _cmd_import(args[1:])
if args[:1] in (["plan"], ["vouch"], ["allowance"], ["signature"]):
return _D.cmd_provider(args)
if args[:1] == ["learn"]:
return _D.cmd_learn(args[1:])
if args[:1] == ["forget"]:
@@ -1424,6 +1441,7 @@ def cmd_workers(args=()):
migrate_standing_facts()
disc = discover(force="--refresh" in args)
disc = dict(disc, tools=_D.merge_tools(disc.get("tools") or []))
_D.refresh_allowances(force=True) # a defined allowance probe is read now: `sisi workers` was asked
records = read_records()
avail = read_availability()
prices = load_prices()
@@ -1497,6 +1515,8 @@ def cmd_workers(args=()):
(" (%s)" % entry["why"]) if entry.get("why") else ""))
for n in load_notes():
print("Note (information for the agent): %s" % note_line(n))
for ln in _D.vouch_lines():
print(ln)
line = facts_line()
if line:
print(line)
@@ -1542,7 +1562,9 @@ def cmd_route(args=()):
return 1
kind, difficulty = setup
records = read_records()
candidates, cold, excluded = routable_candidates(build_candidates(), records)
everything = build_candidates()
_D.apply_allowances(everything) # a defined allowance probe older than a few minutes is read again
candidates, cold, excluded = routable_candidates(everything, records)
prefs = effective_prefs(kind, difficulty, os.getcwd())
everyone = candidates
candidates, limited = apply_limits(candidates, prefs)
@@ -1642,6 +1664,7 @@ def cmd_delegate(args=()):
print("sisi delegate: not a folder: %s" % cwd, file=sys.stderr)
return 1
candidates = build_candidates()
spent = _D.apply_allowances(candidates)
explicit = None
worker = _opt(args, "--worker")
if worker:
@@ -1649,7 +1672,10 @@ def cmd_delegate(args=()):
if explicit is None:
print("sisi delegate: no such worker found here: %s (see `sisi workers`)" % worker, file=sys.stderr)
return 1
else:
if routing.provider_of(explicit["worker"]) in spent: # its allowance is read as spent: another worker, as after a limit
print("sisi: %s has no allowance left until its reset; choosing another worker" % explicit["worker"])
explicit = None
if explicit is None:
candidates, _cold, _excluded = routable_candidates(candidates, read_records())
rec, final, notes = run_delegation(candidates, kind, difficulty, prompt, cwd,
explicit=explicit, review_of=_opt(args, "--review-of"),
+557
View File
@@ -0,0 +1,557 @@
"""One tool, several providers: per-provider plans, the owner's vouch, allowance probes and failure phrases.
Requirements: R-7.2-1 and R-7.2-2 (the least expensive sufficiently capable worker: a flat plan with allowance left
costs nothing extra, a lighter model of the plan first), R-7.2-3 (empirical and revisable: a vouch is a prior that the
judged record replaces), R-7.3-1 (cost counts what a plan really charges), R-16-3 and R-16-4 (a key is used for one
request and never stored, printed or logged; least privilege: a redirect never carries it), R-16-6 and R-16-7
(tool output and server answers are data, validated), R-16-8 (a consequential definition waits for the owner),
R-16-11 (an agent cannot widen what routing trusts: a relayed vouch counts up to difficulty 2)."""
import http.server, json, os, threading, time, unittest
from unittest import mock
import test_discovery as TD
from support import *
from sisi import discovery, routing, workers
SECRET = "SECRETKEYVALUE123456"
MULTI = """#!/bin/sh
if [ "$1" = "models" ]; then echo "zai/a"; echo "zai/b"; echo "other/c"; exit 0; fi
if [ -n "$FAKE_MARK" ]; then echo "$@" >> "$FAKE_MARK"; fi
n=0; last=""
for a in "$@"; do n=$((n+1)); last="$a"; done
model=""; prev=""
for a in "$@"; do if [ "$prev" = "--model" ]; then model="$a"; fi; prev="$a"; done
case "$FAKE_MODE:$model" in
quota:zai/*) echo "weekly allowance used up for this plan"; exit 0 ;;
code1113:zai/*) echo '{"error":{"code":"1113","message":"Insufficient balance or no resource package","usage limit":true}}'; exit 1 ;;
reset:zai/*) echo '{"error":{"code":"1308","message":"limit reached","resetAt":"RESETAT"}}'; exit 1 ;;
esac
echo "$last"
exit 0
"""
AUTH_EXPORT = ('#!/bin/sh\necho \'[{"integrationID":"other","active":true,"value":{"type":"api","key":"NOTTHISKEYXXXX"}},'
'{"integrationID":"zai","active":true,"value":{"type":"api","key":"%s"}}]\'\n' % SECRET)
LEAKY_EXPORT = '#!/bin/sh\necho "%s" ; echo "%s" >&2\nexit 1\n' % (SECRET, SECRET)
PATHS = ["--remaining-path", "data.limits[type=CREDIT_LIMIT].remaining", "--reset-path", "data.limits[type=CREDIT_LIMIT].nextResetTime",
"--total-path", "data.limits[type=CREDIT_LIMIT].total"]
class Quota:
"""A local stand-in for a provider's allowance endpoint."""
def __init__(self):
owner = self
self.hits, self.leaks, self.mode = [], [], "ok"
self.windows = [(100, 1000, 4102444800000), (900, 1000, 4102444900000)]
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
auth = self.headers.get("Authorization")
if self.path == "/leak":
owner.leaks.append(auth)
self.send_response(200); self.end_headers(); self.wfile.write(b"{}")
return
owner.hits.append(auth)
if owner.mode == "redirect":
self.send_response(302); self.send_header("Location", "http://127.0.0.1:%d/leak" % owner.port); self.end_headers()
elif owner.mode == "hang":
time.sleep(3)
elif auth != SECRET:
body = ('{"error":"bad key %s"}' % auth).encode()
self.send_response(401); self.end_headers(); self.wfile.write(body)
else:
body = json.dumps({"data": {"limits": [{"type": "CREDIT_LIMIT", "remaining": r, "total": t, "nextResetTime": n}
for r, t, n in owner.windows]}}).encode()
self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers()
self.wfile.write(body)
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
self.port = self.server.server_address[1]
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
@property
def url(self):
return "http://127.0.0.1:%d/quota" % self.port
def close(self):
self.server.shutdown()
self.server.server_close()
class ProviderCase(TD.DiscoveryCase):
def setUp(self):
super().setUp()
self.exe("multi", MULTI)
f = TD.driver_file(os.path.join(self.tmp, "m.json"), name="multi", exe="multi",
run=["multi", "{model_flag}", "-p", "{prompt}"], list=["multi", "models"], plan=None,
limit_signatures=["allowance used up"], tokens_regex=None)
r = self.sisi("workers", "learn", "multi", "--record", f)
self.assertEqual(r.returncode, 0, r.stdout)
self.write_cfg({"learning": {"agent_relayed_approval": True}, "discovery": {"allowance_timeout_s": 1}})
def cands(self):
return {c["worker"]: c for c in workers.build_candidates()}
def brief(self):
p = os.path.join(self.proj, "brief.md")
open(p, "w").write(TD.BRIEF)
return p
def fact(self, worker, price, plan=None):
args = ["workers", "fact", worker, "--price", str(price), "--source", "test"] + (["--plan", plan] if plan else [])
self.assertEqual(self.sisi(*args).returncode, 0)
def define_probe(self, quota, approve=True, export=AUTH_EXPORT, extra=()):
self.exe("authexport", export)
r = self.sisi("workers", "allowance", "zai", "--url", quota.url, "--header", "Authorization={secret}",
"--secret-from-command", "authexport", "--secret-path", "[integrationID=zai][active=true].value.key",
*PATHS, *extra)
self.assertEqual(r.returncode, 0, r.stdout)
if approve:
self.assertEqual(self.sisi("approve", "probe-zai", "--yes").returncode, 0)
return r
# ---------------------------------------------------------------- item 7: one tool, several providers
def c(worker, tool, **kw):
model = worker if "/" in worker else worker.split("/")[-1]
return dict({"worker": worker, "tool": tool, "model": worker if tool == "multi" else worker.split("/", 1)[-1],
"plan": "flat", "cost": None, "usable": True, "allowance_pct_left": None, "aliases": [worker],
"maker": "m"}, **kw)
class PerProviderConstraints(unittest.TestCase):
"""A constraint on provider `a-b` never reaches provider `a-b-c`, nor a model `a-b` under another tool."""
def setUp(self):
self.ab, self.abc, self.other = c("a-b/x", "multi"), c("a-b-c/y", "multi"), c("other/a-b", "other")
def test_a_provider_pattern_matches_the_provider_exactly(self):
hits = [w["worker"] for w in (self.ab, self.abc, self.other) if routing._pattern_match(w, [{"pattern": "a-b/"}])]
self.assertEqual(hits, ["a-b/x"])
self.assertEqual(routing._pattern_match(c("xa-b/z", "multi"), [{"pattern": "a-b/"}]), None)
def test_avoid_and_prefer_by_provider_pattern(self):
avoid = routing.choose([self.ab, self.abc, self.other], [], {}, "read", 1, now=1.0, avoid=[{"pattern": "a-b/"}])
self.assertNotEqual(avoid["choice"]["worker"], "a-b/x")
self.assertIn(avoid["choice"]["worker"], ("a-b-c/y", "other/a-b"))
prefer = routing.choose([self.abc, self.other, self.ab], [], {}, "read", 1, now=1.0, prefer=[{"pattern": "a-b/"}])
self.assertEqual(prefer["choice"]["worker"], "a-b/x")
def test_a_provider_availability_mark_reaches_that_provider_only(self):
down = {"a-b": {"reason": "limit", "retry_at": 9e9, "scope": "provider"}}
self.assertIsNotNone(routing._down_entry(self.ab, down, 1.0))
self.assertIsNone(routing._down_entry(self.abc, down, 1.0))
self.assertIsNone(routing._down_entry(self.other, down, 1.0), "a model named a-b under another tool is not the provider")
r = routing.choose([self.ab, self.abc, self.other], [], down, "read", 1, now=1.0)
self.assertNotEqual(r["choice"]["worker"], "a-b/x")
def test_only_scopes_to_its_provider(self):
kept, out = workers.apply_limits([self.ab, self.abc, self.other],
{"only": [{"provider": "a-b", "patterns": ["zzz"], "why": "w"}]})
self.assertEqual([w["worker"] for w in kept], ["a-b-c/y", "other/a-b"])
self.assertEqual([w for w, _ in out], ["a-b/x"])
def test_notes_by_provider_pattern(self):
by = {w["worker"]: w for w in (self.ab, self.abc, self.other)}
lines = workers.notes_for(by, self.abc, [("a-b/x", "r"), ("other/a-b", "r")], notes=[{"pattern": "a-b/", "text": "T", "why": "w"}])
self.assertEqual(len(lines), 1)
self.assertIn("passed over: a-b/x", lines[0])
self.assertNotIn("the chosen worker", lines[0])
self.assertNotIn("other/a-b", lines[0])
class ProviderPlans(ProviderCase):
def test_a_providers_plan_costs_its_workers_as_flat_and_others_stay_unknown(self):
self.assertEqual(self.sisi("workers", "plan", "zai", "flat", "--source", "owner", "--note", "quarterly subscription").returncode, 0)
cands = self.cands()
self.assertEqual(cands["zai/a"]["plan"], "flat")
self.assertEqual(cands["zai/b"]["plan"], "flat")
self.assertEqual(cands["other/c"]["plan"], "per-use") # unproven and no plan fact: per-use
shown = self.sisi("workers").stdout
self.assertIn("provider zai: flat-rate plan - quarterly subscription (owner,", shown)
self.assertIn("models: a, b", shown)
def test_free_counts_as_flat_and_a_models_own_plan_fact_wins(self):
self.sisi("workers", "plan", "zai", "free", "--source", "s")
self.assertEqual(self.cands()["zai/a"]["plan"], "flat")
self.fact("zai/a", 2, plan="per-use")
self.assertEqual(self.cands()["zai/a"]["plan"], "per-use")
self.assertEqual(self.cands()["zai/b"]["plan"], "flat")
def test_the_lighter_model_of_a_flat_plan_takes_routine_work(self):
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
self.fact("zai/a", 3)
self.fact("zai/b", 1)
r = self.sisi("route", "--kind", "read", "--difficulty", "1")
self.assertEqual(r.stdout.splitlines()[0], "zai/b", r.stdout)
def test_a_plan_needs_a_source_and_a_known_kind_and_can_be_removed(self):
for args in (("zai", "flat"), ("zai", "monthly", "--source", "s"), ("Bad Name", "flat", "--source", "s"), ()):
self.assertEqual(self.sisi("workers", "plan", *args).returncode, 1, args)
self.sisi("workers", "plan", "zai", "flat", "--source", "s")
self.assertEqual(self.sisi("workers", "plan", "zai", "--remove").returncode, 0)
self.assertEqual(self.cands()["zai/a"]["plan"], "per-use")
# ---------------------------------------------------------------- item 8: the owner's word
class Vouch(unittest.TestCase):
def new(self, worker, **kw):
return dict(c(worker, "multi"), unproven=True, unproven_ok=True, **kw)
def test_a_vouched_worker_is_capable_up_to_its_level_with_the_owners_word_as_evidence(self):
a = self.new("zai/a", vouch={"level": 2, "why": "Verified by hand", "date": "2026-11-23", "relayed": False})
for d, ok in ((1, True), (2, True), (3, False)):
r = routing.choose([a], [], {}, "impl", d, now=1.0)
self.assertEqual(r["choice"] is not None, ok, d)
r = routing.choose([a], [], {}, "impl", 2, now=1.0)
text = "\n".join(routing.explain_choice(r, "impl", 2))
self.assertIn("evidence (the owner's word): vouched for up to difficulty 2", text)
self.assertIn("Verified by hand", text)
def test_proof_before_benchmark_a_vouch_outranks_a_benchmark_above_routine_work(self):
vouched = self.new("zai/a", vouch={"level": 2, "why": "w", "date": "d", "relayed": False}, cost=5.0)
bench = dict(c("big/b", "multi"), standing=95.0, cost=1.0)
r = routing.choose([bench, vouched], [], {}, "impl", 2, now=1.0)
self.assertEqual(r["choice"]["worker"], "zai/a")
self.assertTrue(r["judged_first"])
def test_a_vouch_ranks_with_judged_proof_and_a_thick_bad_record_overrides_it(self):
recs = TD.attempts("old/p", 8, "impl", 2)
vouched = self.new("zai/a", vouch={"level": 2, "why": "w", "date": "d", "relayed": False}, cost=0.1)
proven = c("old/p", "multi", cost=9.0)
self.assertEqual(routing.choose([vouched, proven], recs, {}, "impl", 2, now=1.0)["choice"]["worker"], "zai/a",
"both are proof: the cheaper takes it")
dear = dict(vouched, cost=20.0)
self.assertEqual(routing.choose([dear, proven], recs, {}, "impl", 2, now=1.0)["choice"]["worker"], "old/p")
bad = TD.attempts("zai/a", 8, "impl", 2, outcome="rejected")
a = routing.assess(routing.candidate_stats([vouched], bad), "zai/a", "impl", 2, vouch=2)
self.assertTrue(a["bad"])
self.assertFalse(a["capable"])
def test_a_thin_record_with_repeated_rejections_cancels_the_word(self):
a = routing.assess(routing.candidate_stats([c("zai/a", "multi")], TD.attempts("zai/a", 2, "impl", 2, outcome="rejected")),
"zai/a", "impl", 2, vouch=2)
self.assertFalse(a["capable"])
def test_an_unvouched_new_worker_stays_on_routine_work(self):
flash = self.new("zai/flash")
self.assertIsNone(routing.choose([flash], [], {}, "impl", 2, now=1.0)["choice"])
self.assertEqual(routing.choose([flash], [], {}, "impl", 1, now=1.0)["choice"]["worker"], "zai/flash")
class VouchCommand(ProviderCase):
def route_line(self, *a):
return self.sisi("route", *a).stdout.splitlines()[:1]
def setup_prices(self):
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
self.fact("zai/a", 3)
self.fact("zai/b", 1)
def typed_session(self, words):
from sisi import store
tp = os.path.join(self.tmp, "t.jsonl")
with open(tp, "w") as f:
f.write(json.dumps({"type": "user", "message": {"content": words}}) + "\n")
f.write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "the agent says: invented owner words"}]}}) + "\n")
store.save_session("s1", {"session_id": "s1", "transcript_path": tp})
return {"SISI_SESSION_ID": "s1"}
def test_the_owner_vouches_and_routing_uses_it_then_remove_undoes_it(self):
self.setup_prices()
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "2"), ["zai/a"])
env = self.typed_session("Verified: opencode run -m zai/a completes a tool-using edit-and-test task")
r = self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "Verified: opencode run -m zai/a completes a tool-using edit-and-test task", env=env)
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("typed by the owner", r.stdout)
out = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain").stdout
self.assertEqual(out.splitlines()[0], "zai/a", out)
self.assertIn("the owner's word", out)
self.assertIn("unproven: check this result", out, "a vouched worker is still checked a level more carefully")
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "3"), ["zai/a"])
self.assertIn("Vouched: zai/a up to difficulty 2", self.sisi("workers").stdout)
self.assertEqual(self.sisi("workers", "vouch", "zai/a", "--remove").returncode, 0)
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "2"), ["zai/a"])
def test_a_vouch_with_invented_owner_words_counts_only_up_to_difficulty_two(self):
self.setup_prices()
for env in (None, self.typed_session("something else the owner typed entirely")):
r = self.sisi("workers", "vouch", "zai/a", "--up-to", "3", "--why", "the owner said it works for everything", env=env)
self.assertEqual(r.returncode, 0)
self.assertIn("relayed by an agent", r.stdout)
self.assertIn("counted only up to difficulty 2", r.stdout)
self.assertEqual(discovery.load_vouches()["zai/a"]["origin"], "relayed by an agent")
self.assertEqual(self.cands()["zai/a"]["vouch"]["level"], 2)
self.assertEqual(self.route_line("--kind", "impl", "--difficulty", "2"), ["zai/a"])
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "3"), ["zai/a"])
env = self.typed_session("Verified by hand: it handles everything")
self.sisi("workers", "vouch", "zai/a", "--up-to", "3", "--why", "Verified by hand: it handles everything", env=env)
self.assertEqual(self.cands()["zai/a"]["vouch"]["level"], 3)
def test_once_it_has_its_own_thick_record_the_vouch_is_ignored(self):
self.setup_prices()
self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "x words")
self.assertIn("vouch", self.cands()["zai/a"])
for row in TD.attempts("zai/a", 8, "impl", 1):
workers.append_record(row)
self.assertNotIn("vouch", self.cands()["zai/a"])
self.assertIn("ignored now: its own record decides", self.sisi("workers").stdout)
def test_bad_arguments_are_refused(self):
for args in (("zai/a",), ("zai/a", "--up-to", "5", "--why", "x"), ("zai/a", "--up-to", "2"), ("zai/a", "--up-to", "2", "--why", " ")):
self.assertEqual(self.sisi("workers", "vouch", *args).returncode, 1, args)
self.assertEqual(discovery.load_vouches(), {})
# ---------------------------------------------------------------- item 9: allowance probes and failure phrases
class PathLanguage(unittest.TestCase):
def test_paths_over_the_shapes_the_probe_reads(self):
export = [{"integrationID": "x", "active": True, "value": {"key": "k0"}},
{"integrationID": "zai", "active": False, "value": {"key": "k1"}},
{"integrationID": "zai", "active": True, "value": {"key": "k2"}}]
self.assertEqual(discovery.path_values(export, "[integrationID=zai][active=true].value.key"), ["k2"])
self.assertEqual(discovery.path_values(export, "[2].value.key"), ["k2"])
self.assertEqual(discovery.path_values(export, "[*].integrationID"), ["x", "zai", "zai"])
body = {"data": {"limits": [{"type": "A", "remaining": 1}, {"type": "CREDIT_LIMIT", "remaining": 2}, {"type": "CREDIT_LIMIT", "remaining": 3}]}}
self.assertEqual(discovery.path_values(body, "data.limits[type=CREDIT_LIMIT].remaining"), [2, 3])
self.assertEqual(discovery.path_values("tokens left: 42 of 100", "re:left: (\\d+)"), ["42"])
self.assertEqual(discovery.path_values(body, "data.nothing.here"), [])
for bad in ("", "data..x", "data[", "a b"):
with self.assertRaises(ValueError):
discovery.path_values(body, bad)
def test_times_in_seconds_milliseconds_and_dates(self):
self.assertEqual(discovery.time_value(1795000000), 1795000000.0)
self.assertEqual(discovery.time_value(1795000000000), 1795000000.0)
self.assertEqual(discovery.time_value("1795000000000"), 1795000000.0)
self.assertEqual(discovery.time_value("2026-11-23T10:00:00+00:00"), 1795428000.0)
self.assertIsNone(discovery.time_value("soon"))
self.assertIsNone(discovery.time_value(True))
def test_several_windows_decide_by_the_smallest_remaining_and_the_reset_that_restores_service(self):
st = discovery.allowance_state({"windows": [{"remaining": 0, "reset": 100.0}, {"remaining": 0, "reset": 500.0}, {"remaining": 9, "reset": 50.0}]})
self.assertTrue(st["exhausted"])
self.assertEqual(st["until"], 500.0, "back only when every exhausted window has reset")
st = discovery.allowance_state({"windows": [{"remaining": 0, "reset": 100.0, "total": 10}, {"remaining": 5, "reset": 500.0, "total": 10}]})
self.assertEqual(st["until"], 100.0)
self.assertEqual(st["pct"], 0.0)
self.assertIsNone(discovery.allowance_state({"windows": [{"remaining": 0, "reset": None}]})["until"])
self.assertFalse(discovery.allowance_state({"windows": [{"remaining": 3, "reset": 1.0}]})["exhausted"])
class AllowanceProbe(ProviderCase):
def setUp(self):
super().setUp()
self.q = Quota()
self.addCleanup(self.q.close)
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
self.fact("zai/a", 3)
self.fact("zai/b", 1)
self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "words")
self.fact("other/c", 5, plan="flat")
def everything_stored(self):
text = ""
for root in (self.data, self.state):
for dp, _dn, fns in os.walk(root):
for f in fns:
try:
text += open(os.path.join(dp, f), errors="replace").read()
except OSError:
pass
return text
def test_a_probe_waits_for_the_owner_and_is_never_read_before(self):
self.define_probe(self.q, approve=False)
self.assertIn("WAITING FOR THE OWNER", self.sisi("approve").stdout)
shown = self.sisi("workers").stdout
self.assertIn("allowance probe waits for the owner", shown)
self.sisi("route", "--kind", "read", "--difficulty", "1")
self.assertEqual(self.q.hits, [], "not one request before the owner approved")
self.write_cfg({"discovery": {"allowance_timeout_s": 1}}) # no relay: an agent cannot decide
self.assertEqual(self.sisi("approve", "probe-zai", "--yes").returncode, 2)
self.assertEqual(self.q.hits, [])
def test_workers_shows_the_allowance_and_the_key_is_used_once_and_stored_nowhere(self):
self.define_probe(self.q)
r = self.sisi("workers")
self.assertIn("allowance left: 10% (smallest window)", r.stdout)
self.assertRegex(r.stdout, "next reset (2099|2100)-")
self.assertEqual(self.q.hits, [SECRET])
out = self.sisi("route", "--kind", "read", "--difficulty", "1", "--explain")
self.assertEqual(self.q.hits, [SECRET], "routing reads the cached reading: it is younger than a few minutes")
for text in (r.stdout, r.stderr, out.stdout, out.stderr, self.everything_stored()):
self.assertNotIn(SECRET, text)
self.assertNotIn("NOTTHISKEYXXXX", self.everything_stored())
def test_routing_reads_again_when_the_reading_is_old(self):
self.define_probe(self.q)
self.sisi("workers")
with mock.patch.object(time, "time", return_value=time.time() + 400):
self.sisi("route", "--kind", "read", "--difficulty", "1")
self.assertEqual(len(self.q.hits), 2)
def test_a_failing_probe_command_that_echoes_the_key_leaks_nothing(self):
self.define_probe(self.q, export=LEAKY_EXPORT)
r = self.sisi("workers")
self.assertIn("the probe failed (the secret command exited with status 1)", r.stdout)
for text in (r.stdout, r.stderr, self.everything_stored()):
self.assertNotIn(SECRET, text)
self.assertEqual(self.q.hits, [])
def test_a_server_that_echoes_the_key_back_leaks_nothing(self):
self.define_probe(self.q, export=AUTH_EXPORT.replace(SECRET, SECRET + "WRONG"))
r = self.sisi("workers")
self.assertIn("the server answered HTTP 401", r.stdout)
for text in (r.stdout, r.stderr, self.everything_stored()):
self.assertNotIn(SECRET + "WRONG", text)
def test_a_redirect_is_never_followed_so_the_key_goes_nowhere_else(self):
self.q.mode = "redirect"
self.define_probe(self.q)
r = self.sisi("workers")
self.assertIn("a redirect, which is never followed", r.stdout)
self.assertEqual(self.q.leaks, [])
self.assertEqual(self.q.hits, [SECRET])
def test_a_probe_that_times_out_or_fails_changes_nothing_and_says_so_in_workers_only(self):
self.q.mode = "hang"
self.define_probe(self.q)
before = self.sisi("route", "--kind", "read", "--difficulty", "1")
self.assertEqual(before.returncode, 0, before.stdout)
self.assertNotIn("probe", before.stdout)
self.assertEqual(workers.read_availability(), {})
shown = self.sisi("workers").stdout
self.assertIn("the probe failed (the request failed", shown)
self.assertEqual(workers.read_availability(), {})
def test_a_definition_that_could_send_the_key_somewhere_else_is_refused(self):
self.exe("authexport", AUTH_EXPORT)
base = ["workers", "allowance", "zai", "--header", "Authorization={secret}", "--secret-from-command", "authexport",
"--secret-path", "a.b", *PATHS]
for url in ("http://example.com/quota", "ftp://x/y", "https://user:pw@example.com/q", "https://example.com/q?k={secret}", ""):
self.assertEqual(self.sisi(*base, "--url", url).returncode, 1, url)
self.assertEqual(self.sisi("workers", "allowance", "zai", "--url", self.q.url, "--header", "Authorization=fixed",
"--secret-from-command", "authexport", "--secret-path", "a.b", *PATHS).returncode, 1)
self.assertEqual(self.sisi("workers", "allowance", "zai", "--url", self.q.url, "--header", "Authorization={secret}",
"--secret-from-command", "authexport", "--secret-path", "a..b", *PATHS).returncode, 1)
self.assertEqual(load_providers_allowance(), None)
def test_zero_remaining_marks_the_provider_down_until_the_probe_reset_and_routing_falls_back(self):
self.q.windows = [(0, 1000, 4102444800000), (500, 1000, 4102444900000)]
self.define_probe(self.q)
shown = self.sisi("workers").stdout
self.assertIn("NONE LEFT", shown)
down = workers.read_availability()["zai"]
self.assertEqual(down["retry_at"], 4102444800.0)
self.assertEqual(down["scope"], "provider")
r = self.sisi("route", "--kind", "read", "--difficulty", "1", "--explain")
self.assertEqual(r.stdout.splitlines()[0], "other/c", r.stdout)
self.assertIn("zai", r.stdout)
# the provider's allowance comes back: the probe's own mark is cleared and zai is routable again
self.q.windows = [(800, 1000, 4102444800000)]
with mock.patch.object(time, "time", return_value=time.time() + 400):
r = self.sisi("route", "--kind", "read", "--difficulty", "1")
self.assertEqual(r.stdout.splitlines()[0], "zai/b")
self.assertNotIn("zai", workers.read_availability())
def test_a_spent_explicit_worker_falls_back_to_another_automatically(self):
self.q.windows = [(0, 1000, 4102444800000)]
self.define_probe(self.q)
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", "zai/b")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("has no allowance left until its reset; choosing another worker", r.stdout)
self.assertNotIn("worker: zai/", r.stdout)
def test_a_limit_failure_takes_its_reset_time_from_the_probe(self):
self.q.windows = [(50, 1000, 4102444800000)]
self.define_probe(self.q)
self.sisi("workers") # reads 5% left; the reading stays fresh for a few minutes
self.q.windows = [(0, 1000, 4102444800000)] # spent by the time the run fails
with mock.patch.dict(os.environ, {"FAKE_MODE": "quota"}):
self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", "zai/b")
self.assertEqual(self.q.hits.count(SECRET), 2, "once for `workers`, once more when the limit was reported")
self.assertEqual(workers.read_availability()["zai"]["retry_at"], 4102444800.0)
def load_providers_allowance():
return (discovery.load_providers().get("zai") or {}).get("allowance")
class FailurePhrases(ProviderCase):
def setUp(self):
super().setUp()
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "words")
self.fact("zai/a", 3)
self.fact("zai/b", 1)
self.fact("other/c", 2)
def run_a(self, mode, worker="zai/b"):
with mock.patch.dict(os.environ, {"FAKE_MODE": mode}):
return self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", worker)
def test_the_providers_own_code_is_an_auth_problem_not_a_limit_and_only_that_provider_is_down(self):
text = self.run_a("code1113").stdout
self.assertIn("is unavailable (limit", text, "without the provider's phrase the built-in classifier says limit")
workers.write_json(workers.availability_path(), {})
self.assertEqual(self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth").returncode, 0)
r = self.run_a("code1113")
self.assertIn("zai/b is unavailable (auth", r.stdout)
avail = workers.read_availability()
self.assertIn("zai", avail)
self.assertEqual(avail["zai"]["reason"], "auth")
self.assertNotIn("multi", avail, "the tool is not marked down: its other provider still works")
route = self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[0]
self.assertEqual(route, "other/c")
self.assertIn("other/c", self.run_a("", worker="other/c").stdout)
self.assertIn("failure phrase", self.sisi("workers").stdout)
def test_a_phrase_can_name_the_reset_time(self):
reset = time.time() + 7200
iso = time.strftime("%Y-%m-%dT%H:%M:%S+00:00", time.gmtime(reset))
self.sisi("workers", "signature", "zai", "--match", "limit reached", "--class", "limit", "--until-path", "error.resetAt")
self.exe("multi", MULTI.replace("RESETAT", iso))
self.run_a("reset")
got = workers.read_availability()["zai"]
self.assertEqual(got["reason"], "limit")
self.assertAlmostEqual(got["retry_at"], reset, delta=5)
def test_signature_arguments_are_checked_and_listed_and_removed(self):
for args in (("zai", "--match", "ab", "--class", "auth"), ("zai", "--match", "something", "--class", "weird"),
("zai", "--match", "re:(", "--class", "auth"), ("zai", "--match", "something", "--class", "auth", "--until-path", "a..b")):
self.assertEqual(self.sisi("workers", "signature", *args).returncode, 1, args)
self.sisi("workers", "signature", "zai", "--match", "some phrase", "--class", "error")
self.assertIn("'some phrase' is error", self.sisi("workers", "signature").stdout)
self.sisi("workers", "signature", "zai", "--match", "some phrase", "--remove")
self.assertNotIn("some phrase", self.sisi("workers", "signature").stdout)
def test_a_phrase_of_one_provider_never_classifies_another_providers_output(self):
self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth")
self.assertIsNone(discovery.provider_failure({"worker": "other/c"}, "code 1113"))
self.assertIsNone(discovery.provider_failure({"worker": "zai-x/c"}, "code 1113"))
self.assertIsNotNone(discovery.provider_failure({"worker": "zai/c"}, "code 1113"))
def test_the_other_provider_works_beside_one_that_is_out(self):
self.run_a("quota")
self.assertIn("zai", workers.read_availability())
r = self.run_a("quota", worker="other/c")
self.assertEqual(r.returncode, 0, r.stdout)
self.assertIn("worker: other/c", r.stdout)
if __name__ == "__main__":
unittest.main()