Files
ai-agent/backend/models/ladders.py
gabrielvidalandClaude Fable 5.2 c346bd1314 feat(models): presets with a ladder — a run goes to the first route with quota left (core)
A preset is a named ladder of routes (model + harness + effort). A run sent on
preset:<id> — or on its source's default preset — takes the first rung with
room for its profile's login, and a follow-up steps down when its rung fills.
Provider plugins say which usage windows a model draws on (quotaWindows).
A Claude run's own subagents are held to the subagents preset's first Claude
route with room (subagentModel → CLAUDE_CODE_SUBAGENT_MODEL).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-29 19:17:00 +01:00

748 lines
34 KiB
Python

"""
Presets with a ladder (Settings → Models → Presets; the UI word is *preset*,
the code's is **ladder** — ``models/presets.py`` is the older per-model
preset).
A ladder is a named, ordered list of **rungs** — a model, a harness and an
effort each, never an account. A run sent on ``preset:<id>`` goes to the
**first rung with quota left** and steps down as rungs fill, so every run
still gets done, sometimes on a lesser model:
* **Account.** A rung is routed like any new run (``runs.service
.route_new_run``): the vendor's ★ login of the run's profile, on one of its
runners. A preset never leaves the profile it was sent from.
* **Quota.** A rung's windows are the windows of that account its model
draws on — the provider plugin's ``quotaWindows`` (first regex that matches
the model id), else every window with no model suffix (``five_hour``,
``seven_day``) plus ``<window>_<family>`` when the account reports one (a
per-model sub-limit: Fable's week). It is **full** when one of them is at or
past the ladder's ``fullAt`` % and resets in the future. No reading = room:
missing data never blocks a run. A local vendor (the EVOX2) is ``free``, a
catalogue-priced one (OpenRouter) ``credit`` — never full.
* **Every rung full** (``whenFull``): ``last`` runs the last rung that
routes, ``first`` the first (it pays), ``wait`` holds the start in the run
queue until the earliest reset (``runs/queue.py`` ``hold``).
* **Defaults** (:meth:`LadderStore.defaults`): the preset a source of runs
gets when it names no model, harness or account — ``composer``, ``mcp``
(the hub MCP and the CLI), ``child`` (a conversation a run started),
``subagents`` (a Claude Code run's own subagents — :func:`subagent_model`)
and ``plugin:<id>``.
* **Follow-ups** (:func:`step_for_turn`): a turn into a conversation whose
rung has filled steps down to the next rung with room **on the same harness
and account** — a session can't change either.
The file is ``MODEL_LADDERS_PATH`` (``/data/model-ladders.json``); a hub
without one starts with four presets (Best, Everyday, Background, Free), all
editable and deletable.
"""
from __future__ import annotations
import copy
import datetime
import json
import os
import pathlib
import re
import threading
import time
from typing import Any
from fastapi import HTTPException
PATH = os.environ.get("MODEL_LADDERS_PATH", "/data/model-ladders.json")
PREFIX = "preset:"
WHEN_FULL = ("last", "first", "wait")
FULL_AT_MIN, FULL_AT_MAX, FULL_AT_DEFAULT = 80, 100, 95
MAX_RUNGS = 16
MAX_LADDERS = 32
# The sources a default can be set for, besides ``plugin:<id>``.
CORE_SOURCES = ("composer", "mcp", "child", "subagents")
_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
_MODEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,127}$")
_EFFORT_RE = re.compile(r"^[a-z]{1,16}$")
_PLUGIN_SRC_RE = re.compile(r"^plugin:[a-z0-9][a-z0-9-]{0,63}$")
# ``five_hour``, ``seven_day``: a count and a unit, no model suffix.
_BASE_WINDOW_RE = re.compile(r"^[a-z]+_(hour|day|week|month)s?$")
# The EVOX2's two Qwens, by their provider ids.
_QWEN_38 = "ggml-org/qwen3.8-27b"
_QWEN_36 = "qwen3.6-35b-a3b"
def _r(model: str, harness: str, effort: str = "") -> dict:
return {"model": model, "harness": harness, "effort": effort}
SEED_LADDERS: list[dict] = [
{"id": "best", "name": "Best", "rungs": [
_r("fable", "claude"), _r("opus", "claude"), _r("opus", "agy"), _r("sonnet", "agy"),
_r("gemini-4-neon", "agy"), _r("gpt-oss-120b", "agy"), _r(_QWEN_38, "pi")]},
{"id": "everyday", "name": "Everyday", "rungs": [
_r("sonnet", "claude"), _r("sonnet", "agy"), _r("gemini-4-neon", "agy"),
_r("gpt-oss-120b", "agy"), _r(_QWEN_38, "pi")]},
{"id": "background", "name": "Background", "rungs": [
_r("haiku", "claude"), _r("gemini-3.8-flash", "agy"), _r("gpt-oss-120b", "agy"),
_r(_QWEN_36, "pi")]},
{"id": "free", "name": "Free", "rungs": [_r(_QWEN_38, "pi"), _r(_QWEN_36, "pi")]},
]
SEED_DEFAULTS: dict[str, str] = {
"composer": "best", "mcp": "best", "child": "everyday", "subagents": "background",
"plugin:cron-jobs": "background", "plugin:scheduled-conversations": "everyday",
"plugin:auto-translate": "background", "plugin:mail-agents": "background",
}
class LadderError(ValueError):
pass
# ── the store ────────────────────────────────────────────────────────────────
def _slug(name: str) -> str:
s = re.sub(r"[^a-z0-9]+", "-", (name or "").lower()).strip("-")[:40].strip("-")
return s or "preset"
def clean_rungs(v: Any) -> list[dict]:
if not isinstance(v, list) or len(v) > MAX_RUNGS:
raise LadderError(f"rungs must be a list of at most {MAX_RUNGS} routes")
from models import presets as presets_mod
known = set(presets_mod.harness_order())
out: list[dict] = []
for i, r in enumerate(v):
if not isinstance(r, dict):
raise LadderError(f"route {i + 1} must be an object")
model, harness = r.get("model"), r.get("harness")
if not isinstance(model, str) or not _MODEL_RE.match(model) or model.startswith(PREFIX):
raise LadderError(f"route {i + 1}: bad model")
if not isinstance(harness, str) or not re.match(r"^[a-z0-9_-]{1,32}$", harness):
raise LadderError(f"route {i + 1}: bad harness")
if known and harness not in known and harness not in ("claude", "pi", "opencode", "agy"):
raise LadderError(f"route {i + 1}: unknown harness {harness!r}")
effort = r.get("effort") or ""
if not isinstance(effort, str) or (effort and not _EFFORT_RE.match(effort)):
raise LadderError(f"route {i + 1}: bad effort level")
row = {"model": model, "harness": harness, "effort": effort}
if row not in out: # the same route twice adds nothing
out.append(row)
return out
def _clean_ladder(raw: dict) -> dict | None:
"""A stored ladder, or None for one that can't be read."""
try:
lid = str(raw.get("id") or "")
if not _ID_RE.match(lid):
return None
return {"id": lid, "name": _clean_name(raw.get("name") or lid),
"rungs": clean_rungs(raw.get("rungs") or []),
"fullAt": _clean_full_at(raw.get("fullAt", FULL_AT_DEFAULT)),
"whenFull": raw.get("whenFull") if raw.get("whenFull") in WHEN_FULL else "last"}
except LadderError:
return None
def _clean_name(v: Any) -> str:
name = " ".join(str(v or "").split())[:40]
if not name:
raise LadderError("a preset needs a name")
return name
def _clean_full_at(v: Any) -> int:
if isinstance(v, bool) or not isinstance(v, (int, float)):
raise LadderError("fullAt must be a number")
return int(max(FULL_AT_MIN, min(FULL_AT_MAX, round(v))))
def valid_source(src: str) -> bool:
return src in CORE_SOURCES or bool(_PLUGIN_SRC_RE.match(src or ""))
class LadderStore:
def __init__(self, path: str = PATH):
self.path = pathlib.Path(path)
self._lock = threading.Lock()
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
data = None
if not isinstance(data, dict):
# A hub that never had presets starts with the four.
self._ladders = copy.deepcopy(SEED_LADDERS)
for lad in self._ladders:
lad.update(fullAt=FULL_AT_DEFAULT, whenFull="last")
self._defaults = dict(SEED_DEFAULTS)
else:
self._ladders = [x for x in (_clean_ladder(r) for r in data.get("ladders") or []
if isinstance(r, dict)) if x][:MAX_LADDERS]
self._defaults = {k: v for k, v in (data.get("defaults") or {}).items()
if valid_source(k) and isinstance(v, str) and _ID_RE.match(v)}
def _save(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
tmp = self.path.with_suffix(".tmp")
tmp.write_text(json.dumps({"ladders": self._ladders, "defaults": self._defaults},
ensure_ascii=False, indent=1), encoding="utf-8")
os.replace(tmp, self.path)
def list(self) -> list[dict]:
with self._lock:
return copy.deepcopy(self._ladders)
def get(self, lid: str | None) -> dict | None:
with self._lock:
hit = next((x for x in self._ladders if x["id"] == lid), None)
return copy.deepcopy(hit) if hit else None
def defaults(self) -> dict[str, str]:
"""``{source: ladder id}`` — only the ones whose ladder still exists."""
with self._lock:
ids = {x["id"] for x in self._ladders}
return {k: v for k, v in self._defaults.items() if v in ids}
def default_for(self, source: str | None) -> str | None:
return self.defaults().get(source or "")
def create(self, body: dict) -> dict:
name = _clean_name(body.get("name"))
with self._lock:
if len(self._ladders) >= MAX_LADDERS:
raise LadderError(f"at most {MAX_LADDERS} presets")
base = _slug(name)
taken = {x["id"] for x in self._ladders} | {"defaults"}
lid, n = base, 2
while lid in taken:
lid, n = f"{base[:36]}-{n}", n + 1
lad = {"id": lid, "name": name, "rungs": clean_rungs(body.get("rungs") or []),
"fullAt": _clean_full_at(body.get("fullAt", FULL_AT_DEFAULT)),
"whenFull": body.get("whenFull") or "last"}
if lad["whenFull"] not in WHEN_FULL:
raise LadderError("whenFull is last, first or wait")
self._ladders.append(lad)
self._save()
return copy.deepcopy(lad)
def update(self, lid: str, patch: dict) -> dict | None:
unknown = set(patch) - {"name", "rungs", "fullAt", "whenFull"}
if unknown:
raise LadderError(f"unknown field(s): {', '.join(sorted(unknown))}")
with self._lock:
lad = next((x for x in self._ladders if x["id"] == lid), None)
if lad is None:
return None
new = dict(lad)
if "name" in patch:
new["name"] = _clean_name(patch["name"])
if "rungs" in patch:
new["rungs"] = clean_rungs(patch["rungs"])
if "fullAt" in patch:
new["fullAt"] = _clean_full_at(patch["fullAt"])
if "whenFull" in patch:
if patch["whenFull"] not in WHEN_FULL:
raise LadderError("whenFull is last, first or wait")
new["whenFull"] = patch["whenFull"]
lad.update(new)
self._save()
return copy.deepcopy(lad)
def delete(self, lid: str) -> bool:
with self._lock:
n = len(self._ladders)
self._ladders = [x for x in self._ladders if x["id"] != lid]
if len(self._ladders) == n:
return False
self._defaults = {k: v for k, v in self._defaults.items() if v != lid}
self._save()
return True
def set_defaults(self, patch: dict) -> dict[str, str]:
"""Merge ``{source: ladder id | None}`` (None / "" = *its own*)."""
if not isinstance(patch, dict):
raise LadderError("defaults must be an object")
with self._lock:
ids = {x["id"] for x in self._ladders}
for src, lid in patch.items():
if not valid_source(src):
raise LadderError(f"unknown source {src!r}")
if lid in (None, ""):
self._defaults.pop(src, None)
elif lid in ids:
self._defaults[src] = lid
else:
raise LadderError(f"unknown preset {lid!r}")
self._save()
return self.defaults()
_store: LadderStore | None = None
_store_lock = threading.Lock()
def store() -> LadderStore:
global _store
with _store_lock:
if _store is None:
_store = LadderStore(os.environ.get("MODEL_LADDERS_PATH") or PATH)
return _store
def set_store(s: LadderStore | None) -> None:
"""Tests: point the singleton at a temp file (None resets it)."""
global _store
with _store_lock:
_store = s
# ── what a pick means ────────────────────────────────────────────────────────
def preset_id(model: str | None) -> str | None:
"""``preset:best`` → ``best``; None for a plain model."""
m = (model or "").strip()
return m[len(PREFIX):].strip().lower() if m.lower().startswith(PREFIX) else None
def source_of(stamp: dict | None) -> str | None:
"""Where a new run comes from, read off the stamp its caller set — the
key of its default preset: a plugin's run (``plugin:<id>``), a
conversation a run started (``child``), the app's composer, or a script
(``mcp``: the hub MCP and the ``ai-agent`` CLI)."""
st = stamp or {}
if st.get("plugin"):
return f"plugin:{st['plugin']}"
if st.get("spawnedBy") or st.get("origin") == "child":
return "child"
return {"app": "composer", "script": "mcp"}.get(st.get("origin") or "")
def default_pick(*, model: str | None, harness: str | None, account: str | None,
stamp: dict | None, run_as: str | None, scope: dict | None) -> str | None:
"""The default preset of a new run that names no model, harness or
account — None for a guest's run (they keep their own model list)."""
if model or harness or account or run_as or scope:
return None
return store().default_for(source_of(stamp))
# ── a rung, read against the catalogue and the usage readings ───────────────
def _reg():
from plugins import providers
return providers.current()
def _catalog() -> list[dict]:
from models import catalog
return catalog.list_models()
def entry_of(rung: dict, models: list[dict] | None = None) -> dict | None:
"""The catalogue entry a rung launches: its harness's entry for the model
key (the standard tier), or the entry whose id / alias it names."""
from models import presets as presets_mod
models = _catalog() if models is None else models
on = [m for m in models if (m.get("harness") or "claude") == rung.get("harness")]
want = rung.get("model")
hit = [m for m in on if presets_mod.key_of(m) == want] \
or [m for m in on if want in (m.get("id"), m.get("alias"))]
return next((m for m in hit if not m.get("fast")), hit[0] if hit else None)
def model_arg(entry: dict) -> str:
"""The ``--model`` argument of an entry (a Claude family's newest goes
out as its CLI alias)."""
return entry.get("alias") or entry["id"]
def _epoch(v: Any) -> float | None:
if isinstance(v, bool) or v in (None, ""):
return None
if isinstance(v, (int, float)):
return float(v) / 1000 if v > 1e12 else float(v)
try:
return datetime.datetime.fromisoformat(str(v).replace("Z", "+00:00")).timestamp()
except ValueError:
return None
def window_names(vendor: str | None, model_id: str | None, family: str | None,
reported: list[str]) -> list[str]:
"""The windows of an account that ``model_id`` draws on, among the ones
it reports: the provider's ``quotaWindows``, else the default rule (see
the module docstring)."""
declared = _reg().quota_windows(vendor, model_id)
if declared is not None:
return [w for w in declared if w in reported]
base = [w for w in reported if _BASE_WINDOW_RE.match(w)]
fam = (family or _reg().claude_family(model_id) or "").lower()
own = [f"{w}_{fam}" for w in base if fam and f"{w}_{fam}" in reported]
return base + own
def _vendor_kind(vendor: str | None) -> str:
"""``free`` (a local vendor), ``credit`` (catalogue-priced: OpenRouter)
or ``plan``."""
p = _reg().providers.get(vendor or "")
if p is None:
return "plan"
if p.spec.get("local"):
return "free"
kind = (p.spec.get("pricing") or {}).get("kind")
if kind == "local_energy":
return "free"
return "credit" if kind == "openrouter_catalogue" else "plan"
def windows_of(deps, account: str | None, vendor: str | None, model_id: str | None,
family: str | None, full_at: float, now: float | None = None) -> list[dict]:
"""``[{name, pct, resetsAt, full}]`` for ``model_id`` on ``account`` —
empty when the account reports nothing."""
now = time.time() if now is None else now
poller = getattr(deps, "usage_poller", None)
try:
lim = poller.limit(account) if poller is not None and account else None
except Exception: # noqa: BLE001 — no reading counts as room
lim = None
wins = (lim or {}).get("windows") or {}
out = []
for name in window_names(vendor, model_id, family, list(wins)):
w = wins.get(name) or {}
pct = w.get("pct")
if not isinstance(pct, (int, float)) or isinstance(pct, bool):
continue
resets = _epoch(w.get("resetsAt"))
# Full only while its reset is still ahead: a reading from before the
# reset says nothing about the window now. No reset time: trust a
# fresh reading only.
live = resets > now if resets is not None else not (lim or {}).get("stale")
out.append({"name": name, "pct": round(float(pct), 1), "resetsAt": resets,
"full": bool(float(pct) >= full_at and live)})
return out
def _window_parts(name: str) -> tuple[str, str]:
"""``seven_day_fable`` → ``("week", "Fable")``, ``five_hour`` → ``("5 h",
"")``, ``five_hour_claude_gpt`` → ``("5 h", "Claude & GPT")``."""
bits = name.split("_")
span = {("five", "hour"): "5 h", ("seven", "day"): "week"}.get(
tuple(bits[:2]), " ".join(bits[:2]))
suffix = " & ".join(b.upper() if len(b) <= 3 else b.title() for b in bits[2:])
return span, suffix
def _account_label(account: str | None) -> str:
import accounts as accounts_mod
return (accounts_mod.get(account) or {}).get("label") or account or ""
def _why_full(wins: list[dict], account: str | None) -> str:
"""Why a rung is skipped: ``Personal week 100%`` (the account's own
window), ``Fable week 96%`` (a model's sub-limit)."""
w = max((x for x in wins if x["full"]), key=lambda x: x["pct"], default=None)
if w is None:
return ""
span, suffix = _window_parts(w["name"])
return f"{suffix or _account_label(account)} {span} {round(w['pct'])}%".strip()
def _route(deps, harness: str, model: str, profile: str | None, worker: str | None,
guest: str | None, account: str | None = None) -> tuple[str | None, str]:
"""``route_new_run`` for one rung. An unpinned rung checks its runners
are up (and falls to the profile's next one); a pinned worker is left to
the launch itself (it may be woken there)."""
from runs import service
from workers import picks as worker_picks
pinned = bool(worker_picks.resolve(deps.worker_store, worker, guest=guest))
return service.route_new_run(deps, harness, account, worker, profile,
check_online=not pinned, guest=guest, model=model)
def _detail(e: HTTPException) -> str:
d = e.detail
return str((d.get("message") if isinstance(d, dict) else d) or "can't run here")[:160]
def rung_status(deps, rung: dict, full_at: float, *, profile: str | None = None,
worker: str | None = None, guest: str | None = None,
account: str | None = None, models: list[dict] | None = None,
now: float | None = None) -> dict:
"""One rung, as a run sent now would find it: ``status`` (``room`` |
``full`` | ``free`` | ``credit`` | ``unavailable``), ``reason`` (why it
is skipped), the resolved ``account`` / ``runner`` and its ``windows``.
``account`` pins the login (a follow-up's, a run's subagents')."""
from runs import service
out: dict[str, Any] = {"model": rung.get("model"), "harness": rung.get("harness"),
"effort": rung.get("effort") or "", "status": "unavailable",
"windows": [], "account": None, "accountLabel": None,
"runner": None, "runnerName": None, "modelId": None, "arg": None,
"label": None, "family": None, "vendor": None, "reason": None}
entry = entry_of(rung, models)
if entry is None:
out["reason"] = "not in the catalogue"
return out
out.update(modelId=entry["id"], arg=model_arg(entry), family=entry.get("family"),
label=entry.get("label") or entry.get("displayName") or entry["id"])
if entry.get("efforts") is not None and out["effort"] not in (entry.get("efforts") or []):
out["effort"] = "" # a level this model doesn't take
if entry.get("unavailable"):
out["reason"] = str(entry["unavailable"])[:160]
return out
try:
runner, acct = _route(deps, rung["harness"], out["arg"], profile, worker, guest, account)
except HTTPException as e:
out["reason"] = _detail(e)
return out
vendor = service.run_vendor(rung["harness"], acct, out["arg"])
from profiles import runners as runners_mod
out.update(account=acct, accountLabel=_account_label(acct), runner=runner or "local",
runnerName=runners_mod.runner_name(deps, runner), vendor=vendor)
kind = _vendor_kind(vendor)
if kind != "plan":
out["status"] = kind
if kind == "free":
out["accountLabel"] = (_reg().providers[vendor].spec.get("label") or vendor)
return out
wins = windows_of(deps, acct, vendor, entry["id"], entry.get("family"), full_at, now)
out["windows"] = wins
if any(w["full"] for w in wins):
out.update(status="full", reason=_why_full(wins, acct))
else:
out["status"] = "room"
return out
def _routable(st: dict) -> bool:
return st["status"] in ("room", "full", "free", "credit")
def _has_room(st: dict) -> bool:
return st["status"] in ("room", "free", "credit")
def statuses(deps, ladder: dict, *, profile: str | None = None, worker: str | None = None,
guest: str | None = None, now: float | None = None) -> list[dict]:
models = _annotated_catalog(deps)
return [rung_status(deps, r, ladder.get("fullAt", FULL_AT_DEFAULT), profile=profile,
worker=worker, guest=guest, models=models, now=now)
for r in ladder.get("rungs") or []]
def _annotated_catalog(deps) -> list[dict]:
"""The catalogue with what can't run now marked (no agy host, OpenRouter's
key refused) — the picker's own view."""
try:
from models.routes import agy_down, for_caller, openrouter_down, with_availability
return for_caller(with_availability(_catalog(), openrouter_down()), True, agy_down(deps))
except Exception: # noqa: BLE001 — the plain catalogue then
return _catalog()
def pick(sts: list[dict], when_full: str) -> tuple[int | None, bool]:
"""``(index, every_route_full)``: the first rung with room, else the
``whenFull`` fallback among the rungs that route. None: nothing routes."""
i = next((k for k, s in enumerate(sts) if _has_room(s)), None)
if i is not None:
return i, False
can = [k for k, s in enumerate(sts) if _routable(s)]
if not can:
return None, False
return (can[0] if when_full == "first" else can[-1]), True
def resolve(deps, ladder: dict, *, profile: str | None = None, worker: str | None = None,
guest: str | None = None, now: float | None = None) -> dict:
"""Where a run sent on ``ladder`` goes now: ``{i, n, harness, model,
effort, account, runner, skipped: [{i, model, harness, reason}], full}``
— plus ``wait: {until}`` when every rung is full and the ladder waits
(``until`` = the earliest reset among the full rungs, an epoch).
Raises a 409 when no rung can run at all."""
now = time.time() if now is None else now
sts = statuses(deps, ladder, profile=profile, worker=worker, guest=guest, now=now)
i, full = pick(sts, ladder.get("whenFull") or "last")
if i is None:
why = "; ".join(f"{k + 1} · {s.get('label') or s['model']}: {s.get('reason') or 'unavailable'}"
for k, s in enumerate(sts)) or "it has no route"
raise HTTPException(409, {
"message": f"no route of the {ladder.get('name') or ladder['id']} preset can run — {why}",
"kind": "preset_unroutable"})
st = sts[i]
out = {"preset": ladder["id"], "i": i, "n": len(sts), "harness": st["harness"],
"model": st["arg"], "modelId": st["modelId"], "effort": st["effort"] or None,
"account": st["account"], "runner": st["runner"], "full": full,
"skipped": [{"i": k, "model": s.get("modelId") or s["model"], "harness": s["harness"],
"reason": s.get("reason") or s["status"]}
for k, s in enumerate(sts[:i] if not full else sts) if k != i]}
if full and (ladder.get("whenFull") == "wait"):
resets = [w["resetsAt"] for s in sts if s["status"] == "full"
for w in s["windows"] if w["full"] and w["resetsAt"] and w["resetsAt"] > now]
if resets:
out["wait"] = {"until": min(resets)}
return out
def route_stamp(res: dict) -> dict:
"""``meta.route`` of a run started on a preset."""
return {"i": res["i"], "n": res["n"], "harness": res["harness"],
"model": res.get("modelId") or res["model"], "account": res["account"],
"skipped": res["skipped"], "full": bool(res.get("full")), "at": _now_iso()}
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
# ── follow-up turns ──────────────────────────────────────────────────────────
def step_for_turn(deps, meta: dict, *, account: str | None, harness: str,
from_top: bool = False, now: float | None = None) -> dict | None:
"""A continue of a conversation started on a preset: when its rung has
filled, the next rung of the same ladder with room **on the same harness
and account** — ``{i, model, modelId, effort, from, why}`` — else None
(its rung has room, there is nowhere to step, or the ladder is gone: the
session keeps its model). ``from_top`` re-attaches the preset: the first
such rung, whatever the conversation ran on."""
route = meta.get("route") or {}
ladder = store().get(meta.get("preset"))
if not ladder or not ladder.get("rungs"):
return None
if not from_top and (route.get("exact") or not isinstance(route.get("i"), int)):
return None
models = _annotated_catalog(deps)
full_at = ladder.get("fullAt", FULL_AT_DEFAULT)
rungs = ladder["rungs"]
def status(k: int) -> dict | None:
if rungs[k].get("harness") != harness:
return None
entry = entry_of(rungs[k], models)
if entry is None or entry.get("unavailable"):
return None
from runs import service
vendor = service.run_vendor(harness, account, model_arg(entry))
import accounts as accounts_mod
if account and accounts_mod.vendor_of_account(account) not in (None, vendor):
return None # another vendor's model: not on this login
wins = windows_of(deps, account, vendor, entry["id"], entry.get("family"), full_at, now)
kind = _vendor_kind(vendor)
return {"i": k, "entry": entry, "windows": wins,
"full": kind == "plan" and any(w["full"] for w in wins),
"why": _why_full(wins, account)}
cur_i = -1 if from_top else min(int(route["i"]), len(rungs) - 1)
cur = status(cur_i) if cur_i >= 0 else None
if not from_top and (cur is None or not cur["full"]):
return None
for k in range(cur_i + 1, len(rungs)):
st = status(k)
if st and not st["full"]:
eff = rungs[k].get("effort") or ""
if st["entry"].get("efforts") is not None and eff not in (st["entry"].get("efforts") or []):
eff = ""
return {"i": k, "n": len(rungs), "model": model_arg(st["entry"]),
"modelId": st["entry"]["id"], "effort": eff or None,
"from": {"i": cur_i, "model": route.get("model")} if cur_i >= 0 else None,
"why": (cur or {}).get("why") or ""}
return None
# ── a Claude Code run's own subagents ────────────────────────────────────────
def subagent_model(deps, account: str | None, run_model: str | None,
now: float | None = None) -> str | None:
"""The model a claude run's subagents and workflow agents are held to:
the first ``harness: claude`` rung of the ``subagents`` preset with room
**on the run's own account**; the run's own model when none has; None
(the CLI's own choice per agent) when no preset is set for subagents."""
ladder = store().get(store().default_for("subagents"))
if not ladder:
return None
import accounts as accounts_mod
from runs import service
models = _catalog()
full_at = ladder.get("fullAt", FULL_AT_DEFAULT)
for rung in ladder.get("rungs") or []:
if rung.get("harness") != "claude":
continue
entry = entry_of(rung, models)
if entry is None:
continue
vendor = service.run_vendor("claude", account, model_arg(entry))
if account and accounts_mod.vendor_of_account(account) not in (None, vendor):
continue
wins = windows_of(deps, account, vendor, entry["id"], entry.get("family"), full_at, now)
if not any(w["full"] for w in wins):
return model_arg(entry)
return run_model or None
# ── the API's view ───────────────────────────────────────────────────────────
def _public_rung(st: dict) -> dict:
return {k: st.get(k) for k in ("model", "harness", "effort", "status", "reason", "windows",
"account", "accountLabel", "runner", "runnerName",
"modelId", "label", "family", "vendor")}
def view(deps, ladder: dict, *, profile: str | None = None, now: float | None = None) -> dict:
"""A ladder with each rung's status and ``now`` — the rung a run sent now
would take (None: nothing routes); ``allFull`` when it is the fallback."""
sts = statuses(deps, ladder, profile=profile, now=now)
i, full = pick(sts, ladder.get("whenFull") or "last")
return {"id": ladder["id"], "name": ladder["name"], "fullAt": ladder["fullAt"],
"whenFull": ladder["whenFull"], "rungs": [_public_rung(s) for s in sts],
"now": i, "allFull": full}
def brief(deps, *, profile: str | None = None) -> list[dict]:
"""``[{id, name, now}]`` for ``GET /api/models`` (and ``models.read``):
what a plugin's model list offers — ``now`` = where a run would land."""
out = []
for lad in store().list():
try:
v = view(deps, lad, profile=profile)
except Exception: # noqa: BLE001 — a preset that can't be read is still listed
v = {"now": None, "rungs": []}
r = v["rungs"][v["now"]] if v.get("now") is not None else None
out.append({"id": lad["id"], "name": lad["name"],
"now": {"i": v["now"], "model": r.get("modelId"), "label": r.get("label"),
"harness": r.get("harness"), "account": r.get("account")} if r else None})
return out
def model_hints(deps, *, profile: str | None = None, now: float | None = None) -> dict[str, dict]:
"""Per model key, the quota a plain pick of it would meet (its preset
harness, the profile's login): ``{status, pct, window, account,
accountLabel, reason}`` — the picker's "week 100% · pays" hints."""
from models import presets as presets_mod
models = _annotated_catalog(deps)
out: dict[str, dict] = {}
for key, p in presets_mod.presets(models).items():
entry = presets_mod.entry_for(models, key, p)
if entry is None:
continue
st = rung_status(deps, {"model": entry["id"], "harness": entry.get("harness") or "claude"},
FULL_AT_DEFAULT, profile=profile, models=models, now=now)
top = max(st["windows"], key=lambda w: w["pct"], default=None)
out[key] = {"status": st["status"], "pct": top["pct"] if top else None,
"window": top["name"] if top else None, "account": st["account"],
"accountLabel": st["accountLabel"], "reason": st["reason"]}
return out
def sources(deps) -> list[dict]:
"""The sources a default can be set for (mockup D): the four core ones,
then every installed plugin of the owner's that may start runs."""
out = [{"id": s, "kind": "core"} for s in CORE_SOURCES]
ps = getattr(deps, "plugin_store", None)
seen = set()
if ps is not None:
try:
from plugins.store import OWNER_UID
for rec in ps.list_for(OWNER_UID):
mf = rec.get("manifest") or {}
if "runs.start" in (mf.get("capabilities") or []):
seen.add(rec["id"])
out.append({"id": f"plugin:{rec['id']}", "kind": "plugin",
"plugin": rec["id"], "label": mf.get("name") or rec["id"],
"enabled": bool(rec.get("enabled"))})
except Exception: # noqa: BLE001 — no plugin list, still the core sources
pass
return out