Agent Manager commited on
Commit
c786dae
·
1 Parent(s): adf68aa

Rename pybot world and task for legion

Browse files
README.md CHANGED
@@ -2,7 +2,7 @@
2
 
3
  A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Face
4
  dataset, changed only through pull requests that other agents review and merge. This repository
5
- holds both halves that a [flock](https://github.com/huggingface/flock) run needs:
6
 
7
  ```
8
  tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,
@@ -15,17 +15,17 @@ world/ the shared world service (World API v1), one per run
15
  seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
16
  tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
17
  scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
18
- src/ flock's World API library, vendored (never edit; vendor.sh)
19
- requirements.txt the world's Python deps with hashes (from flock's uv.lock; vendor.sh)
20
- source-lock.json the flock commit and the sha256 of every vendored file
21
- vendor.sh re-vendor src/ and requirements.txt from a flock checkout
22
  Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world
23
  ```
24
 
25
  ## The world
26
 
27
  Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They work
28
- through the world's tools, which flock exposes as `world.*`:
29
 
30
  | tool | what it does |
31
  |---|---|
@@ -42,8 +42,8 @@ the Hub API, and writes its state to `PYBOT_BUCKET` (`world.tar.gz`, restored in
42
  workspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit).
43
 
44
  The world serves `/healthz`, `/manifest`, `/tools/*`, `/metrics` and `/admin/*` on `$PORT`.
45
- `X-World-Token` is the world secret (`FLOCK_WORLD_TOKEN`) or, on `/manifest` and tool calls,
46
- an agent's own token for its `X-Flock-Agent`: HMAC-SHA256(secret, `flock-world-agent\0<agent>`).
47
 
48
  Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in the
49
  sidecar, a second container of the same image with command `python sandbox.py serve` that gets
@@ -69,7 +69,7 @@ git push https://huggingface.co/datasets/<ns>/<name> main # a write token via
69
  World (one per run; give it about 30 s to stop, so the final push completes):
70
 
71
  ```sh
72
- docker run -p 7860:7860 -e HF_TOKEN -e FLOCK_WORLD_TOKEN \
73
  -e PYBOT_REPO=<ns>/<name> -e PYBOT_BUCKET=hf://buckets/<ns>/<bucket>/<run> \
74
  -e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \
75
  <registry>/pybot-world:<tag>
@@ -83,7 +83,7 @@ docker run --name sandbox -e PYBOT_SANDBOX_TOKEN <registry>/pybot-world:<tag> py
83
 
84
  On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set
85
  `PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s in
86
- the URL). On Slurm, leave `PYBOT_SANDBOX_URL` unset and set `FLOCK_WORLD_HOST_FILE` so flock's
87
  controller can follow the world's `host:port`.
88
 
89
  Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give the
@@ -97,11 +97,11 @@ needs only the required ones.
97
  | variable | default | |
98
  |---|---|---|
99
  | `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv |
100
- | `FLOCK_WORLD_TOKEN` | required | the world secret (`X-World-Token`); flock's `resources.world.token_env` holds the same value |
101
  | `PYBOT_REPO` | required | `<ns>/<name>` of the code dataset |
102
  | `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets/<ns>/<bucket>/<prefix>` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) |
103
  | `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here |
104
- | `FLOCK_WORLD_ADMIN_TOKEN` | empty: `/admin` off | admin secret for live knobs and lane pauses |
105
  | `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute |
106
  | `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited |
107
  | `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` |
@@ -130,9 +130,9 @@ needs only the required ones.
130
  | `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) |
131
  | `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) |
132
  | `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `<ws>/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists |
133
- | `PORT`, `PYBOT_WORK`, `FLOCK_WORLD_HOST_FILE`, `WORLD_HOST` | `7860`, `/work`, unset, `$HOSTNAME` | entrypoint only: the port, the state directory, and where to write `host:port` |
134
 
135
- ## How a flock spec uses it
136
 
137
  The world is a resource that the operator starts; every agent runs the task. The spec names the
138
  published task and the world's URL:
@@ -145,7 +145,7 @@ task:
145
  resources:
146
  world:
147
  url: '${WORLD_URL}' # the world's URL (HF Jobs: the world job's public URL)
148
- token_env: PYBOT_WORLD_TOKEN # same value as the world's FLOCK_WORLD_TOKEN; a new one per run
149
  transport: http # backends without mounts (hf-sandbox); `unix` on docker/podman
150
  tools:
151
  - world.*
@@ -161,7 +161,7 @@ pip install --require-hashes --no-deps -r requirements.txt && pip install pytest
161
  python -m pytest # the world's tests (Python 3.12, git, prlimit)
162
  python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
163
  python scripts/check-sidecar.py # the sidecar's checks
164
- ./vendor.sh /path/to/flock # the vendored library matches source-lock.json
165
  ```
166
 
167
  `smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and
 
2
 
3
  A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Face
4
  dataset, changed only through pull requests that other agents review and merge. This repository
5
+ holds both halves that a [legion](https://github.com/huggingface/legion) run needs:
6
 
7
  ```
8
  tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,
 
15
  seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
16
  tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
17
  scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
18
+ src/ legion's World API library, vendored (never edit; vendor.sh)
19
+ requirements.txt the world's Python deps with hashes (from legion's uv.lock; vendor.sh)
20
+ source-lock.json the legion commit and the sha256 of every vendored file
21
+ vendor.sh re-vendor src/ and requirements.txt from a legion checkout
22
  Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world
23
  ```
24
 
25
  ## The world
26
 
27
  Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They work
28
+ through the world's tools, which legion exposes as `world.*`:
29
 
30
  | tool | what it does |
31
  |---|---|
 
42
  workspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit).
43
 
44
  The world serves `/healthz`, `/manifest`, `/tools/*`, `/metrics` and `/admin/*` on `$PORT`.
45
+ `X-World-Token` is the world secret (`LEGION_WORLD_TOKEN`) or, on `/manifest` and tool calls,
46
+ an agent's own token for its `X-Legion-Agent`: HMAC-SHA256(secret, `legion-world-agent\0<agent>`).
47
 
48
  Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in the
49
  sidecar, a second container of the same image with command `python sandbox.py serve` that gets
 
69
  World (one per run; give it about 30 s to stop, so the final push completes):
70
 
71
  ```sh
72
+ docker run -p 7860:7860 -e HF_TOKEN -e LEGION_WORLD_TOKEN \
73
  -e PYBOT_REPO=<ns>/<name> -e PYBOT_BUCKET=hf://buckets/<ns>/<bucket>/<run> \
74
  -e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \
75
  <registry>/pybot-world:<tag>
 
83
 
84
  On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set
85
  `PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s in
86
+ the URL). On Slurm, leave `PYBOT_SANDBOX_URL` unset and set `LEGION_WORLD_HOST_FILE` so legion's
87
  controller can follow the world's `host:port`.
88
 
89
  Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give the
 
97
  | variable | default | |
98
  |---|---|---|
99
  | `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv |
100
+ | `LEGION_WORLD_TOKEN` | required | the world secret (`X-World-Token`); legion's `resources.world.token_env` holds the same value |
101
  | `PYBOT_REPO` | required | `<ns>/<name>` of the code dataset |
102
  | `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets/<ns>/<bucket>/<prefix>` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) |
103
  | `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here |
104
+ | `LEGION_WORLD_ADMIN_TOKEN` | empty: `/admin` off | admin secret for live knobs and lane pauses |
105
  | `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute |
106
  | `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited |
107
  | `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` |
 
130
  | `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) |
131
  | `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) |
132
  | `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `<ws>/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists |
133
+ | `PORT`, `PYBOT_WORK`, `LEGION_WORLD_HOST_FILE`, `WORLD_HOST` | `7860`, `/work`, unset, `$HOSTNAME` | entrypoint only: the port, the state directory, and where to write `host:port` |
134
 
135
+ ## How a legion spec uses it
136
 
137
  The world is a resource that the operator starts; every agent runs the task. The spec names the
138
  published task and the world's URL:
 
145
  resources:
146
  world:
147
  url: '${WORLD_URL}' # the world's URL (HF Jobs: the world job's public URL)
148
+ token_env: PYBOT_WORLD_TOKEN # same value as the world's LEGION_WORLD_TOKEN; a new one per run
149
  transport: http # backends without mounts (hf-sandbox); `unix` on docker/podman
150
  tools:
151
  - world.*
 
161
  python -m pytest # the world's tests (Python 3.12, git, prlimit)
162
  python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
163
  python scripts/check-sidecar.py # the sidecar's checks
164
+ ./vendor.sh /path/to/legion # the vendored library matches source-lock.json
165
  ```
166
 
167
  `smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and
tasks/pybot-agent/environment/Dockerfile CHANGED
@@ -1,4 +1,4 @@
1
  # The agent's own container, the same image as task.toml's docker_image: the full Python 3.12
2
- # image already has git, curl and bash (Harbor's Pi installer and flock's tools need them), and
3
- # root is its default user (flock's tool setup and hf-sandbox need that).
4
  FROM python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735
 
1
  # The agent's own container, the same image as task.toml's docker_image: the full Python 3.12
2
+ # image already has git, curl and bash (Harbor's Pi installer and legion's tools need them), and
3
+ # root is its default user (legion's tool setup and hf-sandbox need that).
4
  FROM python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735
tasks/pybot-agent/instruction.md CHANGED
@@ -7,8 +7,8 @@ code, its pull requests and the message board are shared with the other agents.
7
  `pybot` in your working directory:
8
  `git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`
9
  - Never push to it. Submit, review and merge through the world's tools:
10
- `flock-tool world.tools` lists them with their parameters, and
11
- `flock-tool world.call --json '{"tool": "<name>", "args": {...}}'` calls one as you.
12
  A tool that takes a clone path (open_pr's `path`, default `pybot`, relative to your
13
  working directory) uploads that clone from your container.
14
  - Talk to the other agents on the board with the board tools (`message_board.*`,
 
7
  `pybot` in your working directory:
8
  `git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`
9
  - Never push to it. Submit, review and merge through the world's tools:
10
+ `legion-tool world.tools` lists them with their parameters, and
11
+ `legion-tool world.call --json '{"tool": "<name>", "args": {...}}'` calls one as you.
12
  A tool that takes a clone path (open_pr's `path`, default `pybot`, relative to your
13
  working directory) uploads that clone from your container.
14
  - Talk to the other agents on the board with the board tools (`message_board.*`,
tasks/pybot-agent/task.toml CHANGED
@@ -1,11 +1,11 @@
1
  # One agent of a pybot swarm: one Harbor Trial per agent, each on its own copy of this task. The
2
- # shared state is outside the task: the pybot world (flock's resources.world, tools world.*; its
3
  # code is ../../world) and the board (resources.message_board, tools message_board.*). No
4
  # per-agent reward: tests/test.sh writes 0.
5
  schema_version = "1.4"
6
 
7
  [task]
8
- name = "flock/pybot-agent"
9
  description = "One agent of a swarm that builds a chatbot together: clone $PYBOT_REPO, submit and review through the shared world's tools, talk on the board."
10
 
11
  [metadata]
@@ -14,7 +14,7 @@ world_version = "1.0.0"
14
  world_api = "v1"
15
 
16
  [agent]
17
- timeout_sec = 10800.0 # flock's limits.agent_timeout_seconds overrides it
18
 
19
  [verifier]
20
  timeout_sec = 60.0
 
1
  # One agent of a pybot swarm: one Harbor Trial per agent, each on its own copy of this task. The
2
+ # shared state is outside the task: the pybot world (legion's resources.world, tools world.*; its
3
  # code is ../../world) and the board (resources.message_board, tools message_board.*). No
4
  # per-agent reward: tests/test.sh writes 0.
5
  schema_version = "1.4"
6
 
7
  [task]
8
+ name = "legion/pybot-agent"
9
  description = "One agent of a swarm that builds a chatbot together: clone $PYBOT_REPO, submit and review through the shared world's tools, talk on the board."
10
 
11
  [metadata]
 
14
  world_api = "v1"
15
 
16
  [agent]
17
+ timeout_sec = 10800.0 # legion's limits.agent_timeout_seconds overrides it
18
 
19
  [verifier]
20
  timeout_sec = 60.0
world/Dockerfile CHANGED
@@ -2,7 +2,7 @@
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
- # 3.12+); Python deps are flock's own uv.lock (exact versions + hashes, see vendor.sh).
6
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
7
 
8
  # git: the world's bare repo, fetches and pushes to the Hub. util-linux (unshare) ships in the base.
@@ -13,7 +13,7 @@ RUN apt-get update \
13
  COPY requirements.txt /opt/world/requirements.txt
14
  RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
15
 
16
- # src/: flock's World API library, vendored by vendor.sh (hashes in source-lock.json), never edited.
17
  COPY src/ /opt/world/src/
18
  COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/
19
  COPY seed/ /opt/world/seed/
 
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
+ # 3.12+); Python deps are legion's own uv.lock (exact versions + hashes, see vendor.sh).
6
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
7
 
8
  # git: the world's bare repo, fetches and pushes to the Hub. util-linux (unshare) ships in the base.
 
13
  COPY requirements.txt /opt/world/requirements.txt
14
  RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
15
 
16
+ # src/: legion's World API library, vendored by vendor.sh (hashes in source-lock.json), never edited.
17
  COPY src/ /opt/world/src/
18
  COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/
19
  COPY seed/ /opt/world/seed/
world/entrypoint.sh CHANGED
@@ -8,15 +8,15 @@
8
  #
9
  # Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless.
10
  #
11
- # Required env: HF_TOKEN FLOCK_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET
12
  # (hf://buckets/<ns>/<bucket>/<prefix>, or "off" for no restore and no pushes: smoke tests only).
13
- # Optional: PORT (7860), FLOCK_WORLD_HOST_FILE (writes host:port there: the file flock's controller
14
  # follows), WORLD_HOST ($HOSTNAME), PYBOT_WORK (/work), every PYBOT_* world setting, and
15
  # PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here).
16
  set -euo pipefail
17
  die() { printf '%s pybot-entrypoint: FATAL: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 2; }
18
 
19
- for v in HF_TOKEN FLOCK_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET; do
20
  [ -n "${!v:-}" ] || die "$v is not set"
21
  done
22
  [ -z "${PYBOT_SANDBOX_URL:-}" ] || [ -n "${PYBOT_SANDBOX_TOKEN:-}" ] \
@@ -36,10 +36,10 @@ export PYTHONPATH=$WORLD/src HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp
36
  export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
37
  mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
38
 
39
- if [ -n "${FLOCK_WORLD_HOST_FILE:-}" ]; then # atomic: flock's controller re-reads it every 15 s
40
- { echo "${WORLD_HOST:-$HOSTNAME}:$PORT" > "$FLOCK_WORLD_HOST_FILE.tmp" && mv "$FLOCK_WORLD_HOST_FILE.tmp" "$FLOCK_WORLD_HOST_FILE"; } \
41
- || echo "pybot-entrypoint: cannot write $FLOCK_WORLD_HOST_FILE" >&2
42
  fi
43
 
44
  cd "$WORLD" || die "cannot cd $WORLD"
45
- exec python pybot.py # serve() on 0.0.0.0:$PORT; the token comes from FLOCK_WORLD_TOKEN, never argv
 
8
  #
9
  # Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless.
10
  #
11
+ # Required env: HF_TOKEN LEGION_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET
12
  # (hf://buckets/<ns>/<bucket>/<prefix>, or "off" for no restore and no pushes: smoke tests only).
13
+ # Optional: PORT (7860), LEGION_WORLD_HOST_FILE (writes host:port there: the file legion's controller
14
  # follows), WORLD_HOST ($HOSTNAME), PYBOT_WORK (/work), every PYBOT_* world setting, and
15
  # PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here).
16
  set -euo pipefail
17
  die() { printf '%s pybot-entrypoint: FATAL: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 2; }
18
 
19
+ for v in HF_TOKEN LEGION_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET; do
20
  [ -n "${!v:-}" ] || die "$v is not set"
21
  done
22
  [ -z "${PYBOT_SANDBOX_URL:-}" ] || [ -n "${PYBOT_SANDBOX_TOKEN:-}" ] \
 
36
  export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
37
  mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
38
 
39
+ if [ -n "${LEGION_WORLD_HOST_FILE:-}" ]; then # atomic: legion's controller re-reads it every 15 s
40
+ { echo "${WORLD_HOST:-$HOSTNAME}:$PORT" > "$LEGION_WORLD_HOST_FILE.tmp" && mv "$LEGION_WORLD_HOST_FILE.tmp" "$LEGION_WORLD_HOST_FILE"; } \
41
+ || echo "pybot-entrypoint: cannot write $LEGION_WORLD_HOST_FILE" >&2
42
  fi
43
 
44
  cd "$WORLD" || die "cannot cd $WORLD"
45
+ exec python pybot.py # serve() on 0.0.0.0:$PORT; the token comes from LEGION_WORLD_TOKEN, never argv
world/pybot.py CHANGED
@@ -27,11 +27,11 @@ import snapshot
27
  from repository import Hub, Repository
28
  from sandbox import run, run_tests
29
 
30
- from flock.isolation import protect_supervisor
31
- from flock.world import Agent, ToolError, World, tool
32
- from flock.world.lanes import Lane, LaneBusy, Lanes
33
- from flock.world.store import Store
34
- from flock.world.workspace import apply_patch, unpack
35
 
36
  HERE = Path(__file__).resolve().parent
37
  UPLOAD = contextvars.ContextVar("workspace", default=None)
@@ -72,7 +72,7 @@ TRANSIENT_CODES = ("git_error", "hub_error")
72
  COMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub post
73
  # get_pr: diff bytes returned (cut at a line end, with truncated: true beyond this).
74
  MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))
75
- # State rows in state.db (flock.world.store): these top-level dicts get one row per entry;
76
  # every other top-level value (pr_opens, pr_merges) is one row of kind "_".
77
  KINDS = ("prs", "requests", "drafts", "inbox")
78
  COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this
@@ -155,9 +155,9 @@ class PybotWorld(World):
155
  def manifest(self) -> dict:
156
  m = super().manifest()
157
  for t in m["tools"]:
158
- t["x-flock-timeout_s"] = 330 # a 300 s run_bot conversation plus the upload
159
  if t["name"] in self.WORKSPACE:
160
- t["x-flock-workspace"] = self.WORKSPACE[t["name"]]
161
  return m
162
 
163
  def __init__(self, ws=None, repository=None):
@@ -193,7 +193,7 @@ class PybotWorld(World):
193
  # Saving (see _save): every change marks its rows dirty (_dirty) and bumps save_gen;
194
  # the saver writes the dirty rows to state.db and, while save.legacy_json is on, the
195
  # whole state to prs.json (written_gen is the generation in prs.json).
196
- self.save_interval = self.knob( # admin knobs (flock.world.admin): the env sets the default
197
  "save.interval_s", float, float(os.environ.get("PYBOT_SAVE_INTERVAL_S", SAVE_INTERVAL)),
198
  min=0, doc="Seconds between state saves (0: write on every change).",
199
  on_change=lambda v: setattr(self, "save_interval", v))
@@ -270,7 +270,7 @@ class PybotWorld(World):
270
  # agents at once): "push" for creating, pushing, readying and closing PRs, "merge" for
271
  # merges (never queued behind pushes, whose wait would let main or the PR move under
272
  # its checks), "comment" for review comments, posted from the outbox. Each lane has a
273
- # breaker (flock.world.lanes); the pause covers push and merge. Lock order: see self.lock.
274
  # Admin pauses (POST /admin/pause) apply per lane; the pause flag pauses push and merge.
275
  self.lanes = Lanes({"push": Lane(), "merge": Lane(), "comment": Lane()}, dir=self.ws,
276
  paused=lambda lane: self.paused(lane) or (
@@ -521,7 +521,7 @@ class PybotWorld(World):
521
  setattr(self, name, getattr(self, name) + n)
522
 
523
  def metrics(self):
524
- """World numbers for GET /metrics (flock.world.server)."""
525
  now = time.time()
526
  with self.lock:
527
  budget = self._budget()
@@ -1167,7 +1167,7 @@ class PybotWorld(World):
1167
  raise ToolError("description must not be empty")
1168
  snapshot = UPLOAD.get()
1169
  if not isinstance(snapshot, dict):
1170
- raise ToolError("submit a local clone through flock-tool; the worker uploads it")
1171
  # Scope new_modules: a PR that adds no module is outside the budget (git runs unlocked).
1172
  exempt = (self.budget_scope == "new_modules"
1173
  and not self._adds_module(snapshot, snapshot.get("base_sha", "")))
@@ -1307,7 +1307,7 @@ class PybotWorld(World):
1307
  self.last_create = max(self.last_create, time.monotonic())
1308
  sha, main = self._land(agent, snapshot, base, title, branch_ref, pr, sha, main,
1309
  started, slot)
1310
- self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/flock/pr/{pr}/{sha}", sha))
1311
  return pr, sha, main, old_head
1312
  raise ToolError("main kept moving while opening the PR; open it again", "busy")
1313
 
@@ -1687,7 +1687,7 @@ class PybotWorld(World):
1687
  with _timed(steps, "push"):
1688
  self._lease_push(agent, pr, new, head, time.monotonic())
1689
  with _timed(steps, "update_ref"): # waits for refs_lock
1690
- self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/flock/pr/{pr}/{new}", new))
1691
  with self.lock: # reviews stay: they match the rebased head by patch-id
1692
  rec.update(base_sha=main, head_sha=new)
1693
  self._dirty("prs", pr)
@@ -2207,11 +2207,11 @@ class PybotWorld(World):
2207
 
2208
 
2209
  if __name__ == "__main__":
2210
- from flock.world.server import serve
2211
  # Nothing else configures logging in the world process: this handler sends its warnings and
2212
  # INFO lines (merge_pr timings) to stderr.
2213
  logging.getLogger("pybot").addHandler(logging.StreamHandler())
2214
  logging.getLogger("pybot").setLevel(logging.INFO)
2215
- # FLOCK_WORLD_PORT: the free port flock picked (a local run, a Slurm world job)
2216
  serve("pybot:PybotWorld", host="0.0.0.0",
2217
- port=int(os.environ.get("FLOCK_WORLD_PORT") or os.environ.get("PORT") or 7860))
 
27
  from repository import Hub, Repository
28
  from sandbox import run, run_tests
29
 
30
+ from legion.isolation import protect_supervisor
31
+ from legion.world import Agent, ToolError, World, tool
32
+ from legion.world.lanes import Lane, LaneBusy, Lanes
33
+ from legion.world.store import Store
34
+ from legion.world.workspace import apply_patch, unpack
35
 
36
  HERE = Path(__file__).resolve().parent
37
  UPLOAD = contextvars.ContextVar("workspace", default=None)
 
72
  COMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub post
73
  # get_pr: diff bytes returned (cut at a line end, with truncated: true beyond this).
74
  MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))
75
+ # State rows in state.db (legion.world.store): these top-level dicts get one row per entry;
76
  # every other top-level value (pr_opens, pr_merges) is one row of kind "_".
77
  KINDS = ("prs", "requests", "drafts", "inbox")
78
  COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this
 
155
  def manifest(self) -> dict:
156
  m = super().manifest()
157
  for t in m["tools"]:
158
+ t["x-legion-timeout_s"] = 330 # a 300 s run_bot conversation plus the upload
159
  if t["name"] in self.WORKSPACE:
160
+ t["x-legion-workspace"] = self.WORKSPACE[t["name"]]
161
  return m
162
 
163
  def __init__(self, ws=None, repository=None):
 
193
  # Saving (see _save): every change marks its rows dirty (_dirty) and bumps save_gen;
194
  # the saver writes the dirty rows to state.db and, while save.legacy_json is on, the
195
  # whole state to prs.json (written_gen is the generation in prs.json).
196
+ self.save_interval = self.knob( # admin knobs (legion.world.admin): the env sets the default
197
  "save.interval_s", float, float(os.environ.get("PYBOT_SAVE_INTERVAL_S", SAVE_INTERVAL)),
198
  min=0, doc="Seconds between state saves (0: write on every change).",
199
  on_change=lambda v: setattr(self, "save_interval", v))
 
270
  # agents at once): "push" for creating, pushing, readying and closing PRs, "merge" for
271
  # merges (never queued behind pushes, whose wait would let main or the PR move under
272
  # its checks), "comment" for review comments, posted from the outbox. Each lane has a
273
+ # breaker (legion.world.lanes); the pause covers push and merge. Lock order: see self.lock.
274
  # Admin pauses (POST /admin/pause) apply per lane; the pause flag pauses push and merge.
275
  self.lanes = Lanes({"push": Lane(), "merge": Lane(), "comment": Lane()}, dir=self.ws,
276
  paused=lambda lane: self.paused(lane) or (
 
521
  setattr(self, name, getattr(self, name) + n)
522
 
523
  def metrics(self):
524
+ """World numbers for GET /metrics (legion.world.server)."""
525
  now = time.time()
526
  with self.lock:
527
  budget = self._budget()
 
1167
  raise ToolError("description must not be empty")
1168
  snapshot = UPLOAD.get()
1169
  if not isinstance(snapshot, dict):
1170
+ raise ToolError("submit a local clone through legion-tool; the worker uploads it")
1171
  # Scope new_modules: a PR that adds no module is outside the budget (git runs unlocked).
1172
  exempt = (self.budget_scope == "new_modules"
1173
  and not self._adds_module(snapshot, snapshot.get("base_sha", "")))
 
1307
  self.last_create = max(self.last_create, time.monotonic())
1308
  sha, main = self._land(agent, snapshot, base, title, branch_ref, pr, sha, main,
1309
  started, slot)
1310
+ self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/legion/pr/{pr}/{sha}", sha))
1311
  return pr, sha, main, old_head
1312
  raise ToolError("main kept moving while opening the PR; open it again", "busy")
1313
 
 
1687
  with _timed(steps, "push"):
1688
  self._lease_push(agent, pr, new, head, time.monotonic())
1689
  with _timed(steps, "update_ref"): # waits for refs_lock
1690
+ self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/legion/pr/{pr}/{new}", new))
1691
  with self.lock: # reviews stay: they match the rebased head by patch-id
1692
  rec.update(base_sha=main, head_sha=new)
1693
  self._dirty("prs", pr)
 
2207
 
2208
 
2209
  if __name__ == "__main__":
2210
+ from legion.world.server import serve
2211
  # Nothing else configures logging in the world process: this handler sends its warnings and
2212
  # INFO lines (merge_pr timings) to stderr.
2213
  logging.getLogger("pybot").addHandler(logging.StreamHandler())
2214
  logging.getLogger("pybot").setLevel(logging.INFO)
2215
+ # LEGION_WORLD_PORT: the free port legion picked (a local run, a Slurm world job)
2216
  serve("pybot:PybotWorld", host="0.0.0.0",
2217
+ port=int(os.environ.get("LEGION_WORLD_PORT") or os.environ.get("PORT") or 7860))
world/repository.py CHANGED
@@ -14,8 +14,8 @@ from urllib.parse import urlsplit
14
  from huggingface_hub import HfApi
15
  from huggingface_hub.errors import HfHubHTTPError
16
 
17
- from flock.world import ToolError
18
- from flock.world.server import redact
19
 
20
  log = logging.getLogger(__name__)
21
  # Loose objects packed per maintenance pass at most: every pass finishes; a backlog drains over passes.
@@ -318,7 +318,7 @@ class Repository:
318
  def commit(self, tree, parent, author, title, onto=None, union=False):
319
  """Commit tree on parent; with onto != parent, replay that commit onto it (with union,
320
  PYBOT_UNION_PATHS merge as merge=union: only where a changed diff is refused)."""
321
- who = ("-c", f"user.name={author}", "-c", f"user.email={author}@flock.invalid")
322
  self.git("add", "-A", at=tree)
323
  self.git(*who, "commit", "--allow-empty", "-m", title, at=tree)
324
  sha = self.git("rev-parse", "HEAD", at=tree)
 
14
  from huggingface_hub import HfApi
15
  from huggingface_hub.errors import HfHubHTTPError
16
 
17
+ from legion.world import ToolError
18
+ from legion.world.server import redact
19
 
20
  log = logging.getLogger(__name__)
21
  # Loose objects packed per maintenance pass at most: every pass finishes; a backlog drains over passes.
 
318
  def commit(self, tree, parent, author, title, onto=None, union=False):
319
  """Commit tree on parent; with onto != parent, replay that commit onto it (with union,
320
  PYBOT_UNION_PATHS merge as merge=union: only where a changed diff is refused)."""
321
+ who = ("-c", f"user.name={author}", "-c", f"user.email={author}@legion.invalid")
322
  self.git("add", "-A", at=tree)
323
  self.git(*who, "commit", "--allow-empty", "-m", title, at=tree)
324
  sha = self.git("rev-parse", "HEAD", at=tree)
world/requirements.txt CHANGED
@@ -36,11 +36,11 @@ colorama==0.4.6 ; sys_platform == 'win32' \
36
  exceptiongroup==1.3.1 \
37
  --hash=sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219 \
38
  --hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598
39
- # via flock
40
  fastapi==0.143.1 \
41
  --hash=sha256:4cafaab64df8534758bf0fce61947f5e27e6cd512798ccbbaad5425086c3b664 \
42
  --hash=sha256:687beb445804e4c4dbe2a76fd83c25e9b973ac48c267defb86f791e099baecc4
43
- # via flock
44
  filelock==3.32.7 \
45
  --hash=sha256:37b8a3d9811b0f9aef7e5ec5c71bb320de52df51e6ca9bcd6f5ad81187660da7 \
46
  --hash=sha256:65ff0d0190ea42038b32bda4b77834fb05be2cad4c5b9b01aa4dfb3614536e52
@@ -163,12 +163,12 @@ httpx==0.28.1 \
163
  --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \
164
  --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
165
  # via
166
- # flock
167
  # huggingface-hub
 
168
  huggingface-hub==1.33.0 \
169
  --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \
170
  --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e
171
- # via flock
172
  idna==3.20 \
173
  --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
174
  --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
@@ -178,7 +178,7 @@ idna==3.20 \
178
  jinja2==3.1.6 \
179
  --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \
180
  --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
181
- # via flock
182
  markdown-it-py==4.2.0 \
183
  --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
184
  --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
@@ -303,14 +303,14 @@ packaging==26.3 \
303
  --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
304
  --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
305
  # via
306
- # flock
307
  # huggingface-hub
 
308
  pydantic==2.14.1 \
309
  --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \
310
  --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26
311
  # via
312
  # fastapi
313
- # flock
314
  pydantic-core==2.50.1 \
315
  --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \
316
  --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \
@@ -458,8 +458,8 @@ pyyaml==6.0.3 \
458
  --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \
459
  --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0
460
  # via
461
- # flock
462
  # huggingface-hub
 
463
  # uvicorn
464
  rich==15.0.0 \
465
  --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
@@ -473,6 +473,64 @@ starlette==1.8.0 \
473
  --hash=sha256:1565dc0b35d5737a271ed1e0e04e949f4e81198799f216d2667b0a0fb9cf9522 \
474
  --hash=sha256:dfdd6b29c26483288088d990eee59631dedadd66ce20d203402a7ca8e3c4656f
475
  # via fastapi
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
  tqdm==4.70.1 \
477
  --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \
478
  --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4
@@ -480,7 +538,7 @@ tqdm==4.70.1 \
480
  typer==0.27.3 \
481
  --hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \
482
  --hash=sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff
483
- # via flock
484
  typing-extensions==4.16.0 \
485
  --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
486
  --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
@@ -503,7 +561,7 @@ typing-inspection==0.4.4 \
503
  uvicorn==0.54.0 \
504
  --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \
505
  --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620
506
- # via flock
507
  uvloop==0.23.0 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \
508
  --hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \
509
  --hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \
 
36
  exceptiongroup==1.3.1 \
37
  --hash=sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219 \
38
  --hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598
39
+ # via legion
40
  fastapi==0.143.1 \
41
  --hash=sha256:4cafaab64df8534758bf0fce61947f5e27e6cd512798ccbbaad5425086c3b664 \
42
  --hash=sha256:687beb445804e4c4dbe2a76fd83c25e9b973ac48c267defb86f791e099baecc4
43
+ # via legion
44
  filelock==3.32.7 \
45
  --hash=sha256:37b8a3d9811b0f9aef7e5ec5c71bb320de52df51e6ca9bcd6f5ad81187660da7 \
46
  --hash=sha256:65ff0d0190ea42038b32bda4b77834fb05be2cad4c5b9b01aa4dfb3614536e52
 
163
  --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \
164
  --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
165
  # via
 
166
  # huggingface-hub
167
+ # legion
168
  huggingface-hub==1.33.0 \
169
  --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \
170
  --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e
171
+ # via legion
172
  idna==3.20 \
173
  --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
174
  --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
 
178
  jinja2==3.1.6 \
179
  --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \
180
  --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
181
+ # via legion
182
  markdown-it-py==4.2.0 \
183
  --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
184
  --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
 
303
  --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
304
  --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
305
  # via
 
306
  # huggingface-hub
307
+ # legion
308
  pydantic==2.14.1 \
309
  --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \
310
  --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26
311
  # via
312
  # fastapi
313
+ # legion
314
  pydantic-core==2.50.1 \
315
  --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \
316
  --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \
 
458
  --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \
459
  --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0
460
  # via
 
461
  # huggingface-hub
462
+ # legion
463
  # uvicorn
464
  rich==15.0.0 \
465
  --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
 
473
  --hash=sha256:1565dc0b35d5737a271ed1e0e04e949f4e81198799f216d2667b0a0fb9cf9522 \
474
  --hash=sha256:dfdd6b29c26483288088d990eee59631dedadd66ce20d203402a7ca8e3c4656f
475
  # via fastapi
476
+ tomli==2.5.0 \
477
+ --hash=sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea \
478
+ --hash=sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd \
479
+ --hash=sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0 \
480
+ --hash=sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391 \
481
+ --hash=sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df \
482
+ --hash=sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9 \
483
+ --hash=sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066 \
484
+ --hash=sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f \
485
+ --hash=sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57 \
486
+ --hash=sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6 \
487
+ --hash=sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b \
488
+ --hash=sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3 \
489
+ --hash=sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043 \
490
+ --hash=sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01 \
491
+ --hash=sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646 \
492
+ --hash=sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859 \
493
+ --hash=sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b \
494
+ --hash=sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc \
495
+ --hash=sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5 \
496
+ --hash=sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0 \
497
+ --hash=sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb \
498
+ --hash=sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84 \
499
+ --hash=sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6 \
500
+ --hash=sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b \
501
+ --hash=sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b \
502
+ --hash=sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52 \
503
+ --hash=sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd \
504
+ --hash=sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75 \
505
+ --hash=sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142 \
506
+ --hash=sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03 \
507
+ --hash=sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea \
508
+ --hash=sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374 \
509
+ --hash=sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3 \
510
+ --hash=sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276 \
511
+ --hash=sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b \
512
+ --hash=sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc \
513
+ --hash=sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68 \
514
+ --hash=sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a \
515
+ --hash=sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f \
516
+ --hash=sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b \
517
+ --hash=sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7 \
518
+ --hash=sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0 \
519
+ --hash=sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb \
520
+ --hash=sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7 \
521
+ --hash=sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7 \
522
+ --hash=sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105 \
523
+ --hash=sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5 \
524
+ --hash=sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d \
525
+ --hash=sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2 \
526
+ --hash=sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4 \
527
+ --hash=sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7 \
528
+ --hash=sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1 \
529
+ --hash=sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571 \
530
+ --hash=sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a \
531
+ --hash=sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442 \
532
+ --hash=sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc
533
+ # via legion
534
  tqdm==4.70.1 \
535
  --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \
536
  --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4
 
538
  typer==0.27.3 \
539
  --hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \
540
  --hash=sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff
541
+ # via legion
542
  typing-extensions==4.16.0 \
543
  --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
544
  --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
 
561
  uvicorn==0.54.0 \
562
  --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \
563
  --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620
564
+ # via legion
565
  uvloop==0.23.0 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \
566
  --hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \
567
  --hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \
world/sandbox.py CHANGED
@@ -18,8 +18,8 @@ import urllib.request
18
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
  from pathlib import Path
20
 
21
- from flock.isolation import command as isolate_command
22
- from flock.world import ToolError
23
 
24
  # The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree
25
  # for the shared tests: main grows by about one file per merge, so the cap allows a long run.
@@ -228,6 +228,6 @@ class _Handler(BaseHTTPRequestHandler):
228
  if __name__ == "__main__" and sys.argv[1:] == ["serve"]:
229
  if not os.environ.get("PYBOT_SANDBOX_TOKEN"):
230
  sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused
231
- from flock.isolation import protect_supervisor
232
  protect_supervisor() # a bot under this uid cannot read this process's env or memory
233
  ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever()
 
18
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
  from pathlib import Path
20
 
21
+ from legion.isolation import command as isolate_command
22
+ from legion.world import ToolError
23
 
24
  # The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree
25
  # for the shared tests: main grows by about one file per merge, so the cap allows a long run.
 
228
  if __name__ == "__main__" and sys.argv[1:] == ["serve"]:
229
  if not os.environ.get("PYBOT_SANDBOX_TOKEN"):
230
  sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused
231
+ from legion.isolation import protect_supervisor
232
  protect_supervisor() # a bot under this uid cannot read this process's env or memory
233
  ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever()
world/scripts/check-sidecar.py CHANGED
@@ -54,7 +54,7 @@ def member(name, size=4, kind=tarfile.REGTYPE, link=""):
54
 
55
  def main():
56
  import sandbox
57
- from flock.world import ToolError
58
 
59
  with socket.socket() as s:
60
  s.bind(("127.0.0.1", 0))
 
54
 
55
  def main():
56
  import sandbox
57
+ from legion.world import ToolError
58
 
59
  with socket.socket() as s:
60
  s.bind(("127.0.0.1", 0))
world/scripts/smoke-local.py CHANGED
@@ -50,7 +50,7 @@ class LocalHub: # tests/test_pybot.py's fake: PRs are refs/pr/N in the bare rem
50
  def call(port, method, path, body=None, token=TOKEN, agent="smoke"):
51
  req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method,
52
  data=None if body is None else json.dumps(body).encode(),
53
- headers={"Content-Type": "application/json", "X-Flock-Agent": agent,
54
  **({"X-World-Token": token} if token else {})})
55
  try:
56
  with urllib.request.urlopen(req, timeout=60) as r:
@@ -88,7 +88,7 @@ def main(sidecar=False):
88
  from pybot import PybotWorld
89
  from repository import Repository
90
 
91
- from flock.world.server import create_app
92
 
93
  tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-"))
94
  os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="") # the fake hub ignores both
@@ -96,7 +96,7 @@ def main(sidecar=False):
96
  subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True)
97
  git(seed, "init", "-q", "-b", "main")
98
  git(seed, "add", ".")
99
- git(seed, "-c", "user.name=seed", "-c", "user.email=seed@flock.invalid", "commit", "-qm", "seed")
100
  remote = tmp / "remote.git"
101
  git(tmp, "clone", "-q", "--bare", str(seed), str(remote))
102
  repo = Repository(tmp / "ws" / "repo.git", str(remote))
@@ -122,7 +122,7 @@ def main(sidecar=False):
122
 
123
  assert call(port, "GET", "/manifest", token="wrong")[0] == 401
124
  print("ok GET /manifest with a wrong X-World-Token: 401")
125
- from flock.world.protocol import agent_token
126
  own = agent_token(TOKEN, "smoke")
127
  assert call(port, "GET", "/manifest", token=own)[0] == 200
128
  assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401
 
50
  def call(port, method, path, body=None, token=TOKEN, agent="smoke"):
51
  req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method,
52
  data=None if body is None else json.dumps(body).encode(),
53
+ headers={"Content-Type": "application/json", "X-Legion-Agent": agent,
54
  **({"X-World-Token": token} if token else {})})
55
  try:
56
  with urllib.request.urlopen(req, timeout=60) as r:
 
88
  from pybot import PybotWorld
89
  from repository import Repository
90
 
91
+ from legion.world.server import create_app
92
 
93
  tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-"))
94
  os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="") # the fake hub ignores both
 
96
  subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True)
97
  git(seed, "init", "-q", "-b", "main")
98
  git(seed, "add", ".")
99
+ git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-qm", "seed")
100
  remote = tmp / "remote.git"
101
  git(tmp, "clone", "-q", "--bare", str(seed), str(remote))
102
  repo = Repository(tmp / "ws" / "repo.git", str(remote))
 
122
 
123
  assert call(port, "GET", "/manifest", token="wrong")[0] == 401
124
  print("ok GET /manifest with a wrong X-World-Token: 401")
125
+ from legion.world.protocol import agent_token
126
  own = agent_token(TOKEN, "smoke")
127
  assert call(port, "GET", "/manifest", token=own)[0] == 200
128
  assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401
world/seed/CONTRIBUTING.md CHANGED
@@ -19,7 +19,7 @@
19
  under `bot/modules/` and the shared parts next to it (README.md, "Interface" and
20
  "Architecture"), with tests under `tests/`.
21
  5. Run `python -m unittest discover -s tests` and talk to the whole bot:
22
- `flock-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.
23
  6. Compare with main, blind, before you open the PR:
24
 
25
  ```sh
@@ -37,7 +37,7 @@
37
 
38
  ## Open a PR
39
 
40
- 7. Submit with `flock-tool open_pr --json '{"path":"pybot","branch":"your-topic",
41
  "title":"Your change","description":"..."}'`. The description says what changed and why,
42
  and gives the comparison: the seed, the score line, the "turns answered" line, and one
43
  example it improves. At most two open PRs per agent.
@@ -78,6 +78,6 @@
78
  it shows losses), revert it: `git revert` the merge locally and open a PR. Reverts are
79
  never limited. Then fix the change properly; don't pile a guard on top of it.
80
 
81
- All world and board tools use `flock-tool <name> --json '<arguments>'`; `flock-tool --list`
82
  shows their parameters. There are no DMs: ask in your lane channel's thread and @mention the
83
  person. Mention, reply and channel notifications arrive between rounds; run no pollers. Keep status and test logs in your notes. Never commit or post credentials.
 
19
  under `bot/modules/` and the shared parts next to it (README.md, "Interface" and
20
  "Architecture"), with tests under `tests/`.
21
  5. Run `python -m unittest discover -s tests` and talk to the whole bot:
22
+ `legion-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.
23
  6. Compare with main, blind, before you open the PR:
24
 
25
  ```sh
 
37
 
38
  ## Open a PR
39
 
40
+ 7. Submit with `legion-tool open_pr --json '{"path":"pybot","branch":"your-topic",
41
  "title":"Your change","description":"..."}'`. The description says what changed and why,
42
  and gives the comparison: the seed, the score line, the "turns answered" line, and one
43
  example it improves. At most two open PRs per agent.
 
78
  it shows losses), revert it: `git revert` the merge locally and open a PR. Reverts are
79
  never limited. Then fix the change properly; don't pile a guard on top of it.
80
 
81
+ All world and board tools use `legion-tool <name> --json '<arguments>'`; `legion-tool --list`
82
  shows their parameters. There are no DMs: ask in your lane channel's thread and @mention the
83
  person. Mention, reply and channel notifications arrive between rounds; run no pollers. Keep status and test logs in your notes. Never commit or post credentials.
world/snapshot.py CHANGED
@@ -9,8 +9,8 @@ import tarfile
9
  import tempfile
10
  from pathlib import Path, PurePosixPath
11
 
12
- from flock.worker.sync import HubBucketStore
13
- from flock.world.store import backup_to
14
 
15
  # state.db is copied with the online backup API (consistent while the world writes it).
16
  FILES = ("repo.bundle", "state.db", "prs.json", "prs.jsonl", "eval-queue.jsonl", "knobs.json",
 
9
  import tempfile
10
  from pathlib import Path, PurePosixPath
11
 
12
+ from legion.worker.sync import HubBucketStore
13
+ from legion.world.store import backup_to
14
 
15
  # state.db is copied with the online backup API (consistent while the world writes it).
16
  FILES = ("repo.bundle", "state.db", "prs.json", "prs.jsonl", "eval-queue.jsonl", "knobs.json",
world/source-lock.json CHANGED
@@ -1,22 +1,23 @@
1
  {
2
- "flock_repo": "https://github.com/huggingface/flock",
3
- "flock_commit": "aaab415cbf59efeec3294e1d014c9ac69db5e390",
4
  "files": {
5
- "src/flock/__init__.py": "f26caf93ebbf4da0e48361700fbd1b03ab8e18cf7aa7fb810d023002937b121a",
6
- "src/flock/isolation.py": "35a563e532802a12ca44f84e22652d740139ea6dc92061ccfba9d59ede29f560",
7
- "src/flock/models.py": "43c1101112c689f71475400fe61ee6a6c8c6fd15388c65b656cd3308082702c9",
8
- "src/flock/registry.py": "fe27642c50f25a7a4c9b20e5006b4117d755b2a9ae474a8726a0d9861a5445e8",
9
- "src/flock/tools/__init__.py": "9bb7c72a7a563a9086a12f52399bbca74250c498c09b428d6c7b56cb83b406ee",
10
- "src/flock/tools/loader.py": "a383c95a8910f322373511425ac06a0f152a818e57ab9eefa3eceda934bcd826",
11
- "src/flock/worker/__init__.py": "c4afc77bc9a814ffb811300094c36e0706c2a6a025703241c69688e3c5d2ff83",
12
- "src/flock/worker/sync.py": "90e10862f5b772017460a752c8afb6340c747a6d7a63dbab91c295afe1a49b96",
13
- "src/flock/world/__init__.py": "d9cd12d59e039b7b91c88e978a2b7dcaa657d9f9bb7524835b947348d7829449",
14
- "src/flock/world/admin.py": "93b04d68199239c5c80c981d5e2ae320fbff28da26da6b1cb3cd5eb0765d1562",
15
- "src/flock/world/lanes.py": "f43ff7bfc91c17c48fa73e99fa6e172323b7b158524422b7c3b2d4254680bc47",
16
- "src/flock/world/protocol.py": "94250d3b2c6b8dae8ac61de339044694ee3a72aec832c2df369c11b1b79363a9",
17
- "src/flock/world/server.py": "03665b24ae28ce8e9be951aeca8546721cea9771fdd13ecec87f77b43ae3a848",
18
- "src/flock/world/store.py": "1984943b9c4a8ca05a717f8dd49aa06b04930eae8d96babe60c2e2ed4f6f7d51",
19
- "src/flock/world/workspace.py": "c861b98c3f2603cfdc478f92547e7b8b83faaf5f1e292732c86cc51b7b26ee1a"
 
20
  },
21
- "requirements.txt": "bcc4c96105fcc7eb7b311e32a341d69c669addcb1482d6d7bf59b33043a20bf1"
22
  }
 
1
  {
2
+ "legion_repo": "https://github.com/huggingface/legion",
3
+ "legion_commit": "803873b114d5e04a3a01fea5e2e9084a03596fab",
4
  "files": {
5
+ "src/legion/__init__.py": "2ca25e640556c716182ea3432836ca462f6ac4f9f048fee06532a6229217549c",
6
+ "src/legion/buckets.py": "7cd3362e02cc56bf09db3b434413548c31c407302177def5162d9854a1d70a7f",
7
+ "src/legion/isolation.py": "d2aee168504b93602d3fc4a50898539049a4cddcdec9f18364c664acd436d66f",
8
+ "src/legion/models.py": "11c3fed632ab8d567fd202d487caf6e3eeb4ef2923adc465205bc3e25527f4b1",
9
+ "src/legion/registry.py": "68257009cc7d026bb6ee06e24310b59b427f4f1a07e591ec2d8058e964edc270",
10
+ "src/legion/tools/__init__.py": "c0daaebb255a07ea8032d8e00f9752075cabfd33382afdb8d4ddeede7a960dfc",
11
+ "src/legion/tools/loader.py": "93f23ceb747fbb6c767f8a46cf2b1b562cafdf6e518290862106d547eb47a0d5",
12
+ "src/legion/worker/__init__.py": "c4afc77bc9a814ffb811300094c36e0706c2a6a025703241c69688e3c5d2ff83",
13
+ "src/legion/worker/sync.py": "bc2f6dab07d066a103f719174455b37bc784b8cd80794489da2038213fcbc4fa",
14
+ "src/legion/world/__init__.py": "3fafd99d4e514f00ebf9b9f5ca2bfadd0fe30f83358bb7ef0bb33c601d5cb14f",
15
+ "src/legion/world/admin.py": "aa83dfc00544cc368512896061d3953f1b52a77135639af2b32804eec7f4cda0",
16
+ "src/legion/world/lanes.py": "1bd5ba820732c3c57299b51d91a78199d860cea8c0940e9efe0f24d8e90f26ad",
17
+ "src/legion/world/protocol.py": "edde06d66578c82e08ace3bcdf113ac9217937a693c0449c7d727efdef9eb9ad",
18
+ "src/legion/world/server.py": "896fac8edb9918ab2ccbfb6947d50ad4cca9ad4ce9990bde365a89c0df0a1afd",
19
+ "src/legion/world/store.py": "3b4929798dc7710a94fa617d399a275577121457aade45784388e34d6df9a8f8",
20
+ "src/legion/world/workspace.py": "a20903edc437c127d8752e1b9c0bac48a64e5caade51e9c5dc7f913d5d09a1f5"
21
  },
22
+ "requirements.txt": "03b2bc4359a6929b8a0530546837002c9d5d9da811167257d0cf01f3d801128d"
23
  }
world/src/flock/__init__.py DELETED
@@ -1,3 +0,0 @@
1
- """flock: host coding-harness agent swarms on Hugging Face Jobs."""
2
-
3
- __version__ = "0.0.1"
 
 
 
 
world/src/legion/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """legion: host coding-harness agent swarms on Hugging Face Jobs."""
2
+
3
+ __version__ = "0.0.1"
world/src/legion/buckets.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spec bucket IDs, resolved by the launcher; URLs may add legion's internal prefixes."""
2
+
3
+ import re
4
+ from typing import Annotated, Any
5
+
6
+ from pydantic import AfterValidator
7
+
8
+
9
+ def validate_bucket_id(value: str) -> str:
10
+ """An optional `[namespace/]name`, without a URL or a path inside the bucket."""
11
+ parts = value.split("/")
12
+ if value and (len(parts) > 2 or any(
13
+ not re.fullmatch(r"[\w.-]+", p, flags=re.ASCII) or p in (".", "..")
14
+ for p in parts)):
15
+ raise ValueError("bucket_id must be [namespace/]name, without hf://buckets/ or a prefix")
16
+ return value
17
+
18
+
19
+ BucketId = Annotated[str, AfterValidator(validate_bucket_id)]
20
+
21
+
22
+ def resolve_bucket_id(bucket_id: str, namespace: str, api: Any) -> str:
23
+ """Qualify a bare name using the explicit namespace, else HF_TOKEN's account."""
24
+ validate_bucket_id(bucket_id)
25
+ if not bucket_id or "/" in bucket_id:
26
+ return bucket_id
27
+ return f"{namespace or api.whoami()['name']}/{bucket_id}"
28
+
29
+
30
+ def bucket_url(bucket_id: str) -> str:
31
+ """A qualified spec ID as a Hub URL, ready for legion's checkpoint/agent prefixes."""
32
+ validate_bucket_id(bucket_id)
33
+ if "/" not in bucket_id:
34
+ raise ValueError("bucket_id must be qualified by legion launch before use")
35
+ return f"hf://buckets/{bucket_id}"
world/src/{flock → legion}/isolation.py RENAMED
@@ -29,7 +29,7 @@ _LOCKED = ((os.ST_RDONLY, MS_RDONLY), (os.ST_NOSUID, MS_NOSUID), (os.ST_NODEV, M
29
  DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random")
30
  # The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points
31
  # and stray writes outside the bound dirs land there; the cap bounds each sandbox.
32
- TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "FLOCK_ISOLATION_TMPFS_SIZE", "256m"
33
  SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir
34
  _SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE)
35
  MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442
@@ -56,7 +56,7 @@ def _step(step: str, path) -> Iterator[None]:
56
 
57
 
58
  def enabled() -> bool:
59
- return os.environ.get("FLOCK_PROCESS_ISOLATION") == "1"
60
 
61
 
62
  def _libc():
@@ -70,7 +70,7 @@ def protect_supervisor() -> None:
70
 
71
 
72
  def tmpfs_size(env=os.environ) -> str:
73
- """The size cap of a sandbox's tmpfs root: $FLOCK_ISOLATION_TMPFS_SIZE (bytes, or with a
74
  k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default."""
75
  value = (env.get(TMPFS_SIZE_ENV) or "").strip()
76
  if _SIZE.fullmatch(value):
@@ -87,7 +87,7 @@ def runtime_paths(command: list[str], *, python_only=False) -> list[str]:
87
  paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf",
88
  "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"]
89
  if not python_only:
90
- paths.append(str(Path(__file__).resolve().parents[2])) # editable flock install
91
  for binary in (command[0], "node"):
92
  found = shutil.which(binary)
93
  if not found:
@@ -183,7 +183,7 @@ def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(),
183
  private_dirs=private_dirs, tmp=tmp)}
184
  # Slurm sends USR1 to every process on reclaim. Only worker/world supervisors
185
  # handle it; an unshare wrapper must survive long enough for their bounded drain.
186
- return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "flock-isolate",
187
  unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL",
188
  "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--",
189
  sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
 
29
  DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random")
30
  # The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points
31
  # and stray writes outside the bound dirs land there; the cap bounds each sandbox.
32
+ TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "LEGION_ISOLATION_TMPFS_SIZE", "256m"
33
  SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir
34
  _SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE)
35
  MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442
 
56
 
57
 
58
  def enabled() -> bool:
59
+ return os.environ.get("LEGION_PROCESS_ISOLATION") == "1"
60
 
61
 
62
  def _libc():
 
70
 
71
 
72
  def tmpfs_size(env=os.environ) -> str:
73
+ """The size cap of a sandbox's tmpfs root: $LEGION_ISOLATION_TMPFS_SIZE (bytes, or with a
74
  k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default."""
75
  value = (env.get(TMPFS_SIZE_ENV) or "").strip()
76
  if _SIZE.fullmatch(value):
 
87
  paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf",
88
  "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"]
89
  if not python_only:
90
+ paths.append(str(Path(__file__).resolve().parents[2])) # editable legion install
91
  for binary in (command[0], "node"):
92
  found = shutil.which(binary)
93
  if not found:
 
183
  private_dirs=private_dirs, tmp=tmp)}
184
  # Slurm sends USR1 to every process on reclaim. Only worker/world supervisors
185
  # handle it; an unshare wrapper must survive long enough for their bounded drain.
186
+ return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "legion-isolate",
187
  unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL",
188
  "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--",
189
  sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
world/src/{flock → legion}/models.py RENAMED
@@ -7,17 +7,27 @@ is expressed here. Change it deliberately and update the design doc.
7
  from __future__ import annotations
8
 
9
  import hashlib
 
10
  import re
11
  from datetime import UTC, date, datetime, timedelta
12
  from enum import StrEnum
13
- from typing import Any, Literal, NamedTuple
 
14
 
15
  import yaml
16
- from pydantic import BaseModel, Field, field_validator, model_serializer, model_validator
17
-
18
- from flock.registry import COMPUTE, HARNESSES
19
- from flock.world.protocol import TOOL_NAME_RE as WORLD_TOOL_RE
20
- from flock.world.protocol import WorldManifest
 
 
 
 
 
 
 
 
21
 
22
  # --------------------------------------------------------------------------- spec YAML
23
 
@@ -74,7 +84,7 @@ def until_deadline(until: str, started_at: float) -> float:
74
  # --------------------------------------------------------------------------- enums
75
 
76
 
77
- # the names in flock.registry.HARNESSES; an enum so spec errors and the JSON schema list them
78
  Harness = StrEnum("Harness", [(name, name) for name in HARNESSES], module=__name__)
79
 
80
 
@@ -104,12 +114,9 @@ class TypeHealth(StrEnum):
104
 
105
  AGENT_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*-\d{4,}$")
106
  TYPE_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$")
107
- # Provider names prefix model strings ("hf:Qwen/..."), so no dots and no colons. A model string
108
- # whose prefix does not look like this names no provider.
109
- PROVIDER_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
110
  ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
111
  TOOLS_VERSION_RE = re.compile(r"^[0-9a-f]{16}$")
112
- SELF_HOSTED_PRICING = [0.0, 0.0, 0.0]
113
 
114
  Reasoning = Literal["off", "low", "medium", "high"]
115
  # `reasoning` -> OpenAI `reasoning.effort`.
@@ -122,118 +129,292 @@ def _pricing_row(v: list[float], where: str) -> list[float]:
122
  return [float(x) for x in v]
123
 
124
 
125
- class ProviderSpec(BaseModel):
126
- """Where a model is served (design.md 'Providers'). Field names follow swarmlab's
127
- provider params so a `providers:` block moves between the two projects.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  `api_key_env` names a secret / env var; the value is never in the spec. The controller
130
- sends that secret to the provider's jobs and uses it for preflight; the worker hands it to
131
- the harness."""
132
-
133
- type: Literal["openai_compat", "anthropic"]
134
- base_url: str | None = None # openai_compat: required, ends in /v1; anthropic: API root
135
- # Several servers of one model (openai_compat): preflight probes each and health scrapes each
136
- # one's metrics; agents call `base_url`, which defaults to the first.
137
- base_urls: list[str] | None = None
138
- api_key_env: str
139
- self_hosted: bool = False # price defaults to [0, 0, 0]; real cost is the GPU job's time
140
- # Max agents of this swarm on this provider that may be in a turn at once. Enforced at
141
- # prompt admission by the controller (FLOCK_MAX_WORKING_ENFORCE=0: report only).
142
- max_working: int | None = None
143
- pricing: dict[str, list[float]] = Field(default_factory=dict) # model id ("*" = any) -> row
144
- timeout_s: float | None = None # passthrough to the harness / preflight
145
- max_retries: int | None = None # passthrough to the harness
146
- # How the key is sent. `anthropic` providers: "x-api-key" (default) or "bearer"
147
- # (`Authorization: Bearer`), for gateways and proxies that only take a bearer token. `openai_compat` is always bearer.
148
- auth: Literal["x-api-key", "bearer"] | None = None
149
- # Scrape `<server root>/metrics` (vLLM Prometheus text) of each base URL into the swarm's
150
- # health snapshots: num_requests_waiting / running, KV cache usage (docs/health.md).
151
  metrics: bool = False
 
 
152
 
153
- @field_validator("base_urls", mode="before")
154
  @classmethod
155
  def _url_list(cls, v: Any) -> Any:
156
- """A comma-separated string is a list (`base_urls: ${OPENAI_BASE_URLS:-}`); "" is none."""
157
  if isinstance(v, str):
158
- return [u.strip() for u in v.split(",") if u.strip()] or None
159
- return v
160
-
161
- @field_validator("api_key_env")
162
- @classmethod
163
- def _env_name(cls, v: str) -> str:
164
- if not ENV_NAME_RE.match(v):
165
- raise ValueError(f"api_key_env {v!r} must be an env var name (the key itself never goes in the spec)")
166
  return v
167
 
168
- @field_validator("pricing")
169
  @classmethod
170
- def _rows(cls, v: dict[str, list[float]]) -> dict[str, list[float]]:
171
- return {k: _pricing_row(row, f"pricing[{k!r}]") for k, row in v.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
- @field_validator("max_working")
174
  @classmethod
175
- def _positive(cls, v: int | None) -> int | None:
176
- if v is not None and v < 1:
177
- raise ValueError("max_working must be >= 1")
 
178
  return v
179
 
180
  @model_validator(mode="after")
181
- def _url(self) -> ProviderSpec:
182
- if self.base_urls is not None:
183
- urls = [u.strip().rstrip("/") for u in self.base_urls if u and u.strip()]
184
- if not urls:
185
- raise ValueError("base_urls must list at least one URL")
186
- if len(set(urls)) != len(urls):
187
- raise ValueError("base_urls must not repeat a URL")
188
- if self.type != "openai_compat":
189
- raise ValueError("base_urls is for openai_compat providers")
190
- self.base_urls = urls
191
- if self.base_url is None:
192
- self.base_url = urls[0]
193
- if self.type == "openai_compat" and not self.base_url:
194
- raise ValueError("base_url is required for type openai_compat (e.g. https://router.huggingface.co/v1)")
195
- if self.type == "openai_compat" and self.auth == "x-api-key":
196
- raise ValueError("auth: x-api-key is for anthropic providers; openai_compat always sends a bearer token")
197
- if self.base_url is not None:
198
- self.base_url = self.base_url.rstrip("/")
199
  return self
200
 
 
 
 
 
 
201
  @property
202
  def endpoints(self) -> list[str]:
203
- """The servers to spread agents over: `base_urls`, else `[base_url]`."""
204
- return list(self.base_urls) if self.base_urls else ([self.base_url] if self.base_url else [])
 
 
 
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
- class ModelSpec(BaseModel):
208
- """An alias under `models:`: a provider-prefixed model plus per-model settings."""
209
-
210
- model: str # "<provider>:<model id>"
211
- reasoning: Reasoning | None = None
212
- # Raw request-body fields (swarmlab's `extra`). Not sent (Harbor's Pi cannot); kept for
213
- # spec portability, with a warning at launch.
214
- extra: dict[str, Any] | None = None
215
- pricing: list[float] | None = None # overrides the provider's pricing for this alias
216
 
217
- @field_validator("pricing")
218
- @classmethod
219
- def _row(cls, v: list[float] | None) -> list[float] | None:
220
- return None if v is None else _pricing_row(v, "pricing")
 
 
221
 
222
 
223
  class ResolvedModel(BaseModel):
224
  """A type's model after resolution, pinned into the stored spec at apply time."""
225
 
 
 
226
  provider_name: str
227
- provider: ProviderSpec
228
- model_id: str # what the harness sends as `model`
 
 
 
 
 
229
  reasoning: Reasoning | None = None
230
- extra: dict[str, Any] | None = None
231
  pricing: list[float] # [input, output, cached] USD per 1M tokens, pinned
 
 
 
 
 
232
 
233
  @property
234
  def qualified(self) -> str:
235
  return f"{self.provider_name}:{self.model_id}"
236
 
 
 
 
 
 
237
 
238
  # --------------------------------------------------------------------------- comms (docs/comms.md)
239
 
@@ -305,7 +486,7 @@ class CommsRules(BaseModel):
305
  class CommsSpec(BaseModel):
306
  """Swarm-level `comms:` (docs/comms.md). `url`, `invite_env` and `channel` are resolved
307
  once by the controller at apply (channel name -> `channel_id`); `kickoff_file` and
308
- `protocols` are files next to the spec that `flock launch` inlines (`kickoff`,
309
  `protocols_text`), because the controller and workers cannot read the caller's files."""
310
 
311
  model_config = {"extra": "forbid"}
@@ -316,7 +497,7 @@ class CommsSpec(BaseModel):
316
  # worker's poll interval is max(2 s, poll_cycle_s / its agents).
317
  poll_cycle_s: float | None = Field(default=None, ge=10, le=3600) # unset: 300
318
  url: str
319
- # `space`: `flock init` duplicates `template` into a private per-run Space (`space`, default
320
  # `<template namespace>/board-<swarm>`) and fills BOARD_URL and the invite (docs/comms.md).
321
  # A url: the same as `url:`. Unset: `url` names an existing board.
322
  board: str | None = None
@@ -325,16 +506,16 @@ class CommsSpec(BaseModel):
325
  # Space secret -> the run.env (or environment) name holding its value, e.g. {HF_TOKEN:
326
  # BOARD_BUCKET_TOKEN}: a token scoped to the board's bucket, never the operator's own.
327
  space_secrets: dict[str, str] = Field(default_factory=dict)
328
- # Space variables over flock's (MSGBOARD_REPLICA: `<bucket>/board/<swarm>`); "" blanks one.
329
  space_variables: dict[str, str] = Field(default_factory=dict)
330
  space_hardware: str = "cpu-basic" # the Hub requires one to duplicate a Space
331
  invite_env: str # secret holding a multi-use agent invite (the code never goes in the spec)
332
  channel: str # name, with or without `#`
333
  kickoff_file: str | None = None
334
- kickoff: str | None = None # the file's text, inlined by `flock launch` (or given inline)
335
  rules: CommsRules = Field(default_factory=CommsRules)
336
  protocols: list[str] = Field(default_factory=list) # files appended to the instructions
337
- protocols_text: list[str] = Field(default_factory=list) # inlined by `flock launch`
338
  wake: list[Literal["mention", "thread", "dm", "channel"]] = Field(default_factory=lambda: ["mention", "thread"])
339
  search: Literal["board", "index"] | None = "board"
340
  # Written by the controller at apply; anything given by hand is replaced.
@@ -391,7 +572,7 @@ class CommsSpec(BaseModel):
391
 
392
  def board_url_default(data: Any) -> Any:
393
  """`comms.board` -> `comms.url` in raw spec data, before ${VAR} substitution: `space` reads
394
- BOARD_URL (written by `flock init`), a url is the url. An explicit `url` wins."""
395
  c = data.get("comms") if isinstance(data, dict) else None
396
  if isinstance(c, dict) and c.get("board") and "url" not in c:
397
  c["url"] = "${BOARD_URL}" if c["board"] == "space" else c["board"]
@@ -413,7 +594,7 @@ def comms_tools(ts: TypeSpec, comms: CommsSpec | None) -> list[str]:
413
 
414
 
415
  class DashboardSpec(BaseModel):
416
- """Swarm-level `dashboard:` (docs/dashboard.md): `flock init` writes the run's flock-overview
417
  row to `<registry>/runs/<id>.json` (id: default the swarm). The other row keys are derived from the spec."""
418
 
419
  model_config = {"extra": "forbid"}
@@ -450,15 +631,15 @@ class WorldSpec(BaseModel):
450
 
451
  model_config = {"extra": "forbid"}
452
 
453
- dir: str | None = None # relative to the spec file; `flock launch` resolves it
454
- command: list[str] | None = None # `{port}` and `{python}` are filled in by flock
455
  url: str | None = None
456
  token_env: str | None = None
457
  # Written by the controller at apply; anything given by hand is replaced.
458
  endpoint: str | None = None
459
  manifest: WorldManifest | None = None
460
  # Which credential this configuration belongs to, without the credential: the origin it is
461
- # bound to (`endpoint`, or `local:<swarm>` for a world flock started) and
462
  # HMAC(secret, origin). A worker sends its secret only when its own HMAC matches.
463
  credential_origin: str | None = None
464
  credential_id: str | None = None
@@ -466,7 +647,7 @@ class WorldSpec(BaseModel):
466
  # world waiting for a node (PENDING) is told apart from a crashed one (docs/health.md).
467
  slurm_job_name: str | None = None
468
  # Seconds the world may be down (health probe) before the controller pauses the types that
469
- # use it; resumed when it is back (docs/health.md). None: FLOCK_WORLD_DOWN_PAUSE_S or 1800;
470
  # 0: never. Controller only (not sent to workers).
471
  down_pause_s: float | None = Field(default=None, ge=0)
472
 
@@ -479,7 +660,7 @@ class WorldSpec(BaseModel):
479
  v = shlex.split(v)
480
  if v is not None and (not isinstance(v, list) or not v):
481
  raise ValueError("command must be a non-empty list (or a string), e.g. "
482
- "[flock, world, serve, \"taskboard:TaskBoard\"]")
483
  return [str(x) for x in v] if v is not None else None
484
 
485
  @field_validator("url", "endpoint")
@@ -500,7 +681,7 @@ class WorldSpec(BaseModel):
500
  @model_validator(mode="after")
501
  def _how(self) -> WorldSpec:
502
  if self.command is None and self.url is None:
503
- raise ValueError("world needs `command` (started by flock, compute: local) or `url` "
504
  "(a world already running)")
505
  if self.dir is not None and self.command is None:
506
  raise ValueError("world.dir is where `command` runs; give the command too")
@@ -552,7 +733,7 @@ class WorkdirSpec(BaseModel):
552
 
553
 
554
  class MemoryKnobs(BaseModel):
555
- """Worker memory thresholds, passed through as the FLOCK_MEM_* settings (worker.main)."""
556
 
557
  model_config = {"extra": "forbid"}
558
 
@@ -567,11 +748,11 @@ class WorkerKnobs(BaseModel):
567
 
568
  model_config = {"extra": "forbid"}
569
 
570
- drain_budget_s: float | None = Field(default=None, gt=0) # FLOCK_DRAIN_BUDGET_S
571
  sync_interval_s: float | None = Field(default=None, ge=10) # SYNC_INTERVAL
572
- sync_exclude: list[str] | None = None # FLOCK_SYNC_EXCLUDE (added to the defaults)
573
- restore_batch: int | None = Field(default=None, ge=1) # FLOCK_RESTORE_BATCH
574
- restore_threads: int | None = Field(default=None, ge=1, le=32) # FLOCK_RESTORE_THREADS
575
  memory: MemoryKnobs | None = None
576
 
577
 
@@ -663,14 +844,14 @@ class RampSpec(BaseModel):
663
 
664
  class HarborSpec(BaseModel):
665
  """A `harness: harbor` type's Trial inputs, written by the compile step
666
- (`flock.harbor.spec.compile_spec`), never by hand: each agent is one long-lived Harbor Trial
667
  on the upstream Harbor task path. The worker composes the agent's instructions from `team`,
668
  `role_text`, `roster` and the tools with the upstream `build_agent_instructions`."""
669
 
670
  model_config = {"extra": "forbid"}
671
 
672
  task: dict[str, Any] # ResolvedTask.manifest(): registry commit, dataset, the pinned task
673
- # a partial flock.harbor Spec (model, inference, task, environment, limits, tools_dir,
674
  # tools, resources_dir) for the upstream build_trial_config and the worker's HarborHost
675
  config: dict[str, Any]
676
  team: str = "" # the team_file's text
@@ -682,7 +863,7 @@ class HarborSpec(BaseModel):
682
  tools: dict[str, Any] = Field(default_factory=dict) # the tool bundle's manifest
683
  tools_sha256: str | None = None
684
  resources: dict[str, dict[str, Any]] = Field(default_factory=dict) # resource options
685
- # the content hash of the run's tools and resources folders, packed by `flock launch` and
686
  # uploaded as the swarm's tools bundle of that version: a worker fetches and unpacks it in
687
  # its own run dir (None: config's tools_dir and resources_dir, read where they are)
688
  folders: str | None = None
@@ -696,16 +877,19 @@ class TypeSpec(BaseModel):
696
  """One agent type inside a swarm. See design.md 'Spec'."""
697
 
698
  harness: Harness
699
- # Resolution order (design.md 'Providers'): an alias under `models:`, else "<provider>:<id>"
700
- # with the prefix under `providers:`; SwarmSpec refuses a model that names no provider.
701
- model: str
702
- reasoning: Reasoning | None = None # overrides the alias's reasoning
 
 
 
703
  image: str | None = None # None -> default worker image
704
  system_prompt_file: str | None = None # written into the workdir as AGENTS.md
705
- # The file's contents, inlined by `flock launch` (the controller and workers cannot
706
  # read the caller's files). Wins over system_prompt_file on the worker.
707
  system_prompt: str | None = None
708
- # A second file appended to the system prompt by `flock launch` (after a blank line): a
709
  # per-type section on top of a prompt several types share (e.g. a spawner and its
710
  # child types). The worker only sees the combined `system_prompt`.
711
  system_prompt_append_file: str | None = None
@@ -743,7 +927,7 @@ class TypeSpec(BaseModel):
743
  worker: WorkerKnobs | None = None # None: the worker's env, then built-in defaults
744
  resume_prompt: str | None = None
745
  # Tools from the swarm's tools folder: a list of function names, or "all".
746
- # `flock launch` refuses a name the folder does not define. None: no folder tools.
747
  tools: list[str] | Literal["all"] | None = None
748
  # Re-prompt this type's agents on a cadence, then a final round (docs/loop.md). None: off.
749
  loop: LoopSpec | None = None
@@ -783,9 +967,14 @@ class TypeSpec(BaseModel):
783
 
784
  @property
785
  def harness_model(self) -> str:
786
- """The model id the harness is started with."""
787
  return self.resolved_model.model_id if self.resolved_model else self.model
788
 
 
 
 
 
 
789
  @property
790
  def provider_name(self) -> str | None:
791
  return self.resolved_model.provider_name if self.resolved_model else None
@@ -825,7 +1014,7 @@ class TypeSpec(BaseModel):
825
  raise ValueError("ephemeral: true is for spawned agents only; set replicas: 0")
826
  if self.harbor is None:
827
  raise ValueError("harness harbor needs the `harbor:` block (written by the compile "
828
- "step of a flock.harbor spec)")
829
  return self
830
 
831
  @field_validator("workers")
@@ -883,13 +1072,13 @@ class SlurmResources(BaseModel):
883
 
884
  class ComputeSpec(BaseModel):
885
  """Where workers run (docs/local.md). `hf-jobs` (the default): one HF Job per worker.
886
- `local`: one `python -m flock.worker.main` subprocess per worker on the controller's machine
887
- (`flock launch` runs them on this machine). `slurm`: one `sbatch` job per worker (docs/slurm.md).
888
  The spec also accepts the short form `compute: local`.
889
 
890
  `worker_unknown_after`, `worker_dead_after` and `crash_backoff` are for every backend
891
  (docs/live.md "Worker liveness"). The other keys are for `slurm` and win over the
892
- controller's FLOCK_SLURM_* env, which only fills unset keys (then built-in defaults).
893
  `types` sets per-type `cpus`/`mem`/`time`/`partition` (an interviewer type needs less
894
  than an agent)."""
895
 
@@ -906,12 +1095,12 @@ class ComputeSpec(BaseModel):
906
  launch_dir: str | None = None # shared dir: <worker id>-<incarnation>.env, no secrets
907
  host_file: str | None = None # shared file holding the controller's hostname
908
  run: str | None = None # RUN= in the env file; default: the launch_dir's parent dir name
909
- venv: str | None = None # written to the env file as FLOCK_VENV for the script
910
- secrets_file: str | None = None # path only, as FLOCK_SECRETS_FILE; never read by flock
911
  # workers run in a container whose /tmp is RAM: every agent/harness path goes under this
912
- # root instead: <root>/flock/<worker id>/{work,home,hf,tmp}
913
  container_root: str | None = None
914
- container_image: str | None = None # an Enroot image (.sqsh): FLOCK_CONTAINER_IMAGE
915
 
916
  @model_serializer(mode="wrap")
917
  def _compact(self, handler: Any) -> Any:
@@ -923,7 +1112,7 @@ class ComputeSpec(BaseModel):
923
  types: dict[str, SlurmResources] = Field(default_factory=dict)
924
  # the largest job the partition can ever run: sbatch accepts bigger ones, which then pend
925
  # forever; a launch over these is refused (also checked at apply). None: not checked (the
926
- # controller's FLOCK_SLURM_MAX_CPUS/_MEM, from the cluster profile, still apply at launch)
927
  max_cpus: int | None = Field(default=None, ge=1)
928
  max_mem: str | None = None
929
  # worker liveness (docs/live.md "Worker liveness"); None: the backend's default (`liveness`)
@@ -962,17 +1151,18 @@ class ComputeSpec(BaseModel):
962
 
963
  class SwarmSpec(BaseModel):
964
  swarm: str
965
- # HF namespace jobs are launched under, and the bucket agents sync to (e.g.
966
- # hf://buckets/<namespace>/<bucket>). Required for compute hf-jobs; optional for compute local.
967
- namespace: str = ""
968
- bucket: str = ""
969
- providers: dict[str, ProviderSpec] = Field(default_factory=dict)
970
- models: dict[str, ModelSpec] = Field(default_factory=dict)
 
971
  types: dict[str, TypeSpec]
972
  # The tools folder, relative to the spec file; None: `tools/` next to it.
973
- # Read by `flock launch` only.
974
  tools_dir: str | None = None
975
- # Content hash of the tools bundle, written by `flock launch` after uploading the folder
976
  # (anything given by hand is replaced). Workers fetch that version; None: no tools.
977
  tools_version: str | None = None
978
  # The team's message board (docs/comms.md); None: no comms.
@@ -992,54 +1182,32 @@ class SwarmSpec(BaseModel):
992
  @classmethod
993
  def _valid_tools_version(cls, v: str | None) -> str | None:
994
  if v is not None and not TOOLS_VERSION_RE.match(v):
995
- raise ValueError("tools_version is written by `flock launch` (16 hex digits)")
996
- return v
997
-
998
- @field_validator("providers")
999
- @classmethod
1000
- def _valid_providers(cls, v: dict[str, ProviderSpec]) -> dict[str, ProviderSpec]:
1001
- for name in v:
1002
- if not PROVIDER_NAME_RE.match(name):
1003
- raise ValueError(f"providers.{name}: name must be lowercase [a-z0-9_-], starting with a letter")
1004
  return v
1005
 
1006
  @model_validator(mode="after")
1007
  def _resolve_models(self) -> SwarmSpec:
1008
- """Apply-time checks and pinning: every alias and provider prefix exists, every
1009
- provider-backed model has a price, harness and provider speak the same API. The price
1010
- used is written into the spec (`resolved_model.pricing`, and the self-hosted default
1011
- into the provider's `pricing`), so the stored spec carries what cost is derived from."""
1012
- for alias, m in self.models.items():
1013
- if ":" in alias:
1014
- raise ValueError(f"models.{alias}: an alias cannot contain ':'")
1015
- prefix, sep, model_id = m.model.partition(":")
1016
- if not sep or not prefix or not model_id:
1017
- raise ValueError(f"models.{alias}.model: {m.model!r} must look like '<provider>:<model id>'")
1018
- if prefix not in self.providers:
1019
- raise ValueError(f"models.{alias}.model: unknown provider {prefix!r} in {m.model!r}; "
1020
- f"providers: {sorted(self.providers)}")
1021
  for type_name, ts in self.types.items():
1022
- ts.resolved_model = resolve_model(self, ts, type_name=type_name)
1023
- r = ts.resolved_model
1024
- if r is None:
1025
- raise ValueError(
1026
- f"types.{type_name}.model: harness {ts.harness.value!r} needs a provider-backed "
1027
- f"model ('<provider>:<model id>' or an alias); {ts.model!r} names no provider")
1028
- want = HARNESSES[ts.harness].provider_type
1029
- if r.provider.type != want:
1030
- raise ValueError(
1031
- f"types.{type_name}.model: harness {ts.harness.value!r} cannot use provider "
1032
- f"{r.provider_name!r} (type {r.provider.type}); {ts.harness.value} needs a "
1033
- f"provider of type {want}")
1034
- p = self.providers[r.provider_name]
1035
- if p.self_hosted and r.model_id not in p.pricing and "*" not in p.pricing:
1036
- p.pricing[r.model_id] = list(SELF_HOSTED_PRICING) # pin the default
1037
  for type_name, ts in self.types.items():
1038
  cap = ts.loop.while_.agent_usd if ts.loop else None
1039
  if isinstance(cap, dict) and agent_cap(ts) is None:
1040
  raise ValueError(
1041
  f"types.{type_name}.loop.while.agent_usd: no entry for model {ts.model!r} "
1042
- f"(keys: {sorted(cap)}); key it by the type's model alias or model id")
1043
  return self
1044
 
1045
  @model_validator(mode="after")
@@ -1064,12 +1232,12 @@ class SwarmSpec(BaseModel):
1064
  "(command or url)")
1065
  if ts.world is False and listed:
1066
  raise ValueError(f"types.{name}: world: false but tools lists {', '.join(listed)}")
1067
- if self.dashboard is not None and (self.compute.kind == "local" or not self.bucket):
1068
- raise ValueError("dashboard: needs the run's state in a bucket (`bucket:`, compute "
1069
  "hf-jobs or slurm); compute: local keeps it on this machine")
1070
  c = self.comms
1071
  if c is not None and c.protocols_text and len(c.protocols_text) != len(c.protocols):
1072
- raise ValueError("comms.protocols_text is written by `flock launch` (one per protocols file)")
1073
  return self
1074
 
1075
  @field_validator("swarm")
@@ -1103,14 +1271,9 @@ class SwarmSpec(BaseModel):
1103
  raise ValueError(f"types.{name}.env.HEARTBEAT_INTERVAL ({hb:g}s): two heartbeats "
1104
  f"({2 * hb:g}s) exceed worker_unknown_after ({unknown:g}s); "
1105
  f"raise worker_unknown_after or lower the interval")
1106
- if kind == "hf-jobs":
1107
- missing = [f for f in ("namespace", "bucket") if not getattr(self, f)]
1108
- if missing:
1109
- raise ValueError(f"{' and '.join(missing)} required for compute hf-jobs "
1110
- "(or set `compute: local`, docs/local.md)")
1111
- elif kind != "local" and not self.bucket:
1112
  # agent state goes to an HF bucket on every remote backend, never to a shared disk
1113
- raise ValueError(f"bucket is required for compute {kind}")
1114
  if kind != "local" and self.world is not None and self.world.url is None:
1115
  raise ValueError(f"world.url is required for compute {kind}: run the world as a "
1116
  "Job, Space or cluster job and give its url (starting it from "
@@ -1125,8 +1288,26 @@ class SwarmSpec(BaseModel):
1125
  unknown = set(self.compute.types) - set(self.types)
1126
  if unknown:
1127
  raise ValueError(f"compute.types names unknown types: {sorted(unknown)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
1128
  return self
1129
 
 
 
 
 
 
1130
  @field_validator("spawn")
1131
  @classmethod
1132
  def _valid_spawn(cls, v: dict[str, SpawnRule], info) -> dict[str, SpawnRule]:
@@ -1144,38 +1325,27 @@ class SwarmSpec(BaseModel):
1144
  return v
1145
 
1146
 
1147
- def resolve_model(spec: SwarmSpec, type_spec: TypeSpec, *, type_name: str = "?") -> ResolvedModel | None:
1148
- """Resolve a type's `model`: alias under `models:` -> "<provider>:<id>" with the prefix
1149
- under `providers:`; None when it names no provider. Raises ValueError naming the type
1150
- and field for an unknown provider prefix or a provider-backed model with no price."""
1151
- where = f"types.{type_name}.model"
1152
- alias = spec.models.get(type_spec.model)
1153
- target = alias.model if alias else type_spec.model
1154
- prefix, sep, model_id = target.partition(":")
1155
- if not sep or not PROVIDER_NAME_RE.match(prefix):
1156
- return None # names no provider
1157
- if prefix not in spec.providers:
1158
- raise ValueError(f"{where}: unknown provider {prefix!r} in {target!r}; declare it under "
1159
- f"providers: (known: {sorted(spec.providers)}) or use a model alias")
1160
- if not model_id:
1161
- raise ValueError(f"{where}: {target!r} has no model id after '{prefix}:'")
1162
- provider = spec.providers[prefix]
1163
- pricing = (alias.pricing if alias else None) or provider.pricing.get(model_id) or provider.pricing.get("*")
1164
- if pricing is None:
1165
- if not provider.self_hosted:
1166
- raise ValueError(
1167
- f"{where}: no pricing for {target!r}; add providers.{prefix}.pricing"
1168
- f"[{model_id!r}] = [input, output, cached] (USD per 1M tokens)"
1169
- + (f" or models.{type_spec.model}.pricing" if alias else "")
1170
- + f", or mark providers.{prefix} self_hosted")
1171
- pricing = list(SELF_HOSTED_PRICING)
1172
  return ResolvedModel(
1173
- provider_name=prefix,
1174
- provider=provider,
1175
- model_id=model_id,
1176
- reasoning=type_spec.reasoning or (alias.reasoning if alias else None),
1177
- extra=alias.extra if alias else None,
1178
- pricing=list(pricing),
 
1179
  )
1180
 
1181
 
@@ -1375,7 +1545,7 @@ class LoopFinal(BaseModel):
1375
  model_config = {"extra": "forbid"}
1376
 
1377
  prompt: str | None = None
1378
- prompt_file: str | None = None # inlined into `prompt` by `flock launch`
1379
  reserve_usd: float = 0.0
1380
 
1381
  @field_validator("reserve_usd")
@@ -1430,7 +1600,7 @@ class LoopSpec(BaseModel):
1430
  model_config = {"extra": "forbid", "populate_by_name": True}
1431
 
1432
  prompt: str | None = None
1433
- prompt_file: str | None = None # inlined into `prompt` by `flock launch`
1434
  every: str = "turn_end"
1435
  on: list[str] = Field(default_factory=list) # message_board.mention, world.event:*
1436
  while_: LoopWhile = Field(default_factory=LoopWhile, alias="while")
@@ -1507,7 +1677,7 @@ def agent_cap(ts: TypeSpec) -> float | None:
1507
 
1508
  def loop_refusals(spec: SwarmSpec) -> list[str]:
1509
  """Loop settings this version accepts in the model but cannot run: world-backed wakes and
1510
- prompt files not inlined. `flock launch` and the controller refuse a spec with any of them."""
1511
  out: list[str] = []
1512
  for name, ts in spec.types.items():
1513
  lp = ts.loop
@@ -1516,9 +1686,9 @@ def loop_refusals(spec: SwarmSpec) -> list[str]:
1516
  where = f"types.{name}.loop"
1517
  out += [f"{where}.on: {x} {NEEDS_WORLD}" for x in lp.on if x.startswith("world.")]
1518
  if lp.prompt is None:
1519
- out.append(f"{where}.prompt_file: not inlined (use `flock launch`, which reads it)")
1520
  if lp.final is not None and lp.final.prompt is None:
1521
- out.append(f"{where}.final.prompt_file: not inlined (use `flock launch`, which reads it)")
1522
  return out
1523
 
1524
 
@@ -1577,7 +1747,7 @@ class AgentHeartbeat(BaseModel):
1577
 
1578
 
1579
  class WorkerMem(BaseModel):
1580
- """The worker's cgroup memory (MB) at its last sample (flock.worker.cgroup)."""
1581
 
1582
  current_mb: float | None = None
1583
  limit_mb: float | None = None # None: no limit found, nothing is armed
@@ -1630,19 +1800,19 @@ class WorkerHeartbeat(BaseModel):
1630
  restore: RestoreProgress | None = None # None when no restore is in flight
1631
  tools: dict[str, ToolCounters] | None = None # world tools by name
1632
  knobs_rev: str | None = None # hash of the worker's effective settings
1633
- # nonreclaimable memory passed FLOCK_MEM_ROTATE of the limit: the controller drains the
1634
  # worker when its rotation budget allows (docs/slurm.md "Memory")
1635
  wants_rotation: bool = False
1636
  # agents whose last push to the bucket failed (retried once), with the error; the drain's
1637
- # final heartbeat carries them so `flock stop --release` can name them
1638
  unsynced: dict[str, str] = Field(default_factory=dict)
1639
 
1640
 
1641
  class Event(BaseModel):
1642
  """One line of an agent's event stream.
1643
 
1644
- The on-disk / over-the-wire shape is pi session format v3 (see swarmlab's
1645
- export.py for the reference encoding). `type`, `ts`, `agent` are required by us;
1646
  the rest of the pi record lives in `data`. Harness-neutral types the worker adds:
1647
  session_started, session_resumed, session_restarted, turn_started, turn_ended,
1648
  turn_interrupted, sync.
@@ -1738,7 +1908,7 @@ class AssignCommand(BaseModel):
1738
  restore: bool = True # restore workdir + session from bucket before first prompt
1739
  resume_prompt: str | None = None # sent once after restore when a turn was interrupted
1740
  parent: str | None = None # the spawning agent, None for a replica
1741
- # The agent's scoped controller token, injected into its harness env as FLOCK_AGENT_TOKEN.
1742
  agent_token: str | None = None
1743
  tools_version: str | None = None # the swarm's tools bundle; None: no tools
1744
  comms: CommsSpec | None = None # the swarm's comms block (docs/comms.md), channel resolved
@@ -1834,7 +2004,7 @@ class AgentStatus(BaseModel):
1834
  type: str
1835
  harness: Harness
1836
  model: str
1837
- provider: str | None = None # provider name when the model is provider-backed
1838
  labels: dict[str, str]
1839
  state: AgentState
1840
  idle_since: datetime | None = None
@@ -1915,22 +2085,49 @@ class TypeStatus(BaseModel):
1915
 
1916
 
1917
  class ProviderStatus(BaseModel):
1918
- name: str
1919
- type: str
1920
- self_hosted: bool
1921
- types: list[str] # agent types using this provider
 
 
 
1922
  working: int # agents of those types in a turn now (from heartbeats)
1923
- max_working: int | None = None # enforced at prompt admission unless FLOCK_MAX_WORKING_ENFORCE=0
1924
  # Agents with turns but zero reported tokens: the server sends no usage, cost is unknown.
1925
  zero_usage_agents: int = 0
1926
 
1927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1928
  class SwarmStatus(BaseModel):
1929
  swarm: str
1930
  namespace: str
1931
- bucket: str
1932
  types: dict[str, TypeStatus]
1933
  providers: dict[str, ProviderStatus] = Field(default_factory=dict)
 
1934
  agents_total: int
1935
  workers_total: int
1936
  pending_prompts: int
@@ -1941,9 +2138,10 @@ class SwarmStatus(BaseModel):
1941
  # pause holds (docs/loop.md "Pause and resume"): {types: {T: {since, reason, by, auto}},
1942
  # agents: {A: ...}}; None when nothing is held
1943
  held: dict[str, dict[str, dict[str, Any]]] | None = None
1944
- # `flock stop --release`: {since, reason, unsynced: {agent: error}}; None when not released
1945
  released: dict[str, Any] | None = None
1946
  # bumped by every apply that changes the spec (docs/live.md)
 
1947
  generation: int | None = None
1948
 
1949
 
@@ -1958,8 +2156,8 @@ class LoopRequest(BaseModel):
1958
  class PreflightResult(BaseModel):
1959
  """One provider-backed model probed with a tool call and a follow-up turn."""
1960
 
1961
- model: str # "<provider>:<model id>"
1962
- provider: str
1963
  types: list[str]
1964
  # "responses" (openai_compat) | "messages" (anthropic) |
1965
  # "chat_completions" (openai_compat; Harbor's Pi)
 
7
  from __future__ import annotations
8
 
9
  import hashlib
10
+ import ipaddress
11
  import re
12
  from datetime import UTC, date, datetime, timedelta
13
  from enum import StrEnum
14
+ from typing import Annotated, Any, Literal, NamedTuple
15
+ from urllib.parse import urlsplit
16
 
17
  import yaml
18
+ from pydantic import (
19
+ AfterValidator,
20
+ BaseModel,
21
+ Field,
22
+ field_validator,
23
+ model_serializer,
24
+ model_validator,
25
+ )
26
+
27
+ from legion.buckets import BucketId
28
+ from legion.registry import COMPUTE, HARNESSES
29
+ from legion.world.protocol import TOOL_NAME_RE as WORLD_TOOL_RE
30
+ from legion.world.protocol import WorldManifest
31
 
32
  # --------------------------------------------------------------------------- spec YAML
33
 
 
84
  # --------------------------------------------------------------------------- enums
85
 
86
 
87
+ # the names in legion.registry.HARNESSES; an enum so spec errors and the JSON schema list them
88
  Harness = StrEnum("Harness", [(name, name) for name in HARNESSES], module=__name__)
89
 
90
 
 
114
 
115
  AGENT_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*-\d{4,}$")
116
  TYPE_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$")
 
 
 
117
  ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
118
  TOOLS_VERSION_RE = re.compile(r"^[0-9a-f]{16}$")
119
+ ZERO_PRICING = [0.0, 0.0, 0.0] # a type without `pricing`: its usage costs $0
120
 
121
  Reasoning = Literal["off", "low", "medium", "high"]
122
  # `reasoning` -> OpenAI `reasoning.effort`.
 
129
  return [float(x) for x in v]
130
 
131
 
132
+ # --------------------------------------------------------------------------- inference (docs/open-models.md)
133
+
134
+ HF_ROUTER_URL = "https://router.huggingface.co/v1"
135
+ # `hf_router.provider` values that let the router pick the provider per request
136
+ ROUTER_POLICIES = ("fastest", "cheapest", "preferred")
137
+ # What a Trial gets for servers that take no key: Pi needs a key reference all the same
138
+ NO_KEY_ENV, NO_KEY = "LEGION_INFERENCE_KEY", "none"
139
+ _ROUTER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
140
+
141
+
142
+ def namespace_name(value: str) -> str:
143
+ """A namespace is also an HTTP header value: allow empty, otherwise one ASCII name."""
144
+ if value and not _ROUTER_NAME_RE.fullmatch(value):
145
+ raise ValueError("namespace must be empty or an account name, e.g. my-org")
146
+ return value
147
+
148
+
149
+ Namespace = Annotated[str, AfterValidator(namespace_name)]
150
+
151
+
152
+ class HFRouter(BaseModel):
153
+ """`inference.hf_router`: the HF router, sent `<model>:<provider>`."""
154
+
155
+ model_config = {"extra": "forbid"}
156
+
157
+ # A provider (`deepinfra`), or a selection policy: `fastest` (the router's default),
158
+ # `cheapest` or `preferred` (your order in the Hub settings). None: the router's default.
159
+ provider: str | None = None
160
+
161
+ @field_validator("provider")
162
+ @classmethod
163
+ def _name(cls, v: str | None) -> str | None:
164
+ if v is not None and not _ROUTER_NAME_RE.match(v):
165
+ raise ValueError(f"{v!r} must be a name, e.g. deepinfra or huggingface")
166
+ return v
167
+
168
+ @property
169
+ def policy(self) -> bool:
170
+ """The router picks the provider per request: no provider is named."""
171
+ return self.provider is None or self.provider in ROUTER_POLICIES
172
+
173
+
174
+ # `inference.hf_jobs` (docs/open-models.md "Servers legion starts"): the vLLM image legion starts
175
+ # (it serves Qwen3_5ForConditionalGeneration), the port the jobs proxy exposes, and the job
176
+ # lifetime when neither the spec nor its compile step set one
177
+ DEFAULT_VLLM_IMAGE = "vllm/vllm-openai:v0.33.0"
178
+ VLLM_PORT = 8000
179
+ DEFAULT_SERVER_TIMEOUT = "2h"
180
+ # `vllm_args` keys legion sets itself: the server's address and name, the model, and the
181
+ # tool-calling flags, which are named fields. `api_key`: the jobs proxy drops `Authorization`,
182
+ # so vLLM would refuse every request (the proxy's HF-token check is the authentication).
183
+ VLLM_OWNED = ("host", "port", "served_model_name", "model", "api_key", "enable_auto_tool_choice",
184
+ "tool_call_parser", "reasoning_parser")
185
+ _VLLM_KEY_RE = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
186
+
187
+
188
+ def vllm_arg_key(entry: str) -> str:
189
+ """`max-model-len=131072` -> `max_model_len`: one spelling per flag."""
190
+ return entry.split("=", 1)[0].strip().replace("-", "_")
191
+
192
+
193
+ class HFJobs(BaseModel):
194
+ """`inference.hf_jobs`: vLLM servers legion starts on HF Jobs, one group per model, and stops
195
+ when the run ends (docs/open-models.md). The servers' URLs are pinned into the spec as
196
+ `urls` (`resolved_model.inference.urls`)."""
197
+
198
+ model_config = {"extra": "forbid"}
199
+
200
+ flavor: str = Field(min_length=1) # a GPU flavor (`hf jobs hardware`), e.g. a100-large
201
+ tool_call_parser: str = Field(min_length=1) # Pi needs tool calls: --enable-auto-tool-choice
202
+ reasoning_parser: str | None = None
203
+ # Every other `vllm serve` flag as KEY=VALUE (`max_model_len=131072` -> --max-model-len
204
+ # 131072; `true`/`false` -> --flag/--no-flag). Fills in max_num_seqs (the block's
205
+ # max_working) and tensor_parallel_size (the flavor's GPUs) unless set here.
206
+ vllm_args: list[str] = Field(default_factory=list)
207
+ # The job's lifetime, the backstop if the run never stops it; None: the run's
208
+ # run_timeout_seconds + startup_timeout + a margin (the compile step writes it)
209
+ timeout: str | None = None
210
+ startup_timeout: str = "20m" # how long legion waits for every replica to answer
211
+ replicas: int = Field(default=1, ge=1) # each agent calls one (rendezvous hashing)
212
+ image: str = DEFAULT_VLLM_IMAGE
213
+
214
+ @field_validator("timeout", "startup_timeout")
215
+ @classmethod
216
+ def _duration(cls, v: str | None) -> str | None:
217
+ return None if v is None else _positive_duration(v)
218
+
219
+ @field_validator("vllm_args")
220
+ @classmethod
221
+ def _vllm_args(cls, v: list[str]) -> list[str]:
222
+ seen: set[str] = set()
223
+ for entry in v:
224
+ key, _, value = entry.partition("=")
225
+ name = vllm_arg_key(entry)
226
+ if not _VLLM_KEY_RE.match(key.strip()) or not value.strip():
227
+ raise ValueError(f"vllm_args {entry!r}: use KEY=VALUE (a flag: KEY=true), e.g. "
228
+ "max_model_len=131072")
229
+ if name in VLLM_OWNED:
230
+ named = name in HFJobs.model_fields
231
+ raise ValueError(f"vllm_args {entry!r}: " + (
232
+ f"set hf_jobs.{name} instead" if named else
233
+ "the jobs proxy drops Authorization, so vLLM would refuse every request; "
234
+ "the proxy's HF-token check authenticates" if name == "api_key" else
235
+ "legion sets it"))
236
+ if name in seen:
237
+ raise ValueError(f"vllm_args: {name} is set twice")
238
+ seen.add(name)
239
+ return v
240
+
241
+
242
+ class Inference(BaseModel):
243
+ """Where a model runs (design.md 'Inference'): the HF router (`hf_router`, the default),
244
+ OpenAI-compatible servers you run (`urls`) or vLLM servers legion starts on HF Jobs
245
+ (`hf_jobs`), plus settings for any of them. The same block in a Harbor spec (the run's, a
246
+ role's) and a swarm spec (the swarm's, a type's).
247
 
248
  `api_key_env` names a secret / env var; the value is never in the spec. The controller
249
+ sends that secret to the workers and uses it for its checks; the worker hands it to the
250
+ harness.
251
+
252
+ With `hf_jobs`, `urls` is what the controller pins once the servers answer (only in
253
+ `resolved_model.inference`; a spec that sets both is refused)."""
254
+
255
+ model_config = {"extra": "forbid"}
256
+
257
+ hf_router: HFRouter | None = None
258
+ # Servers (`.../v1`) that all serve the type's `model`; each agent calls one of them
259
+ urls: list[str] | None = None
260
+ hf_jobs: HFJobs | None = None
261
+ api_key_env: str | None = None # default: HF_TOKEN for hf_router and hf_jobs; no key for urls
262
+ # Max agents of this swarm on these endpoints in a turn at once. Enforced at prompt
263
+ # admission by the controller (LEGION_MAX_WORKING_ENFORCE=0: report only).
264
+ max_working: int | None = Field(default=None, ge=1)
265
+ context_window: int | None = Field(default=None, ge=1) # tokens, when the server reports none
266
+ # urls only: scrape each server's vLLM `/metrics` into the health snapshots (docs/health.md)
 
 
 
267
  metrics: bool = False
268
+ # Pi's `--thinking` level; None: Pi's default
269
+ reasoning_effort: Literal["off", "minimal", "low", "medium", "high", "xhigh", "max"] | None = None
270
 
271
+ @field_validator("urls", mode="before")
272
  @classmethod
273
  def _url_list(cls, v: Any) -> Any:
274
+ """A comma-separated string is a list (`urls: ${VLLM_URLS}`)."""
275
  if isinstance(v, str):
276
+ return [u.strip() for u in v.split(",") if u.strip()]
 
 
 
 
 
 
 
277
  return v
278
 
279
+ @field_validator("urls")
280
  @classmethod
281
+ def _urls(cls, v: list[str] | None) -> list[str] | None:
282
+ if v is None:
283
+ return v
284
+ out = []
285
+ for u in v:
286
+ url = urlsplit(u.strip())
287
+ if (url.scheme not in ("http", "https") or not url.hostname or url.username
288
+ or url.password or url.query or url.fragment):
289
+ raise ValueError(f"{u!r} must be an HTTP(S) URL without credentials, e.g. "
290
+ "http://10.0.0.5:8000/v1")
291
+ out.append(u.strip().rstrip("/"))
292
+ if not out:
293
+ raise ValueError("urls must list at least one URL")
294
+ if len(set(out)) != len(out):
295
+ raise ValueError("urls must not repeat a URL")
296
+ return out
297
 
298
+ @field_validator("api_key_env")
299
  @classmethod
300
+ def _env_name(cls, v: str | None) -> str | None:
301
+ if v is not None and not ENV_NAME_RE.match(v):
302
+ raise ValueError(f"api_key_env {v!r} must be an env var name (the key itself never "
303
+ "goes in the spec)")
304
  return v
305
 
306
  @model_validator(mode="after")
307
+ def _one(self) -> Inference:
308
+ given = [k for k in ("hf_router", "urls", "hf_jobs") if getattr(self, k) is not None]
309
+ if self.hf_jobs is not None and self.urls is not None:
310
+ given.remove("urls") # the started servers', pinned (refused in a spec's own block)
311
+ if len(given) > 1:
312
+ raise ValueError(f"set one of hf_router, urls or hf_jobs, not {' and '.join(given)}")
313
+ if not given:
314
+ self.hf_router = HFRouter()
315
+ if self.metrics and self.urls is None:
316
+ raise ValueError("metrics scrapes your servers' vLLM metrics: it needs urls")
 
 
 
 
 
 
 
 
317
  return self
318
 
319
+ def held(self) -> Inference:
320
+ """The block as workers (its key) and Trials (endpoints, Pi's config) hold it: without
321
+ the controller's `max_working`."""
322
+ return self.model_copy(update={"max_working": None})
323
+
324
  @property
325
  def endpoints(self) -> list[str]:
326
+ """The servers' base URLs, as written: `urls` (with `hf_jobs`, the started servers'
327
+ once pinned), or the router's. Empty: hf_jobs servers not started yet."""
328
+ if self.urls:
329
+ return list(self.urls)
330
+ return [HF_ROUTER_URL] if self.hf_router is not None else []
331
 
332
+ @property
333
+ def key_env(self) -> str | None:
334
+ """The key's env name: `api_key_env`, else HF_TOKEN for the router and the HF Jobs
335
+ proxy; None: no key."""
336
+ hf = self.hf_router is not None or self.hf_jobs is not None
337
+ return self.api_key_env or ("HF_TOKEN" if hf else None)
338
+
339
+ def unpinned(self) -> Inference:
340
+ """The block as a spec writes it: without the started servers' `urls`."""
341
+ return self.model_copy(update={"urls": None}) if self.hf_jobs is not None else self
342
+
343
+ def request_model(self, model: str) -> str:
344
+ """What the servers are sent as `model`: `<model>:<provider>` for the router with a
345
+ provider or policy set, else `model`."""
346
+ r = self.hf_router
347
+ return f"{model}:{r.provider}" if r is not None and r.provider else model
348
+
349
+ def endpoint_for(self, run: str, agent: str) -> str:
350
+ """The server `agent` of `run` (a swarm's name, the upstream launcher's run id) calls:
351
+ rendezvous hashing of both over `endpoints`. Stable for a given list, so an agent keeps
352
+ its server (and the server its prefix cache) across Trials and restarts; spreads agents
353
+ roughly evenly, including one name in many runs (every run's `agent-001`); and a URL
354
+ added or removed moves only the agents that must move."""
355
+ return max(self.endpoints,
356
+ key=lambda u: hashlib.sha256(f"{run}\n{agent}\n{u}".encode()).digest())
357
+
358
+ def describe(self) -> str:
359
+ """One line for status: `hf_router deepinfra`, the URLs, or `hf_jobs <flavor>` and the
360
+ started servers' URLs."""
361
+ if self.hf_router is not None:
362
+ return f"hf_router {self.hf_router.provider or 'fastest'}"
363
+ if self.hf_jobs is not None:
364
+ return f"hf_jobs {self.hf_jobs.flavor}" + (
365
+ f", urls {', '.join(self.endpoints)}" if self.urls else ", not started")
366
+ return "urls " + ", ".join(self.endpoints)
367
+
368
+
369
+ def loopback_url(url: str) -> bool:
370
+ """The URL names the machine it is used on: `localhost` or a loopback address."""
371
+ host = urlsplit(url).hostname or ""
372
+ if host == "localhost" or host.endswith(".localhost"):
373
+ return True
374
+ try:
375
+ return ipaddress.ip_address(host).is_loopback
376
+ except ValueError:
377
+ return False
378
 
 
 
 
 
 
 
 
 
 
379
 
380
+ def private_url(url: str) -> bool:
381
+ """The URL names this machine or a private network (an RFC 1918 or link-local address)."""
382
+ try:
383
+ return loopback_url(url) or ipaddress.ip_address(urlsplit(url).hostname or "").is_private
384
+ except ValueError:
385
+ return False
386
 
387
 
388
  class ResolvedModel(BaseModel):
389
  """A type's model after resolution, pinned into the stored spec at apply time."""
390
 
391
+ # The inference block it runs on, which admission (`max_working`) and status count by:
392
+ # `inference` (the swarm's) or `types.<type>.inference` (the type's own)
393
  provider_name: str
394
+ # The block; with `hf_jobs`, plus the started servers' `urls`, pinned by the controller
395
+ # once they answer (controller/servers.py) and kept while the block and model are the same
396
+ inference: Inference
397
+ # Derived only from the spec's explicit namespace. Never from HF_TOKEN's whoami:
398
+ # the inference key can belong to someone else. Sent by preflight and Pi alike.
399
+ headers: dict[str, str] = Field(default_factory=dict)
400
+ model_id: str # the type's `model`: what legion prices the usage under
401
  reasoning: Reasoning | None = None
 
402
  pricing: list[float] # [input, output, cached] USD per 1M tokens, pinned
403
+ # The window the servers serve the model with, from GET /v1/models (vLLM's max_model_len,
404
+ # the router provider's context_length; under a router policy the smallest among the
405
+ # providers with tools), else `inference.context_window`. Pinned by the controller's apply
406
+ # (controller/inference.py); None before that.
407
+ context_window: int | None = None
408
 
409
  @property
410
  def qualified(self) -> str:
411
  return f"{self.provider_name}:{self.model_id}"
412
 
413
+ @property
414
+ def request_model(self) -> str:
415
+ """What the harness sends as `model`."""
416
+ return self.inference.request_model(self.model_id)
417
+
418
 
419
  # --------------------------------------------------------------------------- comms (docs/comms.md)
420
 
 
486
  class CommsSpec(BaseModel):
487
  """Swarm-level `comms:` (docs/comms.md). `url`, `invite_env` and `channel` are resolved
488
  once by the controller at apply (channel name -> `channel_id`); `kickoff_file` and
489
+ `protocols` are files next to the spec that `legion launch` inlines (`kickoff`,
490
  `protocols_text`), because the controller and workers cannot read the caller's files."""
491
 
492
  model_config = {"extra": "forbid"}
 
497
  # worker's poll interval is max(2 s, poll_cycle_s / its agents).
498
  poll_cycle_s: float | None = Field(default=None, ge=10, le=3600) # unset: 300
499
  url: str
500
+ # `space`: `legion init` duplicates `template` into a private per-run Space (`space`, default
501
  # `<template namespace>/board-<swarm>`) and fills BOARD_URL and the invite (docs/comms.md).
502
  # A url: the same as `url:`. Unset: `url` names an existing board.
503
  board: str | None = None
 
506
  # Space secret -> the run.env (or environment) name holding its value, e.g. {HF_TOKEN:
507
  # BOARD_BUCKET_TOKEN}: a token scoped to the board's bucket, never the operator's own.
508
  space_secrets: dict[str, str] = Field(default_factory=dict)
509
+ # Space variables over legion's (MSGBOARD_REPLICA: `<bucket>/board/<swarm>`); "" blanks one.
510
  space_variables: dict[str, str] = Field(default_factory=dict)
511
  space_hardware: str = "cpu-basic" # the Hub requires one to duplicate a Space
512
  invite_env: str # secret holding a multi-use agent invite (the code never goes in the spec)
513
  channel: str # name, with or without `#`
514
  kickoff_file: str | None = None
515
+ kickoff: str | None = None # the file's text, inlined by `legion launch` (or given inline)
516
  rules: CommsRules = Field(default_factory=CommsRules)
517
  protocols: list[str] = Field(default_factory=list) # files appended to the instructions
518
+ protocols_text: list[str] = Field(default_factory=list) # inlined by `legion launch`
519
  wake: list[Literal["mention", "thread", "dm", "channel"]] = Field(default_factory=lambda: ["mention", "thread"])
520
  search: Literal["board", "index"] | None = "board"
521
  # Written by the controller at apply; anything given by hand is replaced.
 
572
 
573
  def board_url_default(data: Any) -> Any:
574
  """`comms.board` -> `comms.url` in raw spec data, before ${VAR} substitution: `space` reads
575
+ BOARD_URL (written by `legion init`), a url is the url. An explicit `url` wins."""
576
  c = data.get("comms") if isinstance(data, dict) else None
577
  if isinstance(c, dict) and c.get("board") and "url" not in c:
578
  c["url"] = "${BOARD_URL}" if c["board"] == "space" else c["board"]
 
594
 
595
 
596
  class DashboardSpec(BaseModel):
597
+ """Swarm-level `dashboard:` (docs/dashboard.md): `legion init` writes the run's flock-overview
598
  row to `<registry>/runs/<id>.json` (id: default the swarm). The other row keys are derived from the spec."""
599
 
600
  model_config = {"extra": "forbid"}
 
631
 
632
  model_config = {"extra": "forbid"}
633
 
634
+ dir: str | None = None # relative to the spec file; `legion launch` resolves it
635
+ command: list[str] | None = None # `{port}` and `{python}` are filled in by legion
636
  url: str | None = None
637
  token_env: str | None = None
638
  # Written by the controller at apply; anything given by hand is replaced.
639
  endpoint: str | None = None
640
  manifest: WorldManifest | None = None
641
  # Which credential this configuration belongs to, without the credential: the origin it is
642
+ # bound to (`endpoint`, or `local:<swarm>` for a world legion started) and
643
  # HMAC(secret, origin). A worker sends its secret only when its own HMAC matches.
644
  credential_origin: str | None = None
645
  credential_id: str | None = None
 
647
  # world waiting for a node (PENDING) is told apart from a crashed one (docs/health.md).
648
  slurm_job_name: str | None = None
649
  # Seconds the world may be down (health probe) before the controller pauses the types that
650
+ # use it; resumed when it is back (docs/health.md). None: LEGION_WORLD_DOWN_PAUSE_S or 1800;
651
  # 0: never. Controller only (not sent to workers).
652
  down_pause_s: float | None = Field(default=None, ge=0)
653
 
 
660
  v = shlex.split(v)
661
  if v is not None and (not isinstance(v, list) or not v):
662
  raise ValueError("command must be a non-empty list (or a string), e.g. "
663
+ "[legion, world, serve, \"taskboard:TaskBoard\"]")
664
  return [str(x) for x in v] if v is not None else None
665
 
666
  @field_validator("url", "endpoint")
 
681
  @model_validator(mode="after")
682
  def _how(self) -> WorldSpec:
683
  if self.command is None and self.url is None:
684
+ raise ValueError("world needs `command` (started by legion, compute: local) or `url` "
685
  "(a world already running)")
686
  if self.dir is not None and self.command is None:
687
  raise ValueError("world.dir is where `command` runs; give the command too")
 
733
 
734
 
735
  class MemoryKnobs(BaseModel):
736
+ """Worker memory thresholds, passed through as the LEGION_MEM_* settings (worker.main)."""
737
 
738
  model_config = {"extra": "forbid"}
739
 
 
748
 
749
  model_config = {"extra": "forbid"}
750
 
751
+ drain_budget_s: float | None = Field(default=None, gt=0) # LEGION_DRAIN_BUDGET_S
752
  sync_interval_s: float | None = Field(default=None, ge=10) # SYNC_INTERVAL
753
+ sync_exclude: list[str] | None = None # LEGION_SYNC_EXCLUDE (added to the defaults)
754
+ restore_batch: int | None = Field(default=None, ge=1) # LEGION_RESTORE_BATCH
755
+ restore_threads: int | None = Field(default=None, ge=1, le=32) # LEGION_RESTORE_THREADS
756
  memory: MemoryKnobs | None = None
757
 
758
 
 
844
 
845
  class HarborSpec(BaseModel):
846
  """A `harness: harbor` type's Trial inputs, written by the compile step
847
+ (`legion.harbor.spec.compile_spec`), never by hand: each agent is one long-lived Harbor Trial
848
  on the upstream Harbor task path. The worker composes the agent's instructions from `team`,
849
  `role_text`, `roster` and the tools with the upstream `build_agent_instructions`."""
850
 
851
  model_config = {"extra": "forbid"}
852
 
853
  task: dict[str, Any] # ResolvedTask.manifest(): registry commit, dataset, the pinned task
854
+ # a partial legion.harbor Spec (model, inference, task, environment, limits, tools_dir,
855
  # tools, resources_dir) for the upstream build_trial_config and the worker's HarborHost
856
  config: dict[str, Any]
857
  team: str = "" # the team_file's text
 
863
  tools: dict[str, Any] = Field(default_factory=dict) # the tool bundle's manifest
864
  tools_sha256: str | None = None
865
  resources: dict[str, dict[str, Any]] = Field(default_factory=dict) # resource options
866
+ # the content hash of the run's tools and resources folders, packed by `legion launch` and
867
  # uploaded as the swarm's tools bundle of that version: a worker fetches and unpacks it in
868
  # its own run dir (None: config's tools_dir and resources_dir, read where they are)
869
  folders: str | None = None
 
877
  """One agent type inside a swarm. See design.md 'Spec'."""
878
 
879
  harness: Harness
880
+ # A Hub id; with `urls`, the name the servers serve it under (design.md 'Inference')
881
+ model: str = Field(min_length=1)
882
+ # Its own endpoints (a whole block); None: the swarm's `inference`
883
+ inference: Inference | None = None
884
+ # [input, output, cached] USD per 1M tokens of `model`; None: $0
885
+ pricing: list[float] | None = None
886
+ reasoning: Reasoning | None = None
887
  image: str | None = None # None -> default worker image
888
  system_prompt_file: str | None = None # written into the workdir as AGENTS.md
889
+ # The file's contents, inlined by `legion launch` (the controller and workers cannot
890
  # read the caller's files). Wins over system_prompt_file on the worker.
891
  system_prompt: str | None = None
892
+ # A second file appended to the system prompt by `legion launch` (after a blank line): a
893
  # per-type section on top of a prompt several types share (e.g. a spawner and its
894
  # child types). The worker only sees the combined `system_prompt`.
895
  system_prompt_append_file: str | None = None
 
927
  worker: WorkerKnobs | None = None # None: the worker's env, then built-in defaults
928
  resume_prompt: str | None = None
929
  # Tools from the swarm's tools folder: a list of function names, or "all".
930
+ # `legion launch` refuses a name the folder does not define. None: no folder tools.
931
  tools: list[str] | Literal["all"] | None = None
932
  # Re-prompt this type's agents on a cadence, then a final round (docs/loop.md). None: off.
933
  loop: LoopSpec | None = None
 
967
 
968
  @property
969
  def harness_model(self) -> str:
970
+ """The model id the harness reports usage under (what legion prices)."""
971
  return self.resolved_model.model_id if self.resolved_model else self.model
972
 
973
+ @field_validator("pricing")
974
+ @classmethod
975
+ def _price_row(cls, v: list[float] | None) -> list[float] | None:
976
+ return None if v is None else _pricing_row(v, "pricing")
977
+
978
  @property
979
  def provider_name(self) -> str | None:
980
  return self.resolved_model.provider_name if self.resolved_model else None
 
1014
  raise ValueError("ephemeral: true is for spawned agents only; set replicas: 0")
1015
  if self.harbor is None:
1016
  raise ValueError("harness harbor needs the `harbor:` block (written by the compile "
1017
+ "step of a legion.harbor spec)")
1018
  return self
1019
 
1020
  @field_validator("workers")
 
1072
 
1073
  class ComputeSpec(BaseModel):
1074
  """Where workers run (docs/local.md). `hf-jobs` (the default): one HF Job per worker.
1075
+ `local`: one `python -m legion.worker.main` subprocess per worker on the controller's machine
1076
+ (`legion launch` runs them on this machine). `slurm`: one `sbatch` job per worker (docs/slurm.md).
1077
  The spec also accepts the short form `compute: local`.
1078
 
1079
  `worker_unknown_after`, `worker_dead_after` and `crash_backoff` are for every backend
1080
  (docs/live.md "Worker liveness"). The other keys are for `slurm` and win over the
1081
+ controller's LEGION_SLURM_* env, which only fills unset keys (then built-in defaults).
1082
  `types` sets per-type `cpus`/`mem`/`time`/`partition` (an interviewer type needs less
1083
  than an agent)."""
1084
 
 
1095
  launch_dir: str | None = None # shared dir: <worker id>-<incarnation>.env, no secrets
1096
  host_file: str | None = None # shared file holding the controller's hostname
1097
  run: str | None = None # RUN= in the env file; default: the launch_dir's parent dir name
1098
+ venv: str | None = None # written to the env file as LEGION_VENV for the script
1099
+ secrets_file: str | None = None # path only, as LEGION_SECRETS_FILE; never read by legion
1100
  # workers run in a container whose /tmp is RAM: every agent/harness path goes under this
1101
+ # root instead: <root>/legion/<worker id>/{work,home,hf,tmp}
1102
  container_root: str | None = None
1103
+ container_image: str | None = None # an Enroot image (.sqsh): LEGION_CONTAINER_IMAGE
1104
 
1105
  @model_serializer(mode="wrap")
1106
  def _compact(self, handler: Any) -> Any:
 
1112
  types: dict[str, SlurmResources] = Field(default_factory=dict)
1113
  # the largest job the partition can ever run: sbatch accepts bigger ones, which then pend
1114
  # forever; a launch over these is refused (also checked at apply). None: not checked (the
1115
+ # controller's LEGION_SLURM_MAX_CPUS/_MEM, from the cluster profile, still apply at launch)
1116
  max_cpus: int | None = Field(default=None, ge=1)
1117
  max_mem: str | None = None
1118
  # worker liveness (docs/live.md "Worker liveness"); None: the backend's default (`liveness`)
 
1151
 
1152
  class SwarmSpec(BaseModel):
1153
  swarm: str
1154
+ # Billing account for Jobs, sandboxes and router calls. Empty: each token's account;
1155
+ # stays empty in the stored spec, so the router never gets an inferred bill-to.
1156
+ namespace: Namespace = ""
1157
+ bucket_id: BucketId = ""
1158
+ # Where the types' models run (design.md 'Inference'), unless a type sets its own
1159
+ inference: Inference = Field(default_factory=Inference)
1160
+ stop_on_success: bool = False
1161
  types: dict[str, TypeSpec]
1162
  # The tools folder, relative to the spec file; None: `tools/` next to it.
1163
+ # Read by `legion launch` only.
1164
  tools_dir: str | None = None
1165
+ # Content hash of the tools bundle, written by `legion launch` after uploading the folder
1166
  # (anything given by hand is replaced). Workers fetch that version; None: no tools.
1167
  tools_version: str | None = None
1168
  # The team's message board (docs/comms.md); None: no comms.
 
1182
  @classmethod
1183
  def _valid_tools_version(cls, v: str | None) -> str | None:
1184
  if v is not None and not TOOLS_VERSION_RE.match(v):
1185
+ raise ValueError("tools_version is written by `legion launch` (16 hex digits)")
 
 
 
 
 
 
 
 
1186
  return v
1187
 
1188
  @model_validator(mode="after")
1189
  def _resolve_models(self) -> SwarmSpec:
1190
+ """Apply-time pinning: each type's inference block and price go into the spec
1191
+ (`resolved_model`), so the stored spec carries what admission and cost derive from. The
1192
+ context window the controller pinned stays while the block (but `max_working`, the
1193
+ controller's) and the model are the same, and so do the hf_jobs servers' `urls`."""
1194
+ if self.stop_on_success and not any(
1195
+ ts.harbor and ts.harbor.config.get("success_check") for ts in self.types.values()):
1196
+ raise ValueError("stop_on_success requires a Harbor success_check")
 
 
 
 
 
 
1197
  for type_name, ts in self.types.items():
1198
+ old, ts.resolved_model = ts.resolved_model, resolve_model(self, ts, type_name=type_name)
1199
+ new = ts.resolved_model
1200
+ if old is not None and (old.inference.unpinned().held(), old.model_id) == (
1201
+ new.inference.held(), new.model_id):
1202
+ new.context_window = old.context_window
1203
+ if new.inference.hf_jobs is not None:
1204
+ new.inference = new.inference.model_copy(update={"urls": old.inference.urls})
 
 
 
 
 
 
 
 
1205
  for type_name, ts in self.types.items():
1206
  cap = ts.loop.while_.agent_usd if ts.loop else None
1207
  if isinstance(cap, dict) and agent_cap(ts) is None:
1208
  raise ValueError(
1209
  f"types.{type_name}.loop.while.agent_usd: no entry for model {ts.model!r} "
1210
+ f"(keys: {sorted(cap)}); key it by the type's model id")
1211
  return self
1212
 
1213
  @model_validator(mode="after")
 
1232
  "(command or url)")
1233
  if ts.world is False and listed:
1234
  raise ValueError(f"types.{name}: world: false but tools lists {', '.join(listed)}")
1235
+ if self.dashboard is not None and (self.compute.kind == "local" or not self.bucket_id):
1236
+ raise ValueError("dashboard: needs the run's state in a bucket (`bucket_id:`, compute "
1237
  "hf-jobs or slurm); compute: local keeps it on this machine")
1238
  c = self.comms
1239
  if c is not None and c.protocols_text and len(c.protocols_text) != len(c.protocols):
1240
+ raise ValueError("comms.protocols_text is written by `legion launch` (one per protocols file)")
1241
  return self
1242
 
1243
  @field_validator("swarm")
 
1271
  raise ValueError(f"types.{name}.env.HEARTBEAT_INTERVAL ({hb:g}s): two heartbeats "
1272
  f"({2 * hb:g}s) exceed worker_unknown_after ({unknown:g}s); "
1273
  f"raise worker_unknown_after or lower the interval")
1274
+ if kind != "local" and not self.bucket_id:
 
 
 
 
 
1275
  # agent state goes to an HF bucket on every remote backend, never to a shared disk
1276
+ raise ValueError(f"bucket_id is required for compute {kind}")
1277
  if kind != "local" and self.world is not None and self.world.url is None:
1278
  raise ValueError(f"world.url is required for compute {kind}: run the world as a "
1279
  "Job, Space or cluster job and give its url (starting it from "
 
1288
  unknown = set(self.compute.types) - set(self.types)
1289
  if unknown:
1290
  raise ValueError(f"compute.types names unknown types: {sorted(unknown)}")
1291
+ for ts in self.types.values(): # who must reach the servers: the agents (docs/open-models.md)
1292
+ r, backend = ts.resolved_model, ts.harbor and ts.harbor.config.get("environment", {})
1293
+ backend = (backend or {}).get("backend")
1294
+ for url in (r.inference.urls or []) if r else []:
1295
+ if (kind == "hf-jobs" or backend in ("hf-sandbox", "e2b")) and private_url(url):
1296
+ raise ValueError(
1297
+ f"{r.provider_name}.urls: {url} is this machine or a private network, "
1298
+ "which sandboxes and HF Jobs workers cannot reach: serve the model at "
1299
+ "a public URL")
1300
+ if kind == "slurm" and loopback_url(url):
1301
+ raise ValueError(
1302
+ f"{r.provider_name}.urls: {url} would be each worker's own node under "
1303
+ "compute slurm: list the server node's address")
1304
  return self
1305
 
1306
+ def inference_blocks(self) -> dict[str, Inference]:
1307
+ """The inference blocks the types run on, by name (`inference`, `types.<t>.inference`)."""
1308
+ return {ts.resolved_model.provider_name: ts.resolved_model.inference
1309
+ for ts in self.types.values() if ts.resolved_model is not None}
1310
+
1311
  @field_validator("spawn")
1312
  @classmethod
1313
  def _valid_spawn(cls, v: dict[str, SpawnRule], info) -> dict[str, SpawnRule]:
 
1325
  return v
1326
 
1327
 
1328
+ def resolve_model(spec: SwarmSpec, type_spec: TypeSpec, *, type_name: str = "?") -> ResolvedModel:
1329
+ """A type's `model` on its inference block (its own, else the swarm's), with its price
1330
+ (`pricing`, else $0). Raises ValueError for a model id the HF router cannot take."""
1331
+ inference = type_spec.inference or spec.inference
1332
+ model = type_spec.model
1333
+ if inference.hf_jobs is not None and inference.urls is not None:
1334
+ where = f"types.{type_name}.inference" if type_spec.inference else "inference"
1335
+ raise ValueError(f"{where}: set one of hf_router, urls or hf_jobs, not urls and hf_jobs "
1336
+ "(legion pins the started servers' urls itself)")
1337
+ if inference.hf_router is not None and (model.startswith("huggingface/") or ":" in model):
1338
+ raise ValueError(f"types.{type_name}.model: {model!r}: the HF router takes a plain Hub id "
1339
+ "(e.g. Qwen/Qwen3.8-27B); name the provider in "
1340
+ "inference.hf_router.provider")
 
 
 
 
 
 
 
 
 
 
 
 
1341
  return ResolvedModel(
1342
+ provider_name=f"types.{type_name}.inference" if type_spec.inference else "inference",
1343
+ inference=inference,
1344
+ headers={"X-HF-Bill-To": spec.namespace}
1345
+ if inference.hf_router is not None and spec.namespace else {},
1346
+ model_id=model,
1347
+ reasoning=type_spec.reasoning,
1348
+ pricing=list(type_spec.pricing or ZERO_PRICING),
1349
  )
1350
 
1351
 
 
1545
  model_config = {"extra": "forbid"}
1546
 
1547
  prompt: str | None = None
1548
+ prompt_file: str | None = None # inlined into `prompt` by `legion launch`
1549
  reserve_usd: float = 0.0
1550
 
1551
  @field_validator("reserve_usd")
 
1600
  model_config = {"extra": "forbid", "populate_by_name": True}
1601
 
1602
  prompt: str | None = None
1603
+ prompt_file: str | None = None # inlined into `prompt` by `legion launch`
1604
  every: str = "turn_end"
1605
  on: list[str] = Field(default_factory=list) # message_board.mention, world.event:*
1606
  while_: LoopWhile = Field(default_factory=LoopWhile, alias="while")
 
1677
 
1678
  def loop_refusals(spec: SwarmSpec) -> list[str]:
1679
  """Loop settings this version accepts in the model but cannot run: world-backed wakes and
1680
+ prompt files not inlined. `legion launch` and the controller refuse a spec with any of them."""
1681
  out: list[str] = []
1682
  for name, ts in spec.types.items():
1683
  lp = ts.loop
 
1686
  where = f"types.{name}.loop"
1687
  out += [f"{where}.on: {x} {NEEDS_WORLD}" for x in lp.on if x.startswith("world.")]
1688
  if lp.prompt is None:
1689
+ out.append(f"{where}.prompt_file: not inlined (use `legion launch`, which reads it)")
1690
  if lp.final is not None and lp.final.prompt is None:
1691
+ out.append(f"{where}.final.prompt_file: not inlined (use `legion launch`, which reads it)")
1692
  return out
1693
 
1694
 
 
1747
 
1748
 
1749
  class WorkerMem(BaseModel):
1750
+ """The worker's cgroup memory (MB) at its last sample (legion.worker.cgroup)."""
1751
 
1752
  current_mb: float | None = None
1753
  limit_mb: float | None = None # None: no limit found, nothing is armed
 
1800
  restore: RestoreProgress | None = None # None when no restore is in flight
1801
  tools: dict[str, ToolCounters] | None = None # world tools by name
1802
  knobs_rev: str | None = None # hash of the worker's effective settings
1803
+ # nonreclaimable memory passed LEGION_MEM_ROTATE of the limit: the controller drains the
1804
  # worker when its rotation budget allows (docs/slurm.md "Memory")
1805
  wants_rotation: bool = False
1806
  # agents whose last push to the bucket failed (retried once), with the error; the drain's
1807
+ # final heartbeat carries them so `legion stop --release` can name them
1808
  unsynced: dict[str, str] = Field(default_factory=dict)
1809
 
1810
 
1811
  class Event(BaseModel):
1812
  """One line of an agent's event stream.
1813
 
1814
+ The on-disk / over-the-wire shape is pi session format v3 (legion.worker.events
1815
+ documents the encoding). `type`, `ts`, `agent` are required by us;
1816
  the rest of the pi record lives in `data`. Harness-neutral types the worker adds:
1817
  session_started, session_resumed, session_restarted, turn_started, turn_ended,
1818
  turn_interrupted, sync.
 
1908
  restore: bool = True # restore workdir + session from bucket before first prompt
1909
  resume_prompt: str | None = None # sent once after restore when a turn was interrupted
1910
  parent: str | None = None # the spawning agent, None for a replica
1911
+ # The agent's scoped controller token, injected into its harness env as LEGION_AGENT_TOKEN.
1912
  agent_token: str | None = None
1913
  tools_version: str | None = None # the swarm's tools bundle; None: no tools
1914
  comms: CommsSpec | None = None # the swarm's comms block (docs/comms.md), channel resolved
 
2004
  type: str
2005
  harness: Harness
2006
  model: str
2007
+ provider: str | None = None # its inference block's name (ResolvedModel.provider_name)
2008
  labels: dict[str, str]
2009
  state: AgentState
2010
  idle_since: datetime | None = None
 
2085
 
2086
 
2087
  class ProviderStatus(BaseModel):
2088
+ """An inference block the types run on (`SwarmSpec.inference_blocks`)."""
2089
+
2090
+ name: str # `inference`, or `types.<t>.inference` for a type's own
2091
+ endpoint: str # Inference.describe(): `hf_router deepinfra` or the URLs
2092
+ types: list[str] # agent types on it
2093
+ # each of their models -> the context window pinned at apply (None: not pinned yet)
2094
+ models: dict[str, int | None] = Field(default_factory=dict)
2095
  working: int # agents of those types in a turn now (from heartbeats)
2096
+ max_working: int | None = None # enforced at prompt admission unless LEGION_MAX_WORKING_ENFORCE=0
2097
  # Agents with turns but zero reported tokens: the server sends no usage, cost is unknown.
2098
  zero_usage_agents: int = 0
2099
 
2100
 
2101
+ class ServerStatus(BaseModel):
2102
+ """One server legion started for an inference block (`hf_jobs`, controller/servers.py): a
2103
+ replica of one model's group."""
2104
+
2105
+ model: str
2106
+ kind: str # the block kind that started it: hf_jobs
2107
+ group: str # the group's key (its jobs' `inference` label)
2108
+ types: list[str] # the agent types it serves
2109
+ flavor: str
2110
+ namespace: str
2111
+ replica: int
2112
+ job_id: str | None = None
2113
+ url: str | None = None # the OpenAI base URL (`.../v1`)
2114
+ stage: str | None = None # the job's: SCHEDULING, RUNNING, COMPLETED, CANCELED, ERROR, ...
2115
+ message: str | None = None # the job's status message (e.g. waiting for hardware)
2116
+ # starting (the job is scheduled or the server does not answer yet), ready (it answers
2117
+ # GET /v1/models), failed (the job ended or never answered: `error`), stopped (cancelled)
2118
+ state: Literal["starting", "ready", "failed", "stopped"]
2119
+ started_at: datetime | None = None # the job's creation
2120
+ ready_at: datetime | None = None
2121
+ error: str | None = None
2122
+
2123
+
2124
  class SwarmStatus(BaseModel):
2125
  swarm: str
2126
  namespace: str
2127
+ bucket_id: str
2128
  types: dict[str, TypeStatus]
2129
  providers: dict[str, ProviderStatus] = Field(default_factory=dict)
2130
+ servers: list[ServerStatus] = Field(default_factory=list) # hf_jobs servers legion started
2131
  agents_total: int
2132
  workers_total: int
2133
  pending_prompts: int
 
2138
  # pause holds (docs/loop.md "Pause and resume"): {types: {T: {since, reason, by, auto}},
2139
  # agents: {A: ...}}; None when nothing is held
2140
  held: dict[str, dict[str, dict[str, Any]]] | None = None
2141
+ # `legion stop --release`: {since, reason, unsynced: {agent: error}}; None when not released
2142
  released: dict[str, Any] | None = None
2143
  # bumped by every apply that changes the spec (docs/live.md)
2144
+ success: dict[str, Any] | None = None
2145
  generation: int | None = None
2146
 
2147
 
 
2156
  class PreflightResult(BaseModel):
2157
  """One provider-backed model probed with a tool call and a follow-up turn."""
2158
 
2159
+ model: str # "<inference block>:<model id>" (ResolvedModel.qualified)
2160
+ provider: str # the inference block's name
2161
  types: list[str]
2162
  # "responses" (openai_compat) | "messages" (anthropic) |
2163
  # "chat_completions" (openai_compat; Harbor's Pi)
world/src/{flock → legion}/registry.py RENAMED
@@ -14,24 +14,29 @@ from typing import Any
14
  class HarnessEntry:
15
  adapter: str # "module:function"; function(workdir, agent name, TypeSpec) -> HarnessAdapter
16
  # (harbor's also takes `host=`, the worker's HarborHost)
17
- provider_type: str # the provider `type` a provider-backed model must have
18
- api: str # the wire API it speaks to that provider (preflight probes this one)
19
 
20
 
21
  HARNESSES: dict[str, HarnessEntry] = {
22
- # one Harbor Trial per agent on the upstream Harbor task path (flock.harbor). Harbor installs Pi
23
- # (flock.harbor.config.PI_VERSION) in the task's container and the Trial delivers the
24
  # instructions
25
- "harbor": HarnessEntry("flock.worker.adapters.harbor:make_adapter", "openai_compat",
26
- "chat_completions"),
27
  }
28
 
29
- # `compute.kind` / FLOCK_COMPUTE -> "module:function"; function(env, deployment, data_dir) ->
30
  # JobsClient. The function also rejects a controller setup the backend cannot run in.
31
  COMPUTE: dict[str, str] = {
32
- "hf-jobs": "flock.controller.jobs:hub_jobs_client",
33
- "local": "flock.controller.local:local_jobs_client", # docs/local.md
34
- "slurm": "flock.controller.slurm:slurm_jobs_client", # docs/slurm.md
 
 
 
 
 
 
 
35
  }
36
 
37
 
 
14
  class HarnessEntry:
15
  adapter: str # "module:function"; function(workdir, agent name, TypeSpec) -> HarnessAdapter
16
  # (harbor's also takes `host=`, the worker's HarborHost)
17
+ api: str # the wire API it speaks to its inference endpoints (preflight probes this one)
 
18
 
19
 
20
  HARNESSES: dict[str, HarnessEntry] = {
21
+ # one Harbor Trial per agent on the upstream Harbor task path (legion.harbor). Harbor installs Pi
22
+ # (legion.harbor.config.PI_VERSION) in the task's container and the Trial delivers the
23
  # instructions
24
+ "harbor": HarnessEntry("legion.worker.adapters.harbor:make_adapter", "chat_completions"),
 
25
  }
26
 
27
+ # `compute.kind` / LEGION_COMPUTE -> "module:function"; function(env, deployment, data_dir) ->
28
  # JobsClient. The function also rejects a controller setup the backend cannot run in.
29
  COMPUTE: dict[str, str] = {
30
+ "hf-jobs": "legion.controller.jobs:hub_jobs_client",
31
+ "local": "legion.controller.local:local_jobs_client", # docs/local.md
32
+ "slurm": "legion.controller.slurm:slurm_jobs_client", # docs/slurm.md
33
+ }
34
+
35
+ # Inference servers legion starts itself: the `inference` block's key -> "module:function";
36
+ # function(env) -> a Starter (legion.controller.servers), which starts a model's servers (or
37
+ # reattaches to the running ones), checks them until they answer, and stops them
38
+ SERVERS: dict[str, str] = {
39
+ "hf_jobs": "legion.controller.hf_jobs_servers:hf_jobs_servers", # docs/open-models.md
40
  }
41
 
42
 
world/src/{flock → legion}/tools/__init__.py RENAMED
@@ -12,7 +12,7 @@ from __future__ import annotations
12
  from dataclasses import dataclass, field
13
  from pathlib import Path
14
 
15
- READONLY_ATTR = "__flock_readonly__"
16
 
17
 
18
  @dataclass
@@ -47,7 +47,7 @@ class ToolError(Exception):
47
 
48
  def readonly[F](fn: F) -> F:
49
  """Mark a tool as read-only (`readonly: true` in the manifest): it changes no state.
50
- Informational: nothing in flock acts on it."""
51
  setattr(fn, READONLY_ATTR, True)
52
  return fn
53
 
 
12
  from dataclasses import dataclass, field
13
  from pathlib import Path
14
 
15
+ READONLY_ATTR = "__legion_readonly__"
16
 
17
 
18
  @dataclass
 
47
 
48
  def readonly[F](fn: F) -> F:
49
  """Mark a tool as read-only (`readonly: true` in the manifest): it changes no state.
50
+ Informational: nothing in legion acts on it."""
51
  setattr(fn, READONLY_ATTR, True)
52
  return fn
53
 
world/src/{flock → legion}/tools/loader.py RENAMED
@@ -4,12 +4,12 @@ Every `*.py` file at the top of the folder whose name does not start with `_` is
4
  Every function defined in it (not imported) whose name does not start with `_` and that has a
5
  docstring is a tool: name = function name, description = the docstring's first paragraph,
6
  parameters = a JSON schema built from the type hints (descriptions from an `Args:` section).
7
- A parameter named `ctx`, or annotated `flock.tools.Context`, is injected at call time and
8
  never shown to the model.
9
 
10
  `load_dir` imports the modules in this process; `describe` runs it in a fresh `python -I`
11
- subprocess (what `flock launch` uses), so a module's side effects, crashes and hangs stay
12
- there. `python -m flock.tools.loader <dir>` prints the manifest as JSON.
13
  """
14
 
15
  from __future__ import annotations
@@ -26,7 +26,7 @@ from dataclasses import asdict, dataclass, field
26
  from pathlib import Path
27
  from typing import Any
28
 
29
- from flock.tools import READONLY_ATTR, Context
30
 
31
  NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
32
  CTX_NAME = "ctx"
@@ -48,7 +48,7 @@ class ToolDef:
48
  is_async: bool = False
49
  # A built-in served by the worker itself, not the folder (`comms:post`, docs/comms.md).
50
  builtin: str | None = None
51
- # Changes nothing (`@flock.tools.readonly`; informational). In the manifest only when true.
52
  readonly: bool = False
53
 
54
  def openai(self) -> dict[str, Any]:
@@ -273,7 +273,7 @@ def describe(folder: str | Path, *, python: str | None = None,
273
  folder = Path(folder).resolve()
274
  if not folder.is_dir():
275
  raise ToolsError(f"tools folder {folder} does not exist")
276
- cmd = [python or sys.executable, "-I", "-B", "-m", "flock.tools.loader", str(folder)]
277
  try:
278
  p = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=timeout,
279
  cwd=str(folder.parent), stdin=subprocess.DEVNULL)
@@ -308,7 +308,7 @@ def select(manifest: Manifest, wanted: list[str] | str | None, *, where: str = "
308
 
309
  def _main(argv: list[str]) -> int:
310
  if len(argv) != 1:
311
- print(json.dumps({"error": "usage: python -m flock.tools.loader <tools dir>"}))
312
  return 2
313
  import contextlib
314
  import io
 
4
  Every function defined in it (not imported) whose name does not start with `_` and that has a
5
  docstring is a tool: name = function name, description = the docstring's first paragraph,
6
  parameters = a JSON schema built from the type hints (descriptions from an `Args:` section).
7
+ A parameter named `ctx`, or annotated `legion.tools.Context`, is injected at call time and
8
  never shown to the model.
9
 
10
  `load_dir` imports the modules in this process; `describe` runs it in a fresh `python -I`
11
+ subprocess (what `legion launch` uses), so a module's side effects, crashes and hangs stay
12
+ there. `python -m legion.tools.loader <dir>` prints the manifest as JSON.
13
  """
14
 
15
  from __future__ import annotations
 
26
  from pathlib import Path
27
  from typing import Any
28
 
29
+ from legion.tools import READONLY_ATTR, Context
30
 
31
  NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
32
  CTX_NAME = "ctx"
 
48
  is_async: bool = False
49
  # A built-in served by the worker itself, not the folder (`comms:post`, docs/comms.md).
50
  builtin: str | None = None
51
+ # Changes nothing (`@legion.tools.readonly`; informational). In the manifest only when true.
52
  readonly: bool = False
53
 
54
  def openai(self) -> dict[str, Any]:
 
273
  folder = Path(folder).resolve()
274
  if not folder.is_dir():
275
  raise ToolsError(f"tools folder {folder} does not exist")
276
+ cmd = [python or sys.executable, "-I", "-B", "-m", "legion.tools.loader", str(folder)]
277
  try:
278
  p = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=timeout,
279
  cwd=str(folder.parent), stdin=subprocess.DEVNULL)
 
308
 
309
  def _main(argv: list[str]) -> int:
310
  if len(argv) != 1:
311
+ print(json.dumps({"error": "usage: python -m legion.tools.loader <tools dir>"}))
312
  return 2
313
  import contextlib
314
  import io
world/src/{flock → legion}/worker/__init__.py RENAMED
File without changes
world/src/{flock → legion}/worker/sync.py RENAMED
@@ -1,4 +1,4 @@
1
- """Bucket sync: per agent, `<BUCKET>/<swarm>/<type>/<agent>/` holds
2
 
3
  workdir/<path relative to the workdir> (if persist_workdir; the deltas with a base)
4
  workdir.base.tar, workdir.base.json (only with the type's workdir.base, below)
@@ -13,9 +13,9 @@ same absolute paths (workdir and work root are fixed, harness homes are fixed by
13
  before the first resume.
14
 
15
  Restore lists the agent's prefix once, then downloads every file it found in batches
16
- (`restore_batch()`: env `FLOCK_RESTORE_BATCH`, default 1000, minimum 1, an invalid value
17
- means the default), `restore_threads()` batches at a time (env `FLOCK_RESTORE_THREADS`,
18
- default 4; the type's `worker:` block overrides both), each to a `.flock-part` sibling renamed into place on success. A batch that
19
  fails is retried file by file, with backoff (`RESTORE_BACKOFF`) between rounds: one unreadable
20
  file is skipped and reported in `RestoreResult.failed` instead of aborting the whole restore. A
21
  permanent "not found" (HTTP 404, e.g. xet "CAS Client Error: ... 404 Not Found" on the
@@ -25,7 +25,7 @@ logged as one summary line per agent. Only a failed listing makes `restore` rais
25
 
26
  Buckets store bytes, not file modes: a restored file comes back 0644, so an executable script
27
  would stop running after a move. Each
28
- push therefore writes `<workdir>/.flock-modes.json` ({relative path: octal mode} for every file
29
  with an executable bit) when it changed, and restore re-applies it after the workdir download.
30
 
31
  Push safety (a periodic sync must never mirror a half-restored workdir over the bucket copy,
@@ -41,10 +41,10 @@ deleting entries the in-flight restore has not fetched yet):
41
  agent). After a failed listing, a skipped file or an interrupted restore, pushes upload
42
  changed files but never delete, for as long as this worker holds the agent: a file it could
43
  not fetch stays in the bucket for the next restore.
44
- - `*.flock-part` (restore temporaries) is never uploaded nor deleted by a push; restore removes
45
  stray ones left by a crash.
46
  - Regenerable caches (`workdir_excludes`: `__pycache__/`, `*.pyc`, `node_modules/`, `.venv/`, ...; env
47
- FLOCK_SYNC_EXCLUDE adds globs, FLOCK_SYNC_EXCLUDE_DEFAULTS=0 drops the defaults) are neither
48
  uploaded nor deleted by the mirror, and restore skips them, also those already in the bucket.
49
  `.git/` and worktrees are never excluded by default.
50
  - The type's `workdir.ephemeral` dirs (root-relative) are excluded like the caches; the agent's
@@ -101,20 +101,20 @@ from datetime import UTC, datetime
101
  from pathlib import Path
102
  from typing import TYPE_CHECKING, Protocol
103
 
104
- from flock.models import WorkdirSpec
105
 
106
  if TYPE_CHECKING:
107
- from flock.models import TypeSpec
108
- from flock.worker.agents import AgentRuntime
109
 
110
  log = logging.getLogger(__name__)
111
 
112
  UPLOAD_CHUNK = 200
113
- MODES_FILE = ".flock-modes.json"
114
  BASE_TAR = "workdir.base.tar" # under the agent prefix (module docstring, "Base tar")
115
  BASE_JSON = "workdir.base.json"
116
- RESTORE_BATCH = 1000 # default of FLOCK_RESTORE_BATCH
117
- RESTORE_THREADS = 4 # default of FLOCK_RESTORE_THREADS
118
  # The type's `worker:` values for this module (sync_exclude, restore_batch, restore_threads),
119
  # set live by `Worker.apply_knobs`; each one present wins over its env variable.
120
  SPEC_KNOBS: dict[str, object] = {}
@@ -129,19 +129,19 @@ def _env_int(name: str, default: int, cap: int | None = None) -> int:
129
 
130
 
131
  def restore_batch() -> int:
132
- """Files per restore download batch: the spec's, else env FLOCK_RESTORE_BATCH (>= 1), else
133
  RESTORE_BATCH."""
134
- return SPEC_KNOBS.get("restore_batch") or _env_int("FLOCK_RESTORE_BATCH", RESTORE_BATCH)
135
 
136
 
137
  def restore_threads() -> int:
138
  """Batches of one agent's restore downloaded in parallel: the spec's, else env
139
- FLOCK_RESTORE_THREADS (>= 1), else RESTORE_THREADS."""
140
- return SPEC_KNOBS.get("restore_threads") or _env_int("FLOCK_RESTORE_THREADS", RESTORE_THREADS, 32)
141
 
142
 
143
  RESTORE_BACKOFF = (1.0, 4.0, 10.0) # seconds before each per-file retry round
144
- PART_SUFFIX = ".flock-part"
145
  PUSH_EXCLUDE = ["*" + PART_SUFFIX] # sync_bucket patterns, matched on relative paths
146
  # Regenerable caches left out of the workdir mirror and of restore (module docstring). A trailing
147
  # "/" names a directory at any depth (`workdir_excludes`); other entries are plain globs.
@@ -163,15 +163,15 @@ def _expand(pattern: str) -> list[str]:
163
 
164
 
165
  def workdir_excludes() -> list[str]:
166
- """Globs for the workdir mirror, relative to the workdir, always including `*.flock-part`:
167
- the defaults (unless env FLOCK_SYNC_EXCLUDE_DEFAULTS=0) plus the spec's `sync_exclude`, else
168
- the comma-separated FLOCK_SYNC_EXCLUDE. `.git/` is never in the defaults."""
169
  pats = list(PUSH_EXCLUDE)
170
- if os.environ.get("FLOCK_SYNC_EXCLUDE_DEFAULTS", "1").strip() != "0":
171
  pats += [x for d in DEFAULT_WORKDIR_EXCLUDE for x in _expand(d)]
172
  extra = SPEC_KNOBS.get("sync_exclude")
173
  if extra is None:
174
- extra = os.environ.get("FLOCK_SYNC_EXCLUDE", "").split(",")
175
  for item in extra:
176
  if item.strip():
177
  pats += _expand(item.strip())
@@ -563,7 +563,7 @@ def count_hub_http(stats: BucketStats) -> None:
563
 
564
 
565
  class BucketStore(Protocol):
566
- """Blocking bucket operations on paths relative to the flock root."""
567
 
568
  def upload(self, files: list[tuple[Path, str]]) -> None: ...
569
  def list(self, prefix: str) -> list[str]: ...
@@ -580,7 +580,7 @@ class BucketStore(Protocol):
580
 
581
  def sync_down(self, prefix: str, local: Path) -> None: ...
582
  def delete(self, paths: list[str]) -> None:
583
- """Delete files (paths relative to the flock root). Used by the controller's state."""
584
  ...
585
 
586
 
@@ -668,7 +668,7 @@ class RestoreResult:
668
  workdir: int = 0
669
  sessions: int = 0
670
  harness: int = 0
671
- # bucket paths (relative to the flock root) that could not be downloaded, after retries
672
  failed: list[str] = field(default_factory=list)
673
 
674
 
@@ -692,7 +692,7 @@ def download_resilient(store: BucketStore, files: list[tuple[str, Path]], *,
692
  progress=None) -> tuple[list[tuple[str, Path]], list[str]]:
693
  """Download (remote, local) pairs; returns (downloaded, failed remote paths). Never raises
694
  for a file: batches first, then the files of a failed batch one by one, retried after each
695
- delay in `backoff` unless the error is a permanent "not found" (`_permanent`). Each file lands in a `.flock-part` sibling, renamed into place only
696
  when it arrived, so a failed file never leaves a truncated copy at its real path.
697
  `progress(n)` is called with the number of files each attempt brought in (serialized: the
698
  first pass runs `restore_threads()` batches in parallel threads)."""
@@ -761,7 +761,7 @@ def download_resilient(store: BucketStore, files: list[tuple[str, Path]], *,
761
 
762
 
763
  def _clean_parts(root: Path) -> int:
764
- """Remove stray `.flock-part` files under `root` (a crash mid-download leaves them)."""
765
  n = 0
766
  if root.is_dir():
767
  for p in root.rglob("*" + PART_SUFFIX):
 
1
+ """Bucket sync: per agent, `<bucket_id>/<swarm>/<type>/<agent>/` holds
2
 
3
  workdir/<path relative to the workdir> (if persist_workdir; the deltas with a base)
4
  workdir.base.tar, workdir.base.json (only with the type's workdir.base, below)
 
13
  before the first resume.
14
 
15
  Restore lists the agent's prefix once, then downloads every file it found in batches
16
+ (`restore_batch()`: env `LEGION_RESTORE_BATCH`, default 1000, minimum 1, an invalid value
17
+ means the default), `restore_threads()` batches at a time (env `LEGION_RESTORE_THREADS`,
18
+ default 4; the type's `worker:` block overrides both), each to a `.legion-part` sibling renamed into place on success. A batch that
19
  fails is retried file by file, with backoff (`RESTORE_BACKOFF`) between rounds: one unreadable
20
  file is skipped and reported in `RestoreResult.failed` instead of aborting the whole restore. A
21
  permanent "not found" (HTTP 404, e.g. xet "CAS Client Error: ... 404 Not Found" on the
 
25
 
26
  Buckets store bytes, not file modes: a restored file comes back 0644, so an executable script
27
  would stop running after a move. Each
28
+ push therefore writes `<workdir>/.legion-modes.json` ({relative path: octal mode} for every file
29
  with an executable bit) when it changed, and restore re-applies it after the workdir download.
30
 
31
  Push safety (a periodic sync must never mirror a half-restored workdir over the bucket copy,
 
41
  agent). After a failed listing, a skipped file or an interrupted restore, pushes upload
42
  changed files but never delete, for as long as this worker holds the agent: a file it could
43
  not fetch stays in the bucket for the next restore.
44
+ - `*.legion-part` (restore temporaries) is never uploaded nor deleted by a push; restore removes
45
  stray ones left by a crash.
46
  - Regenerable caches (`workdir_excludes`: `__pycache__/`, `*.pyc`, `node_modules/`, `.venv/`, ...; env
47
+ LEGION_SYNC_EXCLUDE adds globs, LEGION_SYNC_EXCLUDE_DEFAULTS=0 drops the defaults) are neither
48
  uploaded nor deleted by the mirror, and restore skips them, also those already in the bucket.
49
  `.git/` and worktrees are never excluded by default.
50
  - The type's `workdir.ephemeral` dirs (root-relative) are excluded like the caches; the agent's
 
101
  from pathlib import Path
102
  from typing import TYPE_CHECKING, Protocol
103
 
104
+ from legion.models import WorkdirSpec
105
 
106
  if TYPE_CHECKING:
107
+ from legion.models import TypeSpec
108
+ from legion.worker.agents import AgentRuntime
109
 
110
  log = logging.getLogger(__name__)
111
 
112
  UPLOAD_CHUNK = 200
113
+ MODES_FILE = ".legion-modes.json"
114
  BASE_TAR = "workdir.base.tar" # under the agent prefix (module docstring, "Base tar")
115
  BASE_JSON = "workdir.base.json"
116
+ RESTORE_BATCH = 1000 # default of LEGION_RESTORE_BATCH
117
+ RESTORE_THREADS = 4 # default of LEGION_RESTORE_THREADS
118
  # The type's `worker:` values for this module (sync_exclude, restore_batch, restore_threads),
119
  # set live by `Worker.apply_knobs`; each one present wins over its env variable.
120
  SPEC_KNOBS: dict[str, object] = {}
 
129
 
130
 
131
  def restore_batch() -> int:
132
+ """Files per restore download batch: the spec's, else env LEGION_RESTORE_BATCH (>= 1), else
133
  RESTORE_BATCH."""
134
+ return SPEC_KNOBS.get("restore_batch") or _env_int("LEGION_RESTORE_BATCH", RESTORE_BATCH)
135
 
136
 
137
  def restore_threads() -> int:
138
  """Batches of one agent's restore downloaded in parallel: the spec's, else env
139
+ LEGION_RESTORE_THREADS (>= 1), else RESTORE_THREADS."""
140
+ return SPEC_KNOBS.get("restore_threads") or _env_int("LEGION_RESTORE_THREADS", RESTORE_THREADS, 32)
141
 
142
 
143
  RESTORE_BACKOFF = (1.0, 4.0, 10.0) # seconds before each per-file retry round
144
+ PART_SUFFIX = ".legion-part"
145
  PUSH_EXCLUDE = ["*" + PART_SUFFIX] # sync_bucket patterns, matched on relative paths
146
  # Regenerable caches left out of the workdir mirror and of restore (module docstring). A trailing
147
  # "/" names a directory at any depth (`workdir_excludes`); other entries are plain globs.
 
163
 
164
 
165
  def workdir_excludes() -> list[str]:
166
+ """Globs for the workdir mirror, relative to the workdir, always including `*.legion-part`:
167
+ the defaults (unless env LEGION_SYNC_EXCLUDE_DEFAULTS=0) plus the spec's `sync_exclude`, else
168
+ the comma-separated LEGION_SYNC_EXCLUDE. `.git/` is never in the defaults."""
169
  pats = list(PUSH_EXCLUDE)
170
+ if os.environ.get("LEGION_SYNC_EXCLUDE_DEFAULTS", "1").strip() != "0":
171
  pats += [x for d in DEFAULT_WORKDIR_EXCLUDE for x in _expand(d)]
172
  extra = SPEC_KNOBS.get("sync_exclude")
173
  if extra is None:
174
+ extra = os.environ.get("LEGION_SYNC_EXCLUDE", "").split(",")
175
  for item in extra:
176
  if item.strip():
177
  pats += _expand(item.strip())
 
563
 
564
 
565
  class BucketStore(Protocol):
566
+ """Blocking bucket operations on paths relative to the legion root."""
567
 
568
  def upload(self, files: list[tuple[Path, str]]) -> None: ...
569
  def list(self, prefix: str) -> list[str]: ...
 
580
 
581
  def sync_down(self, prefix: str, local: Path) -> None: ...
582
  def delete(self, paths: list[str]) -> None:
583
+ """Delete files (paths relative to the legion root). Used by the controller's state."""
584
  ...
585
 
586
 
 
668
  workdir: int = 0
669
  sessions: int = 0
670
  harness: int = 0
671
+ # bucket paths (relative to the legion root) that could not be downloaded, after retries
672
  failed: list[str] = field(default_factory=list)
673
 
674
 
 
692
  progress=None) -> tuple[list[tuple[str, Path]], list[str]]:
693
  """Download (remote, local) pairs; returns (downloaded, failed remote paths). Never raises
694
  for a file: batches first, then the files of a failed batch one by one, retried after each
695
+ delay in `backoff` unless the error is a permanent "not found" (`_permanent`). Each file lands in a `.legion-part` sibling, renamed into place only
696
  when it arrived, so a failed file never leaves a truncated copy at its real path.
697
  `progress(n)` is called with the number of files each attempt brought in (serialized: the
698
  first pass runs `restore_threads()` batches in parallel threads)."""
 
761
 
762
 
763
  def _clean_parts(root: Path) -> int:
764
+ """Remove stray `.legion-part` files under `root` (a crash mid-download leaves them)."""
765
  n = 0
766
  if root.is_dir():
767
  for p in root.rglob("*" + PART_SUFFIX):
world/src/{flock → legion}/world/__init__.py RENAMED
@@ -1,10 +1,10 @@
1
- """`flock.world`: a small base for writing a world in Python (docs/world.md).
2
 
3
- A world is any HTTP server that speaks World API v1 (`flock.world.protocol`); this base is a
4
  convenience, not a requirement. Subclass `World`, mark tool methods with `@tool`, and serve it
5
- with `python -m flock.world serve module:Class` (`flock.world.server`):
6
 
7
- from flock.world import Agent, ToolError, World, tool
8
 
9
  class Counter(World):
10
  name, version = "counter", "0.1.0"
@@ -21,7 +21,7 @@ with `python -m flock.world serve module:Class` (`flock.world.server`):
21
  return {"n": self.n, "by": agent.name}
22
 
23
  Tool schemas come from the type hints and docstrings with the tools-folder rules
24
- (flock.tools.loader); a parameter named `agent` (or annotated `Agent`) receives the
25
  caller and is never shown to the model. Override `manifest()` and `call()` to serve tools some
26
  other way. The hooks `on_agent_start`, `on_agent_done` and `on_turn` are sent only when a
27
  subclass overrides them (the manifest lists them in `hooks`).
@@ -36,16 +36,16 @@ from collections.abc import Callable
36
  from dataclasses import dataclass
37
  from typing import Any
38
 
39
- from flock.world.admin import TYPES, Admin, Knob
40
- from flock.world.protocol import HOOK_EVENTS, STATE_DIR_ENV, WORLD_API
41
 
42
  AGENT_PARAM = "agent"
43
 
44
 
45
  @dataclass(frozen=True)
46
  class Agent:
47
- """Who calls: the flock agent name, its type and swarm, the turn and the request id (as
48
- flock sent them; trust them when the token matched)."""
49
 
50
  name: str
51
  type: str = ""
@@ -79,9 +79,9 @@ def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = Fa
79
  raise ValueError(f"pool {pool!r} must be one of {POOLS}")
80
 
81
  def mark(f: Callable) -> Callable:
82
- f.__flock_world_tool__ = True # type: ignore[attr-defined]
83
- f.__flock_world_pool__ = pool # type: ignore[attr-defined]
84
- f.__flock_world_read_only__ = read_only # type: ignore[attr-defined]
85
  return f
86
 
87
  return mark if fn is None else mark(fn)
@@ -93,8 +93,8 @@ def _is_agent(p: inspect.Parameter, hints: dict[str, Any]) -> bool:
93
 
94
 
95
  def tool_schema(fn: Callable) -> dict[str, Any]:
96
- """{name, description, parameters} of a tool method (raises flock.tools.loader.ToolsError)."""
97
- from flock.tools.loader import tool_def
98
 
99
  hints = typing.get_type_hints(fn)
100
  sig = inspect.signature(fn)
@@ -128,14 +128,14 @@ class World:
128
  # ------------------------------------------------------------------ tools
129
  def tools(self) -> dict[str, Callable]:
130
  """The bound `@tool` methods, by name (in definition order)."""
131
- found = self.__dict__.get("_flock_tools")
132
  if found is None: # no __init__ needed in subclasses: built on first use
133
  found = {}
134
  for klass in reversed(type(self).__mro__):
135
  for attr, value in vars(klass).items():
136
- if getattr(value, "__flock_world_tool__", False):
137
  found[attr] = getattr(self, attr)
138
- self.__dict__["_flock_tools"] = found
139
  return found
140
 
141
  def hooks(self) -> list[str]:
@@ -152,13 +152,13 @@ class World:
152
  attributes as they are now; the tool schemas are computed once."""
153
  hooks = self.hooks()
154
  caps = list(dict.fromkeys([*self.capabilities, *(["hooks"] if hooks else [])]))
155
- schemas = self.__dict__.get("_flock_schemas")
156
  if schemas is None:
157
  schemas = [tool_schema(fn) for fn in self.tools().values()]
158
  for t, fn in zip(schemas, self.tools().values(), strict=True):
159
- if getattr(fn, "__flock_world_read_only__", False):
160
  t["annotations"] = {"readOnlyHint": True}
161
- self.__dict__["_flock_schemas"] = schemas
162
  return {"world_api": WORLD_API, "name": self.name, "version": self.version,
163
  "description": self.description, "tools": [dict(t) for t in schemas],
164
  "capabilities": caps, "hooks": hooks}
@@ -175,7 +175,7 @@ class World:
175
 
176
  def pool(self, tool: str) -> str:
177
  """The server's thread pool for `tool`: "fast" (default) or "slow" (`@tool(pool=)`)."""
178
- return getattr(self.tools().get(tool), "__flock_world_pool__", "fast")
179
 
180
  def cancellable(self, tool: str) -> bool:
181
  """May the server cancel this tool's `async` work when its caller disconnects (the
@@ -192,7 +192,7 @@ class World:
192
  # ------------------------------------------------------------------ admin (docs/world.md)
193
  def state_dir(self) -> str | os.PathLike | None:
194
  """Where `knobs.json` lives (knob values and paused lanes set through the admin API,
195
- read back at the next start). Default: $FLOCK_WORLD_STATE_DIR, else None (kept in
196
  memory only). The server may call it before `__init__` ran (to serve /admin while the
197
  world cannot be built): do not rely on attributes `__init__` sets without a fallback."""
198
  return os.environ.get(STATE_DIR_ENV) or None
@@ -200,9 +200,9 @@ class World:
200
  @property
201
  def admin(self) -> Admin:
202
  """This world's knobs and paused lanes (the server may install one before __init__)."""
203
- if "_flock_admin" not in self.__dict__:
204
- self.__dict__["_flock_admin"] = Admin(self.state_dir())
205
- return self.__dict__["_flock_admin"]
206
 
207
  def knob(self, name: str, type: type, default: Any, *, min: float | None = None,
208
  max: float | None = None, doc: str = "",
@@ -230,7 +230,7 @@ class World:
230
  """An agent got its first prompt on its worker (again after a relaunch)."""
231
 
232
  def on_agent_done(self, agent: Agent, data: dict[str, Any]) -> None:
233
- """An agent was removed from the swarm (scale down, `flock stop --delete`, `flock-agent remove`)."""
234
 
235
  def on_turn(self, agent: Agent, data: dict[str, Any]) -> None:
236
  """An agent's turn ended: `data` has status, tool_calls, turn."""
 
1
+ """`legion.world`: a small base for writing a world in Python (docs/world.md).
2
 
3
+ A world is any HTTP server that speaks World API v1 (`legion.world.protocol`); this base is a
4
  convenience, not a requirement. Subclass `World`, mark tool methods with `@tool`, and serve it
5
+ with `python -m legion.world serve module:Class` (`legion.world.server`):
6
 
7
+ from legion.world import Agent, ToolError, World, tool
8
 
9
  class Counter(World):
10
  name, version = "counter", "0.1.0"
 
21
  return {"n": self.n, "by": agent.name}
22
 
23
  Tool schemas come from the type hints and docstrings with the tools-folder rules
24
+ (legion.tools.loader); a parameter named `agent` (or annotated `Agent`) receives the
25
  caller and is never shown to the model. Override `manifest()` and `call()` to serve tools some
26
  other way. The hooks `on_agent_start`, `on_agent_done` and `on_turn` are sent only when a
27
  subclass overrides them (the manifest lists them in `hooks`).
 
36
  from dataclasses import dataclass
37
  from typing import Any
38
 
39
+ from legion.world.admin import TYPES, Admin, Knob
40
+ from legion.world.protocol import HOOK_EVENTS, STATE_DIR_ENV, WORLD_API
41
 
42
  AGENT_PARAM = "agent"
43
 
44
 
45
  @dataclass(frozen=True)
46
  class Agent:
47
+ """Who calls: the legion agent name, its type and swarm, the turn and the request id (as
48
+ legion sent them; trust them when the token matched)."""
49
 
50
  name: str
51
  type: str = ""
 
79
  raise ValueError(f"pool {pool!r} must be one of {POOLS}")
80
 
81
  def mark(f: Callable) -> Callable:
82
+ f.__legion_world_tool__ = True # type: ignore[attr-defined]
83
+ f.__legion_world_pool__ = pool # type: ignore[attr-defined]
84
+ f.__legion_world_read_only__ = read_only # type: ignore[attr-defined]
85
  return f
86
 
87
  return mark if fn is None else mark(fn)
 
93
 
94
 
95
  def tool_schema(fn: Callable) -> dict[str, Any]:
96
+ """{name, description, parameters} of a tool method (raises legion.tools.loader.ToolsError)."""
97
+ from legion.tools.loader import tool_def
98
 
99
  hints = typing.get_type_hints(fn)
100
  sig = inspect.signature(fn)
 
128
  # ------------------------------------------------------------------ tools
129
  def tools(self) -> dict[str, Callable]:
130
  """The bound `@tool` methods, by name (in definition order)."""
131
+ found = self.__dict__.get("_legion_tools")
132
  if found is None: # no __init__ needed in subclasses: built on first use
133
  found = {}
134
  for klass in reversed(type(self).__mro__):
135
  for attr, value in vars(klass).items():
136
+ if getattr(value, "__legion_world_tool__", False):
137
  found[attr] = getattr(self, attr)
138
+ self.__dict__["_legion_tools"] = found
139
  return found
140
 
141
  def hooks(self) -> list[str]:
 
152
  attributes as they are now; the tool schemas are computed once."""
153
  hooks = self.hooks()
154
  caps = list(dict.fromkeys([*self.capabilities, *(["hooks"] if hooks else [])]))
155
+ schemas = self.__dict__.get("_legion_schemas")
156
  if schemas is None:
157
  schemas = [tool_schema(fn) for fn in self.tools().values()]
158
  for t, fn in zip(schemas, self.tools().values(), strict=True):
159
+ if getattr(fn, "__legion_world_read_only__", False):
160
  t["annotations"] = {"readOnlyHint": True}
161
+ self.__dict__["_legion_schemas"] = schemas
162
  return {"world_api": WORLD_API, "name": self.name, "version": self.version,
163
  "description": self.description, "tools": [dict(t) for t in schemas],
164
  "capabilities": caps, "hooks": hooks}
 
175
 
176
  def pool(self, tool: str) -> str:
177
  """The server's thread pool for `tool`: "fast" (default) or "slow" (`@tool(pool=)`)."""
178
+ return getattr(self.tools().get(tool), "__legion_world_pool__", "fast")
179
 
180
  def cancellable(self, tool: str) -> bool:
181
  """May the server cancel this tool's `async` work when its caller disconnects (the
 
192
  # ------------------------------------------------------------------ admin (docs/world.md)
193
  def state_dir(self) -> str | os.PathLike | None:
194
  """Where `knobs.json` lives (knob values and paused lanes set through the admin API,
195
+ read back at the next start). Default: $LEGION_WORLD_STATE_DIR, else None (kept in
196
  memory only). The server may call it before `__init__` ran (to serve /admin while the
197
  world cannot be built): do not rely on attributes `__init__` sets without a fallback."""
198
  return os.environ.get(STATE_DIR_ENV) or None
 
200
  @property
201
  def admin(self) -> Admin:
202
  """This world's knobs and paused lanes (the server may install one before __init__)."""
203
+ if "_legion_admin" not in self.__dict__:
204
+ self.__dict__["_legion_admin"] = Admin(self.state_dir())
205
+ return self.__dict__["_legion_admin"]
206
 
207
  def knob(self, name: str, type: type, default: Any, *, min: float | None = None,
208
  max: float | None = None, doc: str = "",
 
230
  """An agent got its first prompt on its worker (again after a relaunch)."""
231
 
232
  def on_agent_done(self, agent: Agent, data: dict[str, Any]) -> None:
233
+ """An agent was removed from the swarm (scale down, `legion stop --delete`, `legion-agent remove`)."""
234
 
235
  def on_turn(self, agent: Agent, data: dict[str, Any]) -> None:
236
  """An agent's turn ended: `data` has status, tool_calls, turn."""
world/src/{flock → legion}/world/admin.py RENAMED
@@ -19,7 +19,7 @@ from dataclasses import dataclass
19
  from pathlib import Path
20
  from typing import Any
21
 
22
- log = logging.getLogger("flock.world")
23
 
24
  KNOBS_FILE = "knobs.json"
25
  LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")
 
19
  from pathlib import Path
20
  from typing import Any
21
 
22
+ log = logging.getLogger("legion.world")
23
 
24
  KNOBS_FILE = "knobs.json"
25
  LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")
world/src/{flock → legion}/world/lanes.py RENAMED
@@ -25,7 +25,7 @@ import time
25
  import uuid
26
  from pathlib import Path
27
 
28
- log = logging.getLogger("flock.world.lanes")
29
  POLL_S = 0.25 # longest single wait: notices pause flips, configure() and a test's fake clock
30
 
31
 
 
25
  import uuid
26
  from pathlib import Path
27
 
28
+ log = logging.getLogger("legion.world.lanes")
29
  POLL_S = 0.25 # longest single wait: notices pause flips, configure() and a test's fake clock
30
 
31
 
world/src/{flock → legion}/world/protocol.py RENAMED
@@ -9,8 +9,8 @@ A world is any HTTP server that answers two routes with a shared secret:
9
 
10
  Every request carries `X-World-Token` (the secret, or on `/manifest` and tool calls the calling
11
  agent's own `agent_token`); a tool call also names the calling agent
12
- (`X-Flock-Agent`, `X-Flock-Type`, `X-Flock-Swarm`, `X-Flock-Turn`, `X-Request-Id`). This module
13
- is pydantic-only, so the worker, the controller and a world written with `flock.world` share it.
14
  """
15
 
16
  from __future__ import annotations
@@ -20,28 +20,28 @@ import hmac
20
  import re
21
  from typing import Any
22
 
23
- from pydantic import BaseModel, Field, field_validator
24
 
25
  WORLD_API = "v1"
26
 
27
  TOKEN_HEADER = "X-World-Token"
28
- AGENT_HEADER = "X-Flock-Agent"
29
- TYPE_HEADER = "X-Flock-Type"
30
- SWARM_HEADER = "X-Flock-Swarm"
31
- TURN_HEADER = "X-Flock-Turn"
32
  REQUEST_HEADER = "X-Request-Id"
33
 
34
- # Environment of a world flock starts (and of `python -m flock.world serve`), and of the workers.
35
- TOKEN_ENV = "FLOCK_WORLD_TOKEN"
36
- PORT_ENV = "FLOCK_WORLD_PORT"
37
- HOST_ENV = "FLOCK_WORLD_HOST"
38
- SWARM_ENV = "FLOCK_SWARM"
39
- STATE_DIR_ENV = "FLOCK_WORLD_STATE_DIR" # knobs.json (World.state_dir)
40
  # The /admin secret of a world (docs/world.md, "Admin API"); never derived from the world
41
  # secret, which every worker holds. Unset: /admin answers 403.
42
- ADMIN_TOKEN_ENV = "FLOCK_WORLD_ADMIN_TOKEN"
43
 
44
- # Hooks flock sends to a world that lists them in its manifest's `hooks` (POST /hooks).
45
  HOOK_EVENTS = ("agent_start", "agent_done", "turn")
46
 
47
  WORLD_NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
@@ -49,7 +49,7 @@ TOOL_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
49
 
50
 
51
  class WorkspaceUpload(BaseModel):
52
- """`x-flock-workspace` on a tool (worlds with workspace-upload-v1): the worker uploads the
53
  local clone named by argument `arg` (`default` when absent), unless the value is in `skip`
54
  or starts with `skip_prefix`."""
55
 
@@ -61,7 +61,7 @@ class WorkspaceUpload(BaseModel):
61
 
62
  class WorldTool(BaseModel):
63
  """One tool: a Chat Completions function (`parameters` is a JSON schema of type object),
64
- plus optional flock metadata: `x-flock-workspace` and `x-flock-timeout_s` (the least HTTP
65
  timeout the worker gives this tool's calls), and `annotations.readOnlyHint` (the tool
66
  changes nothing: the worker may retry it once)."""
67
 
@@ -70,14 +70,23 @@ class WorldTool(BaseModel):
70
  name: str
71
  description: str = ""
72
  parameters: dict[str, Any] = Field(default_factory=lambda: {"type": "object", "properties": {}})
73
- workspace: WorkspaceUpload | None = Field(None, alias="x-flock-workspace")
74
- timeout_s: float | None = Field(None, alias="x-flock-timeout_s", gt=0)
75
  annotations: dict[str, Any] = Field(default_factory=dict) # MCP-style, e.g. readOnlyHint
76
 
77
  @property
78
  def read_only(self) -> bool:
79
  return self.annotations.get("readOnlyHint") is True
80
 
 
 
 
 
 
 
 
 
 
81
  @field_validator("name")
82
  @classmethod
83
  def _name(cls, v: str) -> str:
@@ -114,7 +123,7 @@ class WorldManifest(BaseModel):
114
  @classmethod
115
  def _api(cls, v: str) -> str:
116
  if v != WORLD_API:
117
- raise ValueError(f"world_api {v!r} is not supported (this flock speaks {WORLD_API!r})")
118
  return v
119
 
120
  @field_validator("name")
@@ -150,20 +159,20 @@ class WorldManifest(BaseModel):
150
 
151
  def agent_token(secret: str, agent: str) -> str:
152
  """One agent's own world token: a world accepts it instead of its secret on `/manifest` and
153
- tool calls whose `X-Flock-Agent` is `agent`, so a token in an agent's hands acts only as it."""
154
- return hmac.new(secret.encode(), f"flock-world-agent\0{agent}".encode(),
155
  hashlib.sha256).hexdigest()
156
 
157
 
158
  def credential_id(token: str, origin: str) -> str:
159
  """Names a (secret, origin) pair without revealing the secret: the controller writes it
160
  into the world block, a worker compares it with its own secret's before sending it."""
161
- return hmac.new(token.encode(), f"flock-world-credential\0{origin}".encode(),
162
  hashlib.sha256).hexdigest()[:32]
163
 
164
 
165
- WORLD_HOST_VAR = "${WORLD_HOST}" # in world.url: the host is read from FLOCK_WORLD_HOST_FILE
166
- WORLD_HOST_FILE_ENV = "FLOCK_WORLD_HOST_FILE"
167
  DEFAULT_PORT = 7860 # what an old host-only host file means (the url's own port)
168
 
169
 
 
9
 
10
  Every request carries `X-World-Token` (the secret, or on `/manifest` and tool calls the calling
11
  agent's own `agent_token`); a tool call also names the calling agent
12
+ (`X-Legion-Agent`, `X-Legion-Type`, `X-Legion-Swarm`, `X-Legion-Turn`, `X-Request-Id`). This module
13
+ is pydantic-only, so the worker, the controller and a world written with `legion.world` share it.
14
  """
15
 
16
  from __future__ import annotations
 
20
  import re
21
  from typing import Any
22
 
23
+ from pydantic import BaseModel, Field, field_validator, model_validator
24
 
25
  WORLD_API = "v1"
26
 
27
  TOKEN_HEADER = "X-World-Token"
28
+ AGENT_HEADER = "X-Legion-Agent"
29
+ TYPE_HEADER = "X-Legion-Type"
30
+ SWARM_HEADER = "X-Legion-Swarm"
31
+ TURN_HEADER = "X-Legion-Turn"
32
  REQUEST_HEADER = "X-Request-Id"
33
 
34
+ # Environment of a world legion starts (and of `python -m legion.world serve`), and of the workers.
35
+ TOKEN_ENV = "LEGION_WORLD_TOKEN"
36
+ PORT_ENV = "LEGION_WORLD_PORT"
37
+ HOST_ENV = "LEGION_WORLD_HOST"
38
+ SWARM_ENV = "LEGION_SWARM"
39
+ STATE_DIR_ENV = "LEGION_WORLD_STATE_DIR" # knobs.json (World.state_dir)
40
  # The /admin secret of a world (docs/world.md, "Admin API"); never derived from the world
41
  # secret, which every worker holds. Unset: /admin answers 403.
42
+ ADMIN_TOKEN_ENV = "LEGION_WORLD_ADMIN_TOKEN"
43
 
44
+ # Hooks legion sends to a world that lists them in its manifest's `hooks` (POST /hooks).
45
  HOOK_EVENTS = ("agent_start", "agent_done", "turn")
46
 
47
  WORLD_NAME_RE = re.compile(r"^[a-z][a-z0-9-]{0,31}$")
 
49
 
50
 
51
  class WorkspaceUpload(BaseModel):
52
+ """`x-legion-workspace` on a tool (worlds with workspace-upload-v1): the worker uploads the
53
  local clone named by argument `arg` (`default` when absent), unless the value is in `skip`
54
  or starts with `skip_prefix`."""
55
 
 
61
 
62
  class WorldTool(BaseModel):
63
  """One tool: a Chat Completions function (`parameters` is a JSON schema of type object),
64
+ plus optional legion metadata: `x-legion-workspace` and `x-legion-timeout_s` (the least HTTP
65
  timeout the worker gives this tool's calls), and `annotations.readOnlyHint` (the tool
66
  changes nothing: the worker may retry it once)."""
67
 
 
70
  name: str
71
  description: str = ""
72
  parameters: dict[str, Any] = Field(default_factory=lambda: {"type": "object", "properties": {}})
73
+ workspace: WorkspaceUpload | None = Field(None, alias="x-legion-workspace")
74
+ timeout_s: float | None = Field(None, alias="x-legion-timeout_s", gt=0)
75
  annotations: dict[str, Any] = Field(default_factory=dict) # MCP-style, e.g. readOnlyHint
76
 
77
  @property
78
  def read_only(self) -> bool:
79
  return self.annotations.get("readOnlyHint") is True
80
 
81
+ @model_validator(mode="before")
82
+ @classmethod
83
+ def _old_keys(cls, v: Any) -> Any:
84
+ # the keys' former prefix: ignored as unknown otherwise, and the upload/timeout silently off
85
+ old = sorted(k for k in v if isinstance(k, str) and k.startswith("x-flock-")) if isinstance(v, dict) else []
86
+ if old:
87
+ raise ValueError(f"{', '.join(old)}: renamed to x-legion-*")
88
+ return v
89
+
90
  @field_validator("name")
91
  @classmethod
92
  def _name(cls, v: str) -> str:
 
123
  @classmethod
124
  def _api(cls, v: str) -> str:
125
  if v != WORLD_API:
126
+ raise ValueError(f"world_api {v!r} is not supported (this legion speaks {WORLD_API!r})")
127
  return v
128
 
129
  @field_validator("name")
 
159
 
160
  def agent_token(secret: str, agent: str) -> str:
161
  """One agent's own world token: a world accepts it instead of its secret on `/manifest` and
162
+ tool calls whose `X-Legion-Agent` is `agent`, so a token in an agent's hands acts only as it."""
163
+ return hmac.new(secret.encode(), f"legion-world-agent\0{agent}".encode(),
164
  hashlib.sha256).hexdigest()
165
 
166
 
167
  def credential_id(token: str, origin: str) -> str:
168
  """Names a (secret, origin) pair without revealing the secret: the controller writes it
169
  into the world block, a worker compares it with its own secret's before sending it."""
170
+ return hmac.new(token.encode(), f"legion-world-credential\0{origin}".encode(),
171
  hashlib.sha256).hexdigest()[:32]
172
 
173
 
174
+ WORLD_HOST_VAR = "${WORLD_HOST}" # in world.url: the host is read from LEGION_WORLD_HOST_FILE
175
+ WORLD_HOST_FILE_ENV = "LEGION_WORLD_HOST_FILE"
176
  DEFAULT_PORT = 7860 # what an old host-only host file means (the url's own port)
177
 
178
 
world/src/{flock → legion}/world/server.py RENAMED
@@ -1,9 +1,9 @@
1
- """Serve a `flock.world.World` over HTTP (World API v1, docs/world.md).
2
 
3
- `python -m flock.world serve module:Class` imports `module` from the current directory, instantiates
4
  `Class` (or takes a World instance named so) and serves it with uvicorn on
5
- `$FLOCK_WORLD_HOST:$FLOCK_WORLD_PORT` (default 127.0.0.1:8765), requiring `X-World-Token` to
6
- equal `$FLOCK_WORLD_TOKEN`. Synchronous tools and hooks run one at a time (a lock), so a world
7
  needs no locking of its own, unless it is `concurrent`; they run in two thread pools, "fast"
8
  and "slow" (`@tool(pool=)`), so slow tools never starve the fast ones; `async def` tools run on the event loop. An `async` tool the world marks `cancellable(name)` is
9
  cancelled when its caller disconnects (checked every second), so a call nobody waits for any
@@ -14,7 +14,7 @@ Prometheus text for `Accept: text/plain`).
14
  Parked mode: `serve` binds the port first and builds the world in a background thread, retrying
15
  with backoff while that raises; meanwhile `/manifest`, tools and hooks answer 503 (`parked`).
16
  `GET /healthz` (no token) says "ready" or "parked". `/admin/*` (the admin secret, never the world
17
- token) reads and sets the world's knobs and pauses its lanes (`flock.world.admin`).
18
  Needs the `controller` extra (FastAPI, uvicorn).
19
  """
20
 
@@ -44,9 +44,9 @@ from fastapi import FastAPI, Request
44
  from fastapi.responses import JSONResponse, PlainTextResponse, Response
45
  from starlette.datastructures import Headers
46
 
47
- from flock.tools.loader import check_args
48
- from flock.world import Admin, Agent, ToolError, World
49
- from flock.world.protocol import (
50
  ADMIN_TOKEN_ENV,
51
  AGENT_HEADER,
52
  HOOK_EVENTS,
@@ -60,18 +60,18 @@ from flock.world.protocol import (
60
  TYPE_HEADER,
61
  agent_token,
62
  )
63
- from flock.world.workspace import MAX_BYTES
64
 
65
- log = logging.getLogger("flock.world")
66
 
67
  DEFAULT_PORT = 8765
68
  FAST_THREADS = 40 # tools that answer in well under a second, and hooks
69
  SLOW_THREADS = 64 # tools that block for seconds or minutes (`@tool(pool="slow")`)
70
  # Admission control (docs/world.md): a tool call is refused with 429 when the fast pool's oldest
71
  # queued call waited longer than this, or the slow pool holds its threads plus this many queued.
72
- FAST_MAX_WAIT_ENV, FAST_MAX_WAIT_S = "FLOCK_WORLD_FAST_MAX_WAIT_S", 2.0
73
- SLOW_QUEUE_ENV, SLOW_QUEUE = "FLOCK_WORLD_SLOW_QUEUE", 8
74
- RETRY_AFTER_ENV, RETRY_AFTER_S = "FLOCK_WORLD_RETRY_AFTER_S", 30.0
75
  REFUSAL_LOG_EVERY_S = 10.0 # at most one WARNING per pool this often about refused calls
76
  # Parked mode: a world whose construction raises is built again after 30 s, doubling to 10 min.
77
  PARK_FIRST_S, PARK_CAP_S = 30.0, 600.0
@@ -189,14 +189,14 @@ def _prometheus(m: dict[str, Any]) -> str:
189
  for k, v in stats.items():
190
  if k == "errors_by_code":
191
  for c, n in v.items():
192
- add("flock_world_tool_errors", f"{{tool={_lv(name)},code={_lv(c)}}}", n)
193
  else:
194
- add(f"flock_world_{label}_{k}", f"{{{label}={_lv(name)}}}", v)
195
  elif key == "world":
196
  for k, v in value.items():
197
- add(f"flock_world_world_{re.sub(r'[^A-Za-z0-9_]', '_', k)}", "", v)
198
  else:
199
- add(f"flock_world_{key}", "", value)
200
  return "\n".join(l for g in groups.values() for l in g) + "\n"
201
 
202
 
@@ -240,7 +240,7 @@ def _error(code: str, message: str, status: int = 200,
240
  class _Auth:
241
  """`X-World-Token`: the world secret on every route but `/healthz` (none) and `/admin/*`
242
  (the admin secret), or on `/manifest` and `/tools/*` the caller's `agent_token` for its
243
- `X-Flock-Agent`. An empty world secret: open; an empty admin secret: /admin is 403."""
244
 
245
  def __init__(self, app: Any, token: str, admin: str) -> None:
246
  self.app, self.token, self.admin = app, token, admin
@@ -298,7 +298,7 @@ def _agent(headers: Any) -> Agent:
298
  def create_app(world: World | Callable[[Admin], World], token: str | None) -> FastAPI:
299
  """The ASGI app for `world`. `token` None or "": no authentication (tests, a trusted
300
  network); otherwise every route needs `X-World-Token: <token>`. `/admin/*` needs the admin
301
- secret, $FLOCK_WORLD_ADMIN_TOKEN (unset: 403).
302
  `world` may be a builder, `build(admin) -> World`: the app starts parked and builds the
303
  world in a thread once it runs, again with backoff while that raises."""
304
  metrics = _Metrics()
@@ -630,7 +630,7 @@ def resolve_target(target: str, path: str | None = None) -> Any:
630
  sys.path.insert(0, where)
631
  obj = getattr(importlib.import_module(module_name), attr)
632
  if not (isinstance(obj, World) or isinstance(obj, type) and issubclass(obj, World)):
633
- raise TypeError(f"{target!r} is not a flock.world.World (subclass or instance)")
634
  return obj
635
 
636
 
@@ -644,7 +644,7 @@ def build(obj: Any, admin: Admin | None = None) -> World:
644
  world = obj.__new__(obj) # the admin goes in first: __init__ registers its knobs
645
  if admin.path is None and (d := world.state_dir()):
646
  admin.attach(d)
647
- world.__dict__["_flock_admin"] = admin
648
  world.__init__()
649
  return world
650
 
@@ -674,7 +674,7 @@ def serve(target: str, *, host: str | None = None, port: int | None = None,
674
  token_env: str = TOKEN_ENV, insecure: bool = False) -> None:
675
  import uvicorn
676
 
677
- from flock.isolation import enabled, protect_supervisor
678
 
679
  if enabled():
680
  protect_supervisor()
 
1
+ """Serve a `legion.world.World` over HTTP (World API v1, docs/world.md).
2
 
3
+ `python -m legion.world serve module:Class` imports `module` from the current directory, instantiates
4
  `Class` (or takes a World instance named so) and serves it with uvicorn on
5
+ `$LEGION_WORLD_HOST:$LEGION_WORLD_PORT` (default 127.0.0.1:8765), requiring `X-World-Token` to
6
+ equal `$LEGION_WORLD_TOKEN`. Synchronous tools and hooks run one at a time (a lock), so a world
7
  needs no locking of its own, unless it is `concurrent`; they run in two thread pools, "fast"
8
  and "slow" (`@tool(pool=)`), so slow tools never starve the fast ones; `async def` tools run on the event loop. An `async` tool the world marks `cancellable(name)` is
9
  cancelled when its caller disconnects (checked every second), so a call nobody waits for any
 
14
  Parked mode: `serve` binds the port first and builds the world in a background thread, retrying
15
  with backoff while that raises; meanwhile `/manifest`, tools and hooks answer 503 (`parked`).
16
  `GET /healthz` (no token) says "ready" or "parked". `/admin/*` (the admin secret, never the world
17
+ token) reads and sets the world's knobs and pauses its lanes (`legion.world.admin`).
18
  Needs the `controller` extra (FastAPI, uvicorn).
19
  """
20
 
 
44
  from fastapi.responses import JSONResponse, PlainTextResponse, Response
45
  from starlette.datastructures import Headers
46
 
47
+ from legion.tools.loader import check_args
48
+ from legion.world import Admin, Agent, ToolError, World
49
+ from legion.world.protocol import (
50
  ADMIN_TOKEN_ENV,
51
  AGENT_HEADER,
52
  HOOK_EVENTS,
 
60
  TYPE_HEADER,
61
  agent_token,
62
  )
63
+ from legion.world.workspace import MAX_BYTES
64
 
65
+ log = logging.getLogger("legion.world")
66
 
67
  DEFAULT_PORT = 8765
68
  FAST_THREADS = 40 # tools that answer in well under a second, and hooks
69
  SLOW_THREADS = 64 # tools that block for seconds or minutes (`@tool(pool="slow")`)
70
  # Admission control (docs/world.md): a tool call is refused with 429 when the fast pool's oldest
71
  # queued call waited longer than this, or the slow pool holds its threads plus this many queued.
72
+ FAST_MAX_WAIT_ENV, FAST_MAX_WAIT_S = "LEGION_WORLD_FAST_MAX_WAIT_S", 2.0
73
+ SLOW_QUEUE_ENV, SLOW_QUEUE = "LEGION_WORLD_SLOW_QUEUE", 8
74
+ RETRY_AFTER_ENV, RETRY_AFTER_S = "LEGION_WORLD_RETRY_AFTER_S", 30.0
75
  REFUSAL_LOG_EVERY_S = 10.0 # at most one WARNING per pool this often about refused calls
76
  # Parked mode: a world whose construction raises is built again after 30 s, doubling to 10 min.
77
  PARK_FIRST_S, PARK_CAP_S = 30.0, 600.0
 
189
  for k, v in stats.items():
190
  if k == "errors_by_code":
191
  for c, n in v.items():
192
+ add("legion_world_tool_errors", f"{{tool={_lv(name)},code={_lv(c)}}}", n)
193
  else:
194
+ add(f"legion_world_{label}_{k}", f"{{{label}={_lv(name)}}}", v)
195
  elif key == "world":
196
  for k, v in value.items():
197
+ add(f"legion_world_world_{re.sub(r'[^A-Za-z0-9_]', '_', k)}", "", v)
198
  else:
199
+ add(f"legion_world_{key}", "", value)
200
  return "\n".join(l for g in groups.values() for l in g) + "\n"
201
 
202
 
 
240
  class _Auth:
241
  """`X-World-Token`: the world secret on every route but `/healthz` (none) and `/admin/*`
242
  (the admin secret), or on `/manifest` and `/tools/*` the caller's `agent_token` for its
243
+ `X-Legion-Agent`. An empty world secret: open; an empty admin secret: /admin is 403."""
244
 
245
  def __init__(self, app: Any, token: str, admin: str) -> None:
246
  self.app, self.token, self.admin = app, token, admin
 
298
  def create_app(world: World | Callable[[Admin], World], token: str | None) -> FastAPI:
299
  """The ASGI app for `world`. `token` None or "": no authentication (tests, a trusted
300
  network); otherwise every route needs `X-World-Token: <token>`. `/admin/*` needs the admin
301
+ secret, $LEGION_WORLD_ADMIN_TOKEN (unset: 403).
302
  `world` may be a builder, `build(admin) -> World`: the app starts parked and builds the
303
  world in a thread once it runs, again with backoff while that raises."""
304
  metrics = _Metrics()
 
630
  sys.path.insert(0, where)
631
  obj = getattr(importlib.import_module(module_name), attr)
632
  if not (isinstance(obj, World) or isinstance(obj, type) and issubclass(obj, World)):
633
+ raise TypeError(f"{target!r} is not a legion.world.World (subclass or instance)")
634
  return obj
635
 
636
 
 
644
  world = obj.__new__(obj) # the admin goes in first: __init__ registers its knobs
645
  if admin.path is None and (d := world.state_dir()):
646
  admin.attach(d)
647
+ world.__dict__["_legion_admin"] = admin
648
  world.__init__()
649
  return world
650
 
 
674
  token_env: str = TOKEN_ENV, insecure: bool = False) -> None:
675
  import uvicorn
676
 
677
+ from legion.isolation import enabled, protect_supervisor
678
 
679
  if enabled():
680
  protect_supervisor()
world/src/{flock → legion}/world/store.py RENAMED
@@ -1,4 +1,4 @@
1
- """`flock.world.store`: a small `(kind, key) -> JSON` table on SQLite in WAL mode (docs/world.md).
2
 
3
  For worlds that keep their state in memory and want saves that cost O(changes): the world reads
4
  its own dicts, marks the rows it changed with `dirty(kind, key)`, and a saver calls
 
1
+ """`legion.world.store`: a small `(kind, key) -> JSON` table on SQLite in WAL mode (docs/world.md).
2
 
3
  For worlds that keep their state in memory and want saves that cost O(changes): the world reads
4
  its own dicts, marks the rows it changed with `dirty(kind, key)`, and a saver calls
world/src/{flock → legion}/world/workspace.py RENAMED
@@ -127,7 +127,7 @@ def apply_patch(snapshot: dict, tree: Path) -> list[str]:
127
  raise ValueError("the tree is not a checkout of the patch's base")
128
  if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)):
129
  raise ValueError("symlinks are not supported")
130
- # shortcut: agents send patches directly (flock.harbor's world.call), and a binary delta can
131
  # expand past its declared size, up to the file-size and memory limits below, with at most
132
  # APPLY_SLOTS applies at once; decode delta headers if that bound is too loose.
133
  if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES
 
127
  raise ValueError("the tree is not a checkout of the patch's base")
128
  if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)):
129
  raise ValueError("symlinks are not supported")
130
+ # shortcut: agents send patches directly (legion.harbor's world.call), and a binary delta can
131
  # expand past its declared size, up to the file-size and memory limits below, with at most
132
  # APPLY_SLOTS applies at once; decode delta headers if that bound is too loose.
133
  if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES
world/tests/conftest.py CHANGED
@@ -1,4 +1,4 @@
1
- """Puts the world's modules and the vendored flock library on sys.path; test helpers."""
2
  from __future__ import annotations
3
 
4
  import shutil
 
1
+ """Puts the world's modules and the vendored legion library on sys.path; test helpers."""
2
  from __future__ import annotations
3
 
4
  import shutil
world/tests/fixtures/seed-basic/CONTRIBUTING.md CHANGED
@@ -10,8 +10,8 @@
10
  `respond(text, memory) -> str | None`; optional integer `PRIORITY` orders modules.
11
  Claim different modules so teams can work without editing the same files.
12
  4. Run `python -m unittest discover -s tests` in the clone, and test the whole bot:
13
- `flock-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.
14
- 5. Submit a small PR using `flock-tool open_pr --json
15
  '{"path":"pybot","branch":"your-topic","title":"Your change",
16
  "description":"What changed, why, and test evidence"}'`.
17
  The worker uploads the clone's tracked and nonignored files, including working
@@ -38,8 +38,8 @@
38
  until those reviewers approve or the author updates the PR for a fresh review.
39
  The world checks the frozen interface and the bot's output/crash/time contract.
40
 
41
- All world and board tools use `flock-tool <name> --json '<arguments>'`.
42
- Run `flock-tool --list` for their current parameters. Board tools include channels,
43
  create_channel, join_channel, post, read, search, dm, read_dms and react. Mention,
44
  reply, DM and joined-channel notifications arrive between rounds; run no pollers.
45
  Keep status and test logs in your notes. Use the board for short conversations.
 
10
  `respond(text, memory) -> str | None`; optional integer `PRIORITY` orders modules.
11
  Claim different modules so teams can work without editing the same files.
12
  4. Run `python -m unittest discover -s tests` in the clone, and test the whole bot:
13
+ `legion-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.
14
+ 5. Submit a small PR using `legion-tool open_pr --json
15
  '{"path":"pybot","branch":"your-topic","title":"Your change",
16
  "description":"What changed, why, and test evidence"}'`.
17
  The worker uploads the clone's tracked and nonignored files, including working
 
38
  until those reviewers approve or the author updates the PR for a fresh review.
39
  The world checks the frozen interface and the bot's output/crash/time contract.
40
 
41
+ All world and board tools use `legion-tool <name> --json '<arguments>'`.
42
+ Run `legion-tool --list` for their current parameters. Board tools include channels,
43
  create_channel, join_channel, post, read, search, dm, read_dms and react. Mention,
44
  reply, DM and joined-channel notifications arrive between rounds; run no pollers.
45
  Keep status and test logs in your notes. Use the board for short conversations.
world/tests/test_pybot.py CHANGED
@@ -15,9 +15,9 @@ from pathlib import Path
15
  import httpx
16
  import pytest
17
 
18
- from flock.world import Agent, ToolError
19
- from flock.world.server import create_app
20
- from flock.world.workspace import capture
21
 
22
  from conftest import ROOT, FakeBucket
23
 
@@ -53,7 +53,7 @@ class LocalHub:
53
  def merge(self, pr, comment): # like the Hub: a three-way merge of refs/pr/N into main
54
  main, head = git(self.remote, "rev-parse", "main"), git(self.remote, "rev-parse", f"refs/pr/{pr}")
55
  tree = git(self.remote, "merge-tree", "--write-tree", main, head).split()[0]
56
- sha = git(self.remote, "-c", "user.name=world", "-c", "user.email=world@flock.invalid",
57
  "commit-tree", tree, "-p", main, "-p", head, "-m", comment)
58
  git(self.remote, "update-ref", "refs/heads/main", sha, main)
59
 
@@ -88,7 +88,7 @@ def _setup(tmp_path, monkeypatch, seed_dir, **env):
88
  shutil.copytree(ROOT / seed_dir, seed, ignore=shutil.ignore_patterns("__pycache__"))
89
  git(seed, "init", "-b", "main")
90
  git(seed, "add", ".")
91
- git(seed, "-c", "user.name=seed", "-c", "user.email=seed@flock.invalid", "commit", "-m", "seed")
92
  remote = tmp_path / "remote.git"
93
  git(tmp_path, "clone", "--bare", str(seed), str(remote))
94
  repo = Repository(tmp_path / "world.git", str(remote))
@@ -213,7 +213,7 @@ async def test_http_upload_is_outside_model_args(setup):
213
  async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://world") as client:
214
  payload = {"args": {"branch": "hello", "title": "Hello bot", "description": "tested"},
215
  "workspace": capture(clone.parent, clone.name)}
216
- headers = {"X-World-Token": "secret", "X-Flock-Agent": "cedar"}
217
  r = await client.post("/tools/open_pr", json=payload, headers=headers)
218
  assert r.json()["ok"], r.text
219
  assert "secret" not in r.text
@@ -732,7 +732,7 @@ def test_refusals_are_logged_and_request_keys_are_bounded(setup, monkeypatch):
732
  refused = [(e["event"], e["agent"], e["pr"], e["code"]) for e in events if e["event"].endswith("_refused")]
733
  assert refused == [("review_pr_refused", "cedar", rec["pr"], "tool_error"),
734
  ("merge_pr_refused", "birch", rec["pr"], "tool_error")]
735
- from flock.world import tool_schema
736
 
737
  schema = tool_schema(world.tools()["merge_pr"])
738
  assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema
@@ -803,12 +803,12 @@ def _module(clone, name, reply):
803
 
804
  def _commit(clone, message="change"):
805
  git(clone, "add", "-A")
806
- git(clone, "-c", "user.name=a", "-c", "user.email=a@flock.invalid", "commit", "-qm", message)
807
 
808
 
809
  def _rebase(clone):
810
  git(clone, "fetch", "-q", "origin")
811
- git(clone, "-c", "user.name=a", "-c", "user.email=a@flock.invalid", "rebase", "-q", "origin/main")
812
 
813
 
814
  def _two_prs(setup, edit_one, edit_two):
@@ -1437,10 +1437,10 @@ def test_update_refs_writes_both_refs_at_once(setup):
1437
  rec = submit(world, clone)
1438
  pr, head = rec["pr"], rec["head_sha"]
1439
  assert world.repo.sha(f"pr:{pr}") == head
1440
- assert world.repo.git("rev-parse", f"refs/flock/pr/{pr}/{head}") == head
1441
  main = world.repo.sha()
1442
- world.repo.update_refs((f"refs/pr/{pr}", main), (f"refs/flock/pr/{pr}/{main}", main))
1443
- assert world.repo.sha(f"pr:{pr}") == main == world.repo.git("rev-parse", f"refs/flock/pr/{pr}/{main}")
1444
 
1445
 
1446
  def _deck_line(clone, deck_id, *turns):
@@ -1541,7 +1541,7 @@ def test_git_maintenance_packs_refs_and_all_loose_objects_without_rewriting_pack
1541
  repo = world.repo
1542
  rec = submit(world, clone)
1543
  _module(clone, "weather", "sunny")
1544
- rec = submit(world, clone, pr=rec["pr"]) # a superseded head keeps its refs/flock/pr ref
1545
  assert repo.git("config", "maintenance.auto") == "false" # fetches start no background gc
1546
  assert repo.git("config", "gc.auto") == "0" # no git command starts gc --auto either
1547
  orphans = [repo.git("hash-object", "-w", "--stdin", data=f"orphan {i}".encode())
@@ -1561,7 +1561,7 @@ def test_git_maintenance_packs_refs_and_all_loose_objects_without_rewriting_pack
1561
  assert set(info) == {"loose_before", "pack_refs_s", "pack_loose_s", "packs", "loose_after"}
1562
  assert info["loose_after"] == "0"
1563
  assert not [f for f in (repo.root / "refs").rglob("*") if f.is_file()] # all in packed-refs
1564
- assert len(repo.git("for-each-ref", "--format=%(refname)", f"refs/flock/pr/{rec['pr']}/").split()) == 2
1565
  assert re.search(r"^count: 0$", repo.git("count-objects", "-v"), re.MULTILINE)
1566
  repo.git("cat-file", "-e", orphans[0]) # packed, not pruned
1567
  after = set(pack_dir.glob("pack-*.pack"))
@@ -2599,7 +2599,7 @@ def test_get_pr_is_a_registered_tool(setup):
2599
 
2600
 
2601
  def test_manifest_declares_workspace_uploads_and_timeouts(setup):
2602
- from flock.world.protocol import WorldManifest
2603
 
2604
  tools = {t.name: t for t in WorldManifest.model_validate(setup[0].manifest()).tools}
2605
  assert tools["open_pr"].workspace.arg == "path" and tools["open_pr"].workspace.default == "pybot"
@@ -2885,7 +2885,7 @@ def test_an_import_cut_before_its_commit_is_redone(setup):
2885
  world.store.close()
2886
  for f in world.ws.glob("state.db*"):
2887
  f.unlink()
2888
- from flock.world.store import Store
2889
 
2890
  Store(world.ws / "state.db").close() # a kill during the first import: schema, no rows
2891
  again = PybotWorld(world.ws, world.repo)
@@ -2920,7 +2920,7 @@ def test_old_merged_and_closed_prs_move_to_the_cold_table(setup):
2920
 
2921
 
2922
  def submit_v2(world, clone, author="cedar", branch="greeting", pr=None):
2923
- from flock.world.workspace import capture_v2
2924
  snapshot = capture_v2(clone.parent, clone.name)
2925
  assert "patch" in snapshot
2926
  return world.call_workspace("open_pr", {"branch": branch, "title": "Improve greetings",
@@ -2938,7 +2938,7 @@ def test_open_pr_and_run_bot_through_a_v2_patch(setup):
2938
  committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines()
2939
  assert "bot/modules/topic.py" in committed and not [n for n in committed if "__pycache__" in n]
2940
  assert git(remote, "show", f"{rec['head_sha']}:bot/modules/greeting.py").endswith('"Hey!"')
2941
- from flock.world.workspace import capture_v2
2942
  out = world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
2943
  Agent("cedar"), capture_v2(clone.parent, clone.name))
2944
  assert out["replies"] == ["Hey!"]
@@ -2950,7 +2950,7 @@ def test_open_pr_and_run_bot_through_a_v2_patch(setup):
2950
  def test_v2_with_an_unknown_base_asks_for_the_full_tree(setup, monkeypatch):
2951
  world, clone, _ = setup
2952
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
2953
- from flock.world.workspace import capture_v2
2954
  v2 = {**capture_v2(clone.parent, clone.name), "base_sha": "1" * 40}
2955
  args = {"branch": "topic", "title": "Topic module", "description": "tested"}
2956
  with pytest.raises(ToolError, match="base is not a main commit"): # a v1 resend can't help
@@ -2993,7 +2993,7 @@ def test_reviewer_cap_refuses_one_more_reviewer_and_hides_full_prs(setup, monkey
2993
 
2994
 
2995
  def test_adds_module_reads_v1_and_v2_uploads(setup):
2996
- from flock.world.workspace import capture_v2
2997
 
2998
  world, clone, _ = setup
2999
  base = git(clone, "rev-parse", "HEAD")
@@ -3181,7 +3181,7 @@ def test_a_create_whose_gap_wait_sees_main_move_opens_on_its_build(setup, monkey
3181
  gaps.append(deadline)
3182
  real_gap(agent, deadline)
3183
  tree = git(remote, "rev-parse", "main^{tree}")
3184
- moved = git(remote, "-c", "user.name=x", "-c", "user.email=x@flock.invalid",
3185
  "commit-tree", tree, "-p", "main", "-m", "a merge elsewhere")
3186
  git(remote, "update-ref", "refs/heads/main", moved)
3187
  world.repo.fetch()
 
15
  import httpx
16
  import pytest
17
 
18
+ from legion.world import Agent, ToolError
19
+ from legion.world.server import create_app
20
+ from legion.world.workspace import capture
21
 
22
  from conftest import ROOT, FakeBucket
23
 
 
53
  def merge(self, pr, comment): # like the Hub: a three-way merge of refs/pr/N into main
54
  main, head = git(self.remote, "rev-parse", "main"), git(self.remote, "rev-parse", f"refs/pr/{pr}")
55
  tree = git(self.remote, "merge-tree", "--write-tree", main, head).split()[0]
56
+ sha = git(self.remote, "-c", "user.name=world", "-c", "user.email=world@legion.invalid",
57
  "commit-tree", tree, "-p", main, "-p", head, "-m", comment)
58
  git(self.remote, "update-ref", "refs/heads/main", sha, main)
59
 
 
88
  shutil.copytree(ROOT / seed_dir, seed, ignore=shutil.ignore_patterns("__pycache__"))
89
  git(seed, "init", "-b", "main")
90
  git(seed, "add", ".")
91
+ git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-m", "seed")
92
  remote = tmp_path / "remote.git"
93
  git(tmp_path, "clone", "--bare", str(seed), str(remote))
94
  repo = Repository(tmp_path / "world.git", str(remote))
 
213
  async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://world") as client:
214
  payload = {"args": {"branch": "hello", "title": "Hello bot", "description": "tested"},
215
  "workspace": capture(clone.parent, clone.name)}
216
+ headers = {"X-World-Token": "secret", "X-Legion-Agent": "cedar"}
217
  r = await client.post("/tools/open_pr", json=payload, headers=headers)
218
  assert r.json()["ok"], r.text
219
  assert "secret" not in r.text
 
732
  refused = [(e["event"], e["agent"], e["pr"], e["code"]) for e in events if e["event"].endswith("_refused")]
733
  assert refused == [("review_pr_refused", "cedar", rec["pr"], "tool_error"),
734
  ("merge_pr_refused", "birch", rec["pr"], "tool_error")]
735
+ from legion.world import tool_schema
736
 
737
  schema = tool_schema(world.tools()["merge_pr"])
738
  assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema
 
803
 
804
  def _commit(clone, message="change"):
805
  git(clone, "add", "-A")
806
+ git(clone, "-c", "user.name=a", "-c", "user.email=a@legion.invalid", "commit", "-qm", message)
807
 
808
 
809
  def _rebase(clone):
810
  git(clone, "fetch", "-q", "origin")
811
+ git(clone, "-c", "user.name=a", "-c", "user.email=a@legion.invalid", "rebase", "-q", "origin/main")
812
 
813
 
814
  def _two_prs(setup, edit_one, edit_two):
 
1437
  rec = submit(world, clone)
1438
  pr, head = rec["pr"], rec["head_sha"]
1439
  assert world.repo.sha(f"pr:{pr}") == head
1440
+ assert world.repo.git("rev-parse", f"refs/legion/pr/{pr}/{head}") == head
1441
  main = world.repo.sha()
1442
+ world.repo.update_refs((f"refs/pr/{pr}", main), (f"refs/legion/pr/{pr}/{main}", main))
1443
+ assert world.repo.sha(f"pr:{pr}") == main == world.repo.git("rev-parse", f"refs/legion/pr/{pr}/{main}")
1444
 
1445
 
1446
  def _deck_line(clone, deck_id, *turns):
 
1541
  repo = world.repo
1542
  rec = submit(world, clone)
1543
  _module(clone, "weather", "sunny")
1544
+ rec = submit(world, clone, pr=rec["pr"]) # a superseded head keeps its refs/legion/pr ref
1545
  assert repo.git("config", "maintenance.auto") == "false" # fetches start no background gc
1546
  assert repo.git("config", "gc.auto") == "0" # no git command starts gc --auto either
1547
  orphans = [repo.git("hash-object", "-w", "--stdin", data=f"orphan {i}".encode())
 
1561
  assert set(info) == {"loose_before", "pack_refs_s", "pack_loose_s", "packs", "loose_after"}
1562
  assert info["loose_after"] == "0"
1563
  assert not [f for f in (repo.root / "refs").rglob("*") if f.is_file()] # all in packed-refs
1564
+ assert len(repo.git("for-each-ref", "--format=%(refname)", f"refs/legion/pr/{rec['pr']}/").split()) == 2
1565
  assert re.search(r"^count: 0$", repo.git("count-objects", "-v"), re.MULTILINE)
1566
  repo.git("cat-file", "-e", orphans[0]) # packed, not pruned
1567
  after = set(pack_dir.glob("pack-*.pack"))
 
2599
 
2600
 
2601
  def test_manifest_declares_workspace_uploads_and_timeouts(setup):
2602
+ from legion.world.protocol import WorldManifest
2603
 
2604
  tools = {t.name: t for t in WorldManifest.model_validate(setup[0].manifest()).tools}
2605
  assert tools["open_pr"].workspace.arg == "path" and tools["open_pr"].workspace.default == "pybot"
 
2885
  world.store.close()
2886
  for f in world.ws.glob("state.db*"):
2887
  f.unlink()
2888
+ from legion.world.store import Store
2889
 
2890
  Store(world.ws / "state.db").close() # a kill during the first import: schema, no rows
2891
  again = PybotWorld(world.ws, world.repo)
 
2920
 
2921
 
2922
  def submit_v2(world, clone, author="cedar", branch="greeting", pr=None):
2923
+ from legion.world.workspace import capture_v2
2924
  snapshot = capture_v2(clone.parent, clone.name)
2925
  assert "patch" in snapshot
2926
  return world.call_workspace("open_pr", {"branch": branch, "title": "Improve greetings",
 
2938
  committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines()
2939
  assert "bot/modules/topic.py" in committed and not [n for n in committed if "__pycache__" in n]
2940
  assert git(remote, "show", f"{rec['head_sha']}:bot/modules/greeting.py").endswith('"Hey!"')
2941
+ from legion.world.workspace import capture_v2
2942
  out = world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
2943
  Agent("cedar"), capture_v2(clone.parent, clone.name))
2944
  assert out["replies"] == ["Hey!"]
 
2950
  def test_v2_with_an_unknown_base_asks_for_the_full_tree(setup, monkeypatch):
2951
  world, clone, _ = setup
2952
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
2953
+ from legion.world.workspace import capture_v2
2954
  v2 = {**capture_v2(clone.parent, clone.name), "base_sha": "1" * 40}
2955
  args = {"branch": "topic", "title": "Topic module", "description": "tested"}
2956
  with pytest.raises(ToolError, match="base is not a main commit"): # a v1 resend can't help
 
2993
 
2994
 
2995
  def test_adds_module_reads_v1_and_v2_uploads(setup):
2996
+ from legion.world.workspace import capture_v2
2997
 
2998
  world, clone, _ = setup
2999
  base = git(clone, "rev-parse", "HEAD")
 
3181
  gaps.append(deadline)
3182
  real_gap(agent, deadline)
3183
  tree = git(remote, "rev-parse", "main^{tree}")
3184
+ moved = git(remote, "-c", "user.name=x", "-c", "user.email=x@legion.invalid",
3185
  "commit-tree", tree, "-p", "main", "-m", "a merge elsewhere")
3186
  git(remote, "update-ref", "refs/heads/main", moved)
3187
  world.repo.fetch()
world/vendor.sh CHANGED
@@ -1,54 +1,55 @@
1
  #!/bin/bash
2
- # vendor.sh: (re)build src/ (flock's World API library) and requirements.txt in this directory
3
- # from a flock checkout. The world's own code (pybot.py and the modules next to it) is never
4
  # touched here.
5
  #
6
- # ./vendor.sh FLOCK_DIR check + vendor at the commit in source-lock.json;
7
  # fails (nothing written) if any file's sha256 differs
8
- # ./vendor.sh FLOCK_DIR --lock REV re-pin: vendor REV and rewrite source-lock.json
9
  #
10
- # Reads FLOCK_DIR with `git archive` only (never checks out or switches branches there).
11
- # Needs git, python3, and uv (requirements.txt is `uv export` of flock's own uv.lock).
12
  set -euo pipefail
13
  die() { echo "vendor.sh: $*" >&2; exit 1; }
14
- [ $# -ge 1 ] || die "usage: vendor.sh FLOCK_DIR [--lock REV]"
15
- FLOCK=$1
16
  ROOT=$(cd "$(dirname "$0")" && pwd)
17
  LOCK=$ROOT/source-lock.json
18
 
19
  # What the world imports, transitively (pybot.py, repository.py, sandbox.py, snapshot.py and
20
- # flock.world.server.serve).
21
  FILES=(
22
- src/flock/__init__.py
23
- src/flock/isolation.py
24
- src/flock/models.py
25
- src/flock/registry.py
26
- src/flock/tools/__init__.py
27
- src/flock/tools/loader.py
28
- src/flock/worker/__init__.py
29
- src/flock/worker/sync.py
30
- src/flock/world/__init__.py
31
- src/flock/world/admin.py
32
- src/flock/world/lanes.py
33
- src/flock/world/protocol.py
34
- src/flock/world/server.py
35
- src/flock/world/store.py
36
- src/flock/world/workspace.py
 
37
  )
38
 
39
  if [ "${2:-}" = --lock ]; then
40
  [ -n "${3:-}" ] || die "--lock needs a revision"
41
  REV=$3
42
  else
43
- REV=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["flock_commit"])' "$LOCK")
44
  fi
45
- COMMIT=$(git -C "$FLOCK" rev-parse --verify "$REV^{commit}") || die "$REV is not a commit in $FLOCK"
46
 
47
  TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
48
  mkdir -p "$TMP/world" "$TMP/proj"
49
- git -C "$FLOCK" archive "$COMMIT" "${FILES[@]}" | tar -x -C "$TMP/world"
50
- git -C "$FLOCK" archive "$COMMIT" pyproject.toml uv.lock | tar -x -C "$TMP/proj"
51
- # The world needs flock's core and `controller` deps (fastapi, uvicorn), not Harbor or the board
52
  # client (msgboard is a git dependency, which pip's --require-hashes refuses): pruned.
53
  (cd "$TMP/proj" && uv export -q --frozen --no-emit-project --extra controller --no-dev --no-header \
54
  --prune harbor --prune podman-compose --prune msgboard -o "$TMP/requirements.txt")
@@ -62,8 +63,8 @@ got = {p.relative_to(tmp / "world").as_posix(): sha(p)
62
  for p in sorted((tmp / "world").rglob("*")) if p.is_file()}
63
  got = {"files": got, "requirements.txt": sha(tmp / "requirements.txt")}
64
  if mode == "--lock":
65
- lock.write_text(json.dumps({"flock_repo": "https://github.com/huggingface/flock",
66
- "flock_commit": commit, **got}, indent=2) + "\n")
67
  sys.exit(0)
68
  want = json.loads(lock.read_text())
69
  bad = sorted(k for k in want["files"].keys() | got["files"].keys()
@@ -77,4 +78,4 @@ PY
77
  rm -rf "$ROOT/src"
78
  mv "$TMP/world/src" "$ROOT/src"
79
  cp "$TMP/requirements.txt" "$ROOT/requirements.txt"
80
- echo "vendored flock $COMMIT: $(find "$ROOT/src" -type f | wc -l) files"
 
1
  #!/bin/bash
2
+ # vendor.sh: (re)build src/ (legion's World API library) and requirements.txt in this directory
3
+ # from a legion checkout. The world's own code (pybot.py and the modules next to it) is never
4
  # touched here.
5
  #
6
+ # ./vendor.sh LEGION_DIR check + vendor at the commit in source-lock.json;
7
  # fails (nothing written) if any file's sha256 differs
8
+ # ./vendor.sh LEGION_DIR --lock REV re-pin: vendor REV and rewrite source-lock.json
9
  #
10
+ # Reads LEGION_DIR with `git archive` only (never checks out or switches branches there).
11
+ # Needs git, python3, and uv (requirements.txt is `uv export` of legion's own uv.lock).
12
  set -euo pipefail
13
  die() { echo "vendor.sh: $*" >&2; exit 1; }
14
+ [ $# -ge 1 ] || die "usage: vendor.sh LEGION_DIR [--lock REV]"
15
+ LEGION=$1
16
  ROOT=$(cd "$(dirname "$0")" && pwd)
17
  LOCK=$ROOT/source-lock.json
18
 
19
  # What the world imports, transitively (pybot.py, repository.py, sandbox.py, snapshot.py and
20
+ # legion.world.server.serve).
21
  FILES=(
22
+ src/legion/__init__.py
23
+ src/legion/buckets.py
24
+ src/legion/isolation.py
25
+ src/legion/models.py
26
+ src/legion/registry.py
27
+ src/legion/tools/__init__.py
28
+ src/legion/tools/loader.py
29
+ src/legion/worker/__init__.py
30
+ src/legion/worker/sync.py
31
+ src/legion/world/__init__.py
32
+ src/legion/world/admin.py
33
+ src/legion/world/lanes.py
34
+ src/legion/world/protocol.py
35
+ src/legion/world/server.py
36
+ src/legion/world/store.py
37
+ src/legion/world/workspace.py
38
  )
39
 
40
  if [ "${2:-}" = --lock ]; then
41
  [ -n "${3:-}" ] || die "--lock needs a revision"
42
  REV=$3
43
  else
44
+ REV=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["legion_commit"])' "$LOCK")
45
  fi
46
+ COMMIT=$(git -C "$LEGION" rev-parse --verify "$REV^{commit}") || die "$REV is not a commit in $LEGION"
47
 
48
  TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
49
  mkdir -p "$TMP/world" "$TMP/proj"
50
+ git -C "$LEGION" archive "$COMMIT" "${FILES[@]}" | tar -x -C "$TMP/world"
51
+ git -C "$LEGION" archive "$COMMIT" pyproject.toml uv.lock | tar -x -C "$TMP/proj"
52
+ # The world needs legion's core and `controller` deps (fastapi, uvicorn), not Harbor or the board
53
  # client (msgboard is a git dependency, which pip's --require-hashes refuses): pruned.
54
  (cd "$TMP/proj" && uv export -q --frozen --no-emit-project --extra controller --no-dev --no-header \
55
  --prune harbor --prune podman-compose --prune msgboard -o "$TMP/requirements.txt")
 
63
  for p in sorted((tmp / "world").rglob("*")) if p.is_file()}
64
  got = {"files": got, "requirements.txt": sha(tmp / "requirements.txt")}
65
  if mode == "--lock":
66
+ lock.write_text(json.dumps({"legion_repo": "https://github.com/huggingface/legion",
67
+ "legion_commit": commit, **got}, indent=2) + "\n")
68
  sys.exit(0)
69
  want = json.loads(lock.read_text())
70
  bad = sorted(k for k in want["files"].keys() | got["files"].keys()
 
78
  rm -rf "$ROOT/src"
79
  mv "$TMP/world/src" "$ROOT/src"
80
  cp "$TMP/requirements.txt" "$ROOT/requirements.txt"
81
+ echo "vendored legion $COMMIT: $(find "$ROOT/src" -type f | wc -l) files"