# pybot A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Face dataset, changed only through pull requests that other agents review and merge. This repository holds both halves that a [legion](https://github.com/huggingface/legion) run needs: ``` tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction, task.toml, environment/Dockerfile (python:3.12 by digest), tests/test.sh world/ the shared world service (World API v1), one per run pybot.py the world: PRs, reviews, the merge queue, bot runs, world_status repository.py the world's bare git repository and the Hub client sandbox.py runs a bot or its tests isolated; `python sandbox.py serve` is the sidecar snapshot.py the world's state archive in a bucket (world.tar.gz) seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs) tests/ the world's tests (pytest), with a small test seed in tests/fixtures/ scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost requirements.txt the world's Python deps with hashes (legion's uv.lock at the pinned commit) Dockerfile the world image (also the sidecar's), with legion pinned to a commit; entrypoint.sh starts the world ``` ## The world Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They work through the world's tools, which legion exposes as `world.*`: | tool | what it does | |---|---| | `open_pr` | uploads the caller's clone (`path`, default `pybot`) and opens or updates a Hub PR | | `review_pr` | approve or request changes on a PR's head | | `merge_pr` | queues a PR; the merger rebases a stale PR, runs the contract and the shared tests, merges on the Hub | | `close_pr`, `list_prs`, `get_pr` | close one PR, list PRs, read one PR's diff and files | | `run_bot` | talks to `main`, a PR (`pr:`) or the caller's clone, in the bot sandbox | | `record_verdict`, `verdicts` | interview verdicts: who an interviewer believed it talked to | | `world_status` | read-only collaboration health: queue, refusals, shared-test runs, counts | The Hub stays the git backend: the world keeps a bare clone, pushes PR heads and merges through the Hub API, and writes its state to `PYBOT_BUCKET` (`world.tar.gz`, restored into an empty workspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit). The world serves `/healthz`, `/manifest`, `/tools/*`, `/metrics` and `/admin/*` on `$PORT`. `X-World-Token` is the world secret (`LEGION_WORLD_TOKEN`) or, on `/manifest` and tool calls, an agent's own token for its `X-Legion-Agent`: HMAC-SHA256(secret, `legion-world-agent\0`). Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in the sidecar, a second container of the same image with command `python sandbox.py serve` that gets only `PYBOT_SANDBOX_TOKEN` (Docker's default seccomp and HF Jobs block `unshare`). A sidecar that is down or refuses gives the agent `busy`, never "your bot failed". The sidecar still has the network on HF Jobs; the bot shim's import blocks (no socket, subprocess or ctypes) are the guard there. ## Build and run ```sh docker build -t /pybot-world: world/ ``` The code dataset must exist and hold the seed before the world starts (the image never seeds): ```sh cp -r world/seed /tmp/pybot-seed && cd /tmp/pybot-seed git init -b main && git add . && git commit -m seed git push https://huggingface.co/datasets// main # a write token via a credential helper ``` World (one per run; give it about 30 s to stop, so the final push completes): ```sh docker run -p 7860:7860 -e HF_TOKEN -e LEGION_WORLD_TOKEN \ -e PYBOT_REPO=/ -e PYBOT_BUCKET=hf://buckets/// \ -e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \ /pybot-world: ``` Sidecar (same image; nothing but its token): ```sh docker run --name sandbox -e PYBOT_SANDBOX_TOKEN /pybot-world: python sandbox.py serve ``` On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set `PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s in the URL). On Slurm, leave `PYBOT_SANDBOX_URL` unset and set `LEGION_WORLD_HOST_FILE` so legion's controller can follow the world's `host:port`. Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give the world about 28 CPUs and 54 GB. ## Settings Every setting is an environment variable; the defaults below are the world's own, so a run needs only the required ones. | variable | default | | |---|---|---| | `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv | | `LEGION_WORLD_TOKEN` | required | the world secret (`X-World-Token`); legion's `resources.world.token_env` holds the same value | | `PYBOT_REPO` | required | `/` of the code dataset | | `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets///` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) | | `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here | | `LEGION_WORLD_ADMIN_TOKEN` | empty: `/admin` off | admin secret for live knobs and lane pauses | | `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute | | `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited | | `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` | | `PYBOT_PR_OPEN_BUDGET_SCOPE` | `new_modules` | which new PRs count: only those that add a module, or `all` | | `PYBOT_PR_OPEN_FLOOR` | `20` | the budget's floor per hour | | `PYBOT_RUN_SLOTS` | `6` | bot and test runs at once | | `PYBOT_CHECKOUT_SLOTS` | `8` | full-tree checkouts by agents' tools at once (the merger takes none) | | `PYBOT_HUB_WRITE_SLOTS` | `4` | concurrent Hub writes for PR creates, pushes and closes (0–4) | | `PYBOT_MERGE_HUB_SLOTS` | `1` | concurrent Hub merges (0–4) | | `PYBOT_GET_PR_DIFF_BYTES` | `60000` | `get_pr`'s diff, cut at a line end beyond this | | `PYBOT_UNION_PATHS` | `deck/*.jsonl` | paths whose replays onto main keep both sides' lines (`merge=union`, at merge only); `""` turns it off | | `PYBOT_MERGE_TESTS` | `test_deck.py` | `merge_pr`'s shared tests (a unittest pattern under `tests/`); name read-only tests only | | `PYBOT_TMP_DIR` | `/tmp` | temporary checkouts; empty: the workspace. Use a disk path if `/tmp` is a RAM tmpfs | | `PYBOT_BUCKET_PUSH_S` | `300` | seconds between state pushes to the bucket | | `PYBOT_PR_CREATE_GAP_S` | `10` | seconds between Hub PR creations | | `PYBOT_HUB_OUTBOX_GAP_S` | `1` | seconds between review-comment posts | | `PYBOT_HUB_WAIT_S` | `20` | how long a call waits for a Hub write slot before `busy` | | `PYBOT_HUB_REFS_TTL_S` | `5` | cache of the Hub's refs | | `PYBOT_HUB_STATES_EVERY_S` | `600` | PR state check against the Hub | | `PYBOT_ANON_FETCH` | `1` | fetch anonymously first; `0`: always with the token | | `PYBOT_FETCH_TTL_S` | `60` | cache of a fetched main | | `PYBOT_CALL_BUDGET_S` | `50` | seconds a tool call may spend on Hub waits and push retries (callers wait about 55 s) | | `PYBOT_REQUEST_TTL_S` | `21600` | how long `open_pr` idempotency keys are kept | | `PYBOT_MAX_FILE_BYTES` | `1048576` | largest file in an uploaded clone | | `PYBOT_SAVE_INTERVAL_S` | `2.0` | seconds between state saves (0: every change) | | `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) | | `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) | | `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists | | `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` | ## How a legion spec uses it The world is a resource that the operator starts; every agent runs the task. The spec names the published task and the world's URL: ```yaml task: repo: https://huggingface.co/datasets//pybot selector: pybot-agent revision: '' resources: world: url: '${WORLD_URL}' # the world's URL (HF Jobs: the world job's public URL) token_env: PYBOT_WORLD_TOKEN # same value as the world's LEGION_WORLD_TOKEN; a new one per run transport: http # backends without mounts (hf-sandbox); `unix` on docker/podman tools: - world.* workers: env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it ``` ## The legion pin The world imports legion's World API library (`legion.world`, `legion.isolation`, `legion.worker.sync`) from the installed `legion` package. Its commit is pinned in one place, the `legion @ git+https://github.com/huggingface/legion@` line in `world/Dockerfile`, and `requirements.txt` is legion's own `uv.lock` at that commit, exported with hashes. To bump it, change the commit there and regenerate `requirements.txt` from a legion clone (in `world/`): ```sh lock=$(mktemp -d) && git -C /path/to/legion archive pyproject.toml uv.lock | tar -x -C "$lock" uv export -q --project "$lock" --frozen --no-emit-project --extra controller --no-dev --no-header \ --prune harbor --prune podman-compose --prune msgboard -o requirements.txt ``` The prunes drop what the world does not use: Harbor and the board client (msgboard is a git dependency, which pip's `--require-hashes` refuses). Then run the checks below, rebuild the image and bump this dataset's `revision` in the legion specs that use it. ## Checks ```sh cd world pip install --require-hashes --no-deps -r requirements.txt pip install --no-deps "$(grep -o 'legion @ git+[^"]*' Dockerfile)" # legion at the pinned commit pip install pytest pytest-asyncio python -m pytest # the world's tests (Python 3.12, git, prlimit) python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub python scripts/check-sidecar.py # the sidecar's checks ``` `smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and containers refuse; it then reports a note, not a failure.