diff --git "a/world/src/legion/models.py" "b/world/src/legion/models.py" deleted file mode 100644--- "a/world/src/legion/models.py" +++ /dev/null @@ -1,2207 +0,0 @@ -"""Shared contracts between controller, worker and CLI. - -This file is the contract. Everything in docs/design.md "Contracts" -is expressed here. Change it deliberately and update the design doc. -""" - -from __future__ import annotations - -import hashlib -import ipaddress -import re -from datetime import UTC, date, datetime, timedelta -from enum import StrEnum -from typing import Annotated, Any, Literal, NamedTuple -from urllib.parse import urlsplit - -import yaml -from pydantic import ( - AfterValidator, - BaseModel, - Field, - field_validator, - model_serializer, - model_validator, -) - -from legion.buckets import BucketId -from legion.registry import COMPUTE, HARNESSES -from legion.world.protocol import TOOL_NAME_RE as WORLD_TOOL_RE -from legion.world.protocol import WorldManifest - -# --------------------------------------------------------------------------- spec YAML - - -class _SpecLoader(yaml.SafeLoader): - """SafeLoader with YAML 1.2 booleans: only true/false. YAML 1.1 (PyYAML's default) also - reads on/off/yes/no as booleans, so an `on:` key became `True`. - Dropping them in the loader protects every key and value of a spec, not just `loop.on`.""" - - -_BOOL = "tag:yaml.org,2002:bool" -_SpecLoader.yaml_implicit_resolvers = { - ch: [(tag, rx) for tag, rx in rs if tag != _BOOL] - for ch, rs in yaml.SafeLoader.yaml_implicit_resolvers.items() -} -_SpecLoader.add_implicit_resolver(_BOOL, re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"), - list("tTfF")) - - -def load_spec_yaml(text: str) -> Any: - """Parse spec YAML (safe, YAML 1.2 booleans); validate with `SwarmSpec.model_validate`.""" - return yaml.load(text, Loader=_SpecLoader) # a SafeLoader subclass - -# --------------------------------------------------------------------------- durations - -_DURATION_RE = re.compile(r"^\s*(\d+)\s*(ms|s|m|h|d)\s*$") -_UNIT_SECONDS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400} - - -def parse_duration(value: str | int | float | timedelta) -> timedelta: - """Parse '30s', '10m', '24h', '7d' (or a number of seconds) into a timedelta.""" - if isinstance(value, timedelta): - return value - if isinstance(value, (int, float)): - return timedelta(seconds=float(value)) - m = _DURATION_RE.match(value) - if not m: - raise ValueError(f"bad duration {value!r}; use e.g. 30s, 10m, 24h, 7d") - return timedelta(seconds=int(m.group(1)) * _UNIT_SECONDS[m.group(2)]) - - -def until_deadline(until: str, started_at: float) -> float: - """Epoch deadline of `while.until`: started_at + duration, or the ISO-8601 time (naive = UTC).""" - try: - return started_at + parse_duration(until).total_seconds() - except ValueError: - try: - t = datetime.fromisoformat(until) - except ValueError: - raise ValueError(f"bad until {until!r}; use a duration (2h) or a time (2026-10-28T20:00Z)") from None - return (t if t.tzinfo else t.replace(tzinfo=UTC)).timestamp() - - -# --------------------------------------------------------------------------- enums - - -# the names in legion.registry.HARNESSES; an enum so spec errors and the JSON schema list them -Harness = StrEnum("Harness", [(name, name) for name in HARNESSES], module=__name__) - - -class AgentState(StrEnum): - working = "working" # a harness process is running a turn - idle = "idle" # no process; idle_since set - stuck = "stuck" # a turn exceeded its timeout and was killed; cleared on next turn - unknown = "unknown" # heartbeat older than compute.worker_unknown_after (per-backend default) - dead = "dead" # heartbeat older than compute.worker_dead_after, or job terminal - - -class WorkerState(StrEnum): - launching = "launching" - running = "running" - draining = "draining" - unknown = "unknown" - dead = "dead" - - -class TypeHealth(StrEnum): - ok = "ok" - crashlooping = "crashlooping" - launch_refused = "launch_refused" # the backend refused the launch (4xx); waits for a new apply - - -# --------------------------------------------------------------------------- spec - -AGENT_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*-\d{4,}$") -TYPE_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$") -ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") -TOOLS_VERSION_RE = re.compile(r"^[0-9a-f]{16}$") -ZERO_PRICING = [0.0, 0.0, 0.0] # a type without `pricing`: its usage costs $0 - -Reasoning = Literal["off", "low", "medium", "high"] -# `reasoning` -> OpenAI `reasoning.effort`. -REASONING_EFFORT = {"off": "none", "low": "low", "medium": "medium", "high": "high"} - - -def _pricing_row(v: list[float], where: str) -> list[float]: - if len(v) != 3 or any(x < 0 for x in v): - raise ValueError(f"{where}: pricing must be [input, output, cached] USD per 1M tokens, >= 0") - return [float(x) for x in v] - - -# --------------------------------------------------------------------------- inference (docs/open-models.md) - -HF_ROUTER_URL = "https://router.huggingface.co/v1" -# `hf_router.provider` values that let the router pick the provider per request -ROUTER_POLICIES = ("fastest", "cheapest", "preferred") -# What a Trial gets for servers that take no key: Pi needs a key reference all the same -NO_KEY_ENV, NO_KEY = "LEGION_INFERENCE_KEY", "none" -_ROUTER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") - - -def namespace_name(value: str) -> str: - """A namespace is also an HTTP header value: allow empty, otherwise one ASCII name.""" - if value and not _ROUTER_NAME_RE.fullmatch(value): - raise ValueError("namespace must be empty or an account name, e.g. my-org") - return value - - -Namespace = Annotated[str, AfterValidator(namespace_name)] - - -class HFRouter(BaseModel): - """`inference.hf_router`: the HF router, sent `:`.""" - - model_config = {"extra": "forbid"} - - # A provider (`deepinfra`), or a selection policy: `fastest` (the router's default), - # `cheapest` or `preferred` (your order in the Hub settings). None: the router's default. - provider: str | None = None - - @field_validator("provider") - @classmethod - def _name(cls, v: str | None) -> str | None: - if v is not None and not _ROUTER_NAME_RE.match(v): - raise ValueError(f"{v!r} must be a name, e.g. deepinfra or huggingface") - return v - - @property - def policy(self) -> bool: - """The router picks the provider per request: no provider is named.""" - return self.provider is None or self.provider in ROUTER_POLICIES - - -# `inference.hf_jobs` (docs/open-models.md "Servers legion starts"): the vLLM image legion starts -# (it serves Qwen3_5ForConditionalGeneration), the port the jobs proxy exposes, and the job -# lifetime when neither the spec nor its compile step set one -DEFAULT_VLLM_IMAGE = "vllm/vllm-openai:v0.33.0" -VLLM_PORT = 8000 -DEFAULT_SERVER_TIMEOUT = "2h" -# `vllm_args` keys legion sets itself: the server's address and name, the model, and the -# tool-calling flags, which are named fields. `api_key`: the jobs proxy drops `Authorization`, -# so vLLM would refuse every request (the proxy's HF-token check is the authentication). -VLLM_OWNED = ("host", "port", "served_model_name", "model", "api_key", "enable_auto_tool_choice", - "tool_call_parser", "reasoning_parser") -_VLLM_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$") - - -def vllm_arg_key(entry: str) -> str: - """`max-model-len=131072` -> `max_model_len`: one spelling per flag.""" - return entry.split("=", 1)[0].strip().replace("-", "_") - - -class HFJobs(BaseModel): - """`inference.hf_jobs`: vLLM servers legion starts on HF Jobs, one group per model, and stops - when the run ends (docs/open-models.md). The servers' URLs are pinned into the spec as - `urls` (`resolved_model.inference.urls`).""" - - model_config = {"extra": "forbid"} - - flavor: str = Field(min_length=1) # a GPU flavor (`hf jobs hardware`), e.g. a100-large - tool_call_parser: str = Field(min_length=1) # Pi needs tool calls: --enable-auto-tool-choice - reasoning_parser: str | None = None - # Every other `vllm serve` flag as KEY=VALUE (`max_model_len=131072` -> --max-model-len - # 131072; `true`/`false` -> --flag/--no-flag). Fills in max_num_seqs (the block's - # max_working) and tensor_parallel_size (the flavor's GPUs) unless set here. - vllm_args: list[str] = Field(default_factory=list) - # The job's lifetime, the backstop if the run never stops it; None: the run's - # run_timeout_seconds + startup_timeout + a margin (the compile step writes it) - timeout: str | None = None - startup_timeout: str = "20m" # how long legion waits for every replica to answer - replicas: int = Field(default=1, ge=1) # each agent calls one (rendezvous hashing) - image: str = DEFAULT_VLLM_IMAGE - - @field_validator("timeout", "startup_timeout") - @classmethod - def _duration(cls, v: str | None) -> str | None: - return None if v is None else _positive_duration(v) - - @field_validator("vllm_args") - @classmethod - def _vllm_args(cls, v: list[str]) -> list[str]: - seen: set[str] = set() - for entry in v: - key, _, value = entry.partition("=") - name = vllm_arg_key(entry) - if not _VLLM_KEY_RE.match(key.strip()) or not value.strip(): - raise ValueError(f"vllm_args {entry!r}: use KEY=VALUE (a flag: KEY=true), e.g. " - "max_model_len=131072") - if name in VLLM_OWNED: - named = name in HFJobs.model_fields - raise ValueError(f"vllm_args {entry!r}: " + ( - f"set hf_jobs.{name} instead" if named else - "the jobs proxy drops Authorization, so vLLM would refuse every request; " - "the proxy's HF-token check authenticates" if name == "api_key" else - "legion sets it")) - if name in seen: - raise ValueError(f"vllm_args: {name} is set twice") - seen.add(name) - return v - - -class Inference(BaseModel): - """Where a model runs (design.md 'Inference'): the HF router (`hf_router`, the default), - OpenAI-compatible servers you run (`urls`) or vLLM servers legion starts on HF Jobs - (`hf_jobs`), plus settings for any of them. The same block in a Harbor spec (the run's, a - role's) and a swarm spec (the swarm's, a type's). - - `api_key_env` names a secret / env var; the value is never in the spec. The controller - sends that secret to the workers and uses it for its checks; the worker hands it to the - harness. - - With `hf_jobs`, `urls` is what the controller pins once the servers answer (only in - `resolved_model.inference`; a spec that sets both is refused).""" - - model_config = {"extra": "forbid"} - - hf_router: HFRouter | None = None - # Servers (`.../v1`) that all serve the type's `model`; each agent calls one of them - urls: list[str] | None = None - hf_jobs: HFJobs | None = None - api_key_env: str | None = None # default: HF_TOKEN for hf_router and hf_jobs; no key for urls - # Max agents of this swarm on these endpoints in a turn at once. Enforced at prompt - # admission by the controller (LEGION_MAX_WORKING_ENFORCE=0: report only). - max_working: int | None = Field(default=None, ge=1) - context_window: int | None = Field(default=None, ge=1) # tokens, when the server reports none - # urls only: scrape each server's vLLM `/metrics` into the health snapshots (docs/health.md) - metrics: bool = False - # Pi's `--thinking` level; None: Pi's default - reasoning_effort: Literal["off", "minimal", "low", "medium", "high", "xhigh", "max"] | None = None - - @field_validator("urls", mode="before") - @classmethod - def _url_list(cls, v: Any) -> Any: - """A comma-separated string is a list (`urls: ${VLLM_URLS}`).""" - if isinstance(v, str): - return [u.strip() for u in v.split(",") if u.strip()] - return v - - @field_validator("urls") - @classmethod - def _urls(cls, v: list[str] | None) -> list[str] | None: - if v is None: - return v - out = [] - for u in v: - url = urlsplit(u.strip()) - if (url.scheme not in ("http", "https") or not url.hostname or url.username - or url.password or url.query or url.fragment): - raise ValueError(f"{u!r} must be an HTTP(S) URL without credentials, e.g. " - "http://10.0.0.5:8000/v1") - out.append(u.strip().rstrip("/")) - if not out: - raise ValueError("urls must list at least one URL") - if len(set(out)) != len(out): - raise ValueError("urls must not repeat a URL") - return out - - @field_validator("api_key_env") - @classmethod - def _env_name(cls, v: str | None) -> str | None: - if v is not None and not ENV_NAME_RE.match(v): - raise ValueError(f"api_key_env {v!r} must be an env var name (the key itself never " - "goes in the spec)") - return v - - @model_validator(mode="after") - def _one(self) -> Inference: - given = [k for k in ("hf_router", "urls", "hf_jobs") if getattr(self, k) is not None] - if self.hf_jobs is not None and self.urls is not None: - given.remove("urls") # the started servers', pinned (refused in a spec's own block) - if len(given) > 1: - raise ValueError(f"set one of hf_router, urls or hf_jobs, not {' and '.join(given)}") - if not given: - self.hf_router = HFRouter() - if self.metrics and self.urls is None: - raise ValueError("metrics scrapes your servers' vLLM metrics: it needs urls") - return self - - def held(self) -> Inference: - """The block as workers (its key) and Trials (endpoints, Pi's config) hold it: without - the controller's `max_working`.""" - return self.model_copy(update={"max_working": None}) - - @property - def endpoints(self) -> list[str]: - """The servers' base URLs, as written: `urls` (with `hf_jobs`, the started servers' - once pinned), or the router's. Empty: hf_jobs servers not started yet.""" - if self.urls: - return list(self.urls) - return [HF_ROUTER_URL] if self.hf_router is not None else [] - - @property - def key_env(self) -> str | None: - """The key's env name: `api_key_env`, else HF_TOKEN for the router and the HF Jobs - proxy; None: no key.""" - hf = self.hf_router is not None or self.hf_jobs is not None - return self.api_key_env or ("HF_TOKEN" if hf else None) - - def unpinned(self) -> Inference: - """The block as a spec writes it: without the started servers' `urls`.""" - return self.model_copy(update={"urls": None}) if self.hf_jobs is not None else self - - def request_model(self, model: str) -> str: - """What the servers are sent as `model`: `:` for the router with a - provider or policy set, else `model`.""" - r = self.hf_router - return f"{model}:{r.provider}" if r is not None and r.provider else model - - def endpoint_for(self, run: str, agent: str) -> str: - """The server `agent` of `run` (a swarm's name, the upstream launcher's run id) calls: - rendezvous hashing of both over `endpoints`. Stable for a given list, so an agent keeps - its server (and the server its prefix cache) across Trials and restarts; spreads agents - roughly evenly, including one name in many runs (every run's `agent-001`); and a URL - added or removed moves only the agents that must move.""" - return max(self.endpoints, - key=lambda u: hashlib.sha256(f"{run}\n{agent}\n{u}".encode()).digest()) - - def describe(self) -> str: - """One line for status: `hf_router deepinfra`, the URLs, or `hf_jobs ` and the - started servers' URLs.""" - if self.hf_router is not None: - return f"hf_router {self.hf_router.provider or 'fastest'}" - if self.hf_jobs is not None: - return f"hf_jobs {self.hf_jobs.flavor}" + ( - f", urls {', '.join(self.endpoints)}" if self.urls else ", not started") - return "urls " + ", ".join(self.endpoints) - - -def loopback_url(url: str) -> bool: - """The URL names the machine it is used on: `localhost` or a loopback address.""" - host = urlsplit(url).hostname or "" - if host == "localhost" or host.endswith(".localhost"): - return True - try: - return ipaddress.ip_address(host).is_loopback - except ValueError: - return False - - -def private_url(url: str) -> bool: - """The URL names this machine or a private network (an RFC 1918 or link-local address).""" - try: - return loopback_url(url) or ipaddress.ip_address(urlsplit(url).hostname or "").is_private - except ValueError: - return False - - -class ResolvedModel(BaseModel): - """A type's model after resolution, pinned into the stored spec at apply time.""" - - # The inference block it runs on, which admission (`max_working`) and status count by: - # `inference` (the swarm's) or `types..inference` (the type's own) - provider_name: str - # The block; with `hf_jobs`, plus the started servers' `urls`, pinned by the controller - # once they answer (controller/servers.py) and kept while the block and model are the same - inference: Inference - # Derived only from the spec's explicit namespace. Never from HF_TOKEN's whoami: - # the inference key can belong to someone else. Sent by preflight and Pi alike. - headers: dict[str, str] = Field(default_factory=dict) - model_id: str # the type's `model`: what legion prices the usage under - reasoning: Reasoning | None = None - pricing: list[float] # [input, output, cached] USD per 1M tokens, pinned - # The window the servers serve the model with, from GET /v1/models (vLLM's max_model_len, - # the router provider's context_length; under a router policy the smallest among the - # providers with tools), else `inference.context_window`. Pinned by the controller's apply - # (controller/inference.py); None before that. - context_window: int | None = None - - @property - def qualified(self) -> str: - return f"{self.provider_name}:{self.model_id}" - - @property - def request_model(self) -> str: - """What the harness sends as `model`.""" - return self.inference.request_model(self.model_id) - - -# --------------------------------------------------------------------------- comms (docs/comms.md) - -# Built-in comms tools a type may list in `tools:`; the model sees the bare name (`post`). -COMMS_TOOLS = ("comms:post", "comms:read", "comms:search") -EXTENDED_COMMS_TOOLS = ("comms:channels", "comms:create_channel", "comms:join_channel", - "comms:dm", "comms:read_dms", "comms:react", "comms:votes", "comms:doc", - "comms:edit_doc") -ALL_COMMS_TOOLS = COMMS_TOOLS + EXTENDED_COMMS_TOOLS -COMMS_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$") - - -def normalize_board_url(url: str) -> str: - """The one spelling of a board url, used wherever board urls are stored or compared (spec, - identities, board clients, message sources): scheme and host lowercased, default port and - trailing slashes dropped, IPv6 brackets and userinfo kept, so it is idempotent. - `http://Board.invalid:80/` -> `http://board.invalid`; `http://[::1]:8080/` -> `http://[::1]:8080`.""" - from urllib.parse import urlsplit, urlunsplit - - u = urlsplit(url.strip()) - scheme, host = u.scheme.lower(), (u.hostname or "").lower() - if ":" in host: # an IPv6 literal keeps its brackets: `http://[::1]:8080` - host = f"[{host}]" - port = u.port - netloc = host if port is None or (scheme, port) in (("http", 80), ("https", 443)) else f"{host}:{port}" - if u.username or u.password: - netloc = u.netloc.rsplit("@", 1)[0] + "@" + netloc - return urlunsplit((scheme, netloc, u.path.rstrip("/"), u.query, "")) - - -def comms_name(entry: str) -> str: - """`comms:post` -> `post`, the name the model sees.""" - return entry.split(":", 1)[1] - - -class CommsRules(BaseModel): - """Enforced by the worker before it calls the board; a refused post is a tool result - ("refused: ..."), never a board request. Live: a re-apply reaches workers by heartbeat.""" - - model_config = {"extra": "forbid"} - - min_post_gap: str | None = None # per agent, e.g. 20s - max_posts: int | None = None # per agent, for the run (kept in the agent's synced state) - max_len: int | None = None # characters per post - threads: Literal["per_topic"] | None = None # posts must say thread: new or a root id - max_channels_per_agent: int = Field(default=3, ge=1, le=100) - max_channels: int = Field(default=60, ge=1, le=100) - no_group_mentions: bool = False # refuse @all / @agents / @humans (and @everyone, @people) - - @field_validator("min_post_gap") - @classmethod - def _gap(cls, v: str | None) -> str | None: - if v is not None: - parse_duration(v) - return v - - @field_validator("max_posts", "max_len") - @classmethod - def _positive(cls, v: int | None) -> int | None: - if v is not None and v < 1: - raise ValueError("must be >= 1") - return v - - @property - def gap_s(self) -> float: - return parse_duration(self.min_post_gap).total_seconds() if self.min_post_gap else 0.0 - - -class CommsSpec(BaseModel): - """Swarm-level `comms:` (docs/comms.md). `url`, `invite_env` and `channel` are resolved - once by the controller at apply (channel name -> `channel_id`); `kickoff_file` and - `protocols` are files next to the spec that `legion launch` inlines (`kickoff`, - `protocols_text`), because the controller and workers cannot read the caller's files.""" - - model_config = {"extra": "forbid"} - - kind: Literal["msgboard"] = "msgboard" - extended: bool = False # multi-channel tools and serialized per-identity activity polling - # extended: each agent identity's feed is polled about once per this many seconds; the - # worker's poll interval is max(2 s, poll_cycle_s / its agents). - poll_cycle_s: float | None = Field(default=None, ge=10, le=3600) # unset: 300 - url: str - # `space`: `legion init` duplicates `template` into a private per-run Space (`space`, default - # `