world: serve a plain HTTP API without external world libraries
Browse filesThe world now runs on its own small HTTP server (server.py, standard library)
with per-seat agent credentials from PYBOT_TOKEN_<seat> (Bearer or
X-World-Token): POST /v1/tools/<name> with flat arguments, the direct
GET /world/manifest and POST /world/tools/<name> routes with the
{"ok", ...} envelope, /healthz, and /metrics and /admin behind
PYBOT_ADMIN_TOKEN. Admission control (429 + Retry-After) and parked mode
are kept.
open_pr and run_bot take the agent's change as a workspace argument
{base_sha, patch} (patch only); a missing base is fetched from the Hub,
else the call fails with unknown_base. Tool schemas come from the tool
methods' type hints and docstrings (api.py). The lanes, state store and
process isolation are vendored; bucket snapshots use huggingface_hub
directly. requirements.txt lists only huggingface_hub.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Files changed (19)
- world/Dockerfile+6-12
- world/api.pyAdded+372
- world/entrypoint.sh+9-13
- world/isolation.pyAdded+381
- world/lanes.pyAdded+385
- world/pybot.py+82-152
- world/pytest.ini-2
- world/repository.py+2-3
- world/requirements.txt+1-660
- world/sandbox.py+3-3
- world/scripts/check-sidecar.py+2-2
- world/scripts/smoke-local.py+24-27
- world/server.pyAdded+323
- world/snapshot.py+30-4
- world/store.pyAdded+179
- world/tests/conftest.py+19-1
- world/tests/fixtures/seed-basic/CONTRIBUTING.md+7-8
- world/tests/test_pybot.py+179-115
- world/workspace.pyAdded+67
112345656791089101112131416151618192021222317181920# pybot world image: World API v1 on $PORT (7860). Build from this directory:# pybot world image: its HTTP API (server.py) on $PORT (7860). Build from this directory:# docker build -t <registry>/pybot-world:<tag> world/# The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is# pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on# 3.12+); Python deps are legion's own uv.lock (exact versions + hashes), and legion itself is# installed at the commit that lock comes from (README, "The legion pin").# 3.12+). The world's only Python dependency is huggingface_hub (requirements.txt).FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
# git: the world's bare repo, fetches and pushes to the Hub, and pip's legion checkout.# util-linux (unshare) ships in the base.# git: the world's bare repo, fetches and pushes to the Hub.# util-linux (unshare, prlimit) ships in the base.RUN apt-get update \ && apt-get install -y --no-install-recommends git \ && rm -rf /var/lib/apt/lists/*
COPY requirements.txt /opt/world/requirements.txtRUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txtRUN pip install --no-cache-dir -r /opt/world/requirements.txt
# legion's World API library, pinned to a commit (pip cannot hash a git requirement, so it gets its# own install). --no-deps: its deps are the hashed ones above; the world needs no Harbor or board.RUN pip install --no-cache-dir --no-deps \ "legion @ git+https://github.com/huggingface/legion@803873b114d5e04a3a01fea5e2e9084a03596fab"
COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/COPY *.py /opt/world/COPY seed/ /opt/world/seed/COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372"""The world's tool layer: `@tool` methods of a `World` subclass, their JSON schemas (from the typehints and the docstring's first paragraph), argument checks, runtime knobs and lane pauses(the admin API, saved in `knobs.json`), and secret redaction. `server.py` serves it over HTTP.
A parameter named `agent` (or annotated `Agent`) receives the caller and is never shown in theschema."""from __future__ import annotations
import inspectimport jsonimport loggingimport osimport reimport threadingimport typesimport typingfrom collections.abc import Callablefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any
log = logging.getLogger(__name__)POOLS = ("fast", "slow")
@dataclass(frozen=True)class Agent: """Who calls: the agent's name (from its credential) and the request id, if one was sent."""
name: str request_id: str = ""
class ToolError(Exception): """Raise from a tool: the agent reads `message` as the tool's error result. `retry_after_s`: the call cannot succeed before then (a budget, a busy backend)."""
def __init__(self, message: str, code: str = "tool_error", retry_after_s: float | None = None) -> None: super().__init__(message) self.code = code self.message = message self.retry_after_s = retry_after_s
def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = False) -> Any: """Mark a method as a tool: `@tool`, or `@tool(pool="slow", read_only=True)`. `pool`: the server's thread pool for the call ("slow" for tools that block for seconds). `read_only`: the tool changes nothing (manifest `annotations.readOnlyHint`).""" if pool not in POOLS: raise ValueError(f"pool {pool!r} must be one of {POOLS}")
def mark(f: Callable) -> Callable: f.world_tool = {"pool": pool, "read_only": read_only} # type: ignore[attr-defined] return f
return mark if fn is None else mark(fn)
# ------------------------------------------------------------------ schemas and argument checks
def _is_agent(name: str, hint: Any) -> bool: return name == "agent" or hint is Agent
def type_schema(hint: Any) -> dict[str, Any]: """The JSON schema of a type hint: str, int, float, bool, list[...], dict, Literal[...], X | None (accepts null too).""" origin, args = typing.get_origin(hint), typing.get_args(hint) if origin in (typing.Union, types.UnionType): rest = [a for a in args if a is not type(None)] if len(rest) != 1 or len(rest) == len(args): raise TypeError(f"unions other than `X | None` are not supported: {hint!r}") schema = type_schema(rest[0]) schema["type"] = [schema["type"], "null"] if "enum" in schema: schema["enum"] = [*schema["enum"], None] return schema simple = {str: "string", bool: "boolean", int: "integer", float: "number", dict: "object"} if hint in simple or origin is dict: return {"type": simple[dict if origin is dict else hint]} if origin is list: return {"type": "array", "items": type_schema(args[0]) if args else {}} if origin is typing.Literal: kinds = {type(a) for a in args} return {"type": "string" if kinds == {str} else "integer", "enum": list(args)} raise TypeError(f"unsupported type {hint!r}")
def tool_schema(fn: Callable) -> dict[str, Any]: """{name, description, parameters} of a tool function or method.""" hints = typing.get_type_hints(fn) props, required = {}, [] for p in inspect.signature(fn).parameters.values(): if p.name == "self" or _is_agent(p.name, hints.get(p.name)): continue props[p.name] = schema = type_schema(hints[p.name]) if p.default is p.empty: required.append(p.name) elif p.default is not None: schema["default"] = p.default params: dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False} if required: params["required"] = required doc = inspect.getdoc(fn) or "" return {"name": fn.__name__, "description": " ".join(doc.split("\n\n")[0].split()), "parameters": params}
_JSON_TYPES = {"string": (str,), "integer": (int,), "number": (int, float), "boolean": (bool,), "array": (list,), "object": (dict,), "null": (type(None),)}
def _check(schema: dict[str, Any], value: Any, where: str) -> str | None: t = schema.get("type") types_ = [t] if isinstance(t, str) else t or [] if types_ and not any(isinstance(value, _JSON_TYPES[x]) and not ( x in ("integer", "number") and isinstance(value, bool)) for x in types_): return f"{where} must be {' or '.join(types_)}, got {json.dumps(value)[:60]}" if "enum" in schema and value not in schema["enum"]: return f"{where} must be one of {schema['enum']}, got {json.dumps(value)[:60]}" if isinstance(value, list) and schema.get("items"): for i, v in enumerate(value): if err := _check(schema["items"], v, f"{where}[{i}]"): return err return None
def check_args(params: dict[str, Any], args: Any) -> str | None: """An error message for arguments that do not fit the tool's schema, else None.""" if not isinstance(args, dict): return f"arguments must be a JSON object, got {type(args).__name__}" props = params["properties"] if unknown := [k for k in args if k not in props]: return f"unknown argument(s) {', '.join(unknown)}; expected: {', '.join(props) or 'none'}" if missing := [k for k in params.get("required", ()) if k not in args]: return f"missing required argument(s): {', '.join(missing)}" return next((err for k, v in args.items() if (err := _check(props[k], v, k))), None)
# ------------------------------------------------------------------ secrets
_SECRET_NAME = re.compile(r"TOKEN|SECRET|PASSWORD|INVITE|API_KEY|_KEY$", re.IGNORECASE)
def redact(value: Any) -> Any: """`value` (JSON-able) with the value of every secret-looking environment variable (8+ characters) replaced by "[redacted]".""" secrets = sorted({v for k, v in os.environ.items() if _SECRET_NAME.search(k) and len(v) >= 8}, key=len, reverse=True) text = json.dumps(value, default=str) if not any(s in text for s in secrets): return value for s in secrets: text = text.replace(json.dumps(s)[1:-1], "[redacted]") return json.loads(text)
# ------------------------------------------------------------------ admin: knobs and lane pauses
LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")KNOB_TYPES = (int, float, bool, str)
@dataclassclass Knob: name: str type: type default: Any min: float | None = None max: float | None = None doc: str = "" on_change: Callable[[Any], None] | None = None
def check(self, value: Any) -> Any: """`value` as this knob's type (raises ValueError).""" t = self.type if t is bool or t is str: ok = isinstance(value, t) else: # int or float: JSON numbers, not booleans; 2.0 is an int, 2.5 is not ok = isinstance(value, int | float) and not isinstance(value, bool) and ( t is float or float(value).is_integer()) if not ok: raise ValueError(f"{self.name}: expected {t.__name__}, got {json.dumps(value)}") value = t(value) if self.min is not None and value < self.min: raise ValueError(f"{self.name}: {value} is below the minimum {self.min:g}") if self.max is not None and value > self.max: raise ValueError(f"{self.name}: {value} is above the maximum {self.max:g}") return value
class Admin: """Knobs (name -> value) and paused lanes (lane -> reason), saved in `<state dir>/knobs.json` and read back at the next start. Thread-safe."""
def __init__(self, state_dir: str | os.PathLike | None = None) -> None: self.path = Path(state_dir) / "knobs.json" if state_dir is not None else None self.knobs: dict[str, Knob] = {} self.values: dict[str, Any] = {} self.stored: dict[str, Any] = {} # values set through the admin API self.paused: dict[str, str] = {} self.lock = threading.RLock() try: data = json.loads(self.path.read_text()) if self.path else {} knobs, paused = data.get("knobs") or {}, data.get("paused") or {} if not isinstance(knobs, dict) or not isinstance(paused, dict) or not all( isinstance(k, str) and isinstance(v, str) for k, v in paused.items()): raise ValueError('expected {"knobs": {name: value}, "paused": {lane: reason}}') self.stored, self.paused = dict(knobs), dict(paused) except FileNotFoundError: pass except (OSError, ValueError, AttributeError) as e: # never fail the start over this file log.warning("%s: unreadable (%s); starting from the defaults", self.path, e)
def register(self, knob: Knob) -> Any: with self.lock: value = knob.check(knob.default) if knob.name in self.stored: try: value = knob.check(self.stored[knob.name]) except ValueError as e: log.warning("knobs.json: stored value ignored: %s", e) self.knobs[knob.name] = knob self.values[knob.name] = value return value
def describe(self) -> dict[str, dict[str, Any]]: with self.lock: return {n: {"value": self.values[n], "default": k.default, "type": k.type.__name__, "min": k.min, "max": k.max, "doc": k.doc} for n, k in self.knobs.items()}
def set(self, updates: dict[str, Any]) -> list[dict[str, Any]]: """Validate every update, apply them (on_change callbacks included) and save, all or nothing. Returns [{name, old, new}]; raises ValueError (nothing changed) on a bad value or a failing on_change (those already applied get on_change(old) back).""" if not isinstance(updates, dict) or not updates: raise ValueError("expected {knob: value, ...}") with self.lock: if unknown := sorted(set(updates) - set(self.knobs)): raise ValueError(f"unknown knob(s) {', '.join(unknown)}; knobs: " f"{', '.join(self.knobs) or 'none'}") checked = {n: self.knobs[n].check(v) for n, v in updates.items()} changes: list[dict[str, Any]] = [] for n, v in checked.items(): try: if self.knobs[n].on_change is not None: self.knobs[n].on_change(v) except Exception as e: # noqa: BLE001 (any refusal rolls the patch back) for c in reversed(changes): try: if self.knobs[c["name"]].on_change is not None: self.knobs[c["name"]].on_change(c["old"]) except Exception: log.exception("knob %s: restoring %r failed", c["name"], c["old"]) raise ValueError(f"{n}: the world refused {json.dumps(v)}: {e}") from None changes.append({"name": n, "old": self.values[n], "new": v}) for c in changes: self.values[c["name"]] = self.stored[c["name"]] = c["new"] self._save() return changes
def pause(self, lanes: list[str], reason: str = "") -> None: self._lanes(lanes) with self.lock: self.paused.update(dict.fromkeys(lanes, reason)) self._save()
def resume(self, lanes: list[str]) -> None: self._lanes(lanes) with self.lock: for lane in lanes: self.paused.pop(lane, None) self._save()
@staticmethod def _lanes(lanes: Any) -> None: if not isinstance(lanes, list) or not lanes or not all( isinstance(x, str) and LANE_RE.match(x) for x in lanes): raise ValueError(f"lanes: expected a list of names matching {LANE_RE.pattern}")
def _save(self) -> None: if self.path is None: return tmp = self.path.with_suffix(".tmp") tmp.write_text(json.dumps({"knobs": self.stored, "paused": self.paused}, indent=1)) tmp.replace(self.path)
# ------------------------------------------------------------------ the base class
class World: """Base class. Class attributes: `name`, `description` (shown to the agents); `concurrent` is informational (the server always runs calls concurrently: the world guards its state)."""
name: typing.ClassVar[str] = "world" description: typing.ClassVar[str] = ""
@classmethod def tool_functions(cls) -> dict[str, Callable]: """The `@tool` functions of the class, by name (in definition order).""" found = {} for klass in reversed(cls.__mro__): for attr, value in vars(klass).items(): if hasattr(value, "world_tool"): found[attr] = value return found
@classmethod def manifest(cls) -> dict[str, Any]: """{"name", "description", "tools": [{name, description, parameters, annotations?}]}, built once per class (it depends on the code only).""" if "_manifest" not in cls.__dict__: tools = [] for fn in cls.tool_functions().values(): t = tool_schema(fn) if fn.world_tool["read_only"]: t["annotations"] = {"readOnlyHint": True} tools.append(t) cls._manifest = {"name": cls.name, "description": cls.description, "tools": tools} return json.loads(json.dumps(cls._manifest))
def tools(self) -> dict[str, Callable]: """The bound `@tool` methods, by name.""" return {name: getattr(self, name) for name in self.tool_functions()}
@classmethod def pool(cls, tool: str) -> str: fn = cls.tool_functions().get(tool) return fn.world_tool["pool"] if fn is not None else "fast"
def call(self, tool: str, args: dict[str, Any], agent: Agent) -> Any: """Run `tool` for `agent` (KeyError for an unknown tool; ToolError for a refusal).""" fn = self.tool_functions()[tool] hints = typing.get_type_hints(fn) extra = {p.name: agent for p in inspect.signature(fn).parameters.values() if p.name != "self" and _is_agent(p.name, hints.get(p.name))} return fn(self, **args, **extra)
def metrics(self) -> dict[str, float]: """World-specific numbers for `GET /metrics`.""" return {}
def state_dir(self) -> str | os.PathLike | None: """Where `knobs.json` lives (None: in memory only).""" return None
@property def admin(self) -> Admin: if "_admin" not in self.__dict__: self.__dict__["_admin"] = Admin(self.state_dir()) return self.__dict__["_admin"]
def knob(self, name: str, type: type, default: Any, *, min: float | None = None, max: float | None = None, doc: str = "", on_change: Callable[[Any], None] | None = None) -> Any: """Register a runtime knob (int, float, bool or str) and return its current value: the value set through `PATCH /admin/knobs` if any (it survives restarts), else `default`. A change calls `on_change(value)` (raise to refuse it).""" if type not in KNOB_TYPES: raise ValueError(f"knob {name}: type must be one of int, float, bool, str") return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
@property def knobs(self) -> dict[str, Any]: """The knobs' current values, by name.""" return self.admin.values
def paused(self, lane: str) -> bool: """Did an operator pause `lane` (`POST /admin/pause`)?""" return lane in self.admin.paused7 unmodified lines89101112131415111213141516171819192021222324257 unmodified lines3334353536373839404141424344454247437 unmodified lines## Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless.## Required env: HF_TOKEN LEGION_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET# (hf://buckets/<ns>/<bucket>/<prefix>, or "off" for no restore and no pushes: smoke tests only).# Optional: PORT (7860), LEGION_WORLD_HOST_FILE (writes host:port there: the file legion's controller# follows), WORLD_HOST ($HOSTNAME), PYBOT_WORK (/work), every PYBOT_* world setting, and# PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here).# Required env: HF_TOKEN PYBOT_REPO PYBOT_BUCKET# (hf://buckets/<ns>/<bucket>/<prefix>, or "off" for no restore and no pushes: smoke tests only),# and PYBOT_TOKEN_<seat> for seats 0, 1, ... (agent-001, agent-002, ...): each agent's credential.# Optional: PORT (7860), PYBOT_ADMIN_TOKEN (/metrics and /admin), PYBOT_WORK (/work), every PYBOT_*# world setting, and PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here).set -euo pipefaildie() { printf '%s pybot-entrypoint: FATAL: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 2; }
for v in HF_TOKEN LEGION_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET; dofor v in HF_TOKEN PYBOT_REPO PYBOT_BUCKET; do [ -n "${!v:-}" ] || die "$v is not set"done[ -n "${PYBOT_TOKEN_0:-}" ] || die "PYBOT_TOKEN_0 is not set (the agents' credentials: PYBOT_TOKEN_<seat>)"[ -z "${PYBOT_SANDBOX_URL:-}" ] || [ -n "${PYBOT_SANDBOX_TOKEN:-}" ] \ || die "PYBOT_SANDBOX_URL is set but PYBOT_SANDBOX_TOKEN is not (the sidecar would refuse every run)"case ${PYBOT_BUCKET%/} in7 unmodified linesWORLD=${WORLD_DIR:-/opt/world}WORK=${PYBOT_WORK:-/work}# Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container.# A host PYTHONPATH must not shadow the image's installed legion.# A host PYTHONPATH must not shadow the image's installed packages.unset PYTHONPATHexport HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmpexport PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
if [ -n "${LEGION_WORLD_HOST_FILE:-}" ]; then # atomic: legion's controller re-reads it every 15 s { echo "${WORLD_HOST:-$HOSTNAME}:$PORT" > "$LEGION_WORLD_HOST_FILE.tmp" && mv "$LEGION_WORLD_HOST_FILE.tmp" "$LEGION_WORLD_HOST_FILE"; } \ || echo "pybot-entrypoint: cannot write $LEGION_WORLD_HOST_FILE" >&2fi
cd "$WORLD" || die "cannot cd $WORLD"exec python pybot.py # serve() on 0.0.0.0:$PORT; the token comes from LEGION_WORLD_TOKEN, never argvexec python pybot.py # serves on 0.0.0.0:$PORT; credentials come from the env, never argv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381"""Linux process isolation for bot and test subprocesses. Setup errors abort; there is no unsandboxed fallback.
unshare creates a user/PID/mount namespace and private procfs. The trusted setupthen builds a small root with read-only runtimes and only the caller's data,chroots and drops capabilities before executing any agent-supplied code."""from __future__ import annotations
import contextlibimport ctypesimport jsonimport osimport reimport shutilimport sysfrom collections.abc import Iteratorfrom pathlib import Path
MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC = 1, 2, 4, 8MS_REMOUNT, MS_BIND = 32, 4096MS_NOATIME, MS_NODIRATIME, MS_REC, MS_RELATIME, MS_STRICTATIME = 1024, 2048, 16384, 1 << 21, 1 << 24# statvfs flags of a mount that an unprivileged namespace cannot clear (they are locked) -># the mount(2) flags a read-only remount must repeat._LOCKED = ((os.ST_RDONLY, MS_RDONLY), (os.ST_NOSUID, MS_NOSUID), (os.ST_NODEV, MS_NODEV), (os.ST_NOEXEC, MS_NOEXEC), (os.ST_NOATIME, MS_NOATIME), (os.ST_NODIRATIME, MS_NODIRATIME), (os.ST_RELATIME, MS_RELATIME))
DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random")# The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points# and stray writes outside the bound dirs land there; the cap bounds each sandbox.TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "PYBOT_ISOLATION_TMPFS_SIZE", "256m"SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir_SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE)MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442
class IsolationSetupError(OSError): """A sandbox setup step failed: names the step and path (never argv or the env)."""
class IsolationMountError(IsolationSetupError): """A mount(2) call of the sandbox setup failed: names the target and flags, no argv."""
@contextlib.contextmanagerdef _step(step: str, path) -> Iterator[None]: """Turn a plain OSError of one setup step into an IsolationSetupError naming it.""" try: yield except IsolationSetupError: raise except OSError as e: raise IsolationSetupError(e.errno, f"isolation {step} failed: " f"{e.strerror or type(e).__name__}: path={path}") from None
def _libc(): return ctypes.CDLL(None, use_errno=True)
def protect_supervisor() -> None: """Deny same-UID ptrace and /proc/<pid>/{environ,mem,root} on the world.""" if not sys.platform.startswith("linux") or _libc().prctl(4, 0, 0, 0, 0) != 0: raise RuntimeError("PR_SET_DUMPABLE=0 is required for process isolation")
def tmpfs_size(env=os.environ) -> str: """The size cap of a sandbox's tmpfs root: $PYBOT_ISOLATION_TMPFS_SIZE (bytes, or with a k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default.""" value = (env.get(TMPFS_SIZE_ENV) or "").strip() if _SIZE.fullmatch(value): return value.lower() if value: print(f"isolation: ignoring {TMPFS_SIZE_ENV}={value!r}; using {TMPFS_SIZE_DEFAULT}", file=sys.stderr) return TMPFS_SIZE_DEFAULT
def runtime_paths(command: list[str], *, python_only=False) -> list[str]: paths = ["/usr", "/bin", "/sbin", "/lib", "/lib64", sys.prefix, sys.base_prefix] # Config files needed by Python, Node, TLS, DNS and git; never a host home or the shared-disk root. paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf", "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"] if not python_only: for binary in (command[0], "node"): found = shutil.which(binary) if not found: continue target = Path(found).resolve() modules = next((p for p in target.parents if p.name == "node_modules"), None) paths.append(str(modules or target.parent)) return sorted({str(Path(p).absolute()) for p in paths if Path(p).exists()}, key=lambda p: (len(p), p))
def symlink_chain(path: str | Path) -> tuple[list[tuple[str, str]], str]: """Resolve `path` one hop at a time: every symlink met on the way (as `(link, target)`, the target exactly as stored) and the final real path. Components that do not exist are kept as they are. A loop or more than 40 hops raises.""" links: list[tuple[str, str]] = [] pending = list(Path(os.path.abspath(path)).parts[1:]) current = Path("/") while pending: name = pending.pop(0) if name in ("", "."): continue if name == "..": current = current.parent continue candidate = current / name if not candidate.is_symlink(): current = candidate continue target = os.readlink(candidate) links.append((str(candidate), target)) if len(links) > 40: raise RuntimeError(f"isolation: too many symlinks resolving {path}") if os.path.isabs(target): current = Path("/") pending = list(Path(target).parts[1:]) + pending else: pending = list(Path(target).parts) + pending return links, str(current)
def _within(path: str, roots: list[str]) -> bool: return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
def plan(argv: list[str], *, cwd: Path, readonly=(), writable=(), python_only=False, private_dirs=(), tmp=None) -> dict: """Mounts and symlinks for the chroot. Every path is bound at its real location, and each symlink hop on the way to it (and to the interpreter, the command and node) is recreated inside, so the original spelling resolves there too (a uv venv's python links through `cpython-3.12-...` to `cpython-3.12.14-...`).""" links: dict[str, str] = {}
def real(p) -> str: hops, final = symlink_chain(p) links.update(hops) return final
ro = [real(p) for p in runtime_paths(argv, python_only=python_only) + [str(p) for p in readonly]] rw = [real(p) for p in writable] probes = [sys.executable, argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])] if not python_only: probes.append(shutil.which("node")) for probe in filter(None, probes): final = real(probe) if not _within(final, ro + rw): raise RuntimeError(f"isolation cannot represent {probe}: it resolves to {final}, " "outside every mounted path") real(cwd) def ordered(paths: list[str]) -> list[str]: # parents before nested mounts return sorted(dict.fromkeys(paths), key=lambda p: (len(p), p))
# `tmp` (a disk-backed dir) is bound over the sandbox's /tmp, so files written there do not # fill the tmpfs root. Not when a planned path lives under /tmp itself (a test's tmp_path): # the bind would hide it, and /tmp stays on the size-capped tmpfs. tmp_dir = real(tmp) if tmp is not None else None if tmp_dir is not None and any(_within(p, [SANDBOX_TMP]) for p in [*ro, *rw, *links, real(cwd)]): tmp_dir = None return {"readonly": ordered(ro), "writable": list(dict.fromkeys(rw)), "symlinks": sorted(links.items(), key=lambda kv: (len(kv[0]), kv[0])), "private_dirs": [str(Path(p).absolute()) for p in private_dirs], "tmp": tmp_dir}
def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(), network=False, python_only=False, private_dirs=(), tmp=None) -> list[str]: """Build a trusted invocation. Only explicitly mounted paths survive the chroot. `tmp`: a disk-backed directory bound writable at the sandbox's /tmp (see `plan`).""" unshare = shutil.which("unshare") if not unshare: raise RuntimeError("unshare is required for process isolation") config = {"root": str(root.absolute()), "cwd": str(cwd.absolute()), "readonly_root": not network, "tmpfs_size": tmpfs_size(), **plan(argv, cwd=cwd, readonly=readonly, writable=writable, python_only=python_only, private_dirs=private_dirs, tmp=tmp)} # A reclaim may send USR1 to every process. Only the world handles it; an unshare # wrapper must survive long enough for its bounded drain. return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "pybot-isolate", unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL", "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--", sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
def _mount(source, target, kind=None, flags=0, data=None): def encoded(value): return os.fsencode(value) if value is not None else None libc = _libc() libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_ulong, ctypes.c_char_p] if libc.mount(encoded(source), encoded(target), encoded(kind), flags, encoded(data)) != 0: errno = ctypes.get_errno() raise IsolationMountError(errno, f"isolation mount failed: {os.strerror(errno)}: " f"source={source} target={target} type={kind} " f"flags={flags:#x}")
def readonly_remount_flags(target) -> int: """MS_REMOUNT|MS_BIND|MS_RDONLY plus nosuid/nodev, and every locked flag the bound mount already has (statvfs of the bind target): a user namespace cannot clear them, and leaving them out fails with EPERM. No atime flag on the source means strictatime.""" inherited = os.statvfs(target).f_flag flags = MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV for flag, mount_flag in _LOCKED: if inherited & flag: flags |= mount_flag if not inherited & (os.ST_NOATIME | os.ST_RELATIME): flags |= MS_STRICTATIME return flags
def _readonly_recursive(target) -> bool: """mount_setattr(AT_RECURSIVE, MOUNT_ATTR_RDONLY): make every submount of a recursive bind read-only too (a remount only changes the top one). False if the kernel lacks it (before 5.12); the mountinfo check still refuses a writable submount.""" libc = _libc() attr = (ctypes.c_uint64 * 4)(MOUNT_ATTR_RDONLY, 0, 0, 0) libc.syscall.restype = ctypes.c_long rc = libc.syscall(ctypes.c_long(SYS_MOUNT_SETATTR), ctypes.c_int(AT_FDCWD), ctypes.c_char_p(os.fsencode(target)), ctypes.c_uint(AT_RECURSIVE), ctypes.byref(attr), ctypes.c_size_t(ctypes.sizeof(attr))) # Any failure (ENOSYS before 5.12, EPERM on a locked mount): the mountinfo check that # follows the binds still refuses a writable submount. return rc == 0
def _unescape(field: str) -> str: return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field)
def parse_mountinfo(text: str) -> list[tuple[str, set[str]]]: """(mount point, per-mount options) of each /proc/self/mountinfo line.""" out = [] for line in text.splitlines(): fields = line.split() if len(fields) >= 6: out.append((_unescape(fields[4]), set(fields[5].split(",")))) return out
def check_mounts(mounts: list[tuple[str, set[str]]], root: str, readonly: list[str], writable: list[str] = (), extra: list[str] = ()) -> None: """Fail closed after the binds. Every mount under `root` must be a planned target (or `extra`: proc, the /dev nodes), or a submount a recursive bind of one brought along (e.g. a container's zoneinfo file bound over /usr's); and every mount at or under a read-only target, outside a writable one, must be `ro`.""" def under(path: str, roots) -> bool: return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
planned = [*readonly, *writable, *extra] for point, opts in mounts: if point == root or not under(point, [root]): continue if not under(point, planned): raise IsolationMountError(1, f"isolation: unexpected mount {point} in the sandbox root") if under(point, readonly) and not under(point, writable) and "ro" not in opts: raise IsolationMountError(30, f"isolation: {point} is mounted writable under a " "read-only path")
def _bind(root: Path, source: str, *, readonly: bool, target: Path | None = None): """Bind `source` at its own path under `root` (or at `target`, a path under `root`).""" path = Path(source) if not path.exists(): raise IsolationSetupError(2, f"isolation bind failed: required path is missing: path={source}") target = target if target is not None else root / path.relative_to("/") # Create the mount point only when missing: it may already exist on a read-only bind # (/etc/localtime -> /usr/share/zoneinfo/... under the /usr bind), where touch()'s utime # fails with EROFS. with _step("mount point creation", target): target.parent.mkdir(parents=True, exist_ok=True) if path.is_dir(): if not target.is_dir(): target.mkdir() elif not target.exists(): target.touch() # Recursive: a user namespace refuses (EINVAL) a non-recursive bind of a tree that has # locked submounts, since it would uncover what they hide. Only explicitly listed paths # are bound, so a submount comes in only under a path that was asked for. _mount(source, target, flags=MS_BIND | MS_REC) if readonly: # Step two: read-only only works as a remount of the bind, with the locked flags; # then the submounts the recursive bind brought along, where the kernel can. _mount(None, target, flags=readonly_remount_flags(target)) _readonly_recursive(target)
def _drop_privileges(): libc = _libc() # NOROOT + locked: exec as namespace uid 0 must never regain capabilities. if libc.prctl(28, 3, 0, 0, 0) or libc.prctl(38, 1, 0, 0, 0): raise RuntimeError("cannot lock sandbox privileges") # All currently defined capabilities fit below 64. EINVAL marks unsupported bits. for cap in range(64): if libc.prctl(24, cap, 0, 0, 0) != 0 and ctypes.get_errno() != 22: raise RuntimeError("cannot drop sandbox capability bounding set") class Header(ctypes.Structure): _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)] class Data(ctypes.Structure): _fields_ = [("effective", ctypes.c_uint32), ("permitted", ctypes.c_uint32), ("inheritable", ctypes.c_uint32)] if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()) != 0: raise RuntimeError("cannot clear sandbox capabilities")
OOM_SCORE_ADJ = 800 # sandboxed processes die before the world (which keeps 0) on an OOM kill
def set_oom_score_adj(value: int = OOM_SCORE_ADJ, path: str = "/proc/self/oom_score_adj") -> bool: """Raise this process's OOM score (inherited by what it execs). Raising needs no privilege; False when /proc refuses it.""" try: Path(path).write_text(str(value)) return True except OSError: return False
def _enter(config, argv): # Never share a process group with a supervisor outside the PID namespace. if os.getpgrp() != os.getpid(): os.setsid() set_oom_score_adj() root = Path(config["root"]) with _step("root creation", root): root.mkdir(parents=True, exist_ok=True) size = config.get("tmpfs_size") or TMPFS_SIZE_DEFAULT if not _SIZE.fullmatch(size): raise IsolationSetupError(22, f"isolation tmpfs size is invalid: path={root}") _mount("tmpfs", root, "tmpfs", MS_NOSUID | MS_NODEV, f"mode=755,size={size}") for path in config["readonly"]: _bind(root, path, readonly=True) for path in config["writable"]: _bind(root, path, readonly=False) for link, target in config.get("symlinks", ()): inside = root / Path(link).relative_to("/") if os.path.lexists(inside): continue # already visible through a bind mount with _step("symlink creation", inside): inside.parent.mkdir(parents=True, exist_ok=True) inside.symlink_to(target) for path in config["private_dirs"]: with _step("private directory creation", path): (root / Path(path).relative_to("/")).mkdir(parents=True, exist_ok=True) for path in ("tmp", "proc", "dev"): with _step("directory creation", root / path): (root / path).mkdir(exist_ok=True) if config.get("tmp"): # the sandbox's /tmp on the caller's disk-backed dir, not the tmpfs _bind(root, config["tmp"], readonly=False, target=root / SANDBOX_TMP.lstrip("/")) for path in DEV_NODES: _bind(root, path, readonly=False) with _step("symlink creation", root / "dev/fd"): (root / "dev/fd").symlink_to("/proc/self/fd") _mount("proc", root / "proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC) inside = lambda p: os.path.realpath(root / Path(p).relative_to("/")) check_mounts(parse_mountinfo(Path("/proc/self/mountinfo").read_text()), os.path.realpath(root), [inside(p) for p in config["readonly"]], [inside(p) for p in (*config["writable"], *([SANDBOX_TMP] if config.get("tmp") else []))], [inside(p) for p in ("/proc", *DEV_NODES)]) if config["readonly_root"]: _mount(None, root, flags=MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV) with _step("chroot", root): os.chroot(root) with _step("chdir", config["cwd"]): os.chdir(config["cwd"]) _drop_privileges() os.execvpe(argv[0], argv, dict(os.environ))
if __name__ == "__main__": try: _enter(json.loads(sys.argv[1]), sys.argv[2:]) except IsolationSetupError as e: # step, path and flags only, never argv or the env print(f"process isolation failed during setup: {e.strerror}", file=sys.stderr) raise SystemExit(125) from None except Exception: # noqa: BLE001 - fail closed, without leaking arguments or paths # Paths, argv and errors could contain credentials. Fail closed without their values. print("process isolation failed during setup", file=sys.stderr) raise SystemExit(125) from None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385"""External-write lanes for worlds: bounded concurrency, a circuit breaker and a persistent outbox.
A world that writes to an outside service (a Git host, an API with one token) gives each kindof write its own lane, so one kind never starves another:
lanes = Lanes({"push": Lane(slots=1), "merge": Lane(slots=1), "comment": Lane(slots=1, gap_s=1.0)}, dir=state_dir) with lanes.hold("push", deadline=time.monotonic() + 20) as slot: # LaneBusy past deadline ...write...; slot.ok() # or slot.fail("transient") / slot.fail("final") lanes.outbox("comment", drain=post).put(key=pr, payload=text) # persistent, never drops
`Lane.slots`, `Lane.gap_s` and `Lane.paused` are plain attributes (`Lane.configure()` changesthe first two and wakes waiters); the breaker never changes them, it only lowers what iseffective while tripped."""from __future__ import annotations
import collectionsimport contextlibimport jsonimport loggingimport osimport threadingimport timeimport uuidfrom pathlib import Path
log = logging.getLogger(__name__)POLL_S = 0.25 # longest single wait: notices pause flips, configure() and a test's fake clock
class LaneBusy(Exception): """No slot within the deadline; `reason` is "slots", "gap" or "paused"."""
def __init__(self, lane: str, reason: str, retry_after_s: float) -> None: super().__init__(f"lane {lane} busy ({reason}); retry in {retry_after_s:.0f} s") self.lane, self.reason, self.retry_after_s = lane, reason, retry_after_s
class Breaker: """Transient failures of one lane, or of a group of lanes that trip together."""
def __init__(self, trip_after: int, trip_window_s: float, quiet_s: float) -> None: self.trip_after, self.trip_window_s, self.quiet_s = trip_after, trip_window_s, quiet_s self.name = "" self.lock = threading.Lock() # a leaf lock: taken with a lane's cond held self.failures = collections.deque() # clock times of recent transient failures self.tripped = False
def failure(self, now: float) -> None: with self.lock: self.failures.append(now) while self.failures and self.failures[0] < now - self.trip_window_s: self.failures.popleft() if not self.tripped and len(self.failures) >= self.trip_after: self.tripped = True log.warning("lanes %s: tripped after %d transient failures in %.0f s; 1 slot and " "a gap until %.0f quiet s", self.name, len(self.failures), self.trip_window_s, self.quiet_s)
def is_tripped(self, now: float) -> bool: """Ends a trip after quiet_s without a transient failure.""" with self.lock: if self.tripped and now - self.failures[-1] >= self.quiet_s: self.tripped = False self.failures.clear() log.warning("lanes %s: recovered after %.0f quiet s", self.name, self.quiet_s) return self.tripped
class Lane: """One kind of external write.
Breaker: `trip_after` transient failures within `trip_window_s` trip the lane to min(slots, 1) slot and at least `trip_gap_s` between writes; after `quiet_s` without a transient failure it returns to `slots` and `gap_s`. `Lanes(breaker_groups=)` makes lanes share one breaker (the first lane's trip_after, trip_window_s and quiet_s)."""
def __init__(self, slots: int = 1, gap_s: float = 0.0, *, trip_after: int = 3, trip_window_s: float = 900.0, trip_gap_s: float = 5.0, quiet_s: float = 600.0, retry_after_s: float = 60.0) -> None: self.slots, self.gap_s, self.paused = slots, gap_s, False self.breaker = Breaker(trip_after, trip_window_s, quiet_s) self.trip_gap_s, self.retry_after_s = trip_gap_s, retry_after_s self.name, self.clock, self.paused_fn = "", time.monotonic, None # set by Lanes self.cond = threading.Condition() self.in_flight, self.last_at = 0, float("-inf") self.stats = {"waits_total": 0, "wait_s_total": 0.0, "ok": 0, "transient": 0, "final": 0}
def configure(self, slots: int | None = None, gap_s: float | None = None) -> None: with self.cond: if slots is not None: self.slots = slots if gap_s is not None: self.gap_s = gap_s self.cond.notify_all()
def is_paused(self) -> bool: return self.paused or bool(self.paused_fn and self.paused_fn(self.name))
def _effective(self, now): """(slots, gap_s) in force now (cond held).""" if self.breaker.is_tripped(now): return min(self.slots, 1), max(self.gap_s, self.trip_gap_s) return self.slots, self.gap_s
def acquire(self, deadline: float | None, pausable: bool = True) -> None: with self.cond: start = now = self.clock() while True: slots, gap = self._effective(now) reason = ("paused" if pausable and self.is_paused() else "slots" if self.in_flight >= slots else "gap" if now < self.last_at + gap else None) if reason is None: break if deadline is not None and now >= deadline: self.stats["waits_total"] += 1 self.stats["wait_s_total"] += now - start retry = (self.last_at + gap - now) if reason == "gap" else self.retry_after_s raise LaneBusy(self.name, reason, max(1.0, retry)) self.cond.wait(POLL_S if deadline is None else min(POLL_S, deadline - now)) now = self.clock() if now > start: self.stats["waits_total"] += 1 self.stats["wait_s_total"] += now - start self.in_flight += 1 self.last_at = now
def release(self) -> None: with self.cond: self.in_flight -= 1 self.cond.notify_all()
def report(self, kind: str) -> None: """Count an outcome: "ok", "transient" (feeds the breaker) or "final".""" with self.cond: self.stats[kind] += 1 if kind == "transient": self.breaker.failure(self.clock())
def metrics(self) -> dict: with self.cond: now = self.clock() slots, _ = self._effective(now) return {"slots": self.slots, "effective_slots": slots, "in_flight": self.in_flight, **self.stats, "tripped": int(self.breaker.is_tripped(now)), "paused": int(self.is_paused())}
class Slot: """A held slot: report the write's outcome with ok() or fail()."""
def __init__(self, lane: Lane) -> None: self.lane = lane
def ok(self) -> None: self.lane.report("ok")
def fail(self, kind: str = "transient") -> None: if kind not in ("transient", "final"): raise ValueError("kind must be transient or final") self.lane.report(kind)
class Outbox: """Writes for one lane that must happen eventually, drained by a background thread.
`drain(key, payloads)` makes one write of the queued payloads of `key` (more than one when they piled up: the world joins them; at most max_batch of them and max_chars characters, or one) and returns "ok", "transient" or "final" (an exception counts as transient), or "split": retry the key's payloads one per write (e.g. the service refused a joined write). Transient failures retry forever with capped doubling backoff; only ok and final remove payloads. Stored as JSON lines in `path` (keys: str or int), compacted on load and when mostly settled."""
def __init__(self, lanes: Lanes, name: str, path: Path, drain, backoff=(5.0, 600.0), max_batch: int = 10, max_chars: int = 60_000) -> None: self.lanes, self.name, self.path, self.drain = lanes, name, path, drain self.backoff, self.max_batch, self.max_chars = backoff, max_batch, max_chars self.lock = threading.Lock() self.entries = {} # key -> {"payloads", "queued_at", "tries", "next_at"} in put order self.lines = 0 # lines in the file self._load() self.stop, self.wake = threading.Event(), threading.Event() self.thread = threading.Thread(target=self._run, name=f"lane-{name}-outbox", daemon=True) if drain is not None: self.thread.start()
def _entry(self, key, ts): return self.entries.setdefault(key, {"payloads": [], "queued_at": ts, "tries": 0, "next_at": 0.0, "batch": self.max_batch})
def _load(self): if self.path.exists(): for line in self.path.read_text().splitlines(): try: op = json.loads(line) if "put" in op: self._entry(op["put"], op["ts"])["payloads"].append(op["payload"]) elif op["done"] in self.entries: entry = self.entries[op["done"]] del entry["payloads"][:op["n"]] if not entry["payloads"]: del self.entries[op["done"]] except (ValueError, KeyError, TypeError): # a line cut by a crash log.warning("lane %s outbox: skipped an unreadable line", self.name) self._compact()
def _compact(self): """Rewrite the file with the pending payloads only (lock held, or during __init__).""" self.path.parent.mkdir(parents=True, exist_ok=True) tmp = self.path.with_name(f"{self.path.name}.{uuid.uuid4().hex}.tmp") with open(tmp, "w") as out: for key, e in self.entries.items(): out.writelines(json.dumps({"put": key, "payload": payload, "ts": e["queued_at"]}) + "\n" for payload in e["payloads"]) out.flush() os.fsync(out.fileno()) # the data is on disk before the name points at it os.replace(tmp, self.path) self.lines = sum(len(e["payloads"]) for e in self.entries.values())
def _append(self, op): with open(self.path, "a") as out: out.write(json.dumps(op) + "\n") self.lines += 1
def put(self, key, payload) -> None: """Queue payload for key; joins payloads of the same key still waiting.""" with self.lock: ts = self.lanes.wall() self._append({"put": key, "payload": payload, "ts": ts}) self._entry(key, ts)["payloads"].append(payload) self.wake.set()
def depth(self) -> tuple[int, float]: """(pending payloads, age in seconds of the oldest).""" with self.lock: now = self.lanes.wall() return (sum(len(e["payloads"]) for e in self.entries.values()), max((now - e["queued_at"] for e in self.entries.values()), default=0.0))
def _settle(self, key, n, kind): with self.lock: entry = self.entries.get(key) if entry is None: return if kind == "split": entry["batch"] = 1 return if kind == "transient": entry["tries"] += 1 delay = min(self.backoff[1], self.backoff[0] * 2 ** (entry["tries"] - 1)) entry["next_at"] = self.lanes.wall() + delay log.warning("lane %s outbox: write for %r failed; retry %d in %.0f s", self.name, key, entry["tries"], delay) return if kind == "final": log.warning("lane %s outbox: dropped %d payload(s) for %r: final", self.name, n, key) del entry["payloads"][:n] entry["tries"], entry["next_at"] = 0, 0.0 if kind != "ok": entry["batch"] = 1 # the rest of a refused batch goes one by one if not entry["payloads"]: del self.entries[key] self._append({"done": key, "n": n}) pending = sum(len(e["payloads"]) for e in self.entries.values()) if self.lines > 2 * pending + 1000: self._compact()
def _batch(self, key): """The payloads of key for the next write (lock held): oldest first, within the entry's batch size and max_chars, at least one.""" entry = self.entries.get(key) if entry is None: return [] out, chars = [], 0 for payload in entry["payloads"][:entry["batch"]]: chars += len(payload if isinstance(payload, str) else json.dumps(payload)) if out and chars > self.max_chars: break out.append(payload) return out
def _run(self): while not self.stop.is_set(): try: self._step() except Exception: # keep the thread alive: a disk error, a bad drain result log.exception("lane %s outbox: drain loop failed", self.name) self.stop.wait(POLL_S)
def _step(self): with self.lock: now = self.lanes.wall() due = [(e["queued_at"], i, k) for i, (k, e) in enumerate(self.entries.items()) if e["next_at"] <= now] key = min(due)[2] if due else None if key is None: self.wake.wait(POLL_S) self.wake.clear() return try: with self.lanes.hold(self.name, deadline=self.lanes.clock() + 1.0) as slot: with self.lock: # taken with the slot held: joins what piled up meanwhile payloads = self._batch(key) if not payloads: return try: kind = self.drain(key, payloads) or "ok" except Exception: log.exception("lane %s outbox: drain failed", self.name) kind = "transient" if kind not in ("ok", "transient", "final", "split"): raise ValueError(f"drain returned {kind!r}") if kind == "split" and len(payloads) == 1: kind = "transient" if kind == "ok": slot.ok() elif kind != "split": slot.fail(kind) except LaneBusy: self.stop.wait(POLL_S) return self._settle(key, len(payloads), kind)
def close(self, timeout: float = 5.0) -> None: self.stop.set() self.wake.set() if self.thread.is_alive() and self.thread is not threading.current_thread(): self.thread.join(timeout)
class Lanes: """Named lanes sharing a clock, an optional `paused(name)` callback and a state dir for outboxes (`<dir>/outbox-<name>.jsonl`). `breaker_groups`: tuples of lane names that share one breaker (writes that fail together, e.g. two kinds that move the same refs)."""
def __init__(self, lanes: dict[str, Lane], dir: str | Path | None = None, clock=time.monotonic, wall=time.time, paused=None, breaker_groups: list[tuple[str, ...]] = ()) -> None: self.lanes, self.dir, self.clock, self.wall = lanes, Path(dir) if dir else None, clock, wall self.outboxes: dict[str, Outbox] = {} for name, lane in lanes.items(): lane.name, lane.clock, lane.paused_fn = name, clock, paused lane.breaker.name = name for group in breaker_groups: # a transient failure in any of them trips them all shared = lanes[group[0]].breaker shared.name = "+".join(group) for name in group[1:]: lanes[name].breaker = shared
def __getitem__(self, name: str) -> Lane: return self.lanes[name]
@contextlib.contextmanager def hold(self, name: str, deadline: float | None = None, pausable: bool = True): """Hold a slot of lane `name`, waiting until `deadline` (on `clock`; None: no limit); raises LaneBusy. `pausable=False` ignores the pause (e.g. closing what was opened).""" lane = self.lanes[name] lane.acquire(deadline, pausable) try: yield Slot(lane) finally: lane.release()
def outbox(self, name: str, drain=None, **kwargs) -> Outbox: """The lane's outbox; the first call with `drain` starts its drainer thread.""" if name not in self.outboxes: if self.dir is None: raise ValueError("Lanes(dir=...) is needed for an outbox") self.outboxes[name] = Outbox(self, name, self.dir / f"outbox-{name}.jsonl", drain, **kwargs) return self.outboxes[name]
def metrics(self) -> dict[str, dict]: out = {} for name, lane in self.lanes.items(): box = self.outboxes.get(name) depth, age = box.depth() if box else (0, 0.0) out[name] = {**lane.metrics(), "outbox_depth": depth, "outbox_oldest_age_s": age} return out
def close(self, timeout: float = 5.0) -> None: """Stop the drainer threads; what is queued stays on disk for the next start.""" end = time.monotonic() + timeout for box in self.outboxes.values(): box.close(max(0.0, end - time.monotonic()))1123451 unmodified line789910111211 unmodified lines24252627282930312930313233343233343537363738394041444542434445461 unmodified line484950535152535415 unmodified lines707172757374757654 unmodified lines1311321331361371381341351361373 unmodified lines14114214314814915015115214414515515615715815916016116214614714827 unmodified lines17617717819617918018118270 unmodified lines253254255273256257258259244 unmodified lines504505506524507508509510452 unmodified lines96396496598398496696796818 unmodified lines98798898910091010101110129909919929939949959969979989991000100110021003100410051006100710081009101010111014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610121013101410151016101710371038103910401041104210431044104510461047104810491050105110521053105410551056105710181019106010611062106310641065106610671068106910701071107210731074107510761077102010211022102310241078107910801081108210831084108510861087108810891090109110921093109410951096102510981099110010261027102811021029103010311032103310341035103610371038103910401041104239 unmodified lines10821083108411481085108610871151108810891090109110 unmodified lines110211031104116811051106117011711172117311071108110911101111111211134 unmodified lines11181119112011841121112211231124119 unmodified lines12441245124613101247124812491250373 unmodified lines16241625162616901627162816291630468 unmodified lines20992100210121652102210321042105216921062107217121082109211021112112211321142115211621762177217821792180218121822183218421852186211721882118211921202121212215 unmodified lines21382139214021412210214221432144214521462215221622172147"""Run-4 world: local snapshots, native Hub PRs and independent reviews.""""""The pybot world: local snapshots, native Hub PRs and independent reviews (`python pybot.py`serves it on $PORT, server.py)."""from __future__ import annotations
import atexit1 unmodified lineimport collectionsimport concurrent.futuresimport contextlibimport contextvarsimport functoolsimport hashlibimport inspect11 unmodified linesfrom typing import ClassVar, Literal
import snapshotfrom api import Agent, ToolError, World, toolfrom isolation import protect_supervisorfrom lanes import Lane, LaneBusy, Lanesfrom repository import Hub, Repositoryfrom sandbox import run, run_tests
from legion.isolation import protect_supervisorfrom legion.world import Agent, ToolError, World, toolfrom legion.world.lanes import Lane, LaneBusy, Lanesfrom legion.world.store import Storefrom legion.world.workspace import apply_patch, unpackfrom store import Storefrom workspace import apply_patch
HERE = Path(__file__).resolve().parentUPLOAD = contextvars.ContextVar("workspace", default=None)FIXED = ("bot/__init__.py", "bot/__main__.py", "bot/runtime.py", "bot/modules/__init__.py")# A module the loader finds: bot/modules/<name>.py or a package bot/modules/<name>/__init__.py.MODULE_FILE = re.compile(r"bot/modules/(?:[^/]+\.py|[^/]+/__init__\.py)")MAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20)))EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/", "*.egg-info/", ".DS_Store")MAX_REQUESTS = 5000 # open_pr idempotency keys kept for worker retries (oldest dropped)# ... and for at most this long (a worker retries within minutes).MAX_REQUESTS = 5000 # open_pr idempotency keys (X-Request-Id) kept for retries (oldest dropped)# ... and for at most this long (a client retries within minutes).REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600"))# state.db (and prs.json, see save.legacy_json) is written by a background thread at most once# per this many seconds while the state changed (0: write synchronously on every change).1 unmodified lineSAVE_INTERVAL = float(os.environ.get("PYBOT_SAVE_INTERVAL_S", "2.0"))FETCH_TTL = float(os.environ.get("PYBOT_FETCH_TTL_S", "60"))NAME = re.compile(r"^[a-z][a-z0-9-]{0,63}$")# A world tool call must answer within about 55 s (the worker's deadline); Hub waits and push# A world tool call must answer within about a minute (a caller's deadline); Hub waits and push# retries stay inside this budget, counted from the start of the call.CALL_BUDGET = float(os.environ.get("PYBOT_CALL_BUDGET_S", "50"))PUSH_RETRY_DELAYS = (2, 5)15 unmodified linesCOMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub post# get_pr: diff bytes returned (cut at a line end, with truncated: true beyond this).MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))# State rows in state.db (legion.world.store): these top-level dicts get one row per entry;# State rows in state.db (store.py): these top-level dicts get one row per entry;# every other top-level value (pr_opens, pr_merges) is one row of kind "_".KINDS = ("prs", "requests", "drafts", "inbox")COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this54 unmodified lines
class PybotWorld(World): name, version = "pybot", "1.0.0" concurrent = True capabilities: ClassVar[list[str]] = ["workspace-upload-v1", "workspace-upload-v2"] name = "pybot" description = ("Edit your local git clone, then submit with open_pr. Another agent must " "approve the PR's current change (a clean rebase keeps the approval) before merge; " "merge_pr queues a PR and the world merges the queue in order, rebasing each PR "3 unmodified lines "merges and refused merges, closes, updates); handle it first. New PRs are limited swarm-wide to " "about the merge rate (pr_budget).")
# The worker uploads the caller's local clone for these calls (workspace-upload-v1). WORKSPACE: ClassVar[dict] = { "open_pr": {"arg": "path", "default": "pybot"}, "run_bot": {"arg": "ref_or_path", "default": "main", "skip": ["main"], "skip_prefix": "pr:"}, } MERGER: ClassVar[bool] = True # start the merge queue's thread (tests run it by hand: _merge_next)
def manifest(self) -> dict: m = super().manifest() for t in m["tools"]: t["x-legion-timeout_s"] = 330 # a 300 s run_bot conversation plus the upload if t["name"] in self.WORKSPACE: t["x-legion-workspace"] = self.WORKSPACE[t["name"]] return m
def __init__(self, ws=None, repository=None): protect_supervisor() self.ws = Path(ws or os.environ.get("PYBOT_WS", HERE / "ws"))27 unmodified lines # Saving (see _save): every change marks its rows dirty (_dirty) and bumps save_gen; # the saver writes the dirty rows to state.db and, while save.legacy_json is on, the # whole state to prs.json (written_gen is the generation in prs.json). self.save_interval = self.knob( # admin knobs (legion.world.admin): the env sets the default self.save_interval = self.knob( # admin knobs (api.py): the env sets the default "save.interval_s", float, float(os.environ.get("PYBOT_SAVE_INTERVAL_S", SAVE_INTERVAL)), min=0, doc="Seconds between state saves (0: write on every change).", on_change=lambda v: setattr(self, "save_interval", v))70 unmodified lines # agents at once): "push" for creating, pushing, readying and closing PRs, "merge" for # merges (never queued behind pushes, whose wait would let main or the PR move under # its checks), "comment" for review comments, posted from the outbox. Each lane has a # breaker (legion.world.lanes); the pause covers push and merge. Lock order: see self.lock. # breaker (lanes.py); the pause covers push and merge. Lock order: see self.lock. # Admin pauses (POST /admin/pause) apply per lane; the pause flag pauses push and merge. self.lanes = Lanes({"push": Lane(), "merge": Lane(), "comment": Lane()}, dir=self.ws, paused=lambda lane: self.paused(lane) or (244 unmodified lines setattr(self, name, getattr(self, name) + n)
def metrics(self): """World numbers for GET /metrics (legion.world.server).""" """World numbers for GET /metrics (server.py).""" now = time.time() with self.lock: budget = self._budget()452 unmodified lines inbox is non-empty. open_pr, review_pr, merge_pr and close_pr results carry pr_budget. A ToolError leaves the inbox untouched.""" result = super().call(tool, args, agent) if inspect.isawaitable(result): return result if isinstance(result, dict) and tool in ("open_pr", "review_pr", "merge_pr", "close_pr"): with self.lock: result = {**result, "pr_budget": self._budget()}18 unmodified lines if not NAME.fullmatch(agent.name): raise ToolError("invalid agent identity")
def call_workspace(self, name, args, agent, snapshot): if name not in ("open_pr", "run_bot"): raise ToolError("this tool does not accept workspace uploads") token = UPLOAD.set(snapshot) def _workspace(self, workspace): """Check a workspace's shape and that its base is in the repository (fetched from the Hub when missing: unknown_base if still not there). Returns its base sha.""" base = workspace.get("base_sha") if isinstance(workspace, dict) else None if not (isinstance(base, str) and re.fullmatch(r"[0-9a-f]{40}", base) and isinstance(workspace.get("patch"), str)): raise ToolError('workspace must be {"base_sha": "<40 hex>", "patch": "<base64>"}', "bad_workspace") if not self.repo.has_commit(base): self.repo.refresh(0) if not self.repo.has_commit(base): raise ToolError(f"unknown base {base[:12]}: fetch origin/main and rebase your branch", "unknown_base") return base
def _files(self, workspace, tree): """Apply a workspace's patch on tree, a checkout of its base. Returns the paths that differ from the base, for the compile check.""" # Default excludes even if an agent drops .gitignore: caches are never committed. (tree / ".git/info").mkdir(exist_ok=True) (tree / ".git/info/exclude").write_text("\n".join(EXCLUDE) + "\n") try: return self.call(name, args, agent) finally: UPLOAD.reset(token)
def _files(self, snapshot, tree): """Apply an upload over tree (a checkout of its base, or an empty directory).
Byte-identical files are not rewritten; tracked files missing from the upload are deleted. Returns the paths that differ from the tree, for the compile check. A v2 upload (a patch) applies only on a checkout of its base. """ if (tree / ".git").is_dir(): # Default excludes even if an agent drops .gitignore: caches are never committed. (tree / ".git/info").mkdir(exist_ok=True) (tree / ".git/info/exclude").write_text("\n".join(EXCLUDE) + "\n") if "patch" in snapshot: try: names = apply_patch(snapshot, tree) except (ValueError, OSError) as exc: raise ToolError(f"invalid workspace upload: {exc}"[:300], "bad_workspace") from exc for name in names: f = tree / name if f.is_file() and f.stat().st_size > MAX_FILE_BYTES: names = apply_patch(workspace, tree) except (ValueError, OSError) as exc: raise ToolError(f"invalid workspace: {exc}"[:300], "bad_workspace") from exc for name in names: f = tree / name if f.is_file() and f.stat().st_size > MAX_FILE_BYTES: raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; " "remove it from the clone or add it to .gitignore", "file_too_large") return names files = snapshot.get("files") if not isinstance(files, dict): raise ToolError("invalid workspace upload", "bad_workspace") changed = {} for name, encoded in files.items(): rel = PurePosixPath(name) if isinstance(name, str) else None if (rel is None or rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts or "\\" in name or not isinstance(encoded, str)): raise ToolError("invalid workspace upload", "bad_workspace") if len(encoded) > (MAX_FILE_BYTES + 2) // 3 * 4: raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; " "remove it from the clone or add it to .gitignore", "file_too_large") target = tree / rel try: data = base64.b64decode(encoded, validate=True) except ValueError as exc: raise ToolError("invalid workspace upload", "bad_workspace") from exc if len(data) > MAX_FILE_BYTES: raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; " "remove it from the clone or add it to .gitignore", "file_too_large") if target.is_file() and not target.is_symlink() and target.read_bytes() == data: continue changed[name] = encoded if (tree / ".git").is_dir(): tracked = self.repo.git("ls-files", "-z", at=tree).split("\0") for name in tracked: if name and name not in files: (tree / name).unlink(missing_ok=True) changed.setdefault(name, None) try: unpack({"files": {k: v for k, v in changed.items() if v is not None}}, tree) except (ValueError, TypeError, OSError) as exc: raise ToolError("invalid workspace upload", "bad_workspace") from exc return sorted(changed)
def _adds_module(self, snapshot, base): """Does an upload add a module the loader finds (MODULE_FILE, new or renamed to)? Anything unreadable counts as adding one, so the budget still applies to it.""" return names
def _adds_module(self, workspace): """Does a workspace's patch add a module the loader finds (MODULE_FILE, new or renamed to)? Anything unreadable counts as adding one, so the budget still applies to it.""" if "patch" in snapshot: try: patch = base64.b64decode(snapshot.get("patch") or "", validate=True) except (ValueError, TypeError): return True for block in re.split(rb"^diff --git ", patch, flags=re.MULTILINE)[1:]: header = block.split(b"\n@@", 1)[0].decode(errors="replace") names = re.match(r"a/(\S+) b/(\S+)\n", header) if names is None: # a quoted path (spaces, non-ASCII): count it if it may be one if "bot/modules/" in header.split("\n", 1)[0]: return True continue old, new = names.groups() if MODULE_FILE.fullmatch(new) and ("\nnew file mode" in header or old != new): return True return False files = snapshot.get("files") if not isinstance(files, dict): return True try: tracked = set(self.repo.git("ls-tree", "-r", "--name-only", base, "--", "bot/modules") .splitlines()) except ToolError: patch = base64.b64decode(workspace.get("patch") or "", validate=True) except (ValueError, TypeError, AttributeError): return True return any(isinstance(n, str) and MODULE_FILE.fullmatch(n) and n not in tracked for n in files) for block in re.split(rb"^diff --git ", patch, flags=re.MULTILINE)[1:]: header = block.split(b"\n@@", 1)[0].decode(errors="replace") names = re.match(r"a/(\S+) b/(\S+)\n", header) if names is None: # a quoted path (spaces, non-ASCII): count it if it may be one if "bot/modules/" in header.split("\n", 1)[0]: return True continue old, new = names.groups() if MODULE_FILE.fullmatch(new) and ("\nnew file mode" in header or old != new): return True return False
def _contract(self, tree, names=None): """Check the fixed interface, and that names (default: every .py file) compile."""39 unmodified lines @tool(pool="slow") @logs_refusals def open_pr(self, agent: Agent, branch: str, title: str, description: str, path: str = "pybot", pr: int | None = None) -> dict: path: str = "pybot", pr: int | None = None, workspace: dict | None = None) -> dict: """Submit your local clone, or update your existing PR with pr:<number>.
The worker uploads path from your private workspace. Include tests and run_bot path is your clone; the pybot tools send its change as workspace. Include tests and run_bot evidence in description. At most two open PRs per agent. Read CONTRIBUTING.md. branch is a short slug like my-topic; the world stores it as agents/<you>/<slug>. New PRs are budgeted swarm-wide: one is refused (code open_budget) while the swarm10 unmodified lines raise ToolError(f"title must be 3–200 characters (got {len(title) if isinstance(title, str) else 0})") if not isinstance(description, str) or not description.strip(): raise ToolError("description must not be empty") snapshot = UPLOAD.get() snapshot = workspace if not isinstance(snapshot, dict): raise ToolError("submit a local clone through legion-tool; the worker uploads it") # Scope new_modules: a PR that adds no module is outside the budget (git runs unlocked). exempt = (self.budget_scope == "new_modules" and not self._adds_module(snapshot, snapshot.get("base_sha", ""))) raise ToolError("open_pr needs your clone's change: call it through the pybot tools, " "which send it as workspace", "bad_workspace") # Scope new_modules: a PR that adds no module is outside the budget. exempt = self.budget_scope == "new_modules" and not self._adds_module(snapshot) key = agent.request_id branch_ref = f"agents/{agent.name}/{branch}" with self.lock:4 unmodified lines # The lock is held only for state and the main check; fetches, copies, compiles, # Hub calls and pushes run outside it. A reservation keeps the cap and slugs exact. self.repo.refresh(FETCH_TTL) base = snapshot.get("base_sha", "") base = self._workspace(snapshot) token = object() with self.lock: if key and key in self.state["requests"]:119 unmodified lines self.last_create = max(self.last_create, time.monotonic()) sha, main = self._land(agent, snapshot, base, title, branch_ref, pr, sha, main, started, slot) self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/legion/pr/{pr}/{sha}", sha)) self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/pybot/pr/{pr}/{sha}", sha)) return pr, sha, main, old_head raise ToolError("main kept moving while opening the PR; open it again", "busy")
373 unmodified lines with _timed(steps, "push"): self._lease_push(agent, pr, new, head, time.monotonic()) with _timed(steps, "update_ref"): # waits for refs_lock self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/legion/pr/{pr}/{new}", new)) self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/pybot/pr/{pr}/{new}", new)) with self.lock: # reviews stay: they match the rebased head by patch-id rec.update(base_sha=main, head_sha=new) self._dirty("prs", pr)468 unmodified lines "changes_requested": len(changes), "changes_requested_prs": changes[:STATUS_QUEUE_MAX]}
@tool(pool="slow") def run_bot(self, ref_or_path: str, lines: list[str]) -> dict: def run_bot(self, ref_or_path: str, lines: list[str], workspace: dict | None = None) -> dict: """Run main, pr:<number>, or a local clone path. 300 seconds for the whole conversation.""" with tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp: tree = Path(tmp) / "tree" snapshot = UPLOAD.get() # Fetches run outside the checkout slot: a fetch holds no permit. if hub_ref := ref_or_path == "main" or ref_or_path.startswith("pr:"): self.repo.refresh(FETCH_TTL) # outside the checkout slot: a fetch holds no permit self.repo.refresh(FETCH_TTL) elif workspace is None: raise ToolError("use main, pr:<number>, or a clone path inside your workspace") else: sha = self._workspace(workspace) with self._checkout_slot(): # released before the run, which has its own slots if hub_ref: sha = self.repo.sha(ref_or_path) self.repo.checkout(sha, tree) elif isinstance(snapshot, dict): sha = snapshot.get("base_sha") if isinstance(sha, str) and self.repo.ancestor(sha, "main"): self.repo.checkout(sha, tree) # then only changed files are written/compiled self._contract(tree, self._files(snapshot, tree)) elif "patch" in snapshot: raise ToolError("unknown base; send the full tree", "need_full") else: tree.mkdir() self._files(snapshot, tree) self._contract(tree) else: raise ToolError("use main, pr:<number>, or a clone path inside your workspace") self.repo.checkout(sha, tree) # then only changed files are written/compiled self._contract(tree, self._files(workspace, tree)) return {"ref": ref_or_path, "sha": sha, **self._run(tree, lines)}
@contextlib.contextmanager15 unmodified lines
if __name__ == "__main__": import pybot # the module by its own name: its logger is "pybot", and its atexit hook saves from legion.world.server import serve from server import serve # Nothing else configures logging in the world process: this handler sends its warnings and # INFO lines (merge_pr timings) to stderr. logging.getLogger("pybot").addHandler(logging.StreamHandler()) logging.getLogger("pybot").setLevel(logging.INFO) # LEGION_WORLD_PORT: the free port legion picked (a local run, a Slurm world job) serve("pybot:PybotWorld", host="0.0.0.0", port=int(os.environ.get("LEGION_WORLD_PORT") or os.environ.get("PORT") or 7860)) serve(pybot.PybotWorld, host="0.0.0.0", port=int(os.environ.get("PORT") or 7860))1232[pytest]asyncio_mode = autoasyncio_default_fixture_loop_scope = functiontestpaths = tests13 unmodified lines141516171817181920296 unmodified lines31731831932132032132232313 unmodified linesfrom huggingface_hub import HfApifrom huggingface_hub.errors import HfHubHTTPError
from legion.world import ToolErrorfrom legion.world.server import redactfrom api import ToolError, redact
log = logging.getLogger(__name__)# Loose objects packed per maintenance pass at most: every pass finishes; a backlog drains over passes.296 unmodified lines def commit(self, tree, parent, author, title, onto=None, union=False): """Commit tree on parent; with onto != parent, replay that commit onto it (with union, PYBOT_UNION_PATHS merge as merge=union: only where a changed diff is refused).""" who = ("-c", f"user.name={author}", "-c", f"user.email={author}@legion.invalid") who = ("-c", f"user.name={author}", "-c", f"user.email={author}@pybot.invalid") self.git("add", "-A", at=tree) self.git(*who, "commit", "--allow-empty", "-m", title, at=tree) sha = self.git("rev-parse", "HEAD", at=tree)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596601annotated-doc==0.0.5 \ --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \ --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb # via # fastapi # typerannotated-types==0.8.0 \ --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 # via pydanticanyio==4.15.1 \ --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \ --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94 # via # httpx # starlette # watchfilescertifi==2026.10.23 \ --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \ --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1 # via # httpcore # httpxclick==8.5.0 \ --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 # via # huggingface-hub # uvicorncolorama==0.4.6 ; sys_platform == 'win32' \ --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 # via # tqdm # typerexceptiongroup==1.3.1 \ --hash=sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219 \ --hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598 # via legionfastapi==0.143.1 \ --hash=sha256:4cafaab64df8534758bf0fce61947f5e27e6cd512798ccbbaad5425086c3b664 \ --hash=sha256:687beb445804e4c4dbe2a76fd83c25e9b973ac48c267defb86f791e099baecc4 # via legionfilelock==3.32.7 \ --hash=sha256:37b8a3d9811b0f9aef7e5ec5c71bb320de52df51e6ca9bcd6f5ad81187660da7 \ --hash=sha256:65ff0d0190ea42038b32bda4b77834fb05be2cad4c5b9b01aa4dfb3614536e52 # via huggingface-hubfsspec==2026.9.0 \ --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \ --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f # via huggingface-hubh11==0.16.0 \ --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 # via # httpcore # uvicornhf-xet==1.7.0 ; platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64' \ --hash=sha256:0a9e802f33bf50c851abe45fc5380e61f959e2d369647d6742b79ad9d6c27cab \ --hash=sha256:19c0e64f14175ccb6a1aff69e0d2ab9ec5269a560e6687abaf2b3fa4f73de7cd \ --hash=sha256:2814a6e999d13464c4d679b788cc5d784eb5a4edfc638a31f10e9a11ab531ef8 \ --hash=sha256:2b7bb5727889b0f2436dbaaad8fc4c3e66b8240d992716989e0c086b4278b1bc \ --hash=sha256:4ee5e05a627f5ab5bad7a86582277d645556ea1e199903aae19e033a392aa13a \ --hash=sha256:57bc157b8b7fe3bee9dcb9af7f3da8de41801c3b31a9ef68a77a33c6a6be382f \ --hash=sha256:59fba37039233c7fcbe196817d6cdcf1b40dfb17b410f229d85b0cf0a1848da4 \ --hash=sha256:757168feb5679647c0bb13ee5d0faebe799c4dff9051419885a566ebd79f949d \ --hash=sha256:80f79dae613ce9e0ea1fd1ae15616ca9ac74aed4c770aabc199c4f03ebecc863 \ --hash=sha256:87dab080f8f7d32781c2586904e3603f4e60d09bfc727706c3ae419e0829beeb \ --hash=sha256:acc3851cf2576a8fb2ae926da863f4efabe21303cf292e9a44332802ab0dcc6a \ --hash=sha256:b01fe18dbbd151a2403d2c64ed30dc6547b00d6babab9a617d77c7acdb81ee66 \ --hash=sha256:b91569d5f1b61c34b043687da02c05dd3604f3d329e7868510bf3f7971599006 \ --hash=sha256:d406ec79053c0871817f700c2ac8c36ba0d87f9c34b7458b0f0063bb218b0466 \ --hash=sha256:e3e88a7a75d7d95cbee1f37dc31341d6201124cf21c6c4b1dfab8ccba9b09e0f \ --hash=sha256:fa029678be1ba7f953c409b0b27bf15cc69cd1c9b3a674fbd78856ebefca1052 \ --hash=sha256:fcfd6c22418e57dd5b3aea649e813b2e2cfb2aebf317b210d90f1fe4b3018b52 # via huggingface-hubhttpcore==1.0.9 \ --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 # via httpxhttptools==0.9.0 \ --hash=sha256:02bc5b3dcb6394b9d825fd62a7bfa0b2943063a3c89abc4492ad45e334a20eb5 \ --hash=sha256:050f7ab098121873c8f13e35857f97ab60a76185c8302bde9a384939bb7c3b96 \ --hash=sha256:050f84b7ec46a6efe0e5f521cf8729e3397c1cef4384f62ed8d5d68ca0045776 \ --hash=sha256:06bfe7fad972a417269d8a5fc53b87e4eca970354abf5e9e24336fd06d64292e \ --hash=sha256:088de1738e1af624466a01c35d652dbe6fb825be887c76d68aa850621d81db88 \ --hash=sha256:0adc974916efe1fbf89d0363a86dcb2c746727643e362ff398de1a4b50b6bc77 \ --hash=sha256:0cc339a807c156d840b54f8bf050ba0fc265eb81692c24bca8535b52fbd797c6 \ --hash=sha256:130635fea6e611a6b2026120037965ddb88b3dafd11bb64e264b101a70a76630 \ --hash=sha256:18d800aaa2d6bff7d889df810d1b19a5fde72b1f6c0ca96e8d9f28a692fe5460 \ --hash=sha256:1a4050a651e1f2faf05eb028ce9f2168abbcee9e24b209f5c1f2eb96d8c569e4 \ --hash=sha256:1a7f1df31829c258158be01bb04eb668c4fba7df1ddf2262131a972962e651b6 \ --hash=sha256:1f6da814aeecbc6cb8872d6d3e85ed16e8ab1653f9557cea8658725ce212348a \ --hash=sha256:2095207b75a83c9e947346da9c127fb7e4fb29f41589df2643764f06b750989c \ --hash=sha256:2319858018eedd0c0b2f950a620413c0a9d1352607be4267eb28209eca8b1e3f \ --hash=sha256:26e1d9629f3bf70d23f0d22238152aec51c837a7c9e384cb74f356fdccad7eb3 \ --hash=sha256:29b0d823e3c1e7cd1093a5dc889245db693ef13ada624cd66e2262421ef38867 \ --hash=sha256:34266cec8c1d4e3e91fcca7efe38971d6bdda64a7944f2a46ab576da15173680 \ --hash=sha256:36fac804b8cfd6b935ae64f71349f833d2b6298404626d017a2c57bb942bc643 \ --hash=sha256:3af4e45ff455fce5511fdf2653c1ce428ef09c56fe37a83eb4d924c2d474f31e \ --hash=sha256:3e3201fe4d46e0d15d7ff9fafc94a605da9eb82d2c5b9837f0368acb325481f1 \ --hash=sha256:45b3002392948dcf578029c89f6318e1289a993a1a5ec38a4161560fab60f811 \ --hash=sha256:465bc1526debf53a3be92022a16ca0c38f891ea3b5c1587af4f52e44020f8a07 \ --hash=sha256:4a4d8c2c7e73ba5967be74d7c3a5ff81fde815ee1b48d9c5c0f14de8463a847b \ --hash=sha256:4c58dc91aefb31adad500aa68054334f429b840b36dd29e34e834101044cb2ef \ --hash=sha256:4efbee349138a3fee7a4cc3a95abd2d499fae70dd5bff9fed9138d6f570f4283 \ --hash=sha256:4fb995082fe41ec410b33c48b54fb1d44abb8a6ee762c31e8c42519e8c3a30a9 \ --hash=sha256:52fe0176682a25b15370f23f5b0f1366a84771df89144fb0cd979cb72a94b5ca \ --hash=sha256:58a1b0ec4cbb930e69669f9771715b2c7898d3cdf064d9811f7a66afef96b544 \ --hash=sha256:63d38e9a9a10a20fb57593742e63c6b1e78dd7f6ef5472de8e0b1e4cf4f3db26 \ --hash=sha256:6b1ac7f1bc6c0dbf90684b77571a51a21b2463909fd916ce0ac9bfc4d566dc75 \ --hash=sha256:6b900073e7b8481ef1aaf4f6c1789d210a1db01a9da8789821578cfeb4c2d540 \ --hash=sha256:6c12d0393a903b58bc5f5a7406d6c5290acfb8284290d68547ce620c06f7d133 \ --hash=sha256:6ebd39ee26db460cfe5ab8b71a15d1149b289139a0d3981522757d6af620887e \ --hash=sha256:6f9549ca354a1d6d6167c458a1f1b12147726b968f02dd64b6a5801dba91ae0f \ --hash=sha256:6ff0145b34610e57c9fae20df4e133c8d54266447387de6fcc0bdabfe4db4569 \ --hash=sha256:6ff5f0ed70783dcb9562dbd20edca51c3d4d277f128223709e3da6b75986d1d4 \ --hash=sha256:714bf348f468532d86bed670837e7d5ddff3834dd7f5d3c08066da400c86f088 \ --hash=sha256:757e3f79cb865a7db94e0db5f4d0ed3284a69e39d53568f433982ea13c60cac1 \ --hash=sha256:7e32b83bd8c2f8b6fa726ef34e63e21c4d7eddc277d40d4ef7245ea3ed28e5b6 \ --hash=sha256:805b0f2618e5d4c3e28f45b731eb1a0539691ae4a2f97b4ce014de0bf96a1ff5 \ --hash=sha256:80eae881cfb69383303e9a4d7961a478025b89c24f38f2e69b30c516fa0d57f2 \ --hash=sha256:813a32f94991b9627795528053c73a57d2ce3eb98ede89f0e1c7a31095938e81 \ --hash=sha256:8463b34ebde3f000627e9dbd8a545f995ad49fbf7ff9dd5abc0cd507da98a603 \ --hash=sha256:8d90d10e9b6594c28f27896a68fab97fd784c43804e9fe419dab8e8dcfcf4b02 \ --hash=sha256:8e1e037bb57dbc549c6fe20370b763ea74bdb09413cdcf857e4f14d9e4e2fb13 \ --hash=sha256:931f45f84e15daafec5f82cc92e6710569e1f50933f3253d206eab4132bec678 \ --hash=sha256:995b52f7c260ac7023640221f27472303968753cb6fc6fce1ddfb0e9db59a398 \ --hash=sha256:9b4da5789d7cf576c7e81f0088c632f6ee3786d87d17f08e90e703c22ce15633 \ --hash=sha256:b2ab3aad55d75d0b8df8d8a1b5920baaec9b161112cd5e95984848b4d2cd3dfe \ --hash=sha256:b2cc6991f16f6d666d48e4b57318104e7b29109e32e2f6b86e9d44c4e6a27f4e \ --hash=sha256:b5a3f5f70967a1aa2bc47fec42a1e19d2fb38c61700e3ee62b63a4af4f4fd001 \ --hash=sha256:b6ee42112d785a913dd63ec0335435a3dddbea5040c151252db815b0095cf066 \ --hash=sha256:b928ab0ecaa664e8caecc529dcb8bc881b6b35bb2b74bf9a39ae25f982ee8812 \ --hash=sha256:b9430f65db521db7962ad951571d446171213686f96c998a54dc18ed574821e2 \ --hash=sha256:b9cd15cb7cf0d5cc41f649fd789aae12c56c3b83eff593f8e095c1d4555ad5c3 \ --hash=sha256:bb1533541c729ad422f870a780d8b4af924f9817d45b5f580390418cda72eaa2 \ --hash=sha256:bca180cbe84e4fba7807eb408a8655295f697928512324517e30a091ede522a8 \ --hash=sha256:beb2c8a34cc90fb4d862b7284eafdb322030d6a8b2ee5eb6a744f84205beedc3 \ --hash=sha256:bfdabac0c6d3d6a5be8c2a100a001c92c14a39bbafd5999545a675c493626e64 \ --hash=sha256:c0e45def4d9ce7073e2226535572442d9d6efb4047c7a5fd8960807e877ce70a \ --hash=sha256:c0f537e5e8152e8d9cae82804024790cb973061abd3b7ef8f66f46e2b5c7bb51 \ --hash=sha256:c42424213c28804f8d0e20f5692106cfb57bf72e1dbc4092b8481fb2f9e4c707 \ --hash=sha256:cb2bb3ac0af7fdab2311b895c9eb95442b45deb14cc949b9e65545e74aa0be69 \ --hash=sha256:cd3e55223a77d6e08d5730ebacb4930ecca5d2ce7c57e7ba10833be7e52903f1 \ --hash=sha256:ce8e723b4637034b76f5382a30a6b725518c332273e8d62a6c7d46e90837c947 \ --hash=sha256:d1e329a1866981efe0201d05a374617f6c6cf14434a501d78ab22793d1ab1fa6 \ --hash=sha256:d3906b5c549ff2ad2473cb711e1fc65d76715c2726a402108fbf55eab6c6b49d \ --hash=sha256:d484ebb7e3a3f3597b0f645fbd1b85633674ca808c1f5ba11c2caf7c66f5c8b6 \ --hash=sha256:db735a23ecb0f0450d2b24e0a05fb00a8a35c9db172919c4d3e023e7c7ee4c9b \ --hash=sha256:dbc9fd1521e573045d71b6afab7398439c5cc259e8cb9d416fe62d485c4899c6 \ --hash=sha256:df3867518b205be3648e2fbd522bf380c851b5c2500588047505afdd786b6669 \ --hash=sha256:e0acbd474d0af4afacc6e66c4273f8a19e25f8af4379fc816388095ea6b01371 \ --hash=sha256:eae4e9c7a0785a1a715de0a74fb822ab40084c060f444f18f075d05e322aa7ef \ --hash=sha256:edd5aa045fa3cc57143db018dd32ce7962bd5b525d05230709015d7e570100aa \ --hash=sha256:f67db0ba2bedafec15b8e5330d40da1e1c7921559fa715af021252bfef81a6f8 \ --hash=sha256:f78f7ae1c2e5aabf29583fc0d302d8081a663776f84578025662eb6f5d63a921 \ --hash=sha256:f9489c1d87160c126f73b004742fe8654fa1ce37ed89e9e01330a1c10aaecde4 \ --hash=sha256:f9ccc9884241efceb4547a92955d128574c864681f11b7ea3ecbde295fafbe8b \ --hash=sha256:fc1a4f9d18d32a6e0a0a0a382986a60a2126f5144dd08715be7adb8df18e8a46 # via uvicornhttpx==0.28.1 \ --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \ --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad # via # huggingface-hub # legionhuggingface-hub==1.33.0 \ --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \ --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e # via legionidna==3.20 \ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c # via # anyio # httpxjinja2==3.1.6 \ --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \ --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 # via legionmarkdown-it-py==4.2.0 \ --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \ --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a # via richmarkupsafe==3.0.4 \ --hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \ --hash=sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b \ --hash=sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653 \ --hash=sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c \ --hash=sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e \ --hash=sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc \ --hash=sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92 \ --hash=sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f \ --hash=sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4 \ --hash=sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7 \ --hash=sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691 \ --hash=sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc \ --hash=sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde \ --hash=sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99 \ --hash=sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9 \ --hash=sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df \ --hash=sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5 \ --hash=sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17 \ --hash=sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8 \ --hash=sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea \ --hash=sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248 \ --hash=sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741 \ --hash=sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6 \ --hash=sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7 \ --hash=sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1 \ --hash=sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67 \ --hash=sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f \ --hash=sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9 \ --hash=sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c \ --hash=sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc \ --hash=sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba \ --hash=sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17 \ --hash=sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6 \ --hash=sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2 \ --hash=sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163 \ --hash=sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b \ --hash=sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634 \ --hash=sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38 \ --hash=sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed \ --hash=sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c \ --hash=sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148 \ --hash=sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a \ --hash=sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f \ --hash=sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811 \ --hash=sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2 \ --hash=sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6 \ --hash=sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed \ --hash=sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0 \ --hash=sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b \ --hash=sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96 \ --hash=sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59 \ --hash=sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2 \ --hash=sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65 \ --hash=sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72 \ --hash=sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8 \ --hash=sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e \ --hash=sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a \ --hash=sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2 \ --hash=sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453 \ --hash=sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6 \ --hash=sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977 \ --hash=sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978 \ --hash=sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581 \ --hash=sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369 \ --hash=sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a \ --hash=sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916 \ --hash=sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b \ --hash=sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f \ --hash=sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c \ --hash=sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464 \ --hash=sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9 \ --hash=sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee \ --hash=sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300 \ --hash=sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6 \ --hash=sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d \ --hash=sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46 \ --hash=sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97 \ --hash=sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733 \ --hash=sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe \ --hash=sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429 \ --hash=sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39 \ --hash=sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894 \ --hash=sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c \ --hash=sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c \ --hash=sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77 \ --hash=sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe \ --hash=sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad \ --hash=sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85 \ --hash=sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e \ --hash=sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34 \ --hash=sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c \ --hash=sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749 \ --hash=sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214 \ --hash=sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932 \ --hash=sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494 \ --hash=sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1 \ --hash=sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0 \ --hash=sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786 \ --hash=sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78 \ --hash=sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e \ --hash=sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289 \ --hash=sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c \ --hash=sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe \ --hash=sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237 \ --hash=sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19 \ --hash=sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977 # via jinja2mdurl==0.1.2 \ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba # via markdown-it-pyopentelemetry-api==1.45.1 \ --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb # via fastapipackaging==26.3 \ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c # via # huggingface-hub # legionpydantic==2.14.1 \ --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \ --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26 # via # fastapi # legionpydantic-core==2.50.1 \ --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \ --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \ --hash=sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019 \ --hash=sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685 \ --hash=sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b \ --hash=sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482 \ --hash=sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658 \ --hash=sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498 \ --hash=sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec \ --hash=sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a \ --hash=sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b \ --hash=sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4 \ --hash=sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a \ --hash=sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8 \ --hash=sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb \ --hash=sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e \ --hash=sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8 \ --hash=sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7 \ --hash=sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a \ --hash=sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e \ --hash=sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396 \ --hash=sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255 \ --hash=sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899 \ --hash=sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43 \ --hash=sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb \ --hash=sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f \ --hash=sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d \ --hash=sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415 \ --hash=sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c \ --hash=sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea \ --hash=sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2 \ --hash=sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e \ --hash=sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568 \ --hash=sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6 \ --hash=sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a \ --hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9 \ --hash=sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1 \ --hash=sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff \ --hash=sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f \ --hash=sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5 \ --hash=sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb \ --hash=sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4 \ --hash=sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0 \ --hash=sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597 \ --hash=sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b \ --hash=sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa \ --hash=sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242 \ --hash=sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f \ --hash=sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc \ --hash=sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f \ --hash=sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c \ --hash=sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61 \ --hash=sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102 \ --hash=sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4 \ --hash=sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e \ --hash=sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54 \ --hash=sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070 \ --hash=sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed \ --hash=sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb \ --hash=sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5 \ --hash=sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19 \ --hash=sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5 \ --hash=sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112 \ --hash=sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9 \ --hash=sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5 \ --hash=sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72 \ --hash=sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2 \ --hash=sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8 \ --hash=sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295 \ --hash=sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e \ --hash=sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe \ --hash=sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290 \ --hash=sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea \ --hash=sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662 \ --hash=sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41 \ --hash=sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44 \ --hash=sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807 \ --hash=sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78 \ --hash=sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c \ --hash=sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3 \ --hash=sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831 \ --hash=sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86 \ --hash=sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2 \ --hash=sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f \ --hash=sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f \ --hash=sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10 \ --hash=sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5 \ --hash=sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b \ --hash=sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09 \ --hash=sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a \ --hash=sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e \ --hash=sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459 \ --hash=sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08 \ --hash=sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709 \ --hash=sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a \ --hash=sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20 # via pydanticpygments==2.21.0 \ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \ --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c # via richpython-dotenv==1.2.4 \ --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc \ --hash=sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0 # via uvicornpyyaml==6.0.3 \ --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \ --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \ --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \ --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \ --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \ --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \ --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \ --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \ --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \ --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \ --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \ --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \ --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \ --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \ --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \ --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \ --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \ --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \ --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \ --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \ --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \ --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \ --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \ --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \ --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \ --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \ --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \ --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \ --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \ --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \ --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \ --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \ --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \ --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \ --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \ --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \ --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \ --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \ --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0 # via # huggingface-hub # legion # uvicornrich==15.0.0 \ --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \ --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36 # via typershellingham==1.5.4 \ --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \ --hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de # via typerstarlette==1.8.0 \ --hash=sha256:1565dc0b35d5737a271ed1e0e04e949f4e81198799f216d2667b0a0fb9cf9522 \ --hash=sha256:dfdd6b29c26483288088d990eee59631dedadd66ce20d203402a7ca8e3c4656f # via fastapitomli==2.5.0 \ --hash=sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea \ --hash=sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd \ --hash=sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0 \ --hash=sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391 \ --hash=sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df \ --hash=sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9 \ --hash=sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066 \ --hash=sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f \ --hash=sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57 \ --hash=sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6 \ --hash=sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b \ --hash=sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3 \ --hash=sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043 \ --hash=sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01 \ --hash=sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646 \ --hash=sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859 \ --hash=sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b \ --hash=sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc \ --hash=sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5 \ --hash=sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0 \ --hash=sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb \ --hash=sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84 \ --hash=sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6 \ --hash=sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b \ --hash=sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b \ --hash=sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52 \ --hash=sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd \ --hash=sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75 \ --hash=sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142 \ --hash=sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03 \ --hash=sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea \ --hash=sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374 \ --hash=sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3 \ --hash=sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276 \ --hash=sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b \ --hash=sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc \ --hash=sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68 \ --hash=sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a \ --hash=sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f \ --hash=sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b \ --hash=sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7 \ --hash=sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0 \ --hash=sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb \ --hash=sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7 \ --hash=sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7 \ --hash=sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105 \ --hash=sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5 \ --hash=sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d \ --hash=sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2 \ --hash=sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4 \ --hash=sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7 \ --hash=sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1 \ --hash=sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571 \ --hash=sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a \ --hash=sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442 \ --hash=sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc # via legiontqdm==4.70.1 \ --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \ --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4 # via huggingface-hubtyper==0.27.3 \ --hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \ --hash=sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff # via legiontyping-extensions==4.16.0 \ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 # via # anyio # exceptiongroup # fastapi # huggingface-hub # opentelemetry-api # pydantic # pydantic-core # starlette # typing-inspectiontyping-inspection==0.4.4 \ --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \ --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147 # via # fastapi # pydanticuvicorn==0.54.0 \ --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \ --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620 # via legionuvloop==0.23.0 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \ --hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \ --hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \ --hash=sha256:12634f15e6625f78b3f2922f91404c4d7173487eba11746764153f556e9852dc \ --hash=sha256:1748321e3c59a14a75404b1ae8d5a8d81c4e201803ea0e14c1b6fd84421024b5 \ --hash=sha256:19c64108b507cd0bc140e400e3396bacebd9d504956aa7726272bf6de7d9aabb \ --hash=sha256:1e84575f11873c109cf3962ad0bdf679094466184125f4cadcc41a73febff41f \ --hash=sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27 \ --hash=sha256:2dcff2d69be43e6559e5dad2c5a7a2dbfb60e05a77311b6c4b7a4a8123d86c65 \ --hash=sha256:31e0cf90bc8fd88784f6802cdba968a51fb1aec1cc3feec74d862b2d371d1330 \ --hash=sha256:378188efbb1524f2219d05246a3e1e5907217848d2882144dff59585f1b81d55 \ --hash=sha256:4448e9124537620f9c25d004c227bb5104440b58955c19bbd312d910af919a63 \ --hash=sha256:4a08875543bbd4519faf30497506c9cda8a48470467ffdf967c7313c7a5981a8 \ --hash=sha256:4b8e207c67d207a8608fec57e116511030af3495dc0109b8c333cf9cb412b16f \ --hash=sha256:4f1798f56c6f4ba5ac11fa2869e5717926e4470d97a1dd42b4f59219d43b5027 \ --hash=sha256:5a2bbad3a63007f7e9524d4903ba04fee252557c2acd86f9a3d4f91786695254 \ --hash=sha256:5bb9be71d9ee39b4359b832f9569518ec9bc08704194034e79e4958e6bc4d46d \ --hash=sha256:6b3cbc4f96ddfa1fb88a78a69dd851369825b7816d9702eee8c4461505ba172e \ --hash=sha256:6c7ef4701a96553514b2688e342ef1bf2beae6cfd172d89a76c768292aabf405 \ --hash=sha256:7337b06a9f9ed9ea3049f04b76f65819db9b19bb832ee598e97b388eadf25e5f \ --hash=sha256:76345f51367fb1f23e08605c6efb18374f669be5b223658fbab6b17627950507 \ --hash=sha256:7e35c9bc977760981693e1a7a51493b58ee5a501f9ebb1e547565ee40b6c6208 \ --hash=sha256:93935ab27b6eaef4c3e5489aebc84284f0644592f7ab516df60ee1b27eaf5eb3 \ --hash=sha256:a6ac96da66c35bf789bdcde78a88dc7d56b7907d8379648c54adc1c61594575d \ --hash=sha256:b90397a50ad6332ed3e459c648ac20d182cce24a557354363ad85fc9ea4a17cd \ --hash=sha256:bbbdb8fcd5e7062e546eec1ac78c28bb21ae7df54c18f8e4b06e15a18d661a49 \ --hash=sha256:bd6f2f81c7b9da99d301c0b16b82044e76fe887086e42e1590ecf520b94dbdac \ --hash=sha256:be53e1d5f83de43dc175c87612ecc128d444b38e5c56cb3f807f5a73d6887476 \ --hash=sha256:c3f23f403a273900d57de6ee5ca0614c650f7f58563065dad1a4744498960e53 \ --hash=sha256:cbe8d03d4efcccdb7fcedecbaa1e1fa02913eaf3a74cb933634a6bc6d2ea9e2a \ --hash=sha256:dc61e4f9e37b507069dc7e659ae28bca7adcb04c993c3508214315d12c63f848 \ --hash=sha256:e095f9e105af76593b4c183bb0bcbdae64bd913a59ec595732dc108b48730ab5 \ --hash=sha256:e2cba180d6451822763eda8364f342435a873bcfb3849cbd82fdeca248ca65eb \ --hash=sha256:f1341c6abcee1c31277cfe28d34e46196f2143ec3d755e6efe7452126e1f626d \ --hash=sha256:f3fbfe82829d8e381426a289b87e59e585278728361db9ce975b88b51f64f410 \ --hash=sha256:f673d835bdb1a60229cc3609a113fd2c9ce3f4a3c75ad4eaed111180c00199d2 \ --hash=sha256:f7548ede3ee908cfabc0d068106e303a9a2d811af959cdf6ab85676344cedcda \ --hash=sha256:fa8ed556fcc87a4091cf61587ef172fa104323dc89ecc085a618ba7ff8629a8f # via uvicornwatchfiles==1.3.0 \ --hash=sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441 \ --hash=sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95 \ --hash=sha256:04c5500faa725d69a99b0f63750e80795e455bb951849e9c98a811b4324997c4 \ --hash=sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61 \ --hash=sha256:26b81bc515a0f03f66a69a6fea86eea54c8eca4173c46dd7222569f79dd2f977 \ --hash=sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509 \ --hash=sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5 \ --hash=sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661 \ --hash=sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30 \ --hash=sha256:7c1125e99f84934a92996ae343501285617373acd66f16b59fd5654b27ad8d80 \ --hash=sha256:81c989d7267bfb7b676cd32c83bec97914e396870983cbf493e29415037bff5e \ --hash=sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207 \ --hash=sha256:a5b631db08fd3032db57ec6a92d1777cd60f88803287e4e941a4858c53aab1e0 \ --hash=sha256:a85e243c87109d9f48a2e0d10d6abdee8768cc114848b32281ec83d7f81d86ef \ --hash=sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1 \ --hash=sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c \ --hash=sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29 \ --hash=sha256:ca39661934749df580d89f3dde266f2af7c6968f4c21c72ce2dc387d299e6aa7 \ --hash=sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935 \ --hash=sha256:d4593392e87669836670f87d62fc754059eaeb0e6157af44060a46558cebe5a3 \ --hash=sha256:d754e049006e81a9be49dc78ba7802081cee426e968cbc63ee19e164fa2d0e39 \ --hash=sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc \ --hash=sha256:da213822ec9082b62cadf3008e07a8c690ec7a3c89f6dc5e55a8cf07b56a1b26 \ --hash=sha256:dd538c71766c59c732e2c5cedc39323c99c11897b99f93eac773438e54af206a \ --hash=sha256:e0204f90677b7fb8d3a824279a71a01166bea9f6e53923b8056592d87b33b0b6 \ --hash=sha256:e5871d4a7f788a9f64fb06f5793389d29d171e5c32d37c3ebfd520b017cc7694 \ --hash=sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca \ --hash=sha256:ec3cd4bb181a7b6329134204c2277c7144ab5f62cce9c5335d6f901ee7ce8d6a \ --hash=sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3 # via uvicornwebsockets==15.0.1 \ --hash=sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2 \ --hash=sha256:0af68c55afbd5f07986df82831c7bff04846928ea8d1fd7f30052638788bc9b5 \ --hash=sha256:0f3c1e2ab208db911594ae5b4f79addeb3501604a165019dd221c0bdcabe4db8 \ --hash=sha256:229cf1d3ca6c1804400b0a9790dc66528e08a6a1feec0d5040e8b9eb14422375 \ --hash=sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597 \ --hash=sha256:3c714d2fc58b5ca3e285461a4cc0c9a66bd0e24c5da9911e30158286c9b5be7f \ --hash=sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3 \ --hash=sha256:558d023b3df0bffe50a04e710bc87742de35060580a293c2a984299ed83bc4e4 \ --hash=sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665 \ --hash=sha256:595b6c3969023ecf9041b2936ac3827e4623bfa3ccf007575f04c5a6aa318c22 \ --hash=sha256:5a939de6b7b4e18ca683218320fc67ea886038265fd1ed30173f5ce3f8e85675 \ --hash=sha256:5d54b09eba2bada6011aea5375542a157637b91029687eb4fdb2dab11059c1b4 \ --hash=sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65 \ --hash=sha256:746ee8dba912cd6fc889a8147168991d50ed70447bf18bcda7039f7d2e3d9151 \ --hash=sha256:756c56e867a90fb00177d530dca4b097dd753cde348448a1012ed6c5131f8b7d \ --hash=sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee \ --hash=sha256:ba9e56e8ceeeedb2e080147ba85ffcd5cd0711b89576b83784d8605a7df455fa \ --hash=sha256:c338ffa0520bdb12fbc527265235639fb76e7bc7faafbb93f6ba80d9c06578a9 \ --hash=sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe \ --hash=sha256:e09473f095a819042ecb2ab9465aee615bd9c2028e4ef7d933600a8401c79561 \ --hash=sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215 \ --hash=sha256:ee443ef070bb3b6ed74514f5efaa37a252af57c90eb33b956d35c8e9c10a1931 \ --hash=sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f \ --hash=sha256:fcd5cf9e305d7b8338754470cf69cf81f420459dbae8a3b40cee57417f4614a7 # via uvicornhuggingface_hub==1.33.017 unmodified lines18192021222122232425202 unmodified lines22822923023123123223317 unmodified linesfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Path
from legion.isolation import command as isolate_commandfrom legion.world import ToolErrorfrom api import ToolErrorfrom isolation import command as isolate_command
# The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree# for the shared tests: main grows by about one file per merge, so the cap allows a long run.202 unmodified linesif __name__ == "__main__" and sys.argv[1:] == ["serve"]: if not os.environ.get("PYBOT_SANDBOX_TOKEN"): sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused from legion.isolation import protect_supervisor from isolation import protect_supervisor protect_supervisor() # a bot under this uid cannot read this process's env or memory ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever()6 unmodified lines789101011121340 unmodified lines54555657575859606 unmodified linesmain) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logsits HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeoutworks.Local path without `unshare` (blocked on many boxes). Needs requirements.txt and legion, 3.12+.Local path without `unshare` (blocked on many boxes). Needs requirements.txt, 3.12+."""import base64import io40 unmodified lines
def main(): import sandbox from legion.world import ToolError from api import ToolError
with socket.socket() as s: s.bind(("127.0.0.1", 0))1 unmodified line2345656789910111211 unmodified lines242526272728293016 unmodified lines474849505051525354535455565726 unmodified lines8485868787889091899091921 unmodified line949596999798991003 unmodified lines1041051061091101111071081091101115 unmodified lines1171181191231241251261271281291301201211221231241251261331271281351291301371381311321331401341351361371381391401 unmodified line
Starts PybotWorld from world/ with plain Python on a free port, backed by a FAKEin-process hub (a local bare git repo + LocalHub, injected as `repository`; the shipped code stilldefaults to the real Hub). Checks /healthz, the token (and a per-agent one), /manifest's tools andone run_bot call.defaults to the real Hub). Checks /healthz, the agent credentials, /world/manifest's tools andone run_bot call on each route.With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only itstoken) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no networkcalls beyond localhost. Needs the deps in requirements.txt, legion (README) and git.calls beyond localhost. Needs the deps in requirements.txt and git."""import jsonimport os11 unmodified linessys.path.insert(0, str(SRC))TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict", "verdicts", "run_bot", "world_status"}TOKEN = "smoke-token"TOKEN, OTHER = "smoke-credential-0", "smoke-credential-1" # agent-001, agent-002
def git(path, *args):16 unmodified lines def merge(self, pr, comment): raise NotImplementedError("not used by this smoke")
def call(port, method, path, body=None, token=TOKEN, agent="smoke"):def call(port, method, path, body=None, token=TOKEN): req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method, data=None if body is None else json.dumps(body).encode(), headers={"Content-Type": "application/json", "X-Legion-Agent": agent, **({"X-World-Token": token} if token else {})}) headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {token}"} if token else {})}) try: with urllib.request.urlopen(req, timeout=60) as r: return r.status, json.loads(r.read())26 unmodified lines
def main(sidecar=False): import uvicorn from pybot import PybotWorld from repository import Repository
from legion.world.server import create_app from server import App, Server
tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-")) os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="") # the fake hub ignores both1 unmodified line subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True) git(seed, "init", "-q", "-b", "main") git(seed, "add", ".") git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-qm", "seed") git(seed, "-c", "user.name=seed", "-c", "user.email=seed@pybot.invalid", "commit", "-qm", "seed") remote = tmp / "remote.git" git(tmp, "clone", "-q", "--bare", str(seed), str(remote)) repo = Repository(tmp / "ws" / "repo.git", str(remote))3 unmodified lines port = free_port() if sidecar: sidecar_proc, sidecar_log = start_sidecar(tmp) server = uvicorn.Server(uvicorn.Config(create_app(world, TOKEN), host="127.0.0.1", port=port, log_level="warning")) threading.Thread(target=server.run, daemon=True).start() server = Server(App(world, {TOKEN: "agent-001", OTHER: "agent-002"}), "127.0.0.1", port) threading.Thread(target=server.serve_forever, daemon=True).start() for _ in range(100): try: if call(port, "GET", "/healthz", token=None) == (200, {"status": "ready"}):5 unmodified lines sys.exit("FAIL: /healthz never said ready") print(f"ok GET /healthz on 127.0.0.1:{port}: ready")
assert call(port, "GET", "/manifest", token="wrong")[0] == 401 print("ok GET /manifest with a wrong X-World-Token: 401") from legion.world.protocol import agent_token own = agent_token(TOKEN, "smoke") assert call(port, "GET", "/manifest", token=own)[0] == 200 assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401 print("ok GET /manifest with the agent's own token: 200; as another agent: 401") status, m = call(port, "GET", "/manifest") assert call(port, "GET", "/world/manifest", token="wrong")[0] == 401 assert call(port, "GET", "/world/manifest", token=None)[0] == 401 print("ok GET /world/manifest with a wrong or no credential: 401") assert call(port, "GET", "/world/manifest", token=OTHER)[0] == 200 status, m = call(port, "GET", "/world/manifest") names = {t["name"] for t in m["tools"]} assert status == 200 and names == TOOLS, (status, names) print(f"ok GET /manifest: {m['name']} {m['version']}, {len(names)} tools: {', '.join(sorted(names))}") print(f"ok GET /world/manifest: {m['name']}, {len(names)} tools: {', '.join(sorted(names))}")
status, r = call(port, "POST", "/tools/run_bot", status, r = call(port, "POST", "/world/tools/run_bot", {"args": {"ref_or_path": "main", "lines": ["Hello"]}}) ran = status == 200 and r["result"]["ok"] # False where unshare is not permitted (README) print(f"{'ok ' if ran else 'note'} POST /tools/run_bot main ['Hello']: {status} " ran = status == 200 and r["result"]["ok"] # False where unshare is not permitted print(f"{'ok ' if ran else 'note'} POST /world/tools/run_bot main ['Hello']: {status} " f"{json.dumps(r)[:300]}") server.should_exit = True status, r = call(port, "POST", "/v1/tools/run_bot", {"ref_or_path": "main", "lines": ["Hello"]}) assert status == 200 and r["ok"] == ran, (status, r) print(f"ok POST /v1/tools/run_bot main ['Hello']: {status} {json.dumps(r)[:200]}") server.shutdown() if sidecar: sidecar_proc.terminate() sidecar_proc.wait(10)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323"""HTTP API of a `World` (api.py), on the standard library's threaded server.
Agents (seat i is `agent-<i+1, 3 digits>`) authenticate with their credential from`PYBOT_TOKEN_<seat>`, sent as `Authorization: Bearer <c>` or `X-World-Token: <c>`:
POST /v1/tools/<name> body: the arguments (flat JSON object) 200 the result as JSON; refusal 4xx {"error": {"code", "message"}}; busy 429 (or 503 while starting) with Retry-After GET /world/manifest {"name", "description", "tools": [{name, description, parameters}]} POST /world/tools/<name> body {"args": {...}}: 200 {"ok": true, "result": ...} or {"ok": false, "error": {"code", "message", "retry_after_s"?}} GET /healthz no credential: {"status": "ready"} or {"status": "parked"}
Operators use `PYBOT_ADMIN_TOKEN` (never an agent credential; unset: 403) for `GET /metrics` and`/admin/*`: GET/PATCH /admin/knobs, GET /admin/paused, POST /admin/pause, POST /admin/resume.
Admission control: the fast pool (40 threads) refuses a call that waited 2 s for a thread, theslow pool (`@tool(pool="slow")`, 64 threads) one that finds 64 running and 8 queued: 429 withRetry-After 30. Parked mode: the port is bound first and the world is built in a thread, againafter 30 s (doubling to 10 min) while that raises; tool calls meanwhile answer 503."""from __future__ import annotations
import hmacimport jsonimport loggingimport mathimport osimport reimport signalimport threadingimport timeimport uuidfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom typing import Any
from api import Agent, ToolError, World, check_args, redact
log = logging.getLogger(__name__)MAX_BODY = 1 << 20 # a tool call's request bodyADMIN_MAX_BODY = 64 << 10FAST_THREADS, FAST_MAX_WAIT_S = 40, 2.0SLOW_THREADS, SLOW_QUEUE = 64, 8RETRY_AFTER_S = 30PARK_FIRST_S, PARK_CAP_S = 30.0, 600.0SEAT_ENV = re.compile(r"PYBOT_TOKEN_(\d+)")
def seat_credentials(env=os.environ) -> dict[str, str]: """credential -> agent name, from PYBOT_TOKEN_<seat> (seat 0 is agent-001).""" return {v: f"agent-{int(m[1]) + 1:03d}" for k, v in env.items() if (m := SEAT_ENV.fullmatch(k)) and v}
def _credential(headers) -> str: """`X-World-Token`, else the `Authorization: Bearer` value ("" when neither).""" auth = headers.get("Authorization") or "" return headers.get("X-World-Token") or (auth[7:].strip() if auth[:7].lower() == "bearer " else "")
class Refused(Exception): """A protocol-level refusal: HTTP status, code, message, optional retry-after seconds."""
def __init__(self, status: int, code: str, message: str, retry_after_s: float | None = None): super().__init__(message) self.status, self.code, self.message, self.retry_after_s = status, code, message, retry_after_s
class Pool: """A tool pool's threads with admission control (see the module docstring)."""
def __init__(self, threads: int, max_wait_s: float | None = None, queue: int | None = None): self.slots = threading.BoundedSemaphore(threads) self.threads, self.max_wait_s, self.queue = threads, max_wait_s, queue self.lock = threading.Lock() self.in_flight = self.refused = 0
def run(self, fn, *args): with self.lock: full = self.queue is not None and self.in_flight >= self.threads + self.queue if not full: self.in_flight += 1 try: if full or not self.slots.acquire(timeout=self.max_wait_s): with self.lock: self.refused += 1 raise Refused(429, "overloaded", f"the world is overloaded; retry in {RETRY_AFTER_S} s", RETRY_AFTER_S) try: return fn(*args) finally: self.slots.release() finally: if not full: with self.lock: self.in_flight -= 1
class App: """The routes of a world: an instance, or its class (built in parked mode, `builder`)."""
def __init__(self, world: World | type[World], credentials: dict[str, str], admin_token: str = ""): self.cls = world if isinstance(world, type) else type(world) self.world = None if isinstance(world, type) else world self.credentials, self.admin_token = credentials, admin_token self.pools = {"fast": Pool(FAST_THREADS, FAST_MAX_WAIT_S), "slow": Pool(SLOW_THREADS, None, SLOW_QUEUE)} self.manifest = self.cls.manifest() self.schemas = {t["name"]: t["parameters"] for t in self.manifest["tools"]} self.park = {"error": "the world is starting", "attempt": 0, "retry_at": 0.0} self.started = time.monotonic() self.stop = threading.Event()
def builder(self) -> None: """Build the world, again with backoff while that raises (parked mode).""" delay = PARK_FIRST_S while self.world is None and not self.stop.is_set(): self.park["attempt"] += 1 try: self.world = self.cls() log.warning("world %s: ready after %d attempt(s)", self.cls.name, self.park["attempt"]) except BaseException as e: # SystemExit too: a parked error, not a dead thread log.exception("world: construction failed (attempt %d); retrying in %g s", self.park["attempt"], delay) line = (f"{type(e).__name__}: {e}".strip().splitlines() or [""])[0][:300] self.park.update(error=redact(line), retry_at=time.monotonic() + delay) self.stop.wait(delay) delay = min(delay * 2, PARK_CAP_S)
def agent(self, headers) -> str: """The caller's agent name from its credential (401 when missing or unknown).""" got = _credential(headers) # Compare with every credential: the time taken does not depend on which one matched. name = None for credential, who in self.credentials.items(): if hmac.compare_digest(got.encode(), credential.encode()): name = who if not got or name is None: raise Refused(401, "unauthorized", "missing or unknown credential") return name
def check_admin(self, headers) -> None: if not self.admin_token: raise Refused(403, "forbidden", "no admin token: set PYBOT_ADMIN_TOKEN on the world") if not hmac.compare_digest(_credential(headers).encode(), self.admin_token.encode()): raise Refused(401, "unauthorized", "missing or wrong admin token")
def ready(self) -> World: if self.world is None: left = max(0.0, self.park["retry_at"] - time.monotonic()) raise Refused(503, "parked", f"the world is not ready ({self.park['error']}); attempt " f"{self.park['attempt']}", max(1, math.ceil(left))) return self.world
def dispatch(self, name: str, args: Any, agent: Agent) -> Any: """Run tool `name`: its result (redacted), or ToolError / Refused.""" if name not in self.schemas: raise Refused(404, "unknown_tool", f"no tool {name!r}; tools: {', '.join(self.schemas)}") if err := check_args(self.schemas[name], args): raise ToolError(f"{name}: {err}", "bad_args") world = self.ready() try: result = self.pools[self.cls.pool(name)].run(world.call, name, args, agent) return redact(json.loads(json.dumps(result, default=str))) except (ToolError, Refused): raise except Exception: # The exception text can hold paths, command output or credentials: it stays in # the world's log, under an id the agent can quote. ref = uuid.uuid4().hex[:8] log.exception("tool %s failed for %s (error id %s)", name, agent.name, ref) raise Refused(500, "internal", f"the tool failed with an internal error (error id {ref})")
def metrics(self) -> dict[str, Any]: world = self.world try: custom = world.metrics() if world is not None else {} except Exception: log.exception("world.metrics() failed") custom = {} pools = {name: {"in_flight": p.in_flight, "limit": p.threads, "overloaded_429_total": p.refused} for name, p in self.pools.items()} return {"uptime_s": time.monotonic() - self.started, "parked": int(world is None), "attempt": self.park["attempt"], "pools": pools, "world": custom}
class Server(ThreadingHTTPServer): daemon_threads = True request_queue_size = 128 # many agents connect at once
def __init__(self, app: App, host: str, port: int): self.app = app super().__init__((host, port), Handler)
class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" # keep-alive: every answer has a Content-Length
def log_message(self, format, *args): # no access log pass
def send(self, status: int, body: Any, retry_after_s: float | None = None) -> None: data = json.dumps(body).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) if retry_after_s is not None and status in (429, 503): self.send_header("Retry-After", str(max(1, math.ceil(retry_after_s)))) self.end_headers() self.wfile.write(data)
def body(self, limit: int) -> Any: """The JSON body ({} when empty); 413 over `limit` bytes, 400 if it is not JSON.""" try: n = int(self.headers.get("Content-Length") or 0) except ValueError: n = -1 if n < 0 or n > limit or "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): self.close_connection = True # the body is never read raise Refused(413, "too_large", f"the request body must be at most {limit} bytes " "(with Content-Length)") data = self.rfile.read(n) try: return json.loads(data) if data.strip() else {} except ValueError: raise Refused(400, "bad_request", "the body must be JSON") from None
def do_GET(self): self.route("GET")
def do_POST(self): self.route("POST")
def do_PATCH(self): self.route("PATCH")
def route(self, method: str) -> None: app, path = self.server.app, self.path.split("?", 1)[0] upstream = path.startswith("/v1/tools/") try: if method == "GET" and path == "/healthz": return self.send(200, {"status": "parked" if app.world is None else "ready"}) if path == "/metrics" or path.startswith("/admin/"): app.check_admin(self.headers) return self.admin(method, path) if method == "GET" and path == "/world/manifest": app.agent(self.headers) return self.send(200, app.manifest) if method == "POST" and (upstream or path.startswith("/world/tools/")): agent = Agent(app.agent(self.headers), self.headers.get("X-Request-Id") or "") body = self.body(MAX_BODY) if upstream: args = body elif not isinstance(body, dict) or not isinstance(body.get("args", {}), dict): raise ToolError('the body must be {"args": {...}}', "bad_request") else: args = body.get("args", {}) result = app.dispatch(path.rsplit("/", 1)[1], args, agent) return self.send(200, result if upstream else {"ok": True, "result": result}) raise Refused(404, "not_found", f"no route {method} {path}") except ToolError as e: error = {"code": e.code, "message": redact(e.message)} if e.retry_after_s is not None: error["retry_after_s"] = e.retry_after_s if upstream: # with a retry time: busy (429), else a refusal (400) status = 429 if e.retry_after_s is not None else 400 return self.send(status, {"error": error}, e.retry_after_s) return self.send(200, {"ok": False, "error": error}) except Refused as e: error = {"code": e.code, "message": e.message} if e.retry_after_s is not None: error["retry_after_s"] = e.retry_after_s if e.status == 500 and not upstream: # a tool's internal error is a tool error return self.send(200, {"ok": False, "error": error}) return self.send(e.status, {"error": error} if upstream else {"ok": False, "error": error}, e.retry_after_s)
def admin(self, method: str, path: str) -> None: app = self.server.app if method == "GET" and path == "/metrics": return self.send(200, app.metrics()) admin = app.ready().admin try: if method == "GET" and path == "/admin/knobs": return self.send(200, admin.describe()) if method == "PATCH" and path == "/admin/knobs": changes = admin.set(self.body(ADMIN_MAX_BODY)) return self.send(200, {"ok": True, "changes": changes, "knobs": admin.describe()}) if method == "GET" and path == "/admin/paused": return self.send(200, {"paused": dict(admin.paused)}) if method == "POST" and path in ("/admin/pause", "/admin/resume"): body = self.body(ADMIN_MAX_BODY) body = body if isinstance(body, dict) else {} if path == "/admin/pause": admin.pause(body.get("lanes"), str(body.get("reason") or "")) else: admin.resume(body.get("lanes")) return self.send(200, {"ok": True, "paused": dict(admin.paused)}) except ValueError as e: raise Refused(400, "bad_request", str(e)) from None raise Refused(404, "not_found", f"no route {method} {path}")
def serve(cls: type[World], host: str = "0.0.0.0", port: int = 7860) -> None: """Serve `cls` until SIGTERM or SIGUSR1 (a reclaim notice); then return, so the world's atexit hooks (a final save) run.""" credentials = seat_credentials() if not credentials: raise SystemExit("no PYBOT_TOKEN_<seat> is set: the world needs the agents' credentials") app = App(cls, credentials, os.environ.get("PYBOT_ADMIN_TOKEN", "")) server = Server(app, host, port)
def stop(signum, frame): if not app.stop.is_set(): log.warning("world: signal %d: shutting down", signum) app.stop.set() threading.Thread(target=server.shutdown, daemon=True).start()
signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGUSR1, stop) threading.Thread(target=app.builder, name="world-build", daemon=True).start() log.warning("world %s on http://%s:%d (%d agent credentials)", cls.name, host, port, len(credentials)) server.serve_forever() server.server_close()112344 unmodified lines91011121312131415161718192021222324252627282930313233343536373839404142434445462147484950"""One archive for world state; agent clones live in their own worker snapshots.""""""One archive for world state (world.tar.gz in PYBOT_BUCKET); agent clones live with the agents."""from __future__ import annotations
import argparse4 unmodified linesimport tempfilefrom pathlib import Path, PurePosixPath
from legion.worker.sync import HubBucketStorefrom legion.world.store import backup_tofrom store import backup_to
# state.db is copied with the online backup API (consistent while the world writes it).FILES = ("repo.bundle", "state.db", "prs.json", "prs.jsonl", "eval-queue.jsonl", "knobs.json", "outbox-comment.jsonl")
class Bucket: """Files under hf://buckets/<ns>/<name>[/<prefix>], through huggingface_hub's bucket API."""
def __init__(self, url, token=None): from huggingface_hub import HfApi
parts = url.removeprefix("hf://buckets/").strip("/").split("/") if len(parts) < 2: raise ValueError(f"bad bucket url {url!r}; expected hf://buckets/<namespace>/<name>[/prefix]") self.bucket_id, self.base = "/".join(parts[:2]), "".join(f"{p}/" for p in parts[2:]) self.api = HfApi(token=token)
def list(self, prefix): from huggingface_hub import BucketFile
full = self.base + prefix return [f.path[len(self.base):] for f in self.api.list_bucket_tree( self.bucket_id, prefix=full, recursive=True) if isinstance(f, BucketFile) and f.path.startswith(full)]
def upload(self, files): self.api.batch_bucket_files(self.bucket_id, add=[(str(p), self.base + r) for p, r in files])
def download(self, files): self.api.download_bucket_files(self.bucket_id, [(self.base + r, str(p)) for r, p in files])
def transfer(mode, workspace, bucket, store=None): store = store or HubBucketStore(bucket, token=os.environ.get("HF_TOKEN")) store = store or Bucket(bucket, token=os.environ.get("HF_TOKEN")) if mode == "restore" and "world.tar.gz" not in store.list("world.tar.gz"): return False # a first start; permission/network/invalid-archive failures still raise workspace = Path(workspace)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179"""A small `(kind, key) -> JSON` table on SQLite in WAL mode.
For worlds that keep their state in memory and want saves that cost O(changes): the world readsits own dicts, marks the rows it changed with `dirty(kind, key)`, and a saver calls`flush(read)`, which upserts (or deletes) only those rows in one transaction. `backup_to(path)`writes a consistent copy while others write (SQLite online backup API), for archives.
Rows moved out of the hot set (`put(..., cold=True)`) stay readable with `get` and`iter(kind, cold=True)`; `iter(kind)` (the hot rows) is what a world loads at start.
store = Store(ws / "state.db") state = {key: value for key, value in store.iter("prs")} state["7"] = {...}; store.dirty("prs", "7") store.flush(lambda kind, key: state.get(key)) # None deletes the row"""
from __future__ import annotations
import contextlibimport jsonimport sqlite3import threadingimport timefrom collections.abc import Callable, Iteratorfrom pathlib import Pathfrom typing import Any
SCHEMA = """CREATE TABLE IF NOT EXISTS rows ( kind TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, cold INTEGER NOT NULL DEFAULT 0, ts REAL NOT NULL, PRIMARY KEY (kind, key));"""UPSERT = ("INSERT INTO rows (kind, key, value, cold, ts) VALUES (?, ?, ?, ?, ?) " "ON CONFLICT (kind, key) DO UPDATE SET value = excluded.value, cold = excluded.cold, " "ts = excluded.ts")
class Store: """Thread-safe: one connection behind a lock (writes are short: dirty rows only)."""
def __init__(self, path: str | Path) -> None: self.path = Path(path) self._lock = threading.Lock() # (kind, key) -> generation of its newest change; _written: generation last committed, # so a flush that lost a race never commits an older value over a newer one. self._dirty: dict[tuple[str, str], int] = {} self._written: dict[tuple[str, str], int] = {} self._gen = 0 self._flushing = 0 # flushes between their read and their commit self._db = sqlite3.connect(self.path, check_same_thread=False, isolation_level=None) self._db.execute("PRAGMA journal_mode=WAL") self._db.execute("PRAGMA synchronous=NORMAL") # WAL: durable at checkpoints, never corrupt self._db.execute("PRAGMA journal_size_limit=4194304") # truncate the WAL after big writes self._db.executescript(SCHEMA)
def get(self, kind: str, key: str) -> Any: """The row's value (hot or cold), or None.""" with self._lock: row = self._db.execute("SELECT value FROM rows WHERE kind = ? AND key = ?", (kind, key)).fetchone() return None if row is None else json.loads(row[0])
def iter(self, kind: str, cold: bool = False) -> Iterator[tuple[str, Any]]: """(key, value) of the hot rows of `kind` (cold=True: the cold rows), in first-write order.""" with self._lock: rows = self._db.execute("SELECT key, value FROM rows WHERE kind = ? AND cold = ? " "ORDER BY rowid", (kind, int(cold))).fetchall() for key, value in rows: yield key, json.loads(value)
def put(self, kind: str, key: str, value: Any, cold: bool = False) -> None: """Write one row now (and drop its dirty mark: this is its newest value).""" self.write([(kind, key, value)], cold=cold)
def delete(self, kind: str, key: str) -> None: self.write([(kind, key, None)])
def write(self, rows: list[tuple[str, str, Any]], cold: bool = False) -> None: """Upsert (value None: delete) several rows in one transaction.""" with self._lock: self._gen += 1 encoded = [(kind, key, self._gen, None if value is None else json.dumps(value)) for kind, key, value in rows] self._commit(encoded, cold)
def dirty(self, kind: str, key: str) -> None: """Mark a row changed; the next flush writes it.""" with self._lock: self._gen += 1 self._dirty.pop((kind, key), None) # re-insert: keeps the newest change last self._dirty[(kind, key)] = self._gen
@property def pending(self) -> int: """Rows marked dirty and not yet flushed.""" return len(self._dirty)
def flush(self, read: Callable[[str, str], Any], lock=None) -> int: """Write every dirty row in one transaction: `read(kind, key)` gives its current value (None: delete it). `lock` guards what `read` reads: it is held only while the rows are read and encoded, not during the commit. A row changed again meanwhile stays dirty. On a failed commit nothing is written and the rows stay dirty. Returns the rows written.""" with lock or contextlib.nullcontext(), self._lock: rows = [] for (kind, key), gen in self._dirty.items(): value = read(kind, key) rows.append((kind, key, gen, None if value is None else json.dumps(value))) if not rows: return 0 self._flushing += 1 with self._lock: try: self._commit(rows, False) finally: self._flushing -= 1 if not self._flushing: # no older read left in flight: nothing to guard against self._written.clear() return len(rows)
def _commit(self, rows, cold): """Write rows (kind, key, generation, encoded value or None) in one transaction, skipping any already written at a newer generation; then drop their dirty marks.""" rows = [r for r in rows if self._written.get(r[:2], 0) < r[2]] now = time.time() self._db.execute("BEGIN IMMEDIATE") try: for kind, key, _, value in rows: if value is None: self._db.execute("DELETE FROM rows WHERE kind = ? AND key = ?", (kind, key)) else: self._db.execute(UPSERT, (kind, key, value, int(cold), now)) self._db.execute("COMMIT") except BaseException: self._db.execute("ROLLBACK") raise for kind, key, gen, _ in rows: self._written[(kind, key)] = gen if self._dirty.get((kind, key), gen + 1) <= gen: del self._dirty[(kind, key)]
def backup_to(self, path: str | Path) -> None: """Consistent copy of the database, WAL included (SQLite online backup API). Holds the store's lock for the copy: writers wait.""" backup_to(self._db, path, self._lock)
def size(self) -> int: """Bytes on disk (database plus WAL).""" return sum(p.stat().st_size for p in (self.path, self.path.with_name(self.path.name + "-wal")) if p.exists())
def checkpoint(self) -> None: """Fold the WAL into the database file and truncate it.""" with self._lock: self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
def close(self) -> None: self.checkpoint() with self._lock: self._db.close()
def backup_to(db: sqlite3.Connection | str | Path, path: str | Path, lock=None) -> None: """Copy database `db` (a connection, or a file another process may be writing) to `path`.""" path = Path(path) path.unlink(missing_ok=True) src = db if isinstance(db, sqlite3.Connection) else sqlite3.connect(db) dst = sqlite3.connect(path) try: if lock is None: src.backup(dst) else: with lock: src.backup(dst) finally: dst.close() if src is not db: src.close()112345678910111226 unmodified lines3940414243444546474849505152535455"""Puts the world's modules on sys.path (legion is the installed package, README); test helpers.""""""Puts the world's modules on sys.path; test helpers."""from __future__ import annotations
import base64import osimport shutilimport subprocessimport sysimport tempfilefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1] # world/26 unmodified lines self.ops.append("delete") for rel in paths: (self.root / rel).unlink()
def capture(clone: Path) -> dict: """A clone's change as the pybot tools send it: {"base_sha": its merge base with origin/main, "patch": base64 of the binary diff of every tracked and nonignored file against it}.""" def git(*args, env=None): return subprocess.run(["git", "-C", str(clone), *args], check=True, capture_output=True, env=env).stdout base = git("merge-base", "HEAD", "refs/remotes/origin/main").decode().strip() with tempfile.TemporaryDirectory() as tmp: # a temporary index: the clone's stays as it is env = {**os.environ, "GIT_INDEX_FILE": str(Path(tmp) / "index")} git("add", "-A", env=env) patch = git("diff", "--cached", "--binary", "--full-index", "--find-renames", base, env=env) return {"base_sha": base, "patch": base64.b64encode(patch).decode()}9 unmodified lines101112131415161718131415161718192016 unmodified lines373839414240414243449 unmodified lines `respond(text, memory) -> str | None`; optional integer `PRIORITY` orders modules. Claim different modules so teams can work without editing the same files.4. Run `python -m unittest discover -s tests` in the clone, and test the whole bot: `legion-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.5. Submit a small PR using `legion-tool open_pr --json '{"path":"pybot","branch":"your-topic","title":"Your change", "description":"What changed, why, and test evidence"}'`. The worker uploads the clone's tracked and nonignored files, including working edits and deletions, with its git base. Keep tokens, notes and generated data call run_bot with `{"ref_or_path":"pybot","lines":["Hello","Bye"]}`.5. Submit a small PR: call open_pr with `{"path":"pybot","branch":"your-topic", "title":"Your change","description":"What changed, why, and test evidence"}`. The pybot tools send the clone's tracked and nonignored files, including working edits and deletions, as a patch against its git base. Keep tokens, notes and generated data outside the clone. Use the world tools for every repository write. The world commits as your agent and publishes the native Hub PR ref `refs/pr/<number>`. At most two open PRs per agent.16 unmodified lines until those reviewers approve or the author updates the PR for a fresh review. The world checks the frozen interface and the bot's output/crash/time contract.
All world and board tools use `legion-tool <name> --json '<arguments>'`.Run `legion-tool --list` for their current parameters. Board tools include channels,Use the pybot tools (open_pr, review_pr, ...) and the message board tools; theirdescriptions list the current parameters. Board tools include channels,create_channel, join_channel, post, read, search, dm, read_dms and react. Mention,reply, DM and joined-channel notifications arrive between rounds; run no pollers.Keep status and test logs in your notes. Use the board for short conversations.14 unmodified lines1516171819202122181920212227 unmodified lines505152565354555628 unmodified lines858687918889909113 unmodified lines10510610711110810911311011111211311411511611711870 unmodified lines1891901911901911921931921931941951961951961971981992002012022032042052062072082092107 unmodified lines21821922021021121221321421521621721821922022122222322122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129244 unmodified lines33733833927434034134234338 unmodified lines3823833843193853863223233873883893903913923933943953963283973983994004 unmodified lines405406407339340408409410411412137 unmodified lines5505515524845535545555561 unmodified line558559560492561562563564153 unmodified lines71871972065265372172272372472575 unmodified lines80180280373580480580680780880974181081174381281381481543 unmodified lines8598608617937948628638647967978658668678688692 unmodified lines872873874806875876877878879811880881882883622 unmodified lines150615071508144015091510144214431511151215131514151594 unmodified lines1610161116121544161316141615161613 unmodified lines16301631163215641633163416351636122 unmodified lines1759176017611693176217631695176417651766176756 unmodified lines18241825182617581827182817601829183018311763183218331765183418351836183714 unmodified lines1852185318541786178718551856185718581859588 unmodified lines24482449245023822451245223842453245424552456210 unmodified lines266726682669260126022603260426052606260726082609267026712672267326742675267626772678267926802681272 unmodified lines2954295529562888295729582959296027 unmodified lines2988298929902922292329242925292629272928292929302991299229322993299429952996293729972998299930002941294229433001300230033004300529473006300730082950295130093010301129532954301230132956295729582959296029612962296329643014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630372970303830393040304118 unmodified lines3060306130622995299629973063306429993065306630023003306730683005306930703071300830723073307430113075307630773014301530783079308030813082162 unmodified lines3245324632473184324832493250325114 unmodified linesimport httpximport pytest
from legion.world import Agent, ToolErrorfrom legion.world.server import create_appfrom legion.world.workspace import capture
from conftest import ROOT, FakeBucketfrom api import Agent, ToolErrorfrom conftest import ROOT, FakeBucket, capture
import pybotfrom pybot import PybotWorld27 unmodified lines def merge(self, pr, comment): # like the Hub: a three-way merge of refs/pr/N into main main, head = git(self.remote, "rev-parse", "main"), git(self.remote, "rev-parse", f"refs/pr/{pr}") tree = git(self.remote, "merge-tree", "--write-tree", main, head).split()[0] sha = git(self.remote, "-c", "user.name=world", "-c", "user.email=world@legion.invalid", sha = git(self.remote, "-c", "user.name=world", "-c", "user.email=world@pybot.invalid", "commit-tree", tree, "-p", main, "-p", head, "-m", comment) git(self.remote, "update-ref", "refs/heads/main", sha, main)
28 unmodified lines shutil.copytree(ROOT / seed_dir, seed, ignore=shutil.ignore_patterns("__pycache__")) git(seed, "init", "-b", "main") git(seed, "add", ".") git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-m", "seed") git(seed, "-c", "user.name=seed", "-c", "user.email=seed@pybot.invalid", "commit", "-m", "seed") remote = tmp_path / "remote.git" git(tmp_path, "clone", "--bare", str(seed), str(remote)) repo = Repository(tmp_path / "world.git", str(remote))13 unmodified lines
def submit(world, clone, author="cedar", branch="greeting", pr=None): return world.call_workspace("open_pr", {"branch": branch, "title": "Improve greetings", return call_workspace(world, "open_pr", {"branch": branch, "title": "Improve greetings", "description": "Tested a conversation and the interface.", "pr": pr}, Agent(author), capture(clone.parent, clone.name)) Agent(author), capture(clone))
def call_workspace(world, name, args, agent, workspace): """A tool call with the clone's change, as the pybot tools send it.""" return world.call(name, {**args, "workspace": workspace}, agent)
def merge(world, agent, pr):70 unmodified lines merge(world, Agent("pine"), rec["pr"])
def test_upload_rejects_escape_and_symlink(setup): _, clone, _ = setup with pytest.raises(ValueError, match="inside"): capture(clone, "../..")def test_workspace_rejects_escape_and_symlink(setup): world, clone, _ = setup (clone / "leak").symlink_to("/etc/passwd") with pytest.raises(ValueError, match="symlinks"): capture(clone.parent, clone.name) with pytest.raises(ToolError, match="symlinks") as e: submit(world, clone) assert e.value.code == "bad_workspace" (clone / "leak").unlink() args = {"branch": "topic", "title": "Escape", "description": "tested"} for path in ("../leak", ".git/hooks/post-commit"): patch = (f"diff --git a/{path} b/{path}\nnew file mode 100644\n--- /dev/null\n+++ b/{path}\n" "@@ -0,0 +1 @@\n+leak\n").encode() with pytest.raises(ToolError) as e: call_workspace(world, "open_pr", args, Agent("cedar"), {**capture(clone), "patch": base64.b64encode(patch).decode()}) assert e.value.code == "bad_workspace", path assert world.repo.hub.n == 0
def test_seed_module_loading_and_sandbox(setup):7 unmodified lines assert world.run_bot("main", ["hi"])["timeout_s"] == 300
async def test_http_upload_is_outside_model_args(setup): world, clone, _ = setup app = create_app(world, "secret") async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://world") as client: payload = {"args": {"branch": "hello", "title": "Hello bot", "description": "tested"}, "workspace": capture(clone.parent, clone.name)} headers = {"X-World-Token": "secret", "X-Legion-Agent": "cedar"} r = await client.post("/tools/open_pr", json=payload, headers=headers) assert r.json()["ok"], r.text assert "secret" not in r.text payload["workspace"]["files"]["../leak"] = base64.b64encode(b"leak").decode() payload["args"]["branch"] = "bad" r = await client.post("/tools/open_pr", json=payload, headers=headers) assert not r.json()["ok"]def test_http_routes_credentials_and_workspace(setup, monkeypatch): import server
world, clone, remote = setup monkeypatch.setenv("WORLD_TEST_TOKEN", "c" * 40) # a secret-looking env value is redacted creds = {"c" * 40: "cedar", "b" * 40: "birch"} httpd = server.Server(server.App(world, creds, admin_token="a" * 40), "127.0.0.1", 0) threading.Thread(target=httpd.serve_forever, daemon=True).start() cedar, birch = {"Authorization": "Bearer " + "c" * 40}, {"X-World-Token": "b" * 40} try: with httpx.Client(base_url=f"http://127.0.0.1:{httpd.server_port}", timeout=60) as c: assert c.get("/healthz").json() == {"status": "ready"} for headers in ({}, {"X-World-Token": "wrong"}, {"Authorization": "Bearer " + "a" * 40}): assert c.get("/world/manifest", headers=headers).status_code == 401 m = c.get("/world/manifest", headers=birch).json() assert m["name"] == "pybot" and len(m["tools"]) == 10 # upstream route: flat args with the clone's change; the result as is (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n') args = {"branch": "hello", "title": "Hello bot", "description": "tested"} r = c.post("/v1/tools/open_pr", json={**args, "workspace": capture(clone)}, headers=cedar) assert r.status_code == 200 and r.json()["author"] == "cedar", r.text assert "bot/modules/topic.py" in git(remote, "ls-tree", "-r", "--name-only", r.json()["head_sha"]) assert "c" * 40 not in r.text pr, head = r.json()["pr"], r.json()["head_sha"] review = {"pr": pr, "head_sha": head, "verdict": "approve", "comment": "ok"} r = c.post("/v1/tools/review_pr", json=review, headers=cedar) # a refusal: 4xx assert r.status_code == 400 and "self-review" in r.json()["error"]["message"] assert c.post("/v1/tools/nope", json={}, headers=cedar).status_code == 404 r = c.post("/v1/tools/merge_pr", json={"pr": "1"}, headers=cedar) assert r.status_code == 400 and r.json()["error"]["code"] == "bad_args" # direct route: the {"ok", ...} envelope, the same dispatch r = c.post("/world/tools/review_pr", json={"args": review}, headers=birch) assert r.json()["ok"] and r.json()["result"]["reviewer"] == "birch" r = c.post("/world/tools/merge_pr", json={"args": {"pr": "1"}}, headers=birch) assert r.status_code == 200 and r.json()["error"]["code"] == "bad_args" bad = {"base_sha": git(remote, "rev-parse", "main"), "patch": "not base64!"} r = c.post("/world/tools/open_pr", json={"args": {**args, "branch": "bad", "workspace": bad}}, headers=birch) assert not r.json()["ok"] and r.json()["error"]["code"] == "bad_workspace", r.text big = {"args": {"ref_or_path": "main", "lines": ["x" * (1 << 20)]}} for route in ("/v1/tools/run_bot", "/world/tools/run_bot"): assert c.post(route, json=big, headers=birch).status_code == 413 # a refusal with a retry time: 429 with Retry-After upstream, retry_after_s in the envelope monkeypatch.setattr(world, "_check_budget", lambda agent: (_ for _ in ()).throw( ToolError("budget", "open_budget", retry_after_s=60))) r = c.post("/v1/tools/open_pr", json={**args, "branch": "two", "workspace": capture(clone)}, headers=birch) assert r.status_code == 429 and r.headers["Retry-After"] == "60", r.text r = c.post("/world/tools/open_pr", json={"args": {**args, "branch": "two", "workspace": capture(clone)}}, headers=birch) assert r.json()["error"]["retry_after_s"] == 60 # operators: their own token, never an agent's assert c.get("/metrics", headers=cedar).status_code == 401 assert c.get("/metrics", headers={"X-World-Token": "a" * 40}).json()["world"]["open_prs"] == 1 r = c.patch("/admin/knobs", json={"pr.open_floor": 3}, headers={"X-World-Token": "a" * 40}) assert r.json()["ok"] and world.budget_floor == 3 finally: httpd.shutdown() httpd.server_close() # admission control: a pool past its threads (and queue) answers 429 with pytest.raises(server.Refused) as e: busy = server.Pool(1, max_wait_s=0.01) busy.slots.acquire() busy.run(lambda: None) assert (e.value.status, e.value.retry_after_s) == (429, server.RETRY_AFTER_S) full = server.Pool(1, queue=0) full.in_flight = 1 with pytest.raises(server.Refused): full.run(lambda: None)
def test_bot_cannot_read_world_credentials_or_write_files(setup, monkeypatch):44 unmodified lines world, clone, remote = setup world.close() bucket, hub = FakeBucket(tmp_path / "bucket"), LocalHub(remote) monkeypatch.setattr("snapshot.HubBucketStore", lambda url, token=None: bucket) monkeypatch.setattr("snapshot.Bucket", lambda url, token=None: bucket) monkeypatch.setattr(pybot, "Hub", lambda repo_id: hub) monkeypatch.setattr(pybot, "Repository", lambda root, url, hub: Repository(root, str(remote), hub)) monkeypatch.setenv("PYBOT_BUCKET", "hf://buckets/fake/run")38 unmodified linesdef test_upload_respects_ignores_size_limit_and_compiles_only_changes(setup, monkeypatch): world, clone, remote = setup (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n') snapshot = capture(clone.parent, clone.name) junk = {".venv/lib/broken.py": b"def (:\n", "bot/__pycache__/x.cpython-312.pyc": b"\0junk", ".pytest_cache/v/cache/lastfailed": b"{}"} snapshot["files"].update({k: base64.b64encode(v).decode() for k, v in junk.items()}) snapshot["files"].pop(".gitignore") # the world's default excludes still apply for name, data in junk.items(): (clone / name).parent.mkdir(parents=True, exist_ok=True) (clone / name).write_bytes(data) (clone / ".gitignore").unlink() # the junk goes along; the world's default excludes still apply snapshot = capture(clone) assert all(name.encode() in base64.b64decode(snapshot["patch"]) for name in junk) checked = [] real = world._contract monkeypatch.setattr(world, "_contract", lambda tree, names=None: (checked.append(names), real(tree, names))) rec = world.call_workspace("open_pr", {"branch": "topic", "title": "Topic module", rec = call_workspace(world, "open_pr", {"branch": "topic", "title": "Topic module", "description": "tested"}, Agent("cedar"), snapshot) committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines() assert "bot/modules/topic.py" in committed and ".gitignore" not in committed4 unmodified lines with pytest.raises(ToolError, match="file too large: bot/modules/data.py"): submit(world, clone, branch="big") with pytest.raises(ToolError, match="file too large"): world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture(clone.parent, clone.name)) call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture(clone)) assert world.repo.hub.n == 1 # the refused upload created no Hub PR
137 unmodified lines for name in ("open", "ready", "close"): # the push lane; comments and merges have their own monkeypatch.setattr(hub, name, tracked(getattr(hub, name))) monkeypatch.setattr(world.repo, "push", tracked(world.repo.push)) snapshot, errors = capture(clone.parent, clone.name), [] snapshot, errors = capture(clone), []
def call(fn): try:1 unmodified line except Exception as exc: # noqa: BLE001 errors.append(exc)
threads = [threading.Thread(target=call, args=(lambda who=who: world.call_workspace( threads = [threading.Thread(target=call, args=(lambda who=who: call_workspace(world, "open_pr", {"branch": "topic", "title": "Topic", "description": "tested"}, Agent(who), snapshot),)) for who in ("birch", "pine", "oak", "elm", "ash")] threads.append(threading.Thread(target=call, args=(lambda: approve(world, rec, "fir"),)))153 unmodified lines return real(snapshot, tree)
monkeypatch.setattr(world, "_files", slow_files) snapshot = capture(clone.parent, clone.name) slow = threading.Thread(name="slow", target=lambda: results.update(slow=world.call_workspace( snapshot = capture(clone) slow = threading.Thread(name="slow", target=lambda: results.update(slow=call_workspace(world, "open_pr", {"branch": "slow", "title": "Slow upload", "description": "tested"}, Agent("cedar"), snapshot))) slow.start()75 unmodified lines refused = [(e["event"], e["agent"], e["pr"], e["code"]) for e in events if e["event"].endswith("_refused")] assert refused == [("review_pr_refused", "cedar", rec["pr"], "tool_error"), ("merge_pr_refused", "birch", rec["pr"], "tool_error")] from legion.world import tool_schema from api import tool_schema
schema = tool_schema(world.tools()["merge_pr"]) assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema monkeypatch.setattr(pybot, "MAX_REQUESTS", 2) for i in range(3): world.call_workspace("open_pr", {"branch": "greeting", "title": "Bounded keys", call_workspace(world, "open_pr", {"branch": "greeting", "title": "Bounded keys", "description": "x", "pr": rec["pr"]}, Agent("cedar", request_id=f"req-{i}"), capture(clone.parent, clone.name)) Agent("cedar", request_id=f"req-{i}"), capture(clone)) assert list(world.state["requests"]) == ["req-1", "req-2"]
43 unmodified lines for bad, msg in (("hi", r"title must be 3–200 characters \(got 2\)"), ("t" * 201, r"\(got 201\)")): with pytest.raises(ToolError, match=msg): world.call_workspace("open_pr", {"branch": "other", "title": bad, "description": "d"}, Agent("cedar"), capture(clone.parent, clone.name)) call_workspace(world, "open_pr", {"branch": "other", "title": bad, "description": "d"}, Agent("cedar"), capture(clone)) with pytest.raises(ToolError, match="description must not be empty"): world.call_workspace("open_pr", {"branch": "other", "title": "Fine title", "description": " "}, Agent("cedar"), capture(clone.parent, clone.name)) call_workspace(world, "open_pr", {"branch": "other", "title": "Fine title", "description": " "}, Agent("cedar"), capture(clone))
def _module(clone, name, reply):2 unmodified lines
def _commit(clone, message="change"): git(clone, "add", "-A") git(clone, "-c", "user.name=a", "-c", "user.email=a@legion.invalid", "commit", "-qm", message) git(clone, "-c", "user.name=a", "-c", "user.email=a@pybot.invalid", "commit", "-qm", message)
def _rebase(clone): git(clone, "fetch", "-q", "origin") git(clone, "-c", "user.name=a", "-c", "user.email=a@legion.invalid", "rebase", "-q", "origin/main") git(clone, "-c", "user.name=a", "-c", "user.email=a@pybot.invalid", "rebase", "-q", "origin/main")
def _two_prs(setup, edit_one, edit_two):622 unmodified lines rec = submit(world, clone) pr, head = rec["pr"], rec["head_sha"] assert world.repo.sha(f"pr:{pr}") == head assert world.repo.git("rev-parse", f"refs/legion/pr/{pr}/{head}") == head assert world.repo.git("rev-parse", f"refs/pybot/pr/{pr}/{head}") == head main = world.repo.sha() world.repo.update_refs((f"refs/pr/{pr}", main), (f"refs/legion/pr/{pr}/{main}", main)) assert world.repo.sha(f"pr:{pr}") == main == world.repo.git("rev-parse", f"refs/legion/pr/{pr}/{main}") world.repo.update_refs((f"refs/pr/{pr}", main), (f"refs/pybot/pr/{pr}/{main}", main)) assert world.repo.sha(f"pr:{pr}") == main == world.repo.git("rev-parse", f"refs/pybot/pr/{pr}/{main}")
def _deck_line(clone, deck_id, *turns):94 unmodified lines repo = world.repo rec = submit(world, clone) _module(clone, "weather", "sunny") rec = submit(world, clone, pr=rec["pr"]) # a superseded head keeps its refs/legion/pr ref rec = submit(world, clone, pr=rec["pr"]) # a superseded head keeps its refs/pybot/pr ref assert repo.git("config", "maintenance.auto") == "false" # fetches start no background gc assert repo.git("config", "gc.auto") == "0" # no git command starts gc --auto either orphans = [repo.git("hash-object", "-w", "--stdin", data=f"orphan {i}".encode())13 unmodified lines assert set(info) == {"loose_before", "pack_refs_s", "pack_loose_s", "packs", "loose_after"} assert info["loose_after"] == "0" assert not [f for f in (repo.root / "refs").rglob("*") if f.is_file()] # all in packed-refs assert len(repo.git("for-each-ref", "--format=%(refname)", f"refs/legion/pr/{rec['pr']}/").split()) == 2 assert len(repo.git("for-each-ref", "--format=%(refname)", f"refs/pybot/pr/{rec['pr']}/").split()) == 2 assert re.search(r"^count: 0$", repo.git("count-objects", "-v"), re.MULTILINE) repo.git("cat-file", "-e", orphans[0]) # packed, not pruned after = set(pack_dir.glob("pack-*.pack"))122 unmodified lines _review(world, rec, "birch", "request_changes") _review(world, rec, "aspen", "approve") (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hi!"\n') new = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings", new = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": "Added a test.", "pr": rec["pr"]}, Agent("cedar"), capture(clone.parent, clone.name)) Agent("cedar"), capture(clone)) assert len(new["inbox"]) == 2 # birch's and aspen's reviews, no mergeable (changes requested) assert not any("ready to merge_pr" in line for line in new["inbox"]) assert "cedar" not in world.state["inbox"]56 unmodified lines world, clone, _ = setup assert [PybotWorld._age(s) for s in (5, 180, 7200, 200000)] == [ "just now", "3 min ago", "2 h ago", "2 d ago"] first = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings", first = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": "Tested."}, Agent("cedar", request_id="k1"), capture(clone.parent, clone.name)) capture(clone)) with world.lock: world._notify("cedar", 99, "merged", "news") retry = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings", retry = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": "Tested."}, Agent("cedar", request_id="k1"), capture(clone.parent, clone.name)) capture(clone)) assert retry["inbox"] == ["news (just now)"] and retry["pr"] == first["pr"] assert "inbox" not in world.state["requests"]["k1"]
14 unmodified lines world, clone, _ = setup world = PybotWorld(world.ws, world.repo) assert submit(world, clone, "cedar", "one")["pr"] == 1 second = world.call_workspace("open_pr", {"branch": "two", "title": "Two", "description": "t"}, Agent("birch"), capture(clone.parent, clone.name)) second = call_workspace(world, "open_pr", {"branch": "two", "title": "Two", "description": "t"}, Agent("birch"), capture(clone)) assert second["pr_budget"] == {"mode": "merges", "opened_last_hour": 2, "merged_last_hour": 0, "limit": 2, "available": 0, "next_slot_min": 60} with caplog.at_level("WARNING"), pytest.raises(ToolError) as exc:588 unmodified lines
def _open(world, clone, key, description="Tested a conversation.", pr=None, author="cedar"): result = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings", result = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings", "description": description, "pr": pr}, Agent(author, request_id=key), capture(clone.parent, clone.name)) Agent(author, request_id=key), capture(clone)) return {k: v for k, v in result.items() if k not in ("pr_budget", "inbox")}
210 unmodified lines assert got["content"].startswith("PRIORITY")
def test_manifest_declares_workspace_uploads_and_timeouts(setup): from legion.world.protocol import WorldManifest
tools = {t.name: t for t in WorldManifest.model_validate(setup[0].manifest()).tools} assert tools["open_pr"].workspace.arg == "path" and tools["open_pr"].workspace.default == "pybot" run = tools["run_bot"].workspace assert (run.arg, run.default, run.skip, run.skip_prefix) == ("ref_or_path", "main", ["main"], "pr:") assert tools["review_pr"].workspace is None assert {t.timeout_s for t in tools.values()} == {330}def test_manifest_lists_the_tools_and_the_workspace_argument(setup): m = setup[0].manifest() assert m["name"] == "pybot" and m["description"] tools = {t["name"]: t for t in m["tools"]} assert set(tools) == {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict", "verdicts", "world_status", "run_bot"} assert {n for n, t in tools.items() if "workspace" in t["parameters"]["properties"]} == { "open_pr", "run_bot"} assert tools["list_prs"]["annotations"] == {"readOnlyHint": True}
def test_a_slow_hub_merge_does_not_block_reads(setup, monkeypatch):272 unmodified lines world.store.close() for f in world.ws.glob("state.db*"): f.unlink() from legion.world.store import Store from store import Store
Store(world.ws / "state.db").close() # a kill during the first import: schema, no rows again = PybotWorld(world.ws, world.repo)27 unmodified lines submit(w, clone, branch="one")
def submit_v2(world, clone, author="cedar", branch="greeting", pr=None): from legion.world.workspace import capture_v2 snapshot = capture_v2(clone.parent, clone.name) assert "patch" in snapshot return world.call_workspace("open_pr", {"branch": branch, "title": "Improve greetings", "description": "Tested a conversation and the interface.", "pr": pr}, Agent(author), snapshot)
def test_open_pr_and_run_bot_through_a_v2_patch(setup):def test_open_pr_and_run_bot_through_a_patch(setup): world, clone, remote = setup assert "workspace-upload-v2" in world.manifest()["capabilities"] (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n') (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n') (clone / "bot/__pycache__").mkdir(exist_ok=True) (clone / "bot/__pycache__/x.pyc").write_bytes(b"\0junk") rec = submit_v2(world, clone) rec = submit(world, clone) committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines() assert "bot/modules/topic.py" in committed and not [n for n in committed if "__pycache__" in n] assert git(remote, "show", f"{rec['head_sha']}:bot/modules/greeting.py").endswith('"Hey!"') from legion.world.workspace import capture_v2 out = world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture_v2(clone.parent, clone.name)) out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture(clone)) assert out["replies"] == ["Hey!"] (clone / "bot/modules/data.py").write_text("X = 1\n" + "#" * (2 << 20)) with pytest.raises(ToolError, match="file too large"): submit_v2(world, clone, branch="big") submit(world, clone, branch="big")
def test_v2_with_an_unknown_base_asks_for_the_full_tree(setup, monkeypatch): world, clone, _ = setupdef test_a_missing_base_is_fetched_from_the_hub_or_refused(setup, monkeypatch): world, clone, remote = setup (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n') from legion.world.workspace import capture_v2 v2 = {**capture_v2(clone.parent, clone.name), "base_sha": "1" * 40} unknown = {**capture(clone), "base_sha": "1" * 40} args = {"branch": "topic", "title": "Topic module", "description": "tested"} with pytest.raises(ToolError, match="base is not a main commit"): # a v1 resend can't help world.call_workspace("open_pr", args, Agent("cedar"), v2) with pytest.raises(ToolError) as e: world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), v2) assert e.value.code == "need_full" v1 = {**capture(clone.parent, clone.name), "base_sha": "1" * 40} with pytest.raises(ToolError, match="base is not a main commit"): world.call_workspace("open_pr", args, Agent("cedar"), v1) for name, call_args in (("open_pr", args), ("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]})): with pytest.raises(ToolError) as e: call_workspace(world, name, call_args, Agent("cedar"), unknown) assert e.value.code == "unknown_base" with pytest.raises(ToolError) as e: # not a workspace call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), {"base_sha": "x", "files": {}}) assert e.value.code == "bad_workspace" # main moved on the Hub: the world fetches the agent's newer base (clone / "bot/modules/topic.py").unlink() _module(clone, "weather", "Sunny!") _commit(clone, "weather") git(clone, "push", "-q", "origin", "HEAD:main") git(clone, "fetch", "-q") (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n') assert not world.repo.has_commit(capture(clone)["base_sha"]) out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"), capture(clone)) assert out["replies"] == ["Hey!"] and out["sha"] == git(remote, "rev-parse", "main") # the budget is checked before any apply monkeypatch.setattr(world, "_check_budget", lambda agent: (_ for _ in ()).throw( ToolError("budget", "open_budget"))) monkeypatch.setattr(pybot, "apply_patch", lambda *a: pytest.fail("applied")) with pytest.raises(ToolError, match="budget"): world.call_workspace("open_pr", args, Agent("cedar"), capture_v2(clone.parent, clone.name)) call_workspace(world, "open_pr", args, Agent("cedar"), capture(clone))
# ---------------------------------------------------------------- reviewer cap, budget scope, seed (off in BASIC)18 unmodified lines merge(world, Agent("cedar"), rec["pr"])
def test_adds_module_reads_v1_and_v2_uploads(setup): from legion.world.workspace import capture_v2
def test_adds_module_reads_the_patch(setup): world, clone, _ = setup base = git(clone, "rev-parse", "HEAD")
def adds(): return (world._adds_module(capture(clone.parent, clone.name), base), world._adds_module(capture_v2(clone.parent, clone.name), base)) return world._adds_module(capture(clone))
assert adds() == (False, False) assert not adds() (clone / "tests/test_more.py").write_text("x = 1\n") (clone / "bot/modules/greeting.py").write_text('PRIORITY = -1000\n\ndef respond(text, memory):\n return "Hi!"\n') assert adds() == (False, False) # a test and an edit of an existing module assert not adds() # a test and an edit of an existing module (clone / "bot/modules/helpers").mkdir() (clone / "bot/modules/helpers/__init__.py").write_text("") assert adds() == (True, True) # a new package assert adds() # a new package shutil.rmtree(clone / "bot/modules/helpers") git(clone, "mv", "bot/modules/greeting.py", "bot/modules/hello.py") assert adds() == (True, True) # renamed to a new module name assert world._adds_module({"files": None}, base) and world._adds_module({"patch": "%%"}, base) assert adds() # renamed to a new module name assert world._adds_module({"patch": "%%"}) # unreadable: counted
def test_new_modules_scope_rations_only_prs_that_add_a_module(setup, monkeypatch):162 unmodified lines gaps.append(deadline) real_gap(agent, deadline) tree = git(remote, "rev-parse", "main^{tree}") moved = git(remote, "-c", "user.name=x", "-c", "user.email=x@legion.invalid", moved = git(remote, "-c", "user.name=x", "-c", "user.email=x@pybot.invalid", "commit-tree", tree, "-p", "main", "-m", "a merge elsewhere") git(remote, "update-ref", "refs/heads/main", moved) world.repo.fetch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667"""An agent's change, sent as `workspace: {"base_sha", "patch"}` with open_pr and run_bot.
`patch` is the base64 of `git diff --cached --binary --full-index --find-renames <base_sha>` ofthe agent's clone; the world applies it on its own checkout of `base_sha` (`apply_patch`)."""from __future__ import annotations
import base64import osimport reimport subprocessimport threadingfrom pathlib import Path
MAX_BYTES = 128 << 20MAX_FILES = 10000APPLY_MAX_MEMORY = 2 << 30 # address space of `git apply`: a binary delta can expand a lotAPPLY_SLOTS = threading.BoundedSemaphore(4) # `git apply` runs at once, world-wide
def git(root: Path, *args: str) -> str: p = subprocess.run(["git", "-C", str(root), *args], capture_output=True, timeout=30, check=False) if p.returncode: raise ValueError("git failed on the world's checkout") return p.stdout.decode().strip()
# git reads modes as octal and keeps only the type bits (0120000, 120755 are symlinks): any# new mode that is not exactly a regular file's is refused._MODES = re.compile(rb"^(?:new file mode |new mode |index \S+ )(.*)$", re.MULTILINE)_SIZES = re.compile(rb"^(?:literal|delta) (\d+)$", re.MULTILINE)
def apply_patch(workspace: dict, tree: Path) -> list[str]: """Apply the patch onto `tree`, a git checkout of its `base_sha` (the world's own), in the worktree (not the index), so the world's excludes apply when it stages the tree. Returns the paths that differ from the base (added, modified, deleted). ValueError for an invalid patch; symlinks and submodules are refused.""" try: patch = base64.b64decode(workspace.get("patch") or "", validate=True) except (ValueError, TypeError) as exc: raise ValueError("invalid workspace patch") from exc if git(tree, "rev-parse", "HEAD") != workspace.get("base_sha"): raise ValueError("the tree is not a checkout of the patch's base") if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)): raise ValueError("symlinks are not supported") # shortcut: a binary delta can expand past its declared size, up to the file-size and # memory limits below, with at most APPLY_SLOTS applies at once; decode delta headers if # that bound is too loose. if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES or sum(int(n) for n in _SIZES.findall(patch)) > MAX_BYTES): raise ValueError("workspace snapshot exceeds 128 MiB or 10,000 files") if patch: # prlimit, not preexec_fn: the world's server is threaded with APPLY_SLOTS: p = subprocess.run(["prlimit", f"--fsize={MAX_BYTES}", f"--as={APPLY_MAX_MEMORY}", "git", "-C", str(tree), "apply", "--binary", "--whitespace=nowarn", "-"], input=patch, capture_output=True, timeout=120, check=False) if p.returncode: raise ValueError("the workspace patch does not apply to its base") for top, dirs, files in os.walk(tree): if top == str(tree) and ".git" in dirs: dirs.remove(".git") if any(os.path.islink(os.path.join(top, n)) for n in dirs + files): raise ValueError("symlinks are not supported") names = git(tree, "ls-files", "-z", "--modified", "--deleted", "--others", "--exclude-standard") return sorted({n for n in names.split("\0") if n})