Workers and tools installed after sisi are found and learned; plans, allowance reads, error signatures and the owner's vouch feed routing; one approval path for learning changes, learned tools and allowance reads
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
cab81df9d7
24 files changed
+3945
-120
No files matched your search
@@ -8,6 +8,10 @@ All notable changes to this project are recorded here. The format follows
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- Workers that appear after install become routable: the host's own listing and delegation calls, new command-line
|
||||||
|
tools (`sisi workers learn`), per-provider plans, allowance probes, failure phrases and the owner's vouch
|
||||||
|
(`sisi workers plan|allowance|signature|vouch`). Learned tools that switch off approvals and allowance probes are
|
||||||
|
decided with learning changes by one `sisi approve`; one data file (`canon/orchestration-tools.json`) describes a host's tools.
|
||||||
- The durable work-unit record: `sisi unit close|pause|show|list`, an archive per unit in the
|
- The durable work-unit record: `sisi unit close|pause|show|list`, an archive per unit in the
|
||||||
project, one summary line per unit in the user store, five delivery statuses, the policy
|
project, one summary line per unit in the user store, five delivery statuses, the policy
|
||||||
version, start and closing commits. See docs/records.md.
|
version, start and closing commits. See docs/records.md.
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"comment": "Data for sisi/discovery.py: which flags switch off approvals, which names are never tools, and which names hint at an agent tool. A host's own tools (its capability listing and delegation tool, and where the provider and model sit in them) are in canon/orchestration-tools.json, the one description of a host's tools. Names of tools and hosts live in data, never in code. Paths are dotted keys into the tool's JSON.",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is. A delegation entry's name may be a shell-style pattern (`*delegate_task`). `async` says how the tool's result marks a background launch: the dotted `path` into the result, the `running` values meaning \"still running\", and the `ids` paths whose values the later completion message will carry; `title` is the input path of the task's title, the other way that message names it. A listed tool with no `async` is a launch when its call returned in under five seconds with no report in the result.",
|
"_about": "Host tool names the orchestration meter needs (sisi/orchestration.py). Per host: `delegation` tools start a worker (where the call carries the model and the brief text, as dotted paths into the tool's input); `exempt` tools are never counted as direct work (the question dialog, planning and to-do tools, messaging tools). Any other tool, including one named nowhere here, counts. `refuse` says how the host's before-tool hook refuses a call: `json-deny` prints the host's permission-deny JSON, `exit-2` exits with status 2 and the reason on standard error, `none` means the meter only counts there. `evidence` says how sure this entry is. A delegation entry's name may be a shell-style pattern (`*delegate_task`). `async` says how the tool's result marks a background launch: the dotted `path` into the result, the `running` values meaning \"still running\", and the `ids` paths whose values the later completion message will carry; `title` is the input path of the task's title, the other way that message names it. A listed tool with no `async` is a launch when its call returned in under five seconds with no report in the result. `capability` tools list what the host can reach (providers and models, as dotted paths into the tool's result); a delegation entry that names a `provider` path says where the call carries the provider; both carry `reach`, the label under which what discovery learns is stored (sisi/discovery.py, read through orchestration.reach_specs). This file is the one description of a host's tools: sisi/orchestration.py and sisi/discovery.py both read it.",
|
||||||
"claude-code": {
|
"claude-code": {
|
||||||
"refuse": "json-deny",
|
"refuse": "json-deny",
|
||||||
"evidence": "observed live (tools/live_orchestration_check.py)",
|
"evidence": "observed live (tools/live_orchestration_check.py)",
|
||||||
@@ -26,7 +26,23 @@
|
|||||||
"taskId",
|
"taskId",
|
||||||
"childThreadId"
|
"childThreadId"
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
"provider": "target.providerInstanceId",
|
||||||
|
"reach": "t3-code"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"capability": {
|
||||||
|
"mcp__t3-code__orchestrator_capabilities": {
|
||||||
|
"reach": "t3-code",
|
||||||
|
"providers": "providers",
|
||||||
|
"provider": "providerInstanceId",
|
||||||
|
"kind": "driverKind",
|
||||||
|
"name": "displayName",
|
||||||
|
"models": "models",
|
||||||
|
"model": "id",
|
||||||
|
"label": "label",
|
||||||
|
"usable": "canRunChildTask",
|
||||||
|
"constraints": "constraints"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"exempt": {
|
"exempt": {
|
||||||
|
|||||||
+13
-14
@@ -33,13 +33,11 @@ present; nothing here names one. Read on demand: `sisi delegate guide`.
|
|||||||
routine work measured proof outranks a benchmark: the cheapest worker with a judged
|
routine work measured proof outranks a benchmark: the cheapest worker with a judged
|
||||||
record wins, and standing decides only when nobody has one. A thin record is a
|
record wins, and standing decides only when nobody has one. A thin record is a
|
||||||
reason for care, not a verdict.
|
reason for care, not a verdict.
|
||||||
- Always use the newest version of a given model (same maker and class) when it is usable,
|
- Always use the newest version of a given model (same maker and class) when it is usable, never
|
||||||
never an older version of it: newer is almost always better and cheaper, so neither a
|
an older version of it: neither a better old record nor a cheaper old plan brings it back, and a
|
||||||
better old record nor a cheaper old plan brings the old one back. A newer release of a
|
newer release of a different model or class never wins for being newer. A new version starts from its
|
||||||
different model or class never wins for being newer. A new version starts from its
|
predecessor's record. Never guess maker, class or release date from a name: hand `sisi workers
|
||||||
predecessor's record. Never guess maker, class or release date from a name: hand the
|
classify` to a cheap worker and record its answer; `sisi workers classes` records a maker's classes.
|
||||||
output of `sisi workers classify` to a cheap, fast worker and record its answer; record
|
|
||||||
a maker's classes, most capable first, with `sisi workers classes`.
|
|
||||||
- Ask `sisi route --kind K --difficulty N` before delegating; `--explain` says
|
- Ask `sisi route --kind K --difficulty N` before delegating; `--explain` says
|
||||||
why. Difficulty is 1 routine, 2 ordinary, 3 hard. Say the guess out loud;
|
why. Difficulty is 1 routine, 2 ordinary, 3 hard. Say the guess out loud;
|
||||||
the record shows how good the guesses were.
|
the record shows how good the guesses were.
|
||||||
@@ -100,13 +98,14 @@ present; nothing here names one. Read on demand: `sisi delegate guide`.
|
|||||||
|
|
||||||
## Keeping the picture current
|
## Keeping the picture current
|
||||||
|
|
||||||
- What exists, what it costs, and how good it is all change. Discovery is
|
- What exists, what it costs and how good it is change. Discovery is `sisi workers`; prices and
|
||||||
`sisi workers`; prices and benchmark standing are worker facts, each with
|
benchmark standing are worker facts with a source and a date (`sisi workers fact`). When facts are
|
||||||
a source and a date, recorded with `sisi workers fact`.
|
missing or stale, hand the research to a fast, cheap worker. A newly appeared model is unproven:
|
||||||
- When facts are missing or stale, hand the research itself to a fast, cheap
|
low-stakes tasks first, checked one level more carefully, until its record is thick.
|
||||||
worker: find current prices and software-engineering benchmark standing,
|
- Workers appear after install: a new tool is named once (`sisi workers learn NAME` prints the brief
|
||||||
then record them. Treat a newly appeared model as unproven: low-stakes
|
for the cheap worker that learns it) and the host's listing teaches its models; each is unproven
|
||||||
tasks first, checked one level more carefully, until its record is thick.
|
until judged. `sisi workers plan|allowance|signature|vouch` record a provider's facts and the
|
||||||
|
owner's word; a learned tool that switches off approvals, and an allowance probe, wait for `sisi approve`.
|
||||||
- Orchestration legwork is delegable like any other legwork: discovery,
|
- Orchestration legwork is delegable like any other legwork: discovery,
|
||||||
price and benchmark research, routing lookups, first-pass review, and
|
price and benchmark research, routing lookups, first-pass review, and
|
||||||
summarising the record can all go to a fast, cheap worker. The judgement
|
summarising the record can all go to a fast, cheap worker. The judgement
|
||||||
|
|||||||
@@ -18,12 +18,20 @@
|
|||||||
"3": 85
|
"3": 85
|
||||||
},
|
},
|
||||||
"price_blend_input_parts": 3,
|
"price_blend_input_parts": 3,
|
||||||
|
"explore_free_one_in": 3,
|
||||||
"class_span": {
|
"class_span": {
|
||||||
"1": 100,
|
"1": 100,
|
||||||
"2": 70,
|
"2": 70,
|
||||||
"3": 35
|
"3": 35
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"discovery": {
|
||||||
|
"path_refresh_s": 21600,
|
||||||
|
"path_every_starts": 25,
|
||||||
|
"drop_after_listings": 3,
|
||||||
|
"catalogue_over": 8,
|
||||||
|
"smoke_timeout_s": 120
|
||||||
|
},
|
||||||
"unit": {
|
"unit": {
|
||||||
"stale_hours": 12
|
"stale_hours": 12
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-1
@@ -125,7 +125,8 @@ the budget and every other check run first, and a refusal applies nothing. If ap
|
|||||||
again is refused, and so is a second change to a rule that has one waiting. If the owner refuses, the
|
again is refused, and so is a second change to a rule that has one waiting. If the owner refuses, the
|
||||||
learning is rejected, not proposed again.
|
learning is rejected, not proposed again.
|
||||||
- **`sisi approve`** with no arguments lists every waiting change in full: the command, the pattern and
|
- **`sisi approve`** with no arguments lists every waiting change in full: the command, the pattern and
|
||||||
profile, the rule text as a diff, why it needs the owner, and the replay result. A decision needs the word
|
profile, the rule text as a diff, why it needs the owner, and the replay result. The same listing, word and
|
||||||
|
record serve a learned tool that switches off approvals (`drv-NAME`) and an allowance probe (`probe-PROVIDER`). A decision needs the word
|
||||||
`sisi approve ID --yes|--no` prints typed back at the controlling terminal device (never standard input), and
|
`sisi approve ID --yes|--no` prints typed back at the controlling terminal device (never standard input), and
|
||||||
the before-tool hook refuses any shell command of an agent that invokes it; a process with no controlling
|
the before-tool hook refuses any shell command of an agent that invokes it; a process with no controlling
|
||||||
terminal is refused unless the user config sets `learning.agent_relayed_approval`. Every decision, and every
|
terminal is refused unless the user config sets `learning.agent_relayed_approval`. Every decision, and every
|
||||||
|
|||||||
+14
-2
@@ -169,7 +169,7 @@ session start as unproven. Settings under `orchestrate`: `direct_calls`, `direct
|
|||||||
|
|
||||||
In the user store: `workers.json` (discovery cache), `delegations.jsonl` (the ledger),
|
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-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,
|
`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
|
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:
|
during normal use, never a scheduler. Settings live under `workers` in the config:
|
||||||
@@ -179,4 +179,16 @@ during normal use, never a scheduler. Settings live under `workers` in the confi
|
|||||||
## What this does not do
|
## What this does not do
|
||||||
|
|
||||||
Prices and benchmark standing are only as fresh as their recorded source and date. A worker
|
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. Host tool names are data (`canon/orchestration-tools.json`, shared with the orchestration meter), never code.
|
||||||
|
|
||||||
|
- **From the host.** The after-tool hook reads the host's capability listing and delegation calls. Each provider the host says can run a task, and each model, is the worker `provider/model`; a provider the host disables is stored, never routable, and one missing from `discovery.drop_after_listings` listings (3) is dropped. A listing over `discovery.catalogue_over` models (8) is a catalogue: only models used, priced or with a standing are candidates. `sisi route` names the delegation tool and the ids to pass it. Your own `only` limit still decides what is routable.
|
||||||
|
- **From PATH.** Session start compares the executables in the user-level folders on PATH (nothing is run) with the stored list and names new ones once, five at most (`discovery.path_refresh_s`, `discovery.path_every_starts`).
|
||||||
|
- **A tool, learned as data.** `sisi workers learn NAME` prints the brief for a cheap worker to read the tool's help and write a small JSON driver; `--check FILE` validates, `--record FILE` stores it (`worker-drivers.json`) and runs one smoke task, `--verify` retries, `sisi workers forget NAME` removes it. The command is an argument list, never a shell. A name that collides with a built-in driver is refused. A command with a flag that switches off approvals or a sandbox runs nothing until the owner decides.
|
||||||
|
- **Earning a place.** Such a worker is unproven until it has `MIN_ATTEMPTS` judged attempts: difficulty 1 only, a free or flat one gets one routine task in `route.explore_free_one_in` (3), and `sisi route`/`sisi delegate` say to check its result. Unknown plan counts as per-use.
|
||||||
|
- **Providers.** A tool can carry several providers (the part of an id before the first slash), each with facts of its own that never reach another: `sisi workers plan PROVIDER flat|free|per-use --source S`; `sisi workers allowance PROVIDER --url|--command ...` (a probe: the key comes from a named command at probe time, goes in one request, and is never stored or printed; the smallest remaining window decides, the provider is down until every spent window resets; a failed probe changes nothing); `sisi workers signature PROVIDER --match TEXT --class auth|limit|missing|error` (the provider's own failure phrases, before the built-in ones). A limit marks that provider down until the time the error names, else the probe's reset.
|
||||||
|
- **Vouching.** `sisi workers vouch WORKER --up-to 1|2|3 --why "OWNER'S WORDS"`: capable up to that difficulty on the owner's word, ranked with judged proof, shown by `--explain` as its own evidence; a thick bad record overrides it and its own thick record replaces it. Words not found in a message the owner typed count only to difficulty 2.
|
||||||
|
- **The owner's decisions.** Learned drivers that switch off approvals (`drv-NAME`) and allowance probes (`probe-PROVIDER`) are decided with learning changes by one command, `sisi approve`: it lists all three kinds in full, and a decision needs the random word it prints typed at the controlling terminal. An agent's shell command is refused, whatever the id.
|
||||||
+1
-1
@@ -294,7 +294,7 @@ def main(argv):
|
|||||||
return cycle.cmd_cycle(args)
|
return cycle.cmd_cycle(args)
|
||||||
if cmd == "approve":
|
if cmd == "approve":
|
||||||
from . import cycle
|
from . import cycle
|
||||||
return cycle.cmd_approve(args)
|
return cycle.cmd_approve(args) # learning changes (P-N), learned drivers (drv-NAME), allowance probes (probe-NAME)
|
||||||
if cmd == "oracle":
|
if cmd == "oracle":
|
||||||
return cmd_oracle()
|
return cmd_oracle()
|
||||||
if cmd == "risk":
|
if cmd == "risk":
|
||||||
|
|||||||
+52
-10
@@ -248,7 +248,7 @@ def due_notice(session=None):
|
|||||||
if n >= DUE_AFTER or fl:
|
if n >= DUE_AFTER or fl:
|
||||||
lines.append("sisi: a learning cycle is due (%d proposed learning(s)%s; `sisi cycle` prints the brief)"
|
lines.append("sisi: a learning cycle is due (%d proposed learning(s)%s; `sisi cycle` prints the brief)"
|
||||||
% (n, ", %d flagged not working" % fl if fl else ""))
|
% (n, ", %d flagged not working" % fl if fl else ""))
|
||||||
pend = L.pending_notice()
|
pend = L.pending_notice(waiting_count())
|
||||||
if pend:
|
if pend:
|
||||||
lines.append(pend)
|
lines.append(pend)
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
@@ -1241,14 +1241,47 @@ def park_rule_change(action, reasons):
|
|||||||
return pid
|
return pid
|
||||||
|
|
||||||
|
|
||||||
|
def _owner_waiting():
|
||||||
|
"""Everything that waits for the owner, of all three kinds, as dicts with "id", "lines" (the full action) and
|
||||||
|
"apply" (yes -> (exit code, text)): a learning change (P-N), a learned driver (drv-NAME), an allowance
|
||||||
|
probe (probe-PROVIDER). One list, one ask."""
|
||||||
|
def one(i):
|
||||||
|
def apply(yes, how, pid=i["id"]):
|
||||||
|
return 0, apply_pending(pid, yes, how)
|
||||||
|
return {"id": i["id"], "lines": describe_pending(i), "apply": apply, "kind": "change", "item": i}
|
||||||
|
out = [one(i) for i in L.load_pending()]
|
||||||
|
try:
|
||||||
|
from . import discovery
|
||||||
|
for w in discovery.waiting_decisions():
|
||||||
|
inner = w["apply"]
|
||||||
|
w["apply"] = lambda yes, how, f=inner: f(yes)
|
||||||
|
out.append(w)
|
||||||
|
except Exception as e: # a broken listing of drivers must not hide the learning changes
|
||||||
|
from . import store
|
||||||
|
store.log_error("approve-waiting", e)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def waiting_count():
|
||||||
|
"""How many decisions wait for the owner, of all three kinds (the session-start line counts them together)."""
|
||||||
|
n = len(L.load_pending())
|
||||||
|
try:
|
||||||
|
from . import discovery
|
||||||
|
n += discovery.waiting_count()
|
||||||
|
except Exception as e:
|
||||||
|
from . import store
|
||||||
|
store.log_error("approve-count", e)
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
def cmd_approve(argv):
|
def cmd_approve(argv):
|
||||||
items = L.load_pending()
|
waiting = _owner_waiting()
|
||||||
if not argv:
|
if not argv:
|
||||||
if not items:
|
if not waiting:
|
||||||
print("nothing waits for a decision")
|
print("nothing waits for a decision")
|
||||||
return 0
|
return 0
|
||||||
for i in items:
|
for w in waiting:
|
||||||
print("\n".join(describe_pending(i)))
|
print("\n".join(w["lines"]))
|
||||||
print()
|
print()
|
||||||
print("The owner decides, in a terminal: sisi approve ID --yes | --no (and types the word it shows)")
|
print("The owner decides, in a terminal: sisi approve ID --yes | --no (and types the word it shows)")
|
||||||
return 0
|
return 0
|
||||||
@@ -1256,13 +1289,13 @@ def cmd_approve(argv):
|
|||||||
if not yes and "--no" not in argv:
|
if not yes and "--no" not in argv:
|
||||||
print("usage: sisi approve [ID --yes | --no]", file=sys.stderr)
|
print("usage: sisi approve [ID --yes | --no]", file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
item = next((i for i in items if i.get("id") == pid), None)
|
item = next((w for w in waiting if w["id"] == pid), None)
|
||||||
tty = _open_terminal()
|
tty = _open_terminal()
|
||||||
relayed = False
|
relayed = False
|
||||||
if tty is None:
|
if tty is None:
|
||||||
if not relay_allowed():
|
if not relay_allowed():
|
||||||
if item:
|
if item:
|
||||||
print("\n".join(describe_pending(item)), file=sys.stderr)
|
print("\n".join(item["lines"]), file=sys.stderr)
|
||||||
refuse_attempt(pid, "no controlling terminal")
|
refuse_attempt(pid, "no controlling terminal")
|
||||||
print("sisi approve: refused. A decision is the owner's, typed at a terminal: this process has no "
|
print("sisi approve: refused. A decision is the owner's, typed at a terminal: this process has no "
|
||||||
"controlling terminal (an agent, a script, a pipe). Show the owner what it does (the listing "
|
"controlling terminal (an agent, a script, a pipe). Show the owner what it does (the listing "
|
||||||
@@ -1276,7 +1309,7 @@ def cmd_approve(argv):
|
|||||||
print("sisi approve: no pending change %r (`sisi approve` lists them)" % pid, file=sys.stderr)
|
print("sisi approve: no pending change %r (`sisi approve` lists them)" % pid, file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
word = _decision_word()
|
word = _decision_word()
|
||||||
tty.write("\n".join(describe_pending(item)) + "\n\nYou are about to %s %s.\n"
|
tty.write("\n".join(item["lines"]) + "\n\nYou are about to %s %s.\n"
|
||||||
% ("APPROVE" if yes else "REFUSE", pid))
|
% ("APPROVE" if yes else "REFUSE", pid))
|
||||||
if not _typed_word(tty, word):
|
if not _typed_word(tty, word):
|
||||||
refuse_attempt(pid, "the word was not typed at the terminal")
|
refuse_attempt(pid, "the word was not typed at the terminal")
|
||||||
@@ -1288,9 +1321,18 @@ def cmd_approve(argv):
|
|||||||
tty.close()
|
tty.close()
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
|
if item is None:
|
||||||
|
print("sisi approve: no pending change %r (`sisi approve` lists them)" % pid, file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
how = {"terminal": tty is not None, "relayed": relayed}
|
||||||
try:
|
try:
|
||||||
print(apply_pending(pid, yes, {"terminal": tty is not None, "relayed": relayed}))
|
if item["kind"] != "change": # a change records its own decision inside its transaction (apply_pending)
|
||||||
return 0
|
L.record_approval({"id": pid, "decision": "yes" if yes else "no", "ts": L.now(), "kind": item["kind"],
|
||||||
|
"session": os.environ.get("SISI_SESSION_ID") or None, "terminal": bool(how["terminal"]),
|
||||||
|
"relayed": "relayed by an agent" if relayed else None, "action": item.get("action")})
|
||||||
|
rc, text = item["apply"](yes, how)
|
||||||
|
print(text, file=sys.stdout if rc == 0 else sys.stderr)
|
||||||
|
return rc
|
||||||
except (CycleError, overlay.OverlayError, documents.DocumentError) as e:
|
except (CycleError, overlay.OverlayError, documents.DocumentError) as e:
|
||||||
print("sisi approve: %s" % e, file=sys.stderr)
|
print("sisi approve: %s" % e, file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
|
|||||||
+1671
File diff suppressed because it is too large.
Load diff
+6
-4
@@ -88,10 +88,12 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T
|
|||||||
"""A failure message arrived. Classify it; record the worker down (when it can be identified and `record`);
|
"""A failure message arrived. Classify it; record the worker down (when it can be identified and `record`);
|
||||||
mark its pending run superseded; remember it in the meter for the question-dialog check; return the fallback
|
mark its pending run superseded; remember it in the meter for the question-dialog check; return the fallback
|
||||||
text, or None when the text is not an unavailability. Never raises past the caller's guard."""
|
text, or None when the text is not an unavailability. Never raises past the caller's guard."""
|
||||||
if workers.classify_failure(text) is None:
|
|
||||||
return None
|
|
||||||
from . import orchestration
|
from . import orchestration
|
||||||
worker = worker or workers.identify_worker(text)
|
worker = worker or workers.identify_worker(text)
|
||||||
|
cand = workers.resolve_worker(worker, workers._cached_candidates()[0]) if worker else None
|
||||||
|
failure = workers.failure_for(text, cand) # with the worker's provider's phrases and its learned driver's
|
||||||
|
if failure is None:
|
||||||
|
return None
|
||||||
info = {"worker": worker, "ts": time.time(), "kind": kind, "difficulty": difficulty}
|
info = {"worker": worker, "ts": time.time(), "kind": kind, "difficulty": difficulty}
|
||||||
run, marked = None, None
|
run, marked = None, None
|
||||||
if run_id:
|
if run_id:
|
||||||
@@ -106,7 +108,7 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T
|
|||||||
due = workers.read_availability().get(str(worker).lower()) or {}
|
due = workers.read_availability().get(str(worker).lower()) or {}
|
||||||
info.update(until=due.get("retry_at"), reason=("%s: %s" % (due.get("reason"), (due.get("note") or "")[:60])) if due else None)
|
info.update(until=due.get("retry_at"), reason=("%s: %s" % (due.get("reason"), (due.get("note") or "")[:60])) if due else None)
|
||||||
if not info.get("reason"):
|
if not info.get("reason"):
|
||||||
reason, note, _ = workers.classify_failure(text)
|
reason, note, _ = failure
|
||||||
info["reason"] = "%s: %s" % (reason, note[:60])
|
info["reason"] = "%s: %s" % (reason, note[:60])
|
||||||
if run_id:
|
if run_id:
|
||||||
workers.append_record({"kind": "run-end", "run_id": run_id, "ts": round(time.time()), "status": "superseded",
|
workers.append_record({"kind": "run-end", "run_id": run_id, "ts": round(time.time()), "status": "superseded",
|
||||||
@@ -117,7 +119,7 @@ def handle(m, sid, cwd, text, own_model=None, worker=None, run_id=None, record=T
|
|||||||
for part in re.split(r"[/\s]+", str(n or "").lower()):
|
for part in re.split(r"[/\s]+", str(n or "").lower()):
|
||||||
if len(part) >= 4:
|
if len(part) >= 4:
|
||||||
names.add(part)
|
names.add(part)
|
||||||
names.update(("fallback", "fall back", "unavailable") + _REASON_WORDS.get(workers.classify_failure(text)[0], ()))
|
names.update(("fallback", "fall back", "unavailable") + _REASON_WORDS.get(failure[0], ()))
|
||||||
m["unavail_names"] = sorted(names)
|
m["unavail_names"] = sorted(names)
|
||||||
orchestration._event(m, sid, "unavailable", worker=worker, run=run_id)
|
orchestration._event(m, sid, "unavailable", worker=worker, run=run_id)
|
||||||
return fallback_text(info, cwd, own_model)
|
return fallback_text(info, cwd, own_model)
|
||||||
+3
-3
@@ -23,7 +23,7 @@ LONG = {
|
|||||||
'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id",
|
'retro': " sisi retro print the unit's record and what stands out in it\n sisi retro --finding F --cause C --impact value|correctness|time|cost|attention --disposition promote|record|drop [--same-as ID | --new] [--target ID]\n record one finding; promote also needs --change, --mechanism,\n --expect and --validate; record needs --limits; drop needs --why-not;\n a match in scope is printed and attached as a recurrence (--new records\n a learning of its own); --target names the rule or recipe it concerns\n sisi retro --adopt ID a parent adopts a subagent's candidate learning, by id",
|
||||||
'lessons': ' sisi lessons [--json] | ID the learning records and their statuses; with an id (L-0007): that one learning in full',
|
'lessons': ' sisi lessons [--json] | ID the learning records and their statuses; with an id (L-0007): that one learning in full',
|
||||||
'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n with no argument: the brief (file format, values, at most eight learnings) for the agent that\n turns proposed learnings into mechanisms; check lists every problem in the file and runs\n nothing; apply replays command checks in an exported copy, then applies (no scheduler:\n due-ness is a counter)',
|
'cycle': ' sisi cycle [due|apply FILE|check FILE|revert [ID]|help]\n with no argument: the brief (file format, values, at most eight learnings) for the agent that\n turns proposed learnings into mechanisms; check lists every problem in the file and runs\n nothing; apply replays command checks in an exported copy, then applies (no scheduler:\n due-ness is a counter)',
|
||||||
'approve': " sisi approve [ID --yes|--no] list, in full, the consequential changes waiting for the owner; decide one\n (the owner types the word it prints, at the terminal; an agent's shell command is refused)",
|
'approve': " sisi approve [ID --yes|--no] list, in full, what waits for the owner (learning changes, learned tools, allowance probes); decide one\n (the owner types the word it prints, at the terminal; an agent's shell command is refused)",
|
||||||
'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)',
|
'learn': ' sisi learn [--scope user|project] TEXT\n record an owner statement; it takes effect at once and\n `sisi oracle` prints it. Scope for other learnings is\n earned by evidence, never claimed\n sisi learn --withdraw ID --reason WHY\n take a statement recorded by mistake out of delivery (kept in history)',
|
||||||
'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires',
|
'risk': ' sisi risk [--json] risk floor for the working-tree change, with reasons and\n what that profile requires',
|
||||||
'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list",
|
'handover': " sisi handover [--all] | done ID --where PATH [--quote FRAGMENT]\n project-scope learnings waiting to be filed in this project's own docs or\n work list; done confirms one is filed (the named file must contain\n its key text) and removes it from the list",
|
||||||
@@ -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); --learning prints only the learning report',
|
'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); --learning prints only the learning report',
|
||||||
'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library',
|
'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "<claim>" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library',
|
||||||
'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe',
|
'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "<work>" best-matching recipe',
|
||||||
'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --maker M --class C [--released DATE] --source S the maker, class and release date researched for a model\n sisi workers classify [--record FILE [--by WORKER]] the question for a cheap worker (maker, class, release date of routable models), or store its answer\n sisi workers classes MAKER CLASS... --source S | MAKER --remove the classes of a maker, most capable first (a prior between them)\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 fact W --maker M --class C [--released DATE] --source S the maker, class and release date researched for a model\n sisi workers classify [--record FILE [--by WORKER]] the question for a cheap worker (maker, class, release date of routable models), or store its answer\n sisi workers classes MAKER CLASS... --source S | MAKER --remove the classes of a maker, most capable first (a prior between them)\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',
|
'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',
|
'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',
|
'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"),
|
(("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"),
|
(("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"),
|
(("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"),
|
(("verifiers",), "verifiers show|for|doctor|lint|WORDS", "ways to know work is correct"),
|
||||||
(("done",), "done [ID|for \"<work>\"]", "the recipe saying what makes a kind of work done"),
|
(("done",), "done [ID|for \"<work>\"]", "the recipe saying what makes a kind of work done"),
|
||||||
(("rule",), "rule [N|ID]", "the rules and how each is enforced"),
|
(("rule",), "rule [N|ID]", "the rules and how each is enforced"),
|
||||||
|
|||||||
+6
-6
@@ -794,14 +794,14 @@ def approved_ids():
|
|||||||
return {a["id"] for a in load_approvals() if a.get("decision") == "yes" and a.get("id")}
|
return {a["id"] for a in load_approvals() if a.get("decision") == "yes" and a.get("id")}
|
||||||
|
|
||||||
|
|
||||||
def pending_notice():
|
def pending_notice(count=None):
|
||||||
n = len(load_pending())
|
"""The session-start line for decisions waiting for the owner. `count` is every kind together (learning
|
||||||
|
changes, learned drivers, allowance probes: cycle.waiting_count); by default only the learning changes."""
|
||||||
|
n = len(load_pending()) if count is None else count
|
||||||
if not n:
|
if not n:
|
||||||
return ""
|
return ""
|
||||||
return ("sisi: %d learning change(s) wait for the owner's decision. Ask the owner through the host's "
|
return ("sisi: %d decision(s) wait for the owner. Ask through the host's question dialog, then give the owner the "
|
||||||
"question dialog (`sisi approve` lists each change in full; show the owner what it would do) and give "
|
"command to run in a terminal (`sisi approve` lists them). Do not run it for the owner." % n)
|
||||||
"the owner the command to run in a terminal: `sisi approve ID --yes` or `--no`. "
|
|
||||||
"Do not run it for the owner." % n)
|
|
||||||
|
|
||||||
|
|
||||||
# ---- owner statements (one path: learn writes, oracle prints) ---------------------
|
# ---- owner statements (one path: learn writes, oracle prints) ---------------------
|
||||||
|
|||||||
+36
-2
@@ -49,6 +49,37 @@ def hosts():
|
|||||||
return _HOSTS
|
return _HOSTS
|
||||||
|
|
||||||
|
|
||||||
|
def _name_regex(name):
|
||||||
|
"""A tool name from the data file as a case-insensitive regular expression: an exact name, a shell-style pattern
|
||||||
|
(`*delegate_task`, as `_matches` reads it), or a regular expression when it starts with `^`."""
|
||||||
|
n = str(name)
|
||||||
|
if n.startswith("^"):
|
||||||
|
return "(?i)" + n
|
||||||
|
if any(c in n for c in "*?["):
|
||||||
|
return "(?i)" + fnmatch.translate(n)
|
||||||
|
return "(?i)^" + re.escape(n) + "$"
|
||||||
|
|
||||||
|
|
||||||
|
def reach_specs():
|
||||||
|
"""What discovery needs of the hosts' tools, from the same data file the meter reads: one dict per `reach`
|
||||||
|
(the label what is learned is stored under) with "host" (the label), "capability_tool" and "delegation_tool"
|
||||||
|
(regular expressions), "capability" (dotted paths into the listing) and "delegation" ("tool_name", "provider"
|
||||||
|
and "model": dotted paths into the delegation tool's input). A reach lacking either tool is still returned."""
|
||||||
|
out = {}
|
||||||
|
for hd in hosts().values():
|
||||||
|
for name, spec in (hd.get("capability") or {}).items():
|
||||||
|
if isinstance(spec, dict) and spec.get("reach"):
|
||||||
|
r = out.setdefault(spec["reach"], {"host": spec["reach"]})
|
||||||
|
r.update(capability_tool=_name_regex(name), capability={k: v for k, v in spec.items() if k != "reach"})
|
||||||
|
for name, spec in (hd.get("delegation") or {}).items():
|
||||||
|
if isinstance(spec, dict) and spec.get("reach") and spec.get("provider"):
|
||||||
|
r = out.setdefault(spec["reach"], {"host": spec["reach"]})
|
||||||
|
r.update(delegation_tool=_name_regex(name),
|
||||||
|
delegation={"tool_name": str(name).rsplit("__", 1)[-1].lstrip("*"), "provider": spec["provider"],
|
||||||
|
"model": spec.get("model")})
|
||||||
|
return list(out.values())
|
||||||
|
|
||||||
|
|
||||||
def host_data(host):
|
def host_data(host):
|
||||||
return hosts().get(host or "claude-code") or {}
|
return hosts().get(host or "claude-code") or {}
|
||||||
|
|
||||||
@@ -668,10 +699,13 @@ def _before_delegation(payload, hd, tool, inp, host, sid, sess, m, c, cwd):
|
|||||||
return {"deny": route_text()}
|
return {"deny": route_text()}
|
||||||
import uuid
|
import uuid
|
||||||
run_id = uuid.uuid4().hex[:8]
|
run_id = uuid.uuid4().hex[:8]
|
||||||
worker = model or own or "(inherited)"
|
provider = _dig(inp, spec.get("provider")) if spec.get("provider") else None
|
||||||
|
provider = provider.strip() if isinstance(provider, str) else ""
|
||||||
|
# a delegation that names a provider (the host's cross-provider tool) is the worker `provider/model`, as discovery names it
|
||||||
|
worker = ("%s/%s" % (provider, model) if provider and model and "/" not in model else model) or own or "(inherited)"
|
||||||
against = None
|
against = None
|
||||||
if route and route.get("worker"):
|
if route and route.get("worker"):
|
||||||
against = not workers.same_model(worker, route["worker"])
|
against = not workers.same_worker(worker, route["worker"], bool(provider))
|
||||||
try:
|
try:
|
||||||
workers.append_record({"kind": "run", "id": run_id, "ts": round(now),
|
workers.append_record({"kind": "run", "id": run_id, "ts": round(now),
|
||||||
"type": (route or {}).get("kind"), "difficulty": (route or {}).get("difficulty"),
|
"type": (route or {}).get("kind"), "difficulty": (route or {}).get("difficulty"),
|
||||||
|
|||||||
+78
-18
@@ -67,6 +67,7 @@ CONTRADICTION_REJECTIONS = 2 # a thin record with this many rejections below th
|
|||||||
UNKNOWN_ALLOWANCE = 50.0 # allowance weight when a tool reports none
|
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
|
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_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_STANDING_FLOOR = {1: 0.0, 2: 60.0, 3: 85.0} # percent of the best usable standing needed
|
||||||
DEFAULT_CLASS_SPAN = {1: 100.0, 2: 70.0, 3: 35.0} # how far down a maker's class order still counts as capable
|
DEFAULT_CLASS_SPAN = {1: 100.0, 2: 70.0, 3: 35.0} # how far down a maker's class order still counts as capable
|
||||||
DEFAULT_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price
|
DEFAULT_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price
|
||||||
@@ -197,14 +198,19 @@ def class_rank(c, opts=None):
|
|||||||
|
|
||||||
def _pattern_match(c, patterns):
|
def _pattern_match(c, patterns):
|
||||||
"""The (pattern, why) a candidate matches, or None. A pattern matches as a substring of the
|
"""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")))
|
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 []:
|
for entry in patterns or []:
|
||||||
if isinstance(entry, dict):
|
if isinstance(entry, dict):
|
||||||
pat, why = str(entry.get("pattern") or ""), str(entry.get("why") or "")
|
pat, why = str(entry.get("pattern") or ""), str(entry.get("why") or "")
|
||||||
else:
|
else:
|
||||||
pat, why = str(entry), ""
|
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 pat, why
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -226,12 +232,22 @@ def _availability_keys(c):
|
|||||||
return keys
|
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):
|
def _down_entry(c, availability, now):
|
||||||
keys = _availability_keys(c)
|
keys = _availability_keys(c)
|
||||||
|
prov = provider_of(c.get("worker"))
|
||||||
for k, e in (availability or {}).items():
|
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
|
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 e
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -329,7 +345,7 @@ def _cell(stats, worker, kind, difficulty):
|
|||||||
|
|
||||||
# ---------------------------------------------------------------- capability evidence
|
# ---------------------------------------------------------------- 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}
|
_NO_CELL = {"n": 0, "good": 0}
|
||||||
|
|
||||||
|
|
||||||
@@ -371,7 +387,7 @@ def _by_difficulty(stats, worker, kind):
|
|||||||
return own, pooled
|
return own, pooled
|
||||||
|
|
||||||
|
|
||||||
def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None, rank=None, spans=None):
|
def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None, rank=None, spans=None, vouch=0):
|
||||||
"""What the evidence says about one worker for a kind and difficulty. Returns a dict:
|
"""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"
|
tier "a", "b-higher", "b-all", "standing", "unknown" or "none"
|
||||||
capable whether the evidence says it is capable enough
|
capable whether the evidence says it is capable enough
|
||||||
@@ -386,7 +402,9 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f
|
|||||||
The class tier is the last prior: a worker with no judged proof and no standing of its own, whose class has a
|
The class tier is the last prior: a worker with no judged proof and no standing of its own, whose class has a
|
||||||
place in its maker's recorded order (`rank`, from class_rank), is capable when that place is within the span the
|
place in its maker's recorded order (`rank`, from class_rank), is capable when that place is within the span the
|
||||||
difficulty allows (`spans`, see class_spans). Standing is compared only with the best standing; a rate only with
|
difficulty allows (`spans`, see class_spans). Standing is compared only with the best standing; a rate only with
|
||||||
the bar; neither is ever compared with a class."""
|
the bar; neither is ever compared with a class.
|
||||||
|
`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
|
d = difficulty
|
||||||
own, pooled = _by_difficulty(stats, worker, kind)
|
own, pooled = _by_difficulty(stats, worker, kind)
|
||||||
out = {"tier": "none", "capable": False, "bad": False, "weak": False, "contradicted": False,
|
out = {"tier": "none", "capable": False, "bad": False, "weak": False, "contradicted": False,
|
||||||
@@ -421,6 +439,9 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f
|
|||||||
out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell),
|
out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell),
|
||||||
inherited_from=cell.get("from"))
|
inherited_from=cell.get("from"))
|
||||||
return out
|
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:
|
if standing is not None:
|
||||||
pct = _floor_pct(floors, d)
|
pct = _floor_pct(floors, d)
|
||||||
needed = (best_standing or 0.0) * pct / 100.0
|
needed = (best_standing or 0.0) * pct / 100.0
|
||||||
@@ -472,6 +493,13 @@ def _standing_of(c):
|
|||||||
# ---------------------------------------------------------------- the pool, then the choice
|
# ---------------------------------------------------------------- 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 _unusable(c, availability, now):
|
def _unusable(c, availability, now):
|
||||||
"""Why a candidate cannot be used right now (plain words), or None."""
|
"""Why a candidate cannot be used right now (plain words), or None."""
|
||||||
if "contributor" in str(c.get("model") or c["worker"]).lower():
|
if "contributor" in str(c.get("model") or c["worker"]).lower():
|
||||||
@@ -515,7 +543,7 @@ def superseded_by(pool, opts=None):
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts=None):
|
def _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts=None, difficulty=None):
|
||||||
"""The workers that may be recommended at all: (eligible, passed, stats, author_maker, superseded)."""
|
"""The workers that may be recommended at all: (eligible, passed, stats, author_maker, superseded)."""
|
||||||
exclude = {str(x) for x in exclude}
|
exclude = {str(x) for x in exclude}
|
||||||
stats = candidate_stats(candidates, records)
|
stats = candidate_stats(candidates, records)
|
||||||
@@ -532,6 +560,8 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of,
|
|||||||
tried.append(c)
|
tried.append(c)
|
||||||
elif why is not None:
|
elif why is not None:
|
||||||
passed.append((w, why))
|
passed.append((w, why))
|
||||||
|
elif 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"))
|
||||||
else:
|
else:
|
||||||
eligible.append(c)
|
eligible.append(c)
|
||||||
|
|
||||||
@@ -579,7 +609,7 @@ def _assess_all(eligible, stats, kind, difficulty, floors, opts=None):
|
|||||||
best = max(standings) if standings else None
|
best = max(standings) if standings else None
|
||||||
spans = (opts or {}).get("class_span")
|
spans = (opts or {}).get("class_span")
|
||||||
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,
|
||||||
rank=class_rank(c, opts), spans=spans)
|
rank=class_rank(c, opts), spans=spans, vouch=vouch_level(c))
|
||||||
for c in eligible}, best)
|
for c in eligible}, best)
|
||||||
|
|
||||||
|
|
||||||
@@ -639,7 +669,7 @@ def _prefer_judged(capable, assessments, difficulty):
|
|||||||
those capable by the judged record across all kinds; failing that, everyone capable."""
|
those capable by the judged record across all kinds; failing that, everyone capable."""
|
||||||
if difficulty is None or difficulty < 2:
|
if difficulty is None or difficulty < 2:
|
||||||
return list(capable), False
|
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]
|
own = [c for c in capable if assessments[c["worker"]]["tier"] in tiers]
|
||||||
if own:
|
if own:
|
||||||
return own, True
|
return own, True
|
||||||
@@ -668,14 +698,29 @@ def _select(eligible, assessments, difficulty):
|
|||||||
return pool, ("nothing" if top[:2] <= (1, 0) else "strongest")
|
return pool, ("nothing" if top[:2] <= (1, 0) 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=(),
|
def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(),
|
||||||
avoid=None, prefer=None, floors=None, opts=None):
|
avoid=None, prefer=None, floors=None, opts=None, explore_free_every=EXPLORE_FREE_EVERY):
|
||||||
"""Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker", ...}.
|
"""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
|
`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."""
|
`prefer` are the user's own [{"pattern", "why"}] constraints; `floors` the standing floors."""
|
||||||
now = float(now or 0)
|
now = float(now or 0)
|
||||||
eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude,
|
eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude,
|
||||||
avoid, review_of, opts)
|
avoid, review_of, opts, difficulty)
|
||||||
assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors, opts)
|
assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors, opts)
|
||||||
key, rate, load_ratio, recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible))
|
key, rate, load_ratio, recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible))
|
||||||
|
|
||||||
@@ -690,7 +735,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)))
|
ranked = sorted(pool, key=lambda c: (-(assessments[c["worker"]].get("measure") or 0.0), key(c)))
|
||||||
choice = ranked[0] if ranked else None
|
choice = ranked[0] if ranked else None
|
||||||
explored = 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):
|
and _cell(stats, choice["worker"], kind, difficulty)["n"] >= MIN_ATTEMPTS):
|
||||||
total = sum(_cell(stats, c["worker"], kind, difficulty)["n"] for c in candidates)
|
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:
|
if total >= EXPLORE_EVERY - 1 and total % EXPLORE_EVERY == EXPLORE_EVERY - 1:
|
||||||
@@ -718,7 +767,10 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None,
|
|||||||
detail[w] = extra
|
detail[w] = extra
|
||||||
continue
|
continue
|
||||||
if explored is not None and c is explored:
|
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)
|
"gathers evidence on low-stakes work (about one task in %d)" % EXPLORE_EVERY)
|
||||||
elif _pattern_match(choice, prefer) and not _pattern_match(c, prefer):
|
elif _pattern_match(choice, prefer) and not _pattern_match(c, prefer):
|
||||||
_pat, _why = _pattern_match(choice, prefer)
|
_pat, _why = _pattern_match(choice, prefer)
|
||||||
@@ -739,7 +791,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None,
|
|||||||
judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1]
|
judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1]
|
||||||
capable_n = len(pool) if basis == "capable" else 0
|
capable_n = len(pool) if basis == "capable" else 0
|
||||||
return {"choice": choice, "passed_over": passed, "stats": stats, "author_maker": author_maker,
|
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},
|
"load_ratios": {c["worker"]: load_ratio(c) for c in candidates},
|
||||||
"assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first,
|
"assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first,
|
||||||
"best_standing": best, "passed_detail": detail, "floors": floors,
|
"best_standing": best, "passed_detail": detail, "floors": floors,
|
||||||
@@ -777,6 +829,8 @@ def _why_not(a, difficulty, basis, cheaper):
|
|||||||
if a["tier"] == "b-all":
|
if a["tier"] == "b-all":
|
||||||
return (lead + "its only judged proof is across other kinds, and a worker with a judged record "
|
return (lead + "its only judged proof is across other kinds, and a worker with a judged record "
|
||||||
"for this kind is usable", None)
|
"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, its class's place in its maker's order, or as an "
|
return (lead + "capable only by benchmark standing, its class's place in its maker's order, or as an "
|
||||||
"exploration; above difficulty 1 a worker with a judged record is preferred to a benchmark, and a "
|
"exploration; above difficulty 1 a worker with a judged record is preferred to a benchmark, and a "
|
||||||
"benchmark to a class order",
|
"benchmark to a class order",
|
||||||
@@ -817,7 +871,7 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected,
|
|||||||
"strongest" or "only", and choice is None when nobody is usable. Pure; the caller supplies facts."""
|
"strongest" or "only", and choice is None when nobody is usable. Pure; the caller supplies facts."""
|
||||||
now = float(now or 0)
|
now = float(now or 0)
|
||||||
eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude,
|
eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude,
|
||||||
avoid, review_of, opts)
|
avoid, review_of, opts, difficulty)
|
||||||
eff = inherit_stats(candidates, stats, opts)
|
eff = inherit_stats(candidates, stats, opts)
|
||||||
assessments, best = _assess_all(eligible, eff, kind, difficulty, floors, opts)
|
assessments, best = _assess_all(eligible, eff, kind, difficulty, floors, opts)
|
||||||
key, _rate, _load, _recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible))
|
key, _rate, _load, _recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible))
|
||||||
@@ -900,6 +954,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 "
|
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",
|
"needed for difficulty %d" % (a["standing"], src, choice.get("standing_date") or "no date stated",
|
||||||
a["needed"], difficulty))
|
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 == "class":
|
if tier == "class":
|
||||||
return ("evidence (class order): place %d of %d in its maker's recorded class order, which reaches the top %g%% "
|
return ("evidence (class order): place %d of %d in its maker's recorded class order, which reaches the top %g%% "
|
||||||
"for difficulty %d; no judged record or benchmark decides" % (a["class_pos"] + 1, a["class_n"],
|
"for difficulty %d; no judged record or benchmark decides" % (a["class_pos"] + 1, a["class_n"],
|
||||||
@@ -945,8 +1004,9 @@ def explain_choice(result, kind, difficulty):
|
|||||||
if a is not None:
|
if a is not None:
|
||||||
lines.append(evidence_line(a, kind, difficulty, choice, basis))
|
lines.append(evidence_line(a, kind, difficulty, choice, basis))
|
||||||
if result.get("explored"):
|
if result.get("explored"):
|
||||||
lines.append("this is an exploration pick: %s was the usual choice, passed over once so a cheaper "
|
lines.append("this is an exploration pick: %s was the usual choice, passed over once so %s gathers evidence"
|
||||||
"thin-record worker gathers evidence" % result["explored"])
|
% (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"):
|
if result.get("author_maker"):
|
||||||
choice_maker = choice.get("maker") or maker_of(choice.get("model") or choice["worker"])
|
choice_maker = choice.get("maker") or maker_of(choice.get("model") or choice["worker"])
|
||||||
if choice_maker != result["author_maker"]:
|
if choice_maker != result["author_maker"]:
|
||||||
|
|||||||
+17
-3
@@ -180,15 +180,29 @@ def _orchestrate():
|
|||||||
if _has("workers", "retry_context") and _has("routing", "retry_choice") else None,
|
if _has("workers", "retry_context") and _has("routing", "retry_choice") else None,
|
||||||
"the before-tool hook answers one refusal at a time, in a fixed order: workers are exempt, then the contract "
|
"the before-tool hook answers one refusal at a time, in a fixed order: workers are exempt, then the contract "
|
||||||
"guard, then the delegation guard, then the direct-work budget (sisi/watch.py)"
|
"guard, then the delegation guard, then the direct-work budget (sisi/watch.py)"
|
||||||
if meter and _guard_scope() else None],
|
if meter and _guard_scope() else None,
|
||||||
|
"a worker learned by use (a command-line tool's driver, a provider and model the host lists) is unproven: "
|
||||||
|
"offered routine work only unless the owner vouched, its result carries the check-it line, and a learned "
|
||||||
|
"command runs without a shell after a smoke task (sisi/discovery.py, sisi/routing.py)"
|
||||||
|
if _has("discovery", "annotate", "prove") and _has("routing", "vouch_level") else None,
|
||||||
|
"a learned tool that switches off approvals, and an allowance probe, wait for the owner's own decision: the same "
|
||||||
|
"typed word at the terminal as a learning change, refused to an agent by the before-tool hook, every decision "
|
||||||
|
"and refused attempt recorded (sisi/cycle.py, sisi/watch.py, sisi/discovery.py)"
|
||||||
|
if _has("discovery", "waiting_decisions") and _has("cycle", "cmd_approve") else None,
|
||||||
|
"a provider's own failure phrases and its allowance probe decide whether a failure is a limit or a login "
|
||||||
|
"problem and when it is back; only that provider is marked down (sisi/discovery.py, sisi/workers.py)"
|
||||||
|
if _has("discovery", "provider_failure", "limit_until") else None],
|
||||||
measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record (sisi/routing.py, sisi/workers.py)"
|
measured=["the delegation ledger and `sisi delegate judge`, `sisi route` recommends the worker from that record (sisi/routing.py, sisi/workers.py)"
|
||||||
if _has("routing", "choose") and _has("workers", "cmd_delegate") else None,
|
if _has("routing", "choose") and _has("workers", "cmd_delegate") else None,
|
||||||
"the unit record and `sisi status` show direct calls and characters, refusals, extensions with their reasons, "
|
"the unit record and `sisi status` show direct calls and characters, refusals, extensions with their reasons, "
|
||||||
"delegations started, judged and unjudged, and the share of tool calls delegated (sisi/orchestration.py, sisi/scorecard.py)"
|
"delegations started, judged and unjudged, and the share of tool calls delegated (sisi/orchestration.py, sisi/scorecard.py)"
|
||||||
if _has("orchestration", "telemetry") else None,
|
if _has("orchestration", "telemetry") else None,
|
||||||
"`sisi workers` shows how often the router was overridden and how the overrides turned out; a model discovery "
|
"`sisi workers` shows how often the router was overridden and how the overrides turned out; a model discovery "
|
||||||
"has not seen before is named once at session start as unproven (sisi/workers.py)"
|
"has not seen before, and a new command-line tool, are named once at session start (sisi/workers.py, sisi/discovery.py)"
|
||||||
if _has("workers", "override_line", "new_worker_line") else None],
|
if _has("workers", "override_line", "new_worker_line") else None,
|
||||||
|
"the owner's vouch for a worker is shown by `sisi workers` and `sisi route --explain` as its own kind of "
|
||||||
|
"evidence, never as a judged record (sisi/discovery.py, sisi/routing.py)"
|
||||||
|
if _has("discovery", "vouch_lines") else None],
|
||||||
judgement=["who gets the task, how much to check what comes back, the quality of a brief"])
|
judgement=["who gets the task, how much to check what comes back, the quality of a brief"])
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+10
-4
@@ -101,15 +101,21 @@ def main(args=()):
|
|||||||
store.save_session(sid, sess)
|
store.save_session(sid, sess)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
store.log_error("tick-workers", e)
|
store.log_error("tick-workers", e)
|
||||||
try:
|
try: # ONE line for new worker models and new command-line tools (each kind is announced once)
|
||||||
sess3 = rec or store.load_session(sid)
|
sess3 = rec or store.load_session(sid)
|
||||||
from . import workers as _W3, workerid as _WI
|
from . import discovery, workers as _W3, workerid as _WI
|
||||||
if not _WI.is_worker_session(payload, sess3, {}):
|
if not _WI.is_worker_session(payload, sess3, {}):
|
||||||
line = _W3.new_worker_line()
|
models = []
|
||||||
|
try:
|
||||||
|
models = _W3.new_worker_names()
|
||||||
|
except Exception as ex:
|
||||||
|
store.log_error("tick-new-workers", ex)
|
||||||
|
tools = discovery.new_tools() # the first run only stores the list
|
||||||
|
line = discovery.new_line(models, tools)
|
||||||
if line:
|
if line:
|
||||||
sys.stdout.write(line + "\n")
|
sys.stdout.write(line + "\n")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
store.log_error("tick-new-workers", e)
|
store.log_error("tick-discovery", e)
|
||||||
try:
|
try:
|
||||||
from . import cycle
|
from . import cycle
|
||||||
# cycle.due_notice carries both the due-cycle line and the pending-decision line (learning.pending_notice).
|
# cycle.due_notice carries both the due-cycle line and the pending-decision line (learning.pending_notice).
|
||||||
|
|||||||
+21
-4
@@ -126,7 +126,11 @@ def note_shell(sess, cmd, payload):
|
|||||||
|
|
||||||
|
|
||||||
_APPROVE = re.compile(r"(?:^|[\s/;&|(=`$])(?:sisi|sisi\.py|__main__\.py)(?=\s)(?:\s+-{1,2}[\w=-]+)*\s+approve\b([^;&|\n)`]*)")
|
_APPROVE = re.compile(r"(?:^|[\s/;&|(=`$])(?:sisi|sisi\.py|__main__\.py)(?=\s)(?:\s+-{1,2}[\w=-]+)*\s+approve\b([^;&|\n)`]*)")
|
||||||
_DECISION = re.compile(r"\bP-\d+\b[\s\S]*--(?:yes|no)\b|--(?:yes|no)\b[\s\S]*\bP-\d+\b")
|
# what names a change to decide, whatever its kind: P-N (a learning change), drv-NAME (a learned tool),
|
||||||
|
# probe-PROVIDER (an allowance probe) or any other word that is not the documentation's own placeholder
|
||||||
|
_ID = r"(?:P-\d+|(?:drv|probe)-(?!(?:NAME|PROVIDER|ID|X+)\b)[A-Za-z0-9][\w.-]*)"
|
||||||
|
_PLACEHOLDER = re.compile(r"^(?:ID|NAME|PROVIDER|(?:drv|probe|P)-(?:ID|NAME|PROVIDER|N+|X+))$|^\.\.\.$|^\[.*\]$|^<.*>$")
|
||||||
|
_DECISION = re.compile(_ID + r"\b[\s\S]*--(?:yes|no)\b|--(?:yes|no)\b[\s\S]*\b" + _ID)
|
||||||
_FLAG = re.compile(r"--(?:yes|no)\b")
|
_FLAG = re.compile(r"--(?:yes|no)\b")
|
||||||
APPROVE_REFUSED = ("sisi: refused. Approving or refusing a learning change is the owner's alone; an agent does not "
|
APPROVE_REFUSED = ("sisi: refused. Approving or refusing a learning change is the owner's alone; an agent does not "
|
||||||
"run `sisi approve ID --yes|--no`, however it is wrapped. Show the owner what is waiting (run "
|
"run `sisi approve ID --yes|--no`, however it is wrapped. Show the owner what is waiting (run "
|
||||||
@@ -134,6 +138,14 @@ APPROVE_REFUSED = ("sisi: refused. Approving or refusing a learning change is th
|
|||||||
"to type himself in a terminal.")
|
"to type himself in a terminal.")
|
||||||
|
|
||||||
|
|
||||||
|
def _names_something(args):
|
||||||
|
"""Does the first word after `approve` (the id `sisi approve` reads) name a change: any word that is not a
|
||||||
|
flag and not the documentation's placeholder? An id of any shape counts: the refusal does not depend on
|
||||||
|
how it looks."""
|
||||||
|
words = [w for w in args.split() if not w.startswith("-")]
|
||||||
|
return bool(words) and not _PLACEHOLDER.match(words[0])
|
||||||
|
|
||||||
|
|
||||||
def refuse_self_approval(cmd, sid):
|
def refuse_self_approval(cmd, sid):
|
||||||
"""Before-tool guard, for main threads and workers alike: a shell command whose text invokes
|
"""Before-tool guard, for main threads and workers alike: a shell command whose text invokes
|
||||||
sisi's approve command with a decision (`--yes` or `--no` for a change it names) is refused (exit 2,
|
sisi's approve command with a decision (`--yes` or `--no` for a change it names) is refused (exit 2,
|
||||||
@@ -149,13 +161,13 @@ def refuse_self_approval(cmd, sid):
|
|||||||
# a decision has --yes or --no and names the change: an id, or something a shell would fill in
|
# a decision has --yes or --no and names the change: an id, or something a shell would fill in
|
||||||
# (a variable, a command, a brace); prose that only mentions the command (`sisi approve ID --yes`
|
# (a variable, a command, a brace); prose that only mentions the command (`sisi approve ID --yes`
|
||||||
# in a doc, a search pattern) is not an invocation
|
# in a doc, a search pattern) is not an invocation
|
||||||
named = bool(re.search(r"\bP-\d+\b", text))
|
named = bool(re.search(r"\b" + _ID, text))
|
||||||
hit = any(_FLAG.search(m.group(1)) and (named or re.search(r"[${`]", m.group(1)))
|
hit = any(_FLAG.search(m.group(1)) and (named or re.search(r"[${`]", m.group(1)) or _names_something(m.group(1)))
|
||||||
for m in _APPROVE.finditer(text)) \
|
for m in _APPROVE.finditer(text)) \
|
||||||
or bool(re.search(r"\bsisi\b", text) and _DECISION.search(text))
|
or bool(re.search(r"\bsisi\b", text) and _DECISION.search(text))
|
||||||
if not hit:
|
if not hit:
|
||||||
return
|
return
|
||||||
pid = re.search(r"\bP-\d+\b", text)
|
pid = re.search(_ID, text)
|
||||||
from . import cycle
|
from . import cycle
|
||||||
cycle.refuse_attempt(pid.group(0) if pid else "", "an agent's shell command invoked it (refused by the "
|
cycle.refuse_attempt(pid.group(0) if pid else "", "an agent's shell command invoked it (refused by the "
|
||||||
"before-tool hook)", how="hook", session=sid)
|
"before-tool hook)", how="hook", session=sid)
|
||||||
@@ -329,6 +341,11 @@ def run(payload, args=(), host=None):
|
|||||||
after(payload)
|
after(payload)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
store.log_error("watch", e)
|
store.log_error("watch", e)
|
||||||
|
try:
|
||||||
|
from . import discovery
|
||||||
|
discovery.after_tool(payload) # the host's capability listing and delegation tool: what it can reach
|
||||||
|
except Exception as e:
|
||||||
|
store.log_error("watch-discovery", e)
|
||||||
try:
|
try:
|
||||||
from . import unitguard
|
from . import unitguard
|
||||||
unitguard.after(payload)
|
unitguard.after(payload)
|
||||||
|
|||||||
+144
-44
@@ -39,6 +39,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
|
import datetime, json, os, re, shutil, statistics, subprocess, sys, time, uuid
|
||||||
|
|
||||||
from . import brief as brief_contract
|
from . import brief as brief_contract
|
||||||
|
from . import discovery as _D
|
||||||
from . import paths, routing, store
|
from . import paths, routing, store
|
||||||
|
|
||||||
LIST_TIMEOUT_S = 30
|
LIST_TIMEOUT_S = 30
|
||||||
@@ -134,9 +135,10 @@ 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, 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()
|
low = (text or "").lower()
|
||||||
retry = None
|
retry = None
|
||||||
m = re.search(r"retryafterms\D{0,4}(\d+)", low)
|
m = re.search(r"retryafterms\D{0,4}(\d+)", low)
|
||||||
@@ -146,10 +148,11 @@ def classify_failure(text, returncode=0):
|
|||||||
until = parse_reset(text)
|
until = parse_reset(text)
|
||||||
if until is not None:
|
if until is not None:
|
||||||
retry = until - time.time()
|
retry = until - time.time()
|
||||||
for sig in AUTH_SIGNATURES:
|
extra = extra or {}
|
||||||
|
for sig in AUTH_SIGNATURES + tuple(extra.get("auth") or ()):
|
||||||
if sig in low:
|
if sig in low:
|
||||||
return "auth", "not logged in (%s)" % _phrase(text, sig), retry
|
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:
|
if sig in low:
|
||||||
return "limit", _phrase(text, sig), retry
|
return "limit", _phrase(text, sig), retry
|
||||||
for sig in MISSING_SIGNATURES:
|
for sig in MISSING_SIGNATURES:
|
||||||
@@ -164,6 +167,13 @@ def classify_failure(text, returncode=0):
|
|||||||
_ISO_TIME = r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?"
|
_ISO_TIME = r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?"
|
||||||
|
|
||||||
|
|
||||||
|
def failure_for(text, cand=None, returncode=0):
|
||||||
|
"""classify_failure with what is known of the worker: its provider's own recorded phrases first (a provider's
|
||||||
|
error code can be a login problem and not a limit), then the built-in phrases and a learned driver's own."""
|
||||||
|
driver = _D.driver_for(cand.get("tool")) if cand else None
|
||||||
|
return (_D.provider_failure(cand, text) if cand else None) or classify_failure(text, returncode, _D.extra_signatures(driver))
|
||||||
|
|
||||||
|
|
||||||
def parse_reset(text, now=None):
|
def parse_reset(text, now=None):
|
||||||
"""The epoch second a limit message says the worker is back at (an ISO date-time or date, best after the
|
"""The epoch second a limit message says the worker is back at (an ISO date-time or date, best after the
|
||||||
word "reset"), or None when it names none or only a past one."""
|
word "reset"), or None when it names none or only a past one."""
|
||||||
@@ -367,10 +377,9 @@ def _model_names(disc):
|
|||||||
if "contributor" not in str(m).lower()} # a tier that trains on its prompts is never offered
|
if "contributor" not in str(m).lower()} # a tier that trains on its prompts is never offered
|
||||||
|
|
||||||
|
|
||||||
def new_worker_line():
|
def new_worker_names():
|
||||||
"""One line naming up to three models discovery found that the previous discovery did not have, once; they
|
"""The models discovery found that the previous discovery did not have, once (they are unproven until their
|
||||||
are unproven, so low-stakes work first and a closer look at what they return, until their record is no longer
|
record is no longer thin): a list, empty when there is nothing new or it was said already."""
|
||||||
thin. None when there is nothing new (or it was said already)."""
|
|
||||||
disc = load_discovery()
|
disc = load_discovery()
|
||||||
records = read_records()
|
records = read_records()
|
||||||
judged = {}
|
judged = {}
|
||||||
@@ -380,9 +389,18 @@ def new_worker_line():
|
|||||||
new = [w for w in disc.get("new_unannounced") or []
|
new = [w for w in disc.get("new_unannounced") or []
|
||||||
if "contributor" not in w.lower() and judged.get(w.lower(), 0) < routing.MIN_ATTEMPTS]
|
if "contributor" not in w.lower() and judged.get(w.lower(), 0) < routing.MIN_ATTEMPTS]
|
||||||
if not disc.get("new_unannounced"):
|
if not disc.get("new_unannounced"):
|
||||||
return None
|
return []
|
||||||
disc["new_unannounced"] = []
|
disc["new_unannounced"] = []
|
||||||
write_json(discovery_path(), disc)
|
write_json(discovery_path(), disc)
|
||||||
|
return new
|
||||||
|
|
||||||
|
|
||||||
|
def new_worker_line():
|
||||||
|
"""One line naming up to three models discovery found that the previous discovery did not have, once; they
|
||||||
|
are unproven, so low-stakes work first and a closer look at what they return, until their record is no longer
|
||||||
|
thin. None when there is nothing new (or it was said already). Session start uses discovery.new_line, which
|
||||||
|
says this and the new command-line tools in one line."""
|
||||||
|
new = new_worker_names()
|
||||||
if not new:
|
if not new:
|
||||||
return None
|
return None
|
||||||
more = " (and %d more)" % (len(new) - 3) if len(new) > 3 else ""
|
more = " (and %d more)" % (len(new) - 3) if len(new) > 3 else ""
|
||||||
@@ -488,10 +506,11 @@ def _parse_time(value):
|
|||||||
return None
|
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).
|
"""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
|
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
|
now = time.time() if now is None else now
|
||||||
avail = read_availability()
|
avail = read_availability()
|
||||||
for key in keys:
|
for key in keys:
|
||||||
@@ -503,6 +522,8 @@ def record_down(keys, reason, note=None, now=None, retry_after_s=None, until_ts=
|
|||||||
entry["reason"] = reason
|
entry["reason"] = reason
|
||||||
if note:
|
if note:
|
||||||
entry["note"] = note
|
entry["note"] = note
|
||||||
|
if provider and key == str(provider).strip().lower():
|
||||||
|
entry["scope"] = "provider"
|
||||||
if until_ts is not None:
|
if until_ts is not None:
|
||||||
entry["retry_at"] = float(until_ts)
|
entry["retry_at"] = float(until_ts)
|
||||||
else:
|
else:
|
||||||
@@ -540,12 +561,14 @@ def mark_unavailable(worker, text, now=None):
|
|||||||
when the text shows only the model is. The time it is back is parsed from the message when it gives one,
|
when the text shows only the model is. The time it is back is parsed from the message when it gives one,
|
||||||
else the usual widening wait. Returns {"worker", "keys", "reason", "note", "until"} or None when the text
|
else the usual widening wait. Returns {"worker", "keys", "reason", "note", "until"} or None when the text
|
||||||
is no such failure. Never a quality judgement."""
|
is no such failure. Never a quality judgement."""
|
||||||
failure = classify_failure(text)
|
if not worker:
|
||||||
if failure is None or not worker:
|
return None
|
||||||
|
cand = resolve_worker(worker, _cached_candidates()[0]) or {"worker": worker, "model": worker, "tool": None}
|
||||||
|
failure = failure_for(text, cand)
|
||||||
|
if failure is None:
|
||||||
return None
|
return None
|
||||||
reason, note, retry = failure
|
reason, note, retry = failure
|
||||||
now = time.time() if now is None else now
|
now = time.time() if now is None else now
|
||||||
cand = resolve_worker(worker, _cached_candidates()[0]) or {"worker": worker, "model": worker, "tool": None}
|
|
||||||
model = str(cand.get("model") or "")
|
model = str(cand.get("model") or "")
|
||||||
if _MODEL_ONLY.search(text or ""):
|
if _MODEL_ONLY.search(text or ""):
|
||||||
keys = [cand["worker"]]
|
keys = [cand["worker"]]
|
||||||
@@ -556,7 +579,10 @@ def mark_unavailable(worker, text, now=None):
|
|||||||
else:
|
else:
|
||||||
keys = [cand["worker"]]
|
keys = [cand["worker"]]
|
||||||
until = parse_reset(text, now)
|
until = parse_reset(text, now)
|
||||||
avail = record_down(keys, reason, note, now=now, retry_after_s=None if until else retry, until_ts=until)
|
if until is None and reason == "limit":
|
||||||
|
until = _D.limit_until(cand) # the provider's own allowance probe says when it is back
|
||||||
|
avail = record_down(keys, reason, note, now=now, retry_after_s=None if until else retry, until_ts=until,
|
||||||
|
provider=_provider_to_mark(cand))
|
||||||
shown = avail.get(str(keys[-1]).lower()) or {}
|
shown = avail.get(str(keys[-1]).lower()) or {}
|
||||||
return {"worker": cand["worker"], "keys": keys, "reason": reason, "note": note,
|
return {"worker": cand["worker"], "keys": keys, "reason": reason, "note": note,
|
||||||
"until": until if until is not None else shown.get("retry_at")}
|
"until": until if until is not None else shown.get("retry_at")}
|
||||||
@@ -766,6 +792,12 @@ def route_floors():
|
|||||||
return routing.standing_floors(route_cfg().get("standing_floor"))
|
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):
|
def _price_for(prices, tool, model, worker):
|
||||||
models = prices.get("models") if isinstance(prices.get("models"), dict) else {}
|
models = prices.get("models") if isinstance(prices.get("models"), dict) else {}
|
||||||
tools = prices.get("tools") if isinstance(prices.get("tools"), dict) else {}
|
tools = prices.get("tools") if isinstance(prices.get("tools"), dict) else {}
|
||||||
@@ -809,7 +841,7 @@ def build_candidates(disc=None, records=None):
|
|||||||
prices = load_prices()
|
prices = load_prices()
|
||||||
prior = load_strength_prior()
|
prior = load_strength_prior()
|
||||||
model_facts = load_model_facts()[0]
|
model_facts = load_model_facts()[0]
|
||||||
disc_tools = disc.get("tools") or []
|
disc_tools = _D.merge_tools(disc.get("tools") or [])
|
||||||
cands, seen = [], set()
|
cands, seen = [], set()
|
||||||
|
|
||||||
def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None, host_native=False):
|
def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None, host_native=False):
|
||||||
@@ -843,6 +875,8 @@ def build_candidates(disc=None, records=None):
|
|||||||
if not t.get("installed", True):
|
if not t.get("installed", True):
|
||||||
continue
|
continue
|
||||||
models = t.get("models") or []
|
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:
|
if models:
|
||||||
for m in models:
|
for m in models:
|
||||||
add(t["name"], m, usable=bool(t.get("usable", True)), reason=t.get("reason"),
|
add(t["name"], m, usable=bool(t.get("usable", True)), reason=t.get("reason"),
|
||||||
@@ -873,7 +907,7 @@ def build_candidates(disc=None, records=None):
|
|||||||
if c is not None:
|
if c is not None:
|
||||||
c["aliases"].append(str(w))
|
c["aliases"].append(str(w))
|
||||||
alias_set.add(str(w).lower())
|
alias_set.add(str(w).lower())
|
||||||
return cands
|
return _D.annotate(cands, records, disc_tools)
|
||||||
|
|
||||||
|
|
||||||
def resolve_worker(name, candidates):
|
def resolve_worker(name, candidates):
|
||||||
@@ -883,10 +917,11 @@ def resolve_worker(name, candidates):
|
|||||||
return c
|
return c
|
||||||
if "/" in str(name or ""):
|
if "/" in str(name or ""):
|
||||||
tool, model = str(name).split("/", 1)
|
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,
|
return {"worker": str(name), "tool": tool, "model": model,
|
||||||
"maker": routing.maker_of(model), "plan": None, "cost": None,
|
"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]}
|
"reason": None, "aliases": [str(name), model]}
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -974,7 +1009,8 @@ def notes_for(candidates_by_worker, chosen, passed, notes=None, limit=5):
|
|||||||
|
|
||||||
|
|
||||||
DATA_FILES = ("delegations.jsonl", "worker-availability.json", "worker-prices.json",
|
DATA_FILES = ("delegations.jsonl", "worker-availability.json", "worker-prices.json",
|
||||||
"model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-models.json")
|
"model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-models.json", "worker-drivers.json",
|
||||||
|
"worker-providers.json", "worker-vouches.json")
|
||||||
|
|
||||||
|
|
||||||
def _data_state():
|
def _data_state():
|
||||||
@@ -1056,20 +1092,19 @@ def facts_line(now=None, unclassified=0):
|
|||||||
"""One session-start line asking for worker facts to be researched, or "" when they are fresh and every routable
|
"""One session-start line asking for worker facts to be researched, or "" when they are fresh and every routable
|
||||||
worker is classified. `unclassified` is how many routable workers have no recorded maker, class and release date."""
|
worker is classified. `unclassified` is how many routable workers have no recorded maker, class and release date."""
|
||||||
status = facts_status(now)
|
status = facts_status(now)
|
||||||
ask = ("%d routable worker%s no recorded maker, class and release date, so %s never compared with a newer or older "
|
targets = _D.facts_targets(_cached_candidates()[0])
|
||||||
"version: run `sisi workers classify`, hand its output to a fast, cheap worker, then `sisi workers classify "
|
ask = ("%d routable worker%s no recorded maker, class and release date, so never compared with another version "
|
||||||
"--record FILE`." % (unclassified, " has" if unclassified == 1 else "s have", "it is" if unclassified == 1 else "they are"))
|
"(`sisi workers classify`)." % (unclassified, " has" if unclassified == 1 else "s have"))
|
||||||
if status["state"] == "ok":
|
if status["state"] == "ok" and not targets:
|
||||||
return ("sisi: " + ask) if unclassified else ""
|
return ("sisi: " + ask) if unclassified else ""
|
||||||
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)"
|
what = "worker facts are missing (no prices or benchmark standing recorded yet)"
|
||||||
else:
|
else:
|
||||||
what = "worker facts are stale (newest from %s)" % (status["newest"] or "an unstated date")
|
what = "worker facts are stale (newest from %s)" % (status["newest"] or "an unstated date")
|
||||||
return ("sisi: %s: ask a fast, cheap worker to research current prices and "
|
return ("sisi: %s: have a cheap worker research them (`sisi workers fact W --price N|--standing N "
|
||||||
"software-engineering benchmark standing for the workers found here (`sisi workers`) "
|
"--source S`).%s" % (what, (" " + ask) if unclassified else ""))
|
||||||
"and record each with its source: `sisi workers fact WORKER --price N --source S` "
|
|
||||||
"and `sisi workers fact WORKER --standing N --source S`. Until then routing "
|
|
||||||
"goes by the judged record alone.%s" % (what, (" Also: " + ask) if unclassified else ""))
|
|
||||||
|
|
||||||
|
|
||||||
def estimate_cost(tokens, price_entry):
|
def estimate_cost(tokens, price_entry):
|
||||||
@@ -1092,7 +1127,7 @@ def routable_candidates(candidates, records):
|
|||||||
keep = []
|
keep = []
|
||||||
for c in candidates:
|
for c in candidates:
|
||||||
judged = sum(cell["n"] for cell in stats.get(c["worker"], {}).get("by_cell", {}).values())
|
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)
|
keep.append(c)
|
||||||
if not keep:
|
if not keep:
|
||||||
return list(candidates), True, 0
|
return list(candidates), True, 0
|
||||||
@@ -1118,6 +1153,8 @@ def mechanism_for(cand, host=None):
|
|||||||
"""How to start the chosen worker: the host's own subagents first, its cross-provider
|
"""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."""
|
delegation when the config says it has one (workers.host_cross_provider), else sisi itself."""
|
||||||
host = host_tool() if host is None else host
|
host = host_tool() if host is None else host
|
||||||
|
if cand.get("host_mechanism"):
|
||||||
|
return cand["host_mechanism"]
|
||||||
if cand.get("host_native"):
|
if cand.get("host_native"):
|
||||||
return "use the host's own subagent tool with model %s" % (cand.get("model") or cand["worker"])
|
return "use the host's own subagent tool with model %s" % (cand.get("model") or cand["worker"])
|
||||||
if host and cand.get("tool") == host:
|
if host and cand.get("tool") == host:
|
||||||
@@ -1137,6 +1174,15 @@ def same_model(a, b):
|
|||||||
return a == b or a in b or b in a
|
return a == b or a in b or b in a
|
||||||
|
|
||||||
|
|
||||||
|
def same_worker(chosen, routed, provider_named=False):
|
||||||
|
"""Do a delegation's worker and the router's recommendation name one worker? As same_model, except that a
|
||||||
|
model of the same name under another provider is another worker when the call names its provider."""
|
||||||
|
if provider_named and "/" in str(routed) and "/" in str(chosen) \
|
||||||
|
and str(chosen).split("/", 1)[0].lower() != str(routed).split("/", 1)[0].lower():
|
||||||
|
return False
|
||||||
|
return same_model(chosen, routed)
|
||||||
|
|
||||||
|
|
||||||
def _own_workers(candidates, own_model):
|
def _own_workers(candidates, own_model):
|
||||||
return [c["worker"] for c in candidates
|
return [c["worker"] for c in candidates
|
||||||
if own_model and any(same_model(own_model, x) for x in
|
if own_model and any(same_model(own_model, x) for x in
|
||||||
@@ -1150,12 +1196,16 @@ def recommend(kind, difficulty, cwd=None, own_model=None):
|
|||||||
other worker is usable."""
|
other worker is usable."""
|
||||||
records = read_records()
|
records = read_records()
|
||||||
candidates, _tools = _cached_candidates(records)
|
candidates, _tools = _cached_candidates(records)
|
||||||
|
try:
|
||||||
|
_D.apply_allowances(candidates, cached_only=True) # a hook never asks a provider; the last reading stands
|
||||||
|
except Exception as e: # an allowance that cannot be read changes nothing about who is recommended
|
||||||
|
store.log_error("recommend-allowance", e)
|
||||||
candidates, _cold, _x = routable_candidates(candidates, records)
|
candidates, _cold, _x = routable_candidates(candidates, records)
|
||||||
prefs = effective_prefs(kind, difficulty, cwd or os.getcwd())
|
prefs = effective_prefs(kind, difficulty, cwd or os.getcwd())
|
||||||
candidates, _limited = apply_limits(candidates, prefs)
|
candidates, _limited = apply_limits(candidates, prefs)
|
||||||
result = routing.choose(candidates, records, read_availability(), kind, difficulty, now=time.time(),
|
result = routing.choose(candidates, records, read_availability(), kind, difficulty, now=time.time(),
|
||||||
exclude=_own_workers(candidates, own_model), avoid=prefs["avoid"], prefer=prefs["prefer"],
|
exclude=_own_workers(candidates, own_model), avoid=prefs["avoid"], prefer=prefs["prefer"],
|
||||||
floors=route_floors())
|
floors=route_floors(), opts=route_opts(), explore_free_every=explore_free_every())
|
||||||
choice = result["choice"]
|
choice = result["choice"]
|
||||||
if choice is None:
|
if choice is None:
|
||||||
return None, None, 0
|
return None, None, 0
|
||||||
@@ -1375,11 +1425,26 @@ def _append_transcript(path, heading, cmd, out, err, rc):
|
|||||||
% (heading, " ".join(str(c)[:200] for c in cmd), rc, out or "", err or ""))
|
% (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 _provider_to_mark(cand):
|
||||||
|
"""The provider a failure of this worker marks down: its own (a tool that carries several, or a host's), or
|
||||||
|
the part of its model before a slash."""
|
||||||
|
model = str(cand.get("model") or "")
|
||||||
|
return _down_provider(cand) or (model.split("/", 1)[0] if "/" in model else None)
|
||||||
|
|
||||||
|
|
||||||
def _down_keys(cand, reason):
|
def _down_keys(cand, reason):
|
||||||
keys = [cand["worker"]]
|
keys = [cand["worker"]]
|
||||||
model = str(cand.get("model") or "")
|
model = str(cand.get("model") or "")
|
||||||
|
prov = _down_provider(cand)
|
||||||
if reason == "auth" and cand.get("tool"):
|
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:
|
if reason == "limit" and "/" in model:
|
||||||
keys.append(model.split("/", 1)[0])
|
keys.append(model.split("/", 1)[0])
|
||||||
return keys
|
return keys
|
||||||
@@ -1401,7 +1466,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
|
|||||||
prefs = effective_prefs(kind, difficulty, cwd)
|
prefs = effective_prefs(kind, difficulty, cwd)
|
||||||
if cand is not None and cand.get("host_native"):
|
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 "
|
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
|
return None, None, notes
|
||||||
limited = apply_limits(candidates, prefs)[0]
|
limited = apply_limits(candidates, prefs)[0]
|
||||||
candidates = [c for c in limited if not c.get("host_native")]
|
candidates = [c for c in limited if not c.get("host_native")]
|
||||||
@@ -1411,12 +1477,12 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
|
|||||||
result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty,
|
result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty,
|
||||||
review_of=review_of, now=time.time(), exclude=tried,
|
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(),
|
||||||
opts=route_opts())
|
opts=route_opts(), explore_free_every=explore_free_every())
|
||||||
cand = result["choice"]
|
cand = result["choice"]
|
||||||
if cand is None:
|
if cand is None:
|
||||||
native = routing.choose([c for c in limited if c.get("host_native")], read_records(), read_availability(),
|
native = routing.choose([c for c in limited if c.get("host_native")], read_records(), read_availability(),
|
||||||
kind, difficulty, now=time.time(), exclude=tried,
|
kind, difficulty, now=time.time(), exclude=tried,
|
||||||
avoid=prefs["avoid"], prefer=prefs["prefer"])["choice"]
|
avoid=prefs["avoid"], prefer=prefs["prefer"], opts=route_opts())["choice"]
|
||||||
if native is not None: # every command-line worker is out: the host's own subagents take it, at once
|
if native is not None: # every command-line worker is out: the host's own subagents take it, at once
|
||||||
notes.append("sisi: no command-line worker remains for kind %s at difficulty %s. Fall back now with the "
|
notes.append("sisi: no command-line worker remains for kind %s at difficulty %s. Fall back now with the "
|
||||||
"same brief: %s (model %s). Do not ask the person and do not report this to them: "
|
"same brief: %s (model %s). Do not ask the person and do not report this to them: "
|
||||||
@@ -1429,7 +1495,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"
|
notes.append("sisi: refusing %s: its id contains 'contributor', a tier that trains on prompts"
|
||||||
% cand["worker"])
|
% cand["worker"])
|
||||||
return None, None, notes
|
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:
|
if driver is None or shutil.which(driver["exe"]) is None:
|
||||||
record_down(_down_keys(cand, "missing"), "missing",
|
record_down(_down_keys(cand, "missing"), "missing",
|
||||||
"no command-line tool found for %s" % cand["worker"])
|
"no command-line tool found for %s" % cand["worker"])
|
||||||
@@ -1454,16 +1525,20 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
|
|||||||
% (cand["worker"], timeout, transcript))
|
% (cand["worker"], timeout, transcript))
|
||||||
return None, None, notes
|
return None, None, notes
|
||||||
_append_transcript(transcript, cand["worker"], cmd, out, err, rc)
|
_append_transcript(transcript, cand["worker"], cmd, out, err, rc)
|
||||||
failure = classify_failure(out + "\n" + err, rc)
|
failure = failure_for(out + "\n" + err, cand, rc)
|
||||||
if failure is not None:
|
if failure is not None:
|
||||||
reason, note, retry = failure
|
reason, note, retry = failure
|
||||||
until = parse_reset(out + "\n" + err) # the time the message itself names, when it names one
|
until = parse_reset(out + "\n" + err) # the time the message itself names, when it names one
|
||||||
record_down(_down_keys(cand, reason), reason, note, retry_after_s=None if until else retry, until_ts=until)
|
if until is None and reason == "limit":
|
||||||
|
until = _D.limit_until(cand) # else the provider's allowance probe, when one is defined
|
||||||
|
record_down(_down_keys(cand, reason), reason, note, retry_after_s=None if until else retry, until_ts=until,
|
||||||
|
provider=_provider_to_mark(cand))
|
||||||
mark_discovery_stale()
|
mark_discovery_stale()
|
||||||
notes.append("%s is unavailable (%s: %s); trying the next choice" % (cand["worker"], reason, note))
|
notes.append("%s is unavailable (%s: %s); trying the next choice" % (cand["worker"], reason, note))
|
||||||
cand = None
|
cand = None
|
||||||
continue
|
continue
|
||||||
tokens, cost = extract_usage(out + "\n" + err)
|
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"
|
cost_class = "measured" if cost is not None else "unavailable"
|
||||||
if cost is None:
|
if cost is None:
|
||||||
estimated = estimate_cost(tokens, _price_for(load_prices(), cand.get("tool"),
|
estimated = estimate_cost(tokens, _price_for(load_prices(), cand.get("tool"),
|
||||||
@@ -1656,8 +1731,16 @@ def cmd_workers(args=()):
|
|||||||
return _cmd_up(args[1:])
|
return _cmd_up(args[1:])
|
||||||
if args[:1] == ["import"]:
|
if args[:1] == ["import"]:
|
||||||
return _cmd_import(args[1:])
|
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"]:
|
||||||
|
return _D.cmd_forget(args[1:])
|
||||||
migrate_standing_facts()
|
migrate_standing_facts()
|
||||||
disc = discover(force="--refresh" in args)
|
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()
|
records = read_records()
|
||||||
avail = read_availability()
|
avail = read_availability()
|
||||||
prices = load_prices()
|
prices = load_prices()
|
||||||
@@ -1677,6 +1760,8 @@ def cmd_workers(args=()):
|
|||||||
else:
|
else:
|
||||||
state = "usable now"
|
state = "usable now"
|
||||||
print("%s - %s" % (t["name"], state))
|
print("%s - %s" % (t["name"], state))
|
||||||
|
for line in _D.tool_lines(t):
|
||||||
|
print(line)
|
||||||
models = t.get("models") or []
|
models = t.get("models") or []
|
||||||
if models:
|
if models:
|
||||||
shown = models if len(models) <= 24 else models[:24] + ["... and %d more" % (len(models) - 24)]
|
shown = models if len(models) <= 24 else models[:24] + ["... and %d more" % (len(models) - 24)]
|
||||||
@@ -1738,6 +1823,8 @@ def cmd_workers(args=()):
|
|||||||
(" (%s)" % entry["why"]) if entry.get("why") else ""))
|
(" (%s)" % entry["why"]) if entry.get("why") else ""))
|
||||||
for n in load_notes():
|
for n in load_notes():
|
||||||
print("Note (information for the agent): %s" % note_line(n))
|
print("Note (information for the agent): %s" % note_line(n))
|
||||||
|
for ln in _D.vouch_lines():
|
||||||
|
print(ln)
|
||||||
line = facts_line()
|
line = facts_line()
|
||||||
if line:
|
if line:
|
||||||
print(line)
|
print(line)
|
||||||
@@ -1819,7 +1906,8 @@ def _route_retry(args, ctx, kind, difficulty, candidates, records, prefs):
|
|||||||
strongest known."""
|
strongest known."""
|
||||||
rejected = ctx["rejected"]
|
rejected = ctx["rejected"]
|
||||||
res = routing.retry_choice(candidates, records, read_availability(), kind, difficulty, rejected[0], len(rejected),
|
res = routing.retry_choice(candidates, records, read_availability(), kind, difficulty, rejected[0], len(rejected),
|
||||||
now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors())
|
now=time.time(), avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(),
|
||||||
|
opts=route_opts())
|
||||||
pick = res["choice"]
|
pick = res["choice"]
|
||||||
if pick is None:
|
if pick is None:
|
||||||
print("no usable worker for kind %s at difficulty %d after a rejection by %s"
|
print("no usable worker for kind %s at difficulty %d after a rejection by %s"
|
||||||
@@ -1827,6 +1915,8 @@ def _route_retry(args, ctx, kind, difficulty, candidates, records, prefs):
|
|||||||
return None
|
return None
|
||||||
print(pick["worker"])
|
print(pick["worker"])
|
||||||
print("mechanism: %s" % mechanism_for(pick))
|
print("mechanism: %s" % mechanism_for(pick))
|
||||||
|
for line in _D.unproven_lines(pick):
|
||||||
|
print(line)
|
||||||
if res["step"] == "same":
|
if res["step"] == "same":
|
||||||
print(RETRY_BRIEF_LINE)
|
print(RETRY_BRIEF_LINE)
|
||||||
else:
|
else:
|
||||||
@@ -1877,7 +1967,9 @@ def cmd_route(args=()):
|
|||||||
return 1
|
return 1
|
||||||
kind, difficulty = setup
|
kind, difficulty = setup
|
||||||
records = read_records()
|
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())
|
prefs = effective_prefs(kind, difficulty, os.getcwd())
|
||||||
everyone = candidates
|
everyone = candidates
|
||||||
candidates, limited = apply_limits(candidates, prefs)
|
candidates, limited = apply_limits(candidates, prefs)
|
||||||
@@ -1888,7 +1980,7 @@ def cmd_route(args=()):
|
|||||||
result = routing.choose(candidates, records, read_availability(), kind, difficulty,
|
result = routing.choose(candidates, records, read_availability(), kind, difficulty,
|
||||||
review_of=_opt(args, "--review-of"), now=time.time(),
|
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(),
|
||||||
opts=route_opts())
|
opts=route_opts(), explore_free_every=explore_free_every())
|
||||||
result["passed_over"] = list(result["passed_over"]) + limited
|
result["passed_over"] = list(result["passed_over"]) + limited
|
||||||
by_worker = {c["worker"]: c for c in everyone}
|
by_worker = {c["worker"]: c for c in everyone}
|
||||||
down = _down_now(read_availability(), time.time())
|
down = _down_now(read_availability(), time.time())
|
||||||
@@ -1907,9 +1999,11 @@ def cmd_route(args=()):
|
|||||||
route_decision(kind, difficulty, result["choice"]["worker"], ctx["attempt"]["id"] if ctx else None)
|
route_decision(kind, difficulty, result["choice"]["worker"], ctx["attempt"]["id"] if ctx else None)
|
||||||
print(result["choice"]["worker"])
|
print(result["choice"]["worker"])
|
||||||
print("mechanism: %s" % mechanism_for(result["choice"]))
|
print("mechanism: %s" % mechanism_for(result["choice"]))
|
||||||
|
for line in _D.unproven_lines(result["choice"]):
|
||||||
|
print(line)
|
||||||
for line in _down_lines(down):
|
for line in _down_lines(down):
|
||||||
print(line)
|
print(line)
|
||||||
head = 2 + len(_down_lines(down))
|
head = 2 + len(_D.unproven_lines(result["choice"])) + len(_down_lines(down))
|
||||||
explain = "--explain" in args
|
explain = "--explain" in args
|
||||||
# Notes for the chosen worker always print; notes for workers passed over only with --explain.
|
# 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.
|
# Plain output stays within 6 lines: the worker, the mechanism, what is down, then the notes.
|
||||||
@@ -1984,6 +2078,7 @@ def cmd_delegate(args=()):
|
|||||||
print("sisi delegate: not a folder: %s" % cwd, file=sys.stderr)
|
print("sisi delegate: not a folder: %s" % cwd, file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
candidates = build_candidates()
|
candidates = build_candidates()
|
||||||
|
spent = _D.apply_allowances(candidates)
|
||||||
explicit = None
|
explicit = None
|
||||||
worker = _opt(args, "--worker")
|
worker = _opt(args, "--worker")
|
||||||
if worker:
|
if worker:
|
||||||
@@ -1991,7 +2086,10 @@ def cmd_delegate(args=()):
|
|||||||
if explicit is None:
|
if explicit is None:
|
||||||
print("sisi delegate: no such worker found here: %s (see `sisi workers`)" % worker, file=sys.stderr)
|
print("sisi delegate: no such worker found here: %s (see `sisi workers`)" % worker, file=sys.stderr)
|
||||||
return 1
|
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())
|
candidates, _cold, _excluded = routable_candidates(candidates, read_records())
|
||||||
rec, final, notes = run_delegation(candidates, kind, difficulty, prompt, cwd,
|
rec, final, notes = run_delegation(candidates, kind, difficulty, prompt, cwd,
|
||||||
explicit=explicit, review_of=_opt(args, "--review-of"),
|
explicit=explicit, review_of=_opt(args, "--review-of"),
|
||||||
@@ -2002,6 +2100,8 @@ def cmd_delegate(args=()):
|
|||||||
return 1
|
return 1
|
||||||
if final:
|
if final:
|
||||||
print(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("worker: %s" % rec["worker"])
|
||||||
print("transcript: %s" % rec["transcript"])
|
print("transcript: %s" % rec["transcript"])
|
||||||
print("record your judgement: sisi delegate judge %s --outcome accepted|rejected "
|
print("record your judgement: sisi delegate judge %s --outcome accepted|rejected "
|
||||||
|
|||||||
@@ -180,6 +180,15 @@ class Approval(Base):
|
|||||||
"sisi approve $(echo P-0001) --yes",
|
"sisi approve $(echo P-0001) --yes",
|
||||||
"sisi approve P-000{1,2} --yes",
|
"sisi approve P-000{1,2} --yes",
|
||||||
"sisi approve docs; sisi approve $X --yes",
|
"sisi approve docs; sisi approve $X --yes",
|
||||||
|
# a learned tool (drv-NAME) and an allowance probe (probe-PROVIDER) are decided the same way, so the same
|
||||||
|
# wrappers are refused for them, and for an id of any shape
|
||||||
|
'script -qec "sisi approve drv-x --yes" /dev/null </dev/null',
|
||||||
|
"sh -c 'sisi approve probe-zai --yes'",
|
||||||
|
"/path/to/bin/sisi approve drv-x --no",
|
||||||
|
"python3 -m sisi approve probe-a.b --yes",
|
||||||
|
"env SISI_SESSION_ID=x sisi approve drv-x --yes",
|
||||||
|
"sisi${IFS}approve${IFS}probe-zai${IFS}--yes",
|
||||||
|
"sisi approve whatever --yes",
|
||||||
]
|
]
|
||||||
for cmd in wrapped:
|
for cmd in wrapped:
|
||||||
with self.subTest(cmd=cmd):
|
with self.subTest(cmd=cmd):
|
||||||
@@ -196,7 +205,7 @@ class Approval(Base):
|
|||||||
"sisi cycle apply f.json", "sisi cycle check c.json", "echo approve the plan",
|
"sisi cycle apply f.json", "sisi cycle check c.json", "echo approve the plan",
|
||||||
"git commit -m 'approve the design'", "ls",
|
"git commit -m 'approve the design'", "ls",
|
||||||
# prose that only mentions the command is not an invocation
|
# prose that only mentions the command is not an invocation
|
||||||
'grep -rn "sisi approve" docs', "grep -n 'sisi approve ID --yes|--no' SECURITY.md",
|
'grep -rn "sisi approve" docs', "grep -n 'sisi approve drv-NAME --yes' SECURITY.md", "grep -n 'sisi approve ID --yes|--no' SECURITY.md",
|
||||||
"python3 - <<'E'\nprint('give him: sisi approve ID --yes')\nE"):
|
"python3 - <<'E'\nprint('give him: sisi approve ID --yes')\nE"):
|
||||||
with self.subTest(cmd=cmd):
|
with self.subTest(cmd=cmd):
|
||||||
self.assertEqual(self.hook(cmd), 0, cmd)
|
self.assertEqual(self.hook(cmd), 0, cmd)
|
||||||
|
|||||||
@@ -0,0 +1,713 @@
|
|||||||
|
"""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, shutil, 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)
|
||||||
|
git = shutil.which("git")
|
||||||
|
if git: # decisions and the store's history need git; nothing else of the machine's tools is on this PATH
|
||||||
|
os.symlink(git, os.path.join(self.bindir, "git"))
|
||||||
|
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_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)
|
||||||
|
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.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)
|
||||||
|
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_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]]}
|
||||||
|
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_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"), "")
|
||||||
|
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_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")
|
||||||
|
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("typed at 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()
|
||||||
|
owner = terminal() # the owner's own terminal: the full action is shown and the word typed back
|
||||||
|
with owner:
|
||||||
|
r = self.sisi("approve", "drv-fakeagent", "--yes")
|
||||||
|
t = owner.fake
|
||||||
|
self.assertIn("fakeagent --dangerously-skip-permissions -p {prompt}", t.text)
|
||||||
|
self.assertIn("Type the word", t.text)
|
||||||
|
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()
|
||||||
|
with terminal():
|
||||||
|
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_three_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 4 more", line)
|
||||||
|
self.assertEqual(sum(1 for i in range(7) if "p%d/m" % i in line), 3)
|
||||||
|
self.assertIn("sisi workers fact W --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()
|
||||||
@@ -346,7 +346,7 @@ class ConfigDefault(SisiCase):
|
|||||||
for section in ("gate", "verify", "retro", "route", "unit", "orchestrate"):
|
for section in ("gate", "verify", "retro", "route", "unit", "orchestrate"):
|
||||||
self.assertIn(section, cfg)
|
self.assertIn(section, cfg)
|
||||||
self.assertEqual(sorted(cfg["orchestrate"]), ["direct_calls", "direct_chars", "enabled", "extension", "route_window_min"])
|
self.assertEqual(sorted(cfg["orchestrate"]), ["direct_calls", "direct_chars", "enabled", "extension", "route_window_min"])
|
||||||
self.assertEqual(sorted(cfg["route"]), ["class_span", "price_blend_input_parts", "standing_floor"])
|
self.assertEqual(sorted(cfg["route"]), ["class_span", "explore_free_one_in", "price_blend_input_parts", "standing_floor"])
|
||||||
self.assertEqual(cfg["unit"], {"stale_hours": 12})
|
self.assertEqual(cfg["unit"], {"stale_hours": 12})
|
||||||
self.assertEqual(store.config()["orchestrate"]["direct_calls"], 6)
|
self.assertEqual(store.config()["orchestrate"]["direct_calls"], 6)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,517 @@
|
|||||||
|
"""The two lines of work merged: the discovery of new workers, and the reconciled learning cycle, orchestration
|
||||||
|
meter and routing. One test class per point where they meet.
|
||||||
|
|
||||||
|
Requirements: R-11.5-11 and R-16-11 (the owner alone decides what widens what runs: one approval path for
|
||||||
|
learning changes, learned tools and allowance probes), R-7.2-1 to R-7.2-3 (a worker learned by use is routed,
|
||||||
|
guarded, recorded and fallen back from like any other), R-16-8 (every decision and refused attempt is recorded),
|
||||||
|
R-16-9 (hooks fail open)."""
|
||||||
|
import contextlib, io, json, os, shutil, subprocess, sys, time, unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
import test_discovery as TD
|
||||||
|
import test_providers as TP
|
||||||
|
from support import *
|
||||||
|
from sisi import cycle, discovery, fallback, orchestration, routing, watch, workers
|
||||||
|
from sisi import learning as L
|
||||||
|
|
||||||
|
REPO = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||||
|
BIN = os.path.join(REPO, "bin", "sisi")
|
||||||
|
|
||||||
|
|
||||||
|
def shell(cmd, sid="sess-hook"):
|
||||||
|
return {"session_id": sid, "cwd": "/tmp", "hook_event_name": "PreToolUse", "tool_name": "Bash",
|
||||||
|
"tool_input": {"command": cmd}}
|
||||||
|
|
||||||
|
|
||||||
|
class MergeCase(TD.DiscoveryCase):
|
||||||
|
def waiting_driver(self):
|
||||||
|
self.exe("fakeagent")
|
||||||
|
f = TD.driver_file(os.path.join(self.tmp, "d.json"), run=["fakeagent", "--dangerously-skip-permissions", "-p", "{prompt}"],
|
||||||
|
approvals_off_reason="cannot run unattended without it")
|
||||||
|
r = self.sisi("workers", "learn", "fakeagent", "--record", f)
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
|
||||||
|
def waiting_probe(self):
|
||||||
|
self.exe("authexport", "#!/bin/sh\necho x\n")
|
||||||
|
r = self.sisi("workers", "allowance", "zai", "--command", "authexport", "--remaining-path", "left",
|
||||||
|
"--reset-path", "reset")
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
|
||||||
|
def waiting_change(self):
|
||||||
|
L.save_pending([{"id": "P-0001", "learning": None, "action": {"action": "disable-rule", "rule_id": "nothing"},
|
||||||
|
"reasons": ["a test"], "scope": None}], "test")
|
||||||
|
|
||||||
|
def hook(self, cmd, sid="sess-hook"):
|
||||||
|
try:
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()):
|
||||||
|
watch.before(shell(cmd, sid))
|
||||||
|
except SystemExit as e:
|
||||||
|
return e.code
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 1. one approval path
|
||||||
|
|
||||||
|
|
||||||
|
class OneApprovalPath(MergeCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.waiting_driver()
|
||||||
|
self.waiting_probe()
|
||||||
|
self.waiting_change()
|
||||||
|
|
||||||
|
def test_one_listing_shows_all_three_kinds_in_full(self):
|
||||||
|
out = self.sisi("approve").stdout
|
||||||
|
for part in ("P-0001", "drv-fakeagent", "probe-zai", "fakeagent --dangerously-skip-permissions -p {prompt}",
|
||||||
|
"authexport"):
|
||||||
|
self.assertIn(part, out)
|
||||||
|
line = L.pending_notice(cycle.waiting_count())
|
||||||
|
self.assertIn("3 decision(s)", line)
|
||||||
|
|
||||||
|
def test_the_discovery_branchs_own_copy_of_the_owner_logic_is_gone(self):
|
||||||
|
for name in ("approve_hook", "_owner_may_decide"):
|
||||||
|
self.assertFalse(hasattr(discovery, name), name)
|
||||||
|
src = open(os.path.join(REPO, "sisi", "discovery.py"), encoding="utf-8").read()
|
||||||
|
for word in ("relay_allowed", "agent_relayed_approval", "_open_terminal", "_stdin_is_tty", "isatty"):
|
||||||
|
self.assertNotIn(word, src, word)
|
||||||
|
|
||||||
|
def test_every_kind_needs_the_word_typed_at_the_terminal_and_shows_the_full_action(self):
|
||||||
|
for pid in ("drv-fakeagent", "probe-zai"):
|
||||||
|
with self.subTest(pid=pid):
|
||||||
|
owner = terminal("wrong")
|
||||||
|
with owner:
|
||||||
|
r = self.sisi("approve", pid, "--yes")
|
||||||
|
self.assertEqual(r.returncode, 2, r.stdout + r.stderr)
|
||||||
|
self.assertIn("Type the word", owner.fake.text)
|
||||||
|
self.assertIn("authexport" if pid.startswith("probe") else "--dangerously-skip-permissions", owner.fake.text)
|
||||||
|
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||||
|
self.assertEqual(discovery.load_providers()["zai"]["allowance"]["state"], "waiting-owner")
|
||||||
|
self.assertEqual(self.runs(), [], "nothing ran")
|
||||||
|
refused = [r for r in L.load_approvals() if r.get("decision") == "refused"]
|
||||||
|
self.assertEqual(sorted(r["id"] for r in refused), ["drv-fakeagent", "probe-zai"])
|
||||||
|
|
||||||
|
def test_the_owners_decision_is_recorded_like_a_change(self):
|
||||||
|
with terminal():
|
||||||
|
self.assertEqual(self.sisi("approve", "probe-zai", "--yes").returncode, 0)
|
||||||
|
with terminal():
|
||||||
|
r = self.sisi("approve", "drv-fakeagent", "--yes")
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "usable")
|
||||||
|
self.assertEqual(discovery.load_providers()["zai"]["allowance"]["state"], "usable")
|
||||||
|
rows = {a["id"]: a for a in L.load_approvals()}
|
||||||
|
for pid in ("drv-fakeagent", "probe-zai"):
|
||||||
|
self.assertEqual(rows[pid]["decision"], "yes")
|
||||||
|
self.assertTrue(rows[pid]["terminal"])
|
||||||
|
self.assertIn("action", rows[pid])
|
||||||
|
self.assertEqual(rows["drv-fakeagent"]["action"]["command"][:2], ["fakeagent", "--dangerously-skip-permissions"])
|
||||||
|
|
||||||
|
def test_the_owners_no_removes_either_kind_and_is_recorded(self):
|
||||||
|
with terminal():
|
||||||
|
self.assertEqual(self.sisi("approve", "probe-zai", "--no").returncode, 0)
|
||||||
|
with terminal():
|
||||||
|
self.assertEqual(self.sisi("approve", "drv-fakeagent", "--no").returncode, 0)
|
||||||
|
self.assertEqual(discovery.load_drivers(), {})
|
||||||
|
self.assertNotIn("allowance", discovery.load_providers().get("zai", {}))
|
||||||
|
self.assertEqual(sorted((a["id"], a["decision"]) for a in L.load_approvals()),
|
||||||
|
[("drv-fakeagent", "no"), ("probe-zai", "no")])
|
||||||
|
|
||||||
|
def test_without_a_terminal_it_is_refused_and_recorded_whatever_the_id(self):
|
||||||
|
for pid in ("drv-fakeagent", "probe-zai", "drv-nothing", "whatever"):
|
||||||
|
r = self.sisi("approve", pid, "--yes", env={"SISI_SESSION_ID": "sess-7"})
|
||||||
|
self.assertEqual(r.returncode, 2, pid)
|
||||||
|
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||||
|
self.assertEqual(self.runs(), [])
|
||||||
|
refused = [r for r in L.load_approvals() if r["decision"] == "refused"]
|
||||||
|
self.assertEqual(len(refused), 4)
|
||||||
|
self.assertTrue(all(r["session"] == "sess-7" for r in refused))
|
||||||
|
|
||||||
|
def test_a_probe_is_never_usable_before_the_owner_decides(self):
|
||||||
|
# the definition and the decision are two steps, even for a person typing the definition
|
||||||
|
self.assertEqual(discovery.load_providers()["zai"]["allowance"]["state"], "waiting-owner")
|
||||||
|
|
||||||
|
def test_the_hook_refuses_any_id_in_every_wrapping(self):
|
||||||
|
ids = ["P-0001", "drv-x", "drv-fakeagent", "probe-zai", "probe-a.b", "whatever", "$ID", "drv-NAMES"]
|
||||||
|
wrappers = ['script -qec "sisi approve %s --yes" /dev/null </dev/null', "sh -c 'sisi approve %s --yes'",
|
||||||
|
"/path/to/bin/sisi approve %s --yes", "python3 -m sisi approve %s --no",
|
||||||
|
"env SISI_SESSION_ID=x sisi approve %s --yes", "expect -c 'spawn sisi approve %s --yes; expect eof'",
|
||||||
|
"bash -lc \"cd /tmp && sisi approve %s --yes\"", "sisi${IFS}approve${IFS}%s${IFS}--yes",
|
||||||
|
"cd x; sisi approve %s --yes; echo done"]
|
||||||
|
n = 0
|
||||||
|
for pid in ids:
|
||||||
|
for w in wrappers:
|
||||||
|
cmd = w % pid
|
||||||
|
with self.subTest(cmd=cmd):
|
||||||
|
self.assertEqual(self.hook(cmd), 2, cmd)
|
||||||
|
n += 1
|
||||||
|
refused = [r for r in L.load_approvals() if r["decision"] == "refused" and r["how"] == "hook"]
|
||||||
|
self.assertEqual(len(refused), n)
|
||||||
|
self.assertTrue(all(r["session"] == "sess-hook" for r in refused))
|
||||||
|
self.assertIn("drv-x", {r["id"] for r in refused})
|
||||||
|
self.assertIn("probe-zai", {r["id"] for r in refused})
|
||||||
|
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||||
|
|
||||||
|
def test_the_listing_and_prose_are_not_refused(self):
|
||||||
|
for cmd in ("sisi approve", "sisi approve | head", "grep -n 'sisi approve drv-NAME --yes' SECURITY.md",
|
||||||
|
"grep -rn 'sisi approve ID --yes|--no' docs",
|
||||||
|
"python3 - <<'E'\nprint('give him: sisi approve probe-PROVIDER --yes')\nE",
|
||||||
|
"sisi workers allowance zai --command x"):
|
||||||
|
with self.subTest(cmd=cmd):
|
||||||
|
self.assertEqual(self.hook(cmd), 0, cmd)
|
||||||
|
|
||||||
|
def test_the_hook_process_refuses_with_exit_2(self):
|
||||||
|
for cmd in ('sh -c "sisi approve drv-fakeagent --yes"', "%s approve probe-zai --yes" % BIN,
|
||||||
|
'script -qec "sisi approve drv-x --no" /dev/null'):
|
||||||
|
r = self.sisi_proc("watch", "--before", stdin=json.dumps(shell(cmd)))
|
||||||
|
self.assertEqual(r.returncode, 2, cmd + r.stderr)
|
||||||
|
self.assertIn("owner's alone", r.stderr)
|
||||||
|
|
||||||
|
@unittest.skipUnless(os.path.exists("/usr/bin/script") or os.path.exists("/bin/script"), "no script(1)")
|
||||||
|
def test_script_gives_a_terminal_but_not_the_owners_hands(self):
|
||||||
|
script = "/usr/bin/script" if os.path.exists("/usr/bin/script") else "/bin/script"
|
||||||
|
for pid in ("drv-fakeagent", "probe-zai"):
|
||||||
|
p = subprocess.run([script, "-qec", "%s %s approve %s --yes" % (sys.executable, BIN, pid), "/dev/null"],
|
||||||
|
cwd=self.proj, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60,
|
||||||
|
env=dict(os.environ))
|
||||||
|
self.assertIn("refused", p.stdout + p.stderr, pid)
|
||||||
|
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||||
|
self.assertEqual(discovery.load_providers()["zai"]["allowance"]["state"], "waiting-owner")
|
||||||
|
self.assertEqual(self.runs(), [])
|
||||||
|
|
||||||
|
def test_no_terminal_in_a_real_process_is_refused(self):
|
||||||
|
p = self.sisi_proc("approve", "drv-fakeagent", "--yes")
|
||||||
|
self.assertEqual(p.returncode, 2, p.stdout + p.stderr)
|
||||||
|
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||||
|
|
||||||
|
|
||||||
|
class CollidingNameIsRefused(MergeCase):
|
||||||
|
def test_a_driver_for_a_name_a_builtin_driver_has_is_refused_with_the_reason(self):
|
||||||
|
builtin = workers.DRIVERS[0]["name"]
|
||||||
|
self.exe(builtin)
|
||||||
|
f = TD.driver_file(os.path.join(self.tmp, "d.json"), name=builtin, exe=builtin, run=[builtin, "-p", "{prompt}"])
|
||||||
|
r = self.sisi("workers", "learn", builtin, "--record", f)
|
||||||
|
self.assertNotEqual(r.returncode, 0, r.stdout)
|
||||||
|
self.assertRegex(r.stdout + r.stderr, "built-in|already")
|
||||||
|
self.assertEqual(discovery.load_drivers(), {})
|
||||||
|
self.assertEqual(self.runs(), [])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 2. one description of a host's tools
|
||||||
|
|
||||||
|
|
||||||
|
class OneHostDescription(MergeCase):
|
||||||
|
def test_both_modules_read_the_same_file_and_discovery_json_holds_no_hosts(self):
|
||||||
|
with open(os.path.join(REPO, "canon", "discovery.json"), encoding="utf-8") as f:
|
||||||
|
self.assertNotIn("hosts", json.load(f))
|
||||||
|
hosts = discovery.data()["hosts"]
|
||||||
|
self.assertEqual(hosts, orchestration.reach_specs())
|
||||||
|
h = next(x for x in hosts if x["host"] == "t3-code")
|
||||||
|
self.assertRegex("mcp__t3-code__orchestrator_capabilities", h["capability_tool"])
|
||||||
|
self.assertRegex("mcp__t3-code__delegate_task", h["delegation_tool"])
|
||||||
|
self.assertEqual(h["delegation"]["provider"], "target.providerInstanceId")
|
||||||
|
hd = orchestration.host_data("claude-code")
|
||||||
|
self.assertIsNotNone(orchestration.delegation_spec(hd, "mcp__t3-code__delegate_task"))
|
||||||
|
self.assertEqual(orchestration.delegation_spec(hd, "mcp__t3-code__delegate_task")["model"], h["delegation"]["model"])
|
||||||
|
|
||||||
|
def test_changing_the_one_file_changes_what_both_modules_recognise(self):
|
||||||
|
other = {"claude-code": {"refuse": "json-deny", "evidence": "test",
|
||||||
|
"delegation": {"mcp__other__x_delegate": {"model": "m", "brief": "b", "provider": "p", "reach": "other"}},
|
||||||
|
"capability": {"^mcp__other__list$": dict(orchestration.hosts()["claude-code"]["capability"]
|
||||||
|
["mcp__t3-code__orchestrator_capabilities"], reach="other")},
|
||||||
|
"exempt": {}}}
|
||||||
|
with mock.patch.object(orchestration, "hosts", return_value=other):
|
||||||
|
discovery._DATA.clear()
|
||||||
|
self.addCleanup(discovery._DATA.clear)
|
||||||
|
self.feed("mcp__other__list_all", TD.LISTING) # no such tool in the data: ignored
|
||||||
|
self.assertFalse(os.path.exists(discovery.host_state_file()))
|
||||||
|
self.feed("mcp__other__list", TD.LISTING)
|
||||||
|
self.assertIn("alpha", self.host_state()["hosts"]["other"]["providers"])
|
||||||
|
self.assertEqual(orchestration.classify("claude-code", "mcp__other__x_delegate", {}, ""), "delegation")
|
||||||
|
self.feed("mcp__other__x_delegate", None, {"p": "gamma", "m": "g-1"})
|
||||||
|
self.assertIn("gamma", self.host_state()["hosts"]["other"]["providers"])
|
||||||
|
discovery._DATA.clear()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 3. a worker learned by discovery is a worker everywhere
|
||||||
|
|
||||||
|
|
||||||
|
class HookCase(MergeCase):
|
||||||
|
"""Hook calls in the way the host sends them, in process, with a host that lists providers and a learned tool."""
|
||||||
|
own = "gamma-top"
|
||||||
|
sid = "sess-1"
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.git_init()
|
||||||
|
os.makedirs(self.data, exist_ok=True)
|
||||||
|
with open(os.path.join(self.data, "workers.json"), "w") as f:
|
||||||
|
json.dump({"checked": time.time(), "tools": []}, f)
|
||||||
|
self.sisi("tick", "--tool", "claude-code", stdin=json.dumps(
|
||||||
|
{"session_id": self.sid, "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup", "model": self.own}))
|
||||||
|
|
||||||
|
def payload(self, ev, tool, inp, **kw):
|
||||||
|
d = {"session_id": self.sid, "cwd": self.proj, "hook_event_name": ev, "tool_name": tool, "tool_input": inp}
|
||||||
|
d.update(kw)
|
||||||
|
return json.dumps(d)
|
||||||
|
|
||||||
|
def prompt(self, text="fix the parser and explain each module in the project"):
|
||||||
|
self.sisi("prompt", "--tool", "claude-code", stdin=json.dumps(
|
||||||
|
{"session_id": self.sid, "cwd": self.proj, "hook_event_name": "UserPromptSubmit", "prompt": text}))
|
||||||
|
|
||||||
|
def route(self, kind="read", difficulty="1", *extra):
|
||||||
|
r = self.sisi("route", "--kind", kind, "--difficulty", difficulty, *extra, env={"SISI_SESSION_ID": self.sid})
|
||||||
|
return r
|
||||||
|
|
||||||
|
def pre(self, tool, inp, **kw):
|
||||||
|
r = self.sisi("watch", "--before", "--tool", "claude-code", stdin=self.payload("PreToolUse", tool, inp, **kw))
|
||||||
|
self.assertEqual(r.returncode, 0, r.stderr)
|
||||||
|
out = json.loads(r.stdout) if r.stdout.strip() else {}
|
||||||
|
hs = out.get("hookSpecificOutput") or {}
|
||||||
|
return hs.get("permissionDecision") == "deny", hs.get("permissionDecisionReason") or hs.get("additionalContext") or ""
|
||||||
|
|
||||||
|
def host_deleg(self, provider, model, **kw):
|
||||||
|
return self.pre("mcp__t3-code__delegate_task", {"target": {"providerInstanceId": provider, "model": model},
|
||||||
|
"task": "Outcome: x\nAcceptance: y\nFiles you may change: none"}, **kw)
|
||||||
|
|
||||||
|
def listing(self):
|
||||||
|
self.feed(TD.LISTING_TOOL, TD.LISTING)
|
||||||
|
|
||||||
|
|
||||||
|
class LearnedWorkersEverywhere(HookCase):
|
||||||
|
def test_the_meters_router_lines_may_be_a_host_worker_with_its_mechanism(self):
|
||||||
|
self.listing()
|
||||||
|
self.prompt()
|
||||||
|
denied, text = self.pre("mcp__t3-code__delegate_task", {"target": {"model": ""}, "task": "x"})
|
||||||
|
self.assertTrue(denied, text)
|
||||||
|
self.assertRegex(text, r"alpha/m-[12]")
|
||||||
|
self.assertIn("cross-provider delegation", text)
|
||||||
|
self.assertIn("target.providerInstanceId=alpha", text)
|
||||||
|
self.assertNotIn("beta/", text, "a provider the host says cannot run a task is never offered")
|
||||||
|
|
||||||
|
def test_the_meters_router_lines_may_be_a_learned_tool_with_its_mechanism(self):
|
||||||
|
self.learn()
|
||||||
|
self.prompt()
|
||||||
|
denied, text = self.pre("mcp__t3-code__delegate_task", {"target": {"model": ""}, "task": "x"})
|
||||||
|
self.assertTrue(denied, text)
|
||||||
|
self.assertRegex(text, r"fakeagent/(default|fa-[12]).*sisi delegate")
|
||||||
|
|
||||||
|
def test_a_delegation_naming_a_host_model_is_recognised_recorded_and_compared_with_the_route(self):
|
||||||
|
self.listing()
|
||||||
|
self.prompt()
|
||||||
|
routed = self.route().stdout.splitlines()[0]
|
||||||
|
self.assertRegex(routed, r"^alpha/m-[12]$")
|
||||||
|
prov, model = routed.split("/")
|
||||||
|
denied, ctx = self.host_deleg(prov, model, tool_use_id="t1")
|
||||||
|
self.assertFalse(denied, ctx)
|
||||||
|
self.assertIn("recorded as run", ctx)
|
||||||
|
run = [r for r in workers.read_records() if r.get("kind") == "run"][-1]
|
||||||
|
self.assertEqual(run["worker"], routed, "the ledger names the worker as discovery does: provider/model")
|
||||||
|
self.assertIs(run["chosen_against_route"], False)
|
||||||
|
self.assertEqual(run["route_worker"], routed)
|
||||||
|
self.route()
|
||||||
|
denied, ctx = self.host_deleg("beta", model, tool_use_id="t2") # the same model name under another provider
|
||||||
|
self.assertFalse(denied, ctx)
|
||||||
|
run = [r for r in workers.read_records() if r.get("kind") == "run"][-1]
|
||||||
|
self.assertEqual(run["worker"], "beta/" + model)
|
||||||
|
self.assertIs(run["chosen_against_route"], True)
|
||||||
|
self.assertIn("you chose beta/%s over the router's %s" % (model, routed), ctx)
|
||||||
|
|
||||||
|
def test_a_host_delegation_naming_the_sessions_own_model_is_refused(self):
|
||||||
|
self.listing()
|
||||||
|
self.prompt()
|
||||||
|
denied, text = self.host_deleg("alpha", self.own)
|
||||||
|
self.assertTrue(denied)
|
||||||
|
self.assertIn("own model", text)
|
||||||
|
|
||||||
|
def test_a_model_the_owners_own_only_limit_excludes_is_stored_but_never_routable(self):
|
||||||
|
r = self.sisi("workers", "only", "alpha", "m-1", "--why", "the owner checked only this one")
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.listing()
|
||||||
|
self.assertIn("m-2", self.host_state()["hosts"]["t3-code"]["providers"]["alpha"]["models"], "stored")
|
||||||
|
self.assertIn("alpha/m-2", {c["worker"] for c in workers.build_candidates()}, "known as a worker")
|
||||||
|
for kind, d in (("read", 1), ("impl", 1), ("impl", 2)):
|
||||||
|
self.assertNotEqual(self.route(kind, str(d)).stdout.splitlines()[0], "alpha/m-2")
|
||||||
|
if d == 1:
|
||||||
|
self.assertEqual(self.route(kind, str(d)).stdout.splitlines()[0], "alpha/m-1")
|
||||||
|
self.assertNotEqual(workers.recommend(kind, d, self.proj, self.own)[0], "alpha/m-2")
|
||||||
|
explained = self.route("read", "1", "--explain").stdout
|
||||||
|
self.assertIn("alpha/m-2", explained)
|
||||||
|
self.assertRegex(explained, r"(?i)only")
|
||||||
|
|
||||||
|
def test_a_failure_notice_for_a_host_worker_marks_its_provider_down_with_the_errors_own_time(self):
|
||||||
|
self.listing()
|
||||||
|
when = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 7200))
|
||||||
|
with orchestration.Meter(self.sid) as m:
|
||||||
|
text = fallback.handle(m, self.sid, self.proj, "alpha m-1 failed: usage limit reached, resets at %s" % when,
|
||||||
|
own_model=self.own)
|
||||||
|
self.assertIn("alpha/m-1", text)
|
||||||
|
down = workers.read_availability()
|
||||||
|
self.assertEqual(down["alpha"]["scope"], "provider")
|
||||||
|
self.assertAlmostEqual(down["alpha"]["retry_at"], time.time() + 7200, delta=5)
|
||||||
|
picked = self.route().stdout.splitlines()
|
||||||
|
self.assertFalse(picked and picked[0].startswith("alpha/"), picked) # neither of its models is chosen now
|
||||||
|
|
||||||
|
def test_a_learned_tools_own_phrase_is_a_failure_for_the_automatic_fallback(self):
|
||||||
|
self.learn()
|
||||||
|
text = "fakeagent/fa-1 said: weekly allowance used up for this plan"
|
||||||
|
self.assertIsNone(workers.classify_failure(text), "the built-in phrases do not know it")
|
||||||
|
with orchestration.Meter(self.sid) as m:
|
||||||
|
out = fallback.handle(m, self.sid, self.proj, text, own_model=self.own)
|
||||||
|
self.assertIsNotNone(out, "the learned driver's phrase counts")
|
||||||
|
self.assertEqual(workers.read_availability()["fakeagent/fa-1"]["reason"], "limit")
|
||||||
|
|
||||||
|
def test_a_learned_worker_and_a_host_worker_are_classified_and_take_part_in_the_newest_version_rule(self):
|
||||||
|
self.learn()
|
||||||
|
self.listing()
|
||||||
|
asked = self.sisi("workers", "classify").stdout
|
||||||
|
for w in ("fakeagent/fa-1", "fakeagent/fa-2", "fakeagent/default", "alpha/m-1"):
|
||||||
|
self.assertIn(w, asked.splitlines(), w)
|
||||||
|
answer = os.path.join(self.tmp, "answer.json")
|
||||||
|
with open(answer, "w") as f:
|
||||||
|
json.dump({"workers": {"fakeagent/fa-1": {"maker": "fa", "class": "standard", "released": "2026-01-01"},
|
||||||
|
"fakeagent/fa-2": {"maker": "fa", "class": "standard", "released": "2026-06-01"},
|
||||||
|
"fakeagent/default": {"maker": "unknown", "class": "unknown", "released": "unknown"},
|
||||||
|
"alpha/m-1": {"maker": "al", "class": "standard", "released": "2026-03-01"},
|
||||||
|
"alpha/m-2": {"maker": "al", "class": "standard", "released": "2026-04-01"}}}, f)
|
||||||
|
r = self.sisi("workers", "classify", "--record", answer, "--by", "a test")
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.assertNotIn("fakeagent/fa-1", self.sisi("workers", "classify").stdout.splitlines())
|
||||||
|
explained = self.route("read", "1", "--explain").stdout
|
||||||
|
self.assertNotEqual(explained.splitlines()[0], "fakeagent/fa-1")
|
||||||
|
self.assertIn("superseded by fakeagent/fa-2", explained, "the older version of a learned worker is replaced by the newer")
|
||||||
|
self.assertIn("superseded by alpha/m-2", explained, "and so is a host worker's")
|
||||||
|
|
||||||
|
def test_route_retry_of_names_a_learned_worker_with_its_check_line(self):
|
||||||
|
self.learn()
|
||||||
|
self.sisi("workers", "vouch", "fakeagent/fa-1", "--up-to", "2", "--why", "words")
|
||||||
|
workers.append_record({"kind": "attempt", "id": "a1", "run_id": None, "ts": 1, "project": "p", "type": "impl",
|
||||||
|
"difficulty": 2, "worker": "fakeagent/fa-1", "outcome": "rejected", "check": "tests"})
|
||||||
|
r = self.sisi("route", "--retry-of", "a1", env={"SISI_SESSION_ID": self.sid})
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.assertTrue(r.stdout.startswith("fakeagent/"), r.stdout)
|
||||||
|
self.assertIn("mechanism:", r.stdout)
|
||||||
|
self.assertIn("unproven: check this result", r.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
class LearnedProviderFallback(TP.ProviderCase):
|
||||||
|
"""A provider of a learned tool: the reset time comes from the error, else from the provider's allowance probe."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.q = TP.Quota()
|
||||||
|
self.addCleanup(self.q.close)
|
||||||
|
self.git_init()
|
||||||
|
|
||||||
|
def notice(self, text, worker=None):
|
||||||
|
with orchestration.Meter("sess-9") as m:
|
||||||
|
return fallback.handle(m, "sess-9", self.proj, text, own_model="gamma-top", worker=worker)
|
||||||
|
|
||||||
|
def test_a_limit_with_no_time_in_it_takes_the_probes_reset_and_marks_only_that_provider(self):
|
||||||
|
self.q.windows = [(0, 1000, 4102444800000)]
|
||||||
|
self.define_probe(self.q)
|
||||||
|
out = self.notice("zai/b failed: weekly allowance used up for this plan")
|
||||||
|
self.assertIsNotNone(out)
|
||||||
|
down = workers.read_availability()
|
||||||
|
self.assertEqual(down["zai"]["retry_at"], 4102444800.0)
|
||||||
|
self.assertEqual(down["zai"]["scope"], "provider")
|
||||||
|
self.assertNotIn("other", down)
|
||||||
|
self.assertNotIn("zai/", self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[0])
|
||||||
|
|
||||||
|
def test_the_errors_own_time_wins_over_the_probe(self):
|
||||||
|
self.q.windows = [(0, 1000, 4102444800000)]
|
||||||
|
self.define_probe(self.q)
|
||||||
|
when = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 3600))
|
||||||
|
self.notice("zai/b failed: weekly allowance used up for this plan, resets at %s" % when)
|
||||||
|
self.assertAlmostEqual(workers.read_availability()["zai"]["retry_at"], time.time() + 3600, delta=5)
|
||||||
|
|
||||||
|
def test_the_providers_own_phrase_is_read_by_the_automatic_path(self):
|
||||||
|
self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth")
|
||||||
|
self.notice("zai/b failed: error code 1113 from the provider")
|
||||||
|
got = workers.read_availability()["zai"]
|
||||||
|
self.assertEqual((got["reason"], got["scope"]), ("auth", "provider"))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 4. the owner's vouch and capability
|
||||||
|
|
||||||
|
|
||||||
|
class VouchAgainstTheReconciledRouting(unittest.TestCase):
|
||||||
|
def cand(self, worker, **kw):
|
||||||
|
c = {"worker": worker, "tool": worker.split("/")[0], "model": worker, "usable": True, "plan": "flat", "cost": 1.0,
|
||||||
|
"unproven": True, "unproven_ok": True}
|
||||||
|
c.update(kw)
|
||||||
|
return c
|
||||||
|
|
||||||
|
def attempts(self, worker, n, kind, difficulty, outcome="accepted"):
|
||||||
|
return [{"kind": "attempt", "id": "%s%d" % (worker, i), "ts": 1, "type": kind, "difficulty": difficulty,
|
||||||
|
"worker": worker, "outcome": outcome, "check": "tests"} for i in range(n)]
|
||||||
|
|
||||||
|
def test_a_vouch_at_difficulty_three_ranks_with_judged_proof_before_a_benchmark(self):
|
||||||
|
vouched = self.cand("zai/a", vouch={"level": 3, "why": "tried it", "date": "2026-11-23", "relayed": False}, cost=5.0)
|
||||||
|
bench = dict(self.cand("big/b", unproven=False, unproven_ok=False), standing=99.0, cost=1.0)
|
||||||
|
for d in (2, 3):
|
||||||
|
r = routing.choose([bench, vouched], [], {}, "impl", d, now=1.0)
|
||||||
|
self.assertEqual(r["choice"]["worker"], "zai/a", d)
|
||||||
|
self.assertTrue(r["judged_first"])
|
||||||
|
self.assertIn("evidence (the owner's word)", "\n".join(routing.explain_choice(r, "impl", d)))
|
||||||
|
|
||||||
|
def test_it_ranks_with_a_judged_record_and_a_thick_bad_record_overrides_it_at_both_levels(self):
|
||||||
|
proven = self.cand("old/p", unproven=False, unproven_ok=False, cost=9.0)
|
||||||
|
for d in (2, 3):
|
||||||
|
recs = self.attempts("old/p", 8, "impl", d)
|
||||||
|
vouched = self.cand("zai/a", vouch={"level": 3, "why": "w", "date": "d", "relayed": False}, cost=1.0)
|
||||||
|
self.assertEqual(routing.choose([vouched, proven], recs, {}, "impl", d, now=1.0)["choice"]["worker"], "zai/a")
|
||||||
|
bad = recs + self.attempts("zai/a", 8, "impl", d, outcome="rejected")
|
||||||
|
self.assertEqual(routing.choose([vouched, proven], bad, {}, "impl", d, now=1.0)["choice"]["worker"], "old/p")
|
||||||
|
|
||||||
|
def test_the_routing_module_is_pure(self):
|
||||||
|
src = open(os.path.join(REPO, "sisi", "routing.py"), encoding="utf-8").read()
|
||||||
|
for word in ("import os", "import subprocess", "open(", "from . import store", "from . import workers", "from . import discovery",
|
||||||
|
"import json", "time.time()"):
|
||||||
|
self.assertNotIn(word, src, word)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 6. the session-start lines stay few
|
||||||
|
|
||||||
|
|
||||||
|
class SessionStartStaysShort(HookCase):
|
||||||
|
def start(self, sid="sess-start"):
|
||||||
|
r = self.sisi("tick", "--tool", "claude-code", stdin=json.dumps(
|
||||||
|
{"session_id": sid, "cwd": self.proj, "hook_event_name": "SessionStart", "source": "startup", "model": self.own}))
|
||||||
|
return r.stdout
|
||||||
|
|
||||||
|
def test_the_worst_case_prints_at_most_five_lines_and_nine_hundred_characters(self):
|
||||||
|
# a decision waiting of each kind, a cycle due, new workers AND new tools, worker facts missing, wiring broken
|
||||||
|
self.waiting_driver()
|
||||||
|
self.waiting_probe()
|
||||||
|
self.waiting_change()
|
||||||
|
discovery.new_tools(now=1.0) # the first look stores the list
|
||||||
|
time.sleep(0.02)
|
||||||
|
self.exe("brandnewtool")
|
||||||
|
self.exe("anotheragent")
|
||||||
|
self.listing()
|
||||||
|
with open(os.path.join(self.data, "workers.json"), "w") as f:
|
||||||
|
json.dump({"checked": time.time(), "tools": [], "new_unannounced": ["longprovider/a-very-long-model-name-1", "p/m2", "p/m3", "p/m4"]}, f)
|
||||||
|
with mock.patch("sisi.cycle.due_count", return_value=12), \
|
||||||
|
mock.patch("sisi.wiring.quick_problem", return_value="the generated rulebook is out of date (run `sisi update` to rebuild)"):
|
||||||
|
out = self.start()
|
||||||
|
lines = [l for l in out.splitlines() if l.strip()]
|
||||||
|
shown = [l for l in lines if not l.startswith("sisi: this session's model")] # the standing orchestration reminder is not a notice
|
||||||
|
self.assertLessEqual(len(shown), 5, out)
|
||||||
|
self.assertLess(sum(len(l) for l in shown), 900, "%d characters: %s" % (sum(len(l) for l in shown), out))
|
||||||
|
self.assertEqual(sum(1 for l in shown if "wait for the owner" in l), 1, "all three kinds in ONE line")
|
||||||
|
self.assertIn("3 decision(s)", out)
|
||||||
|
self.assertEqual(sum(1 for l in shown if "unproven" in l and "new " in l), 1, "new workers and new tools in ONE line")
|
||||||
|
self.assertIn("brandnewtool", out)
|
||||||
|
self.assertIn("longprovider", out)
|
||||||
|
self.assertEqual(sum(1 for l in shown if "worker facts" in l), 1)
|
||||||
|
self.assertEqual(sum(1 for l in shown if "learning cycle is due" in l), 1)
|
||||||
|
self.assertEqual(sum(1 for l in shown if "Run `sisi doctor`" in l), 1)
|
||||||
|
|
||||||
|
def test_each_line_is_printed_only_when_true(self):
|
||||||
|
out = self.start("sess-quiet")
|
||||||
|
for word in ("wait for the owner", "learning cycle", "new worker", "new command-line", "doctor"):
|
||||||
|
self.assertNotIn(word, out, word)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -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({"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:
|
||||||
|
with terminal(): # the owner's own terminal
|
||||||
|
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.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()
|
||||||
Reference in new issue
Block a user