A plugin that provides runs.limits sets how many agents each machine runs at once. A launch over the limit waits in the hub's queue (runs/queue.py) and starts when the machine is back under it; the limit rides every launch to the sidecar, which hands it to the run for the plugin's hooks. SubagentStart / SubagentStop join the script hook events. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
144 lines
4.5 KiB
Python
144 lines
4.5 KiB
Python
"""How many agents each machine runs at once, from a live plugin
|
|
(``provides: {"runs.limits": "<action>"}`` — the ``agent-limits`` plugin,
|
|
2026-11-29, after the EVOX2 ran out of memory under ~20 conversations).
|
|
|
|
The provider's action runs as the owner with ``{"op": "limits"}`` and answers
|
|
``{"limits": {<runner id>: <int>}}`` — a runner id is a worker's id, or
|
|
``local`` for the lab. A runner it doesn't name (or names with 0) has no
|
|
limit. The answer is cached :data:`TTL_SECS`; :func:`touched` drops it when
|
|
the provider ran a write, :func:`changed` when a provider came or went.
|
|
|
|
The core does the rest (``runs/queue.py``): a start on a runner at its limit
|
|
waits in the hub's queue, and the limit rides every launch to the runner's
|
|
sidecar (``agentLimit``), where the plugin's own harness hooks cap the
|
|
harness's native subagents against the same budget.
|
|
|
|
No plugin: no limit, nothing queues.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
import time
|
|
from typing import Any
|
|
|
|
from plugins.store import OWNER_UID
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
PROVIDES = "runs.limits"
|
|
TTL_SECS = 30.0
|
|
MAX_LIMIT = 256
|
|
LOCAL = "local"
|
|
|
|
_lock = threading.Lock()
|
|
_cache: tuple[float, dict[str, int]] | None = None
|
|
|
|
|
|
def invalidate() -> None:
|
|
global _cache
|
|
with _lock:
|
|
_cache = None
|
|
|
|
|
|
def changed() -> None:
|
|
"""A provider came or went (install, enable, disable, uninstall)."""
|
|
invalidate()
|
|
_wake()
|
|
|
|
|
|
def provides(rec: dict[str, Any] | None) -> bool:
|
|
return PROVIDES in (((rec or {}).get("manifest") or {}).get("provides") or {})
|
|
|
|
|
|
def touched(deps, rec: dict[str, Any] | None, *, action: str | None = None) -> None:
|
|
"""The plugin ``rec`` ran something: when it provides the limits (and
|
|
``action``, if named, isn't read-only), drop the cache, let the queue look
|
|
again and tell the app."""
|
|
if not provides(rec):
|
|
return
|
|
if action:
|
|
act = (((rec or {}).get("manifest") or {}).get("actions") or {}).get(action) or {}
|
|
if act.get("readOnly"):
|
|
return
|
|
invalidate()
|
|
_wake()
|
|
try:
|
|
deps.hub.publish({"type": "run-queue"})
|
|
except Exception: # noqa: BLE001 — no hub (tests)
|
|
pass
|
|
|
|
|
|
def _wake() -> None:
|
|
try:
|
|
from runs import queue as run_queue
|
|
run_queue.wake()
|
|
except Exception: # noqa: BLE001 — never from a plugin's bookkeeping
|
|
pass
|
|
|
|
|
|
def _provider(deps) -> tuple[dict[str, Any], dict[str, Any]] | None:
|
|
"""The owner's first enabled, approved plugin providing ``runs.limits``."""
|
|
from plugins.waiting import _providers_for
|
|
try:
|
|
found = _providers_for(deps, OWNER_UID, PROVIDES)
|
|
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
|
|
return None
|
|
for rec, _grant in found:
|
|
mf = rec.get("manifest") or {}
|
|
act = (mf.get("actions") or {}).get((mf.get("provides") or {}).get(PROVIDES))
|
|
if act:
|
|
return rec, act
|
|
return None
|
|
|
|
|
|
def has_provider(deps) -> bool:
|
|
return _provider(deps) is not None
|
|
|
|
|
|
def _clean(raw: Any) -> dict[str, int]:
|
|
out: dict[str, int] = {}
|
|
if not isinstance(raw, dict):
|
|
return out
|
|
for k, v in raw.items():
|
|
if not isinstance(k, str) or isinstance(v, bool):
|
|
continue
|
|
try:
|
|
n = int(v)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if n > 0:
|
|
out[k] = min(n, MAX_LIMIT)
|
|
return out
|
|
|
|
|
|
def limits(deps) -> dict[str, int]:
|
|
"""``{runner id: limit}`` — ``{}`` without a provider or when it fails (a
|
|
broken plugin never holds a run back)."""
|
|
global _cache
|
|
now = time.monotonic()
|
|
with _lock:
|
|
if _cache and now - _cache[0] < TTL_SECS:
|
|
return dict(_cache[1])
|
|
prov = _provider(deps)
|
|
out: dict[str, int] = {}
|
|
if prov:
|
|
rec, act = prov
|
|
from plugins.runner import run_script
|
|
try:
|
|
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
|
|
payload={"trigger": PROVIDES, "op": "limits"},
|
|
timeout_sec=min(20, int(act.get("timeoutSec") or 20)))
|
|
out = _clean((res or {}).get("limits") if isinstance(res, dict) else None)
|
|
except Exception as e: # noqa: BLE001
|
|
log.warning("%s via %s failed: %s", PROVIDES, rec.get("id"), e)
|
|
with _lock:
|
|
_cache = (now, out)
|
|
return dict(out)
|
|
|
|
|
|
def limit_for(deps, runner: str | None) -> int | None:
|
|
"""The limit of ``runner`` (None = the lab), or None when it has none."""
|
|
return limits(deps).get(runner or LOCAL)
|