From 09376762b0a01f8082f4f8afba37d9c4d285a9ec Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 15:41:17 -0700 Subject: [PATCH 1/4] Items 1-5: workers that appear after install become routable: host listing and delegation learned in the after-tool hook, new PATH tools named once, learned drivers as data with a smoke task and owner approval for approvals-off flags, unproven workers (routine work only, free ones explored one in three), facts line names them. done / next: item 6 live proof, timing, repeat runs Co-Authored-By: Claude Sonnet 5.5 --- canon/discovery.json | 66 +++ canon/orchestration.md | 6 + config.default.json | 10 +- docs/workers.md | 13 +- sisi/cli.py | 5 +- sisi/discovery.py | 999 ++++++++++++++++++++++++++++++++++++++++ sisi/helptext.py | 4 +- sisi/routing.py | 51 +- sisi/tick.py | 8 + sisi/watch.py | 2 + sisi/workers.py | 70 ++- tests/test_discovery.py | 669 +++++++++++++++++++++++++++ 12 files changed, 1869 insertions(+), 34 deletions(-) create mode 100644 canon/discovery.json create mode 100644 sisi/discovery.py create mode 100644 tests/test_discovery.py diff --git a/canon/discovery.json b/canon/discovery.json new file mode 100644 index 0000000..1cb3ea9 --- /dev/null +++ b/canon/discovery.json @@ -0,0 +1,66 @@ +{ + "comment": "Data for sisi/discovery.py: what a host's capability listing and delegation tool look like, which flags switch off approvals, which names are never tools, and which names hint at an agent tool. Names of tools and hosts live here, never in code. Paths are dotted keys into the tool's JSON.", + "hosts": [ + { + "host": "t3-code", + "capability_tool": "^mcp__t3-code__orchestrator_capabilities$", + "delegation_tool": "^mcp__t3-code__delegate_task$", + "capability": { + "providers": "providers", + "provider": "providerInstanceId", + "kind": "driverKind", + "name": "displayName", + "models": "models", + "model": "id", + "label": "label", + "usable": "canRunChildTask", + "constraints": "constraints" + }, + "delegation": { + "tool_name": "delegate_task", + "provider": "target.providerInstanceId", + "model": "target.model" + } + } + ], + "blocking_constraint_words": ["disabled", "unavailable", "not installed", "not authenticated", "not signed in", "unsupported"], + "approval_bypass_patterns": [ + "^--?dangerous", + "^--?yolo$", + "^--?always-approve$", + "^--?auto-approve", + "^--?allow-all", + "^--?skip-permissions", + "^--?no-sandbox", + "^--?bypass", + "^--?full-auto$", + "^--?force$", + "^--?auto$", + "^-y$", + "^--?yes$", + "^--?no-?confirm", + "^--?approval(-mode)?[=:]?(yolo|never|none|off)$", + "^(yolo|never|danger-full-access|bypass)$", + "^--?sandbox[=:]?(off|false|none|disabled|danger-full-access)$" + ], + "not_a_tool": ["sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh", "env", "sudo", "doas", "su", "xargs", + "python", "python3", "perl", "ruby", "node", "deno", "bun", "php", "lua", "awk", "sed", "eval", + "exec", "nohup", "timeout", "time", "watch", "cmd", "powershell", "pwsh"], + "agent_name_hints": ["agent", "code", "coder", "copilot", "pilot", "assist", "ai", "llm", "gpt", "chat", "claw", "gen", "mind", "brain"], + "driver_format_help": { + "name": "short id of the tool, lowercase letters, digits, dot, dash, underscore", + "exe": "the command name as found on PATH (a bare name, no slash); must be the tool itself, never a shell or interpreter", + "run": "argument list that runs ONE task without interaction; first item is exe; exactly one item is the whole token {prompt}; other whole-token placeholders allowed: {model_flag} {effort_flag} {cwd_flag} {cwd}", + "list": "argument list that prints the model names one per line, or null", + "list_kind": "\"lines\"", + "model_flag": "the flag that chooses a model (for {model_flag}), or null", + "effort_flag": "the flag that chooses reasoning effort (for {effort_flag}), or null", + "cwd_flag": "the flag that sets the working folder (for {cwd_flag}), or null", + "plan": "\"free\", \"flat\" (a subscription with an allowance) or \"per-use\"; null when unknown", + "auth_signatures": "lowercase phrases its output contains when it is not logged in (6 to 80 characters each)", + "limit_signatures": "lowercase phrases its output contains when a quota or rate limit is hit", + "tokens_regex": "a regular expression with ONE group that captures the total token count from its output, or null", + "approvals_off_reason": "only when the tool cannot run without a flag that switches off approvals or its sandbox: say why", + "notes": "anything the next reader needs, one short paragraph" + } +} diff --git a/canon/orchestration.md b/canon/orchestration.md index e5e5d75..f5ea973 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -90,6 +90,12 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. worker: find current prices and software-engineering benchmark standing, then record them. Treat a newly appeared model as unproven: low-stakes tasks first, checked one level more carefully, until its record is thick. +- Workers appear after sisi is installed. A new command-line tool is named once at session + start (`sisi workers learn NAME` prints the brief for the cheap worker that learns it); + what the host can reach is learned from its own capability listing and delegation calls. + 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. - 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 diff --git a/config.default.json b/config.default.json index 128649f..9934781 100644 --- a/config.default.json +++ b/config.default.json @@ -17,7 +17,15 @@ "2": 60, "3": 85 }, - "price_blend_input_parts": 3 + "price_blend_input_parts": 3, + "explore_free_one_in": 3 + }, + "discovery": { + "path_refresh_s": 21600, + "path_every_starts": 25, + "drop_after_listings": 3, + "catalogue_over": 8, + "smoke_timeout_s": 120 }, "unit": { "stale_hours": 12 diff --git a/docs/workers.md b/docs/workers.md index 2927c93..4b21d67 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -96,7 +96,7 @@ allows it per tool (`workers.allow_bypass`). In the user store: `workers.json` (discovery cache), `delegations.jsonl` (the ledger), `worker-availability.json`, `worker-prices.json` and `model-strength.json` (worker facts), -`worker-prefs.json` (avoid/prefer) and `worker-notes.json` (standing notes). When facts are missing or older than +`worker-prefs.json` (avoid/prefer), `worker-notes.json` (standing notes) and `worker-drivers.json` (learned drivers). When facts are missing or older than `workers.facts_max_age_days` (default 30), session start prints one line asking for a fast, cheap worker to research current prices and benchmark standing and record them — an age check during normal use, never a scheduler. Settings live under `workers` in the config: @@ -106,4 +106,13 @@ during normal use, never a scheduler. Settings live under `workers` in the confi ## What this does not do Prices and benchmark standing are only as fresh as their recorded source and date. A worker -with no judged record, price or prior is listed but never routed to until evidence exists. +with no judged record, price or prior is listed but never routed to until evidence exists, except a new worker from the section above, which is tried on routine work first. + +## Workers that appear later + +A worker that did not exist when sisi was installed becomes routable through ordinary use. Nothing is scheduled; each way in runs inside a hook or a command already run. The names of a host's tools and the shape of their data are in `canon/discovery.json` (data, never code). + +- **From the host.** The after-tool hook (`sisi watch --after`) recognises the host's capability-listing tool and its delegation tool by the patterns in that file. A listing adds every provider the host says can run a task, each model as the worker `provider/model` exactly as the host names it (a provider the host disables is recorded but never routable). A provider missing from `discovery.drop_after_listings` listings (default 3) is dropped. A delegation seen passing is recorded too. Once per set of new workers the agent gets one line with the count. `sisi route` names the host's delegation tool and the provider and model ids to pass it. A provider listing more than `discovery.catalogue_over` models (default 8) is a catalogue: its models are stored, and only those used, priced or with a standing are candidates. Kept in the scratch folder (`discovery/host-workers.json`); the next listing rebuilds it. +- **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. diff --git a/sisi/cli.py b/sisi/cli.py index d9af30c..409372f 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -291,8 +291,9 @@ def main(argv): from . import cycle return cycle.cmd_cycle(args) if cmd == "approve": - from . import cycle - return cycle.cmd_approve(args) + from . import cycle, discovery + handled = discovery.approve_hook(args) # a learned driver waiting for the owner (ids drv-NAME) + return handled if handled is not None else cycle.cmd_approve(args) if cmd == "oracle": return cmd_oracle() if cmd == "risk": diff --git a/sisi/discovery.py b/sisi/discovery.py new file mode 100644 index 0000000..1a624b6 --- /dev/null +++ b/sisi/discovery.py @@ -0,0 +1,999 @@ +"""A changing environment: workers that appear after sisi was installed become routable through normal use. + +Three ways in, none scheduled (everything runs inside a hook or a command the person already ran): + host the after-tool hook watches for the host's capability listing and its delegation tool (their + names and the shape of their data are in canon/discovery.json) and records each provider and + model the host says can run a task, as the worker `provider/model` reached through the host's + cross-provider delegation. Kept in the scratch folder: the next listing rebuilds it. + PATH session start lists the executables in the user-level folders on PATH (cached; refreshed on a + folder's change, an age or a counter) and names the new ones once. Nothing is executed. + driver `sisi workers learn NAME` hands a cheap worker a brief; the driver it writes (a small JSON file: + the format of workers.DRIVERS as data) is validated, stored in the user store as unverified, + proved by ONE smoke task, and only then usable. A driver with a flag that switches off approvals + waits for the owner (`sisi approve`) and never runs, smoke task included, before that. +A worker that arrives this way is unproven: routine work only (difficulty 1) until it has judged attempts, +checked a level more carefully, and explored more often when it costs nothing extra (see routing.py). +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 + +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} +MAX_NAMED = 5 +SMOKE_PROMPT = ("Reply with exactly this one word and nothing else: %s. " + "Do not read, write, create or run anything.") +PLACEHOLDERS = ("{model_flag}", "{effort_flag}", "{cwd_flag}", "{cwd}") +DRIVER_FIELDS = ("name", "exe", "run", "list", "list_kind", "model_flag", "effort_flag", "cwd_flag", "plan", + "auth_signatures", "limit_signatures", "tokens_regex", "approvals_off_reason", "notes") +USAGE_WORDS = re.compile(r"unknown (flag|option|command)|unrecogni[sz]ed|invalid (option|flag|argument)|" + r"no such (option|flag)|unexpected argument|flag provided but not defined|" + r"usage:|did you mean", re.I) +_NAME = re.compile(r"^[a-z0-9][a-z0-9._-]{0,39}$") +_EXE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$") + +_DATA = [] + + +def data(): + """canon/discovery.json (names of hosts' tools, flag patterns, hints), read once per process.""" + if not _DATA: + try: + with open(paths.canon("discovery.json"), encoding="utf-8") as f: + d = json.load(f) + _DATA.append(d if isinstance(d, dict) else {}) + except (OSError, ValueError): + _DATA.append({}) + return _DATA[0] + + +def cfg(name): + c = store.config().get("discovery") + v = c.get(name) if isinstance(c, dict) else None + d = DEFAULTS[name] + return v if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0 else d + + +# ---------------------------------------------------------------- small files + + +def _state_file(name): + return os.path.join(paths.state(), "discovery", name) + + +def _load(path): + try: + with open(path, encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + +def _save(path, obj): + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = "%s.tmp%d" % (path, os.getpid()) + with open(tmp, "w", encoding="utf-8") as f: + json.dump(obj, f, indent=1, ensure_ascii=False) + f.write("\n") + os.replace(tmp, path) + + +def _day(ts): + try: + return time.strftime("%Y-%m-%d", time.localtime(float(ts))) + except (TypeError, ValueError, OSError): + return "an unknown date" + + +def _plural(n, word): + return "%d %s%s" % (n, word, "" if n == 1 else "s") + + +# ---------------------------------------------------------------- a new command-line tool on PATH + + +def user_path_dirs(path=None): + """The PATH folders that live under the user's own home (system folders are never listed).""" + home = os.path.realpath(paths.home()) + out = [] + for d in (os.environ.get("PATH", "") if path is None else path).split(os.pathsep): + if not d or not os.path.isabs(d): + continue + rp = os.path.realpath(d) + if (rp == home or rp.startswith(home + os.sep)) and os.path.isdir(rp) and rp not in out: + out.append(rp) + return out + + +def list_executables(folder): + """Names of the executable files in one folder. Nothing is run; a file is only looked at.""" + names = [] + try: + with os.scandir(folder) as it: + for e in it: + try: + if not e.name.startswith(".") and e.is_file() and os.access(e.path, os.X_OK): + names.append(e.name) + except OSError: + pass + except OSError: + pass + return names + + +def _marks(dirs): + out = {} + for d in dirs: + try: + out[d] = os.stat(d).st_mtime_ns + except OSError: + out[d] = 0 + return out + + +def _known_tool_names(): + """Names sisi already has a driver for (built in or learned): never announced as new.""" + from . import workers + names = {d["exe"] for d in workers.DRIVERS} + names.update(load_drivers()) + return names + + +def _candidate_names(names, known): + skip = set(data().get("not_a_tool") or ()) | known + return [n for n in names if _EXE_NAME.match(n) and n not in skip] + + +def _hinted(name): + hints = set(data().get("agent_name_hints") or ()) + return bool(hints & set(re.split(r"[-_.]", name.lower()))) + + +def new_tools_line(new): + """One line naming at most five new tools, those whose names look like an agent's first.""" + ordered = sorted(new, key=lambda n: (not _hinted(n), n)) + shown = ordered[:MAX_NAMED] + more = " and %d more" % (len(ordered) - len(shown)) if len(ordered) > len(shown) else "" + return ("sisi: new command-line tool%s on this machine since the last look: %s%s. If one is an AI coding agent, " + "have a fast, cheap worker learn it so it can be routed to: `sisi workers learn NAME` prints the brief " + "for that worker. Ordinary programs can be ignored." % ("" if len(new) == 1 else "s", ", ".join(shown), more)) + + +def session_start(now=None): + """The session-start notice about new executables in the user-level PATH folders, or "". The first + run stores the list and says nothing. The list is looked at again when a folder changed, when it is + older than discovery.path_refresh_s, or after discovery.path_every_starts session starts; otherwise + one stat per folder is all it costs. A name is announced once.""" + now = time.time() if now is None else now + f = _state_file("path.json") + st = _load(f) + dirs = user_path_dirs() + marks = _marks(dirs) + starts = int(st.get("starts") or 0) + 1 + first = not isinstance(st.get("names"), list) + due = (first or st.get("marks") != marks or now - float(st.get("checked") or 0) >= cfg("path_refresh_s") + or starts >= cfg("path_every_starts")) + if not due: + st["starts"] = starts + _save(f, st) + return "" + names = sorted({n for d in dirs for n in list_executables(d)}) + announced = [n for n in st.get("announced") or [] if isinstance(n, str)] + new = [] if first else _candidate_names([n for n in names if n not in set(st["names"]) | set(announced)], + _known_tool_names()) + st.update(names=names, marks=marks, checked=now, starts=0, announced=(announced + new)[-500:]) + _save(f, st) + return new_tools_line(new) if new else "" + + +# ---------------------------------------------------------------- what the host can reach + + +def dig(obj, dotted): + for part in str(dotted or "").split("."): + if not isinstance(obj, dict) or part not in obj: + return None + obj = obj[part] + return obj + + +def _objects(x, depth=0): + """Every JSON object inside a tool result, which a host may wrap as text blocks or a string.""" + if depth > 5: + return + if isinstance(x, str): + s = x.strip() + if s[:1] in "{[": + try: + yield from _objects(json.loads(s), depth + 1) + except ValueError: + pass + elif isinstance(x, dict): + yield x + for k in ("content", "structuredContent", "result", "text", "output"): + if k in x: + yield from _objects(x[k], depth + 1) + elif isinstance(x, list): + for item in x[:20]: + yield from _objects(item, depth + 1) + + +def _clean_id(v, limit=200): + return v if isinstance(v, str) and 0 < len(v) <= limit and v.isprintable() else None + + +def parse_listing(result, spec, blocking=()): + """[{provider, kind, name, usable, reason, models: [{id, label}]}] from a capability listing, by the + host's field names (the data file). A provider is usable only when the host says it can run a task + and states no blocking constraint. Anything malformed is skipped.""" + cap = spec.get("capability") or {} + found = None + for obj in _objects(result): + rows = dig(obj, cap.get("providers")) + if isinstance(rows, list): + found = rows + break + out = [] + for p in (found or [])[:200]: + pid = _clean_id(p.get(cap.get("provider"))) if isinstance(p, dict) else None + if pid is None: + continue + constraints = [c for c in (p.get(cap.get("constraints")) or []) if isinstance(c, str)][:5] + blocked = [c for c in constraints if any(w in c.lower() for w in blocking)] + usable = p.get(cap.get("usable")) is True and not blocked + models = [] + raw = p.get(cap.get("models")) + for m in (raw[:2000] if isinstance(raw, list) else []): + mid = _clean_id(m.get(cap.get("model"))) if isinstance(m, dict) else None + if mid: + label = m.get(cap.get("label")) + models.append({"id": mid, "label": label[:80] if isinstance(label, str) else None}) + out.append({"provider": pid, "kind": _clean_id(p.get(cap.get("kind")), 60), + "name": _clean_id(p.get(cap.get("name")), 80), "usable": usable, + "reason": (blocked or constraints or [None])[0] if not usable else None, "models": models}) + return out + + +def host_state_file(): + return _state_file("host-workers.json") + + +def apply_listing(state, host, parsed, now, drop_after): + """Fold a listing into the stored host workers. Returns how many usable workers are new and worth + trying (a provider with more models than discovery.catalogue_over is a catalogue, not a menu). + A worker missing from `drop_after` listings in a row is forgotten.""" + rec = state.setdefault("hosts", {}).setdefault(host, {"providers": {}}) + provs = rec["providers"] + seen = set() + fresh = 0 + for p in parsed: + entry = provs.setdefault(p["provider"], {"models": {}}) + entry.update(kind=p["kind"], name=p["name"], usable=p["usable"], reason=p["reason"]) + small = len(p["models"]) <= cfg("catalogue_over") + for m in p["models"]: + mrec = entry["models"].get(m["id"]) + if mrec is None: + mrec = entry["models"][m["id"]] = {"first_seen": now, "announced": False, "source": "listing"} + if p["usable"] and small and not mrec.get("announced"): + fresh += 1 + if p["usable"]: + mrec["announced"] = True + mrec.update(label=m["label"], last_seen=now, missed=0) + seen.add((p["provider"], m["id"])) + for pid in list(provs): + for mid in list(provs[pid]["models"]): + if (pid, mid) not in seen: + mrec = provs[pid]["models"][mid] + mrec["missed"] = int(mrec.get("missed") or 0) + 1 + if mrec["missed"] >= drop_after: + del provs[pid]["models"][mid] + if not provs[pid]["models"]: + del provs[pid] + return fresh + + +def apply_delegation(state, host, provider, model, now): + """A delegation seen in use: recorded the same way, already announced (the agent just used it).""" + provs = state.setdefault("hosts", {}).setdefault(host, {"providers": {}})["providers"] + entry = provs.setdefault(provider, {"models": {}, "usable": True}) + mrec = entry["models"].setdefault(model, {"first_seen": now, "source": "delegation", "label": None}) + mrec.update(announced=True, last_seen=now, missed=0, used=now) + return mrec + + +def _match(pattern, tool): + try: + return bool(pattern) and bool(re.search(pattern, tool)) + except re.error: + return False + + +def _tool_input(payload): + for k in ("tool_input", "toolInput", "input"): + if isinstance(payload.get(k), dict): + return payload[k] + return {} + + +def _tool_result(payload): + for k in ("tool_response", "toolResponse", "tool_result", "tool_output", "result", "output"): + if payload.get(k) is not None: + return payload[k] + return None + + +def after_tool(payload): + """The after-tool hook's one call. A listing or delegation tool of a known host updates the stored + host workers; once per set of new workers it prints one line to the agent. Everything else returns + at once. Fails open.""" + try: + if not isinstance(payload, dict): + return + tool = payload.get("tool_name") or payload.get("toolName") or payload.get("tool") + if not isinstance(tool, str) or not tool: + return + hosts = [h for h in data().get("hosts") or [] if isinstance(h, dict)] + listing = next((h for h in hosts if _match(h.get("capability_tool"), tool)), None) + delegation = None if listing else next((h for h in hosts if _match(h.get("delegation_tool"), tool)), None) + if listing is None and delegation is None: + return + f = host_state_file() + state = _load(f) + now = time.time() + line = "" + if listing is not None: + parsed = parse_listing(_tool_result(payload), listing, data().get("blocking_constraint_words") or ()) + if not parsed: + return + fresh = apply_listing(state, listing["host"], parsed, now, int(cfg("drop_after_listings")) or 1) + if fresh: + line = ("sisi: %s reachable through the host's cross-provider delegation (new and unproven: " + "routine work only until judged; `sisi workers` lists them, `sisi route` can choose them)." + % _plural(fresh, "new worker")) + else: + spec = delegation.get("delegation") or {} + inp = _tool_input(payload) + provider, model = _clean_id(dig(inp, spec.get("provider"))), _clean_id(dig(inp, spec.get("model"))) + if not provider or not model: + return + apply_delegation(state, delegation["host"], provider, model, now) + _save(f, state) + if line: + import sys + ev = payload.get("hook_event_name") or "PostToolUse" + sys.stdout.write(json.dumps({"systemMessage": line, "hookSpecificOutput": { + "hookEventName": ev, "additionalContext": line}}) + "\n") + except Exception as e: # a tool call is never held up by this + store.log_error("discovery-after-tool", e) + + +def host_tools(): + """Discovery entries (the shape workers.discover() makes) for the providers the host lists, one per + provider, each model named `provider/model` as the host names it.""" + out = [] + spec = {h.get("host"): h for h in data().get("hosts") or [] if isinstance(h, dict)} + for host, hrec in (_load(host_state_file()).get("hosts") or {}).items(): + d = (spec.get(host) or {}).get("delegation") or {} + for pid, p in sorted((hrec.get("providers") or {}).items()): + if not isinstance(p, dict) or not isinstance(p.get("models"), dict): + continue + usable = p.get("usable") is not False + firsts = [m.get("first_seen") for m in p["models"].values() if isinstance(m, dict) and m.get("first_seen")] + out.append({"name": pid, "installed": True, "usable": usable, + "reason": None if usable else "the host says it cannot run a task (%s)" % (p.get("reason") or "no reason given"), + "models": ["%s/%s" % (pid, m) for m in sorted(p["models"])], "plan": None, + "host": {"host": host, "provider": pid, "tool": d.get("tool_name"), "provider_field": d.get("provider"), + "model_field": d.get("model"), "first_seen": min(firsts) if firsts else None}}) + return out + + +def host_route(tool_entry, worker): + """(provider, model) the host's delegation tool needs for a worker of this provider entry.""" + prov = tool_entry["host"]["provider"] + return prov, worker[len(prov) + 1:] if worker.startswith(prov + "/") else worker + + +def host_mechanism(entry, worker): + h = entry["host"] + prov, model = host_route(entry, worker) + return ("use the host's cross-provider delegation%s: %s=%s and %s=%s" + % (" (its `%s` tool)" % h["tool"] if h.get("tool") else "", h.get("provider_field") or "provider", prov, + h.get("model_field") or "model", model)) + + +# ---------------------------------------------------------------- learned drivers: validation + + +def _bypass_patterns(): + out = [] + for p in data().get("approval_bypass_patterns") or []: + try: + out.append(re.compile(p, re.I)) + except re.error: + pass + return out + + +def bypass_args(argv): + """The arguments of a command that switch off approvals or a sandbox, by the patterns in the data file.""" + pats = _bypass_patterns() + return [a for a in argv if isinstance(a, str) and any(p.search(a) for p in pats)] + + +def _signatures(v, field, problems): + if v is None: + return [] + if not isinstance(v, list) or len(v) > 12 or not all(isinstance(s, str) and 6 <= len(s.strip()) <= 80 for s in v): + problems.append("%s: a list of at most 12 phrases of 6 to 80 characters" % field) + return [] + return [s.strip().lower() for s in v] + + +def _argv(v, field, problems, prompt): + if not isinstance(v, list) or not 1 <= len(v) <= 40 or not all(isinstance(a, str) for a in v): + problems.append("%s: a list of 1 to 40 arguments" % field) + return None + count = 0 + for a in v: + if not a or len(a) > 300 or "\0" in a or "\n" in a: + problems.append("%s: an argument is empty, longer than 300 characters or has a control character" % field) + return None + if a == "{prompt}": + count += 1 + elif a in PLACEHOLDERS: + pass + elif "{" in a or "}" in a: + problems.append("%s: %r mixes text with a placeholder; a placeholder must be a whole argument" % (field, a[:40])) + return None + if prompt and count != 1: + problems.append("%s: exactly one argument must be the whole token {prompt} (found %d)" % (field, count)) + if not prompt and count: + problems.append("%s: must not contain {prompt}" % field) + return list(v) + + +def validate_driver(obj, which, builtin_names=()): + """(driver, problems): a clean driver dict from an agent-written file, or the list of what is wrong. + `which(name)` finds a command on PATH. Only known fields pass; the command is a bare argument list.""" + problems = [] + if not isinstance(obj, dict): + return None, ["the file must hold one JSON object"] + extra = sorted(set(obj) - set(DRIVER_FIELDS)) + if extra: + problems.append("unknown field(s): %s (allowed: %s)" % (", ".join(extra[:6]), ", ".join(DRIVER_FIELDS))) + name, exe = obj.get("name"), obj.get("exe") + if not isinstance(name, str) or not _NAME.match(name): + problems.append("name: lowercase letters, digits, dot, dash or underscore, up to 40 characters") + elif name in builtin_names: + problems.append("name: %r belongs to a driver sisi already has" % name) + if not isinstance(exe, str) or not _EXE_NAME.match(exe): + problems.append("exe: a bare command name, no folder (it must be found on PATH)") + elif exe in (data().get("not_a_tool") or ()): + problems.append("exe: %r is a shell or interpreter, not an agent tool" % exe) + elif not which(exe): + problems.append("exe: %r is not on PATH" % exe) + run = _argv(obj.get("run"), "run", problems, True) + if run is not None and isinstance(exe, str) and run[0] != exe: + problems.append("run: the first argument must be exe (%r)" % exe) + lst = None + if obj.get("list") is not None: + lst = _argv(obj.get("list"), "list", problems, False) + if lst is not None and (lst[0] != exe or any(a in PLACEHOLDERS for a in lst)): + problems.append("list: must start with exe and hold no placeholders") + if obj.get("list_kind") not in (None, "lines"): + problems.append('list_kind: only "lines" (one model name per line)') + flags = {} + for field in ("model_flag", "effort_flag", "cwd_flag"): + v = obj.get(field) + if v is not None and not (isinstance(v, str) and re.match(r"^-[A-Za-z-]{1,40}$", v)): + problems.append("%s: a flag such as --model, or null" % field) + flags[field] = v + plan = obj.get("plan") + if plan not in (None, "free", "flat", "per-use"): + problems.append('plan: "free", "flat", "per-use" or null') + for field in ("approvals_off_reason", "notes"): + v = obj.get(field) + if v is not None and not (isinstance(v, str) and len(v) <= 600): + problems.append("%s: text of at most 600 characters" % field) + rx = obj.get("tokens_regex") + if rx is not None: + try: + if not (isinstance(rx, str) and len(rx) <= 120 and re.compile(rx).groups == 1): + raise ValueError + except (re.error, ValueError): + problems.append("tokens_regex: a regular expression of at most 120 characters with exactly one group") + sig = {"auth_signatures": _signatures(obj.get("auth_signatures"), "auth_signatures", problems), + "limit_signatures": _signatures(obj.get("limit_signatures"), "limit_signatures", problems)} + if problems: + return None, problems + driver = {"name": name, "exe": exe, "run": run, "list": lst, "list_kind": "lines" if lst else None, + "model_flag": flags["model_flag"], "effort_flag": flags["effort_flag"], "cwd_flag": flags["cwd_flag"], + "plan": plan, "tokens_regex": rx, "approvals_off_reason": obj.get("approvals_off_reason"), + "notes": obj.get("notes"), "bypass_args": [], "learned": True} + driver.update(sig) + return driver, [] + + +# ---------------------------------------------------------------- learned drivers: the store + + +def drivers_path(): + return paths.data_file("worker-drivers.json") + + +def load_drivers(): + d = _load(drivers_path()).get("drivers") + return {k: v for k, v in d.items() if isinstance(v, dict) and isinstance(v.get("driver"), dict)} if isinstance(d, dict) else {} + + +def save_drivers(drivers): + _save(drivers_path(), {"drivers": drivers}) + + +def driver_for(name): + """The learned driver NAME may run, or None: only a usable one (verified by its smoke task, and + approved by the owner when it switches off approvals) is ever run.""" + rec = load_drivers().get(name or "") + return rec["driver"] if rec and rec.get("state") == "usable" else None + + +STATE_WORDS = {"usable": None, "waiting-owner": "waiting for the owner: `sisi approve drv-%s`", + "unverified": "learned but not yet proved by its smoke task", "failed": "its smoke task failed"} + + +def learned_tools(which=None): + """Discovery entries for the learned drivers, from the store alone (no tool is run).""" + import shutil + which = which or shutil.which + out = [] + for name, rec in sorted(load_drivers().items()): + d = rec["driver"] + path = which(d.get("exe") or "") + state = rec.get("state") + why = STATE_WORDS.get(state) + why = (why % name if why and "%s" in why else why) + if why and rec.get("reason"): + why = "%s (%s)" % (why, rec["reason"]) + plan = "flat" if d.get("plan") in ("free", "flat") else d.get("plan") + out.append({"name": name, "installed": bool(path), "path": path, "usable": state == "usable" and bool(path), + "reason": why, "models": [m for m in rec.get("models") or [] if isinstance(m, str)], + "learned_by_use": not d.get("list"), "plan": plan, "with_default": True, + "learned": {"by": rec.get("learned_by"), "at": rec.get("learned_at"), "state": state, + "free": d.get("plan") == "free"}}) + return out + + +def merge_tools(tools): + """The discovered tools plus the learned drivers and the host's providers. Built-in tools win a name.""" + have = {t.get("name") for t in tools} + extra = [t for t in learned_tools() + host_tools() if t["name"] not in have] + return list(tools) + extra + + +def tool_lines(t): + """Extra lines for `sisi workers` under one tool: who learned it, or how the host reaches it.""" + 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"])] + 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 [] + + +# ---------------------------------------------------------------- running a learned tool once + + +def _valid_name(name): + return isinstance(name, str) and bool(_NAME.match(name)) + + +def smoke(driver, timeout=None): + """Run ONE tiny read-only task through a driver, in a temporary folder, with a time limit and no + input. Returns {"ok", "kind", "note", "output", "seconds"}; kind is ok, login, quota, error, timeout, + bad-template or no-answer. The command is an argument list: the brief never reaches a shell.""" + import shutil, subprocess, tempfile, uuid + from . import workers + timeout = float(cfg("smoke_timeout_s") if timeout is None else timeout) + nonce = "ok" + uuid.uuid4().hex[:8] + tmp = tempfile.mkdtemp(prefix="sisi-smoke-") + cmd = workers.build_command(driver, {"model": None, "worker": driver["name"] + "/default"}, + SMOKE_PROMPT % nonce, tmp, 1) + started = time.time() + try: + r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, cwd=tmp, stdin=subprocess.DEVNULL, + env=dict(os.environ, SISI_WORKER_RUN="1")) + rc, out, err = r.returncode, r.stdout or "", r.stderr or "" + except subprocess.TimeoutExpired as e: + txt = lambda v: v.decode("utf-8", "replace") if isinstance(v, bytes) else (v or "") + return {"ok": False, "kind": "timeout", "output": (txt(e.stdout) + txt(e.stderr))[-600:], "seconds": timeout, + "note": "did not finish within %gs; it may be waiting for a question it cannot be asked " + "(a login, an approval)" % timeout} + except OSError as e: + return {"ok": False, "kind": "error", "output": "", "seconds": 0.0, "note": "could not start it: %s" % e} + finally: + shutil.rmtree(tmp, ignore_errors=True) + text = out + "\n" + err + res = {"output": " ".join(text.split())[:600], "seconds": round(time.time() - started, 1)} + fail = workers.classify_failure(text, rc, extra_signatures(driver)) + if fail is not None: + kind = {"auth": "login", "limit": "quota"}.get(fail[0], "error") + return dict(res, ok=False, kind=kind, note=fail[1]) + if rc != 0: + bad = bool(USAGE_WORDS.search(text)) + return dict(res, ok=False, kind="bad-template" if bad else "error", + note=("it rejected the command line" if bad else "it exited with status %s" % rc)) + if nonce not in text: + return dict(res, ok=False, kind="no-answer", note="it ran but did not answer the smoke prompt " + "(the template may not run a task without interaction)") + return dict(res, ok=True, kind="ok", note="answered the smoke prompt") + + +def extra_signatures(driver): + """The failure phrases a learned driver adds ({} for a built-in one).""" + d = driver or {} + return {"auth": d.get("auth_signatures") or [], "limit": d.get("limit_signatures") or []} + + +def tokens_from(driver, text): + """Total tokens a learned tool prints, by the driver's own regular expression, else None.""" + rx = (driver or {}).get("tokens_regex") + if not rx: + return None + try: + m = re.search(rx, (text or "")[-200000:]) + return int(m.group(1).replace(",", "")) if m else None + except (re.error, ValueError, IndexError): + return None + + +def held_note(cand): + """For a candidate whose learned driver may not run yet: why not (never run, never marked missing).""" + rec = load_drivers().get(cand.get("tool") or "") + if rec is None or rec.get("state") == "usable": + return None + return "%s is held: its learned driver is not usable yet (%s); trying the next choice" % ( + cand["worker"], rec.get("reason") or STATE_WORDS.get(rec.get("state")) or rec.get("state")) + + +def models_of(driver, timeout=30): + """The model names a learned tool lists (its own list command, run once), or [].""" + import subprocess + from . import workers + if not driver.get("list"): + return [] + try: + r = subprocess.run(driver["list"], capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError): + return [] + if r.returncode != 0: + return [] + return workers._parse_models({"list_kind": "lines"}, r.stdout or "")[:500] + + +def prove(name, drivers, now=None): + """Run the smoke task for a stored driver and record what happened. Returns the smoke result.""" + from . import workers + rec = drivers[name] + res = smoke(rec["driver"]) + now = time.time() if now is None else now + rec["smoke"] = {"at": now, "kind": res["kind"], "note": res["note"], "output": res["output"]} + if res["ok"]: + rec.update(state="usable", reason=None, verified_at=now, models=models_of(rec["driver"])) + workers.clear_down(name) + elif res["kind"] in ("login", "quota", "error"): + rec.update(state="unverified", reason="%s: %s" % (res["kind"], res["note"])) + else: + rec.update(state="failed", reason="%s: %s" % (res["kind"], res["note"])) + save_drivers(drivers) + return res + + +def describe_driver(name, rec): + d = rec["driver"] + lines = ["%s: waiting for the owner" % ("drv-" + name), + " the tool %s was learned by %s on %s; it runs the brief of every task through this command" + % (name, rec.get("learned_by") or "an unknown worker", _day(rec.get("learned_at"))), + " COMMAND (an argument list, run without a shell; {prompt} is the task's brief): %s" % " ".join(d["run"]), + " switches off approvals or a sandbox: %s" % " ".join(rec.get("bypass") or []), + " the worker's reason: %s" % (d.get("approvals_off_reason") or "none stated"), + " until approved it never runs, its one smoke task included"] + return lines + + +def record(name, path, by=None, now=None): + """`sisi workers learn NAME --record FILE`: validate, store as unverified, and prove it with one smoke + task, unless it switches off approvals, in which case it waits for the owner. Returns (exit code, lines).""" + import shutil + from . import workers + now = time.time() if now is None else now + try: + if os.path.getsize(path) > 20000: + return 1, ["sisi workers learn: the driver file is larger than 20000 bytes"] + with open(path, encoding="utf-8") as f: + obj = json.load(f) + except (OSError, ValueError) as e: + return 1, ["sisi workers learn: cannot read %s as JSON: %s" % (path, e)] + driver, problems = validate_driver(obj, shutil.which, {d["name"] for d in workers.DRIVERS} | {d["exe"] for d in workers.DRIVERS}) + if driver is None: + return 1, ["sisi workers learn: the driver file is not valid:"] + [" - " + p for p in problems] + if driver["name"] != name or driver["exe"] != name: + return 1, ["sisi workers learn: the file's name and exe must both be %r, the tool the brief was written for" % name] + drivers = load_drivers() + flags = bypass_args(driver["run"] + (driver["list"] or [])) + rec = {"driver": driver, "state": "unverified", "reason": None, "learned_by": by or store.tool() or "an unknown worker", + "learned_at": now, "bypass": flags, "models": []} + drivers[name] = rec + if flags: + rec.update(state="waiting-owner", reason="it switches off approvals or a sandbox (%s)" % " ".join(flags)) + save_drivers(drivers) + return 0, ["driver %s stored, WAITING FOR THE OWNER: its command has %s." % (name, " ".join(flags))] + \ + describe_driver(name, rec) + ["The owner decides, in a terminal: sisi approve drv-%s --yes | --no" % name] + save_drivers(drivers) + res = prove(name, drivers, now) + lines = ["driver %s stored; smoke task: %s" % (name, "PASSED, the driver is usable" if res["ok"] else + "FAILED (%s): %s" % (res["kind"], res["note"]))] + if res["output"]: + lines.append("the tool printed: %s" % res["output"]) + if not res["ok"]: + lines.append("the driver stays unusable (%s). Fix the file and run `sisi workers learn %s --record FILE` again%s." + % (drivers[name]["reason"], name, ", or log the tool in and run `sisi workers learn %s --verify`" % name + if res["kind"] in ("login", "quota") else "")) + return (0 if res["ok"] else 1), lines + + +def verify(name): + drivers = load_drivers() + rec = drivers.get(name) + if rec is None: + return 1, ["sisi workers learn: no stored driver %r (see `sisi workers`)" % name] + if rec.get("state") == "waiting-owner": + return 1, ["sisi workers learn: %s waits for the owner (`sisi approve drv-%s`); it is not run before" % (name, name)] + res = prove(name, drivers) + return (0 if res["ok"] else 1), ["smoke task for %s: %s" % (name, "PASSED, usable" if res["ok"] else + "FAILED (%s): %s" % (res["kind"], res["note"]))] + + +def forget(name): + """`sisi workers forget NAME`: remove a learned driver, or a provider the host listed.""" + drivers = load_drivers() + if name in drivers: + del drivers[name] + save_drivers(drivers) + return 0, ["forgot the learned driver %s" % name] + f = host_state_file() + state = _load(f) + hit = [h for h, r in (state.get("hosts") or {}).items() if name in (r.get("providers") or {})] + for h in hit: + del state["hosts"][h]["providers"][name] + if hit: + _save(f, state) + return 0, ["forgot the host provider %s (it returns when the host lists it again)" % name] + return 1, ["sisi workers forget: %r is neither a learned tool nor a host provider" % name] + + +# ---------------------------------------------------------------- the owner's approval of a waiting driver + + +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.""" + import sys + from . import cycle, learning + waiting = waiting_drivers() + if not args: + if not waiting: + return None + for n, r in sorted(waiting.items()): + print("\n".join(describe_driver(n, r))) + print() + if learning.load_pending(): + return None + print("The owner decides, in a terminal: sisi approve drv-NAME --yes | --no") + return 0 + if not args[0].startswith("drv-"): + return None + name = args[0][4:] + yes = "--yes" in args + if name not in waiting: + print("sisi approve: no driver %r waits for a decision" % name, file=sys.stderr) + return 2 + if not yes and "--no" not in args: + print("usage: sisi approve drv-NAME --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) + return 2 + if not yes: + forget(name) + print("drv-%s refused; the driver was removed" % name) + return 0 + drivers = load_drivers() + drivers[name]["state"] = "unverified" + drivers[name]["approved_at"] = time.time() + save_drivers(drivers) + res = prove(name, drivers) + print("drv-%s approved. Smoke task: %s" % (name, "PASSED, the driver is usable" if res["ok"] else + "FAILED (%s): %s" % (res["kind"], res["note"]))) + return 0 if res["ok"] else 1 + + +# ---------------------------------------------------------------- the brief for a cheap worker + + +def learn_brief(name, exe_path): + help_ = data().get("driver_format_help") or {} + fields = "\n".join(" %s: %s" % (k, help_[k]) for k in DRIVER_FIELDS if k in help_) + return "\n".join([ + "You are a worker. Do this task yourself; do not delegate it further.", + "", + "## Outcome and scope", + "Teach sisi to run the command-line AI tool `%s` (at %s) as a worker: write ONE small JSON file, a driver, " + "that says how to run a single task through it without interaction. Out of scope: running real tasks, " + "logging in, changing the tool's settings, installing anything." % (name, exe_path), + "", + "## Context and sources of truth", + "The tool's own help output is the only source. Run `%s --help` and `%s help SUBCOMMAND` for what it shows. " + "Find: how to run one task without interaction (a print or exec mode, the prompt as an argument); how to choose a " + "model; how to list models (only if help shows a list command); how to set the working folder; where it reports " + "token usage; what its login, quota and rate-limit errors say (quote the phrases help shows; do not provoke them); " + "whether it is free, a flat subscription or billed per use. Driver fields:\n%s" % (name, name, fields), + "", + "## Constraints and interfaces", + "Run only commands that print help, a version or a list. Never start a task, log in or log out, or change a setting.", + "The command is run without a shell, as an argument list; the whole token {prompt} is where the brief goes.", + "Never include a flag that switches off approvals or a sandbox unless the tool cannot run without one; then say " + "why in approvals_off_reason. Such a driver waits for the owner and is not run before they approve it.", + "If the tool cannot run a task without interaction, or needs a login that is not done, write no file and " + "report exactly what it printed.", + "", + "## Acceptance", + "`sisi workers learn %s --check FILE` prints `valid`. Every field you set is traced in your report to a line " + "of the tool's help (quote it); a field you could not trace is null." % name, + "", + "## Deliverables and report format", + "The driver file (JSON) at FILE in the folder you were given, and a short report: each field with the help line " + "behind it, what you could not find, and the output of the record command below.", + "", + "## Files you may change", + "Only the one driver file, FILE. Everything else is read-only.", + "", + "## Verification", + "Run `sisi workers learn %s --record FILE`. It validates the file, stores it, and runs one tiny read-only smoke task " + "through the tool (a temporary folder, a time limit). Paste its output in your report. If it says the driver is " + "unusable, say why and do not retry more than once." % name, + "", + "## Budget and escalation", + "About ten help commands and fifteen minutes. Stop and report instead of guessing when help does not answer a field.", + ""]) + + +USAGE = ("usage: sisi workers learn NAME print the brief for a cheap worker that learns the tool\n" + " sisi workers learn NAME --check FILE validate a driver file, change nothing\n" + " sisi workers learn NAME --record FILE [--by TEXT] validate, store, run one smoke task\n" + " sisi workers learn NAME --verify run the smoke task again for a stored driver\n" + " sisi workers forget NAME remove a learned driver or a host provider") + + +def _opt(args, name): + return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else None + + +def cmd_learn(args): + import shutil + from . import workers + args = list(args) + name = args[0] if args and not args[0].startswith("-") else None + if not _valid_name(name): + print(USAGE) + return 1 + if "--record" in args or "--check" in args: + path = _opt(args, "--record") or _opt(args, "--check") + if not path: + print(USAGE) + return 1 + if "--check" in args: + try: + with open(path, encoding="utf-8") as f: + obj = json.load(f) + except (OSError, ValueError) as e: + print("sisi workers learn: cannot read %s as JSON: %s" % (path, e)) + return 1 + driver, problems = validate_driver(obj, shutil.which, {d["name"] for d in workers.DRIVERS}) + if driver is None or driver["name"] != name: + print("\n".join(["not valid:"] + [" - " + p for p in (problems or ["the file's name is not %r" % name])])) + return 1 + flags = bypass_args(driver["run"] + (driver["list"] or [])) + print("valid" + (" (it switches off approvals or a sandbox with %s: it will wait for the owner)" % " ".join(flags) + if flags else "")) + return 0 + code, lines = record(name, path, by=_opt(args, "--by")) + elif "--verify" in args: + code, lines = verify(name) + else: + exe = shutil.which(name) + if not exe: + print("sisi workers learn: %r is not on PATH" % name) + return 1 + print(learn_brief(name, exe)) + return 0 + print("\n".join(lines)) + return code + + +def cmd_forget(args): + if not args or not _valid_name(args[0]): + print(USAGE) + return 1 + code, lines = forget(args[0]) + print("\n".join(lines)) + return code + + +# ---------------------------------------------------------------- routing: new workers are unproven + + +def judged_counts(records): + """{worker id, lower case: judged attempts} from the delegation record.""" + out = {} + for r in records: + if r.get("kind") == "attempt" and r.get("worker"): + k = str(r["worker"]).lower() + out[k] = out.get(k, 0) + 1 + return out + + +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.""" + marked = {t["name"]: t for t in tools if t.get("learned") or t.get("host")} + if not marked: + return cands + from . import routing + counts = judged_counts(records) + cap = cfg("catalogue_over") + for c in cands: + 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" + if c.get("model") is None or len(t.get("models") or []) <= cap: + c["unproven_ok"] = True + if t.get("host"): + c["host_native"] = True + c["host_mechanism"] = host_mechanism(t, c["worker"]) + return cands + + +def facts_targets(cands): + """The worker ids to research: candidates to try that have no price and no standing yet.""" + return [c["worker"] for c in cands if c.get("unproven_ok") and not c.get("price_source") and c.get("standing") is None] + + +def facts_phrase(targets): + shown = targets[:MAX_NAMED] + return "the new workers %s%s" % (", ".join(shown), " and %d more" % (len(targets) - len(shown)) if len(targets) > len(shown) else "") + + +UNPROVEN_LINE = ("unproven: check this result with at least the tests or a read of the diff " + "(a new worker with no judged record; routine work only until it has one)") + + +def unproven_lines(cand): + return [UNPROVEN_LINE] if cand and cand.get("unproven") else [] diff --git a/sisi/helptext.py b/sisi/helptext.py index aeb8073..35585a9 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -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 "" 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 "" 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)', + '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', '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', @@ -65,7 +65,7 @@ GROUPS = ( (("learn",), "learn [--scope S] TEXT | --withdraw ID", "record what the owner said; take a mistaken one back"), (("route",), "route --kind K --difficulty N [--explain]", "the most affordable usable worker for a task"), (("delegate",), "delegate brief|check|guide|judge|amend", "write, check, run and judge a brief for a worker"), - (("workers",), "workers [fact|avoid|prefer|only|note|down|up]", "workers found here, what each costs, the judged record"), + (("workers",), "workers [fact|...|down|up|learn|forget]", "workers found here, what each costs, the judged record"), (("verifiers",), "verifiers show|for|doctor|lint|WORDS", "ways to know work is correct"), (("done",), "done [ID|for \"\"]", "the recipe saying what makes a kind of work done"), (("rule",), "rule [N|ID]", "the rules and how each is enforced"), diff --git a/sisi/routing.py b/sisi/routing.py index 354dc6d..f3d51c4 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -60,6 +60,7 @@ CONTRADICTION_REJECTIONS = 2 # a thin record with this many rejections below th UNKNOWN_ALLOWANCE = 50.0 # allowance weight when a tool reports none STRONG_BAND = 10.0 # standing points from the best still counts as among the strongest EXPLORE_EVERY = 10 # about one low-stakes task in ten tries a cheaper thin-record worker +EXPLORE_FREE_EVERY = 3 # an unproven worker that costs nothing extra gets one routine task in three DEFAULT_STANDING_FLOOR = {1: 0.0, 2: 60.0, 3: 85.0} # percent of the best usable standing needed DEFAULT_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price @@ -313,8 +314,10 @@ def _standing_of(c): # ---------------------------------------------------------------- the pool, then the choice -def _prepare(candidates, records, availability, now, exclude, avoid, review_of): - """The workers that may be recommended at all: (eligible, passed, stats, author_maker).""" +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 + offered routine work only: above difficulty 1 it is passed over whatever benchmark it has.""" exclude = {str(x) for x in exclude} stats = candidate_stats(candidates, records) passed = [] @@ -328,6 +331,9 @@ 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: + 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) if down is not None: passed.append((w, "unavailable (%s) until its retry time" % (down.get("reason") or "down"))) @@ -439,13 +445,29 @@ def _select(eligible, assessments, difficulty): return pool, ("nothing" if top[0] <= 1 else "strongest") +def _free_slot(choice, ranked, candidates, stats, kind, difficulty, basis, prefer, every): + """The unproven worker that costs nothing extra (a flat or free plan) to try on this routine task + instead of the usual choice, or None. One routine task in `every` (route.explore_free_one_in), a + function of the judged record like the paid slot below, so the choice stays deterministic.""" + if choice is None or difficulty != 1 or basis != "capable" or not every or every < 1: + return None + if choice.get("unproven") or _pattern_match(choice, prefer): + return None + free = [c for c in ranked if c is not choice and c.get("unproven") and c.get("plan") == "flat"] + total = sum(_cell(stats, c["worker"], kind, difficulty)["n"] for c in candidates) + if not free or total % every != every - 1: + return None + return sorted(free, key=lambda c: (_cell(stats, c["worker"], kind, difficulty)["n"], c["worker"]))[0] + + def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(), - avoid=None, prefer=None, floors=None): + avoid=None, prefer=None, floors=None, explore_free_every=EXPLORE_FREE_EVERY): """Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker", ...}. `passed_over` is [(worker, plain reason)] covering every candidate not chosen. `avoid` and `prefer` are the user's own [{"pattern", "why"}] constraints; `floors` the standing floors.""" now = float(now or 0) - eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of) + eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of, + difficulty) assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer) @@ -460,7 +482,11 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, ranked = sorted(pool, key=lambda c: (-(assessments[c["worker"]].get("measure") or 0.0), key(c))) choice = ranked[0] if ranked else None explored = None - if (choice is not None and difficulty == 1 and basis == "capable" and not _pattern_match(choice, prefer) + free_slot = _free_slot(choice, ranked, candidates, stats, kind, difficulty, basis, prefer, explore_free_every) + if free_slot is not None: + explored, choice = choice, free_slot + ranked = [choice] + [c for c in ranked if c is not choice] + elif (choice is not None and difficulty == 1 and basis == "capable" and not _pattern_match(choice, prefer) and _cell(stats, choice["worker"], kind, difficulty)["n"] >= MIN_ATTEMPTS): total = sum(_cell(stats, c["worker"], kind, difficulty)["n"] for c in candidates) if total >= EXPLORE_EVERY - 1 and total % EXPLORE_EVERY == EXPLORE_EVERY - 1: @@ -488,7 +514,10 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, detail[w] = extra continue if explored is not None and c is explored: - reason = ("the usual choice, passed over this once so a cheaper thin-record worker " + reason = ("the usual choice, passed over this once so an unproven worker that costs nothing extra " + "gathers evidence on routine work (about one task in %d)" % explore_free_every + if free_slot is not None else + "the usual choice, passed over this once so a cheaper thin-record worker " "gathers evidence on low-stakes work (about one task in %d)" % EXPLORE_EVERY) elif _pattern_match(choice, prefer) and not _pattern_match(c, prefer): _pat, _why = _pattern_match(choice, prefer) @@ -507,7 +536,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1] capable_n = len(pool) if basis == "capable" else 0 return {"choice": choice, "passed_over": passed, "stats": stats, "author_maker": author_maker, - "explored": explored["worker"] if explored else None, + "explored": explored["worker"] if explored else None, "explored_free": free_slot is not None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}, "assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first, "best_standing": best, "passed_detail": detail, "floors": floors, @@ -561,7 +590,8 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, else is usable). Returns {"choice", "step", "assessments", ...}; step is "same", "better", "strongest" or "only", and choice is None when nobody is usable. Pure; the caller supplies facts.""" now = float(now or 0) - eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of) + eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of, + difficulty) assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) key, _rate, _load = _make_key(stats, kind, difficulty, prefer) out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker, @@ -676,8 +706,9 @@ def explain_choice(result, kind, difficulty): if a is not None: lines.append(evidence_line(a, kind, difficulty, choice, basis)) if result.get("explored"): - lines.append("this is an exploration pick: %s was the usual choice, passed over once so a cheaper " - "thin-record worker gathers evidence" % result["explored"]) + lines.append("this is an exploration pick: %s was the usual choice, passed over once so %s gathers evidence" + % (result["explored"], "an unproven worker that costs nothing extra" + if result.get("explored_free") else "a cheaper thin-record worker")) if result.get("author_maker"): choice_maker = choice.get("maker") or maker_of(choice.get("model") or choice["worker"]) if choice_maker != result["author_maker"]: diff --git a/sisi/tick.py b/sisi/tick.py index 7c8dc36..a2a0c4a 100644 --- a/sisi/tick.py +++ b/sisi/tick.py @@ -101,6 +101,14 @@ def main(args=()): store.save_session(sid, sess) except Exception as e: store.log_error("tick-workers", e) + try: + from . import discovery, workers as _W2 + if not _W2.is_subagent_payload(payload): + note = discovery.session_start() # new executables on PATH, once per set (the first run only stores them) + if note: + sys.stdout.write(note + "\n") + except Exception as e: + store.log_error("tick-discovery", e) try: from . import cycle # cycle.due_notice carries both the due-cycle line and the pending-decision line (learning.pending_notice). diff --git a/sisi/watch.py b/sisi/watch.py index 865b0e0..6b6f956 100644 --- a/sisi/watch.py +++ b/sisi/watch.py @@ -233,6 +233,8 @@ def main(args=()): store.log_error("watch-commit-notice", e) elif "--after" in args or ev in AFTER_EVENTS: after(payload) + from . import discovery + discovery.after_tool(payload) # the host's capability listing and delegation tool: what it can reach from . import unitguard unitguard.after(payload) except Exception as e: # fail open: a tool call must never be held up by measurement diff --git a/sisi/workers.py b/sisi/workers.py index 41cbc13..64e0f75 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -33,6 +33,7 @@ researched when they are missing or old. No price, score or model name ships in import datetime, json, os, re, shutil, statistics, subprocess, sys, time, uuid from . import brief as brief_contract +from . import discovery as _D from . import paths, routing, store LIST_TIMEOUT_S = 30 @@ -121,18 +122,20 @@ ERROR_SIGNATURES = ( ) -def classify_failure(text, returncode=0): +def classify_failure(text, returncode=0, extra=None): """(reason, note, retry_after_s) for a run or listing that never got to do the work, else None. - reason is one of auth, limit, missing, error. Text decides even when the exit status is 0.""" + reason is one of auth, limit, missing, error. Text decides even when the exit status is 0. + `extra` is {"auth": [...], "limit": [...]}: phrases a learned driver adds to the built-in ones.""" low = (text or "").lower() retry = None m = re.search(r"retryafterms\D{0,4}(\d+)", low) if m: retry = int(m.group(1)) / 1000.0 - for sig in AUTH_SIGNATURES: + extra = extra or {} + for sig in AUTH_SIGNATURES + tuple(extra.get("auth") or ()): if sig in low: return "auth", "not logged in (%s)" % _phrase(text, sig), retry - for sig in LIMIT_SIGNATURES: + for sig in LIMIT_SIGNATURES + tuple(extra.get("limit") or ()): if sig in low: return "limit", _phrase(text, sig), retry for sig in ERROR_SIGNATURES: @@ -573,6 +576,12 @@ def route_floors(): return routing.standing_floors(route_cfg().get("standing_floor")) +def explore_free_every(): + """`route.explore_free_one_in`: an unproven worker that costs nothing extra gets one routine task in this many.""" + v = route_cfg().get("explore_free_one_in") + return int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 1 else routing.EXPLORE_FREE_EVERY + + def _price_for(prices, tool, model, worker): models = prices.get("models") if isinstance(prices.get("models"), dict) else {} tools = prices.get("tools") if isinstance(prices.get("tools"), dict) else {} @@ -615,7 +624,7 @@ def build_candidates(disc=None, records=None): records = read_records() if records is None else records prices = load_prices() prior = load_strength_prior() - disc_tools = disc.get("tools") or [] + disc_tools = _D.merge_tools(disc.get("tools") or []) cands, seen = [], set() def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None): @@ -646,6 +655,8 @@ def build_candidates(disc=None, records=None): if not t.get("installed", True): continue models = t.get("models") or [] + if t.get("with_default"): + models = [None] + list(models) # a learned tool's own default model is always a worker if models: for m in models: add(t["name"], m, usable=bool(t.get("usable", True)), reason=t.get("reason"), @@ -676,7 +687,7 @@ def build_candidates(disc=None, records=None): if c is not None: c["aliases"].append(str(w)) alias_set.add(str(w).lower()) - return cands + return _D.annotate(cands, records, disc_tools) def resolve_worker(name, candidates): @@ -686,10 +697,11 @@ def resolve_worker(name, candidates): return c if "/" in str(name or ""): tool, model = str(name).split("/", 1) - if tool in DRIVER_BY_NAME: + driver = DRIVER_BY_NAME.get(tool) or _D.driver_for(tool) + if driver is not None: return {"worker": str(name), "tool": tool, "model": model, "maker": routing.maker_of(model), "plan": None, "cost": None, - "allowance_pct_left": None, "usable": shutil.which(DRIVER_BY_NAME[tool]["exe"]) is not None, + "allowance_pct_left": None, "usable": shutil.which(driver["exe"]) is not None, "reason": None, "aliases": [str(name), model]} return None @@ -777,7 +789,7 @@ 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") + "model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-drivers.json") def _data_state(): @@ -858,9 +870,12 @@ def facts_status(now=None): def facts_line(now=None): """One session-start line asking for worker facts to be researched, or "" when they are fresh.""" status = facts_status(now) - if status["state"] == "ok": + targets = _D.facts_targets(_cached_candidates()[0]) + if status["state"] == "ok" and not targets: return "" - if status["state"] == "missing": + if targets: + what = "worker facts are missing for %s" % _D.facts_phrase(targets) + elif status["state"] == "missing": what = "worker facts are missing (no prices or benchmark standing recorded yet)" else: what = "worker facts are stale (newest from %s)" % (status["newest"] or "an unstated date") @@ -891,7 +906,7 @@ def routable_candidates(candidates, records): keep = [] for c in candidates: judged = sum(cell["n"] for cell in stats.get(c["worker"], {}).get("by_cell", {}).values()) - if judged or c.get("price_source") or c.get("standing") is not None: + if judged or c.get("price_source") or c.get("standing") is not None or c.get("unproven_ok"): keep.append(c) if not keep: return list(candidates), True, 0 @@ -914,6 +929,8 @@ def mechanism_for(cand, host=None): """How to start the chosen worker: the host's own subagents first, its cross-provider delegation when the config says it has one (workers.host_cross_provider), else sisi itself.""" host = host_tool() if host is None else host + if cand.get("host_mechanism"): + return cand["host_mechanism"] if cand.get("host_native"): return "use the host's own subagent tool with model %s" % (cand.get("model") or cand["worker"]) if host and cand.get("tool") == host: @@ -1170,7 +1187,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev prefs = effective_prefs(kind, difficulty, cwd) result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, review_of=review_of, now=time.time(), exclude=tried, - avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) + avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), + explore_free_every=explore_free_every()) cand = result["choice"] if cand is None: notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) @@ -1180,7 +1198,12 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev notes.append("sisi: refusing %s: its id contains 'contributor', a tier that trains on prompts" % cand["worker"]) return None, None, notes - driver = DRIVER_BY_NAME.get(cand.get("tool") or "") + driver = DRIVER_BY_NAME.get(cand.get("tool") or "") or _D.driver_for(cand.get("tool")) + held = _D.held_note(cand) if driver is None else None + if held: # a learned driver not yet proved or approved: not a missing tool, and never run + notes.append(held) + cand = None + continue if driver is None or shutil.which(driver["exe"]) is None: record_down(_down_keys(cand, "missing"), "missing", "no command-line tool found for %s" % cand["worker"]) @@ -1205,7 +1228,7 @@ 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) + failure = 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) @@ -1214,6 +1237,7 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev cand = None continue tokens, cost = extract_usage(out + "\n" + err) + tokens = _D.tokens_from(driver, out + "\n" + err) if tokens is None else tokens cost_class = "measured" if cost is not None else "unavailable" if cost is None: estimated = estimate_cost(tokens, _price_for(load_prices(), cand.get("tool"), @@ -1392,8 +1416,13 @@ def cmd_workers(args=()): return _cmd_up(args[1:]) if args[:1] == ["import"]: return _cmd_import(args[1:]) + if args[:1] == ["learn"]: + return _D.cmd_learn(args[1:]) + if args[:1] == ["forget"]: + return _D.cmd_forget(args[1:]) migrate_standing_facts() disc = discover(force="--refresh" in args) + disc = dict(disc, tools=_D.merge_tools(disc.get("tools") or [])) records = read_records() avail = read_availability() prices = load_prices() @@ -1413,6 +1442,8 @@ def cmd_workers(args=()): else: state = "usable now" print("%s - %s" % (t["name"], state)) + for line in _D.tool_lines(t): + print(line) models = t.get("models") or [] if models: shown = models if len(models) <= 24 else models[:24] + ["... and %d more" % (len(models) - 24)] @@ -1516,7 +1547,8 @@ def cmd_route(args=()): candidates, limited = apply_limits(candidates, prefs) result = routing.choose(candidates, records, read_availability(), kind, difficulty, review_of=_opt(args, "--review-of"), now=time.time(), - avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) + avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), + explore_free_every=explore_free_every()) result["passed_over"] = list(result["passed_over"]) + limited by_worker = {c["worker"]: c for c in everyone} down = _down_now(read_availability(), time.time()) @@ -1533,9 +1565,11 @@ def cmd_route(args=()): return 1 print(result["choice"]["worker"]) print("mechanism: %s" % mechanism_for(result["choice"])) + for line in _D.unproven_lines(result["choice"]): + print(line) for line in _down_lines(down): print(line) - head = 2 + len(_down_lines(down)) + head = 2 + len(_D.unproven_lines(result["choice"])) + len(_down_lines(down)) explain = "--explain" in args # Notes for the chosen worker always print; notes for workers passed over only with --explain. # Plain output stays within 6 lines: the worker, the mechanism, what is down, then the notes. @@ -1625,6 +1659,8 @@ def cmd_delegate(args=()): return 1 if final: print(final) + for line in _D.unproven_lines(next((c for c in candidates if c["worker"] == rec["worker"]), None)): + print(line) print("worker: %s" % rec["worker"]) print("transcript: %s" % rec["transcript"]) print("record your judgement: sisi delegate judge %s --outcome accepted|rejected " diff --git a/tests/test_discovery.py b/tests/test_discovery.py new file mode 100644 index 0000000..d962201 --- /dev/null +++ b/tests/test_discovery.py @@ -0,0 +1,669 @@ +"""A changing environment: workers installed or reachable after sisi was installed are found and used. + +Requirements: R-7.2-1 and R-7.2-2 (least expensive sufficiently capable worker, from the record), R-7.2-3 (the routing +policy is empirical and revisable: an unproven worker earns difficulty by its judged record), R-12-1 (what was learned +is persisted so it is not rediscovered), R-16-3 and R-16-7 (a driver file is untrusted input: validated, least +privilege), R-16-4 (the brief never reaches a shell), R-16-6 (a tool's output is data), R-16-8 (consequential changes +are recorded), R-16-11 (a learned driver cannot widen permissions: approvals-off waits for the owner).""" +import json, os, stat, sys, time, unittest +from unittest import mock + +from support import * +from sisi import brief as brief_contract, discovery, routing, workers + +FAKE_AGENT = """#!/bin/sh +# a fake agent tool: `models` lists, anything else runs one task and echoes the prompt it was given +if [ "$1" = "models" ]; then echo "fa-1"; echo "fa-2"; exit 0; fi +if [ -n "$FAKE_MARK" ]; then echo ran >> "$FAKE_MARK"; fi +n=0; last="" +for a in "$@"; do n=$((n+1)); last="$a"; done +if [ -n "$FAKE_ARGS" ]; then echo "$n" > "$FAKE_ARGS"; fi +case "$FAKE_MODE" in + login) echo "Error: you are not authenticated. Run 'fa login'" >&2; exit 1 ;; + quota) echo "weekly allowance used up for this plan" ; exit 0 ;; + flag) echo "error: unknown flag --print-all" >&2; exit 2 ;; + hang) while true; do :; done ;; + silent) echo "hello"; exit 0 ;; +esac +echo "$last" +echo "total tokens: 321" +exit 0 +""" + +BRIEF = ("You are a worker.\n\n## Outcome and scope\nDo the toy task.\n\n## Context and sources of truth\nThis brief.\n\n" + "## Constraints and interfaces\nNone.\n\n## Acceptance\nThe final report says done.\n\n" + "## Deliverables and report format\nA short report.\n\n## Files you may change\ntoy.txt only.\n\n" + "## Verification\nNone needed.\n\n## Budget and escalation\nFive minutes; escalate if blocked.\n") + +LISTING = {"providers": [ + {"providerInstanceId": "alpha", "driverKind": "kindA", "displayName": "Alpha", + "models": [{"id": "m-1", "label": "M One", "options": []}, {"id": "m-2", "label": "M Two", "options": []}], + "canRunChildTask": True, "constraints": []}, + {"providerInstanceId": "beta", "driverKind": "kindB", "displayName": "Beta", + "models": [{"id": "b-1", "label": "B One", "options": []}], + "canRunChildTask": False, "constraints": ["Provider instance is disabled."]}]} +LISTING_TOOL = "mcp__t3-code__orchestrator_capabilities" +DELEGATE_TOOL = "mcp__t3-code__delegate_task" + + +def driver_file(path, **over): + d = {"name": "fakeagent", "exe": "fakeagent", "run": ["fakeagent", "-p", "{prompt}", "{model_flag}"], + "list": ["fakeagent", "models"], "list_kind": "lines", "model_flag": "--model", "effort_flag": None, + "cwd_flag": None, "plan": "flat", "auth_signatures": None, "limit_signatures": ["allowance used up"], + "tokens_regex": "total tokens: (\\d+)", "approvals_off_reason": None, "notes": "a test driver"} + d.update(over) + with open(path, "w") as f: + json.dump(d, f) + return path + + +def hook_payload(tool, result=None, tool_input=None): + out = {"hook_event_name": "PostToolUse", "tool_name": tool, "session_id": "s1", "cwd": os.getcwd(), + "tool_input": tool_input or {}} + if result is not None: + out["tool_response"] = result + return out + + +def wrapped(listing): + return {"content": [{"type": "text", "text": json.dumps(listing)}]} + + +class DiscoveryCase(SisiCase): + def setUp(self): + super().setUp() + self.userbin = os.path.join(self.home, ".local", "bin") + self.bindir = os.path.join(self.tmp, "sysbin") + os.makedirs(self.userbin) + os.makedirs(self.bindir) + self.marker = os.path.join(self.tmp, "mark") + self.argsfile = os.path.join(self.tmp, "args") + patcher = mock.patch.dict(os.environ, {"PATH": self.userbin + os.pathsep + self.bindir, + "FAKE_MARK": self.marker, "FAKE_ARGS": self.argsfile}) + patcher.start() + self.addCleanup(patcher.stop) + discovery._DATA.clear() + + def exe(self, name, body=FAKE_AGENT, where=None): + p = os.path.join(where or self.userbin, name) + with open(p, "w") as f: + f.write(body) + os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR) + return p + + def runs(self): + return open(self.marker).read().split() if os.path.exists(self.marker) else [] + + def write_cfg(self, obj): + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, "config.json"), "w") as f: + json.dump(obj, f) + + def write_data(self, name, obj): + os.makedirs(self.data, exist_ok=True) + with open(os.path.join(self.data, name), "w") as f: + json.dump(obj, f) + + def feed(self, tool, result=None, tool_input=None): + """The after-tool hook's call, in process; returns what it printed.""" + import contextlib, io + out = io.StringIO() + with contextlib.redirect_stdout(out): + discovery.after_tool(hook_payload(tool, result, tool_input)) + return out.getvalue() + + def host_state(self): + with open(discovery.host_state_file()) as f: + return json.load(f) + + def learn(self, **over): + self.exe("fakeagent") + f = driver_file(os.path.join(self.tmp, "driver.json"), **over) + return self.sisi("workers", "learn", "fakeagent", "--record", f, "--by", "tester") + + +# ---------------------------------------------------------------- item 2: a new tool on PATH + + +class NewToolOnPath(DiscoveryCase): + def test_first_run_prints_nothing_second_run_names_the_new_tool_once(self): + self.exe("oldtool", "#!/bin/sh\n") + self.assertEqual(discovery.session_start(now=1000.0), "") # stores the list, says nothing + time.sleep(0.02) + self.exe("shinyagent", "#!/bin/sh\necho ran >> %s\n" % self.marker) + line = discovery.session_start(now=1001.0) + self.assertIn("shinyagent", line) + self.assertNotIn("oldtool", line) + self.assertIn("sisi workers learn", line) + self.assertEqual(len(line.splitlines()), 1) + self.assertEqual(discovery.session_start(now=1002.0), "", "the same name is announced once") + self.assertEqual(discovery.session_start(now=1000.0 + 7 * 3600), "", "and not again after the age passes") + self.assertEqual(self.runs(), [], "nothing on PATH is ever executed") + + def test_the_tick_hook_prints_the_notice_once_over_two_session_starts(self): + env = {"PATH": self.userbin + os.pathsep + os.environ["PATH"]} + first = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a1", "source": "startup", "cwd": self.proj}), env=env) + self.assertNotIn("new command-line tool", first.stdout) + time.sleep(0.02) + self.exe("brandnew") + second = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a2", "source": "startup", "cwd": self.proj}), env=env) + self.assertEqual(second.stdout.count("brandnew"), 1, second.stdout + second.stderr) + third = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a3", "source": "startup", "cwd": self.proj}), env=env) + self.assertNotIn("brandnew", third.stdout) + + def test_only_user_level_folders_are_listed(self): + discovery.session_start(now=1.0) + self.exe("sysonly", where=self.bindir) # outside the home: a system folder + self.assertEqual(self.sisi_free(), "") + + def sisi_free(self): + return discovery.session_start(now=2.0) + + def test_at_most_five_names_agent_looking_ones_first(self): + discovery.session_start(now=1.0) + time.sleep(0.02) + for n in ("aaa", "bbb", "ccc", "ddd", "eee", "fff", "my-agent"): + self.exe(n) + line = discovery.session_start(now=2.0) + self.assertIn("my-agent", line) + self.assertIn("and 2 more", line) + self.assertEqual(sum(1 for n in ("aaa", "bbb", "ccc", "ddd", "eee", "fff", "my-agent") if n in line), 5) + + def test_shells_and_tools_sisi_already_knows_are_not_announced(self): + discovery.session_start(now=1.0) + time.sleep(0.02) + for n in ("bash", "codex"): + self.exe(n) + self.assertEqual(discovery.session_start(now=2.0), "") + + def test_the_cached_list_is_not_rescanned_until_something_changes(self): + discovery.session_start(now=1.0) + with mock.patch.object(discovery, "list_executables", side_effect=AssertionError("rescanned")): + self.assertEqual(discovery.session_start(now=2.0), "") + # the counter and the age each force a rescan + with mock.patch.object(discovery, "list_executables", return_value=[]) as m: + discovery.session_start(now=1.0 + 7 * 3600) + self.assertTrue(m.called) + self.write_cfg({"discovery": {"path_every_starts": 2}}) + with mock.patch.object(discovery, "list_executables", return_value=[]) as m: + discovery.session_start(now=1.0 + 7 * 3600 + 1) + self.assertFalse(m.called) + discovery.session_start(now=1.0 + 7 * 3600 + 2) + self.assertTrue(m.called) + + +# ---------------------------------------------------------------- item 1: what the host can reach + + +class HostListing(DiscoveryCase): + def test_listing_records_enabled_workers_exactly_as_named_and_says_so_once(self): + out = self.feed(LISTING_TOOL, wrapped(LISTING)) + msg = json.loads(out) + self.assertIn("2 new workers", msg["systemMessage"]) + self.assertEqual(len(out.splitlines()), 1) + prov = self.host_state()["hosts"]["t3-code"]["providers"] + self.assertEqual(sorted(prov["alpha"]["models"]), ["m-1", "m-2"]) + self.assertTrue(prov["alpha"]["usable"]) + self.assertFalse(prov["beta"]["usable"]) + self.assertEqual(self.feed(LISTING_TOOL, wrapped(LISTING)), "", "once per set of new workers") + bigger = json.loads(json.dumps(LISTING)) + bigger["providers"][0]["models"].append({"id": "m-3", "label": "M Three"}) + self.assertIn("1 new worker ", json.loads(self.feed(LISTING_TOOL, bigger))["systemMessage"]) + + def test_every_shape_a_host_may_wrap_the_result_in_is_read(self): + for result in (LISTING, wrapped(LISTING), json.dumps(LISTING), [{"type": "text", "text": json.dumps(LISTING)}]): + if os.path.exists(discovery.host_state_file()): + os.unlink(discovery.host_state_file()) + self.assertIn("2 new workers", self.feed(LISTING_TOOL, result)) + + def test_a_disabled_provider_is_never_routable(self): + self.feed(LISTING_TOOL, wrapped(LISTING)) + cands = {c["worker"]: c for c in workers.build_candidates()} + self.assertTrue(cands["alpha/m-1"]["usable"]) + self.assertFalse(cands["beta/b-1"]["usable"]) + self.assertIn("disabled", cands["beta/b-1"]["reason"]) + self.assertNotIn("beta", self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[0]) + shown = self.sisi("workers").stdout + self.assertIn("beta - not usable now", shown) + self.assertIn("alpha - usable now", shown) + + def test_a_routed_host_worker_names_the_provider_and_model_to_pass_to_the_hosts_delegation_tool(self): + self.feed(LISTING_TOOL, wrapped(LISTING)) + r = self.sisi("route", "--kind", "read", "--difficulty", "1") + self.assertEqual(r.returncode, 0, r.stderr) + lines = r.stdout.splitlines() + self.assertEqual(lines[0], "alpha/m-1") + self.assertIn("mechanism: use the host's cross-provider delegation", lines[1]) + self.assertIn("delegate_task", lines[1]) + self.assertIn("target.providerInstanceId=alpha", lines[1]) + self.assertIn("target.model=m-1", lines[1]) + self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout) + + def test_a_worker_gone_from_enough_listings_is_dropped(self): + self.feed(LISTING_TOOL, wrapped(LISTING)) + only_beta = {"providers": [LISTING["providers"][1]]} + self.feed(LISTING_TOOL, wrapped(only_beta)) + self.feed(LISTING_TOOL, wrapped(only_beta)) + self.assertIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"], "two listings: still kept") + self.feed(LISTING_TOOL, wrapped(only_beta)) + self.assertNotIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"]) + self.write_cfg({"discovery": {"drop_after_listings": 1}}) + self.feed(LISTING_TOOL, wrapped(LISTING)) + self.feed(LISTING_TOOL, wrapped(only_beta)) + self.assertNotIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"]) + + def test_a_delegation_seen_in_use_is_recorded_and_not_announced(self): + out = self.feed(DELEGATE_TOOL, tool_input={"task": "x", "target": {"providerInstanceId": "gamma", "model": "g-1"}}) + self.assertEqual(out, "") + rec = self.host_state()["hosts"]["t3-code"]["providers"]["gamma"]["models"]["g-1"] + self.assertEqual(rec["source"], "delegation") + self.assertEqual([c["worker"] for c in workers.build_candidates() if c["tool"] == "gamma"], ["gamma/g-1"]) + self.feed(DELEGATE_TOOL, tool_input={"target": {"providerInstanceId": 5, "model": None}}) # malformed: ignored + + def test_hundreds_of_models_are_stored_but_only_used_priced_or_ranked_ones_are_candidates(self): + big = {"providers": [{"providerInstanceId": "big", "driverKind": "k", "displayName": "Big", "canRunChildTask": True, + "constraints": [], "models": [{"id": "m-%d" % i, "label": "m"} for i in range(300)]}]} + self.assertEqual(self.feed(LISTING_TOOL, wrapped(big)), "", "a catalogue is not announced worker by worker") + self.assertEqual(len(self.host_state()["hosts"]["t3-code"]["providers"]["big"]["models"]), 300) + self.write_data("worker-prices.json", {"models": {"big/m-7": {"plan": "per-use", "cost_per_million_tokens": 2.0, + "source": "s", "date": "2026-11-01"}}}) + self.write_data("model-strength.json", {"models": {"big/m-9": {"standing": 50, "source": "s", "date": "2026-11-01"}}}) + cands = workers.build_candidates() + self.assertEqual(len([c for c in cands if c["tool"] == "big"]), 300) + keep, cold, excluded = workers.routable_candidates(cands, []) + self.assertEqual(sorted(c["worker"] for c in keep), ["big/m-7", "big/m-9"]) + self.assertEqual(excluded, 298) + self.assertFalse(cold) + + def test_input_that_is_not_json_is_ignored(self): + env = {"SISI_STATE": self.state} + for stdin in ("this is not json", "[1,2]", "", '{"tool_name": 7}', json.dumps(hook_payload(LISTING_TOOL, "not json at all"))): + r = self.sisi_proc("watch", "--after", stdin=stdin, env=env) + self.assertEqual(r.returncode, 0) + self.assertEqual(r.stdout, "") + self.assertFalse(os.path.exists(discovery.host_state_file())) + + def test_the_real_hook_command_records_and_prints_one_line(self): + r = self.sisi_proc("watch", "--after", stdin=json.dumps(hook_payload(LISTING_TOOL, wrapped(LISTING)))) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(len(r.stdout.splitlines()), 1, r.stdout) + self.assertIn("2 new workers", json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"]) + + def test_other_tools_cost_nothing_and_are_left_alone(self): + self.assertEqual(self.feed("Read", {"x": 1}), "") + self.assertEqual(self.feed("Bash"), "") + self.assertFalse(os.path.exists(discovery.host_state_file())) + + def test_forgetting_a_host_provider(self): + self.feed(LISTING_TOOL, wrapped(LISTING)) + r = self.sisi("workers", "forget", "alpha") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertNotIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"]) + self.assertEqual(self.sisi("workers", "forget", "nobody").returncode, 1) + + +# ---------------------------------------------------------------- item 3: a driver learned as data + + +class LearnedDriver(DiscoveryCase): + def check_file(self, **over): + self.exe("fakeagent") + f = driver_file(os.path.join(self.tmp, "d.json"), **over) + return self.sisi("workers", "learn", "fakeagent", "--check", f) + + def test_the_brief_is_a_valid_delegation_contract_naming_the_format(self): + self.exe("fakeagent") + r = self.sisi("workers", "learn", "fakeagent") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(brief_contract.missing_required(r.stdout), []) + for word in ("{prompt}", "approvals_off_reason", "--record", "tokens_regex", "limit_signatures", "help"): + self.assertIn(word, r.stdout) + self.assertEqual(self.sisi("workers", "learn", "nosuchtool").returncode, 1) + + def test_record_validates_stores_runs_one_smoke_task_and_marks_the_driver_usable(self): + r = self.learn() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("PASSED", r.stdout) + self.assertEqual(self.runs(), ["ran"], "exactly one task: the smoke task") + rec = discovery.load_drivers()["fakeagent"] + self.assertEqual(rec["state"], "usable") + self.assertEqual(rec["learned_by"], "tester") + self.assertEqual(rec["models"], ["fa-1", "fa-2"]) + shown = self.sisi("workers").stdout + self.assertIn("fakeagent - usable now", shown) + self.assertIn("learned by tester on", shown) + self.assertIn("models: fa-1, fa-2", shown) + self.assertTrue(os.path.exists(os.path.join(self.data, "worker-drivers.json"))) + + def test_a_template_that_tries_shell_injection_through_the_placeholder_is_refused(self): + self.exe("fakeagent") + cases = [dict(run=["sh", "-c", "fakeagent {prompt}"], exe="sh"), + dict(run=["fakeagent", "-p", "--prompt={prompt}"]), + dict(run=["fakeagent", "-c", "echo {prompt}; {prompt}"]), + dict(run=["fakeagent", "-p", "{prompt}", "{prompt}"]), + dict(run=["fakeagent", "-p", "x"]), + dict(run=["fakeagent", "-p", "{prompt}\n; rm -rf ~"]), + dict(run=["fakeagent", "-p", "{prompt}", "{unknown}"]), + dict(run=["bash", "-c", "{prompt}"], exe="bash", name="fakeagent")] + for over in cases: + f = driver_file(os.path.join(self.tmp, "bad.json"), **over) + r = self.sisi("workers", "learn", "fakeagent", "--record", f) + self.assertEqual(r.returncode, 1, (over, r.stdout)) + self.assertIn("not valid", r.stdout) + self.assertEqual(self.runs(), [], "a refused file never runs anything") + self.assertEqual(discovery.load_drivers(), {}) + + def test_a_binary_not_on_path_or_another_tool_than_the_one_named_is_refused(self): + self.exe("fakeagent") + for over in (dict(exe="ghostagent", name="ghostagent", run=["ghostagent", "{prompt}"]), + dict(exe="/bin/sh", run=["/bin/sh", "{prompt}"]), + dict(exe="fakeagent", name="codex"), + dict(unexpected=1)): + f = driver_file(os.path.join(self.tmp, "bad.json"), **over) + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", f).returncode, 1, over) + other = self.exe("otheragent") + f = driver_file(os.path.join(self.tmp, "o.json"), name="otheragent", exe="otheragent", run=["otheragent", "{prompt}"], + list=None, list_kind=None) + r = self.sisi("workers", "learn", "fakeagent", "--record", f) # a file for another tool than the one named + self.assertEqual(r.returncode, 1) + self.assertIn("must both be 'fakeagent'", r.stdout) + self.assertEqual(self.runs(), []) + + def test_a_file_that_is_not_json_or_too_large_is_refused(self): + self.exe("fakeagent") + p = os.path.join(self.tmp, "x.json") + open(p, "w").write("{not json") + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", p).returncode, 1) + open(p, "w").write(json.dumps({"name": "fakeagent", "notes": "x" * 30000})) + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", p).returncode, 1) + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", os.path.join(self.tmp, "nope")).returncode, 1) + + def test_the_brief_reaches_the_tool_as_one_argument_never_a_shell_string(self): + self.learn() + os.unlink(self.marker) + brief = os.path.join(self.proj, "b.md") + pwn = os.path.join(self.tmp, "pwned") + open(brief, "w").write(BRIEF + '\n"; touch %s; $(touch %s) `touch %s` \'\n' % (pwn, pwn, pwn)) + r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", brief, "--worker", "fakeagent/default") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertFalse(os.path.exists(pwn)) + self.assertEqual(open(self.argsfile).read().strip(), "2", "the tool saw -p and ONE prompt argument") + + def test_a_learned_driver_runs_like_a_built_in_one_usage_and_judging(self): + self.learn() + r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief()) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("Do the toy task", r.stdout) # the report: the tool echoed the brief + self.assertIn("worker: fakeagent/default", r.stdout) + self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout) + run = [x for x in workers.read_records() if x.get("kind") == "run"][-1] + self.assertEqual(run["tokens"], 321) + self.assertEqual(run["tokens_class"], "measured") + j = self.sisi("delegate", "judge", run["id"], "--outcome", "accepted", "--check", "read") + self.assertEqual(j.returncode, 0, j.stdout + j.stderr) + self.assertEqual([r["worker"] for r in workers.read_records() if r.get("kind") == "attempt"], ["fakeagent/default"]) + + def brief(self): + p = os.path.join(self.proj, "brief.md") + open(p, "w").write(BRIEF) + return p + + def test_the_drivers_own_limit_phrase_is_unavailability_and_the_next_worker_runs(self): + self.learn() + self.exe("second", FAKE_AGENT.replace("echo \"$last\"", "echo \"$last\"; echo \"second worker report\"")) + f = driver_file(os.path.join(self.tmp, "s.json"), name="second", exe="second", run=["second", "-p", "{prompt}"], + list=None, list_kind=None, model_flag=None) + self.assertEqual(self.sisi("workers", "learn", "second", "--record", f).returncode, 0) + # `fakeagent` now reports its allowance used up (the learned phrase); the second tool answers + self.exe("fakeagent", FAKE_AGENT.replace('case "$FAKE_MODE"', 'FAKE_MODE=quota\ncase "$FAKE_MODE"')) + r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", "fakeagent/default") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("second worker report", r.stdout) + self.assertIn("fakeagent/default is unavailable (limit", r.stdout) + + def test_a_smoke_task_that_fails_leaves_the_driver_unusable_with_the_reason(self): + for mode, kind in (("login", "login"), ("quota", "quota"), ("flag", "bad-template"), ("silent", "no-answer")): + discovery.save_drivers({}) + with mock.patch.dict(os.environ, {"FAKE_MODE": mode}): + r = self.learn() + self.assertEqual(r.returncode, 1, (mode, r.stdout)) + self.assertIn("FAILED (%s)" % kind, r.stdout) + rec = discovery.load_drivers()["fakeagent"] + self.assertNotEqual(rec["state"], "usable") + self.assertIn(kind, rec["reason"]) + self.assertIsNone(discovery.driver_for("fakeagent")) + shown = self.sisi("workers").stdout + self.assertIn("fakeagent - not usable now", shown) + self.assertIn(kind, shown) + cands = {c["worker"]: c for c in workers.build_candidates()} + self.assertFalse(cands["fakeagent/default"]["usable"]) + # a login the owner then completes: --verify proves it + discovery.save_drivers({}) + with mock.patch.dict(os.environ, {"FAKE_MODE": "login"}): + self.learn() + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--verify").returncode, 1) + r = self.sisi("workers", "learn", "fakeagent", "--verify") + self.assertEqual(r.returncode, 0, r.stdout) + self.assertIsNotNone(discovery.driver_for("fakeagent")) + + def test_a_task_that_waits_for_a_question_is_stopped_by_the_time_limit(self): + self.write_cfg({"discovery": {"smoke_timeout_s": 1}}) + with mock.patch.dict(os.environ, {"FAKE_MODE": "hang"}): + r = self.learn() + self.assertEqual(r.returncode, 1) + self.assertIn("FAILED (timeout)", r.stdout) + self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "failed") + + def test_the_smoke_task_runs_in_a_temporary_folder_with_no_input(self): + body = FAKE_AGENT.replace('echo "$last"', 'pwd > "$FAKE_ARGS.cwd"; read x && echo "got input" >> "$FAKE_ARGS.cwd"; echo "$last"') + self.exe("fakeagent", body) + f = driver_file(os.path.join(self.tmp, "d.json")) + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", f).returncode, 0) + seen = open(self.argsfile + ".cwd").read() + self.assertIn("sisi-smoke-", seen) + self.assertNotIn("got input", seen) + self.assertFalse(os.path.exists(seen.splitlines()[0]), "the temporary folder is removed") + + def test_forget_removes_a_learned_driver(self): + self.learn() + self.assertEqual(self.sisi("workers", "forget", "fakeagent").returncode, 0) + self.assertEqual(discovery.load_drivers(), {}) + self.assertNotIn("fakeagent", self.sisi("workers").stdout) + + def test_the_bypass_flag_patterns_catch_the_known_spellings(self): + for flag in ("--dangerously-skip-permissions", "--dangerously-bypass-approvals-and-sandbox", "--yolo", "-y", + "--always-approve", "--allow-all", "--force", "--auto", "--no-sandbox", "--full-auto", + "--approval-mode=yolo", "--sandbox=off"): + self.assertEqual(discovery.bypass_args(["t", "-p", flag]), [flag], flag) + for flag in ("-p", "--print", "--model", "--output-format", "--sandbox", "text"): + self.assertEqual(discovery.bypass_args(["t", flag]), [], flag) + + +class WaitsForTheOwner(DiscoveryCase): + def bypass(self): + self.exe("fakeagent") + f = driver_file(os.path.join(self.tmp, "d.json"), run=["fakeagent", "--dangerously-skip-permissions", "-p", "{prompt}"], + approvals_off_reason="cannot run unattended without it") + return self.sisi("workers", "learn", "fakeagent", "--record", f) + + def test_an_approvals_off_driver_is_stored_waiting_and_nothing_runs(self): + r = self.bypass() + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("WAITING FOR THE OWNER", r.stdout) + self.assertIn("fakeagent --dangerously-skip-permissions -p {prompt}", r.stdout) + self.assertIn("cannot run unattended without it", r.stdout) + self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner") + self.assertEqual(self.runs(), [], "not even the smoke task ran") + self.assertIsNone(discovery.driver_for("fakeagent")) + cands = {c["worker"]: c for c in workers.build_candidates()} + self.assertFalse(cands["fakeagent/default"]["usable"]) + self.assertIn("waiting for the owner", self.sisi("workers").stdout) + self.assertNotEqual(self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[:1], ["fakeagent/default"]) + brief = os.path.join(self.proj, "b.md") + open(brief, "w").write(BRIEF) + d = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", brief, "--worker", "fakeagent/default") + self.assertEqual(d.returncode, 1) + self.assertEqual(self.runs(), []) + self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--verify").returncode, 1) + self.assertEqual(self.runs(), []) + + def test_approve_lists_the_exact_command_and_an_agent_cannot_decide(self): + self.bypass() + listing = self.sisi("approve").stdout + self.assertIn("drv-fakeagent", listing) + self.assertIn("fakeagent --dangerously-skip-permissions -p {prompt}", listing) + refused = self.sisi("approve", "drv-fakeagent", "--yes") + self.assertEqual(refused.returncode, 2) + self.assertIn("owner in a terminal", refused.stderr) + self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner") + self.assertEqual(self.runs(), []) + self.assertEqual(self.sisi("approve", "drv-ghost", "--yes").returncode, 2) + + def test_the_owners_yes_runs_the_smoke_task_and_only_then_the_driver_is_usable(self): + self.bypass() + self.write_cfg({"learning": {"agent_relayed_approval": True}}) # stands in for the owner's terminal here + r = self.sisi("approve", "drv-fakeagent", "--yes") + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn("PASSED", r.stdout) + self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "usable") + self.assertEqual(self.runs(), ["ran"]) + + def test_the_owners_no_removes_the_driver(self): + self.bypass() + self.write_cfg({"learning": {"agent_relayed_approval": True}}) + self.assertEqual(self.sisi("approve", "drv-fakeagent", "--no").returncode, 0) + self.assertEqual(discovery.load_drivers(), {}) + self.assertEqual(self.runs(), []) + + +# ---------------------------------------------------------------- item 4: new workers earn their place + + +def cand(worker, plan=None, cost=None, unproven=False, **kw): + tool, model = worker.split("/") + return dict({"worker": worker, "tool": tool, "model": model, "plan": plan, "cost": cost, "usable": True, + "allowance_pct_left": None, "aliases": [worker], "maker": model, "unproven": unproven, + "unproven_ok": unproven}, **kw) + + +def attempts(worker, n, kind="read", difficulty=1, outcome="accepted"): + return [{"kind": "attempt", "worker": worker, "type": kind, "difficulty": difficulty, "outcome": outcome, + "id": "%s-%d-%d" % (worker, difficulty, i)} for i in range(n)] + + +class NewWorkersEarnTheirPlace(unittest.TestCase): + def test_a_new_worker_is_never_chosen_above_routine_work(self): + proven = cand("old/a", plan="flat") + new = cand("new/b", plan="flat", unproven=True) + records = attempts("old/a", 8, "impl", 3) + for d in (2, 3): + r = routing.choose([proven, new], records, {}, "impl", d, now=1.0) + self.assertEqual(r["choice"]["worker"], "old/a") + self.assertTrue(any(w == "new/b" and "unproven" in why for w, why in r["passed_over"])) + alone = routing.choose([new], [], {}, "impl", 3, now=1.0) + self.assertIsNone(alone["choice"], "nobody else: the main agent does it, the new worker is not tried on hard work") + self.assertIsNone(routing.choose([new], [], {}, "impl", 2, now=1.0)["choice"]) + self.assertEqual(routing.choose([new], [], {}, "impl", 1, now=1.0)["choice"]["worker"], "new/b") + + def test_a_benchmark_standing_does_not_unlock_hard_work_for_an_unproven_worker(self): + new = cand("new/b", plan="flat", unproven=True, standing=99.0) + old = cand("old/a", plan="per-use", cost=1.0, standing=10.0) + self.assertEqual(routing.choose([new, old], [], {}, "impl", 3, now=1.0)["choice"]["worker"], "old/a") + + def test_after_enough_judged_attempts_it_competes_by_the_ordinary_rules(self): + worker = cand("new/b", plan="flat", unproven=False) + r = routing.choose([worker], attempts("new/b", 8, "impl", 2), {}, "impl", 2, now=1.0) + self.assertEqual(r["choice"]["worker"], "new/b") + + def test_a_free_new_worker_gets_one_routine_task_in_three_a_paid_one_never_by_this_slot(self): + old = cand("old/a", plan="flat", cost=1.0) + free = cand("new/b", plan="flat", unproven=True) + paid = cand("new/c", plan="per-use", cost=0.5, unproven=True) + picks = {} + for total in range(8, 14): + records = attempts("old/a", total) + picks[total] = routing.choose([old, free], records, {}, "read", 1, now=1.0, explore_free_every=3)["choice"]["worker"] + self.assertEqual([picks[t] for t in range(8, 14)], + ["new/b" if t % 3 == 2 else "old/a" for t in range(8, 14)], picks) + r = routing.choose([old, free], attempts("old/a", 8), {}, "read", 1, now=1.0, explore_free_every=3) + self.assertTrue(r["explored_free"]) + self.assertTrue(any("costs nothing extra" in why for w, why in r["passed_over"] if w == "old/a")) + # the config knob: every task, or never + self.assertEqual(routing.choose([old, free], attempts("old/a", 9), {}, "read", 1, now=1.0, + explore_free_every=1)["choice"]["worker"], "new/b") + self.assertEqual(routing.choose([old, free], attempts("old/a", 8), {}, "read", 1, now=1.0, + explore_free_every=0)["choice"]["worker"], "old/a") + # a paid unproven worker is not in the free slot (the existing one-in-ten covers it) + self.assertEqual(routing.choose([old, paid], attempts("old/a", 8), {}, "read", 1, now=1.0, + explore_free_every=3)["choice"]["worker"], "old/a") + + def test_the_rate_is_read_from_config(self): + with mock.patch.object(workers, "route_cfg", return_value={"explore_free_one_in": 5}): + self.assertEqual(workers.explore_free_every(), 5) + with mock.patch.object(workers, "route_cfg", return_value={}): + self.assertEqual(workers.explore_free_every(), 3) + with mock.patch.object(workers, "route_cfg", return_value={"explore_free_one_in": "x"}): + self.assertEqual(workers.explore_free_every(), 3) + self.assertEqual(json.load(open(os.path.join(REPO, "config.default.json")))["route"]["explore_free_one_in"], 3) + + +class NewWorkersThroughTheCommands(DiscoveryCase): + def test_route_says_unproven_until_the_record_has_enough_attempts(self): + self.learn() + r = self.sisi("route", "--kind", "read", "--difficulty", "1", "--explain") + self.assertEqual(r.stdout.splitlines()[0], "fakeagent/default", r.stdout) + self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout) + self.assertNotEqual(self.sisi("route", "--kind", "read", "--difficulty", "3").stdout.splitlines()[:1], ["fakeagent/default"]) + for w in ("fakeagent/default", "fakeagent/fa-1", "fakeagent/fa-2"): + for row in attempts(w, 8): + workers.append_record(row) + r = self.sisi("route", "--kind", "read", "--difficulty", "1") + self.assertTrue(r.stdout.startswith("fakeagent/")) + self.assertNotIn("unproven", r.stdout) + + def test_a_flat_plan_from_the_driver_or_a_fact_is_a_flat_plan_and_unknown_is_per_use(self): + self.learn() + c = {c["worker"]: c for c in workers.build_candidates()}["fakeagent/default"] + self.assertEqual(c["plan"], "flat") + discovery.save_drivers(dict(discovery.load_drivers(), fakeagent=dict( + discovery.load_drivers()["fakeagent"], driver=dict(discovery.load_drivers()["fakeagent"]["driver"], plan=None)))) + c = {c["worker"]: c for c in workers.build_candidates()}["fakeagent/default"] + self.assertEqual(c["plan"], "per-use") + self.write_data("worker-prices.json", {"tools": {"fakeagent": {"plan": "flat", "source": "s", "date": "2026-11-01"}}}) + c = {c["worker"]: c for c in workers.build_candidates()}["fakeagent/default"] + self.assertEqual(c["plan"], "flat") + + +# ---------------------------------------------------------------- item 5: facts follow + + +class FactsNameTheNewWorkers(DiscoveryCase): + def test_the_missing_facts_line_names_at_most_five_new_workers(self): + self.write_data("worker-prices.json", {"models": {"other/x": {"plan": "per-use", "cost_per_million_tokens": 1.0, + "source": "s", "date": time.strftime("%Y-%m-%d")}}}) + self.assertEqual(workers.facts_line(), "", "facts are fresh and nobody new lacks any") + many = {"providers": [{"providerInstanceId": "p%d" % i, "driverKind": "k", "displayName": "P", "canRunChildTask": True, + "constraints": [], "models": [{"id": "m", "label": "m"}]} for i in range(7)]} + self.feed(LISTING_TOOL, wrapped(many)) + line = workers.facts_line() + self.assertIn("worker facts are missing for the new workers p0/m", line) + self.assertIn("and 2 more", line) + self.assertEqual(sum(1 for i in range(7) if "p%d/m" % i in line), 5) + self.assertIn("sisi workers fact WORKER --price N", line) + for i in range(7): + self.write_data("model-strength.json", {"models": {"p%d/m" % j: {"standing": 40, "source": "s", "date": "2026-11-01"} + for j in range(7)}}) + self.assertEqual(workers.facts_line(), "") + + def test_with_nothing_new_the_line_is_the_one_it_always_was(self): + line = workers.facts_line() + self.assertIn("worker facts are missing (no prices or benchmark standing recorded yet)", line) + self.assertNotIn("new workers", line) + + def test_a_learned_tool_is_a_target_too(self): + self.learn() + self.assertIn("fakeagent/default", workers.facts_line()) + + +if __name__ == "__main__": + unittest.main() From 3a12dccf16c6fde418e226a589658d206357b468 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 15:50:03 -0700 Subject: [PATCH 2/4] Item 6: agy learned for real (smoke passed), host listing proof; model list ignores progress lines, disabled providers are not research targets, delegate names the host mechanism, config read once per hook. done / next: report Co-Authored-By: Claude Sonnet 5.5 --- sisi/discovery.py | 31 ++++++++++++++++++------------- sisi/workers.py | 3 ++- tests/test_discovery.py | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 14 deletions(-) diff --git a/sisi/discovery.py b/sisi/discovery.py index 1a624b6..10e231e 100644 --- a/sisi/discovery.py +++ b/sisi/discovery.py @@ -49,11 +49,12 @@ def data(): return _DATA[0] -def cfg(name): +def conf(): + """The `discovery` settings, each valid or its default; the config is read once per call.""" c = store.config().get("discovery") - v = c.get(name) if isinstance(c, dict) else None - d = DEFAULTS[name] - return v if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0 else d + c = c if isinstance(c, dict) else {} + return {k: (c[k] if isinstance(c.get(k), (int, float)) and not isinstance(c.get(k), bool) and c[k] >= 0 else d) + for k, d in DEFAULTS.items()} # ---------------------------------------------------------------- small files @@ -174,8 +175,9 @@ def session_start(now=None): marks = _marks(dirs) starts = int(st.get("starts") or 0) + 1 first = not isinstance(st.get("names"), list) - due = (first or st.get("marks") != marks or now - float(st.get("checked") or 0) >= cfg("path_refresh_s") - or starts >= cfg("path_every_starts")) + c = conf() + due = (first or st.get("marks") != marks or now - float(st.get("checked") or 0) >= c["path_refresh_s"] + or starts >= c["path_every_starts"]) if not due: st["starts"] = starts _save(f, st) @@ -261,7 +263,7 @@ def host_state_file(): return _state_file("host-workers.json") -def apply_listing(state, host, parsed, now, drop_after): +def apply_listing(state, host, parsed, now, drop_after, catalogue_over): """Fold a listing into the stored host workers. Returns how many usable workers are new and worth trying (a provider with more models than discovery.catalogue_over is a catalogue, not a menu). A worker missing from `drop_after` listings in a row is forgotten.""" @@ -272,7 +274,7 @@ def apply_listing(state, host, parsed, now, drop_after): for p in parsed: entry = provs.setdefault(p["provider"], {"models": {}}) entry.update(kind=p["kind"], name=p["name"], usable=p["usable"], reason=p["reason"]) - small = len(p["models"]) <= cfg("catalogue_over") + small = len(p["models"]) <= catalogue_over for m in p["models"]: mrec = entry["models"].get(m["id"]) if mrec is None: @@ -348,7 +350,9 @@ def after_tool(payload): parsed = parse_listing(_tool_result(payload), listing, data().get("blocking_constraint_words") or ()) if not parsed: return - fresh = apply_listing(state, listing["host"], parsed, now, int(cfg("drop_after_listings")) or 1) + c = conf() + fresh = apply_listing(state, listing["host"], parsed, now, int(c["drop_after_listings"]) or 1, + c["catalogue_over"]) if fresh: line = ("sisi: %s reachable through the host's cross-provider delegation (new and unproven: " "routine work only until judged; `sisi workers` lists them, `sisi route` can choose them)." @@ -599,7 +603,7 @@ def smoke(driver, timeout=None): bad-template or no-answer. The command is an argument list: the brief never reaches a shell.""" import shutil, subprocess, tempfile, uuid from . import workers - timeout = float(cfg("smoke_timeout_s") if timeout is None else timeout) + timeout = float(conf()["smoke_timeout_s"] if timeout is None else timeout) nonce = "ok" + uuid.uuid4().hex[:8] tmp = tempfile.mkdtemp(prefix="sisi-smoke-") cmd = workers.build_command(driver, {"model": None, "worker": driver["name"] + "/default"}, @@ -673,7 +677,8 @@ def models_of(driver, timeout=30): return [] if r.returncode != 0: return [] - return workers._parse_models({"list_kind": "lines"}, r.stdout or "")[:500] + # a tool may print a progress line before the list: only a token shaped like an id (a digit or - _ . / :) counts + return [m for m in workers._parse_models({"list_kind": "lines"}, r.stdout or "") if re.search(r"[-_./:\d]", m)][:500] def prove(name, drivers, now=None): @@ -964,7 +969,7 @@ def annotate(cands, records, tools): return cands from . import routing counts = judged_counts(records) - cap = cfg("catalogue_over") + cap = conf()["catalogue_over"] for c in cands: t = marked.get(c.get("tool")) if t is None: @@ -973,7 +978,7 @@ def annotate(cands, records, tools): c["unproven"] = n < routing.MIN_ATTEMPTS if c["unproven"]: c["plan"] = c.get("plan") or "per-use" - if c.get("model") is None or len(t.get("models") or []) <= cap: + if c.get("usable", True) and (c.get("model") is None or len(t.get("models") or []) <= cap): c["unproven_ok"] = True if t.get("host"): c["host_native"] = True diff --git a/sisi/workers.py b/sisi/workers.py index 64e0f75..5d60faa 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -1179,7 +1179,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev prefs = effective_prefs(kind, difficulty, cwd) if cand is not None and cand.get("host_native"): notes.append("sisi: %s is a host-native worker; start it with the host's own subagent tool " - "(`sisi delegate` runs only command-line tools)" % cand["worker"]) + "(`sisi delegate` runs only command-line tools)" % cand["worker"] if not cand.get("host_mechanism") else + "sisi: %s is reached through the host, not by `sisi delegate`: %s" % (cand["worker"], cand["host_mechanism"])) return None, None, notes candidates = [c for c in apply_limits(candidates, prefs)[0] if not c.get("host_native")] while True: diff --git a/tests/test_discovery.py b/tests/test_discovery.py index d962201..7ec3f9c 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -140,6 +140,18 @@ class NewToolOnPath(DiscoveryCase): self.assertEqual(discovery.session_start(now=1000.0 + 7 * 3600), "", "and not again after the age passes") self.assertEqual(self.runs(), [], "nothing on PATH is ever executed") + def test_a_name_that_leaves_and_comes_back_is_not_announced_again(self): + discovery.session_start(now=1.0) + time.sleep(0.02) + p = self.exe("wanderer") + self.assertIn("wanderer", discovery.session_start(now=2.0)) + time.sleep(0.02) + os.unlink(p) + self.assertEqual(discovery.session_start(now=3.0), "") + time.sleep(0.02) + self.exe("wanderer") + self.assertEqual(discovery.session_start(now=4.0), "") + def test_the_tick_hook_prints_the_notice_once_over_two_session_starts(self): env = {"PATH": self.userbin + os.pathsep + os.environ["PATH"]} first = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a1", "source": "startup", "cwd": self.proj}), env=env) @@ -222,6 +234,9 @@ class HostListing(DiscoveryCase): self.assertTrue(cands["alpha/m-1"]["usable"]) self.assertFalse(cands["beta/b-1"]["usable"]) self.assertIn("disabled", cands["beta/b-1"]["reason"]) + self.assertFalse(cands["beta/b-1"].get("unproven_ok")) + self.assertNotIn("beta/b-1", workers.facts_line()) + self.assertIn("alpha/m-1", workers.facts_line()) self.assertNotIn("beta", self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[0]) shown = self.sisi("workers").stdout self.assertIn("beta - not usable now", shown) @@ -239,6 +254,15 @@ class HostListing(DiscoveryCase): self.assertIn("target.model=m-1", lines[1]) self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout) + def test_sisi_delegate_does_not_run_a_host_worker_it_says_how_the_host_starts_it(self): + self.feed(LISTING_TOOL, wrapped(LISTING)) + brief = os.path.join(self.proj, "b.md") + open(brief, "w").write(BRIEF) + r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", brief, "--worker", "alpha/m-1") + self.assertEqual(r.returncode, 1) + self.assertIn("target.providerInstanceId=alpha", r.stdout) + self.assertIn("target.model=m-1", r.stdout) + def test_a_worker_gone_from_enough_listings_is_dropped(self): self.feed(LISTING_TOOL, wrapped(LISTING)) only_beta = {"providers": [LISTING["providers"][1]]} @@ -289,6 +313,11 @@ class HostListing(DiscoveryCase): self.assertEqual(len(r.stdout.splitlines()), 1, r.stdout) self.assertIn("2 new workers", json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"]) + def test_a_payload_that_is_not_an_object_does_nothing(self): + for payload in (None, [1], "x", 5, {}, {"tool_name": None}, {"tool_name": LISTING_TOOL}): + discovery.after_tool(payload) + self.assertFalse(os.path.exists(discovery.host_state_file())) + def test_other_tools_cost_nothing_and_are_left_alone(self): self.assertEqual(self.feed("Read", {"x": 1}), "") self.assertEqual(self.feed("Bash"), "") @@ -369,6 +398,14 @@ class LearnedDriver(DiscoveryCase): self.assertIn("must both be 'fakeagent'", r.stdout) self.assertEqual(self.runs(), []) + def test_a_shell_or_interpreter_is_not_a_tool_even_when_the_name_matches(self): + self.exe("sh") # a command on PATH that is not an agent tool + f = driver_file(os.path.join(self.tmp, "sh.json"), name="sh", exe="sh", run=["sh", "{prompt}"], list=None, + list_kind=None, model_flag=None) + r = self.sisi("workers", "learn", "sh", "--check", f) + self.assertEqual(r.returncode, 1, r.stdout) + self.assertIn("shell or interpreter", r.stdout) + def test_a_file_that_is_not_json_or_too_large_is_refused(self): self.exe("fakeagent") p = os.path.join(self.tmp, "x.json") From a03102aba9add518baa90754c2180242621dc622 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:06:03 -0700 Subject: [PATCH 3/4] 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 --- canon/orchestration.md | 3 + docs/workers.md | 9 + sisi/discovery.py | 688 ++++++++++++++++++++++++++++++++++++++-- sisi/helptext.py | 2 +- sisi/routing.py | 54 +++- sisi/workers.py | 42 ++- tests/test_providers.py | 557 ++++++++++++++++++++++++++++++++ 7 files changed, 1310 insertions(+), 45 deletions(-) create mode 100644 tests/test_providers.py diff --git a/canon/orchestration.md b/canon/orchestration.md index f5ea973..34d77e8 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -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 diff --git a/docs/workers.md b/docs/workers.md index 4b21d67..b0ae24b 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -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. diff --git a/sisi/discovery.py b/sisi/discovery.py index 10e231e..e0f0143 100644 --- a/sisi/discovery.py +++ b/sisi/discovery.py @@ -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 diff --git a/sisi/helptext.py b/sisi/helptext.py index 35585a9..10caded 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -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 "" 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 "" 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', diff --git a/sisi/routing.py b/sisi/routing.py index f3d51c4..86a7d7f 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -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"): diff --git a/sisi/workers.py b/sisi/workers.py index 5d60faa..03e42c7 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -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"), diff --git a/tests/test_providers.py b/tests/test_providers.py new file mode 100644 index 0000000..66c83bb --- /dev/null +++ b/tests/test_providers.py @@ -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() From 3dc9b918140c996fd331ecbccf1d7d37e8def566 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:08:43 -0700 Subject: [PATCH 4/4] helptext: fix the workers entry (quoting). done / next: owner setup on a copy of the store Co-Authored-By: Claude Sonnet 5.5 --- sisi/helptext.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sisi/helptext.py b/sisi/helptext.py index 10caded..edfbf14 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -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 "" 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 "" 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\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', + '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] the plan of a provider (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 WORDS\" | --remove the word of the owner 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 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 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',