Files

255 lines
9.4 KiB
Python

"""Declarative Claude subagents contributed by live plugins (``agents[]`` in
``plugin.json``) and per-person preference resolution (``scope: default+override``,
``optionsFrom: user.modelFamilies``).
Subagents are loaded **in-process** by :mod:`runs.extras` when launching a
Claude run — zero subprocess latency. Preferences live in each person's
``ai-agent-settings`` ui-state blob (``pluginPrefs[pid]``):
* The operator's stored value is everyone's default (when a pref declares
``scope: "default+override"``);
* Any other user's stored value overrides only the fields they changed, and
missing fields follow the operator's default live;
* A ``select`` pref with ``optionsFrom: "user.modelFamilies"`` restricts its
choices to the Claude model families (``haiku``, ``sonnet``, ``opus``) the
person is allowed to run, clamping disallowed defaults/overrides to the
cheapest family they may use (or disabling the agent when none).
"""
from __future__ import annotations
import json
import logging
import pathlib
from typing import Any
from plugins.store import OWNER_UID
log = logging.getLogger(__name__)
MODEL_FAMILIES = ("haiku", "sonnet", "opus")
SETTINGS_KEY = "ai-agent-settings"
def allowed_model_families(models: list[str] | None) -> list[str]:
"""Claude family aliases a person may use (none listed = every one)."""
if not models:
return list(MODEL_FAMILIES)
mine = {str(m).lower() for m in models}
return [m for m in MODEL_FAMILIES if any(m in a for a in mine)]
def _read_plugin_prefs(ui_state, key: str, pid: str) -> dict[str, Any]:
if ui_state is None:
return {}
raw = ui_state.get(key)
if not raw:
return {}
try:
blob = json.loads(raw)
state = blob.get("state") if isinstance(blob, dict) else None
prefs = (state.get("pluginPrefs") if isinstance(state, dict) else None) or {}
mine = prefs.get(pid)
return dict(mine) if isinstance(mine, dict) else {}
except (ValueError, TypeError, AttributeError):
return {}
def owner_prefs(deps, pid: str) -> dict[str, Any]:
return _read_plugin_prefs(getattr(deps, "ui_state", None), SETTINGS_KEY, pid)
def person_prefs(deps, uid: str, pid: str) -> dict[str, Any]:
if uid == OWNER_UID:
return owner_prefs(deps, pid)
return _read_plugin_prefs(getattr(deps, "ui_state", None), f"u.{uid}.{SETTINGS_KEY}", pid)
def _valid_pref_val(spec: dict[str, Any], raw: Any, options: list[str] | None = None) -> tuple[bool, Any]:
typ = spec.get("type")
if typ == "switch":
return (isinstance(raw, bool), raw)
if typ == "range":
if isinstance(raw, (int, float)) and not isinstance(raw, bool):
lo, hi = float(spec.get("min", 0)), float(spec.get("max", 100))
return True, min(hi, max(lo, float(raw)))
return False, None
if typ == "color":
if isinstance(raw, str) and len(raw) == 7 and raw.startswith("#"):
return True, raw.lower()
return False, None
if typ == "select":
opts = options if options is not None else list(spec.get("options") or [])
if isinstance(raw, str) and raw in opts:
return True, raw
return False, None
return False, None
def resolve_prefs_for(
deps,
pid: str,
manifest: dict[str, Any],
uid: str,
user_models: list[str] | None = None,
) -> tuple[dict[str, Any], dict[str, Any], dict[str, list[str]]]:
"""Return ``(effective, hub_defaults, dynamic_options)`` for ``(uid, pid)``."""
specs = (manifest.get("ui") or {}).get("prefs") or []
if not specs:
return {}, {}, {}
is_owner = uid == OWNER_UID
owner_raw = owner_prefs(deps, pid)
own_raw = owner_raw if is_owner else person_prefs(deps, uid, pid)
families = list(MODEL_FAMILIES) if is_owner else allowed_model_families(user_models)
effective: dict[str, Any] = {}
hub_defaults: dict[str, Any] = {}
dyn_opts: dict[str, list[str]] = {}
for spec in specs:
key = spec["key"]
is_fam = spec.get("optionsFrom") == "user.modelFamilies"
opts = families if is_fam else list(spec.get("options") or [])
if is_fam:
dyn_opts[key] = list(families)
# Operator's default value (validated against full manifest options)
all_opts = list(MODEL_FAMILIES) if is_fam else list(spec.get("options") or [])
ok_o, val_o = _valid_pref_val(spec, owner_raw.get(key), all_opts)
hub_val = val_o if ok_o else spec.get("default")
if spec.get("scope") == "default+override":
hub_defaults[key] = hub_val
# Caller's effective value
if is_owner:
effective[key] = hub_val
else:
ok_u, val_u = _valid_pref_val(spec, own_raw.get(key), opts)
if ok_u:
effective[key] = val_u
elif spec.get("scope") == "default+override":
ok_h, val_h = _valid_pref_val(spec, hub_val, opts)
if ok_h:
effective[key] = val_h
elif is_fam:
effective[key] = opts[0] if opts else None
else:
effective[key] = spec.get("default")
else:
ok_d, val_d = _valid_pref_val(spec, spec.get("default"), opts)
effective[key] = val_d if ok_d else (opts[0] if (is_fam and opts) else spec.get("default"))
return effective, hub_defaults, dyn_opts
def enrich_ui_prefs(
deps,
pid: str,
manifest: dict[str, Any],
*,
uid: str,
is_owner: bool,
user_models: list[str] | None = None,
) -> list[dict[str, Any]]:
"""Enrich ``ui.prefs`` specs sent to the browser with ``hubDefault`` and
resolved ``options`` (for ``optionsFrom: user.modelFamilies``)."""
specs = (manifest.get("ui") or {}).get("prefs") or []
if not specs:
return []
_, hub_defaults, dyn_opts = resolve_prefs_for(
deps, pid, manifest, OWNER_UID if is_owner else uid, user_models,
)
out: list[dict[str, Any]] = []
for s in specs:
item = dict(s)
k = s["key"]
if k in dyn_opts:
item["options"] = dyn_opts[k]
if not is_owner and k in hub_defaults:
item["hubDefault"] = hub_defaults[k]
out.append(item)
return out
def _active_agent_plugins(deps, uid: str) -> list[dict[str, Any]]:
"""Every enabled, approved plugin active for ``uid`` that declares ``agents[]``."""
store = getattr(deps, "plugin_store", None)
if store is None:
return []
out: list[dict[str, Any]] = []
seen: set[str] = set()
try:
u_map = store._state["users"].get(uid) or {} # noqa: SLF001
pids = sorted(u_map)
except Exception:
pids = []
for pid in pids:
rec = store.get_raw(uid, pid)
if not rec or not rec.get("enabled") or rec.get("needsApproval"):
continue
if (rec.get("manifest") or {}).get("agents"):
seen.add(pid)
out.append(rec)
if uid != OWNER_UID:
for rec in store.managed_plugins():
pid = rec["id"]
if pid in seen or not (rec.get("manifest") or {}).get("agents"):
continue
if store.effective_grant(uid, pid, rec["manifest"]).get("enabled"):
seen.add(pid)
out.append(rec)
return out
def _read_prompt(plugin_dir: str, rel: str) -> str | None:
try:
root = pathlib.Path(plugin_dir).resolve()
target = (root / rel).resolve()
target.relative_to(root)
if not target.is_file():
return None
return target.read_text(encoding="utf-8")[:64 * 1024]
except (OSError, ValueError):
return None
def agent_definitions_for(deps, person: str | None) -> dict[str, dict[str, Any]]:
"""All plugin-contributed Claude subagent definitions for ``person``
(``None`` or ``"owner"`` = the operator). Ready for ``claude --agents``."""
uid = OWNER_UID if (not person or person == OWNER_UID) else str(person).strip().lower()
user_models = None
if uid != OWNER_UID:
users = getattr(deps, "users", None)
u = users.get(uid) if users else None
user_models = (u or {}).get("models")
out: dict[str, dict[str, Any]] = {}
for rec in _active_agent_plugins(deps, uid):
mf = rec.get("manifest") or {}
pid = mf.get("id") or rec.get("id") or ""
prefs, _, _ = resolve_prefs_for(deps, pid, mf, uid, user_models)
for ag in mf.get("agents") or []:
ep = ag.get("enabledPref")
if ep and prefs.get(ep) is False:
continue
mp = ag.get("modelPref")
model = prefs.get(mp) if mp else ag.get("defaultModel")
if mp and model is None:
# Model family clamping left no allowed model for this user
continue
prompt = _read_prompt(rec.get("dir") or "", ag["promptFile"])
if not prompt:
continue
defn: dict[str, Any] = {
"description": ag["description"],
"prompt": prompt,
"tools": list(ag.get("tools") or []),
}
if model:
defn["model"] = str(model)
if ag.get("omitClaudeMd"):
defn["omitClaudeMd"] = True
efp = ag.get("effortPref")
effort = prefs.get(efp) if efp else ag.get("defaultEffort")
if effort and str(effort) != "inherit":
defn["effort"] = str(effort)
out[ag["name"]] = defn
return out