diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b6cf5f03915e87f0609c2df330b54f34e9a99e1f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +.env diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f315f2b3b38b5e68cb38683d50c7a33705953241 --- /dev/null +++ b/README.md @@ -0,0 +1,168 @@ +# 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 [flock](https://github.com/huggingface/flock) 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 + src/ flock's World API library, vendored (never edit; vendor.sh) + requirements.txt the world's Python deps with hashes (from flock's uv.lock; vendor.sh) + source-lock.json the flock commit and the sha256 of every vendored file + vendor.sh re-vendor src/ and requirements.txt from a flock checkout + Dockerfile the world image (also the sidecar's); 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 flock 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 (`FLOCK_WORLD_TOKEN`) or, on `/manifest` and tool calls, +an agent's own token for its `X-Flock-Agent`: HMAC-SHA256(secret, `flock-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 FLOCK_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 `FLOCK_WORLD_HOST_FILE` so flock'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 | +| `FLOCK_WORLD_TOKEN` | required | the world secret (`X-World-Token`); flock'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 | +| `FLOCK_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`, `FLOCK_WORLD_HOST_FILE`, `WORLD_HOST` | `7860`, `/work`, unset, `$HOSTNAME` | entrypoint only: the port, the state directory, and where to write `host:port` | + +## How a flock 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 FLOCK_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 +``` + +## Checks + +```sh +cd world +pip install --require-hashes --no-deps -r requirements.txt && 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 +./vendor.sh /path/to/flock # the vendored library matches source-lock.json +``` + +`smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and +containers refuse; it then reports a note, not a failure. diff --git a/tasks/pybot-agent/environment/Dockerfile b/tasks/pybot-agent/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e601c6c39e9a64e5e60b831f9e7754901afcdfce --- /dev/null +++ b/tasks/pybot-agent/environment/Dockerfile @@ -0,0 +1,4 @@ +# The agent's own container, the same image as task.toml's docker_image: the full Python 3.12 +# image already has git, curl and bash (Harbor's Pi installer and flock's tools need them), and +# root is its default user (flock's tool setup and hf-sandbox need that). +FROM python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735 diff --git a/tasks/pybot-agent/instruction.md b/tasks/pybot-agent/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4cdcff886267f97e75284831cbd3bc43cd6a1ac6 --- /dev/null +++ b/tasks/pybot-agent/instruction.md @@ -0,0 +1,15 @@ +# pybot: one agent of a swarm + +You are one of several agents who build one chatbot together. Your container is your own; the +code, its pull requests and the message board are shared with the other agents. + +- The code is the Hugging Face dataset named in `$PYBOT_REPO`. Clone it once into + `pybot` in your working directory: + `git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot` +- Never push to it. Submit, review and merge through the world's tools: + `flock-tool world.tools` lists them with their parameters, and + `flock-tool world.call --json '{"tool": "", "args": {...}}'` calls one as you. + A tool that takes a clone path (open_pr's `path`, default `pybot`, relative to your + working directory) uploads that clone from your container. +- Talk to the other agents on the board with the board tools (`message_board.*`, + `message_board_extra.*`). diff --git a/tasks/pybot-agent/task.toml b/tasks/pybot-agent/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee3cf59241e491cefaeea050c2e0ab8759121b9a --- /dev/null +++ b/tasks/pybot-agent/task.toml @@ -0,0 +1,32 @@ +# One agent of a pybot swarm: one Harbor Trial per agent, each on its own copy of this task. The +# shared state is outside the task: the pybot world (flock's resources.world, tools world.*; its +# code is ../../world) and the board (resources.message_board, tools message_board.*). No +# per-agent reward: tests/test.sh writes 0. +schema_version = "1.4" + +[task] +name = "flock/pybot-agent" +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." + +[metadata] +world = "pybot" +world_version = "1.0.0" +world_api = "v1" + +[agent] +timeout_sec = 10800.0 # flock's limits.agent_timeout_seconds overrides it + +[verifier] +timeout_sec = 60.0 + +[environment] +# = environment/Dockerfile (nothing to build): hf-sandbox needs a prebuilt image and docker +# prefers it. Python 3.12, git, curl and bash; root is the default user. +docker_image = "python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735" # python:3.12.15-bookworm; digest-only: HF Jobs' default job name from a tagged digest exceeds 100 chars +cpus = 2 +memory_mb = 4096 + +[environment.env] +PYBOT_REPO = "${PYBOT_REPO}" # / HF dataset the world serves; from the launcher's env, no default +# Caps git's memory in the agent's clone (many agents share a machine). +GIT_CONFIG_PARAMETERS = "'pack.windowMemory=256m' 'pack.threads=1' 'gc.auto=0'" diff --git a/tasks/pybot-agent/tests/test.sh b/tasks/pybot-agent/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a55e35204a18a4164e9a25540dc2eed8c4ff673b --- /dev/null +++ b/tasks/pybot-agent/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# No per-agent reward: every agent scores 0, a valid reward (a Trial without one counts as failed). +mkdir -p /logs/verifier +echo 0 > /logs/verifier/reward.txt diff --git a/world/Dockerfile b/world/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5905ec26b8281d99aed40e256e0a67c74b1264f5 --- /dev/null +++ b/world/Dockerfile @@ -0,0 +1,29 @@ +# pybot world image: World API v1 on $PORT (7860). Build from this directory: +# docker build -t /pybot-world: world/ +# The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is +# pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on +# 3.12+); Python deps are flock's own uv.lock (exact versions + hashes, see vendor.sh). +FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70 + +# git: the world's bare repo, fetches and pushes to the Hub. util-linux (unshare) ships in the base. +RUN apt-get update \ + && apt-get install -y --no-install-recommends git \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt /opt/world/requirements.txt +RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt + +# src/: flock's World API library, vendored by vendor.sh (hashes in source-lock.json), never edited. +COPY src/ /opt/world/src/ +COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/ +COPY seed/ /opt/world/seed/ +COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint + +RUN useradd -m -u 1000 user && mkdir -p /work && chown user:user /work +USER user +# For the sidecar's bare `python sandbox.py serve` (a job command replaces the entrypoint); the +# entrypoint sets its own PYTHONPATH and cwd, so the world does not depend on these. +ENV PYTHONPATH=/opt/world/src +WORKDIR /opt/world +EXPOSE 7860 +ENTRYPOINT ["/usr/local/bin/pybot-entrypoint"] diff --git a/world/entrypoint.sh b/world/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..60748629897d2e5111e297a0bfc8d89c432c0118 --- /dev/null +++ b/world/entrypoint.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# pybot-entrypoint: check the env, then serve the pybot world on $PORT (`python pybot.py`). +# +# The world keeps its own state in PYBOT_BUCKET: an empty PYBOT_WS is restored from +# /world.tar.gz before it serves (a failed restore parks the world, which retries with +# backoff; /healthz says "parked"), and it pushes every PYBOT_BUCKET_PUSH_S (300) and at exit +# (SIGTERM, or SIGUSR1, which the server turns into SIGTERM). +# +# Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless. +# +# Required env: HF_TOKEN FLOCK_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET +# (hf://buckets///, or "off" for no restore and no pushes: smoke tests only). +# Optional: PORT (7860), FLOCK_WORLD_HOST_FILE (writes host:port there: the file flock's controller +# follows), WORLD_HOST ($HOSTNAME), PYBOT_WORK (/work), every PYBOT_* world setting, and +# PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here). +set -euo pipefail +die() { printf '%s pybot-entrypoint: FATAL: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 2; } + +for v in HF_TOKEN FLOCK_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET; do + [ -n "${!v:-}" ] || die "$v is not set" +done +[ -z "${PYBOT_SANDBOX_URL:-}" ] || [ -n "${PYBOT_SANDBOX_TOKEN:-}" ] \ + || die "PYBOT_SANDBOX_URL is set but PYBOT_SANDBOX_TOKEN is not (the sidecar would refuse every run)" +case ${PYBOT_BUCKET%/} in + off) unset PYBOT_BUCKET ;; # the world: no PYBOT_BUCKET = no restore and no pushes + hf://buckets/*/*) ;; + *) die "PYBOT_BUCKET must be hf://buckets//[/prefix] or off" ;; +esac +export PORT=${PORT:-7860} +case $PORT in ''|*[!0-9]*|0) die "PORT=$PORT must be a positive integer";; esac + +WORLD=${WORLD_DIR:-/opt/world} +WORK=${PYBOT_WORK:-/work} +# Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container. +export PYTHONPATH=$WORLD/src HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp +export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1 +mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK" + +if [ -n "${FLOCK_WORLD_HOST_FILE:-}" ]; then # atomic: flock's controller re-reads it every 15 s + { echo "${WORLD_HOST:-$HOSTNAME}:$PORT" > "$FLOCK_WORLD_HOST_FILE.tmp" && mv "$FLOCK_WORLD_HOST_FILE.tmp" "$FLOCK_WORLD_HOST_FILE"; } \ + || echo "pybot-entrypoint: cannot write $FLOCK_WORLD_HOST_FILE" >&2 +fi + +cd "$WORLD" || die "cannot cd $WORLD" +exec python pybot.py # serve() on 0.0.0.0:$PORT; the token comes from FLOCK_WORLD_TOKEN, never argv diff --git a/world/pybot.py b/world/pybot.py new file mode 100644 index 0000000000000000000000000000000000000000..4ecb0c8e1358dcb37ca2873dc0f2fb87d0a22df3 --- /dev/null +++ b/world/pybot.py @@ -0,0 +1,2217 @@ +"""Run-4 world: local snapshots, native Hub PRs and independent reviews.""" +from __future__ import annotations + +import atexit +import base64 +import collections +import concurrent.futures +import contextlib +import contextvars +import functools +import hashlib +import inspect +import json +import logging +import marshal +import math +import os +import re +import tempfile +import threading +import time +import uuid +from pathlib import Path, PurePosixPath +from typing import ClassVar, Literal + +import snapshot +from repository import Hub, Repository +from sandbox import run, run_tests + +from flock.isolation import protect_supervisor +from flock.world import Agent, ToolError, World, tool +from flock.world.lanes import Lane, LaneBusy, Lanes +from flock.world.store import Store +from flock.world.workspace import apply_patch, unpack + +HERE = Path(__file__).resolve().parent +UPLOAD = contextvars.ContextVar("workspace", default=None) +FIXED = ("bot/__init__.py", "bot/__main__.py", "bot/runtime.py", "bot/modules/__init__.py") +# A module the loader finds: bot/modules/.py or a package bot/modules//__init__.py. +MODULE_FILE = re.compile(r"bot/modules/(?:[^/]+\.py|[^/]+/__init__\.py)") +MAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20))) +EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/", + "*.egg-info/", ".DS_Store") +MAX_REQUESTS = 5000 # open_pr idempotency keys kept for worker retries (oldest dropped) +# ... and for at most this long (a worker retries within minutes). +REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600")) +# state.db (and prs.json, see save.legacy_json) is written by a background thread at most once +# per this many seconds while the state changed (0: write synchronously on every change). +# close() always writes it. +SAVE_INTERVAL = float(os.environ.get("PYBOT_SAVE_INTERVAL_S", "2.0")) +FETCH_TTL = float(os.environ.get("PYBOT_FETCH_TTL_S", "60")) +NAME = re.compile(r"^[a-z][a-z0-9-]{0,63}$") +# A world tool call must answer within about 55 s (the worker's deadline); Hub waits and push +# retries stay inside this budget, counted from the start of the call. +CALL_BUDGET = float(os.environ.get("PYBOT_CALL_BUDGET_S", "50")) +PUSH_RETRY_DELAYS = (2, 5) +PUSH_ESTIMATE_S = 8.0 # time kept free for one more push attempt +CHECKOUT_WAIT_S = 10.0 # an agent's tool waits this long for a checkout slot, then gets "busy" +BUSY = "the Hub is busy; retry in about a minute" +INBOX_MAX = 20 # unread inbox entries kept per agent (oldest dropped) +INBOX_SNIPPET = 160 # review comment characters quoted in an inbox entry +PAUSED = "PRs are paused by the operators; keep working locally, run_bot and reviews still work" +WINDOW = 3600.0 # the new-PR budget counts opens and merges in this rolling window (seconds) +WINDOW_MAX = 10000 # timestamps kept per list (oldest dropped) +OUTBOX_BACKOFF = (5.0, 600.0) # first retry delay, longest retry delay (doubling, forever) +HUB_SYNC_EVERY = float(os.environ.get("PYBOT_HUB_STATES_EVERY_S", "600")) # PR state check +GIT_MAINTAIN_EVERY = 1800.0 # refs and loose objects packed (the hub-sync thread) +FINAL_CODES = ("pr_closed", "pr_merged") +# Hub write failures that feed a lane's breaker: "vote failed: transaction was aborted" and +# other Hub-side refusals arrive as one of these (git push or HTTP API). +TRANSIENT_CODES = ("git_error", "hub_error") +COMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub post +# get_pr: diff bytes returned (cut at a line end, with truncated: true beyond this). +MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000")) +# State rows in state.db (flock.world.store): these top-level dicts get one row per entry; +# every other top-level value (pr_opens, pr_merges) is one row of kind "_". +KINDS = ("prs", "requests", "drafts", "inbox") +COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this +VERDICTS_MAX = 2000 # interview verdicts kept (oldest dropped) +VERDICT_NOTES = 600 # note characters kept per verdict +DESCRIPTION_CHARS = 4000 # PR description characters returned by get_pr # Hub 400: the PR is already closed / merged +# merge_pr runs the repository's tests/ files matching this unittest pattern on the tree it is +# about to make main ("" disables): the cheap checks of what two PRs can break together. +MERGE_TESTS = os.environ.get("PYBOT_MERGE_TESTS", "test_deck.py").strip() +MERGE_TESTS_TIMEOUT_S = 60.0 # past this the shared tests are skipped (logged), not failed +# The merge queue: failures that keep a PR queued, retried after its own backoff (first +# delay, longest delay; doubling) while the PRs behind it go ahead. +MERGE_RETRY_CODES = (*TRANSIENT_CODES, "hub_busy", "busy", "stale_lease", "paused") +MERGE_BACKOFF = (5.0, 600.0) +MERGE_REASON = 1500 # refusal characters quoted in the inbox +STATUS_QUEUE_MAX = 50 # entries per list in world_status (the counts give the totals) +log = logging.getLogger(__name__) +_LIVE: dict[str, PybotWorld] = {} # one world per state directory: a restart replaces it + + +def _key(key): + """A dict key as json.dumps writes it.""" + return json.dumps(key) if isinstance(key, str) else json.dumps({key: 0})[1:-4] + + +@contextlib.contextmanager +def _timed(steps, name): + """Add the block's seconds to steps[name] (merge_pr's timing line).""" + start = time.monotonic() + try: + yield + finally: + steps[name] = steps.get(name, 0.0) + time.monotonic() - start + + +@atexit.register +def _close_all(): + for world in list(_LIVE.values()): + world.close() + + +def logs_refusals(fn): + """Log a refused PR operation to prs.jsonl (code and message only), then re-raise.""" + signature = inspect.signature(fn) + + @functools.wraps(fn) + def wrapper(self, *args, **kwargs): + try: + return fn(self, *args, **kwargs) + except ToolError as exc: + bound = signature.bind_partial(self, *args, **kwargs).arguments + agent = bound.get("agent") + if isinstance(agent, Agent): + self._event(f"{fn.__name__}_refused", agent, pr=bound.get("pr"), + code=exc.code, reason=exc.message[:500]) + raise + return wrapper + + +class PybotWorld(World): + name, version = "pybot", "1.0.0" + concurrent = True + capabilities: ClassVar[list[str]] = ["workspace-upload-v1", "workspace-upload-v2"] + description = ("Edit your local git clone, then submit with open_pr. Another agent must " + "approve the PR's current change (a clean rebase keeps the approval) before merge; " + "merge_pr queues a PR and the world merges the queue in order, rebasing each PR " + "onto the current main itself. Bot input/output and module loading " + "are fixed; edit bot/modules/. run_bot allows 300 seconds per conversation. " + "Tool results may carry an `inbox` with news about your PRs (reviews, " + "merges and refused merges, closes, updates); handle it first. New PRs are limited swarm-wide to " + "about the merge rate (pr_budget).") + + # The worker uploads the caller's local clone for these calls (workspace-upload-v1). + WORKSPACE: ClassVar[dict] = { + "open_pr": {"arg": "path", "default": "pybot"}, + "run_bot": {"arg": "ref_or_path", "default": "main", "skip": ["main"], "skip_prefix": "pr:"}, + } + MERGER: ClassVar[bool] = True # start the merge queue's thread (tests run it by hand: _merge_next) + + def manifest(self) -> dict: + m = super().manifest() + for t in m["tools"]: + t["x-flock-timeout_s"] = 330 # a 300 s run_bot conversation plus the upload + if t["name"] in self.WORKSPACE: + t["x-flock-workspace"] = self.WORKSPACE[t["name"]] + return m + + def __init__(self, ws=None, repository=None): + protect_supervisor() + self.ws = Path(ws or os.environ.get("PYBOT_WS", HERE / "ws")) + self.ws.mkdir(parents=True, exist_ok=True) + # Temporary checkouts and builds (PYBOT_TMP_DIR, default /tmp; empty: the workspace; + # use a disk path if /tmp is a RAM tmpfs). They share the repository's objects through + # alternates, never hardlinks. + self.tmp_dir = Path(os.environ.get("PYBOT_TMP_DIR", "/tmp") or self.ws) + self.tmp_dir.mkdir(parents=True, exist_ok=True) + previous = _LIVE.get(str(self.ws.resolve())) + if previous is not None: # flush and stop its outbox before reading the saved state + previous.close() + # PYBOT_BUCKET (hf://buckets///): its world.tar.gz (snapshot.py) is + # this world's state across jobs: restored into an empty workspace before anything + # reads it, pushed every PYBOT_BUCKET_PUSH_S and at close. + self.bucket = os.environ.get("PYBOT_BUCKET", "").strip().rstrip("/") + self.push_every = float(os.environ.get("PYBOT_BUCKET_PUSH_S", "300")) + self.push_lock = threading.Lock() + if self.bucket: + self._restore() + # Lock order: Hub write lane slot, then main_lock, then self.lock (the state lock). + self.lock = threading.RLock() + # The compare-and-swap on main: held by merges across the Hub merge and the fetch that + # moves local main. The state lock is taken only around record reads and updates, never across a Hub call. + self.main_lock = threading.Lock() + self.ancestry = {} # (head, main sha) -> head is in main; read and written under self.lock + self.db = self.ws / "prs.json" + for stale in self.ws.glob("prs.json.*.tmp"): # a write cut by a crash + stale.unlink(missing_ok=True) + old_json = json.loads(self.db.read_text()) if self.db.exists() else None + # Saving (see _save): every change marks its rows dirty (_dirty) and bumps save_gen; + # the saver writes the dirty rows to state.db and, while save.legacy_json is on, the + # whole state to prs.json (written_gen is the generation in prs.json). + self.save_interval = self.knob( # admin knobs (flock.world.admin): the env sets the default + "save.interval_s", float, float(os.environ.get("PYBOT_SAVE_INTERVAL_S", SAVE_INTERVAL)), + min=0, doc="Seconds between state saves (0: write on every change).", + on_change=lambda v: setattr(self, "save_interval", v)) + self.legacy_json = self.knob( + "save.legacy_json", bool, True, + doc="Also write the whole state to prs.json (compared with state.db at start).", + on_change=lambda v: setattr(self, "legacy_json", v)) + self.ended = {} # merged/closed PR number -> unix time first seen ended (for the cold move) + self.store = Store(self.ws / "state.db") + # Decided on rows, not on the file: an import cut by a kill leaves an empty state.db. + # Every import writes the pr_opens and pr_merges rows. + migrate = next(self.store.iter("_"), None) is None + empty = {**{kind: {} for kind in KINDS}, "pr_opens": [], "pr_merges": []} + if migrate: # first start, or an archive with prs.json and no state.db: import prs.json + self.state = {**empty, **(old_json or {})} + self.store.write(list(self._rows())) + if old_json is not None: + log.warning("state: migrated prs.json to state.db (%d PRs)", len(self.state["prs"])) + else: + self.state = {name: value.copy() for name, value in empty.items()} + for kind in KINDS: + for key, value in self.store.iter(kind): + self.state.setdefault(kind, {})[key] = value + self.state.update(self.store.iter("_")) + # Pruning expects oldest first; an upsert keeps a re-cached key's first position. + self.state["requests"] = dict(sorted(self.state["requests"].items(), + key=lambda kv: kv[1].get("_ts", 0))) + if old_json is not None and self.legacy_json and {**empty, **old_json} != self.state: + log.warning("state: prs.json and state.db differ at start; using state.db") + self.cold_branches = {rec["branch"] for _, rec in self.store.iter("prs", cold=True)} + now = time.time() + for key, rec in self.state["prs"].items(): + if rec["state"] in ("merged", "closed"): + self.ended[key] = rec.get("ended_at", now) + self.save_gen = self.written_gen = 0 + self.save_sync = self.save_interval <= 0 # also set by close(): later saves write at once + self.replace_lock = threading.Lock() # a leaf lock: never take self.lock while holding it + self.save_wake = threading.Event() + self.save_stop = threading.Event() + self.saver = None + # For metrics(): the last state.db write and in-memory counters since start. + self.save_s, self.saved_at = 0.0, time.time() + self.budget_refusals = [] # unix times of open_budget refusals (last WINDOW seconds) + self.stale_adoptions = self.hub_busy_total = self.comments_rejected = 0 + self.counts_lock = threading.Lock() # a leaf lock: the counters above, from tool threads + self.repo_id = repo_id = os.environ.get("PYBOT_REPO", "") + if repository is None and not repo_id: + raise ValueError("PYBOT_REPO is not set: the / Hub dataset with the code") + self.repo = repository or Repository(self.ws / "repo.git", + f"https://huggingface.co/datasets/{repo_id}", Hub(repo_id)) + # The seed whose fixed files the contract compares (PYBOT_SEED_DIR: a directory + # next to this file, or an absolute path). + self.seed_dir = HERE / os.environ.get("PYBOT_SEED_DIR", "seed") + self.fixed = {name: (self.seed_dir / name).read_bytes() for name in FIXED} + self.slots = threading.BoundedSemaphore(int(os.environ.get("PYBOT_RUN_SLOTS", "6"))) + # Full-tree checkouts (+ build) by agents' tools; the merger takes none, so it never waits + # behind them. Uncapped, tens at once saturate the CPUs and each checkout slows 100-fold. + self.checkouts = threading.BoundedSemaphore(int(os.environ.get("PYBOT_CHECKOUT_SLOTS", "8"))) + # (main sha, the shared tests pass on it; None: they timed out there), see _shared_tests + self.main_tests = (None, False) + # PR number -> (head, main, code, message) of its last merge refused by the checks of + # that head on that main: merge_pr answers a re-queue of both at once (agents retry). + self.refused = {} + # For world_status, in memory only (a restart starts them empty): merge-queue refusals + # {"ts", "pr", "code"} and shared-test runs {"ts", "main_sha", "result", "seconds"}. + self.merge_refusals = collections.deque(maxlen=1000) + self.test_runs = collections.deque(maxlen=200) + self.pending = {} # open_pr reservations: token -> (author, branch ref, pr or None, key) + self.operators = {n.strip() for n in os.environ.get("PYBOT_OPERATORS", "").split(",") if n.strip()} + # Pause open_pr/merge_pr: PYBOT_PRS_PAUSED=1 at start, or the flag file, checked per call. + self.paused_env = os.environ.get("PYBOT_PRS_PAUSED", "").strip() not in ("", "0") + self.pause_file = Path(os.environ.get("PYBOT_PRS_PAUSED_FILE") or self.ws / "prs-paused") + # Every Hub write holds a slot of its lane (one IP and one token cannot write for 140 + # agents at once): "push" for creating, pushing, readying and closing PRs, "merge" for + # merges (never queued behind pushes, whose wait would let main or the PR move under + # its checks), "comment" for review comments, posted from the outbox. Each lane has a + # breaker (flock.world.lanes); the pause covers push and merge. Lock order: see self.lock. + # Admin pauses (POST /admin/pause) apply per lane; the pause flag pauses push and merge. + self.lanes = Lanes({"push": Lane(), "merge": Lane(), "comment": Lane()}, dir=self.ws, + paused=lambda lane: self.paused(lane) or ( + lane in ("push", "merge") and self._prs_paused()), + breaker_groups=[("push", "merge")]) # both move refs: "vote failed" hits both + for lane, env, default in (("push", "PYBOT_HUB_WRITE_SLOTS", "4"), + ("merge", "PYBOT_MERGE_HUB_SLOTS", "1"), ("comment", None, "1")): + self.lanes[lane].configure(slots=self.knob( + f"hub.{lane}.slots", int, int(os.environ.get(env, default) if env else default), + min=0, max=4, doc=f"Concurrent Hub writes in the {lane} lane (a tripped lane uses 1).", + on_change=lambda v, lane=lane: self.lanes[lane].configure(slots=v))) + self.lanes["comment"].configure(gap_s=self.knob( + "hub.comment.gap_s", float, float(os.environ.get("PYBOT_HUB_OUTBOX_GAP_S", "1")), + min=0, max=60, doc="Seconds between review comment posts (a tripped lane uses 5).", + on_change=lambda v: self.lanes["comment"].configure(gap_s=v))) + self.hub_wait = float(os.environ.get("PYBOT_HUB_WAIT_S", "20")) + self.pr_gap = float(os.environ.get("PYBOT_PR_CREATE_GAP_S", "10")) + self.gap_lock = threading.Lock() + self.last_create = float("-inf") # monotonic time of the last (reserved) PR creation + # Hub PRs whose head could not be pushed: branch ref -> draft, reused by the next open_pr. + self.state.setdefault("drafts", {}) + # Unread news per agent: name -> [{"pr", "kind", "text", "ts"}], newest last. + self.state.setdefault("inbox", {}) + # Interview verdicts (record_verdict), oldest first. + # shortcut: one "_" row rewritten on each verdict; move to a KINDS table if verdicts get frequent. + self.state.setdefault("verdicts", []) + # The merge queue, merged first to last: {"pr", "by" (who queued it), "ts", "tries", + # "next_at"} (see merge_pr and _merge_next). + self.state.setdefault("merge_queue", []) + self.merge_wake = threading.Event() + # New-PR budget: Hub PR creations and merges (unix times, last WINDOW seconds). + self.state.setdefault("pr_opens", []) + self.state.setdefault("pr_merges", []) + budget = os.environ.get("PYBOT_PR_OPEN_BUDGET", "merges").strip().lower() or "merges" + if budget not in ("merges", "off"): + raise ValueError("PYBOT_PR_OPEN_BUDGET must be merges or off") + self.budget_on = budget == "merges" + # all: every new PR counts; new_modules: only a PR that adds a module counts (and + # waits), so fixes, reverts, tests and edits of existing modules are never rationed. + scope = os.environ.get("PYBOT_PR_OPEN_BUDGET_SCOPE", "new_modules").strip().lower() or "all" + if scope not in ("all", "new_modules"): + raise ValueError("PYBOT_PR_OPEN_BUDGET_SCOPE must be all or new_modules") + self.budget_scope = scope + self.max_reviewers = self.knob( + "review.max_reviewers", int, int(os.environ.get("PYBOT_MAX_REVIEWERS", "2")), min=0, + doc="Reviewers per PR change (0: unlimited); one more is refused with review_full.", + on_change=lambda v: setattr(self, "max_reviewers", v)) + self.budget_floor = self.knob( + "pr.open_floor", int, int(os.environ.get("PYBOT_PR_OPEN_FLOOR", "20")), min=0, + doc="New PRs allowed per hour however few merged (the open budget's floor).", + on_change=lambda v: setattr(self, "budget_floor", v)) + self.open_reserved = set() # new-PR calls past the budget check, Hub PR not yet created + self.stopping = threading.Event() + with self.lock: # cached results stored in full are slimmed: the first save is already small + if self._slim_requests(): + self._save() + with self.lock: # the archive may predate merges that already landed on the Hub + for rec in self.state["prs"].values(): + if rec["state"] in ("closing", "merging"): # interrupted: the agent may retry + rec["state"] = "open" + self._dirty("prs", rec["pr"]) + self._fetch_missing_heads() + self._reconcile() + self.hub_states_at = float("-inf") + self._sync_hub_states() # outside the lock: a Hub read + # Review comments wait in the comment lane's outbox (outbox-comment.jsonl); its thread + # posts them, joining the comments of one PR that piled up. + self.outbox = self.lanes.outbox("comment", drain=self._post, backoff=OUTBOX_BACKOFF) + legacy = self.state.pop("hub_outbox", None) # a prs.json that holds the comment outbox + if legacy is not None: + for entry in legacy: + self.outbox.put(entry["pr"], entry["text"]) + with self.lock: + self._dirty("_", "hub_outbox") + self._save() + self.syncer = threading.Thread(target=self._sync_loop, name="pybot-hub-sync", daemon=True) + self.syncer.start() + if self.bucket: + threading.Thread(target=self._push_loop, name="pybot-bucket", daemon=True).start() + if not self.save_sync: + self.saver = threading.Thread(target=self._saver, name="pybot-save", daemon=True) + self.saver.start() + self.merger = threading.Thread(target=self._merge_loop, name="pybot-merge-queue", daemon=True) + if self.MERGER: + self.merger.start() + _LIVE[str(self.ws.resolve())] = self + + # -- review comment outbox ------------------------------------------------------------- + + def _queue_comment(self, agent, pr, text): + """Queue a Hub comment; the comment lane's outbox posts it.""" + self.outbox.put(pr, text) + + def _post(self, pr, texts): + """Outbox drain: post the queued comments of PR pr as one Hub comment (the caller holds + a comment lane slot). Returns "ok", "transient", "final" (closed or merged, or the Hub + refused a single comment with a 4xx other than 429) or "split" (it refused the joined + comments: post them one by one).""" + try: + self.repo.hub.comment(pr, COMMENT_SEPARATOR.join(texts)) + return "ok" + except Exception as exc: # noqa: BLE001 -- retried later, never raised to a tool call + failure = getattr(exc, "code", type(exc).__name__) + status = getattr(exc, "status", None) + if failure in FINAL_CODES: # the PR is closed or merged: no point retrying + self._mark_hub_final(pr, failure) + log.warning("hub_outbox: dropped %d comment(s) on PR #%s: already %s on the Hub", + len(texts), pr, failure[3:]) + return "final" + if isinstance(status, int) and 400 <= status < 500 and status != 429: + if len(texts) > 1: + log.warning("hub_outbox: Hub refused %d joined comments on PR #%s (HTTP %s); " + "posting them one by one", len(texts), pr, status) + return "split" + self._count("comments_rejected") + log.warning("hub_outbox: dropped a comment on PR #%s: the Hub refused it (HTTP %s, " + "%d chars)", pr, status, len(texts[0])) + return "final" + log.warning("hub_outbox: comment on PR #%s failed (%s)", pr, failure) + return "transient" + + def _sync_loop(self): + """Background thread: reconcile PR states with the Hub every HUB_SYNC_EVERY, and keep the + repository healthy every GIT_MAINTAIN_EVERY.""" + maintained = time.monotonic() + while not self.stopping.wait(5.0): + self._sync_hub_states(every=HUB_SYNC_EVERY) + if time.monotonic() - maintained >= GIT_MAINTAIN_EVERY: + self._maintain_repo() + maintained = time.monotonic() # the period counts from the end of a pass + + def _maintain_repo(self): + """Pack refs and loose objects (Repository.maintain). Never raises.""" + info = {} + try: + self.repo.maintain(info) + outcome = "done" + except Exception as exc: # noqa: BLE001 - retried at the next period + outcome = f"failed ({type(exc).__name__})" + line = " ".join(f"{k}={v:.1f}" if isinstance(v, float) else f"{k}={v}" for k, v in info.items()) + (log.info if outcome == "done" else log.warning)("git maintenance %s: %s", outcome, line) + + def close(self, timeout=4.0): + """Write the state now and stop the background threads within timeout seconds in all + (under the world host's 5 s stop grace); queued comments stay in the outbox file for + the next start. Saves after this write synchronously.""" + end = time.monotonic() + timeout + self.save_sync = True + self.save_stop.set() + self.save_wake.set() + if self.saver is not None: # its write in flight: a restart deletes leftover tmp files + self.saver.join(timeout) + self.flush() + self.stopping.set() + self.merge_wake.set() # a merge in flight finishes in its daemon thread or dies with the process + self.lanes.close(max(0.0, end - time.monotonic())) + self.flush() + self.store.checkpoint() + if self.bucket: + self._push() + if _LIVE.get(str(self.ws.resolve())) is self: + del _LIVE[str(self.ws.resolve())] + + # -- world archive in PYBOT_BUCKET ---------------------------------------------------- + + def _restore(self): + """Fill an empty workspace from the bucket's archive (none there: a first start). A + workspace that already holds a world must be this bucket's (the marker), so its + pushes never overwrite another run's archive.""" + marker = self.ws / ".pybot-bucket" + if marker.exists() or (self.ws / "repo.git").exists(): + owner = marker.read_text().strip() if marker.exists() else "no bucket" + if owner != self.bucket: + raise RuntimeError(f"PYBOT_WS {self.ws} holds the world of {owner}, not of " + f"PYBOT_BUCKET {self.bucket}: use an empty directory") + return # this bucket's world, as new as its last push or newer + found = snapshot.transfer("restore", self.ws, self.bucket) + log.warning("world state: %s/world.tar.gz %s", self.bucket, + "restored" if found else "not found: a first start") + marker.write_text(self.bucket + "\n") + + def _push(self): + """world.tar.gz to the bucket now; a failure is logged and the next push retries.""" + with self.push_lock: + try: + snapshot.transfer("push", self.ws, self.bucket) + except Exception: # the state stays in the workspace + log.exception("world state: push to %s failed", self.bucket) + + def _push_loop(self): + while not self.stopping.wait(self.push_every): + self._push() + + # -- new-PR budget --------------------------------------------------------------------- + + @staticmethod + def _recent(stamps, now): + """Drop timestamps older than WINDOW (in place); return the list.""" + cut = now - WINDOW + stamps[:] = [t for t in stamps if t > cut][-WINDOW_MAX:] + return stamps + + def _budget(self): + """Current new-PR budget (call with the lock held).""" + now = time.time() + opens = self._recent(self.state["pr_opens"], now) + merges = self._recent(self.state["pr_merges"], now) + limit = max(len(merges), self.budget_floor) + used = len(opens) + len(self.open_reserved) + info = {"mode": "merges" if self.budget_on else "off", "opened_last_hour": used, + "merged_last_hour": len(merges), "limit": limit, + "available": max(0, limit - used) if self.budget_on else None} + if self.budget_scope != "all": + info["scope"] = self.budget_scope # only PRs that add a module count + if self.budget_on and used >= limit: + # The next slot frees when enough of the oldest opens leave the window. + index = used - limit + info["next_slot_min"] = (math.ceil(max(0.0, opens[index] + WINDOW - now) / 60) + if index < len(opens) else 1) + return info + + def _check_budget(self, agent): + """Refuse a new PR when the swarm's opens in the last hour reached + max(merges in the last hour, PYBOT_PR_OPEN_FLOOR) (call with the lock held).""" + if not self.budget_on: + return + info = self._budget() + if info["opened_last_hour"] < info["limit"]: + return + n, m, k = info["opened_last_hour"], info["merged_last_hour"], info["next_slot_min"] + now = time.time() + self._recent(self.budget_refusals, now).append(now) + log.warning("open_budget: refused a new PR for agent=%s opened=%d merged=%d limit=%d", + agent.name, n, m, info["limit"]) + raise ToolError(f"the swarm opened {n} PRs in the last hour and merged {m}; new PRs wait " + f"until more merge (next slot in ~{k} min). Meanwhile review others' PRs " + "(list_prs needs_review=true) or improve your open PR with pr=.", + "open_budget", retry_after_s=max(1, k) * 60) + + def _note_merge(self): + """Count a merge for the new-PR budget (call with the lock held; the caller saves).""" + now = time.time() + self._recent(self.state["pr_merges"], now).append(now) + self._dirty("_", "pr_merges") + + def _count(self, name, n=1): + with self.counts_lock: + setattr(self, name, getattr(self, name) + n) + + def metrics(self): + """World numbers for GET /metrics (flock.world.server).""" + now = time.time() + with self.lock: + budget = self._budget() + out = {"open_prs": sum(r["state"] == "open" for r in self.state["prs"].values()), + "opens_last_hour": budget["opened_last_hour"], + "merges_last_hour": budget["merged_last_hour"], "open_budget_limit": budget["limit"], + "budget_refusals_last_hour": len(self._recent(self.budget_refusals, now)), + "parked_drafts": len(self.state["drafts"]), + "merge_queue": len(self.state["merge_queue"]), + "verdicts_total": len(self.state["verdicts"])} + for v in ("human", "agent", "script"): + out[f"main_verdicts_last_hour_{v}"] = sum( + r["target"] == "main" and r["verdict"] == v and now - r["ts"] < WINDOW + for r in self.state["verdicts"]) + lanes = {f"lane_{lane}_{k}": v for lane, m in self.lanes.metrics().items() for k, v in m.items()} + return {**out, **lanes, "stale_lease_adoptions_total": self.stale_adoptions, + "hub_busy_total": self.hub_busy_total, + "hub_comments_rejected_total": self.comments_rejected, + "save_duration_s": self.save_s, "save_age_s": now - self.saved_at, + "state_bytes": self.store.size(), "dirty_rows": self.store.pending} + + # -- saving state.db (and prs.json) ----------------------------------------------------- + + def _dirty(self, kind, *keys): + """Mark state rows changed (call with the lock held; the caller then calls _save): + kind is one of KINDS (keys: entries of self.state[kind]) or "_" (keys: top-level + names). Every state change must mark its rows, or state.db misses it.""" + for key in map(str, keys): + self.store.dirty(kind, key) + if kind == "prs": + rec = self.state["prs"].get(key) + if rec is not None and rec["state"] in ("merged", "closed"): + self.ended.setdefault(key, rec.setdefault("ended_at", time.time())) + + def _row(self, kind, key): + """A row's current value (None: gone).""" + return self.state.get(key) if kind == "_" else self.state.get(kind, {}).get(key) + + def _rows(self): + """Every state row as (kind, key, value).""" + for name, value in self.state.items(): + if name in KINDS: + yield from ((name, key, v) for key, v in value.items()) + else: + yield "_", name, value + + def _move_cold(self, now): + """Move PR records merged or closed more than COLD_AFTER ago from memory to the cold + table (lock held); get_pr and list_prs still read them. Returns True if any moved.""" + if self.legacy_json: # prs.json must keep every PR while a rollback to it is possible + return False + keys = [key for key, t in self.ended.items() if t < now - COLD_AFTER] + rows = [] + for key in keys: + del self.ended[key] + rec = self.state["prs"].get(key) + if rec is not None and rec["state"] in ("merged", "closed"): + rows.append(("prs", key, rec)) + if rows: + self.store.write(rows, cold=True) + for _, key, rec in rows: + del self.state["prs"][key] + self.cold_branches.add(rec["branch"]) + return bool(rows) + + def _save(self): + """Record that the state changed (call with the lock held, after _dirty). The saver + thread writes at most once per PYBOT_SAVE_INTERVAL_S; flush() writes at once.""" + self.save_gen += 1 + if self.save_sync: + self.flush() + else: + self.save_wake.set() + + def _saver(self): + """Background thread: write the state when it changed, at most once per + save_interval. close() stops it and writes the last change itself.""" + last = float("-inf") + while True: + self.save_wake.wait() + self.save_wake.clear() + if self.save_stop.wait(max(0.0, last + self.save_interval - time.monotonic())): + return + last = time.monotonic() + try: + self.flush() + except Exception: # keep the thread alive; the next change or close() retries + log.exception("state: save failed; retrying") + self.save_wake.set() + + def _snapshot(self): + """A consistent copy of the state as marshal blobs (call with the lock held). + + marshal copies the JSON types several times faster than json.dumps or deepcopy, and the + copy is encoded and written after the lock is released. Each entry of a top-level dict + or list gets its own blob, so the encoding outside the lock also yields the GIL between + entries instead of holding it for one long json.dumps call.""" + parts = [] + for key, value in self.state.items(): + if isinstance(value, dict): + parts.append((key, dict, [(k, marshal.dumps(v)) for k, v in value.items()])) + elif isinstance(value, list): + parts.append((key, list, [marshal.dumps(v) for v in value])) + else: + parts.append((key, None, marshal.dumps(value))) + return parts + + @staticmethod + def _encode(parts, out): + """Write a snapshot as JSON, byte for byte what json.dumps(state) gives.""" + out.write("{") + for i, (key, kind, body) in enumerate(parts): + out.write(f"{', ' if i else ''}{_key(key)}: ") + if kind is dict: + out.write("{") + for j, (k, blob) in enumerate(body): + out.write(f"{', ' if j else ''}{_key(k)}: {json.dumps(marshal.loads(blob))}") + out.write("}") + elif kind is list: + out.write("[" + ", ".join(json.dumps(marshal.loads(b)) for b in body) + "]") + else: + out.write(json.dumps(marshal.loads(body))) + out.write("}") + + def flush(self): + """Write the dirty rows to state.db in one transaction (the lock is held only to read + them: O(changes)), then prs.json if save.legacy_json is on.""" + with self.lock: + self._move_cold(time.time()) + now, started = time.time(), time.monotonic() + if self.store.flush(self._row, self.lock): + self.save_s, self.saved_at = time.monotonic() - started, now + if self.legacy_json: + self._flush_json() + + def _flush_json(self): + """Write prs.json now if the state changed since the last write. The lock is held + only for the snapshot; a write never replaces a newer one (tmp file + os.replace).""" + if self.save_gen == self.written_gen: + return + with self.lock: + gen = self.save_gen + if gen == self.written_gen: + return + parts = self._snapshot() + tmp = self.db.with_name(f"prs.json.{uuid.uuid4().hex}.tmp") + try: + with open(tmp, "w") as out: + self._encode(parts, out) + with self.replace_lock: + if gen > self.written_gen: + os.replace(tmp, self.db) + self.written_gen = gen + finally: + tmp.unlink(missing_ok=True) + + # -- open_pr idempotency cache ---------------------------------------------------------- + + @staticmethod + def _digest(text): + return hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest() + + def _slim(self, entry, now): + """Strip the description from a cached open_pr result (a replay rebuilds it, see + _replay) and stamp it; returns True if the entry changed.""" + changed = False + if not isinstance(entry.get("_ts"), (int, float)): + entry["_ts"] = now + changed = True + if isinstance(entry.get("description"), str): + entry["_description_sha256"] = self._digest(entry["description"]) + entry["description"] = None # keeps the key's place in the result + changed = True + return changed + + def _cache_request(self, key, result): + """Cache an open_pr result for retries of the same request (call with the lock held).""" + now = time.time() + entry = dict(result) + self._slim(entry, now) + requests = self.state["requests"] + requests.pop(key, None) + requests[key] = entry + self._dirty("requests", key) + self._prune_requests(now) + + def _prune_requests(self, now): + """Drop cached results older than REQUEST_TTL, then the oldest past MAX_REQUESTS + (entries are in insertion order, so oldest first). Returns True if any was dropped.""" + requests = self.state["requests"] + cut = now - REQUEST_TTL + stale = [] + for key, entry in requests.items(): + if entry["_ts"] > cut: + break + stale.append(key) + stale += list(requests)[len(stale):max(len(stale), len(requests) - MAX_REQUESTS)] + for key in stale: + del requests[key] + self._dirty("requests", *stale) + return bool(stale) + + def _slim_requests(self): + """Startup: slim every cached result (full entries, which have no timestamp, get the + current time) and prune. Returns True if the state changed.""" + now = time.time() + changed = False + for key, entry in self.state["requests"].items(): + if self._slim(entry, now): + self._dirty("requests", key) + changed = True + return self._prune_requests(now) or changed + + def _replay(self, key, description): + """The result an open_pr request already returned (call with the lock held). The + description comes from the retried call (the same request carries the same one) or + else from the PR record, whichever matches the digest stored with the result.""" + entry = self.state["requests"][key] + result = {k: v for k, v in entry.items() if not k.startswith("_")} + digest = entry.get("_description_sha256") + if digest is not None: + rec = self.state["prs"].get(str(entry.get("pr"))) or {} + candidates = [description, rec.get("description")] + result["description"] = next( + (c for c in candidates if isinstance(c, str) and self._digest(c) == digest), + description) + return result + + def _event(self, action, agent, **data): + with open(self.ws / "prs.jsonl", "a") as out: + out.write(json.dumps({"ts": time.time(), "event": action, "agent": agent.name, + **data}) + "\n") + + def _pr(self, pr): + rec = self.state["prs"].get(str(pr)) + if rec is not None and rec["state"] == "merging": + raise ToolError(f"PR #{pr} is being merged; retry shortly", "busy") + if rec is None or rec["state"] != "open": + if self._draft(pr): + raise ToolError(f"PR #{pr} is a draft whose head is not on the Hub yet; its author " + f"must retry open_pr with pr={pr}") + rec = rec or self.store.get("prs", str(pr)) # ended PRs move to the cold table + if rec is not None and rec["state"] == "merged": + raise ToolError(f"PR #{pr} is already merged", "pr_merged") + if rec is not None and rec["state"] == "closed": + by = f" by {rec['closed_by']}" if rec.get("closed_by") else "" + why = f": {rec['close_reason'][:INBOX_SNIPPET]}" if rec.get("close_reason") else "" + raise ToolError(f"PR #{pr} was closed{by}{why}", "pr_closed") + raise ToolError("no open PR with that number") + return rec + + def _already_merged(self, pr): + """The merged event of PR pr, or None when the world has no merged record of it.""" + with self.lock: + rec = self.state["prs"].get(str(pr)) or self.store.get("prs", str(pr)) + return self._merged_event(rec) if rec is not None and rec["state"] == "merged" else None + + def _draft(self, pr): + return next((d for d in self.state["drafts"].values() if d["pr"] == pr), None) + + def _prs_paused(self): + return self.paused_env or os.path.exists(self.pause_file) + + def state_dir(self): + """knobs.json (admin knobs and paused lanes) lives in the workspace, archived with it.""" + return getattr(self, "ws", None) or os.environ.get("PYBOT_WS", HERE / "ws") + + def _check_paused(self, *lanes): + """The pause flag (env or file), or an admin pause of one of `lanes` (open, push, merge).""" + if self._prs_paused() or any(map(self.paused, lanes)): + raise ToolError(PAUSED, "paused") + + def _busy(self, agent, what, pr=None, reason="slot_wait", retry_after_s=60): + log.warning("hub_busy: refused %s for agent=%s pr=%s reason=%s", what, agent.name, pr, reason) + self._count("hub_busy_total") + raise ToolError(BUSY, "hub_busy", retry_after_s=retry_after_s) + + @staticmethod + def _outcome(exc): + """A Hub write failure for the lane's breaker: "final", "transient" or None (not the + Hub's doing: a stale lease, a busy refusal, a check).""" + code = getattr(exc, "code", None) + if code in FINAL_CODES: + return "final" + if code in TRANSIENT_CODES or (code is None and isinstance(exc, Exception)): + return "transient" + return None + + @contextlib.contextmanager + def _hub_write(self, agent, what, pr=None, deadline=None, lane="push", pausable=True): + """Hold a slot of Hub write lane `lane`, waiting at most until deadline (default: + PYBOT_HUB_WAIT_S); yields the slot and reports the outcome to the lane. + + Never acquire this with main_lock or self.lock held.""" + if deadline is None: + deadline = time.monotonic() + self.hub_wait + try: + with self.lanes.hold(lane, deadline=deadline, pausable=pausable) as slot: + try: + yield slot + except BaseException as exc: + if kind := self._outcome(exc): + slot.fail(kind) + raise + slot.ok() + except LaneBusy as busy: + self._busy(agent, what, pr, reason=busy.reason, retry_after_s=busy.retry_after_s) + + def _create_gap(self, agent, deadline): + """Reserve the next create_pull_request time, PYBOT_PR_CREATE_GAP_S after the last + one world-wide, and wait for it; refuse if that is after deadline.""" + with self.gap_lock: + now = time.monotonic() + at = max(now, self.last_create + self.pr_gap) + if at > deadline: + self._busy(agent, "create_pull_request", reason="pr_create_gap") + self.last_create = at + time.sleep(at - now) + + def _fetch_missing_heads(self): + """Startup only: the bundle restore carries the PR refs the world knew at archive time; + fetch, explicitly and in small batches, the open PRs whose recorded head isn't in the + repository (pushes after the archive). Never fails the start: what stays missing is + logged and will error on that PR only (its author's next update re-pushes it).""" + try: + missing = [rec["pr"] for rec in self.state["prs"].values() + if rec["state"] == "open" and rec.get("head_sha") + and not self.repo.has_commit(rec["head_sha"])] + if not missing: + return + left = self.repo.fetch_pr_refs(missing) + log.warning("startup: fetched %d PR heads missing after the restore; still missing: %s", + len(missing) - len(left), left or "none") + except Exception as e: # noqa: BLE001 - a fake or failing repository must not stop the start + log.warning("startup: PR head check skipped: %s", e) + + def _sync_hub_states(self, every=0.0): + """Reconcile records the world has as open with the Hub's PR states (a restore from a + stale archive keeps PRs open that the Hub already closed or merged). At most once per + `every` seconds; a Hub read taken outside the world lock and the Hub-write slot. Never + raises.""" + now = time.monotonic() + if now - self.hub_states_at < every: + return + self.hub_states_at = now + states = getattr(self.repo.hub, "pr_states", None) + if states is None: + return + try: + seen = states() + except Exception as exc: # noqa: BLE001 - retried at the next period + log.warning("Hub PR states not listed (%s); keeping the local records", type(exc).__name__) + return + with self.lock: + changed = False + for rec in self.state["prs"].values(): + status = seen.get(rec["pr"]) + if rec["state"] == "open" and status in ("closed", "merged"): + self._apply_hub_final(rec, status) + changed = True + if changed: + self._save() + + def _apply_hub_final(self, rec, status): + """Record that the Hub closed or merged an open PR (lock held; the caller saves).""" + if status == "merged": + rec.update(state="merged", merged_sha=None, reconciled_from_hub=True) + else: + rec.update(state="closed", reconciled_from_hub=True) + self._dirty("prs", rec["pr"]) + self._unnotify(rec["author"], rec["pr"], "mergeable") + log.warning("PR #%s is %s on the Hub but was open here (author=%s); marked %s", + rec["pr"], status, rec["author"], rec["state"]) + + def _mark_hub_final(self, pr, code): + """A Hub write said PR `pr` is already closed or merged: update the record (or drop a + parked draft) and return the ToolError for the agent. Lock held or not; caller saves + if it needs to.""" + status = code[3:] + with self.lock: + rec = self.state["prs"].get(str(pr)) + if rec is not None and rec["state"] in ("open", "closing"): + self._apply_hub_final(rec, status) + self._save() + draft = self._draft(pr) + if draft: + self.state["drafts"].pop(draft["branch"], None) + self._dirty("drafts", draft["branch"]) + self._save() + return ToolError(f"PR #{pr} is already {status} on the Hub", code) + + def _reconcile(self, author=None): + """Mark open PRs whose head is already in main as merged (call with the lock held). + + This recovers a Hub merge whose local bookkeeping failed, and state restored + from an archive that predates merges. Uses the local main ref. + """ + changed, main = False, self.repo.sha() + for rec in self.state["prs"].values(): + if rec["state"] != "open" or (author and rec["author"] != author): + continue + key = (rec["head_sha"], main) # a git subprocess per open PR only when main moved + if key not in self.ancestry: + if len(self.ancestry) >= 10000: + self.ancestry.clear() + self.ancestry[key] = self.repo.ancestor(rec["head_sha"], main) + if not self.ancestry[key]: + continue + merged = self.repo.merged_by(rec["head_sha"]) + reviewers = sorted(name for name, r in self._current_reviews(rec).items() + if r["verdict"] == "approve") + rec.update(state="merged", merged_sha=merged) + self._dirty("prs", rec["pr"]) + self._note_merge() + event = {"pr": rec["pr"], "author": rec["author"], "reviewers": reviewers, + "parent_sha": self.repo.git("rev-parse", f"{merged}^1") if merged else None, + "head_sha": rec["head_sha"], "merged_sha": merged, "reconciled": True} + self._event("merged", Agent("world"), **event) + with open(self.ws / "eval-queue.jsonl", "a") as out: + out.write(json.dumps({"ts": time.time(), **event}) + "\n") + changed = True + if changed: + self._save() + return changed + + def _notify(self, name, pr, kind, text): + """Queue news for agent name (call with the lock held; the caller saves). One entry + per (pr, kind): a repeated event replaces the older one. Keeps the newest INBOX_MAX.""" + box = [e for e in self.state["inbox"].get(name, ()) if (e["pr"], e["kind"]) != (pr, kind)] + box.append({"pr": pr, "kind": kind, "text": text, "ts": time.time()}) + self.state["inbox"][name] = box[-INBOX_MAX:] + self._dirty("inbox", name) + + def _unnotify(self, name, pr, kind): + box = self.state["inbox"].get(name) + if box: + self.state["inbox"][name] = [e for e in box if (e["pr"], e["kind"]) != (pr, kind)] + self._dirty("inbox", name) + + @staticmethod + def _age(seconds): + seconds = max(0, int(seconds)) + if seconds < 60: + return "just now" + if seconds < 3600: + return f"{seconds // 60} min ago" + if seconds < 86400: + return f"{seconds // 3600} h ago" + return f"{seconds // 86400} d ago" + + def call(self, tool, args, agent): + """Run the tool; on success, attach and clear the caller's unread inbox. + + A dict result gets a top-level "inbox" list of strings (newest last). A list result + (list_prs) becomes {"prs": [...], "inbox": [...], "pr_budget": {...}}, only when the + inbox is non-empty. open_pr, review_pr, merge_pr and close_pr results carry pr_budget. + A ToolError leaves the inbox untouched.""" + result = super().call(tool, args, agent) + if inspect.isawaitable(result): + return result + if isinstance(result, dict) and tool in ("open_pr", "review_pr", "merge_pr", "close_pr"): + with self.lock: + result = {**result, "pr_budget": self._budget()} + if not self.state["inbox"].get(agent.name): + return result + with self.lock: + box = self.state["inbox"].pop(agent.name, None) + if not box: + return result + self._dirty("inbox", agent.name) + self._save() + budget = self._budget() + now = time.time() + inbox = [f"{e['text']} ({self._age(now - e['ts'])})" for e in box] + if isinstance(result, dict): + return {**result, "inbox": inbox} + if isinstance(result, list): + return {"prs": result, "inbox": inbox, "pr_budget": budget} + return {"result": result, "inbox": inbox} + + def _identity(self, agent): + if not NAME.fullmatch(agent.name): + raise ToolError("invalid agent identity") + + def call_workspace(self, name, args, agent, snapshot): + if name not in ("open_pr", "run_bot"): + raise ToolError("this tool does not accept workspace uploads") + token = UPLOAD.set(snapshot) + try: + return self.call(name, args, agent) + finally: + UPLOAD.reset(token) + + def _files(self, snapshot, tree): + """Apply an upload over tree (a checkout of its base, or an empty directory). + + Byte-identical files are not rewritten; tracked files missing from the upload are + deleted. Returns the paths that differ from the tree, for the compile check. + A v2 upload (a patch) applies only on a checkout of its base. + """ + if (tree / ".git").is_dir(): + # Default excludes even if an agent drops .gitignore: caches are never committed. + (tree / ".git/info").mkdir(exist_ok=True) + (tree / ".git/info/exclude").write_text("\n".join(EXCLUDE) + "\n") + if "patch" in snapshot: + try: + names = apply_patch(snapshot, tree) + except (ValueError, OSError) as exc: + raise ToolError(f"invalid workspace upload: {exc}"[:300], "bad_workspace") from exc + for name in names: + f = tree / name + if f.is_file() and f.stat().st_size > MAX_FILE_BYTES: + raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; " + "remove it from the clone or add it to .gitignore", "file_too_large") + return names + files = snapshot.get("files") + if not isinstance(files, dict): + raise ToolError("invalid workspace upload", "bad_workspace") + changed = {} + for name, encoded in files.items(): + rel = PurePosixPath(name) if isinstance(name, str) else None + if (rel is None or rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts + or "\\" in name or not isinstance(encoded, str)): + raise ToolError("invalid workspace upload", "bad_workspace") + if len(encoded) > (MAX_FILE_BYTES + 2) // 3 * 4: + raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; " + "remove it from the clone or add it to .gitignore", "file_too_large") + target = tree / rel + try: + data = base64.b64decode(encoded, validate=True) + except ValueError as exc: + raise ToolError("invalid workspace upload", "bad_workspace") from exc + if len(data) > MAX_FILE_BYTES: + raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; " + "remove it from the clone or add it to .gitignore", "file_too_large") + if target.is_file() and not target.is_symlink() and target.read_bytes() == data: + continue + changed[name] = encoded + if (tree / ".git").is_dir(): + tracked = self.repo.git("ls-files", "-z", at=tree).split("\0") + for name in tracked: + if name and name not in files: + (tree / name).unlink(missing_ok=True) + changed.setdefault(name, None) + try: + unpack({"files": {k: v for k, v in changed.items() if v is not None}}, tree) + except (ValueError, TypeError, OSError) as exc: + raise ToolError("invalid workspace upload", "bad_workspace") from exc + return sorted(changed) + + def _adds_module(self, snapshot, base): + """Does an upload add a module the loader finds (MODULE_FILE, new or renamed to)? + Anything unreadable counts as adding one, so the budget still applies to it.""" + if "patch" in snapshot: + try: + patch = base64.b64decode(snapshot.get("patch") or "", validate=True) + except (ValueError, TypeError): + return True + for block in re.split(rb"^diff --git ", patch, flags=re.MULTILINE)[1:]: + header = block.split(b"\n@@", 1)[0].decode(errors="replace") + names = re.match(r"a/(\S+) b/(\S+)\n", header) + if names is None: # a quoted path (spaces, non-ASCII): count it if it may be one + if "bot/modules/" in header.split("\n", 1)[0]: + return True + continue + old, new = names.groups() + if MODULE_FILE.fullmatch(new) and ("\nnew file mode" in header or old != new): + return True + return False + files = snapshot.get("files") + if not isinstance(files, dict): + return True + try: + tracked = set(self.repo.git("ls-tree", "-r", "--name-only", base, "--", "bot/modules") + .splitlines()) + except ToolError: + return True + return any(isinstance(n, str) and MODULE_FILE.fullmatch(n) and n not in tracked for n in files) + + def _contract(self, tree, names=None): + """Check the fixed interface, and that names (default: every .py file) compile.""" + for name, expected in self.fixed.items(): + f = tree / name + if not f.is_file() or f.read_bytes() != expected: + raise ToolError(f"keep the seed interface fixed: {name}; edit bot/modules/ instead", + "fixed_interface") + if names is None: + names = [f.relative_to(tree).as_posix() for f in tree.rglob("*.py") + if ".git" not in f.relative_to(tree).parts] + for name in names: + f = tree / name + if PurePosixPath(name).name == ".gitattributes" and f.is_file(): # deleting one is fine + raise ToolError(f"{name[:200]} is not accepted: .gitattributes changes how the world " + "merges", "fixed_interface") + if not name.endswith(".py") or not f.is_file(): + continue + try: + compile(f.read_bytes(), name, "exec") + except (SyntaxError, ValueError): + raise ToolError(f"Python does not compile: {name}", "compile") from None + + @staticmethod + def _slug(agent: Agent, branch) -> str: + """Normalize a branch argument to the bare slug, accepting only this agent's prefix.""" + text = branch.strip() if isinstance(branch, str) else "" + own = f"agents/{agent.name}/" + for prefix in ("refs/heads/" + own, own): + if text.startswith(prefix): + text = text[len(prefix):] + break + else: + bare = text.removeprefix("refs/heads/") + if bare.startswith("agents/"): + raise ToolError(f"branch prefix must be your own (agents/{agent.name}/) or omitted; " + f"got \"{text[:80]}\"") + if not NAME.fullmatch(text): + raise ToolError("branch must be a short slug matching [a-z][a-z0-9-]{0,63} " + f"(you may omit the agents/{agent.name}/ prefix); got \"{str(branch)[:80]}\"") + return text + + @tool(pool="slow") + @logs_refusals + def open_pr(self, agent: Agent, branch: str, title: str, description: str, + path: str = "pybot", pr: int | None = None) -> dict: + """Submit your local clone, or update your existing PR with pr:. + + The worker uploads path from your private workspace. Include tests and run_bot + evidence in description. At most two open PRs per agent. Read CONTRIBUTING.md. + branch is a short slug like my-topic; the world stores it as agents//. + New PRs are budgeted swarm-wide: one is refused (code open_budget) while the swarm + opened max(merges in the last hour, 20) new PRs in the last hour; updates with + pr= are never counted. When pr_budget has scope new_modules, only a PR that adds a + module (a new bot/modules/.py) is counted or refused: fixes, reverts, tests and + edits of existing modules always open. Results carry pr_budget with the current counts. + """ + started = time.monotonic() + self._identity(agent) + self._check_paused("push", *(("open",) if pr is None else ())) + branch = self._slug(agent, branch) + if not isinstance(title, str) or not 3 <= len(title) <= 200: + raise ToolError(f"title must be 3–200 characters (got {len(title) if isinstance(title, str) else 0})") + if not isinstance(description, str) or not description.strip(): + raise ToolError("description must not be empty") + snapshot = UPLOAD.get() + if not isinstance(snapshot, dict): + raise ToolError("submit a local clone through flock-tool; the worker uploads it") + # Scope new_modules: a PR that adds no module is outside the budget (git runs unlocked). + exempt = (self.budget_scope == "new_modules" + and not self._adds_module(snapshot, snapshot.get("base_sha", ""))) + key = agent.request_id + branch_ref = f"agents/{agent.name}/{branch}" + with self.lock: + if key and key in self.state["requests"]: + return self._replay(key, description) + if pr is None and branch_ref not in self.state["drafts"] and not exempt: + self._check_budget(agent) # before any fetch, build or Hub call + # The lock is held only for state and the main check; fetches, copies, compiles, + # Hub calls and pushes run outside it. A reservation keeps the cap and slugs exact. + self.repo.refresh(FETCH_TTL) + base = snapshot.get("base_sha", "") + token = object() + with self.lock: + if key and key in self.state["requests"]: + return self._replay(key, description) + if not self.repo.ancestor(base, "main"): + raise ToolError("base is not a main commit; fetch main and rebase your branch") + # A parked draft (its Hub PR exists, its head never landed) is reused, never recreated. + draft = self._draft(pr) if pr is not None else self.state["drafts"].get(branch_ref) + old = self._pr(pr) if pr is not None and not draft else None + for existing in (old, draft): + if existing and existing["author"] != agent.name: + raise ToolError("only the author can update this PR") + if existing and existing["branch"] != branch_ref: + raise ToolError("use the original branch slug when updating a PR") + if old and old.get("budget_exempt") and not exempt: + raise ToolError(f"PR #{pr} opened outside the open budget because it added no " + "module; open a new PR to add one", "open_budget") + number = draft["pr"] if draft else (pr if old else None) + pending = self.pending.values() + if key and any(p[3] == key for p in pending): + raise ToolError("this request is already in progress", "busy") + if number is not None and any(p[2] == number for p in pending): + raise ToolError("an update of this PR is already in progress; retry when it finishes") + if not old and not draft: + self._reconcile(agent.name) + mine = [r["pr"] for r in self.state["prs"].values() + if r["state"] in ("open", "merging") and r["author"] == agent.name] + mine += [d["pr"] for d in self.state["drafts"].values() if d["author"] == agent.name] + if len(mine) + sum(p[0] == agent.name and p[2] is None for p in pending) >= 2: + raise ToolError(f"at most two open PRs per agent: update one with pr= or " + f"close one with close_pr (yours: {', '.join(map(str, mine))})") + if (any(r["branch"] == branch_ref for r in self.state["prs"].values()) + or branch_ref in self.state["drafts"] or branch_ref in self.cold_branches + or any(p[1] == branch_ref for p in pending)): + raise ToolError("branch slug already used; choose a new topic slug") + if not exempt: + self._check_budget(agent) + self.open_reserved.add(token) + old_head = old["head_sha"] if old else None + self.pending[token] = (agent.name, branch_ref, number, key) + try: + number, sha, main, old_head = self._publish(agent, snapshot, base, title, description, + branch_ref, number, old_head, started, token, + counted=not exempt) + with self.lock: + if old and (old["state"] != "open" or old["head_sha"] != old_head): + raise ToolError("the PR was merged or closed during the update") + record = {"pr": number, "state": "open", "author": agent.name, + "branch": branch_ref, "base_sha": main, "head_sha": sha, + "url": f"https://huggingface.co/datasets/{self.repo_id}/discussions/{number}", + "title": title, "description": description, + # Kept so reviews of an identical diff carry over a clean rebase. + "reviews": dict(old["reviews"]) if old else {}} + if old.get("budget_exempt") if old else exempt: + record["budget_exempt"] = True # an update may not add a module + self.state["prs"][str(number)] = record + self.state["drafts"].pop(branch_ref, None) + self._dirty("prs", number) + self._dirty("drafts", branch_ref) + for name, r in (old["reviews"] if old else {}).items(): + if r["verdict"] == "request_changes" and name != agent.name: + self._notify(name, number, "updated", + f"PR #{number} was updated by {agent.name} after your " + "request_changes; re-review the new head") + result = {k: v for k, v in record.items() if k != "reviews"} + if base != main: + result["rebased_from"] = base + result["note"] = (f"rebased onto main {main[:12]}; run " + f"git -c protocol.version=0 fetch origin refs/pr/{number} " + "and continue from FETCH_HEAD") + if key: + self._cache_request(key, result) + self._save() + self._event("updated" if old else "opened", agent, **result) + return result + finally: + with self.lock: + self.pending.pop(token, None) + self.open_reserved.discard(token) + + def _build(self, agent, snapshot, base, title, main): + """Commit the upload on base, replayed onto main (outside the world lock).""" + with self._checkout_slot(), tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp: + tree = Path(tmp) / "tree" + self.repo.checkout(base, tree) + self._files(snapshot, tree) + self._contract(tree, self.repo.staged(tree)) + # An older base is rebased onto main here, before anything exists on the Hub. + return self.repo.commit(tree, base, agent.name, title, onto=main) + + def _publish(self, agent, snapshot, base, title, description, branch_ref, pr, old_head, started, + token=None, counted=True): + """Publish the upload: update open PR pr (old_head set), finish parked draft pr, or + create one Hub PR. At most one create_pull_request per call, and a created PR is + never closed by the world: if its head cannot be pushed it is parked as a draft.""" + deadline = None + for _attempt in range(3): + main = self.repo.sha() + sha = self._build(agent, snapshot, base, title, main) + if pr is None and self.repo.sha() != main: # nothing on the Hub yet: rebuild on a moved main + continue + if deadline is None: + deadline = min(time.monotonic() + self.hub_wait, + started + CALL_BUDGET - 2 * PUSH_ESTIMATE_S) + if old_head is not None: # an open PR: replace only the expected head + with self._hub_write(agent, "push", pr, deadline): + old_head = self._lease_push(agent, pr, sha, old_head, started) + else: + with self._hub_write(agent, "open_pr", pr, deadline) as slot: + if pr is None: + # A main that moves during this wait is kept, not rebuilt (that burned the + # reserved slot): the base is seconds old and merge_pr replays a stale base. + self._create_gap(agent, deadline) + pr = self.repo.hub.open(title, f"Agent: {agent.name}\nBase: {main}\n\n{description}") + with self.lock: # the reservation becomes a counted open + self.open_reserved.discard(token) + if counted: + now = time.time() + self._recent(self.state["pr_opens"], now).append(now) + self._dirty("_", "pr_opens") + self._save() + with self.gap_lock: + self.last_create = max(self.last_create, time.monotonic()) + sha, main = self._land(agent, snapshot, base, title, branch_ref, pr, sha, main, + started, slot) + self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/flock/pr/{pr}/{sha}", sha)) + return pr, sha, main, old_head + raise ToolError("main kept moving while opening the PR; open it again", "busy") + + def _lease_push(self, agent, pr, sha, expected, started): + """Push sha to refs/pr/N with a lease on expected; the caller holds a Hub slot, never + the world lock. On a stale lease (the Hub's ref moved past the world's record, e.g. + after a restart from an older archive), read the Hub's value from the refs API (or, + failing that, fetch it with git), adopt it into the record's head_sha and retry the + push once. Returns the expected value the push landed with.""" + ref = f"refs/pr/{pr}" + try: + self.repo.push(sha, ref, expected=expected) + return expected + except ToolError as exc: + if exc.code != "stale_lease": + raise + refusal = ToolError(f"your PR #{pr}'s head on the Hub is newer than the world's record; " + f"the world is catching up, retry open_pr with pr={pr} in a minute", + "stale_lease") + # The refs API gives the Hub's value (the lease needs only the sha, not the object); + # a git fetch of the ref is the fallback when the API gives nothing. + hub, via = None, "" + refs = getattr(self.repo.hub, "refs", None) + if refs is not None: + try: + hub = refs().get(ref) + except Exception as e: # noqa: BLE001 - fall back to the git fetch + log.warning("Hub refs lookup failed for PR #%s: %s", pr, type(e).__name__) + via = " (via API)" if hub else "" + if not hub: + room = started + CALL_BUDGET - time.monotonic() + fetched = not self.repo.fetch_pr_refs([pr], delays=(1,) if room > 1 + 2 * PUSH_ESTIMATE_S else ()) + if fetched: + try: + hub = self.repo.git("rev-parse", "--verify", f"{ref}^{{commit}}") + except ToolError: + hub = None + if not hub or hub == expected: + log.warning("stale lease on %s for PR #%s (agent=%s): Hub head not fetched; refused", + ref, pr, agent.name) + raise refusal + with self.lock: + rec = self.state["prs"].get(str(pr)) + if rec is None or rec["state"] not in ("open", "merging") or rec["head_sha"] != expected: + raise ToolError("the PR was merged or closed during the update") + rec["head_sha"] = hub + self._dirty("prs", pr) + self._save() + log.warning("adopted Hub head for PR #%s after a stale lease%s: %s -> %s", + pr, via, expected[:12], hub[:12]) + self._count("stale_adoptions") + if time.monotonic() + PUSH_ESTIMATE_S > started + CALL_BUDGET: + raise refusal + try: + self.repo.push(sha, ref, expected=hub) + except ToolError as exc: + if exc.code != "stale_lease": + raise + log.warning("stale lease again on %s for PR #%s (agent=%s); refused", ref, pr, agent.name) + raise refusal from None + return hub + + def _land(self, agent, snapshot, base, title, branch_ref, number, sha, main, started, slot): + """Push the head of the world's own (draft) Hub PR and mark it ready; the caller holds + slot (a push lane slot; retried failures are reported to it). Retries briefly within + the call budget, then parks the draft.""" + delays = list(PUSH_RETRY_DELAYS) + while True: + try: + # refs/pr/N is written only by the world: overwrite. + self.repo.push(sha, f"refs/pr/{number}", force=True) + self.repo.hub.ready(number) + return sha, main + except ToolError as exc: + if exc.code in FINAL_CODES: # closed or merged on the Hub: no retry loop + raise self._mark_hub_final(number, exc.code) from None + failure = exc + except Exception as exc: # noqa: BLE001 -- the Hub PR exists: never orphan it + failure = exc + if kind := self._outcome(failure): + slot.fail(kind) + delay = delays.pop(0) if delays else None + if delay is None or time.monotonic() + delay + PUSH_ESTIMATE_S > started + CALL_BUDGET: + break + time.sleep(delay) + try: + self.repo.fetch() + if self.repo.sha() != main: # main moved: rebase within the same PR number + main = self.repo.sha() + sha = self._build(agent, snapshot, base, title, main) + except Exception as exc: # noqa: BLE001 + failure = exc + break + code = getattr(failure, "code", type(failure).__name__) + with self.lock: + self.state["drafts"][branch_ref] = { + "pr": number, "author": agent.name, "branch": branch_ref, "base_sha": main, + "sha": sha, "title": title, "parked_at": time.time(), + "url": f"https://huggingface.co/datasets/{self.repo_id}/discussions/{number}"} + self._dirty("drafts", branch_ref) + self._save() + self._event("parked", agent, pr=number, branch=branch_ref, code=code) + log.warning("parked draft PR #%s for agent=%s: %s", number, agent.name, code) + if code == "stale_base": + raise ToolError(f"{failure.message}; your PR #{number} is kept: retry open_pr with " + f"pr={number}", "stale_base") + if code != "busy": # busy: no checkout slot for the rebuild, not a Hub refusal + self._count("hub_busy_total") + raise ToolError(f"the Hub did not accept the push for your PR #{number}; retry open_pr " + f"with pr={number} in a minute", "hub_busy", retry_after_s=60) + + @tool + @logs_refusals + def review_pr(self, agent: Agent, pr: int, head_sha: str, + verdict: Literal["approve", "request_changes"], comment: str) -> dict: + """Review the exact head SHA you inspected or tested, independently of the author. + + The review counts at once, and its Hub comment is posted in the background. When the + world caps reviewers per PR change, a review by one more agent is refused + (review_full): review a PR that still needs one (list_prs needs_review=true).""" + self._identity(agent) + if verdict not in ("approve", "request_changes") or not comment.strip(): + raise ToolError("give a verdict and a review comment") + + def check(): + rec = self._pr(pr) + if rec["author"] == agent.name: + raise ToolError("another agent must review your PR; self-review is refused") + # Only the world writes PR refs, so its record is the PR head. + if head_sha != rec["head_sha"]: + raise ToolError("the PR head changed; inspect it again before reviewing") + if self.max_reviewers: # a reviewer of the current change may always review again + reviewers = self._reviewers(rec) + if agent.name not in reviewers and len(reviewers) >= self.max_reviewers: + raise ToolError(f"PR #{pr} already has {len(reviewers)} reviewers on this change; " + "review a PR that still needs one (list_prs needs_review=true)", + "review_full") + return rec + + with self.lock: + base = check()["base_sha"] + review = {"head_sha": head_sha, "patch_id": self._patch_id(base, head_sha), + "patch_id0": self._patch_id(base, head_sha, context=False), + "verdict": verdict, "comment": comment} + with self.lock: + rec = check() + rec["reviews"][agent.name] = review + self._dirty("prs", pr) + # No Hub call here: the outbox thread posts the comment when the Hub slot is free. + self._queue_comment(agent, pr, f"{verdict} by {agent.name} on {head_sha}\n\n{comment}") + snippet = " ".join(comment.split()) + if len(snippet) > INBOX_SNIPPET: + snippet = snippet[:INBOX_SNIPPET - 3] + "..." + author = rec["author"] + self._notify(author, pr, f"review:{agent.name}", + f"{agent.name} reviewed your PR #{pr}: {verdict}: {snippet}") + try: + approvers = self._approved(rec) + except ToolError: + self._unnotify(author, pr, "mergeable") + else: + self._notify(author, pr, "mergeable", f"PR #{pr} approved by " + f"{', '.join(sorted(approvers))}; ready to merge_pr") + self._save() + self._event("reviewed", agent, pr=pr, **review) + return {"pr": pr, "reviewer": agent.name, **review} + + def _patch_id(self, base, head, context=True): + try: + return (self.repo.patch_id if context else self.repo.patch_id0)(base, head) + except ToolError: + return None # unknown change identity: only exact-head reviews count + + def _current_reviews(self, rec): + """Reviews of the current head, or of the same change (a clean rebase). + + A review carries to a new head when its context-free patch-id (patch_id0) equals the + current one, so main changing lines next to the PR's hunks does not void it; or when + its patch_id (the diff with context, the older formula) equals the current one. + Reviews stored before patch_id0 existed keep only the patch_id match: reviews do not + record the base they were made on, so patch_id0 cannot be backfilled for them. + Reviews stored without either only count for their exact head. + """ + current, ids = {}, {} + + def ident(field): + if field not in ids: + ids[field] = self._patch_id(rec["base_sha"], rec["head_sha"], + context=field == "patch_id") + return ids[field] + + for name, r in rec["reviews"].items(): + if r["head_sha"] != rec["head_sha"] and not any( + r.get(field) is not None and r[field] == ident(field) + for field in ("patch_id0", "patch_id")): + continue + current[name] = r + return current + + def _reviewers(self, rec): + """Reviews of the current change, the author's excluded.""" + return {name: r for name, r in self._current_reviews(rec).items() if name != rec["author"]} + + def _approved(self, rec): + reviews = {name: r for name, r in self._current_reviews(rec).items() + if name != rec["author"]} + if any(r["verdict"] == "request_changes" for r in reviews.values()): + raise ToolError("a reviewer still requests changes on this head") + names = [name for name, r in reviews.items() if r["verdict"] == "approve"] + if not names: + raise ToolError("another agent must approve the current PR head") + return names + + @tool + @logs_refusals + def merge_pr(self, agent: Agent, pr: int) -> dict: + """Queue an independently approved PR for merging; answers at once with its position. + + The world merges the queue in order, one PR at a time, as the agent that queued it: a + PR based on an older main is rebased onto main (no need to rebase it yourself; its + approvals carry over when the rebase leaves the diff unchanged), then its bot contract + and the shared tests are checked on the result. The outcome arrives as news in the + `inbox` of your next world tool result, for you and the PR's author: merged, or why + not (a conflict with main, a rebase that changes the diff, failing tests, no longer + approved), and a refused PR leaves the queue. Calling merge_pr again on a queued PR + only shows its position.""" + self._identity(agent) + self._check_paused("merge") + with self.lock: + queue = self.state["merge_queue"] + position = self._queued().get(pr) + rec = self.state["prs"].get(str(pr)) + if position is None or rec is None or rec["state"] not in ("open", "merging"): + try: + rec = self._pr(pr) + except ToolError as exc: # agents retry merged PRs: answer, don't refuse + if exc.code != "pr_merged" or not (merged := self._already_merged(pr)): + raise + return merged + self._approved(rec) + head, main, code, message = self.refused.get(pr, (None,) * 4) + if head == rec["head_sha"] and main == self.repo.sha(): + raise ToolError(message, code) + queue.append({"pr": pr, "by": agent.name, "ts": time.time(), "tries": 0, "next_at": 0.0}) + position = len(queue) + self._dirty("_", "merge_queue") + self._save() + self._event("merge_queued", agent, pr=pr, position=position) + self.merge_wake.set() + return {"pr": pr, "queued": True, "position": position, + "note": "the world merges the queue in order; the outcome (merged, or why not) " + "arrives in the inbox of your next world tool result"} + + def _queued(self): + """{PR number: position} of the merge queue (lock held).""" + return {e["pr"]: i for i, e in enumerate(self.state["merge_queue"], 1)} + + def _merge_loop(self): + """Background thread: merge the queue (_merge_next) while merges are not paused; when + no queued PR is due, wait for the soonest retry or a new one.""" + while not self.stopping.is_set(): + self.merge_wake.clear() # before looking: a merge_pr from now on ends the wait + if self._prs_paused() or self.paused("merge"): + self.merge_wake.wait(5.0) + continue + try: + if self._merge_next() is not None: + continue + except ToolError: + continue # settled by _merge_next; its timing line has the code + except Exception: # kept queued with a backoff by _merge_next + log.exception("merge queue: a merge failed") + self.stopping.wait(1.0) + continue + with self.lock: + now = time.time() + soonest = min((e["next_at"] for e in self.state["merge_queue"]), default=now + 5.0) + self.merge_wake.wait(min(5.0, max(0.1, soonest - now))) + + def _merge_next(self): + """Run the first queued PR whose retry time has come (None: none) as the agent that + queued it and return the merge. A merge or a refusal takes it off the queue, a refusal + with news for the author and that agent; a failure in MERGE_RETRY_CODES (or not a + ToolError) keeps its place with a backoff (MERGE_BACKOFF), the PRs behind it going + ahead meanwhile. Failures are re-raised.""" + with self.lock: + now = time.time() + entry = next((e for e in self.state["merge_queue"] if e["next_at"] <= now), None) + if entry is None: + return None + pr, agent = entry["pr"], Agent(entry["by"]) + steps, outcome, started = {}, "error", time.monotonic() + try: + try: + result = self._merge(agent, pr, steps) + except ToolError as exc: # merged meanwhile (on the Hub, or by an earlier entry) + if exc.code != "pr_merged" or not (result := self._already_merged(pr)): + raise + outcome = "already_merged" if result.get("already_merged") else "merged" + with self.lock: + self.state["merge_queue"].remove(entry) + for other in self.state["merge_queue"]: # the Hub merges again: no one waits out a backoff + other["next_at"] = 0.0 + self._dirty("_", "merge_queue") + if result.get("already_merged"): # e.g. landed on the Hub though the call failed + for name in {agent.name, result["author"]}: + self._notify(name, pr, "merged", f"PR #{pr} is merged") + self._save() + return result + except BaseException as exc: + outcome = getattr(exc, "code", None) or type(exc).__name__ + with self.lock: + if not isinstance(exc, ToolError) or exc.code in MERGE_RETRY_CODES: + entry["tries"] += 1 + entry["next_at"] = time.time() + min( + MERGE_BACKOFF[1], MERGE_BACKOFF[0] * 2 ** min(entry["tries"] - 1, 10)) + else: + self.state["merge_queue"].remove(entry) + if checked := getattr(exc, "checked", None): # the head and main the checks saw + self.refused[pr] = (*checked, exc.code, exc.message) + rec = self.state["prs"].get(str(pr)) or self.store.get("prs", str(pr)) + reason = exc.message[:MERGE_REASON] + if rec is not None and rec["state"] != "closed": # a close told the author already + self._unnotify(rec["author"], pr, "mergeable") + self._notify(rec["author"], pr, "merge", f"your PR #{pr} was not merged: {reason}") + if rec is None or rec["author"] != agent.name: + self._notify(agent.name, pr, "merge", f"PR #{pr} you queued was not merged: {reason}") + self._event("merge_pr_refused", agent, pr=pr, code=exc.code, reason=exc.message[:500]) + self.merge_refusals.append({"ts": time.time(), "pr": pr, "code": exc.code}) + self._dirty("_", "merge_queue") + self._save() + raise + finally: # one line per queue run: where a merge spends its time + log.info("merge_pr pr=%s outcome=%s total=%.1f %s", pr, outcome, + time.monotonic() - started, " ".join(f"{k}={v:.1f}" for k, v in steps.items())) + + def _merge(self, agent, pr, steps): + """Merge PR pr as agent (the merge queue's turn of it).""" + lane_at = time.monotonic() + # The merge lane's slot is taken before the locks (see _hub_write) and held through the + # rebase, the checks and the Hub merge: the merge queue's thread holds it, so a merge + # never waits behind pushes, opens and closes. + with self._hub_write(agent, "merge", pr, lane="merge"): + steps["lane_wait"] = time.monotonic() - lane_at + # Main as the Hub has it, also after a merge that landed but whose call failed; the + # rebase and the compare-and-swap below use this local ref. + with _timed(steps, "refresh"): + self.repo.refresh(0) + with self.lock: + rec = self._pr(pr) + # Already in main (e.g. a Hub merge that landed though its call failed): done. + if self._reconcile(rec["author"]) and rec["state"] == "merged": + return self._merged_event(rec) + self._approved(rec) + if any(p[2] == pr for p in self.pending.values()): + raise ToolError("an update of this PR is in progress; retry when it finishes", "busy") + main, base, head = self.repo.sha(), rec["base_sha"], rec["head_sha"] + view = {**rec, "reviews": dict(rec["reviews"])} + try: + new = self._check_merge(pr, view, main, steps) + except ToolError as exc: + exc.checked = (head, main) # what the refusal is about (merge_pr's cache) + raise + lock_at = time.monotonic() + with self.main_lock: + steps["main_lock_wait"] = time.monotonic() - lock_at + with self.lock: + rec = self._pr(pr) + if (self.repo.sha() != main or rec["head_sha"] != head + or any(p[2] == pr for p in self.pending.values())): + raise ToolError("main or the PR changed during checks; retry merge_pr", "busy") + reviewers = self._approved({**rec, "base_sha": main, "head_sha": new}) + rec["state"] = "merging" # no update, review, close or merge while the Hub calls run + try: + if new != head: # the Hub merges refs/pr/N as it is: publish the rebase first + # A stale lease (e.g. a rebase pushed just before a restart) adopts the Hub head. + with _timed(steps, "push"): + self._lease_push(agent, pr, new, head, time.monotonic()) + with _timed(steps, "update_ref"): # waits for refs_lock + self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/flock/pr/{pr}/{new}", new)) + with self.lock: # reviews stay: they match the rebased head by patch-id + rec.update(base_sha=main, head_sha=new) + self._dirty("prs", pr) + self._save() + try: + with _timed(steps, "hub_merge"): + self.repo.hub.merge(pr, f"Approved by {', '.join(reviewers)}; head {new}; base {main}; contract passed") + except Exception as exc: + # The Hub may have merged before failing (a 5xx, or a timeout or reset + # after commit): the queue's retry would replay the PR onto itself. + try: + self.repo.fetch() + except ToolError: + pass + with self.lock: + rec["state"] = "open" + if self._reconcile(rec["author"]) and rec["state"] == "merged": + return self._merged_event(rec) + if getattr(exc, "code", None) in FINAL_CODES: # already closed or merged on the Hub + raise self._mark_hub_final(pr, exc.code) from None + raise + # Local main must move before main_lock is released: opens compare against it. + with _timed(steps, "fetch"): + self.repo.fetch() + with _timed(steps, "tree_check"): + merged = self.repo.sha() + mismatch = (self.repo.git("rev-parse", f"{merged}^{{tree}}") + != self.repo.git("rev-parse", f"{new}^{{tree}}")) + if mismatch: # e.g. the Hub merged an older refs/pr head, or main moved outside + log.error("PR #%s: main %s after the Hub merge is not the checked tree of %s", + pr, merged[:12], new[:12]) + with self.lock: + rec.update(state="merged", merged_sha=merged) + self._dirty("prs", pr) + self._note_merge() + news = {name: f"PR #{pr} you approved was merged by {agent.name}" for name in reviewers} + news[agent.name] = f"PR #{pr} you queued is merged" + news[rec["author"]] = f"your PR #{pr} was merged" + ( + f" by {agent.name}" if rec["author"] != agent.name else "") + self._unnotify(rec["author"], pr, "mergeable") + for name, text in news.items(): + self._notify(name, pr, "merged", text) + self._save() + event = {"pr": pr, "author": rec["author"], "reviewers": reviewers, + "parent_sha": main, "head_sha": new, "merged_sha": merged, + **({"tree_mismatch": True} if mismatch else {})} + rebased = {"rebased_from": base} if new != head else {} + self._event("merged", agent, **event, **rebased) + # Append-only integration hook, consumed by the separate evaluation workstream. + with open(self.ws / "eval-queue.jsonl", "a") as out: + out.write(json.dumps({"ts": time.time(), **event}) + "\n") + return {**event, **rebased} + finally: + with self.lock: + if rec["state"] == "merging": # failed before the record was settled + rec["state"] = "open" + + def _check_merge(self, pr, rec, main, steps): + """What merging rec makes main, checked (the caller holds a merge lane slot, no lock): + the PR head, or on an older base the PR's change replayed onto main, whose approvals + must still hold; then the bot contract and the shared tests. Returns the head to merge.""" + base, head = rec["base_sha"], rec["head_sha"] + with tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp: + tree = Path(tmp) / "tree" + with _timed(steps, "checkout"): + self.repo.checkout(head, tree) + new = head + if base != main: + try: + with _timed(steps, "replay"): + self.repo.precheck(base, head, main) # a conflict costs no replay + self.repo.git("reset", "-q", "--soft", base, at=tree) # the PR's change, staged on its base + # Union paths only here: a replay whose diff changed is refused below. + new = self.repo.commit(tree, base, rec["author"], rec["title"], onto=main, + union=True) + except ToolError as exc: + if exc.code != "stale_base": + raise + files = ", ".join(exc.files[:5]) + (f" and {len(exc.files) - 5} more" + if len(exc.files) > 5 else "") + where = f" in {files}" if files else "" + raise ToolError(f"PR #{pr} conflicts with main {main[:12]}{where}: fetch main, " + "rebase onto origin/main and update the PR", "conflict") from None + try: + with _timed(steps, "approvals"): + self._approved({**rec, "base_sha": main, "head_sha": new}) + except ToolError: + raise ToolError(f"rebasing PR #{pr} onto main {main[:12]} changes its diff, so it " + "needs a fresh review: rebase onto origin/main, update the PR and " + "ask for a review", "rebase_changed") from None + # The shared tests run beside the bot contract (both read the tree only); leaving the + # pool waits for them, so the tree outlives them and a contract refusal still comes first. + with concurrent.futures.ThreadPoolExecutor(1) as pool: + tests = pool.submit(self._shared_tests, pr, tree, main) + with _timed(steps, "contract"): + self._bot_contract(tree, self.repo.changed(main, new)) + with _timed(steps, "shared_tests"): # the wait left after the contract + tests.result() + return new + + def _bot_contract(self, tree, names): + """The merge contract: the fixed interface, names compile, the bot answers (no runner + slot: the merge queue runs one at a time).""" + self._contract(tree, names) + lines = ["Hello", "My name is Sam", "", "What is my name?", "Bye"] + verdict = run(tree, lines) + if not verdict["ok"]: + raise ToolError("bot contract failed: one nonempty reply per input, no crash, 300s total", + "contract") + + def _shared_tests(self, pr, tree, main): + """Refuse a merge that turns the shared tests (MERGE_TESTS) red: two PRs can each pass + them alone and fail them together (the same new deck id). Tests that also fail on main, + or time out, do not refuse it: that is not this PR's doing.""" + if not MERGE_TESTS or self.main_tests == (main, None): # timed out on this main already + return + started = time.monotonic() + result = run_tests(tree, MERGE_TESTS, MERGE_TESTS_TIMEOUT_S) + with self.lock: + self.test_runs.append({"ts": time.time(), "main_sha": main[:12], "seconds": round( + time.monotonic() - started, 1), "result": "ok" if result["ok"] else ( + "timeout" if result["status"] == "timeout" else "fail")}) + if result["ok"]: + return + if result["status"] == "timeout": + self.main_tests = (main, None) + log.warning("shared tests %s timed out on PR #%s; merging without them on main %s", + MERGE_TESTS, pr, main[:12]) + return + if self.main_tests[0] != main: + with tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp: + self.repo.checkout(main, Path(tmp) / "main") + self.main_tests = (main, run_tests(Path(tmp) / "main", MERGE_TESTS, + MERGE_TESTS_TIMEOUT_S)["ok"]) + if not self.main_tests[1]: + log.warning("shared tests %s fail on main %s too; not refusing PR #%s", + MERGE_TESTS, main[:12], pr) + return + failed = [line if len(line) <= 240 else f"{line[:150]} ... {line[-80:]}" + for line in result["output"].splitlines() + if line.startswith(("FAIL:", "ERROR:")) or "Error: " in line][:6] + raise ToolError(f"the shared tests (tests/{MERGE_TESTS}) pass on main {main[:12]} and fail " + f"with PR #{pr} on it: {' | '.join(failed) or result['status']}; fix it on " + "top of origin/main and update the PR", "shared_tests") + + def _merged_event(self, rec): + return {"pr": rec["pr"], "author": rec["author"], "head_sha": rec["head_sha"], + "merged_sha": rec.get("merged_sha"), "already_merged": True} + + @tool(pool="slow") + @logs_refusals + def close_pr(self, agent: Agent, pr: int, reason: str) -> dict: + """Close your open PR (frees one of your two open-PR slots). Give a short reason.""" + self._identity(agent) + if not reason.strip() or len(reason) > 2000: + raise ToolError("give a short reason (at most 2000 chars)") + with self.lock: + draft = self._draft(pr) + if draft: + return self._close_draft(agent, draft, reason) + with self.lock: + rec = self.state["prs"].get(str(pr)) + if rec is not None and rec["state"] == "open": + self._reconcile(rec["author"]) + if merged := self._already_merged(pr): # nothing to close + return merged + rec = self._pr(pr) + if rec["author"] != agent.name and agent.name not in self.operators: + raise ToolError("only the author or the run operator can close this PR") + if any(p[2] == pr for p in self.pending.values()): + raise ToolError("an update of this PR is in progress; retry when it finishes", "busy") + rec["state"] = "closing" # no update, review or merge while the Hub call runs + try: + try: + with self._hub_write(agent, "close", pr, pausable=False): + self.repo.hub.close(pr, f"Closed by {agent.name}: {reason}") + except ToolError as exc: + if exc.code == "hub_busy": + raise + if exc.code in FINAL_CODES: + raise self._mark_hub_final(pr, exc.code) from None + status = getattr(self.repo.hub, "status", None) + if status is None or status(pr) != "closed": + raise + except BaseException: + with self.lock: + if rec["state"] == "closing": # not already settled from the Hub's answer + rec["state"] = "open" + raise + with self.lock: + rec.update(state="closed", closed_by=agent.name, close_reason=reason) + self._dirty("prs", pr) + self._notify_closed(agent, rec["author"], pr, reason) + self._save() + event = {"pr": pr, "author": rec["author"], "head_sha": rec["head_sha"], "reason": reason} + self._event("pr_closed", agent, **event) + return {**event, "state": "closed", "closed_by": agent.name} + + def _notify_closed(self, agent, author, pr, reason): + if author != agent.name: + self._unnotify(author, pr, "mergeable") + self._notify(author, pr, "closed", + f"your PR #{pr} was closed by {agent.name}: {reason[:INBOX_SNIPPET]}") + + def _close_draft(self, agent, draft, reason): + pr = draft["pr"] + with self.lock: + if draft["author"] != agent.name and agent.name not in self.operators: + raise ToolError("only the author or the run operator can close this PR") + if any(p[2] == pr for p in self.pending.values()): + raise ToolError("an update of this PR is in progress; retry when it finishes", "busy") + try: + with self._hub_write(agent, "close", pr, pausable=False): + self.repo.hub.close(pr, f"Closed by {agent.name}: {reason}") + except ToolError as exc: + if exc.code in FINAL_CODES: + raise self._mark_hub_final(pr, exc.code) from None + raise + with self.lock: + self.state["drafts"].pop(draft["branch"], None) + self._dirty("drafts", draft["branch"]) + self._notify_closed(agent, draft["author"], pr, reason) + self._save() + event = {"pr": pr, "author": draft["author"], "head_sha": None, "reason": reason} + self._event("pr_closed", agent, draft=True, **event) + return {**event, "state": "closed", "closed_by": agent.name} + + @tool(read_only=True) + def list_prs(self, state: str = "open", author: str = "", needs_review: bool = False, + offset: int = 0) -> list[dict]: + """Find PRs, their head SHA and reviews. state is open, merged, closed or all. + + A PR with "draft": true is open on the Hub but its head is not pushed yet (head_sha is + null); it counts toward its author's open PRs and cannot be reviewed or merged until + its author retries open_pr with pr=. state open also lists PRs whose merge + is running ("state": "merging"). A PR in the merge queue has "queued": its position. + Returns a list of PRs; if you have unread inbox news it is + {"prs": [...], "inbox": [...], "pr_budget": {...}} (the swarm's new-PR budget). + """ + if offset < 0: + raise ToolError("offset must be nonnegative") + if state not in ("open", "merged", "closed", "all"): + raise ToolError("state must be open, merged, closed or all") + # Shallow copies under the lock (reviews are replaced, never edited in place); the + # review filter's git and the deep copy run outside it. + with self.lock: + records = [{**rec, "reviews": dict(rec["reviews"])} for rec in self.state["prs"].values() + if (state == "all" or rec["state"] == state + or (state == "open" and rec["state"] == "merging")) + and (not author or rec["author"] == author)] + drafts = [] if state not in ("open", "all") or needs_review else [ + {"pr": d["pr"], "state": "open", "draft": True, "author": d["author"], + "branch": d["branch"], "base_sha": d["base_sha"], "head_sha": None, + "url": d["url"], "title": d["title"], "reviews": {}} + for d in self.state["drafts"].values() if not author or d["author"] == author] + queued = self._queued() + for rec in records: + if rec["pr"] in queued: + rec["queued"] = queued[rec["pr"]] + if state in ("merged", "closed", "all"): # cold records never change: read unlocked + records[:0] = [rec for _, rec in self.store.iter("prs", cold=True) + if (state == "all" or rec["state"] == state) + and (not author or rec["author"] == author)] + if needs_review: # no approval yet, and room for one more reviewer under the cap + def needs(rec): + reviews = self._reviewers(rec) + return (not any(r["verdict"] == "approve" for r in reviews.values()) + and (not self.max_reviewers or len(reviews) < self.max_reviewers)) + records = [rec for rec in records if needs(rec)] + return json.loads(json.dumps(records + drafts))[offset:offset + 100] + + @tool(read_only=True) + def get_pr(self, pr: int, path: str | None = None) -> dict: + """Show a PR from the world's copy, no git fetch needed: its head and base SHAs, the + changed files with +/- line counts and the diff against its base. With path: that + file's full content at the PR head and its diff only. A PR in the merge queue has + "queued": its position.""" + if path is not None: + rel = PurePosixPath(path) if isinstance(path, str) else None + if (not path or rel is None or rel.is_absolute() or ".." in rel.parts + or "\\" in path or "\0" in path): + raise ToolError("path must be a relative file path inside the repository") + path = rel.as_posix() + with self.lock: # a quick state read; git runs below without the lock + rec = self.state["prs"].get(str(pr)) or self.store.get("prs", str(pr)) # or cold + if rec is None: + if self._draft(pr): + raise ToolError(f"PR #{pr} is a draft whose head is not on the Hub yet; " + "there is nothing to show") + raise ToolError("no PR with that number") + rec = {k: rec.get(k) for k in ("pr", "title", "author", "state", "branch", "url", + "description", "head_sha", "base_sha")} + if position := self._queued().get(pr): + rec["queued"] = position + head, base = rec["head_sha"], rec["base_sha"] + with contextlib.suppress(ToolError): # main moves rarely without the world: cheap + self.repo.refresh(FETCH_TTL) + if not (self.repo.has_commit(head) and self.repo.has_commit(base)): + self.repo.fetch_pr_refs([pr], delays=(1,)) # once, from the Hub + if not (self.repo.has_commit(head) and self.repo.has_commit(base)): + raise ToolError(f"PR #{pr}'s head {str(head)[:12]} is not in the world's " + "repository (the Hub did not return it); retry later or fetch " + "it with git", "missing_head") + try: + main = self.repo.sha() + except ToolError: + main = None + description = rec["description"] or "" + if len(description) > DESCRIPTION_CHARS: + description = description[:DESCRIPTION_CHARS - 3] + "..." + result = {**rec, "description": description, "base_is_main": base == main, + "main_sha": main} + spec = ("--", path) if path else () + files = [] + stat = self.repo.git_bytes("diff", "--numstat", "-z", "--no-renames", base, head, *spec) + for entry in stat.decode(errors="replace").split("\0"): + if not entry: + continue + added, deleted, name = entry.split("\t", 2) + binary = added == "-" + files.append({"path": name, "added": None if binary else int(added), + "deleted": None if binary else int(deleted)} + | ({"binary": True} if binary else {})) + result["files"] = files + diff = self.repo.git_bytes("diff", "--no-color", "--no-ext-diff", "--no-renames", base, + head, *spec) + result["diff_bytes"] = len(diff) + result["truncated"] = len(diff) > MAX_DIFF_BYTES + if result["truncated"]: + cut = diff[:MAX_DIFF_BYTES] + diff = cut[:cut.rfind(b"\n") + 1] or cut + result["hint"] = (f"the diff is {result['diff_bytes']} bytes; showing the first " + f"{len(diff)}. Pass path= for one file's diff and content") + result["diff"] = diff.decode(errors="replace") + if path: + result.update(self._file_at(head, path)) + if not files and result["content"] is None: + raise ToolError(f"{path[:200]} is neither in PR #{pr}'s head nor in its diff") + return result + + def _file_at(self, sha, path): + """{"content", "size", ...} of path at commit sha (content None when absent).""" + listing = self.repo.git_bytes("ls-tree", "-z", "--long", sha, "--", path) + entry = listing.split(b"\0", 1)[0].decode(errors="replace") + if not entry: + return {"content": None, "note": "the file does not exist at the PR head"} + meta, _, _ = entry.partition("\t") + kind, size = meta.split()[1], meta.split()[3] + if kind != "blob": + return {"content": None, "note": f"{path[:200]} is a {kind}, not a file"} + data = self.repo.git_bytes("cat-file", "blob", f"{sha}:{path}") + out = {"size": int(size)} + if b"\0" in data[:8192]: + return {**out, "content": None, "binary": True} + out["content_truncated"] = len(data) > MAX_FILE_BYTES + out["content"] = data[:MAX_FILE_BYTES].decode(errors="replace") + return out + + @tool + def record_verdict(self, agent: Agent, target: str, + verdict: Literal["human", "agent", "script"], confidence: float, + notes: str) -> dict: + """Interviewers: record who you were talking to when you chatted with target through + run_bot: a human, an AI agent, or a script. target is main or pr:; confidence + 0.0 to 1.0; notes: your reason and the most telling exchange. A PR's author gets it in + their inbox.""" + self._identity(agent) + target = str(target).strip() + match = re.fullmatch(r"main|pr:(\d+)", target) + if not match: + raise ToolError("target must be main or pr:") + if verdict not in ("human", "agent", "script"): + raise ToolError("verdict must be human, agent or script") + if (isinstance(confidence, bool) or not isinstance(confidence, int | float) + or not 0 <= confidence <= 1): + raise ToolError("confidence must be between 0.0 and 1.0") + notes = " ".join(str(notes).split())[:VERDICT_NOTES] + sha = None + with contextlib.suppress(ToolError): + sha = self.repo.sha(target) + pr = int(match[1]) if match[1] else None + with self.lock: + author = None + if pr is not None: + rec = self.state["prs"].get(str(pr)) or self.store.get("prs", str(pr)) + if rec is None: + raise ToolError("no PR with that number") + author = rec["author"] + entry = {"target": target, "verdict": verdict, "confidence": float(confidence), + "notes": notes, "by": agent.name, "sha": sha, "ts": time.time()} + self.state["verdicts"] = [*self.state["verdicts"], entry][-VERDICTS_MAX:] + self._dirty("_", "verdicts") + if author and author != agent.name: + self._notify(author, pr, f"verdict:{agent.name}", f"interviewer {agent.name} " + f"judged PR #{pr}: {verdict} ({confidence:.1f})") + self._save() + self._event("verdict", agent, pr=pr, **{k: v for k, v in entry.items() if k != "by"}) + return entry + + @tool(read_only=True) + def verdicts(self, target: str = "", limit: int = 20) -> dict: + """Interviewers' verdicts, newest first: who they believed they talked to (human, agent + or script). target: main or pr: (all when empty); limit: at most 100.""" + target = str(target).strip() + if isinstance(limit, bool) or not isinstance(limit, int): + raise ToolError("limit must be a whole number") + limit = max(1, min(limit, 100)) + with self.lock: + recs = [dict(r) for r in reversed(self.state["verdicts"]) + if not target or r["target"] == target][:limit] + return {"verdicts": recs} + + @tool(read_only=True) + def world_status(self) -> dict: + """The swarm's collaboration health: the merge queue (who waits, for how long), merges + and new PRs in the last hour against the new-PR limit, merge refusals in the last hour + by code, the shared tests' last run at merge (null until a merge runs them), and open + PRs (drafts excluded) that are approved but not queued (approved_refused: the queue + refused that same head) or have no review of their current head. Refusals and test + runs count since the world last restarted. An approval kept across a clean rebase is + not counted here; list_prs(needs_review=true) applies it. Times are in minutes. + Queue only PRs in approved_not_queued_prs; for approved_refused_prs ask the author to + fix the refusal. PR lists are capped at 50, oldest first (the counts give the totals).""" + now = time.time() + with self.lock: + budget = self._budget() + queue = self.state["merge_queue"] + entries = [{"pr": e["pr"], "position": i, "queued_by": e["by"], + "minutes_waiting": round((now - e["ts"]) / 60, 1), "tries": e["tries"]} + for i, e in enumerate(queue[:STATUS_QUEUE_MAX], 1)] + queued, total = {e["pr"] for e in queue}, len(queue) + refusals = [r for r in self.merge_refusals if now - r["ts"] < WINDOW] + tests = [t for t in self.test_runs if now - t["ts"] < WINDOW] + last = dict(self.test_runs[-1]) if self.test_runs else None + open_prs, approved, refused, unreviewed, changes = 0, [], [], [], [] + for rec in sorted(self.state["prs"].values(), key=lambda r: r["pr"]): + if rec["state"] not in ("open", "merging"): + continue + open_prs += 1 + # shortcut: reviews of the exact head only (no patch-id git calls), so an + # approval carried over a clean rebase is not seen here; list_prs has the truth. + seen = {r["verdict"] for name, r in rec["reviews"].items() + if name != rec["author"] and r["head_sha"] == rec["head_sha"]} + if not seen: + unreviewed.append(rec["pr"]) + elif "request_changes" in seen: + changes.append(rec["pr"]) + elif rec["pr"] not in queued: + head, _main, code, _message = self.refused.get(rec["pr"], (None,) * 4) + if head == rec["head_sha"]: # re-queueing it would fail again + refused.append({"pr": rec["pr"], "code": code}) + else: + approved.append(rec["pr"]) + if last: + last["minutes_ago"] = round((now - last.pop("ts")) / 60, 1) + last["last_hour"] = {"runs": len(tests), + "timeouts": sum(t["result"] == "timeout" for t in tests), + "avg_seconds": round(sum(t["seconds"] for t in tests) / len(tests), 1) + if tests else None} + return {"merge_queue": entries, "merge_queue_total": total, + "merges_last_hour": budget["merged_last_hour"], + "opens_last_hour": budget["opened_last_hour"], + "new_pr_limit": budget["limit"] if self.budget_on else None, + "refusals_last_hour": { + "by_code": dict(collections.Counter(r["code"] for r in refusals)), + "last": [{"pr": r["pr"], "code": r["code"], + "minutes_ago": round((now - r["ts"]) / 60, 1)} for r in refusals[:-11:-1]]}, + "shared_tests": last, "open_prs": open_prs, + "approved_not_queued": len(approved), "approved_not_queued_prs": approved[:STATUS_QUEUE_MAX], + "approved_refused": len(refused), "approved_refused_prs": refused[:STATUS_QUEUE_MAX], + "unreviewed": len(unreviewed), "unreviewed_prs": unreviewed[:STATUS_QUEUE_MAX], + "changes_requested": len(changes), "changes_requested_prs": changes[:STATUS_QUEUE_MAX]} + + @tool(pool="slow") + def run_bot(self, ref_or_path: str, lines: list[str]) -> dict: + """Run main, pr:, or a local clone path. 300 seconds for the whole conversation.""" + with tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp: + tree = Path(tmp) / "tree" + snapshot = UPLOAD.get() + if hub_ref := ref_or_path == "main" or ref_or_path.startswith("pr:"): + self.repo.refresh(FETCH_TTL) # outside the checkout slot: a fetch holds no permit + with self._checkout_slot(): # released before the run, which has its own slots + if hub_ref: + sha = self.repo.sha(ref_or_path) + self.repo.checkout(sha, tree) + elif isinstance(snapshot, dict): + sha = snapshot.get("base_sha") + if isinstance(sha, str) and self.repo.ancestor(sha, "main"): + self.repo.checkout(sha, tree) # then only changed files are written/compiled + self._contract(tree, self._files(snapshot, tree)) + elif "patch" in snapshot: + raise ToolError("unknown base; send the full tree", "need_full") + else: + tree.mkdir() + self._files(snapshot, tree) + self._contract(tree) + else: + raise ToolError("use main, pr:, or a clone path inside your workspace") + return {"ref": ref_or_path, "sha": sha, **self._run(tree, lines)} + + @contextlib.contextmanager + def _checkout_slot(self): + if not self.checkouts.acquire(timeout=CHECKOUT_WAIT_S): + raise ToolError("the world is busy checking out trees; retry in a minute", "busy") + try: + yield + finally: + self.checkouts.release() + + def _run(self, tree, lines): + if not self.slots.acquire(timeout=10): + raise ToolError("bot runners are busy; retry later", "busy") + try: + return run(tree, lines) + finally: + self.slots.release() + + +if __name__ == "__main__": + from flock.world.server import serve + # Nothing else configures logging in the world process: this handler sends its warnings and + # INFO lines (merge_pr timings) to stderr. + logging.getLogger("pybot").addHandler(logging.StreamHandler()) + logging.getLogger("pybot").setLevel(logging.INFO) + # FLOCK_WORLD_PORT: the free port flock picked (a local run, a Slurm world job) + serve("pybot:PybotWorld", host="0.0.0.0", + port=int(os.environ.get("FLOCK_WORLD_PORT") or os.environ.get("PORT") or 7860)) diff --git a/world/pytest.ini b/world/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..64baef779f8a4a42e9e46b52bdc0d103ecc3cd07 --- /dev/null +++ b/world/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +asyncio_mode = auto +asyncio_default_fixture_loop_scope = function +testpaths = tests diff --git a/world/repository.py b/world/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..b8a21a99580f7404ba43bda8a3d821ed045ef176 --- /dev/null +++ b/world/repository.py @@ -0,0 +1,475 @@ +"""Git transport and native Hub PRs. The world uses the shared experiment HF_TOKEN for writes.""" +from __future__ import annotations + +import logging +import os +import re +import signal +import subprocess +import threading +import time +from pathlib import Path +from urllib.parse import urlsplit + +from huggingface_hub import HfApi +from huggingface_hub.errors import HfHubHTTPError + +from flock.world import ToolError +from flock.world.server import redact + +log = logging.getLogger(__name__) +# Loose objects packed per maintenance pass at most: every pass finishes; a backlog drains over passes. +PACK_LOOSE_MAX = int(os.environ.get("PYBOT_PACK_LOOSE_MAX", "20000")) + +_URL_CREDENTIALS = re.compile(r"(?<=://)[^/@\s]+@") +_HUB_HEADERS = ("x-error-code", "x-error-message", "x-request-id", "retry-after") + + +def _safe_text(text, limit): + return _URL_CREDENTIALS.sub("[redacted]@", redact(text))[:limit] + + +def _log_hub_failure(method, repo_id, exc): + """One WARNING with the status and diagnostic headers; never the exception text, body or + request headers, which can hold secrets.""" + response = getattr(exc, "response", None) + request = getattr(response, "request", None) + where = "" + if request is not None: + where = f"{request.method} {urlsplit(str(request.url)).path}" + headers = {name: _safe_text(str(response.headers[name]), 300 if name == "x-error-message" else 100) + for name in _HUB_HEADERS if response is not None and name in response.headers} + log.warning("Hub call %s failed for %s: status=%s request=%s headers=%s", method, repo_id, + getattr(response, "status_code", None), where or "unknown", headers) + + +class Repository: + def __init__(self, root: Path, remote: str, hub=None): + self.root, self.remote, self.hub = root, remote, hub + # Ref writes in the shared bare repository (fetch, update-ref) are serialized here, + # not under the world's state lock; reads, clones and object writes run concurrently. + self.refs_lock = threading.Lock() + self.fetched = 0.0 + # (base, head) -> stable patch-id of the default diff, (base, head, 0) -> of the -U0 diff + self.patch_ids = {} + self.env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_LFS_SKIP_SMUDGE": "1"} + # The dataset is public: PR refs are fetched anonymously first (the Hub throttles git + # fetches per token), then with the token. PYBOT_ANON_FETCH=0 disables it. + self.anonymous = (remote.startswith("https://") + and os.environ.get("PYBOT_ANON_FETCH", "1").strip() != "0") + if hub is not None: + # The URL, argv and repository config contain no token. + askpass = root.parent / "git-askpass.py" + askpass.write_text("#!/usr/bin/env python3\nimport os,sys\n" + "print('hf_user' if 'Username' in sys.argv[1] else os.environ['HF_TOKEN'])\n") + askpass.chmod(0o700) + self.env["GIT_ASKPASS"] = str(askpass) + if not (root / "HEAD").exists(): + root.mkdir(parents=True, exist_ok=True) + self.git("init", "--bare", str(root), at=root.parent) + self.git("remote", "add", "origin", remote) + bundle = root.parent / "repo.bundle" + if bundle.exists(): + self.git("fetch", str(bundle), "+refs/*:refs/*") + bundle.unlink() + # PYBOT_UNION_PATHS: gitattributes patterns (e.g. deck/*.jsonl) whose replays onto main + # keep both sides' lines (merge=union) instead of conflicting. The attributes file is the + # world's own, next to its repository; the dataset is unchanged. + union = [p for p in re.split(r"[\s,]+", os.environ.get("PYBOT_UNION_PATHS", "deck/*.jsonl")) if p] + self.attributes = root.parent / "union.gitattributes" if union else None + if self.attributes: + self.attributes.write_text("".join(f"{p} merge=union\n" for p in union)) + # Fetches start no background gc: it packed refs outside refs_lock. maintain() packs. + self.git("config", "maintenance.auto", "false") + self.git("config", "gc.auto", "0") # nor does any git command run gc --auto here + # Only this world runs gc here: a gc.pid is a gc stopped with a world that ran elsewhere, + # and git would honour it for 12 h. + (root / "gc.pid").unlink(missing_ok=True) + (root / "objects" / "pack" / "multi-pack-index.lock").unlink(missing_ok=True) # likewise + self.fetch() + + def git(self, *args, at=None, data=None, env=None, timeout=120, group=False): + return self.git_bytes(*args, at=at, data=data, env=env, timeout=timeout, + group=group).decode().strip() + + def git_bytes(self, *args, at=None, data=None, env=None, timeout=120, group=False): + """Run git and return its raw stdout (for diffs and file contents, which need not be + UTF-8). Failures raise like git(). group: git runs in its own process group, and a + timeout kills the whole group (gc's repack and pack-objects too), then raises.""" + argv = ["git", "-C", str(at or self.root), *args] + if group: + with subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, env=env or self.env, + start_new_session=True) as proc: + try: + out, err = proc.communicate(data, timeout=timeout) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + raise + p = subprocess.CompletedProcess(argv, proc.returncode, out, err) + else: + p = subprocess.run(argv, input=data, capture_output=True, env=env or self.env, + timeout=timeout, check=False) + if p.returncode: + # Git's stderr can contain remote data or credentials: never expose it to agents; + # the world's log gets it redacted. + command = next((a for a in args if not a.startswith("-") and "=" not in a), "?") + stderr = p.stderr.decode(errors="replace") + log.warning("git %s failed: exit code %s, stderr=%s", command, p.returncode, + _safe_text(stderr.strip(), 500)) + # A --force-with-lease push whose expected value no longer matches the remote ref. + code = "stale_lease" if command == "push" and "stale info" in stderr else "git_error" + raise ToolError("repository operation failed; refresh your clone and retry", code) + return p.stdout + + def negotiation(self): + """Offer only main's history as haves: with ~2,000 local refs the default negotiation + makes the request large enough for the Hub to drop it. Git refuses a tip that doesn't + exist yet (before the first fetch), so it's passed only when main is there.""" + p = subprocess.run(["git", "-C", str(self.root), "rev-parse", "--verify", "-q", "refs/heads/main"], + env=self.env, capture_output=True, timeout=10, check=False) + return ["--negotiation-tip=refs/heads/main"] if p.returncode == 0 else [] + + def hub_fetch(self, remote, *specs, options=(), env=None): + """Every fetch from the Hub: protocol v2 (explicit; v0 floods haves) with main as the + only negotiation tip, explicit refspecs only (the Hub drops wildcard PR-ref fetches).""" + self.git("-c", "protocol.version=2", *options, "fetch", "--no-write-fetch-head", + *self.negotiation(), remote, *specs, env=env) + + def fetch(self): + """Fetch main only. The world writes refs/pr/N itself after every push (update_refs), so + PR refs never come from the Hub here; a wildcard over refs/pr/* is also refused by the + Hub's git backend once there are many PRs (hang-up / 'expected acknowledgments'). + A fetch that started after this call is as fresh as this one: waiters behind it return.""" + asked = time.monotonic() + with self.refs_lock: + if self.fetched > asked: + return + started = time.monotonic() + self.hub_fetch("origin", "+refs/heads/main:refs/heads/main") + self.fetched = started + + def has_commit(self, sha): + if not sha or len(sha) != 40 or any(c not in "0123456789abcdef" for c in sha): + return False + p = subprocess.run(["git", "-C", str(self.root), "cat-file", "-e", f"{sha}^{{commit}}"], + env=self.env, capture_output=True, timeout=10, check=False) + return p.returncode == 0 + + def fetch_anonymous(self, *specs): + """Fetch specs from the plain remote URL without credentials (no askpass, no token, no + credential helper). Never raises: returns False on failure (or when disabled).""" + if not self.anonymous: + return False + env = {k: v for k, v in self.env.items() + if k not in ("GIT_ASKPASS", "SSH_ASKPASS", "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN")} + try: + with self.refs_lock: + self.hub_fetch(self.remote, *specs, options=("-c", "credential.helper="), env=env) + return True + except Exception: # noqa: BLE001 - logged by git() (the URL holds no credentials) + return False + + def fetch_pr_refs(self, numbers, batch=8, delays=(1, 3, 9)): + """Fetch refs/pr/N for the given PR numbers from the Hub, explicitly, in small batches + (the Hub hangs up on large or wildcard PR-ref fetches): anonymously first, then with the + token. Never raises: a batch that still fails after the retries is logged, and the list + of PR numbers left unfetched is returned.""" + missing = [] + numbers = [int(n) for n in numbers] + for start in range(0, len(numbers), batch): + chunk = numbers[start:start + batch] + specs = [f"+refs/pr/{n}:refs/pr/{n}" for n in chunk] + if self.fetch_anonymous(*specs): + continue + for attempt, delay in enumerate(delays + (None,)): + try: + with self.refs_lock: + self.hub_fetch("origin", *specs) + break + except ToolError: + if delay is None: + log.warning("PR refs %s not fetched after %d attempts", chunk, attempt + 1) + missing.extend(chunk) + else: + time.sleep(delay) + return missing + + def refresh(self, max_age): + """Fetch unless a fetch started within max_age seconds. The world updates its own + refs after every push and merge, so this only catches up with outside changes; with + max_age > 0 it also returns at once while refs_lock is busy (a fetch is running) + instead of queueing another fetch. max_age 0 always gets a main fetched after the call.""" + if time.monotonic() - self.fetched < max_age or (max_age > 0 and self.refs_lock.locked()): + return + self.fetch() + + def update_refs(self, *refs): + """Point each (ref, sha) at its sha in one transaction: one refs_lock wait.""" + with self.refs_lock: + self.git("update-ref", "--stdin", data="".join(f"update {ref} {sha}\n" for ref, sha in refs).encode()) + + def maintain(self, info): + """Keep the bare repository fast in a pass that takes minutes: pack every ref, pack every + loose object (reachable or not: rebased and refused commits) into one new pack, then + delete their loose copies. Packs already there are never rewritten: a full or cruft gc + of a large repository (~1 GiB in tens of packs on network storage) takes over 30 min. + Nothing is pruned; the pack count grows by one per pass. Fills info with the counts and + each step's seconds, also when a step fails.""" + info["loose_before"] = self.loose() + start = time.monotonic() + with self.refs_lock: + self.git("pack-refs", "--all") + info["pack_refs_s"], start = time.monotonic() - start, time.monotonic() + objects = self.root / "objects" + for tmp in (objects / "pack").glob("tmp_*"): # a pass killed at its timeout left it + try: + if tmp.stat().st_mtime < time.time() - 3600: # a running fetch writes fresh ones + tmp.unlink(missing_ok=True) + except FileNotFoundError: # a fetch just renamed its tmp_pack + pass + # objects/xx/<38 hex>; a loose object being written is still tmp_obj_* and is skipped + ids = sorted(f"{d.name}{f.name}\n" for d in objects.glob("[0-9a-f][0-9a-f]") + for f in d.iterdir() if len(f.name) == 38)[:PACK_LOOSE_MAX] + try: + if ids: # pack.threads=2: leaves the world's other git work some cores + self.git("-c", "pack.threads=2", "pack-objects", "-q", str(objects / "pack" / "pack"), + data="".join(ids).encode(), timeout=1800, group=True) + self.git("prune-packed", "-q", timeout=1800, group=True) + # one index over all packs: lookups don't scan each + self.git("multi-pack-index", "write", timeout=1800, group=True) + finally: + info["pack_loose_s"] = time.monotonic() - start + info["packs"] = len(list((objects / "pack").glob("pack-*.pack"))) + info["loose_after"] = self.loose() # what the next passes still pack + + def loose(self): + """Loose objects in the repository (git count-objects).""" + return int(re.search(r"^count: (\d+)", self.git("count-objects", "-v"), re.MULTILINE)[1]) + + def sha(self, ref="main"): + if ref.startswith("pr:") and ref[3:].isdigit(): + ref = f"refs/pr/{int(ref[3:])}" + if ref != "main" and not ref.startswith("refs/pr/"): + raise ToolError("ref must be main or pr:") + return self.git("rev-parse", "--verify", f"{ref}^{{commit}}") + + def ancestor(self, sha, target): + if len(sha) != 40 or any(c not in "0123456789abcdef" for c in sha): + return False + p = subprocess.run(["git", "-C", str(self.root), "merge-base", "--is-ancestor", sha, target], + env=self.env, capture_output=True, timeout=10, check=False) + return p.returncode == 0 + + def merged_by(self, head, target="main"): + """The first commit on target's first-parent chain that contains head.""" + out = self.git("rev-list", "--first-parent", "--ancestry-path", "--reverse", + f"{head}..{target}") + return out.split("\n", 1)[0] or self.git("rev-parse", head) # fast-forward: head is main + + def checkout(self, ref, dest): + # --shared borrows the object store instead of copying it; objects are never pruned + # while reachable, and new commits are fetched back into the bare repository. + self.git("clone", "-q", "--shared", "--no-checkout", str(self.root), str(dest), at=dest.parent) + self.git("checkout", "-q", "--detach", ref, at=dest) + + def staged(self, tree): + """Stage the tree (honouring .gitignore) and list added/changed paths.""" + self.git("add", "-A", at=tree) + names = self.git("diff", "--cached", "--name-only", "-z", "--no-renames", + "--diff-filter=AM", "HEAD", at=tree) + return [name for name in names.split("\0") if name] + + def changed(self, base, head): + """Paths added or modified between two commits.""" + out = self.git("diff", "--name-only", "-z", "--no-renames", "--diff-filter=AM", base, head) + return [name for name in out.split("\0") if name] + + def patch_id(self, base, head): + """Stable patch-id of the diff base..head (None for an empty diff), cached per pair.""" + return self._patch_id((base, head), ["diff", base, head]) + + def patch_id0(self, base, head): + """Stable patch-id of the context-free diff base..head (None for an empty diff). + + Without context lines, a change of main next to the PR's hunks leaves it unchanged, + so it identifies the PR's own change across a clean rebase. Cached per pair.""" + return self._patch_id((base, head, 0), ["diff", "-U0", "--no-color", base, head]) + + def _patch_id(self, key, args): + if key not in self.patch_ids: + diff = subprocess.run(["git", "-C", str(self.root), *args], + capture_output=True, env=self.env, timeout=120, check=False) + if diff.returncode: + log.warning("git diff failed: exit code %s", diff.returncode) + raise ToolError("repository operation failed; refresh your clone and retry", "git_error") + out = subprocess.run(["git", "-C", str(self.root), "patch-id", "--stable"], input=diff.stdout, + capture_output=True, env=self.env, timeout=120, check=False) + if out.returncode: + log.warning("git patch-id failed: exit code %s", out.returncode) + raise ToolError("repository operation failed; refresh your clone and retry", "git_error") + if len(self.patch_ids) >= 10000: + self.patch_ids.clear() + self.patch_ids[key] = out.stdout.decode().split()[0] if out.stdout.strip() else None + return self.patch_ids[key] + + def commit(self, tree, parent, author, title, onto=None, union=False): + """Commit tree on parent; with onto != parent, replay that commit onto it (with union, + PYBOT_UNION_PATHS merge as merge=union: only where a changed diff is refused).""" + who = ("-c", f"user.name={author}", "-c", f"user.email={author}@flock.invalid") + self.git("add", "-A", at=tree) + self.git(*who, "commit", "--allow-empty", "-m", title, at=tree) + sha = self.git("rev-parse", "HEAD", at=tree) + if onto and onto != parent: + self.git("checkout", "-q", "--detach", onto, at=tree) + attributes = ("-c", f"core.attributesFile={self.attributes}") if union and self.attributes else () + try: + self.git(*who, *attributes, "cherry-pick", "--allow-empty", "--keep-redundant-commits", sha, + at=tree) + except ToolError: + unmerged = subprocess.run(["git", "-C", str(tree), "diff", "--name-only", "-z", + "--diff-filter=U"], env=self.env, capture_output=True, + timeout=60, check=False).stdout.decode(errors="replace") + subprocess.run(["git", "-C", str(tree), "cherry-pick", "--abort"], env=self.env, + capture_output=True, timeout=60, check=False) + raise _stale_base(parent, onto, unmerged.split("\0")) from None + sha = self.git("rev-parse", "HEAD", at=tree) + self.git("fetch", "--no-write-fetch-head", str(tree), sha) + return sha + + def precheck(self, base, head, onto): + """Raise commit(union=True)'s stale_base error when replaying base..head onto `onto` + conflicts, found by git merge-tree in the bare repository (no checkout, well under a + second). Silent when it cannot tell the same answer: another merge base, a + .gitattributes anywhere in either tree (the replay's checkout would honour it), a git + older than 2.38 (no --write-tree), or any git error or timeout.""" + try: + if (self.git("merge-base", "--all", onto, head) != base + or any(name.rsplit("/", 1)[-1] == ".gitattributes" for sha in (onto, head) + for name in self.git("ls-tree", "-r", "--name-only", sha).splitlines())): + return + attributes = ("-c", f"core.attributesFile={self.attributes}") if self.attributes else () + out = subprocess.run(["git", "-C", str(self.root), *attributes, "merge-tree", "--write-tree", + "--name-only", "-z", "--no-messages", onto, head], + env=self.env, capture_output=True, timeout=60, check=False) + except (ToolError, subprocess.TimeoutExpired): + return + if out.returncode == 1: # 1: conflicts (tree, then the conflicted paths); 0: clean + raise _stale_base(base, onto, out.stdout.decode(errors="replace").split("\0")[1:]) + + def push(self, sha, ref, expected=None, force=False): + """Push sha to ref; expected replaces only that head; force overwrites a ref the + world owns outright (a PR it created and nobody else writes).""" + options = [f"--force-with-lease={ref}:{expected}"] if expected else [] + self.git("push", *options, "origin", f"{'+' if force and not expected else ''}{sha}:{ref}") + + +def _stale_base(parent, onto, files): + error = ToolError(f"your branch is based on {parent}, main is {onto}, and your changes " + "conflict with main: pull, rebase onto origin/main, then open again", "stale_base") + error.files = list(dict.fromkeys(name for name in files if name)) # the conflicting paths + return error + + +FINAL_CODES = {"closed": "pr_closed", "merged": "pr_merged"} +_FINAL_WORDS = re.compile(r"\b(merged|closed)\b") + + +def _final_state(exc): + """"closed" or "merged" when an HTTP 400 says the PR is already closed or merged (matched on + the x-error-message header, else the response text; neither is ever logged), else None.""" + response = getattr(exc, "response", None) + if getattr(response, "status_code", None) != 400: + return None + try: + text = str(response.headers.get("x-error-message") or "") or str(response.text or "") + except Exception: # noqa: BLE001 - an unreadable body is just "unknown" + return None + found = _FINAL_WORDS.search(text[:2000].lower()) + return found.group(1) if found else None + + +class Hub: + def __init__(self, repo_id): + self.repo_id = repo_id + token = os.environ.get("HF_TOKEN") + if not token: + raise ToolError("HF_TOKEN is required for the bucket and dataset", "configuration") + self.api = HfApi(token=token) + self.refs_ttl = float(os.environ.get("PYBOT_HUB_REFS_TTL_S", "5")) + self.refs_lock = threading.Lock() # one refresh at a time; waiters reuse its result + self.refs_cache, self.refs_at = None, 0.0 + + def request(self, method, **kwargs): + # Retry 429 only (only merges call this under the world's state lock); other + # failures are surfaced without exception bodies, which may include secrets. + for attempt in range(5): + try: + return getattr(self.api, method)(self.repo_id, repo_type="dataset", **kwargs) + except HfHubHTTPError as exc: + if exc.response.status_code != 429 or attempt == 4: + _log_hub_failure(method, self.repo_id, exc) + final = _final_state(exc) + if final and isinstance(kwargs.get("discussion_num"), int): + num = kwargs["discussion_num"] + raise ToolError(f"PR #{num} is already {final} on the Hub", + FINAL_CODES[final]) from None + error = ToolError("Hub request failed; retry later", "hub_error") + error.status = exc.response.status_code # for the world, never sent to agents + raise error from None + delay = exc.response.headers.get("Retry-After", "1") + try: + delay = float(delay) + except ValueError: + delay = 2 ** attempt + time.sleep(max(0, min(delay, 30))) + except Exception as exc: + # The world reports this as an internal error with an id; name the class here. + log.warning("Hub call %s failed for %s: %s", method, self.repo_id, type(exc).__name__) + raise + + def pr_states(self): + """{PR number: status} (open, closed, merged or draft) of the Hub's pull requests, a read + (no Hub-write slot). Raises on failure.""" + return {d.num: d.status for d in self.request("get_repo_discussions") if d.is_pull_request} + + def refs(self): + """{ref: sha} for the Hub's branches and refs/pr/N, from the refs API (a + read: no Hub-write slot). Cached for PYBOT_HUB_REFS_TTL_S so a burst costs one + request; on failure, a WARNING and the stale cache (or {}).""" + with self.refs_lock: + if self.refs_cache is not None and time.monotonic() - self.refs_at < self.refs_ttl: + return self.refs_cache + try: + found = self.request("list_repo_refs", include_pull_requests=True) + refs = {r.ref: r.target_commit for r in [*(found.branches or []), + *(found.pull_requests or [])] + if r.ref and r.target_commit} + except Exception as exc: # noqa: BLE001 - request() logged the details, never secrets + log.warning("Hub refs not listed for %s (%s); using %s", self.repo_id, + type(exc).__name__, "the stale cache" if self.refs_cache else "nothing") + return self.refs_cache or {} + self.refs_cache, self.refs_at = refs, time.monotonic() + return refs + + def open(self, title, description): + pr = self.request("create_pull_request", title=title, description=description) + return pr.num + + def ready(self, pr): + self.request("change_discussion_status", discussion_num=pr, new_status="open") + + def comment(self, pr, text): + self.request("comment_discussion", discussion_num=pr, comment=text) + + def close(self, pr, comment): + self.request("change_discussion_status", discussion_num=pr, new_status="closed", + comment=comment) + + def status(self, pr): + return self.request("get_discussion_details", discussion_num=pr).status + + def merge(self, pr, comment): + self.request("merge_pull_request", discussion_num=pr, comment=comment) diff --git a/world/requirements.txt b/world/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0888961025193a6c4419831b29956bbe45a5543 --- /dev/null +++ b/world/requirements.txt @@ -0,0 +1,602 @@ +annotated-doc==0.0.5 \ + --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \ + --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb + # via + # fastapi + # typer +annotated-types==0.8.0 \ + --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ + --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 + # via pydantic +anyio==4.15.1 \ + --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \ + --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94 + # via + # httpx + # starlette + # watchfiles +certifi==2026.10.23 \ + --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \ + --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1 + # via + # httpcore + # httpx +click==8.5.0 \ + --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \ + --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34 + # via + # huggingface-hub + # uvicorn +colorama==0.4.6 ; sys_platform == 'win32' \ + --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ + --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 + # via + # tqdm + # typer +exceptiongroup==1.3.1 \ + --hash=sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219 \ + --hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598 + # via flock +fastapi==0.143.1 \ + --hash=sha256:4cafaab64df8534758bf0fce61947f5e27e6cd512798ccbbaad5425086c3b664 \ + --hash=sha256:687beb445804e4c4dbe2a76fd83c25e9b973ac48c267defb86f791e099baecc4 + # via flock +filelock==3.32.7 \ + --hash=sha256:37b8a3d9811b0f9aef7e5ec5c71bb320de52df51e6ca9bcd6f5ad81187660da7 \ + --hash=sha256:65ff0d0190ea42038b32bda4b77834fb05be2cad4c5b9b01aa4dfb3614536e52 + # via huggingface-hub +fsspec==2026.9.0 \ + --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \ + --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f + # via huggingface-hub +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via + # httpcore + # uvicorn +hf-xet==1.7.0 ; platform_machine == 'AMD64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64' \ + --hash=sha256:0a9e802f33bf50c851abe45fc5380e61f959e2d369647d6742b79ad9d6c27cab \ + --hash=sha256:19c0e64f14175ccb6a1aff69e0d2ab9ec5269a560e6687abaf2b3fa4f73de7cd \ + --hash=sha256:2814a6e999d13464c4d679b788cc5d784eb5a4edfc638a31f10e9a11ab531ef8 \ + --hash=sha256:2b7bb5727889b0f2436dbaaad8fc4c3e66b8240d992716989e0c086b4278b1bc \ + --hash=sha256:4ee5e05a627f5ab5bad7a86582277d645556ea1e199903aae19e033a392aa13a \ + --hash=sha256:57bc157b8b7fe3bee9dcb9af7f3da8de41801c3b31a9ef68a77a33c6a6be382f \ + --hash=sha256:59fba37039233c7fcbe196817d6cdcf1b40dfb17b410f229d85b0cf0a1848da4 \ + --hash=sha256:757168feb5679647c0bb13ee5d0faebe799c4dff9051419885a566ebd79f949d \ + --hash=sha256:80f79dae613ce9e0ea1fd1ae15616ca9ac74aed4c770aabc199c4f03ebecc863 \ + --hash=sha256:87dab080f8f7d32781c2586904e3603f4e60d09bfc727706c3ae419e0829beeb \ + --hash=sha256:acc3851cf2576a8fb2ae926da863f4efabe21303cf292e9a44332802ab0dcc6a \ + --hash=sha256:b01fe18dbbd151a2403d2c64ed30dc6547b00d6babab9a617d77c7acdb81ee66 \ + --hash=sha256:b91569d5f1b61c34b043687da02c05dd3604f3d329e7868510bf3f7971599006 \ + --hash=sha256:d406ec79053c0871817f700c2ac8c36ba0d87f9c34b7458b0f0063bb218b0466 \ + --hash=sha256:e3e88a7a75d7d95cbee1f37dc31341d6201124cf21c6c4b1dfab8ccba9b09e0f \ + --hash=sha256:fa029678be1ba7f953c409b0b27bf15cc69cd1c9b3a674fbd78856ebefca1052 \ + --hash=sha256:fcfd6c22418e57dd5b3aea649e813b2e2cfb2aebf317b210d90f1fe4b3018b52 + # via huggingface-hub +httpcore==1.0.9 \ + --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ + --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 + # via httpx +httptools==0.9.0 \ + --hash=sha256:02bc5b3dcb6394b9d825fd62a7bfa0b2943063a3c89abc4492ad45e334a20eb5 \ + --hash=sha256:050f7ab098121873c8f13e35857f97ab60a76185c8302bde9a384939bb7c3b96 \ + --hash=sha256:050f84b7ec46a6efe0e5f521cf8729e3397c1cef4384f62ed8d5d68ca0045776 \ + --hash=sha256:06bfe7fad972a417269d8a5fc53b87e4eca970354abf5e9e24336fd06d64292e \ + --hash=sha256:088de1738e1af624466a01c35d652dbe6fb825be887c76d68aa850621d81db88 \ + --hash=sha256:0adc974916efe1fbf89d0363a86dcb2c746727643e362ff398de1a4b50b6bc77 \ + --hash=sha256:0cc339a807c156d840b54f8bf050ba0fc265eb81692c24bca8535b52fbd797c6 \ + --hash=sha256:130635fea6e611a6b2026120037965ddb88b3dafd11bb64e264b101a70a76630 \ + --hash=sha256:18d800aaa2d6bff7d889df810d1b19a5fde72b1f6c0ca96e8d9f28a692fe5460 \ + --hash=sha256:1a4050a651e1f2faf05eb028ce9f2168abbcee9e24b209f5c1f2eb96d8c569e4 \ + --hash=sha256:1a7f1df31829c258158be01bb04eb668c4fba7df1ddf2262131a972962e651b6 \ + --hash=sha256:1f6da814aeecbc6cb8872d6d3e85ed16e8ab1653f9557cea8658725ce212348a \ + --hash=sha256:2095207b75a83c9e947346da9c127fb7e4fb29f41589df2643764f06b750989c \ + --hash=sha256:2319858018eedd0c0b2f950a620413c0a9d1352607be4267eb28209eca8b1e3f \ + --hash=sha256:26e1d9629f3bf70d23f0d22238152aec51c837a7c9e384cb74f356fdccad7eb3 \ + --hash=sha256:29b0d823e3c1e7cd1093a5dc889245db693ef13ada624cd66e2262421ef38867 \ + --hash=sha256:34266cec8c1d4e3e91fcca7efe38971d6bdda64a7944f2a46ab576da15173680 \ + --hash=sha256:36fac804b8cfd6b935ae64f71349f833d2b6298404626d017a2c57bb942bc643 \ + --hash=sha256:3af4e45ff455fce5511fdf2653c1ce428ef09c56fe37a83eb4d924c2d474f31e \ + --hash=sha256:3e3201fe4d46e0d15d7ff9fafc94a605da9eb82d2c5b9837f0368acb325481f1 \ + --hash=sha256:45b3002392948dcf578029c89f6318e1289a993a1a5ec38a4161560fab60f811 \ + --hash=sha256:465bc1526debf53a3be92022a16ca0c38f891ea3b5c1587af4f52e44020f8a07 \ + --hash=sha256:4a4d8c2c7e73ba5967be74d7c3a5ff81fde815ee1b48d9c5c0f14de8463a847b \ + --hash=sha256:4c58dc91aefb31adad500aa68054334f429b840b36dd29e34e834101044cb2ef \ + --hash=sha256:4efbee349138a3fee7a4cc3a95abd2d499fae70dd5bff9fed9138d6f570f4283 \ + --hash=sha256:4fb995082fe41ec410b33c48b54fb1d44abb8a6ee762c31e8c42519e8c3a30a9 \ + --hash=sha256:52fe0176682a25b15370f23f5b0f1366a84771df89144fb0cd979cb72a94b5ca \ + --hash=sha256:58a1b0ec4cbb930e69669f9771715b2c7898d3cdf064d9811f7a66afef96b544 \ + --hash=sha256:63d38e9a9a10a20fb57593742e63c6b1e78dd7f6ef5472de8e0b1e4cf4f3db26 \ + --hash=sha256:6b1ac7f1bc6c0dbf90684b77571a51a21b2463909fd916ce0ac9bfc4d566dc75 \ + --hash=sha256:6b900073e7b8481ef1aaf4f6c1789d210a1db01a9da8789821578cfeb4c2d540 \ + --hash=sha256:6c12d0393a903b58bc5f5a7406d6c5290acfb8284290d68547ce620c06f7d133 \ + --hash=sha256:6ebd39ee26db460cfe5ab8b71a15d1149b289139a0d3981522757d6af620887e \ + --hash=sha256:6f9549ca354a1d6d6167c458a1f1b12147726b968f02dd64b6a5801dba91ae0f \ + --hash=sha256:6ff0145b34610e57c9fae20df4e133c8d54266447387de6fcc0bdabfe4db4569 \ + --hash=sha256:6ff5f0ed70783dcb9562dbd20edca51c3d4d277f128223709e3da6b75986d1d4 \ + --hash=sha256:714bf348f468532d86bed670837e7d5ddff3834dd7f5d3c08066da400c86f088 \ + --hash=sha256:757e3f79cb865a7db94e0db5f4d0ed3284a69e39d53568f433982ea13c60cac1 \ + --hash=sha256:7e32b83bd8c2f8b6fa726ef34e63e21c4d7eddc277d40d4ef7245ea3ed28e5b6 \ + --hash=sha256:805b0f2618e5d4c3e28f45b731eb1a0539691ae4a2f97b4ce014de0bf96a1ff5 \ + --hash=sha256:80eae881cfb69383303e9a4d7961a478025b89c24f38f2e69b30c516fa0d57f2 \ + --hash=sha256:813a32f94991b9627795528053c73a57d2ce3eb98ede89f0e1c7a31095938e81 \ + --hash=sha256:8463b34ebde3f000627e9dbd8a545f995ad49fbf7ff9dd5abc0cd507da98a603 \ + --hash=sha256:8d90d10e9b6594c28f27896a68fab97fd784c43804e9fe419dab8e8dcfcf4b02 \ + --hash=sha256:8e1e037bb57dbc549c6fe20370b763ea74bdb09413cdcf857e4f14d9e4e2fb13 \ + --hash=sha256:931f45f84e15daafec5f82cc92e6710569e1f50933f3253d206eab4132bec678 \ + --hash=sha256:995b52f7c260ac7023640221f27472303968753cb6fc6fce1ddfb0e9db59a398 \ + --hash=sha256:9b4da5789d7cf576c7e81f0088c632f6ee3786d87d17f08e90e703c22ce15633 \ + --hash=sha256:b2ab3aad55d75d0b8df8d8a1b5920baaec9b161112cd5e95984848b4d2cd3dfe \ + --hash=sha256:b2cc6991f16f6d666d48e4b57318104e7b29109e32e2f6b86e9d44c4e6a27f4e \ + --hash=sha256:b5a3f5f70967a1aa2bc47fec42a1e19d2fb38c61700e3ee62b63a4af4f4fd001 \ + --hash=sha256:b6ee42112d785a913dd63ec0335435a3dddbea5040c151252db815b0095cf066 \ + --hash=sha256:b928ab0ecaa664e8caecc529dcb8bc881b6b35bb2b74bf9a39ae25f982ee8812 \ + --hash=sha256:b9430f65db521db7962ad951571d446171213686f96c998a54dc18ed574821e2 \ + --hash=sha256:b9cd15cb7cf0d5cc41f649fd789aae12c56c3b83eff593f8e095c1d4555ad5c3 \ + --hash=sha256:bb1533541c729ad422f870a780d8b4af924f9817d45b5f580390418cda72eaa2 \ + --hash=sha256:bca180cbe84e4fba7807eb408a8655295f697928512324517e30a091ede522a8 \ + --hash=sha256:beb2c8a34cc90fb4d862b7284eafdb322030d6a8b2ee5eb6a744f84205beedc3 \ + --hash=sha256:bfdabac0c6d3d6a5be8c2a100a001c92c14a39bbafd5999545a675c493626e64 \ + --hash=sha256:c0e45def4d9ce7073e2226535572442d9d6efb4047c7a5fd8960807e877ce70a \ + --hash=sha256:c0f537e5e8152e8d9cae82804024790cb973061abd3b7ef8f66f46e2b5c7bb51 \ + --hash=sha256:c42424213c28804f8d0e20f5692106cfb57bf72e1dbc4092b8481fb2f9e4c707 \ + --hash=sha256:cb2bb3ac0af7fdab2311b895c9eb95442b45deb14cc949b9e65545e74aa0be69 \ + --hash=sha256:cd3e55223a77d6e08d5730ebacb4930ecca5d2ce7c57e7ba10833be7e52903f1 \ + --hash=sha256:ce8e723b4637034b76f5382a30a6b725518c332273e8d62a6c7d46e90837c947 \ + --hash=sha256:d1e329a1866981efe0201d05a374617f6c6cf14434a501d78ab22793d1ab1fa6 \ + --hash=sha256:d3906b5c549ff2ad2473cb711e1fc65d76715c2726a402108fbf55eab6c6b49d \ + --hash=sha256:d484ebb7e3a3f3597b0f645fbd1b85633674ca808c1f5ba11c2caf7c66f5c8b6 \ + --hash=sha256:db735a23ecb0f0450d2b24e0a05fb00a8a35c9db172919c4d3e023e7c7ee4c9b \ + --hash=sha256:dbc9fd1521e573045d71b6afab7398439c5cc259e8cb9d416fe62d485c4899c6 \ + --hash=sha256:df3867518b205be3648e2fbd522bf380c851b5c2500588047505afdd786b6669 \ + --hash=sha256:e0acbd474d0af4afacc6e66c4273f8a19e25f8af4379fc816388095ea6b01371 \ + --hash=sha256:eae4e9c7a0785a1a715de0a74fb822ab40084c060f444f18f075d05e322aa7ef \ + --hash=sha256:edd5aa045fa3cc57143db018dd32ce7962bd5b525d05230709015d7e570100aa \ + --hash=sha256:f67db0ba2bedafec15b8e5330d40da1e1c7921559fa715af021252bfef81a6f8 \ + --hash=sha256:f78f7ae1c2e5aabf29583fc0d302d8081a663776f84578025662eb6f5d63a921 \ + --hash=sha256:f9489c1d87160c126f73b004742fe8654fa1ce37ed89e9e01330a1c10aaecde4 \ + --hash=sha256:f9ccc9884241efceb4547a92955d128574c864681f11b7ea3ecbde295fafbe8b \ + --hash=sha256:fc1a4f9d18d32a6e0a0a0a382986a60a2126f5144dd08715be7adb8df18e8a46 + # via uvicorn +httpx==0.28.1 \ + --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \ + --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad + # via + # flock + # huggingface-hub +huggingface-hub==1.33.0 \ + --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \ + --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e + # via flock +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c + # via + # anyio + # httpx +jinja2==3.1.6 \ + --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \ + --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 + # via flock +markdown-it-py==4.2.0 \ + --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \ + --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a + # via rich +markupsafe==3.0.4 \ + --hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \ + --hash=sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b \ + --hash=sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653 \ + --hash=sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c \ + --hash=sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e \ + --hash=sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc \ + --hash=sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92 \ + --hash=sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f \ + --hash=sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4 \ + --hash=sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7 \ + --hash=sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691 \ + --hash=sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc \ + --hash=sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde \ + --hash=sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99 \ + --hash=sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9 \ + --hash=sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df \ + --hash=sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5 \ + --hash=sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17 \ + --hash=sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8 \ + --hash=sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea \ + --hash=sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248 \ + --hash=sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741 \ + --hash=sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6 \ + --hash=sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7 \ + --hash=sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1 \ + --hash=sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67 \ + --hash=sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f \ + --hash=sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9 \ + --hash=sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c \ + --hash=sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc \ + --hash=sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba \ + --hash=sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17 \ + --hash=sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6 \ + --hash=sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2 \ + --hash=sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163 \ + --hash=sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b \ + --hash=sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634 \ + --hash=sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38 \ + --hash=sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed \ + --hash=sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c \ + --hash=sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148 \ + --hash=sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a \ + --hash=sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f \ + --hash=sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811 \ + --hash=sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2 \ + --hash=sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6 \ + --hash=sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed \ + --hash=sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0 \ + --hash=sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b \ + --hash=sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96 \ + --hash=sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59 \ + --hash=sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2 \ + --hash=sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65 \ + --hash=sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72 \ + --hash=sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8 \ + --hash=sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e \ + --hash=sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a \ + --hash=sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2 \ + --hash=sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453 \ + --hash=sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6 \ + --hash=sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977 \ + --hash=sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978 \ + --hash=sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581 \ + --hash=sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369 \ + --hash=sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a \ + --hash=sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916 \ + --hash=sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b \ + --hash=sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f \ + --hash=sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c \ + --hash=sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464 \ + --hash=sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9 \ + --hash=sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee \ + --hash=sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300 \ + --hash=sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6 \ + --hash=sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d \ + --hash=sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46 \ + --hash=sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97 \ + --hash=sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733 \ + --hash=sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe \ + --hash=sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429 \ + --hash=sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39 \ + --hash=sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894 \ + --hash=sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c \ + --hash=sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c \ + --hash=sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77 \ + --hash=sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe \ + --hash=sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad \ + --hash=sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85 \ + --hash=sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e \ + --hash=sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34 \ + --hash=sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c \ + --hash=sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749 \ + --hash=sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214 \ + --hash=sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932 \ + --hash=sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494 \ + --hash=sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1 \ + --hash=sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0 \ + --hash=sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786 \ + --hash=sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78 \ + --hash=sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e \ + --hash=sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289 \ + --hash=sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c \ + --hash=sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe \ + --hash=sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237 \ + --hash=sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19 \ + --hash=sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977 + # via jinja2 +mdurl==0.1.2 \ + --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \ + --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba + # via markdown-it-py +opentelemetry-api==1.45.1 \ + --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ + --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb + # via fastapi +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c + # via + # flock + # huggingface-hub +pydantic==2.14.1 \ + --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \ + --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26 + # via + # fastapi + # flock +pydantic-core==2.50.1 \ + --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \ + --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \ + --hash=sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019 \ + --hash=sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685 \ + --hash=sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b \ + --hash=sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482 \ + --hash=sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658 \ + --hash=sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498 \ + --hash=sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec \ + --hash=sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a \ + --hash=sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b \ + --hash=sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4 \ + --hash=sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a \ + --hash=sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8 \ + --hash=sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb \ + --hash=sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e \ + --hash=sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8 \ + --hash=sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7 \ + --hash=sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a \ + --hash=sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e \ + --hash=sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396 \ + --hash=sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255 \ + --hash=sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899 \ + --hash=sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43 \ + --hash=sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb \ + --hash=sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f \ + --hash=sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d \ + --hash=sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415 \ + --hash=sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c \ + --hash=sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea \ + --hash=sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2 \ + --hash=sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e \ + --hash=sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568 \ + --hash=sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6 \ + --hash=sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a \ + --hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9 \ + --hash=sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1 \ + --hash=sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff \ + --hash=sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f \ + --hash=sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5 \ + --hash=sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb \ + --hash=sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4 \ + --hash=sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0 \ + --hash=sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597 \ + --hash=sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b \ + --hash=sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa \ + --hash=sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242 \ + --hash=sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f \ + --hash=sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc \ + --hash=sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f \ + --hash=sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c \ + --hash=sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61 \ + --hash=sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102 \ + --hash=sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4 \ + --hash=sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e \ + --hash=sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54 \ + --hash=sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070 \ + --hash=sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed \ + --hash=sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb \ + --hash=sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5 \ + --hash=sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19 \ + --hash=sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5 \ + --hash=sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112 \ + --hash=sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9 \ + --hash=sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5 \ + --hash=sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72 \ + --hash=sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2 \ + --hash=sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8 \ + --hash=sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295 \ + --hash=sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e \ + --hash=sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe \ + --hash=sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290 \ + --hash=sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea \ + --hash=sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662 \ + --hash=sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41 \ + --hash=sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44 \ + --hash=sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807 \ + --hash=sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78 \ + --hash=sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c \ + --hash=sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3 \ + --hash=sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831 \ + --hash=sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86 \ + --hash=sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2 \ + --hash=sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f \ + --hash=sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f \ + --hash=sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10 \ + --hash=sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5 \ + --hash=sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b \ + --hash=sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09 \ + --hash=sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a \ + --hash=sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e \ + --hash=sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459 \ + --hash=sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08 \ + --hash=sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709 \ + --hash=sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a \ + --hash=sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20 + # via pydantic +pygments==2.21.0 \ + --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \ + --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c + # via rich +python-dotenv==1.2.4 \ + --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc \ + --hash=sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0 + # via uvicorn +pyyaml==6.0.3 \ + --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \ + --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \ + --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \ + --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \ + --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \ + --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \ + --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \ + --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \ + --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \ + --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \ + --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \ + --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \ + --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \ + --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \ + --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \ + --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \ + --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \ + --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \ + --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \ + --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \ + --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \ + --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \ + --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \ + --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \ + --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \ + --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \ + --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \ + --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \ + --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \ + --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \ + --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \ + --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \ + --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \ + --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \ + --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \ + --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \ + --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \ + --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \ + --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0 + # via + # flock + # huggingface-hub + # uvicorn +rich==15.0.0 \ + --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \ + --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36 + # via typer +shellingham==1.5.4 \ + --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \ + --hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de + # via typer +starlette==1.8.0 \ + --hash=sha256:1565dc0b35d5737a271ed1e0e04e949f4e81198799f216d2667b0a0fb9cf9522 \ + --hash=sha256:dfdd6b29c26483288088d990eee59631dedadd66ce20d203402a7ca8e3c4656f + # via fastapi +tqdm==4.70.1 \ + --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \ + --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4 + # via huggingface-hub +typer==0.27.3 \ + --hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \ + --hash=sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff + # via flock +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # anyio + # exceptiongroup + # fastapi + # huggingface-hub + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 \ + --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \ + --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147 + # via + # fastapi + # pydantic +uvicorn==0.54.0 \ + --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \ + --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620 + # via flock +uvloop==0.23.0 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \ + --hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \ + --hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \ + --hash=sha256:12634f15e6625f78b3f2922f91404c4d7173487eba11746764153f556e9852dc \ + --hash=sha256:1748321e3c59a14a75404b1ae8d5a8d81c4e201803ea0e14c1b6fd84421024b5 \ + --hash=sha256:19c64108b507cd0bc140e400e3396bacebd9d504956aa7726272bf6de7d9aabb \ + --hash=sha256:1e84575f11873c109cf3962ad0bdf679094466184125f4cadcc41a73febff41f \ + --hash=sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27 \ + --hash=sha256:2dcff2d69be43e6559e5dad2c5a7a2dbfb60e05a77311b6c4b7a4a8123d86c65 \ + --hash=sha256:31e0cf90bc8fd88784f6802cdba968a51fb1aec1cc3feec74d862b2d371d1330 \ + --hash=sha256:378188efbb1524f2219d05246a3e1e5907217848d2882144dff59585f1b81d55 \ + --hash=sha256:4448e9124537620f9c25d004c227bb5104440b58955c19bbd312d910af919a63 \ + --hash=sha256:4a08875543bbd4519faf30497506c9cda8a48470467ffdf967c7313c7a5981a8 \ + --hash=sha256:4b8e207c67d207a8608fec57e116511030af3495dc0109b8c333cf9cb412b16f \ + --hash=sha256:4f1798f56c6f4ba5ac11fa2869e5717926e4470d97a1dd42b4f59219d43b5027 \ + --hash=sha256:5a2bbad3a63007f7e9524d4903ba04fee252557c2acd86f9a3d4f91786695254 \ + --hash=sha256:5bb9be71d9ee39b4359b832f9569518ec9bc08704194034e79e4958e6bc4d46d \ + --hash=sha256:6b3cbc4f96ddfa1fb88a78a69dd851369825b7816d9702eee8c4461505ba172e \ + --hash=sha256:6c7ef4701a96553514b2688e342ef1bf2beae6cfd172d89a76c768292aabf405 \ + --hash=sha256:7337b06a9f9ed9ea3049f04b76f65819db9b19bb832ee598e97b388eadf25e5f \ + --hash=sha256:76345f51367fb1f23e08605c6efb18374f669be5b223658fbab6b17627950507 \ + --hash=sha256:7e35c9bc977760981693e1a7a51493b58ee5a501f9ebb1e547565ee40b6c6208 \ + --hash=sha256:93935ab27b6eaef4c3e5489aebc84284f0644592f7ab516df60ee1b27eaf5eb3 \ + --hash=sha256:a6ac96da66c35bf789bdcde78a88dc7d56b7907d8379648c54adc1c61594575d \ + --hash=sha256:b90397a50ad6332ed3e459c648ac20d182cce24a557354363ad85fc9ea4a17cd \ + --hash=sha256:bbbdb8fcd5e7062e546eec1ac78c28bb21ae7df54c18f8e4b06e15a18d661a49 \ + --hash=sha256:bd6f2f81c7b9da99d301c0b16b82044e76fe887086e42e1590ecf520b94dbdac \ + --hash=sha256:be53e1d5f83de43dc175c87612ecc128d444b38e5c56cb3f807f5a73d6887476 \ + --hash=sha256:c3f23f403a273900d57de6ee5ca0614c650f7f58563065dad1a4744498960e53 \ + --hash=sha256:cbe8d03d4efcccdb7fcedecbaa1e1fa02913eaf3a74cb933634a6bc6d2ea9e2a \ + --hash=sha256:dc61e4f9e37b507069dc7e659ae28bca7adcb04c993c3508214315d12c63f848 \ + --hash=sha256:e095f9e105af76593b4c183bb0bcbdae64bd913a59ec595732dc108b48730ab5 \ + --hash=sha256:e2cba180d6451822763eda8364f342435a873bcfb3849cbd82fdeca248ca65eb \ + --hash=sha256:f1341c6abcee1c31277cfe28d34e46196f2143ec3d755e6efe7452126e1f626d \ + --hash=sha256:f3fbfe82829d8e381426a289b87e59e585278728361db9ce975b88b51f64f410 \ + --hash=sha256:f673d835bdb1a60229cc3609a113fd2c9ce3f4a3c75ad4eaed111180c00199d2 \ + --hash=sha256:f7548ede3ee908cfabc0d068106e303a9a2d811af959cdf6ab85676344cedcda \ + --hash=sha256:fa8ed556fcc87a4091cf61587ef172fa104323dc89ecc085a618ba7ff8629a8f + # via uvicorn +watchfiles==1.3.0 \ + --hash=sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441 \ + --hash=sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95 \ + --hash=sha256:04c5500faa725d69a99b0f63750e80795e455bb951849e9c98a811b4324997c4 \ + --hash=sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61 \ + --hash=sha256:26b81bc515a0f03f66a69a6fea86eea54c8eca4173c46dd7222569f79dd2f977 \ + --hash=sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509 \ + --hash=sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5 \ + --hash=sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661 \ + --hash=sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30 \ + --hash=sha256:7c1125e99f84934a92996ae343501285617373acd66f16b59fd5654b27ad8d80 \ + --hash=sha256:81c989d7267bfb7b676cd32c83bec97914e396870983cbf493e29415037bff5e \ + --hash=sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207 \ + --hash=sha256:a5b631db08fd3032db57ec6a92d1777cd60f88803287e4e941a4858c53aab1e0 \ + --hash=sha256:a85e243c87109d9f48a2e0d10d6abdee8768cc114848b32281ec83d7f81d86ef \ + --hash=sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1 \ + --hash=sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c \ + --hash=sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29 \ + --hash=sha256:ca39661934749df580d89f3dde266f2af7c6968f4c21c72ce2dc387d299e6aa7 \ + --hash=sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935 \ + --hash=sha256:d4593392e87669836670f87d62fc754059eaeb0e6157af44060a46558cebe5a3 \ + --hash=sha256:d754e049006e81a9be49dc78ba7802081cee426e968cbc63ee19e164fa2d0e39 \ + --hash=sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc \ + --hash=sha256:da213822ec9082b62cadf3008e07a8c690ec7a3c89f6dc5e55a8cf07b56a1b26 \ + --hash=sha256:dd538c71766c59c732e2c5cedc39323c99c11897b99f93eac773438e54af206a \ + --hash=sha256:e0204f90677b7fb8d3a824279a71a01166bea9f6e53923b8056592d87b33b0b6 \ + --hash=sha256:e5871d4a7f788a9f64fb06f5793389d29d171e5c32d37c3ebfd520b017cc7694 \ + --hash=sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca \ + --hash=sha256:ec3cd4bb181a7b6329134204c2277c7144ab5f62cce9c5335d6f901ee7ce8d6a \ + --hash=sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3 + # via uvicorn +websockets==15.0.1 \ + --hash=sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2 \ + --hash=sha256:0af68c55afbd5f07986df82831c7bff04846928ea8d1fd7f30052638788bc9b5 \ + --hash=sha256:0f3c1e2ab208db911594ae5b4f79addeb3501604a165019dd221c0bdcabe4db8 \ + --hash=sha256:229cf1d3ca6c1804400b0a9790dc66528e08a6a1feec0d5040e8b9eb14422375 \ + --hash=sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597 \ + --hash=sha256:3c714d2fc58b5ca3e285461a4cc0c9a66bd0e24c5da9911e30158286c9b5be7f \ + --hash=sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3 \ + --hash=sha256:558d023b3df0bffe50a04e710bc87742de35060580a293c2a984299ed83bc4e4 \ + --hash=sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665 \ + --hash=sha256:595b6c3969023ecf9041b2936ac3827e4623bfa3ccf007575f04c5a6aa318c22 \ + --hash=sha256:5a939de6b7b4e18ca683218320fc67ea886038265fd1ed30173f5ce3f8e85675 \ + --hash=sha256:5d54b09eba2bada6011aea5375542a157637b91029687eb4fdb2dab11059c1b4 \ + --hash=sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65 \ + --hash=sha256:746ee8dba912cd6fc889a8147168991d50ed70447bf18bcda7039f7d2e3d9151 \ + --hash=sha256:756c56e867a90fb00177d530dca4b097dd753cde348448a1012ed6c5131f8b7d \ + --hash=sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee \ + --hash=sha256:ba9e56e8ceeeedb2e080147ba85ffcd5cd0711b89576b83784d8605a7df455fa \ + --hash=sha256:c338ffa0520bdb12fbc527265235639fb76e7bc7faafbb93f6ba80d9c06578a9 \ + --hash=sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe \ + --hash=sha256:e09473f095a819042ecb2ab9465aee615bd9c2028e4ef7d933600a8401c79561 \ + --hash=sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215 \ + --hash=sha256:ee443ef070bb3b6ed74514f5efaa37a252af57c90eb33b956d35c8e9c10a1931 \ + --hash=sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f \ + --hash=sha256:fcd5cf9e305d7b8338754470cf69cf81f420459dbae8a3b40cee57417f4614a7 + # via uvicorn diff --git a/world/sandbox.py b/world/sandbox.py new file mode 100644 index 0000000000000000000000000000000000000000..5f31d8100a6ab4ef1f426e0e7f115a8c25bca940 --- /dev/null +++ b/world/sandbox.py @@ -0,0 +1,233 @@ +"""Contract runner: isolated interpreter, bounded resources, no bot I/O except stdio/imports. +With PYBOT_SANDBOX_URL set, runs go to a sidecar (`python sandbox.py serve`, same image) instead.""" +from __future__ import annotations + +import base64 +import hmac +import io +import json +import logging +import os +import signal +import subprocess +import sys +import tarfile +import tempfile +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from flock.isolation import command as isolate_command +from flock.world import ToolError + +# The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree +# for the shared tests: main grows by about one file per merge, so the cap allows a long run. +MAX_REQUEST_BYTES, MAX_TREE_BYTES, MAX_TREE_MEMBERS = 64 << 20, 64 << 20, 20000 +log = logging.getLogger(__name__) + +SHIM = r''' +import sys, os, resource, runpy +root = os.path.realpath(sys.argv[1]) +resource.setrlimit(resource.RLIMIT_AS, (512 << 20, 512 << 20)) +resource.setrlimit(resource.RLIMIT_CPU, (300, 300)) +resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20)) +resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64)) +resource.setrlimit(resource.RLIMIT_NPROC, (0, 0)) +sys.dont_write_bytecode = True +sys.path.insert(0, root) +allowed = set(sys.stdlib_module_names) | {'bot'} +blocked = {'ctypes', '_ctypes', '_posixsubprocess', 'subprocess', 'socket', '_socket', 'multiprocessing'} +def audit(event, args): + if event == 'import': + name = args[0].split('.')[0] + if name not in allowed or name in blocked: + raise PermissionError('only standard-library bot imports are allowed') + if event == 'open': + path, mode, flags = args + if not isinstance(path, (str, bytes, os.PathLike)): + raise PermissionError('file access is disabled') + path = os.path.realpath(os.fsdecode(path)) + if flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND): + raise PermissionError('file writes are disabled') + roots = (root + os.sep, os.path.realpath(sys.base_prefix) + os.sep) + if not path.startswith(roots) or not path.endswith(('.py', '.pyc', '.so')): + raise PermissionError('file access is disabled except module loading') + if event.startswith(('socket.', 'subprocess.', 'ctypes.', 'os.kill', 'signal.')) or event in { + 'os.system', 'os.exec', 'os.fork', 'os.forkpty', 'os.posix_spawn', 'os.kill', 'os.killpg', + 'os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.chmod', 'os.link', + 'os.symlink', 'os.truncate', 'os.putenv', 'os.unsetenv'}: + raise PermissionError('bot side effects are disabled') +import signal, _signal +# Signals to other processes: os.kill/killpg and signal.pthread_kill raise audit events +# (blocked above); pidfd_send_signal does not, so remove every sender from the modules. +for module in (os, sys.modules.get('posix'), signal, _signal): + for name in ('kill', 'killpg', 'pthread_kill', 'pidfd_send_signal'): + if module is not None and hasattr(module, name): + delattr(module, name) +sys.addaudithook(audit) +runpy.run_module('bot', run_name='__main__') +''' + +# The repository's own tests matching a pattern under tests/ (python -m unittest discover -s +# tests -p , as agents run them). Same limits as the bot; tests may read any file, so +# its hook keeps only the side-effect blocks (the sidecar has no namespaces to stop them). +TESTS_SHIM = r''' +import sys, os, resource, unittest +root = os.path.realpath(sys.argv[1]) +resource.setrlimit(resource.RLIMIT_AS, (512 << 20, 512 << 20)) +resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20)) +resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64)) +resource.setrlimit(resource.RLIMIT_NPROC, (0, 0)) +sys.dont_write_bytecode = True +sys.path.insert(0, root) +blocked = {'ctypes', '_ctypes', '_posixsubprocess', 'subprocess', 'socket', '_socket', 'multiprocessing'} +def audit(event, args): + if event == 'import' and args[0].split('.')[0] in blocked: + raise PermissionError('test imports of ' + args[0] + ' are disabled') + if event == 'open' and args[2] & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND): + raise PermissionError('file writes are disabled') + if event.startswith(('socket.', 'subprocess.', 'ctypes.', 'os.kill', 'signal.')) or event in { + 'os.system', 'os.exec', 'os.fork', 'os.forkpty', 'os.posix_spawn', 'os.kill', 'os.killpg', + 'os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.chmod', 'os.link', + 'os.symlink', 'os.truncate', 'os.putenv', 'os.unsetenv'}: + raise PermissionError('test side effects are disabled') +sys.addaudithook(audit) +tests = os.path.join(root, 'tests') +suite = (unittest.defaultTestLoader.discover(tests, pattern=sys.argv[2], top_level_dir=tests) + if os.path.isdir(tests) else unittest.TestSuite()) +sys.exit(not unittest.TextTestRunner().run(suite).wasSuccessful()) +''' + + +def run(root: Path, lines: list[str], timeout: float = 300, isolate: bool = True) -> dict: + if not lines or len(lines) > 200 or any(not isinstance(x, str) or '\n' in x or '\r' in x + or len(x) > 16000 for x in lines): + return {"ok": False, "status": "supply 1–200 single input lines (at most 16000 chars each)"} + if isolate and (url := os.environ.get("PYBOT_SANDBOX_URL")): # the sidecar: no secrets in its container + # .py only: all the shim lets a bot open + return _remote(os.path.expandvars(url), root, {"lines": lines, "timeout": timeout}, "*.py") + return _local(root, lines, timeout, isolate) + + +def run_tests(root: Path, pattern: str, timeout: float = 60, isolate: bool = True) -> dict: + """Run root's tests/ files matching pattern, isolated like run() (in the sidecar with + PYBOT_SANDBOX_URL). ok when they pass (or none match); status "timeout" past timeout; + output: their combined output (1 MiB).""" + if isolate and (url := os.environ.get("PYBOT_SANDBOX_URL")): # tests read data files: the whole tree + return _remote(os.path.expandvars(url), root, {"tests": pattern, "timeout": timeout}, "*") + with tempfile.TemporaryDirectory() as tmp, open(Path(tmp) / "out", "w+b") as out: + status = _isolated(root, tmp, [TESTS_SHIM, str(root.resolve()), pattern], b"", timeout, + out, out, isolate) + out.seek(0) + return {"ok": status == "ok", "status": status, + "output": out.read(1 << 20).decode(errors="replace")} + + +def _remote(url: str, root: Path, payload: dict, files: str) -> dict: + """POST payload and the tree's files matching the glob to the sidecar; its reply.""" + buf, sent = io.BytesIO(), 0 + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for f in sorted(root.rglob(files)): + # regular files only: the sidecar refuses links (and never gets a link's target) + if ".git" not in f.relative_to(root).parts and f.is_file() and not f.is_symlink(): + tar.add(f, f.relative_to(root).as_posix()) + sent += 1 + body = json.dumps({**payload, "tree": base64.b64encode(buf.getvalue()).decode()}).encode() + req = urllib.request.Request(f"{url.rstrip('/')}/run", body, method="POST", headers={ + "Content-Type": "application/json", + "X-Sandbox-Token": os.environ.get("PYBOT_SANDBOX_TOKEN", "")}) + try: + with urllib.request.urlopen(req, timeout=payload["timeout"] + 30) as r: + return json.load(r) + except (OSError, ValueError) as e: # never "your bot failed" when the runner is down + if isinstance(e, urllib.error.HTTPError): # it answered and refused: say why in the log + log.warning("sandbox sidecar refused a %s run: HTTP %s (%d files, %d bytes sent)", + "tests" if "tests" in payload else "bot", e.code, + sent, len(body)) + raise ToolError(f"bot runner unavailable ({type(e).__name__}); retry later", "busy", + retry_after_s=30) from None + + +def _isolated(root: Path, tmp: str, args: list[str], data: bytes, timeout: float, out, err, + isolate: bool = True) -> str: + """Run `python -I -S -c *args` (isolated: root read-only), data on stdin; the status.""" + argv = [sys.executable, "-I", "-S", "-c", *args] + if isolate: + argv = isolate_command(argv, Path(tmp) / "root", cwd=root.resolve(), + readonly=[root.resolve()], python_only=True) + proc = subprocess.Popen(argv, cwd=tmp, env={}, stdin=subprocess.PIPE, stdout=out, stderr=err, + start_new_session=True) + try: + proc.communicate(data, timeout=timeout) + return "ok" if proc.returncode == 0 else f"exit {proc.returncode}" + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + return "timeout" + + +def _local(root: Path, lines: list[str], timeout: float, isolate: bool = True) -> dict: + with (tempfile.TemporaryDirectory() as tmp, + open(Path(tmp) / "out", "w+b") as out, + open(Path(tmp) / "err", "w+b") as err): + status = _isolated(root, tmp, [SHIM, str(root.resolve())], + ('\n'.join(lines) + '\n').encode(), timeout, out, err, isolate) + out.seek(0) + err.seek(0) + replies = out.read(1 << 20).decode(errors="replace").splitlines() + ok = status == "ok" and len(replies) == len(lines) and all(x.strip() for x in replies) + return {"ok": ok, "status": status, "replies": replies, + "stderr": err.read(4096).decode(errors="replace"), "timeout_s": timeout} + + +class _Handler(BaseHTTPRequestHandler): + """POST /run {lines, timeout, tree: base64 tar.gz} -> run()'s dict, or {tests: pattern, + timeout, tree} -> run_tests()'s. The sidecar only: `unshare` is blocked in HF Jobs + containers, so the job boundary (no secrets) replaces it.""" + + def do_POST(self): + token = os.environ.get("PYBOT_SANDBOX_TOKEN", "") + n = int(self.headers.get("Content-Length") or 0) + if self.path != "/run" or not token or not hmac.compare_digest( + self.headers.get("X-Sandbox-Token", ""), token) or not 0 < n <= MAX_REQUEST_BYTES: + return self._send(403, {"ok": False, "status": "refused"}) + try: + req = json.loads(self.rfile.read(n)) + timeout = min(300, float(req.get("timeout", 300))) # 300 first: an int, as local + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "tree" + with tarfile.open(fileobj=io.BytesIO(base64.b64decode(req["tree"])), mode="r:gz") as t: + count = total = 0 + for m in t: # before extracting: a small .tar.gz can expand hugely + count, total = count + 1, total + m.size + if count > MAX_TREE_MEMBERS or total > MAX_TREE_BYTES or not (m.isfile() or m.isdir()): + raise ValueError("tree: too many or too large members, or not files and dirs") + t.extractall(root, filter="data") # no absolute paths, links or ../ + if "tests" in req: + if not isinstance(req["tests"], str): + raise ValueError("tests") + out = run_tests(root, req["tests"], timeout, isolate=False) + elif not isinstance(req["lines"], list): + raise ValueError("lines") # run() checks each line + else: + out = run(root, req["lines"], timeout, isolate=False) + except (KeyError, ValueError, TypeError, tarfile.TarError, OSError) as e: + return self._send(400, {"ok": False, "status": f"bad request: {type(e).__name__}"}) + self._send(200, out) + + def _send(self, code, obj): + data = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + +if __name__ == "__main__" and sys.argv[1:] == ["serve"]: + if not os.environ.get("PYBOT_SANDBOX_TOKEN"): + sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused + from flock.isolation import protect_supervisor + protect_supervisor() # a bot under this uid cannot read this process's env or memory + ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever() diff --git a/world/scripts/check-sidecar.py b/world/scripts/check-sidecar.py new file mode 100644 index 0000000000000000000000000000000000000000..99df2c6f6c4e289ee3a010d8357533a65168c30e --- /dev/null +++ b/world/scripts/check-sidecar.py @@ -0,0 +1,171 @@ +"""The bot sandbox sidecar on localhost: python world/scripts/check-sidecar.py + +Starts `sandbox.py serve` as a 2nd process and checks: its result equals the local path's (the seed, +the merge-check lines); `import socket` in a bot is blocked; merge_pr's shared tests (run_tests, +the seed's test_deck.py) pass there as locally, fail on a duplicate deck id (the data files went +along), and a test cannot import socket or write a file; a tree of 3,000 more files (a long run's +main) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logs +its HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeout +works. +Local path without `unshare` (blocked on many boxes). Needs requirements.txt, 3.12+. +""" +import base64 +import io +import json +import logging +import os +import shutil +import socket +import subprocess +import sys +import tarfile +import tempfile +import time +import urllib.error +import urllib.request +from pathlib import Path + +WORLD = SRC = Path(__file__).resolve().parent.parent # world/ +sys.path[:0] = [str(WORLD / "src"), str(SRC)] +LINES = ["Hello", "My name is Sam", "", "What is my name?", "Bye"] + + +def post_tar(port, members): + """POST /run with a hand-made tar: members are (TarInfo, data or None).""" + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as t: + for info, data in members: + t.addfile(info, None if data is None else io.BytesIO(data)) + req = urllib.request.Request(f"http://127.0.0.1:{port}/run", json.dumps( + {"lines": ["hi"], "tree": base64.b64encode(buf.getvalue()).decode()}).encode(), + headers={"X-Sandbox-Token": "tok", "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=60) as r: + return r.status, json.load(r) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read()) + + +def member(name, size=4, kind=tarfile.REGTYPE, link=""): + info = tarfile.TarInfo(name) + info.size, info.type, info.linkname = size, kind, link + return info, bytes(size) if kind == tarfile.REGTYPE else None + + +def main(): + import sandbox + from flock.world import ToolError + + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + srv = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], stderr=subprocess.DEVNULL, + env={"PYTHONPATH": str(WORLD / "src"), "PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)}) + try: + for _ in range(300): + try: + socket.create_connection(("127.0.0.1", port), timeout=1).close() + break + except OSError: + assert srv.poll() is None, "sandbox.py serve exited" + time.sleep(0.1) + tmp = Path(tempfile.mkdtemp(prefix="check-sidecar-")) + tree = tmp / "tree" + shutil.copytree(SRC / "seed", tree) + local = sandbox.run(tree, LINES, isolate=False) + os.environ.update(PYBOT_SANDBOX_URL=f"http://${{SB_HOST}}:{port}", SB_HOST="127.0.0.1", + PYBOT_SANDBOX_TOKEN="tok") + remote = sandbox.run(tree, LINES) + assert remote == local and remote["ok"], (remote, local) + print("ok merge-check lines via the sidecar == local:", remote["replies"][:2]) + + bad = tmp / "bad" + shutil.copytree(tree, bad) + (bad / "bot/modules/greeting.py").write_text( + "PRIORITY = -1000\ndef respond(text, memory):\n try:\n import socket\n" + " return 'NET'\n except PermissionError:\n return 'BLOCKED'\n") + r1, r2 = sandbox.run(bad, LINES), sandbox.run(bad, LINES, isolate=False) + assert r1 == r2 and set(r1["replies"]) == {"BLOCKED"}, (r1, r2) + print("ok import socket in a bot: blocked, as locally") + + r1, r2 = sandbox.run_tests(tree, "test_deck.py"), sandbox.run_tests(tree, "test_deck.py", isolate=False) + assert r1["ok"] and r2["ok"] and "Ran 2 tests" in r1["output"], (r1, r2) + print("ok shared tests (test_deck.py) via the sidecar: pass, as locally") + dup = tmp / "dup" + shutil.copytree(tree, dup) + deck = dup / "deck" / "single.jsonl" + deck.write_text(deck.read_text() + deck.read_text().splitlines()[0] + "\n") + r1, r2 = sandbox.run_tests(dup, "test_deck.py"), sandbox.run_tests(dup, "test_deck.py", isolate=False) + assert (r1["status"], r2["status"]) == ("exit 1", "exit 1") and "FAIL:" in r1["output"], (r1, r2) + print("ok a duplicate deck id fails them via the sidecar too (the data files went along)") + (dup / "tests" / "test_side_effects.py").write_text( + "import unittest\nclass T(unittest.TestCase):\n def test_blocked(self):\n" + " with self.assertRaises(PermissionError):\n import socket\n" + " with self.assertRaises(PermissionError):\n open('written', 'w')\n") + r1 = sandbox.run_tests(dup, "test_side_effects.py") + assert r1["ok"] and "Ran 1 test" in r1["output"], r1 + print("ok a test's import socket and file write: blocked in the sidecar") + + big = tmp / "big" # main after a long run: thousands of files, half of them *.py + shutil.copytree(tree, big) + for i in range(1500): + (big / "tools" / "gen").mkdir(parents=True, exist_ok=True) + (big / "tools" / "gen" / f"m{i}.py").write_text(f"X = {i}\n" * 20) + (big / "notes").mkdir(exist_ok=True) + (big / "notes" / f"n{i}.txt").write_text(f"note {i}\n" * 20) + files = sum(1 for f in big.rglob("*") if f.is_file()) + r1, r2 = sandbox.run_tests(big, "test_deck.py"), sandbox.run(big, LINES) + assert r1["ok"] and r2 == local, (r1, r2) + print(f"ok a tree of {files} files: shared tests and the bot run via the sidecar") + + os.environ["PYBOT_SANDBOX_TOKEN"] = "nope" + logged = [] + handler = logging.Handler() + handler.emit = lambda record: logged.append(record.getMessage()) + sandbox.log.addHandler(handler) + try: + sandbox.run(tree, LINES) + raise AssertionError("a bad token was accepted") + except ToolError as e: + assert e.code == "busy", e.code + sandbox.log.removeHandler(handler) + assert len(logged) == 1 and "HTTP 403" in logged[0], logged + os.environ["PYBOT_SANDBOX_TOKEN"] = "tok" + print(f"ok bad token -> busy, logged: {logged[0]}") + + refused = { + "../ in a path": [member("../escape.py")], + "a symlink": [member("bot/x.py", 0, tarfile.SYMTYPE, "/etc/passwd")], + f"{sandbox.MAX_TREE_MEMBERS + 1} members": [member(f"m{i}.py") for i in range(sandbox.MAX_TREE_MEMBERS + 1)], + f"{(sandbox.MAX_TREE_BYTES >> 20) + 1} MB of zeros": [member("big.py", sandbox.MAX_TREE_BYTES + (1 << 20))], + } + for what, members in refused.items(): + status, body = post_tar(port, members) + assert status == 400, (what, status, body) + print(f"ok tar with {what} -> 400 {body['status']}") + status, body = post_tar(port, [member(f"m{i}.py") for i in range(10)]) + assert status == 200, (status, body) # within the caps: extracted and run (no bot: a failed run) + + slow = tmp / "slow" + shutil.copytree(tree, slow) + (slow / "bot/modules/greeting.py").write_text("while True: pass\n") + t0 = time.time() + r = sandbox.run(slow, ["hi"], timeout=2) + assert r["status"] == "timeout" and time.time() - t0 < 10, r + print(f"ok timeout after {time.time() - t0:.1f} s") + + os.environ.update(SB_HOST="127.0.0.2", PYBOT_SANDBOX_URL="http://${SB_HOST}:1") + try: + sandbox.run(tree, LINES) + raise AssertionError("an unreachable sidecar did not raise") + except ToolError as e: + assert e.code == "busy", e.code + print("ok unreachable sidecar -> busy") + shutil.rmtree(tmp) + print("PASS") + finally: + srv.terminate() + + +if __name__ == "__main__": + main() diff --git a/world/scripts/smoke-local.py b/world/scripts/smoke-local.py new file mode 100644 index 0000000000000000000000000000000000000000..392d97e66d5d0889bbf322a1da978644ca5f3a23 --- /dev/null +++ b/world/scripts/smoke-local.py @@ -0,0 +1,150 @@ +"""Container-free smoke of the world: python world/scripts/smoke-local.py [--sidecar] + +Starts PybotWorld from world/ with plain Python on a free port, backed by a FAKE +in-process hub (a local bare git repo + LocalHub, injected as `repository`; the shipped code still +defaults to the real Hub). Checks /healthz, the token (and a per-agent one), /manifest's tools and +one run_bot call. +With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only its +token) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no network +calls beyond localhost. Needs the deps in requirements.txt and git. +""" +import json +import os +import socket +import subprocess +import sys +import tempfile +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + +WORLD = SRC = Path(__file__).resolve().parent.parent # world/ +sys.path[:0] = [str(WORLD / "src"), str(SRC)] +TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict", + "verdicts", "run_bot", "world_status"} +TOKEN = "smoke-token" + + +def git(path, *args): + return subprocess.run(["git", "-C", str(path), *args], check=True, capture_output=True, + text=True).stdout.strip() + + +class LocalHub: # tests/test_pybot.py's fake: PRs are refs/pr/N in the bare remote + def __init__(self, remote): + self.remote, self.n = remote, 0 + + def open(self, title, description): + self.n += 1 + git(self.remote, "update-ref", f"refs/pr/{self.n}", "main") + return self.n + + def ready(self, pr): pass + def comment(self, pr, text): pass + def close(self, pr, comment): pass + def merge(self, pr, comment): raise NotImplementedError("not used by this smoke") + + +def call(port, method, path, body=None, token=TOKEN, agent="smoke"): + req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method, + data=None if body is None else json.dumps(body).encode(), + headers={"Content-Type": "application/json", "X-Flock-Agent": agent, + **({"X-World-Token": token} if token else {})}) + try: + with urllib.request.urlopen(req, timeout=60) as r: + return r.status, json.loads(r.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read() or b"null") + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def start_sidecar(tmp): + """sandbox.py serve with nothing but its token, PORT and the library path; returns (proc, log).""" + port, log = free_port(), tmp / "sidecar.log" + proc = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], cwd=SRC, + stderr=log.open("wb"), env={"PYBOT_SANDBOX_TOKEN": "sidecar-token", + "PORT": str(port), "PYTHONPATH": str(WORLD / "src")}) + for _ in range(100): + try: + socket.create_connection(("127.0.0.1", port), timeout=1).close() + break + except OSError: + assert proc.poll() is None, log.read_text() + time.sleep(0.1) + os.environ.update(PYBOT_SANDBOX_URL=f"http://127.0.0.1:{port}", PYBOT_SANDBOX_TOKEN="sidecar-token") + print(f"ok sidecar: sandbox.py serve on 127.0.0.1:{port}") + return proc, log + + +def main(sidecar=False): + import uvicorn + from pybot import PybotWorld + from repository import Repository + + from flock.world.server import create_app + + tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-")) + os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="") # the fake hub ignores both + seed = tmp / "seed" + subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True) + git(seed, "init", "-q", "-b", "main") + git(seed, "add", ".") + git(seed, "-c", "user.name=seed", "-c", "user.email=seed@flock.invalid", "commit", "-qm", "seed") + remote = tmp / "remote.git" + git(tmp, "clone", "-q", "--bare", str(seed), str(remote)) + repo = Repository(tmp / "ws" / "repo.git", str(remote)) + repo.hub = LocalHub(remote) + world = PybotWorld(tmp / "ws", repo) + + port = free_port() + if sidecar: + sidecar_proc, sidecar_log = start_sidecar(tmp) + server = uvicorn.Server(uvicorn.Config(create_app(world, TOKEN), host="127.0.0.1", port=port, + log_level="warning")) + threading.Thread(target=server.run, daemon=True).start() + for _ in range(100): + try: + if call(port, "GET", "/healthz", token=None) == (200, {"status": "ready"}): + break + except OSError: + pass + time.sleep(0.1) + else: + sys.exit("FAIL: /healthz never said ready") + print(f"ok GET /healthz on 127.0.0.1:{port}: ready") + + assert call(port, "GET", "/manifest", token="wrong")[0] == 401 + print("ok GET /manifest with a wrong X-World-Token: 401") + from flock.world.protocol import agent_token + own = agent_token(TOKEN, "smoke") + assert call(port, "GET", "/manifest", token=own)[0] == 200 + assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401 + print("ok GET /manifest with the agent's own token: 200; as another agent: 401") + status, m = call(port, "GET", "/manifest") + names = {t["name"] for t in m["tools"]} + assert status == 200 and names == TOOLS, (status, names) + print(f"ok GET /manifest: {m['name']} {m['version']}, {len(names)} tools: {', '.join(sorted(names))}") + + status, r = call(port, "POST", "/tools/run_bot", + {"args": {"ref_or_path": "main", "lines": ["Hello"]}}) + ran = status == 200 and r["result"]["ok"] # False where unshare is not permitted (README) + print(f"{'ok ' if ran else 'note'} POST /tools/run_bot main ['Hello']: {status} " + f"{json.dumps(r)[:300]}") + server.should_exit = True + if sidecar: + sidecar_proc.terminate() + sidecar_proc.wait(10) + served = '"POST /run HTTP/1.1" 200' in sidecar_log.read_text() + assert ran and served, f"run_bot did not succeed through the sidecar: {sidecar_log.read_text()[-600:]}" + print("ok run_bot went through the sidecar (its log: POST /run 200)") + + +if __name__ == "__main__": + main("--sidecar" in sys.argv[1:]) diff --git a/world/seed/.gitignore b/world/seed/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..00f2d38d8063d0c6b219c0081e51888063b0c55e --- /dev/null +++ b/world/seed/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +.venv/ diff --git a/world/seed/AGENTS.md b/world/seed/AGENTS.md new file mode 100644 index 0000000000000000000000000000000000000000..a8e0c00f29277e7ebecc6a4df08d19639191efa5 --- /dev/null +++ b/world/seed/AGENTS.md @@ -0,0 +1,7 @@ +# Python chatbot + +Read README.md, STYLE.md and CONTRIBUTING.md before editing or submitting work. Keep the +seed's runtime and input/output interface fixed; put topic and feature logic in bot/modules/. +Compare every change with main using tools/compare.py and judge it by STYLE.md. Submit through +the world's PR tools; another agent must approve the latest change before it can merge. +Continue working until the system tells you to stop. diff --git a/world/seed/CONTRIBUTING.md b/world/seed/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..d340559570258d37f0c9143e890e2dd1f00565b2 --- /dev/null +++ b/world/seed/CONTRIBUTING.md @@ -0,0 +1,83 @@ +# Contributing + +## Choose work + +1. Read your lane's channel and the board, and `list_prs`, before choosing work. Search for + the idea, join an existing thread and claim a focused piece. Ask for help and coordinate + modules and `memory` keys. +2. Prefer work that improves the turns people send most often (STYLE.md, "Who we talk to"), + and general mechanisms that improve many conversations at once over rules for one phrasing + (README.md, "Architecture"). Improving or merging an existing module beats adding a new one + that overlaps it. + +## Make a change + +3. Clone the repository into your private workspace: + `git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`. + Work on a local topic branch from current `main`. Keep notes outside the clone. +4. Keep the runtime, `bot/__main__.py` and the package initializers fixed. Add or edit modules + under `bot/modules/` and the shared parts next to it (README.md, "Interface" and + "Architecture"), with tests under `tests/`. +5. Run `python -m unittest discover -s tests` and talk to the whole bot: + `flock-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`. +6. Compare with main, blind, before you open the PR: + + ```sh + git fetch origin && git worktree add ../base origin/main + python tools/compare.py ../base . --seed + # judge every item by STYLE.md (1, 2 or =), then: + python tools/compare.py --score "" + git worktree remove ../base + ``` + + Open the PR only if head is better more often than it is worse, and no multi-turn + conversation got worse. A change that only adds deck conversations or tests needs no + comparison. A refactor (for example moving modules onto a shared part) may change no reply + at all: show that with `--sample 0` (the whole deck) and "no reply changed". + +## Open a PR + +7. Submit with `flock-tool open_pr --json '{"path":"pybot","branch":"your-topic", + "title":"Your change","description":"..."}'`. The description says what changed and why, + and gives the comparison: the seed, the score line, the "turns answered" line, and one + example it improves. At most two open PRs per agent. +8. New PRs that add a module (a new file in `bot/modules/`) are limited swarm-wide to about + the merge rate (`open_budget`). Fixes, reverts, tests, deck additions, knowledge in + `bot/knowledge/` and changes to existing modules are never limited. An update to your PR is never limited, but a PR + opened without a new module cannot add one later: open a new PR for it. + +## Review + +9. Find PRs that need a reviewer with `list_prs needs_review=true`. Each PR takes a small + number of reviewers per change (`review_full` means it has enough: pick another). +10. Read the diff (`get_pr`), then run your own comparison, on a seed of your choice: + + ```sh + git fetch origin && git -c protocol.version=0 fetch origin refs/pr/42 + git worktree add ../pr-42 FETCH_HEAD && git worktree add ../base origin/main + python tools/compare.py ../base ../pr-42 --seed + git worktree remove ../pr-42 && git worktree remove ../base + ``` + + `run_bot` accepts `pr:42` and returns its exact SHA. +11. Approve when head is better more often than it is worse on your sample and no + multi-turn conversation got worse, or when a refactor changes no reply on the whole deck. + Request changes only with a concrete loss: the deck id and the two replies. Call + `review_pr` with `pr`, the `head_sha` you checked, `verdict` and a comment that gives your + score line. +12. When the author updates the PR, re-review it promptly: a request for changes blocks the + merge until you approve or the diff changes. + +## Merge and revert + +13. Any agent may call `merge_pr` once another agent approved the current change and nobody + requests changes. `merge_pr` rebases the PR onto the current `main` itself. When it reports + a conflict, rebase onto `origin/main` yourself and update the PR; a clean rebase keeps the + approvals. +14. If a merged change makes the bot worse (a comparison of main against the commit before + it shows losses), revert it: `git revert` the merge locally and open a PR. Reverts are + never limited. Then fix the change properly; don't pile a guard on top of it. + +All world and board tools use `flock-tool --json ''`; `flock-tool --list` +shows their parameters. There are no DMs: ask in your lane channel's thread and @mention the +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. diff --git a/world/seed/README.md b/world/seed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b45060bf17b1b11452c0c65ec85aa24aa4c7209a --- /dev/null +++ b/world/seed/README.md @@ -0,0 +1,106 @@ +--- +license: cc-by-4.0 +language: [en] +tags: [chatbot, multi-agent, python] +pretty_name: pybot +--- +# Python Chatbot + +One natural, helpful conversation partner written in standard-library Python, with no +machine learning. People bring it everyday questions and plans, and chat with it over many +turns; it should answer them the way a knowledgeable friend would. STYLE.md defines a good +reply and shows examples. The seed only says `Hello!`: it demonstrates the interface, not +the intended quality. + +Run from this repository's root: + +```sh +python -m bot # talk to it: one reply per line +python -m unittest discover -s tests # the tests +python tools/compare.py ../base . --seed 7 # compare with another checkout (CONTRIBUTING.md) +``` + +## Interface + +For every input line, including an empty line, the bot prints exactly one nonempty reply line +and flushes. Each conversation is a fresh process, with 300 seconds in total. Use only the +Python standard library, with no network or file I/O beyond importing the bot's modules. + +The seed's `bot/__main__.py`, `bot/runtime.py` and `bot/__init__.py`/`bot/modules/__init__.py` +are fixed: the world refuses changes to them. The runtime loads every module in `bot/modules/` by +itself; the shared parts of the bot live in packages next to it ("Architecture"). A module may +define any of these, all optional: + +| name | what it does | +|---|---| +| `PRIORITY` | an integer (default 0): the order in which modules run, highest first | +| `observe(text, memory)` | remember something from the user's line (a name, a plan, the topic); never replies | +| `respond(text, memory)` | propose a reply (a string), or `None` to pass | +| `after(text, reply, memory)` | see the reply that was chosen, e.g. to avoid repeating it | + +Every turn, all modules observe, then all modules propose a reply, each on its own copy of +`memory`. The arbiter (`bot/modules/arbiter.py`, `choose(text, memory, candidates)`) picks one +reply, and only the chosen module's changes to `memory` are kept, so write facts you always +want kept in `observe`. The runtime appends each turn to `memory["turns"]` as +`{"user", "bot", "module"}`: read it, don't change it. `runtime.turn(text, memory)` returns the +reply, the module that gave it and every candidate, for tools and tests. + +Coordinate module names and `memory` keys on the board. Keep the greeting fallback at +PRIORITY -1000. + +## Architecture + +The bot has four parts. Each has a home and an owning lane, and modules build on them instead +of each doing everything itself: + +| part | what it does | where | lane | +|---|---|---|---| +| understanding engine | what the user said and meant: clean text, the kind of line, the topic, what "it" refers to | `bot/understanding/`, stored in `memory["understood"]` by `bot/modules/understand.py` before any module replies | understanding | +| memory store | what the user and the bot have said: the user's facts, the topic, the turns | `bot/memory/` and the `memory` keys below | conversation | +| knowledge base | facts about the world, as data keyed by meaning | `bot/knowledge/`, one module per domain | answers | +| response composer | what to do this turn, and how to phrase it | the modules' `respond`, `bot/modules/arbiter.py`, `bot/compose/` | routing (every lane writes replies) | + +Shared `memory` keys (add new ones here): + +| key | what | written by | +|---|---|---| +| `memory["turns"]` | every earlier turn: `{"user", "bot", "module"}` | the runtime | +| `memory["understood"]` | this turn's reading of the line: `text`, `clean`, `words`, `kind` | `bot/modules/understand.py` | +| `memory["user"]` | facts the user told about themselves, e.g. `{"name": "Sam"}` (`bot.memory.user`) | the conversation lane | +| `memory["topic"]` | what the conversation is about now | the conversation lane | + +The project runs for a long time and will produce a lot of code. Prefer general mechanisms that +improve many conversations at once (better understanding, a richer knowledge base, a better +composer) over rules or content written for one phrasing. When a reply falls short, find which +part failed and improve that part. + +## Routing + +Many modules can propose a reply to the same line; the arbiter decides which one the user +gets. The seed's arbiter takes the highest PRIORITY. Raising a module's PRIORITY to win more +turns takes them from other modules, so don't: changes to the arbiter and to priorities belong +to the routing lane, and need comparison evidence like any other change. + +## The deck and comparisons + +`deck/` holds realistic conversations, one JSON object per line: +`{"id", "area", "turns": [user lines]}`. `deck/single.jsonl` has one-line requests and +`deck/multi.jsonl` has conversations of several turns. The deck is how the swarm sees the +whole bot: add conversations people would really have, across all everyday topics, and keep +it free of lines written to make one module look good. + +`tools/compare.py` runs two checkouts of the bot on a random sample of the deck and shows each +changed reply side by side, in random order. You judge each one by STYLE.md, then score your +verdicts against the key. Every PR shows this evidence and every reviewer checks it on their +own sample; CONTRIBUTING.md has the steps. + +## Layout + +| path | what | +|---|---| +| `bot/` | the bot: the fixed runtime, `bot/modules/` and the shared parts ("Architecture") | +| `deck/` | the conversations comparisons are run on | +| `tools/compare.py` | the comparison tool | +| `tests/` | unit tests; add one with every module | +| `STYLE.md` | what a good reply is, with examples | +| `CONTRIBUTING.md` | how to propose, review, merge and revert changes | diff --git a/world/seed/STYLE.md b/world/seed/STYLE.md new file mode 100644 index 0000000000000000000000000000000000000000..77af6a708e874db413885e2fff9e7156c6e92151 --- /dev/null +++ b/world/seed/STYLE.md @@ -0,0 +1,175 @@ +# What a good reply is + +This is the bar for every reply the bot gives, and for every comparison you judge with +`tools/compare.py`. When two replies differ, ask one question: + +> Which reply would you rather get from a knowledgeable friend who is trying to help you? + +## Who we talk to + +Ordinary people, in their own words. Most of them bring a bit of context and want something +practical: how to do something, why something happens, what to choose, what to watch or read +or cook, what to say, what to do next. Some just want to chat, share news or let off steam. +Many keep talking for several turns: they add details, follow up, change their mind or come +back to something they said earlier. They type the way people type: typos, chat-speak ("u", +"thx", "idk"), no punctuation, one-word replies ("ok", "lol", "nah"), sudden changes of topic, +and now and then a question about the bot itself. + +The bot's value is answering those people well, across as many everyday topics as possible, +over one turn or twenty. Work on the turns people send most often first. + +## Helpful + +- **Answer in the first sentence.** Then add what makes the answer useful. Don't open with + filler, praise for the question, or a restatement of it. +- **Be concrete.** Names, numbers, times, steps, two or three options with a pick. "Boil it + for 6 minutes" beats "it depends on how you like it". +- **Match the length to the ask.** Most replies are one to three sentences. A list only when + someone asks for steps or options, and then a short one. +- **Answer the question they meant**, even if they mis-asked it. If a request is truly + unclear, give what you can and ask one short question. +- **Stay on their topic.** A reply that is fluent but about something else is a failure, even + if it is clever. So is a stock line that would fit any message. + +## Honest + +- Don't make up facts. A confident wrong answer is worse than a short honest one. +- When the bot doesn't know, say so in a few words and still help: what it does know, or how + to find out. "I don't know" alone is not a reply. +- The bot may have opinions and tastes ("I'd pick the train"), but it doesn't invent a life + story in place of an answer. Talk about itself only when asked about itself. +- Asked what it is, it answers honestly and briefly (a chatbot, here to help and chat), then + gets back to the conversation. + +## Careful, in proportion + +- When someone may be in real danger (a medical emergency, self-harm, abuse), say the + important thing plainly and point to real help. +- Ordinary words that only sound alarming ("this deadline is killing me", "I cut my finger") + are not emergencies. Treating them as one is a bug: answer the actual message. +- No harmful instructions, no insults, no lectures. + +## A conversation, not a series of one-offs + +- Remember what the user told you (names, plans, pets, constraints) and use it when it helps. +- Read follow-ups in context: "how long will it take?" means the thing you were just + discussing. "it", "that", "there" refer back. +- When the user corrects themselves, go with the correction. +- Small talk is welcome. Reply warmly and briefly, and keep the thread going sometimes, but + don't end every reply with a question. +- Short replies ("ok", "lol", "nah", "thx") answer the bot's last turn: read them in that + light, and reply in kind. +- Vary the wording. Never answer the same way twice in a row. +- Not a therapist: don't turn their words back into a question ("Why do you feel tired?"), and + never "Tell me more about X" as a stock reply. + +## Judging a comparison + +`tools/compare.py` shows the replies of two versions of the bot, in random order. For each +item, pick the reply you would rather get (1 or 2), or `=` if neither is better. In order: + +1. A reply that answers beats one that doesn't (a deflection, a stock line, the wrong topic). +2. Correct beats wrong; specific beats vague. +3. If both answer equally well, the shorter, more natural one wins. +4. For a multi-turn conversation, judge the whole conversation: does the bot keep track, + follow up sensibly and stay on topic? + +## Examples + +These show the style, not a script to copy. The bot should handle the same kind of message in +its own words. + +**A practical question** + +> **User:** My jeans shrank in the wash. Can I stretch them back? +> +> **Bot:** Often, yes: soak them in lukewarm water with a spoonful of hair conditioner, then +> pull them gently into shape and let them dry flat. Denim with some stretch in it bounces back +> best. + +**A recommendation** + +> **User:** I need a new book for the holiday. I liked Gone Girl. +> +> **Bot:** Try *The Silent Patient* by Alex Michaelides: short chapters, an unreliable +> narrator and a twist you won't see coming. If you want something longer, Tana French's +> *In the Woods* is excellent. + +**An explanation** + +> **User:** Why do onions make you cry? +> +> **Bot:** Cutting an onion breaks its cells and releases a gas that irritates your eyes, so +> they make tears to wash it away. A sharp knife and a chilled onion release less of it. + +**Not knowing, honestly** + +> **User:** What time does the post office on Hill Road close today? +> +> **Bot:** I can't check live opening hours, sorry. Search for the branch online: its listing +> on a map app usually shows today's hours, holidays included. + +**Something that sounds alarming but isn't** + +> **User:** This spreadsheet is killing me. +> +> **Bot:** Spreadsheets do that. What's it fighting you on, formulas or formatting? + +**Feelings** + +> **User:** I didn't get the flat we applied for. We were so sure. +> +> **Bot:** That's really disappointing, especially when you'd already pictured living there. +> It's worth asking the agent whether anything similar is coming up; they often know before +> listings go live. + +**Small talk** + +> **User:** Morning! Finally Friday. +> +> **Bot:** Morning! The best day of the week. Anything fun planned for the weekend? + +**A conversation that keeps track** + +> **User:** I'm Jess, and I'm planning a picnic for my daughter's 7th birthday. +> +> **Bot:** Lovely idea, Jess! A park with some shade and a toilet nearby makes life easier with +> a group of seven-year-olds. +> +> **User:** About ten kids are coming. What food should I bring? +> +> **Bot:** For ten kids, keep it to finger food: little sandwiches, sausage rolls, cut fruit, +> crisps and some cupcakes instead of a big cake. Bring more water than you think. +> +> **User:** Any games? +> +> **Bot:** A treasure hunt is perfect for that age: hide ten small prizes so everyone finds one. +> Sack races and musical statues work well on grass too. +> +> **User:** Thanks! What did I say my name was? +> +> **Bot:** Jess. I hope your daughter has a brilliant birthday! + +**A correction** + +> **User:** What's a good day trip from Manchester? +> +> **Bot:** The Peak District is under an hour away: Castleton has caves, a ruined castle and +> great walks. +> +> **User:** Sorry, I meant from Birmingham. +> +> **Bot:** From Birmingham, Warwick Castle and Stratford-upon-Avon are both about 40 minutes +> away and easy to combine in one day. + +**A follow-up that depends on the last turn** + +> **User:** How long should I cook a 2kg chicken? +> +> **Bot:** About 1 hour 40 minutes at 190°C (170°C fan): 20 minutes per 500g plus 20, until +> the juices run clear. Rest it for 15 minutes before carving. +> +> **User:** And if I stuff it? +> +> **Bot:** Weigh it with the stuffing and use the same rule, so usually 15 to 20 minutes more. +> Check that the middle of the stuffing is piping hot too. diff --git a/world/seed/bot/__init__.py b/world/seed/bot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..558f72747c4bea355403897b05d6698cd9a471d3 --- /dev/null +++ b/world/seed/bot/__init__.py @@ -0,0 +1 @@ +"""A standard-library chatbot with a fixed input/output interface.""" diff --git a/world/seed/bot/__main__.py b/world/seed/bot/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..2c918145cc7deff38b7aea2471bf1f88d84e7094 --- /dev/null +++ b/world/seed/bot/__main__.py @@ -0,0 +1,19 @@ +"""Fixed interface: one reply per input line. Put bot logic in bot/modules/.""" +import sys + +from .runtime import reply + + +def main(): + memory = {} + for line in sys.stdin: + try: + answer = reply(line.rstrip("\r\n"), memory) + answer = " ".join(str(answer).split()) or "Hello!" + except Exception: # noqa: BLE001 - preserve the bot interface + answer = "Hello!" + print(answer, flush=True) + + +if __name__ == "__main__": + main() diff --git a/world/seed/bot/compose/__init__.py b/world/seed/bot/compose/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c560bf1fe18e83331d757ac3aaa6a8bfc254007 --- /dev/null +++ b/world/seed/bot/compose/__init__.py @@ -0,0 +1,12 @@ +"""Phrasing helpers for the response composer. The routing lane owns the composer: what to do +this turn (bot/modules/arbiter.py chooses among the modules' replies) and how it is phrased. +""" +import random + + +def pick(options, memory): + """One of options, avoiding any reply the bot gave in its last five turns.""" + turns = memory.get("turns") or [] + recent = {t.get("bot") for t in turns[-5:]} + fresh = [o for o in options if o not in recent] or list(options) + return random.Random(len(turns)).choice(fresh) diff --git a/world/seed/bot/knowledge/__init__.py b/world/seed/bot/knowledge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7755ee5a7c559d3a77eba0c509ca4d142c7e8ba --- /dev/null +++ b/world/seed/bot/knowledge/__init__.py @@ -0,0 +1,8 @@ +"""The knowledge base: facts about the world, kept as data. The answers lane owns it. + +One module per domain (bot/knowledge/cooking.py, bot/knowledge/travel.py, ...) holds plain data +(dicts, lists, tuples) keyed by meaning (a dish, a city, a symptom), not by how a question is +worded, and small functions to look it up. Answer modules in bot/modules/ find what was asked +in memory["understood"], look it up here and compose the reply. The bot cannot read files, so +the data lives in .py files. +""" diff --git a/world/seed/bot/memory/__init__.py b/world/seed/bot/memory/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..994d7324eac63185f0bb7aa105b3ecf7e8e9b835 --- /dev/null +++ b/world/seed/bot/memory/__init__.py @@ -0,0 +1,17 @@ +"""The memory store: what the user and the bot have said. The conversation lane owns it. + +Shared keys of the conversation's memory dict (list new ones in README.md): +- memory["turns"]: every earlier turn as {"user", "bot", "module"}; the runtime writes it. +- memory["understood"]: this turn's reading of the user's line (bot/understanding). +- memory["user"]: facts the user told about themselves, e.g. {"name": "Sam", "city": "Leeds"}. +- memory["topic"]: what the conversation is about now. +Write facts in observe(), so they are kept whichever reply is chosen. +""" + + +def user(memory): + """The user's facts (a dict), created on first use.""" + facts = memory.get("user") + if not isinstance(facts, dict): + facts = memory["user"] = {} + return facts diff --git a/world/seed/bot/modules/__init__.py b/world/seed/bot/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77d842313328843db17d397fa86b09cd308e2763 --- /dev/null +++ b/world/seed/bot/modules/__init__.py @@ -0,0 +1 @@ +"""Add topic or feature modules here; see CONTRIBUTING.md.""" diff --git a/world/seed/bot/modules/arbiter.py b/world/seed/bot/modules/arbiter.py new file mode 100644 index 0000000000000000000000000000000000000000..53d529e7cf9cbee08d352fc1452bc601ac34b6a7 --- /dev/null +++ b/world/seed/bot/modules/arbiter.py @@ -0,0 +1,18 @@ +"""Chooses each turn's reply among the modules' candidates. The routing lane owns this file. + +The seed rule: the highest PRIORITY wins (candidates arrive in that order), and a fallback +(PRIORITY below 0) answers only when nothing else does. Improve the rule with +tools/compare.py evidence (README.md, "Routing"); it may read memory but not change it. +""" + + +def choose(text, memory, candidates): + """Return the index of the chosen candidate. + + candidates: [{"module": name, "priority": PRIORITY, "reply": text}], highest PRIORITY + first. memory["turns"] holds the earlier turns of the conversation. + """ + for index, candidate in enumerate(candidates): + if candidate["priority"] >= 0: + return index + return 0 diff --git a/world/seed/bot/modules/greeting.py b/world/seed/bot/modules/greeting.py new file mode 100644 index 0000000000000000000000000000000000000000..fc6660d33cfce631d8ebe6b8f3cdac7c508624e4 --- /dev/null +++ b/world/seed/bot/modules/greeting.py @@ -0,0 +1,6 @@ +"""The seed's fallback: it only answers when no other module does.""" +PRIORITY = -1000 + + +def respond(text, memory): + return "Hello!" diff --git a/world/seed/bot/modules/understand.py b/world/seed/bot/modules/understand.py new file mode 100644 index 0000000000000000000000000000000000000000..1c58c869b2b297307d7a3fa7697bbd4f76d5ca36 --- /dev/null +++ b/world/seed/bot/modules/understand.py @@ -0,0 +1,8 @@ +"""Runs the understanding engine (bot/understanding) before any module proposes a reply.""" +from ..understanding import understand + +PRIORITY = 10000 # observes first, so every other module reads memory["understood"] + + +def observe(text, memory): + memory["understood"] = understand(text, memory) diff --git a/world/seed/bot/runtime.py b/world/seed/bot/runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..3b73d5dc6d0e7e9790f39e2f9456437d2fa8fc99 --- /dev/null +++ b/world/seed/bot/runtime.py @@ -0,0 +1,120 @@ +"""Fixed module interface. Edit bot/modules/, never this file. + +Every turn runs the modules in bot/modules/ in descending PRIORITY (default 0), then by +filename, in three phases: + +1. observe(text, memory): remember things (a name, a fact, the topic). It never replies. +2. respond(text, memory): propose a reply (a string) or pass (None). Every module proposes; + each one works on its own copy of memory, so a reply that is not chosen leaves no trace. +3. choose(text, memory, candidates) in bot/modules/arbiter.py picks one candidate, and the + chosen module's copy of memory becomes the conversation's memory. A candidate is + {"module": name, "priority": PRIORITY, "reply": text}; they arrive in the order above. + Without a working arbiter, the first candidate (the highest PRIORITY) is chosen. + +Then after(text, reply, memory) runs in every module that defines it, and the runtime appends +{"user": text, "bot": reply, "module": name} to memory["turns"] (read it, never change it). +A module that fails is skipped; a turn never fails. +""" +import copy +import importlib +import pkgutil + +from . import modules + +ARBITER = "arbiter" +FALLBACK = "Hello!" + + +def load_modules(): + """[(name, priority, module)], highest PRIORITY first, then by filename.""" + loaded = [] + for entry in pkgutil.iter_modules(modules.__path__): + try: + module = importlib.import_module(f"{modules.__name__}.{entry.name}") + except Exception: # noqa: BLE001, S112 - preserve the bot interface + continue + priority = getattr(module, "PRIORITY", 0) + if isinstance(priority, bool) or not isinstance(priority, (int, float)): + priority = 0 + loaded.append((priority, entry.name, module)) + loaded.sort(key=lambda item: (-item[0], item[1])) + return [(name, priority, module) for priority, name, module in loaded] + + +def _hooks(name): + return [(module_name, priority, getattr(module, name)) for module_name, priority, module in _MODULES + if callable(getattr(module, name, None))] + + +_MODULES = load_modules() +_OBSERVERS = _hooks("observe") +_HANDLERS = _hooks("respond") +_AFTER = _hooks("after") +_ARBITER = next((getattr(module, "choose", None) for name, _, module in _MODULES if name == ARBITER), None) + + +def _copy(memory): + """A module's own copy of memory. memory["turns"] is shared: only the runtime writes it.""" + try: + return {key: value if key == "turns" else copy.deepcopy(value) for key, value in memory.items()} + except Exception: # noqa: BLE001 - a value that cannot be copied: share memory instead + return memory + + +def _choose(text, memory, candidates): + """The arbiter's pick, as an index into candidates; 0 when it fails or returns nonsense.""" + if _ARBITER is None or len(candidates) < 2: + return 0 + views = [dict(c) for c in candidates] + try: + picked = _ARBITER(text, memory, views) + except Exception: # noqa: BLE001 - preserve the bot interface + return 0 + if isinstance(picked, int) and not isinstance(picked, bool) and 0 <= picked < len(views): + return picked + if isinstance(picked, dict): + for i, view in enumerate(views): + if view is picked or view["module"] == picked.get("module"): + return i + return 0 + + +def turn(text, memory): + """One turn: {"reply", "module", "candidates"}. Updates memory in place.""" + for _, _, observe in _OBSERVERS: + try: + observe(text, memory) + except Exception: # noqa: BLE001, S112 - preserve the bot interface + continue + candidates, copies = [], [] + for name, priority, respond in _HANDLERS: + mine = _copy(memory) + try: + answer = respond(text, mine) + except Exception: # noqa: BLE001, S112 - preserve the bot interface + continue + if isinstance(answer, str) and answer.strip(): + candidates.append({"module": name, "priority": priority, "reply": answer}) + copies.append(mine) + if candidates: + index = _choose(text, memory, candidates) + reply, module = candidates[index]["reply"], candidates[index]["module"] + if copies[index] is not memory: + memory.clear() + memory.update(copies[index]) + else: + reply, module = FALLBACK, None + for _, _, after in _AFTER: + try: + after(text, reply, memory) + except Exception: # noqa: BLE001, S112 - preserve the bot interface + continue + turns = memory.get("turns") + if not isinstance(turns, list): + turns = memory["turns"] = [] + turns.append({"user": text, "bot": reply, "module": module}) + return {"reply": reply, "module": module, "candidates": candidates} + + +def reply(text, memory): + return turn(text, memory)["reply"] diff --git a/world/seed/bot/understanding/__init__.py b/world/seed/bot/understanding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a079ce23f993a507cab5916e5732646b0ec5b9 --- /dev/null +++ b/world/seed/bot/understanding/__init__.py @@ -0,0 +1,35 @@ +"""The understanding engine: what the user said and meant. The understanding lane owns it. + +bot/modules/understand.py stores understand(text, memory) in memory["understood"] before any +module proposes a reply, so every module reads one reading of the line instead of matching its +own keywords. Grow it with general mechanisms (spelling and chat-speak, what kind of line it +is, the topic and the things named, what "it" or "that" refers to). Keep the keys below +stable: add new ones and list them in README.md. +""" +import re + +WORD = re.compile(r"[a-z0-9]+(?:'[a-z]+)?") +GREETINGS = ("hi", "hello", "hey", "hiya", "morning", "good morning", "good afternoon", + "good evening", "evening") +THANKS = ("thanks", "thank you", "thx", "cheers", "ty") +QUESTION_STARTS = {"what", "why", "how", "when", "where", "who", "which", "can", "could", "should", + "would", "is", "are", "do", "does", "did", "will", "have", "has"} + + +def understand(text, memory): + """{"text": the line, "clean": lower case with single spaces, "words": its words, + "kind": "empty" | "greeting" | "thanks" | "question" | "statement"}.""" + clean = " ".join(text.lower().split()) + words = WORD.findall(clean) + bare = " ".join(words) + if not words: + kind = "empty" + elif len(words) <= 4 and any(bare == g or bare.startswith(g + " ") for g in GREETINGS): + kind = "greeting" + elif any(bare == t or bare.startswith(t + " ") for t in THANKS): + kind = "thanks" + elif clean.endswith("?") or words[0] in QUESTION_STARTS: + kind = "question" + else: + kind = "statement" + return {"text": text, "clean": clean, "words": words, "kind": kind} diff --git a/world/seed/deck/multi.jsonl b/world/seed/deck/multi.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..236323c6a140710efe5b49da1bf10aa89b19d730 --- /dev/null +++ b/world/seed/deck/multi.jsonl @@ -0,0 +1,40 @@ +{"id": "multi-001", "area": "cooking", "turns": ["I want to bake a birthday cake for my son this weekend.", "He loves chocolate but he's allergic to nuts.", "How long will it take, start to finish?", "Great, and can I make it the day before?"]} +{"id": "multi-002", "area": "cooking", "turns": ["What can I cook tonight with chicken thighs, a lemon and some potatoes?", "Sounds good. What temperature should the oven be?", "I don't have fresh rosemary, only dried. Is that OK?"]} +{"id": "multi-003", "area": "health", "turns": ["I've had a cold for five days now.", "My throat is the worst part. What helps?", "Should I see a doctor if it's not better by Monday?"]} +{"id": "multi-004", "area": "fitness", "turns": ["I'm training for my first 10k in October.", "Right now I can run about 3k without stopping.", "How many times a week should I run?", "And what should I eat the morning of the race?"]} +{"id": "multi-005", "area": "money", "turns": ["My name is Priya and I've just got my first proper job.", "I want to start saving but I've never had a budget.", "What's a simple way to split my salary?", "Thanks! By the way, what's my name?"]} +{"id": "multi-006", "area": "money", "turns": ["I'm thinking of buying a used car.", "My budget is about 6,000 pounds.", "What should I ask the seller?", "And is it worth paying for an inspection?"]} +{"id": "multi-007", "area": "work", "turns": ["I have a performance review tomorrow.", "I think it went badly this year because a big project slipped.", "How do I talk about that without sounding defensive?", "OK. What should I ask for at the end?"]} +{"id": "multi-008", "area": "work", "turns": ["My manager asked me to give a five-minute talk to the team.", "It's about the new booking system we rolled out.", "I get really nervous speaking in front of people.", "Any tricks for the first thirty seconds?"]} +{"id": "multi-009", "area": "school-and-study", "turns": ["My daughter has a science project on volcanoes.", "She's nine.", "Can you explain how a volcano erupts in a way she'd get?", "What could she build for the project?"]} +{"id": "multi-010", "area": "school-and-study", "turns": ["Can you explain what photosynthesis is?", "So where does the oxygen come from?", "And why do plants need sunlight for it?"]} +{"id": "multi-011", "area": "travel", "turns": ["We're planning a weekend in Edinburgh in December.", "It's me, my partner and our dog.", "What should we pack?", "Are there dog-friendly places to eat near the old town?"]} +{"id": "multi-012", "area": "travel", "turns": ["I've never been on a plane before and I fly to Spain next month.", "What happens at security?", "Can I take my own sandwiches?", "Thanks, I feel a bit better now."]} +{"id": "multi-013", "area": "technology", "turns": ["My laptop has started making a loud fan noise.", "It's about four years old.", "What can I do about it myself?", "If that doesn't work, is it worth repairing or should I replace it?"]} +{"id": "multi-014", "area": "technology", "turns": ["I want to set up a family group chat.", "My mum is 78 and not very good with phones.", "Which app would be easiest for her?", "How do I add her to it?"]} +{"id": "multi-015", "area": "home", "turns": ["We're moving into our first flat on Saturday.", "We don't have a car.", "What's the cheapest way to move a sofa and a bed?", "What should we do on the first night there?"]} +{"id": "multi-016", "area": "home", "turns": ["My radiator is cold at the top but hot at the bottom.", "How do I bleed it?", "Do I need to turn the heating off first?"]} +{"id": "multi-017", "area": "garden", "turns": ["I've just got an allotment.", "It's completely overgrown with weeds.", "Where do I even start?", "What could I plant this month?"]} +{"id": "multi-018", "area": "pets", "turns": ["We adopted a rescue dog called Biscuit last week.", "He's scared of men and hides under the table.", "How can my husband get him to trust him?", "How long does that usually take with a dog like Biscuit?"]} +{"id": "multi-019", "area": "pets", "turns": ["My cat has stopped eating her usual food.", "She's 12.", "Should I be worried?"]} +{"id": "multi-020", "area": "family", "turns": ["My twins are turning six next month.", "They want a joint party but they like completely different things.", "One loves dinosaurs and the other loves space.", "Could you suggest a theme that works for both?"]} +{"id": "multi-021", "area": "friends", "turns": ["My friend Sam and I had an argument about money.", "I lent him 200 pounds in March and he hasn't mentioned it since.", "How do I bring it up without ruining the friendship?", "What if he says he can't pay it back yet?"]} +{"id": "multi-022", "area": "entertainment", "turns": ["I'm looking for a TV series to watch with my partner.", "We both liked Line of Duty.", "We're not into anything too gory though.", "Thanks. Which one should we start with tonight?"]} +{"id": "multi-023", "area": "entertainment", "turns": ["What's your favourite book?", "Why that one?", "What would you recommend for someone who doesn't read much?"]} +{"id": "multi-024", "area": "sport", "turns": ["I've been asked to coach my son's under-8s football team.", "I've never coached before.", "What should the first training session look like?", "How do I keep them from all chasing the ball at once?"]} +{"id": "multi-025", "area": "feelings", "turns": ["I didn't get the job I interviewed for last week.", "I really thought I had it.", "I don't know what to do next.", "Thanks. I think I'll ask them for feedback."]} +{"id": "multi-026", "area": "feelings", "turns": ["I'm nervous about a dentist appointment tomorrow.", "I haven't been in about six years.", "What will they probably do?"]} +{"id": "multi-027", "area": "small-talk", "turns": ["Hey there!", "Not much, just got back from a walk by the river.", "Saw a heron, which was nice. Do you like birds?", "What's one you'd love to see?"]} +{"id": "multi-028", "area": "small-talk", "turns": ["Hi, I'm Tom.", "I'm a bus driver in Leeds.", "It's been a long week.", "What do you think I should do this weekend to unwind?", "Good idea. What did I say my job was again?"]} +{"id": "multi-029", "area": "small-talk", "turns": ["Morning!", "I'm on my second coffee already.", "Do you have any plans today?", "Ha, fair enough. Talk later!"]} +{"id": "multi-030", "area": "opinions", "turns": ["Do you think it's worth learning a musical instrument as an adult?", "I'm 45 and I've always wanted to play the piano.", "How long before I could play a simple song?"]} +{"id": "multi-031", "area": "creative", "turns": ["I'm writing a speech for my sister's wedding.", "She's a vet and her husband is a firefighter.", "Can you suggest a funny opening line?", "Can you make it a bit warmer and less jokey?"]} +{"id": "multi-032", "area": "learning", "turns": ["I want to learn Spanish before a trip in six months.", "I can study about 20 minutes a day.", "What's the best way to spend that time?", "How do you say 'where is the train station'?"]} +{"id": "multi-033", "area": "learning", "turns": ["What's the difference between a virus and bacteria?", "So do antibiotics work on colds?", "Then what actually helps a cold?"]} +{"id": "multi-034", "area": "corrections", "turns": ["I'm planning a trip to Rome in July.", "Sorry, I meant Florence, not Rome.", "What should I see there in two days?"]} +{"id": "multi-035", "area": "corrections", "turns": ["Can you recommend a recipe for dinner?", "Something without meat, please.", "And quick, I've only got 20 minutes."]} +{"id": "multi-036", "area": "messy-chat", "turns": ["hey", "not much u?", "lol same", "anyway what should i make for dinner, ive got eggs and spinach", "ok sounds good", "thx"]} +{"id": "multi-037", "area": "messy-chat", "turns": ["I'm off to Japan in March!", "Tokyo and Kyoto", "wait is that cherry blossom season", "ok and do i need a rail pass?", "cool. btw which city did i say first?"]} +{"id": "multi-038", "area": "messy-chat", "turns": ["Can you help me pick a laptop?", "its for uni, im studying architecture", "under 1000", "actually never mind, how do I boil an egg?", "ok back to the laptop, which would you get?"]} +{"id": "multi-039", "area": "messy-chat", "turns": ["Are you a bot?", "ha fair. what can you help with?", "ok give me a quick dinner idea", "nah something without cheese"]} +{"id": "multi-040", "area": "messy-chat", "turns": ["my cat knocked my phone into the bath", "it wont turn on now", "i put it in rice", "how long should i leave it"]} diff --git a/world/seed/deck/single.jsonl b/world/seed/deck/single.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a16cdb66e9ac4eac92d2c0ced7cfb62a6849f5e8 --- /dev/null +++ b/world/seed/deck/single.jsonl @@ -0,0 +1,107 @@ +{"id": "single-001", "area": "cooking", "turns": ["I have leftover rice from last night. What can I make with it for lunch?"]} +{"id": "single-002", "area": "cooking", "turns": ["My scrambled eggs always come out rubbery. What am I doing wrong?"]} +{"id": "single-003", "area": "cooking", "turns": ["How long should I boil an egg if I want the yolk still a bit runny?"]} +{"id": "single-004", "area": "cooking", "turns": ["I'm cooking for a friend who is vegan. Any easy main course ideas?"]} +{"id": "single-005", "area": "food-and-drink", "turns": ["What's the difference between baking soda and baking powder?"]} +{"id": "single-006", "area": "food-and-drink", "turns": ["I'm trying to drink less coffee. What could I have in the afternoon instead?"]} +{"id": "single-007", "area": "food-and-drink", "turns": ["Is it safe to eat cooked chicken that was left out overnight?"]} +{"id": "single-008", "area": "food-and-drink", "turns": ["Which cheeses go well on a cheese board for six people?"]} +{"id": "single-009", "area": "health", "turns": ["I get headaches most afternoons at work. What could be causing them?"]} +{"id": "single-010", "area": "health", "turns": ["How much water should an adult drink in a day?"]} +{"id": "single-011", "area": "health", "turns": ["I cut my finger chopping onions and it won't stop bleeding. What should I do?"]} +{"id": "single-012", "area": "health", "turns": ["My eyes feel tired after a day at the screen. Anything that helps?"]} +{"id": "single-013", "area": "fitness", "turns": ["I want to start running but I get out of breath after two minutes. How should I begin?"]} +{"id": "single-014", "area": "fitness", "turns": ["What's a good stretch for a stiff lower back after sitting all day?"]} +{"id": "single-015", "area": "fitness", "turns": ["Is it better to work out in the morning or the evening?"]} +{"id": "single-016", "area": "fitness", "turns": ["I only have 20 minutes a day. What kind of workout gets the most out of that?"]} +{"id": "single-017", "area": "sleep", "turns": ["My toddler wakes up at 5am every day. Is there a way to shift that later?"]} +{"id": "single-018", "area": "sleep", "turns": ["I keep waking up at 3am and can't get back to sleep. Any advice?"]} +{"id": "single-019", "area": "sleep", "turns": ["Is it bad to sleep with the TV on?"]} +{"id": "single-020", "area": "money", "turns": ["I want to save for a holiday next summer. How should I go about it on a small salary?"]} +{"id": "single-021", "area": "money", "turns": ["What's the difference between a credit card and a debit card?"]} +{"id": "single-022", "area": "money", "turns": ["My energy bills have gone up a lot. What are some quick ways to cut them?"]} +{"id": "single-023", "area": "money", "turns": ["Is it worth paying off a small loan early?"]} +{"id": "single-024", "area": "work", "turns": ["I have a job interview on Thursday for an office manager role. What questions should I prepare for?"]} +{"id": "single-025", "area": "work", "turns": ["How do I politely tell my boss I have too much on my plate?"]} +{"id": "single-026", "area": "work", "turns": ["My colleague keeps taking credit for my ideas in meetings. How should I handle it?"]} +{"id": "single-027", "area": "work", "turns": ["What should I put in a two-line bio for a conference badge? I'm a nurse."]} +{"id": "single-028", "area": "school-and-study", "turns": ["I have a history exam in two weeks and I keep putting off revising. How do I get started?"]} +{"id": "single-029", "area": "school-and-study", "turns": ["What's a good way to remember vocabulary for a French test?"]} +{"id": "single-030", "area": "school-and-study", "turns": ["My son is struggling with fractions. How can I explain them simply?"]} +{"id": "single-031", "area": "school-and-study", "turns": ["How do I write a good opening sentence for an essay?"]} +{"id": "single-032", "area": "science", "turns": ["Why is the sky blue?"]} +{"id": "single-033", "area": "science", "turns": ["How do vaccines teach the body to fight a disease?"]} +{"id": "single-034", "area": "science", "turns": ["What's the difference between weather and climate?"]} +{"id": "single-035", "area": "science", "turns": ["Why does ice float on water?"]} +{"id": "single-036", "area": "science", "turns": ["How do plants make their food?"]} +{"id": "single-037", "area": "history", "turns": ["Who built the pyramids of Giza, and roughly when?"]} +{"id": "single-038", "area": "history", "turns": ["What was the Industrial Revolution in a nutshell?"]} +{"id": "single-039", "area": "history", "turns": ["Why did the Roman Empire split into east and west?"]} +{"id": "single-040", "area": "history", "turns": ["When did people first land on the Moon?"]} +{"id": "single-041", "area": "geography-and-travel", "turns": ["I'm going to Lisbon for three days in May. What shouldn't I miss?"]} +{"id": "single-042", "area": "geography-and-travel", "turns": ["What's the best way to get over jet lag after a long flight east?"]} +{"id": "single-043", "area": "geography-and-travel", "turns": ["What's the capital of Australia? I always mix it up with Sydney."]} +{"id": "single-044", "area": "geography-and-travel", "turns": ["We're driving through France with two kids. Any tips for a long car journey?"]} +{"id": "single-045", "area": "technology", "turns": ["My phone battery drains really fast lately. What can I check?"]} +{"id": "single-046", "area": "technology", "turns": ["What's a password manager and should I use one?"]} +{"id": "single-047", "area": "technology", "turns": ["How do I take a screenshot on a Windows laptop?"]} +{"id": "single-048", "area": "technology", "turns": ["My Wi-Fi keeps dropping in the bedroom. How can I improve the signal?"]} +{"id": "single-049", "area": "home-and-diy", "turns": ["There's mould on my bathroom ceiling. How do I get rid of it and stop it coming back?"]} +{"id": "single-050", "area": "home-and-diy", "turns": ["How do I unblock a slow kitchen sink without calling a plumber?"]} +{"id": "single-051", "area": "home-and-diy", "turns": ["I want to paint my living room. What do I need besides paint?"]} +{"id": "single-052", "area": "home-and-diy", "turns": ["What's the easiest way to get red wine out of a carpet?"]} +{"id": "single-053", "area": "garden-and-plants", "turns": ["The leaves on my basil plant are turning yellow. What's wrong with it?"]} +{"id": "single-054", "area": "garden-and-plants", "turns": ["What vegetables are easy to grow on a balcony?"]} +{"id": "single-055", "area": "garden-and-plants", "turns": ["When should I plant tulip bulbs?"]} +{"id": "single-056", "area": "pets", "turns": ["We're getting a kitten next week. What do we need to buy?"]} +{"id": "single-057", "area": "pets", "turns": ["My dog pulls on the lead all the time. How do I train him out of it?"]} +{"id": "single-058", "area": "pets", "turns": ["Is chocolate really dangerous for dogs?"]} +{"id": "single-059", "area": "pets", "turns": ["How often should I clean my goldfish tank?"]} +{"id": "single-060", "area": "family-and-parenting", "turns": ["My daughter is starting secondary school and she's nervous. How can I help her settle in?"]} +{"id": "single-061", "area": "family-and-parenting", "turns": ["What are some fun things to do with kids on a rainy Saturday?"]} +{"id": "single-062", "area": "family-and-parenting", "turns": ["My parents are visiting for a week and our flat is small. Any tips to keep everyone sane?"]} +{"id": "single-063", "area": "friends-and-relationships", "turns": ["My best friend forgot my birthday. Should I say something?"]} +{"id": "single-064", "area": "friends-and-relationships", "turns": ["I just moved to a new city and don't know anyone. How do people make friends as adults?"]} +{"id": "single-065", "area": "friends-and-relationships", "turns": ["What's a thoughtful anniversary gift that doesn't cost much?"]} +{"id": "single-066", "area": "shopping", "turns": ["I need a new laptop mainly for writing and video calls. What should I look for?"]} +{"id": "single-067", "area": "shopping", "turns": ["Are expensive running shoes actually worth it?"]} +{"id": "single-068", "area": "shopping", "turns": ["What should I check before buying a second-hand bike?"]} +{"id": "single-069", "area": "entertainment", "turns": ["Can you recommend a funny film for a family night? The kids are 8 and 11."]} +{"id": "single-070", "area": "entertainment", "turns": ["I loved The Martian. What should I read next?"]} +{"id": "single-071", "area": "entertainment", "turns": ["What's a good board game for four adults who don't like long rules?"]} +{"id": "single-072", "area": "entertainment", "turns": ["I need a new podcast for my commute. I like history and true stories."]} +{"id": "single-073", "area": "sport", "turns": ["How does the offside rule work in football?"]} +{"id": "single-074", "area": "sport", "turns": ["I want to watch my first cricket match. What should I know?"]} +{"id": "single-075", "area": "sport", "turns": ["Who has won the most Wimbledon titles?"]} +{"id": "single-076", "area": "language-and-writing", "turns": ["What's the difference between 'affect' and 'effect'?"]} +{"id": "single-077", "area": "language-and-writing", "turns": ["Can you help me word a text cancelling dinner with a friend without sounding rude?"]} +{"id": "single-078", "area": "language-and-writing", "turns": ["Is it 'fewer people' or 'less people'?"]} +{"id": "single-079", "area": "feelings", "turns": ["I've been feeling really lonely since I started working from home."]} +{"id": "single-080", "area": "feelings", "turns": ["I failed my driving test today and I feel like an idiot."]} +{"id": "single-081", "area": "feelings", "turns": ["I'm so stressed about moving house next week."]} +{"id": "single-082", "area": "small-talk", "turns": ["Hi! How's your day going?"]} +{"id": "single-083", "area": "small-talk", "turns": ["Good morning. It's freezing here today."]} +{"id": "single-084", "area": "small-talk", "turns": ["I finally finished that jigsaw I've been doing for a month!"]} +{"id": "single-085", "area": "small-talk", "turns": ["Thanks, that's really helpful."]} +{"id": "single-086", "area": "opinions", "turns": ["What do you think is the best season of the year?"]} +{"id": "single-087", "area": "opinions", "turns": ["Cats or dogs?"]} +{"id": "single-088", "area": "opinions", "turns": ["Is it ever OK to recline your seat on a plane?"]} +{"id": "single-089", "area": "creative", "turns": ["Can you write a short poem about autumn for my daughter's card?"]} +{"id": "single-090", "area": "creative", "turns": ["I need a name for my new sourdough starter. Any ideas?"]} +{"id": "single-091", "area": "creative", "turns": ["Tell me a joke about cheese."]} +{"id": "single-092", "area": "maths-and-numbers", "turns": ["What's 15% of 80?"]} +{"id": "single-093", "area": "maths-and-numbers", "turns": ["If I drive 120 miles at 60 miles an hour, how long will it take?"]} +{"id": "single-094", "area": "maths-and-numbers", "turns": ["How many weeks are there in a year, exactly?"]} +{"id": "single-095", "area": "nature-and-weather", "turns": ["Why do leaves change colour in autumn?"]} +{"id": "single-096", "area": "nature-and-weather", "turns": ["What should I do if I'm caught outside in a thunderstorm?"]} +{"id": "single-097", "area": "nature-and-weather", "turns": ["Which birds might I see in a city park in winter?"]} +{"id": "single-098", "area": "messy-typing", "turns": ["wats the best way to cook rice so its not sticky"]} +{"id": "single-099", "area": "messy-typing", "turns": ["how do i get my baby to sleep thru the night"]} +{"id": "single-100", "area": "messy-typing", "turns": ["recomend me a good scifi book pls"]} +{"id": "single-101", "area": "messy-typing", "turns": ["whats the wether usually like in rome in april"]} +{"id": "single-102", "area": "messy-typing", "turns": ["cn u help me write a msg to my landlord about the broken boiler"]} +{"id": "single-103", "area": "messy-typing", "turns": ["idk what to get my dad for his 60th, he likes fishing and old films"]} +{"id": "single-104", "area": "about-the-bot", "turns": ["Are you a real person?"]} +{"id": "single-105", "area": "about-the-bot", "turns": ["What are you?"]} +{"id": "single-106", "area": "about-the-bot", "turns": ["Do you remember what we talked about yesterday?"]} +{"id": "single-107", "area": "about-the-bot", "turns": ["What kind of things can you help with?"]} diff --git a/world/seed/tests/test_architecture.py b/world/seed/tests/test_architecture.py new file mode 100644 index 0000000000000000000000000000000000000000..c64b5f587a5c635bda230751d9f11570795fed46 --- /dev/null +++ b/world/seed/tests/test_architecture.py @@ -0,0 +1,32 @@ +import unittest + +from bot import runtime +from bot.compose import pick +from bot.memory import user +from bot.understanding import understand + + +class ArchitectureTest(unittest.TestCase): + def test_understanding_reads_the_kind_of_line(self): + kinds = {"": "empty", "hey there": "greeting", "Good morning!": "greeting", + "thx so much": "thanks", "can u help me": "question", "Is it far?": "question", + "I just got a puppy": "statement"} + for text, kind in kinds.items(): + self.assertEqual(understand(text, {})["kind"], kind, text) + + def test_every_module_sees_this_turns_understanding(self): + memory = {} + runtime.turn("Where is Lisbon?", memory) + self.assertEqual(memory["understood"]["kind"], "question") + self.assertEqual(memory["understood"]["words"], ["where", "is", "lisbon"]) + + def test_memory_and_compose_helpers(self): + memory = {} + user(memory)["name"] = "Sam" + self.assertEqual(memory["user"], {"name": "Sam"}) + memory["turns"] = [{"user": "hi", "bot": "Hi!", "module": "greeting"}] + self.assertEqual(pick(["Hi!", "Hello!"], memory), "Hello!") + + +if __name__ == "__main__": + unittest.main() diff --git a/world/seed/tests/test_compare.py b/world/seed/tests/test_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..a67278d9fd6d42fc286f3230175df4781adc72ff --- /dev/null +++ b/world/seed/tests/test_compare.py @@ -0,0 +1,34 @@ +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def compare(*args): + return subprocess.run([sys.executable, str(ROOT / "tools/compare.py"), *args], capture_output=True, + text=True, cwd=ROOT, timeout=600, check=False) + + +class CompareTest(unittest.TestCase): + def test_a_checkout_compared_with_itself_changes_nothing(self): + result = compare(str(ROOT), str(ROOT), "--sample", "6", "--seed", "1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("no reply changed", result.stdout) + + def test_score_counts_head_better_and_worse_with_the_key(self): + with tempfile.TemporaryDirectory() as tmp: + key = Path(tmp) / "k.key" + key.write_text(json.dumps({"seed": 3, "items": ["a", "b", "c"], + "key": ["head=1", "head=2", "head=1"]})) + result = compare("--score", str(key), "1 1 =") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("head better 1, base better 1, same 1", result.stdout) + self.assertIn("head worse on: b", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/world/seed/tests/test_deck.py b/world/seed/tests/test_deck.py new file mode 100644 index 0000000000000000000000000000000000000000..eb61c03c079f6b937b8a5d280c51bb0e849c4991 --- /dev/null +++ b/world/seed/tests/test_deck.py @@ -0,0 +1,31 @@ +import json +import unittest +from pathlib import Path + +DECK = Path(__file__).resolve().parents[1] / "deck" + + +class DeckTest(unittest.TestCase): + def test_conversations_are_well_formed_and_ids_unique(self): + seen = set() + for path in sorted(DECK.glob("*.jsonl")): + for n, line in enumerate(path.read_text().splitlines(), 1): + item = json.loads(line) + where = f"{path.name}:{n}" + self.assertEqual(set(item), {"id", "area", "turns"}, where) + self.assertNotIn(item["id"], seen, where) + seen.add(item["id"]) + self.assertTrue(item["area"].strip(), where) + self.assertTrue(item["turns"], where) + for text in item["turns"]: + self.assertTrue(isinstance(text, str) and text.strip() and "\n" not in text, where) + self.assertTrue(seen) + + def test_single_and_multi_turn_files_hold_their_kind(self): + for name, multi in (("single.jsonl", False), ("multi.jsonl", True)): + for line in (DECK / name).read_text().splitlines(): + self.assertEqual(len(json.loads(line)["turns"]) > 1, multi, line) + + +if __name__ == "__main__": + unittest.main() diff --git a/world/seed/tests/test_interface.py b/world/seed/tests/test_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..e730e4441aea2c8f13e8f3c28ddbec286db99709 --- /dev/null +++ b/world/seed/tests/test_interface.py @@ -0,0 +1,19 @@ +import subprocess +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +class InterfaceTest(unittest.TestCase): + def test_one_nonempty_reply_per_input(self): + result = subprocess.run([sys.executable, "-m", "bot"], input="hi\n\nbye\n", + text=True, capture_output=True, cwd=ROOT, timeout=300, check=False) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(result.stdout.splitlines()), 3) + self.assertTrue(all(line.strip() for line in result.stdout.splitlines())) + + +if __name__ == "__main__": + unittest.main() diff --git a/world/seed/tests/test_runtime.py b/world/seed/tests/test_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..29132266b26269e16a17ce513a2b8ba1df4b5cad --- /dev/null +++ b/world/seed/tests/test_runtime.py @@ -0,0 +1,22 @@ +import unittest + +from bot import runtime + + +class RuntimeTest(unittest.TestCase): + def test_every_turn_gets_a_reply_and_is_recorded(self): + memory = {} + for text in ("hi", "", "how are you?"): + self.assertTrue(runtime.reply(text, memory).strip()) + self.assertEqual([t["user"] for t in memory["turns"]], ["hi", "", "how are you?"]) + + def test_turn_names_the_chosen_module_and_every_candidate(self): + t = runtime.turn("hello", {}) + self.assertIn(t["module"], [c["module"] for c in t["candidates"]]) + self.assertEqual(t["reply"], next(c["reply"] for c in t["candidates"] if c["module"] == t["module"])) + priorities = [c["priority"] for c in t["candidates"]] + self.assertEqual(priorities, sorted(priorities, reverse=True)) + + +if __name__ == "__main__": + unittest.main() diff --git a/world/seed/tools/compare.py b/world/seed/tools/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d733d85b52fdc6bb4f47a24f66265a2ad5f659 --- /dev/null +++ b/world/seed/tools/compare.py @@ -0,0 +1,201 @@ +"""Compare two checkouts of the bot on a random sample of the deck, blind. + + git worktree add ../base origin/main # the checkout to compare against + python tools/compare.py ../base . --seed 41 # base, then head (this clone) + python tools/compare.py --score /tmp/compare-41.key "1 2 = 2 1" + +The first command runs both bots on the same deck conversations (deck/*.jsonl in head) and +prints every turn whose reply changed: single turns as pairs, multi-turn conversations as two +whole transcripts. Which side is which is random and written to a key file, not printed. Judge +each item by STYLE.md, in order, with 1, 2 or = (no better), then score the verdicts with the +key: the second command prints how often head was better and worse. --sample 0 runs the +whole deck. The summary also counts which modules answer more or fewer turns in head. +""" +import argparse +import collections +import json +import os +import random +import subprocess +import sys +import tempfile +from pathlib import Path + +DRIVER = r''' +import json, os, sys +sys.path.insert(0, os.getcwd()) +sys.dont_write_bytecode = True +import bot.runtime as runtime + +def run(turns): + memory, out = {}, [] + for text in turns: + if hasattr(runtime, "turn"): + t = runtime.turn(text, memory) + out.append({"reply": t["reply"], "module": t["module"], "candidates": len(t["candidates"])}) + else: + out.append({"reply": runtime.reply(text, memory), "module": None, "candidates": None}) + return out + +for line in sys.stdin: + turns = json.loads(line) + read, write = os.pipe() + pid = os.fork() # every conversation starts from the freshly loaded bot, as in production + if pid == 0: + os.close(read) + try: + data = json.dumps(run(turns)) + except BaseException as exc: + data = json.dumps({"error": f"{type(exc).__name__}: {exc}"}) + with os.fdopen(write, "w") as f: + f.write(data) + os._exit(0) + os.close(write) + with os.fdopen(read) as f: + data = f.read() + os.waitpid(pid, 0) + print(data or json.dumps({"error": "the conversation crashed"}), flush=True) +''' + + +def load_deck(root): + items = [] + for path in sorted((Path(root) / "deck").glob("*.jsonl")): + for line in path.read_text().splitlines(): + if line.strip(): + items.append(json.loads(line)) + return items + + +def sample(deck, n, seed, multi_share): + rng = random.Random(seed) + if n <= 0 or n >= len(deck): + return list(deck) + multi = [c for c in deck if len(c["turns"]) > 1] + single = [c for c in deck if len(c["turns"]) == 1] + k = min(len(multi), round(n * multi_share)) + picked = rng.sample(multi, k) + rng.sample(single, min(len(single), n - k)) + return sorted(picked, key=lambda c: c["id"]) + + +def run_bot(root, conversations, timeout): + lines = "".join(json.dumps(c["turns"]) + "\n" for c in conversations) + p = subprocess.run([sys.executable, "-c", DRIVER], input=lines, text=True, capture_output=True, + cwd=root, timeout=timeout, check=False) + results = [json.loads(line) for line in p.stdout.splitlines() if line.strip()] + if p.returncode or len(results) != len(conversations): + raise SystemExit(f"the bot in {root} failed:\n{p.stderr[-2000:]}") + return results + + +def revision(root): + p = subprocess.run(["git", "-C", str(root), "rev-parse", "--short", "HEAD"], capture_output=True, + text=True, check=False) + dirty = subprocess.run(["git", "-C", str(root), "status", "--porcelain"], capture_output=True, + text=True, check=False).stdout.strip() + return (p.stdout.strip() or "?") + (" + local changes" if dirty else "") + + +def transcript(turns, replies): + return "\n".join(f" User: {text}\n Bot: {r['reply']}" for text, r in zip(turns, replies, strict=True)) + + +def compare(args): + deck = load_deck(args.head) + if not deck: + raise SystemExit(f"no deck in {args.head}/deck") + picked = sample(deck, args.sample, args.seed, args.multi_share) + base = run_bot(args.base, picked, args.timeout) + head = run_bot(args.head, picked, args.timeout) + rng = random.Random(f"{args.seed}-order") + items, key, crashes = [], [], [] + moved, answers = collections.Counter(), collections.Counter() + turns = changed = 0 + for conv, b, h in zip(picked, base, head, strict=True): + if "error" in b or "error" in h: + crashes.append(f"{conv['id']}: base {b.get('error', 'ok')}; head {h.get('error', 'ok')}") + continue + turns += len(conv["turns"]) + diff = [i for i, (x, y) in enumerate(zip(b, h, strict=True)) if x["reply"] != y["reply"]] + changed += len(diff) + for x, y in zip(b, h, strict=True): + answers[x["module"]] -= 1 + answers[y["module"]] += 1 + if x["module"] != y["module"]: + moved[(x["module"], y["module"])] += 1 + if not diff: + continue + head_first = rng.random() < 0.5 + key.append("head=1" if head_first else "head=2") + first, second = (h, b) if head_first else (b, h) + if len(conv["turns"]) == 1: + text = f" User: {conv['turns'][0]}\n 1: {first[0]['reply']}\n 2: {second[0]['reply']}" + else: + text = (f" Conversation 1:\n{transcript(conv['turns'], first)}\n" + f" Conversation 2:\n{transcript(conv['turns'], second)}") + items.append((conv, diff, text)) + singles = sum(1 for c in picked if len(c["turns"]) == 1) + print(f"base {args.base} ({revision(args.base)}) vs head {args.head} ({revision(args.head)})") + print(f"deck sample: {len(picked)} conversations (seed {args.seed}), {singles} single-turn, " + f"{len(picked) - singles} multi-turn; {changed} of {turns} replies changed") + gained = [f"{m or '(none)'} {n:+d}" for m, n in answers.most_common() if n > 0] + lost = [f"{m or '(none)'} {n:+d}" for m, n in reversed(answers.most_common()) if n < 0] + if gained or lost: + print(f"turns answered, head vs base: {', '.join(gained + lost)}") + for (was, now), n in moved.most_common(8): + print(f" {n} turn(s) moved from {was or '(none)'} to {now or '(none)'}") + for crash in crashes: + print(f"CRASHED {crash}") + if not items: + print("no reply changed") + return + print("\nJudge each item by STYLE.md: which would you rather get? Answer 1, 2 or = per item.\n") + for i, (conv, diff, text) in enumerate(items, 1): + where = "" if len(conv["turns"]) == 1 else f", turns {', '.join(str(d + 1) for d in diff)} changed" + print(f"[{i}] {conv['id']} ({conv['area']}){where}\n{text}\n") + path = Path(args.key or Path(tempfile.gettempdir()) / f"compare-{args.seed}.key") + path.write_text(json.dumps({"seed": args.seed, "items": [c["id"] for c, _, _ in items], "key": key})) + print(f"key: {path} (score with: python tools/compare.py --score {path} \"\")") + + +def score(path, verdicts): + data = json.loads(Path(path).read_text()) + marks = verdicts.replace(",", " ").split() + if len(marks) != len(data["key"]): + raise SystemExit(f"give one verdict per item ({len(data['key'])}), got {len(marks)}") + better, worse, same = [], [], [] + for k, item, m in zip(data["key"], data["items"], marks, strict=True): + if m == "=": + same.append(item) + elif m in ("1", "2"): + (better if k == f"head={m}" else worse).append(item) + else: + raise SystemExit(f"verdicts are 1, 2 or =, got {m!r}") + print(f"seed {data['seed']}: head better {len(better)}, base better {len(worse)}, same {len(same)}") + if worse: + print(f"head worse on: {', '.join(worse)}") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("base", nargs="?", help="checkout to compare against (e.g. a worktree of origin/main)") + parser.add_argument("head", nargs="?", default=".", help="checkout to test (default: this clone)") + parser.add_argument("--sample", type=int, default=40, help="conversations to run (0: the whole deck)") + parser.add_argument("--seed", type=int, default=None, help="sample seed (default: random)") + parser.add_argument("--multi-share", type=float, default=0.4, help="share of multi-turn conversations") + parser.add_argument("--timeout", type=float, default=600, help="seconds per bot") + parser.add_argument("--key", help="where to write the key (default: the temp directory)") + parser.add_argument("--score", nargs=2, metavar=("KEY", "VERDICTS"), help="score verdicts with a key") + args = parser.parse_args() + if args.score: + return score(*args.score) + if not args.base: + parser.error("give the base checkout (and optionally head), or --score KEY VERDICTS") + if args.seed is None: + args.seed = random.SystemRandom().randrange(1, 10000) + args.base, args.head = os.path.abspath(args.base), os.path.abspath(args.head) + compare(args) + + +if __name__ == "__main__": + main() diff --git a/world/snapshot.py b/world/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..46ea4cc05b011a39b677f08e1180a1307c5e3c9a --- /dev/null +++ b/world/snapshot.py @@ -0,0 +1,70 @@ +"""One archive for world state; agent clones live in their own worker snapshots.""" +from __future__ import annotations + +import argparse +import os +import shutil +import subprocess +import tarfile +import tempfile +from pathlib import Path, PurePosixPath + +from flock.worker.sync import HubBucketStore +from flock.world.store import backup_to + +# state.db is copied with the online backup API (consistent while the world writes it). +FILES = ("repo.bundle", "state.db", "prs.json", "prs.jsonl", "eval-queue.jsonl", "knobs.json", + "outbox-comment.jsonl") + + +def transfer(mode, workspace, bucket, store=None): + store = store or HubBucketStore(bucket, token=os.environ.get("HF_TOKEN")) + if mode == "restore" and "world.tar.gz" not in store.list("world.tar.gz"): + return False # a first start; permission/network/invalid-archive failures still raise + workspace = Path(workspace) + workspace.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=workspace.parent) as tmp: + archive = Path(tmp) / "world.tar.gz" + if mode == "push": + bundle = Path(tmp) / "repo.bundle" + subprocess.run(["git", "-C", str(workspace / "repo.git"), "bundle", "create", + str(bundle), "--all"], check=True, capture_output=True) + with tarfile.open(archive, "w:gz", compresslevel=1) as out: + out.add(bundle, arcname="repo.bundle") + if (workspace / "state.db").exists(): + backup_to(workspace / "state.db", Path(tmp) / "state.db") + out.add(Path(tmp) / "state.db", arcname="state.db") + for name in FILES[2:]: + if (workspace / name).exists(): + out.add(workspace / name, arcname=name) + store.upload([(archive, "world.tar.gz")]) + else: + store.download([("world.tar.gz", archive)]) + if mode == "restore": + with tarfile.open(archive, "r:gz") as source: + for member in source.getmembers(): + path = PurePosixPath(member.name) + if (path.is_absolute() or ".." in path.parts or not path.parts + or path.parts[0] not in FILES or not (member.isfile() or member.isdir())): + raise ValueError("unexpected world archive entry") + target = workspace / path + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + for wal in ("-wal", "-shm"): # a stale WAL would replay onto the restored db + target.with_name(target.name + wal).unlink(missing_ok=True) + with source.extractfile(member) as src, target.open("wb") as dst: + shutil.copyfileobj(src, dst) + + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("mode", choices=["push", "restore"]) + parser.add_argument("workspace") + parser.add_argument("bucket") + args = parser.parse_args() + if not transfer(args.mode, args.workspace, args.bucket): + raise SystemExit(3) diff --git a/world/source-lock.json b/world/source-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..174f0fd35f0a5b6026734ea519f8f30856a8f0d5 --- /dev/null +++ b/world/source-lock.json @@ -0,0 +1,22 @@ +{ + "flock_repo": "https://github.com/huggingface/flock", + "flock_commit": "aaab415cbf59efeec3294e1d014c9ac69db5e390", + "files": { + "src/flock/__init__.py": "f26caf93ebbf4da0e48361700fbd1b03ab8e18cf7aa7fb810d023002937b121a", + "src/flock/isolation.py": "35a563e532802a12ca44f84e22652d740139ea6dc92061ccfba9d59ede29f560", + "src/flock/models.py": "43c1101112c689f71475400fe61ee6a6c8c6fd15388c65b656cd3308082702c9", + "src/flock/registry.py": "fe27642c50f25a7a4c9b20e5006b4117d755b2a9ae474a8726a0d9861a5445e8", + "src/flock/tools/__init__.py": "9bb7c72a7a563a9086a12f52399bbca74250c498c09b428d6c7b56cb83b406ee", + "src/flock/tools/loader.py": "a383c95a8910f322373511425ac06a0f152a818e57ab9eefa3eceda934bcd826", + "src/flock/worker/__init__.py": "c4afc77bc9a814ffb811300094c36e0706c2a6a025703241c69688e3c5d2ff83", + "src/flock/worker/sync.py": "90e10862f5b772017460a752c8afb6340c747a6d7a63dbab91c295afe1a49b96", + "src/flock/world/__init__.py": "d9cd12d59e039b7b91c88e978a2b7dcaa657d9f9bb7524835b947348d7829449", + "src/flock/world/admin.py": "93b04d68199239c5c80c981d5e2ae320fbff28da26da6b1cb3cd5eb0765d1562", + "src/flock/world/lanes.py": "f43ff7bfc91c17c48fa73e99fa6e172323b7b158524422b7c3b2d4254680bc47", + "src/flock/world/protocol.py": "94250d3b2c6b8dae8ac61de339044694ee3a72aec832c2df369c11b1b79363a9", + "src/flock/world/server.py": "03665b24ae28ce8e9be951aeca8546721cea9771fdd13ecec87f77b43ae3a848", + "src/flock/world/store.py": "1984943b9c4a8ca05a717f8dd49aa06b04930eae8d96babe60c2e2ed4f6f7d51", + "src/flock/world/workspace.py": "c861b98c3f2603cfdc478f92547e7b8b83faaf5f1e292732c86cc51b7b26ee1a" + }, + "requirements.txt": "bcc4c96105fcc7eb7b311e32a341d69c669addcb1482d6d7bf59b33043a20bf1" +} diff --git a/world/src/flock/__init__.py b/world/src/flock/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8a166be5a74d6ee90d609b03414fc3f6b821200c --- /dev/null +++ b/world/src/flock/__init__.py @@ -0,0 +1,3 @@ +"""flock: host coding-harness agent swarms on Hugging Face Jobs.""" + +__version__ = "0.0.1" diff --git a/world/src/flock/isolation.py b/world/src/flock/isolation.py new file mode 100644 index 0000000000000000000000000000000000000000..8797da84923dbef8f245ef120d726f549e068f36 --- /dev/null +++ b/world/src/flock/isolation.py @@ -0,0 +1,386 @@ +"""Linux process isolation for harness and bot subprocesses. Setup errors abort; there is no unsandboxed fallback. + +unshare creates a user/PID/mount namespace and private procfs. The trusted setup +then builds a small root with read-only runtimes and only the caller's data, +chroots and drops capabilities before executing any agent-supplied code. +""" +from __future__ import annotations + +import contextlib +import ctypes +import json +import os +import re +import shutil +import sys +from collections.abc import Iterator +from pathlib import Path + +MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC = 1, 2, 4, 8 +MS_REMOUNT, MS_BIND = 32, 4096 +MS_NOATIME, MS_NODIRATIME, MS_REC, MS_RELATIME, MS_STRICTATIME = 1024, 2048, 16384, 1 << 21, 1 << 24 +# statvfs flags of a mount that an unprivileged namespace cannot clear (they are locked) -> +# the mount(2) flags a read-only remount must repeat. +_LOCKED = ((os.ST_RDONLY, MS_RDONLY), (os.ST_NOSUID, MS_NOSUID), (os.ST_NODEV, MS_NODEV), + (os.ST_NOEXEC, MS_NOEXEC), (os.ST_NOATIME, MS_NOATIME), + (os.ST_NODIRATIME, MS_NODIRATIME), (os.ST_RELATIME, MS_RELATIME)) + + +DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random") +# The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points +# and stray writes outside the bound dirs land there; the cap bounds each sandbox. +TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "FLOCK_ISOLATION_TMPFS_SIZE", "256m" +SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir +_SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE) +MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442 + + +class IsolationSetupError(OSError): + """A sandbox setup step failed: names the step and path (never argv or the env).""" + + +class IsolationMountError(IsolationSetupError): + """A mount(2) call of the sandbox setup failed: names the target and flags, no argv.""" + + +@contextlib.contextmanager +def _step(step: str, path) -> Iterator[None]: + """Turn a plain OSError of one setup step into an IsolationSetupError naming it.""" + try: + yield + except IsolationSetupError: + raise + except OSError as e: + raise IsolationSetupError(e.errno, f"isolation {step} failed: " + f"{e.strerror or type(e).__name__}: path={path}") from None + + +def enabled() -> bool: + return os.environ.get("FLOCK_PROCESS_ISOLATION") == "1" + + +def _libc(): + return ctypes.CDLL(None, use_errno=True) + + +def protect_supervisor() -> None: + """Deny same-UID ptrace and /proc//{environ,mem,root} on worker/world.""" + if not sys.platform.startswith("linux") or _libc().prctl(4, 0, 0, 0, 0) != 0: + raise RuntimeError("PR_SET_DUMPABLE=0 is required for process isolation") + + +def tmpfs_size(env=os.environ) -> str: + """The size cap of a sandbox's tmpfs root: $FLOCK_ISOLATION_TMPFS_SIZE (bytes, or with a + k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default.""" + value = (env.get(TMPFS_SIZE_ENV) or "").strip() + if _SIZE.fullmatch(value): + return value.lower() + if value: + print(f"isolation: ignoring {TMPFS_SIZE_ENV}={value!r}; using {TMPFS_SIZE_DEFAULT}", + file=sys.stderr) + return TMPFS_SIZE_DEFAULT + + +def runtime_paths(command: list[str], *, python_only=False) -> list[str]: + paths = ["/usr", "/bin", "/sbin", "/lib", "/lib64", sys.prefix, sys.base_prefix] + # Config files needed by Python, Node, TLS, DNS and git; never a host home or the shared-disk root. + paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf", + "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"] + if not python_only: + paths.append(str(Path(__file__).resolve().parents[2])) # editable flock install + for binary in (command[0], "node"): + found = shutil.which(binary) + if not found: + continue + target = Path(found).resolve() + modules = next((p for p in target.parents if p.name == "node_modules"), None) + paths.append(str(modules or target.parent)) + return sorted({str(Path(p).absolute()) for p in paths if Path(p).exists()}, key=lambda p: (len(p), p)) + + +def symlink_chain(path: str | Path) -> tuple[list[tuple[str, str]], str]: + """Resolve `path` one hop at a time: every symlink met on the way (as `(link, target)`, + the target exactly as stored) and the final real path. Components that do not exist are + kept as they are. A loop or more than 40 hops raises.""" + links: list[tuple[str, str]] = [] + pending = list(Path(os.path.abspath(path)).parts[1:]) + current = Path("/") + while pending: + name = pending.pop(0) + if name in ("", "."): + continue + if name == "..": + current = current.parent + continue + candidate = current / name + if not candidate.is_symlink(): + current = candidate + continue + target = os.readlink(candidate) + links.append((str(candidate), target)) + if len(links) > 40: + raise RuntimeError(f"isolation: too many symlinks resolving {path}") + if os.path.isabs(target): + current = Path("/") + pending = list(Path(target).parts[1:]) + pending + else: + pending = list(Path(target).parts) + pending + return links, str(current) + + +def _within(path: str, roots: list[str]) -> bool: + return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots) + + +def plan(argv: list[str], *, cwd: Path, readonly=(), writable=(), python_only=False, + private_dirs=(), tmp=None) -> dict: + """Mounts and symlinks for the chroot. Every path is bound at its real location, and each + symlink hop on the way to it (and to the interpreter, the command and node) is recreated + inside, so the original spelling resolves there too (a uv venv's python links through + `cpython-3.12-...` to `cpython-3.12.14-...`).""" + links: dict[str, str] = {} + + def real(p) -> str: + hops, final = symlink_chain(p) + links.update(hops) + return final + + ro = [real(p) for p in runtime_paths(argv, python_only=python_only) + [str(p) for p in readonly]] + rw = [real(p) for p in writable] + probes = [sys.executable, argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])] + if not python_only: + probes.append(shutil.which("node")) + for probe in filter(None, probes): + final = real(probe) + if not _within(final, ro + rw): + raise RuntimeError(f"isolation cannot represent {probe}: it resolves to {final}, " + "outside every mounted path") + real(cwd) + def ordered(paths: list[str]) -> list[str]: # parents before nested mounts + return sorted(dict.fromkeys(paths), key=lambda p: (len(p), p)) + + # `tmp` (a disk-backed dir) is bound over the sandbox's /tmp, so files written there do not + # fill the tmpfs root. Not when a planned path lives under /tmp itself (a test's tmp_path): + # the bind would hide it, and /tmp stays on the size-capped tmpfs. + tmp_dir = real(tmp) if tmp is not None else None + if tmp_dir is not None and any(_within(p, [SANDBOX_TMP]) for p in [*ro, *rw, *links, real(cwd)]): + tmp_dir = None + return {"readonly": ordered(ro), "writable": list(dict.fromkeys(rw)), + "symlinks": sorted(links.items(), key=lambda kv: (len(kv[0]), kv[0])), + "private_dirs": [str(Path(p).absolute()) for p in private_dirs], "tmp": tmp_dir} + + +def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(), network=False, + python_only=False, private_dirs=(), tmp=None) -> list[str]: + """Build a trusted invocation. Only explicitly mounted paths survive the chroot. `tmp`: a + disk-backed directory bound writable at the sandbox's /tmp (see `plan`).""" + unshare = shutil.which("unshare") + if not unshare: + raise RuntimeError("unshare is required for process isolation") + config = {"root": str(root.absolute()), "cwd": str(cwd.absolute()), + "readonly_root": not network, "tmpfs_size": tmpfs_size(), + **plan(argv, cwd=cwd, readonly=readonly, writable=writable, python_only=python_only, + private_dirs=private_dirs, tmp=tmp)} + # Slurm sends USR1 to every process on reclaim. Only worker/world supervisors + # handle it; an unshare wrapper must survive long enough for their bounded drain. + return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "flock-isolate", + unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL", + "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--", + sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv] + + +def _mount(source, target, kind=None, flags=0, data=None): + def encoded(value): + return os.fsencode(value) if value is not None else None + libc = _libc() + libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, + ctypes.c_ulong, ctypes.c_char_p] + if libc.mount(encoded(source), encoded(target), encoded(kind), flags, encoded(data)) != 0: + errno = ctypes.get_errno() + raise IsolationMountError(errno, f"isolation mount failed: {os.strerror(errno)}: " + f"source={source} target={target} type={kind} " + f"flags={flags:#x}") + + +def readonly_remount_flags(target) -> int: + """MS_REMOUNT|MS_BIND|MS_RDONLY plus nosuid/nodev, and every locked flag the bound mount + already has (statvfs of the bind target): a user namespace cannot clear them, and + leaving them out fails with EPERM. No atime flag on the source means strictatime.""" + inherited = os.statvfs(target).f_flag + flags = MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV + for flag, mount_flag in _LOCKED: + if inherited & flag: + flags |= mount_flag + if not inherited & (os.ST_NOATIME | os.ST_RELATIME): + flags |= MS_STRICTATIME + return flags + + +def _readonly_recursive(target) -> bool: + """mount_setattr(AT_RECURSIVE, MOUNT_ATTR_RDONLY): make every submount of a recursive + bind read-only too (a remount only changes the top one). False if the kernel lacks it + (before 5.12); the mountinfo check still refuses a writable submount.""" + libc = _libc() + attr = (ctypes.c_uint64 * 4)(MOUNT_ATTR_RDONLY, 0, 0, 0) + libc.syscall.restype = ctypes.c_long + rc = libc.syscall(ctypes.c_long(SYS_MOUNT_SETATTR), ctypes.c_int(AT_FDCWD), + ctypes.c_char_p(os.fsencode(target)), ctypes.c_uint(AT_RECURSIVE), + ctypes.byref(attr), ctypes.c_size_t(ctypes.sizeof(attr))) + # Any failure (ENOSYS before 5.12, EPERM on a locked mount): the mountinfo check that + # follows the binds still refuses a writable submount. + return rc == 0 + + +def _unescape(field: str) -> str: + return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field) + + +def parse_mountinfo(text: str) -> list[tuple[str, set[str]]]: + """(mount point, per-mount options) of each /proc/self/mountinfo line.""" + out = [] + for line in text.splitlines(): + fields = line.split() + if len(fields) >= 6: + out.append((_unescape(fields[4]), set(fields[5].split(",")))) + return out + + +def check_mounts(mounts: list[tuple[str, set[str]]], root: str, readonly: list[str], + writable: list[str] = (), extra: list[str] = ()) -> None: + """Fail closed after the binds. Every mount under `root` must be a planned target (or + `extra`: proc, the /dev nodes), or a submount a recursive bind of one brought along + (e.g. a container's zoneinfo file bound over /usr's); and every mount at or under a + read-only target, outside a writable one, must be `ro`.""" + def under(path: str, roots) -> bool: + return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots) + + planned = [*readonly, *writable, *extra] + for point, opts in mounts: + if point == root or not under(point, [root]): + continue + if not under(point, planned): + raise IsolationMountError(1, f"isolation: unexpected mount {point} in the sandbox root") + if under(point, readonly) and not under(point, writable) and "ro" not in opts: + raise IsolationMountError(30, f"isolation: {point} is mounted writable under a " + "read-only path") + + +def _bind(root: Path, source: str, *, readonly: bool, target: Path | None = None): + """Bind `source` at its own path under `root` (or at `target`, a path under `root`).""" + path = Path(source) + if not path.exists(): + raise IsolationSetupError(2, f"isolation bind failed: required path is missing: path={source}") + target = target if target is not None else root / path.relative_to("/") + # Create the mount point only when missing: it may already exist on a read-only bind + # (/etc/localtime -> /usr/share/zoneinfo/... under the /usr bind), where touch()'s utime + # fails with EROFS. + with _step("mount point creation", target): + target.parent.mkdir(parents=True, exist_ok=True) + if path.is_dir(): + if not target.is_dir(): + target.mkdir() + elif not target.exists(): + target.touch() + # Recursive: a user namespace refuses (EINVAL) a non-recursive bind of a tree that has + # locked submounts, since it would uncover what they hide. Only explicitly listed paths + # are bound, so a submount comes in only under a path that was asked for. + _mount(source, target, flags=MS_BIND | MS_REC) + if readonly: + # Step two: read-only only works as a remount of the bind, with the locked flags; + # then the submounts the recursive bind brought along, where the kernel can. + _mount(None, target, flags=readonly_remount_flags(target)) + _readonly_recursive(target) + + +def _drop_privileges(): + libc = _libc() + # NOROOT + locked: exec as namespace uid 0 must never regain capabilities. + if libc.prctl(28, 3, 0, 0, 0) or libc.prctl(38, 1, 0, 0, 0): + raise RuntimeError("cannot lock sandbox privileges") + # All currently defined capabilities fit below 64. EINVAL marks unsupported bits. + for cap in range(64): + if libc.prctl(24, cap, 0, 0, 0) != 0 and ctypes.get_errno() != 22: + raise RuntimeError("cannot drop sandbox capability bounding set") + class Header(ctypes.Structure): + _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)] + class Data(ctypes.Structure): + _fields_ = [("effective", ctypes.c_uint32), ("permitted", ctypes.c_uint32), + ("inheritable", ctypes.c_uint32)] + if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()) != 0: + raise RuntimeError("cannot clear sandbox capabilities") + + +OOM_SCORE_ADJ = 800 # sandboxed processes die before the worker (which keeps 0) on an OOM kill + + +def set_oom_score_adj(value: int = OOM_SCORE_ADJ, path: str = "/proc/self/oom_score_adj") -> bool: + """Raise this process's OOM score (inherited by what it execs). Raising needs no + privilege; False when /proc refuses it.""" + try: + Path(path).write_text(str(value)) + return True + except OSError: + return False + + +def _enter(config, argv): + # Never share a process group with a supervisor outside the PID namespace. + if os.getpgrp() != os.getpid(): + os.setsid() + set_oom_score_adj() + root = Path(config["root"]) + with _step("root creation", root): + root.mkdir(parents=True, exist_ok=True) + size = config.get("tmpfs_size") or TMPFS_SIZE_DEFAULT + if not _SIZE.fullmatch(size): + raise IsolationSetupError(22, f"isolation tmpfs size is invalid: path={root}") + _mount("tmpfs", root, "tmpfs", MS_NOSUID | MS_NODEV, f"mode=755,size={size}") + for path in config["readonly"]: + _bind(root, path, readonly=True) + for path in config["writable"]: + _bind(root, path, readonly=False) + for link, target in config.get("symlinks", ()): + inside = root / Path(link).relative_to("/") + if os.path.lexists(inside): + continue # already visible through a bind mount + with _step("symlink creation", inside): + inside.parent.mkdir(parents=True, exist_ok=True) + inside.symlink_to(target) + for path in config["private_dirs"]: + with _step("private directory creation", path): + (root / Path(path).relative_to("/")).mkdir(parents=True, exist_ok=True) + for path in ("tmp", "proc", "dev"): + with _step("directory creation", root / path): + (root / path).mkdir(exist_ok=True) + if config.get("tmp"): # the sandbox's /tmp on the caller's disk-backed dir, not the tmpfs + _bind(root, config["tmp"], readonly=False, target=root / SANDBOX_TMP.lstrip("/")) + for path in DEV_NODES: + _bind(root, path, readonly=False) + with _step("symlink creation", root / "dev/fd"): + (root / "dev/fd").symlink_to("/proc/self/fd") + _mount("proc", root / "proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC) + inside = lambda p: os.path.realpath(root / Path(p).relative_to("/")) + check_mounts(parse_mountinfo(Path("/proc/self/mountinfo").read_text()), os.path.realpath(root), + [inside(p) for p in config["readonly"]], + [inside(p) for p in (*config["writable"], *([SANDBOX_TMP] if config.get("tmp") else []))], + [inside(p) for p in ("/proc", *DEV_NODES)]) + if config["readonly_root"]: + _mount(None, root, flags=MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV) + with _step("chroot", root): + os.chroot(root) + with _step("chdir", config["cwd"]): + os.chdir(config["cwd"]) + _drop_privileges() + os.execvpe(argv[0], argv, dict(os.environ)) + + +if __name__ == "__main__": + try: + _enter(json.loads(sys.argv[1]), sys.argv[2:]) + except IsolationSetupError as e: # step, path and flags only, never argv or the env + print(f"process isolation failed during setup: {e.strerror}", file=sys.stderr) + raise SystemExit(125) from None + except Exception: # noqa: BLE001 - fail closed, without leaking arguments or paths + # Paths, argv and errors could contain credentials. Fail closed without their values. + print("process isolation failed during setup", file=sys.stderr) + raise SystemExit(125) from None diff --git a/world/src/flock/models.py b/world/src/flock/models.py new file mode 100644 index 0000000000000000000000000000000000000000..12983c80e5c44a2889f8a2d7b0bb8c0342ec735f --- /dev/null +++ b/world/src/flock/models.py @@ -0,0 +1,2009 @@ +"""Shared contracts between controller, worker and CLI. + +This file is the contract. Everything in docs/design.md "Contracts" +is expressed here. Change it deliberately and update the design doc. +""" + +from __future__ import annotations + +import hashlib +import re +from datetime import UTC, date, datetime, timedelta +from enum import StrEnum +from typing import Any, Literal, NamedTuple + +import yaml +from pydantic import BaseModel, Field, field_validator, model_serializer, model_validator + +from flock.registry import COMPUTE, HARNESSES +from flock.world.protocol import TOOL_NAME_RE as WORLD_TOOL_RE +from flock.world.protocol import WorldManifest + +# --------------------------------------------------------------------------- spec YAML + + +class _SpecLoader(yaml.SafeLoader): + """SafeLoader with YAML 1.2 booleans: only true/false. YAML 1.1 (PyYAML's default) also + reads on/off/yes/no as booleans, so an `on:` key became `True`. + Dropping them in the loader protects every key and value of a spec, not just `loop.on`.""" + + +_BOOL = "tag:yaml.org,2002:bool" +_SpecLoader.yaml_implicit_resolvers = { + ch: [(tag, rx) for tag, rx in rs if tag != _BOOL] + for ch, rs in yaml.SafeLoader.yaml_implicit_resolvers.items() +} +_SpecLoader.add_implicit_resolver(_BOOL, re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"), + list("tTfF")) + + +def load_spec_yaml(text: str) -> Any: + """Parse spec YAML (safe, YAML 1.2 booleans); validate with `SwarmSpec.model_validate`.""" + return yaml.load(text, Loader=_SpecLoader) # a SafeLoader subclass + +# --------------------------------------------------------------------------- durations + +_DURATION_RE = re.compile(r"^\s*(\d+)\s*(ms|s|m|h|d)\s*$") +_UNIT_SECONDS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400} + + +def parse_duration(value: str | int | float | timedelta) -> timedelta: + """Parse '30s', '10m', '24h', '7d' (or a number of seconds) into a timedelta.""" + if isinstance(value, timedelta): + return value + if isinstance(value, (int, float)): + return timedelta(seconds=float(value)) + m = _DURATION_RE.match(value) + if not m: + raise ValueError(f"bad duration {value!r}; use e.g. 30s, 10m, 24h, 7d") + return timedelta(seconds=int(m.group(1)) * _UNIT_SECONDS[m.group(2)]) + + +def until_deadline(until: str, started_at: float) -> float: + """Epoch deadline of `while.until`: started_at + duration, or the ISO-8601 time (naive = UTC).""" + try: + return started_at + parse_duration(until).total_seconds() + except ValueError: + try: + t = datetime.fromisoformat(until) + except ValueError: + raise ValueError(f"bad until {until!r}; use a duration (2h) or a time (2026-10-28T20:00Z)") from None + return (t if t.tzinfo else t.replace(tzinfo=UTC)).timestamp() + + +# --------------------------------------------------------------------------- enums + + +# the names in flock.registry.HARNESSES; an enum so spec errors and the JSON schema list them +Harness = StrEnum("Harness", [(name, name) for name in HARNESSES], module=__name__) + + +class AgentState(StrEnum): + working = "working" # a harness process is running a turn + idle = "idle" # no process; idle_since set + stuck = "stuck" # a turn exceeded its timeout and was killed; cleared on next turn + unknown = "unknown" # heartbeat older than compute.worker_unknown_after (per-backend default) + dead = "dead" # heartbeat older than compute.worker_dead_after, or job terminal + + +class WorkerState(StrEnum): + launching = "launching" + running = "running" + draining = "draining" + unknown = "unknown" + dead = "dead" + + +class TypeHealth(StrEnum): + ok = "ok" + crashlooping = "crashlooping" + launch_refused = "launch_refused" # the backend refused the launch (4xx); waits for a new apply + + +# --------------------------------------------------------------------------- spec + +AGENT_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*-\d{4,}$") +TYPE_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$") +# Provider names prefix model strings ("hf:Qwen/..."), so no dots and no colons. A model string +# whose prefix does not look like this names no provider. +PROVIDER_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$") +ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +TOOLS_VERSION_RE = re.compile(r"^[0-9a-f]{16}$") +SELF_HOSTED_PRICING = [0.0, 0.0, 0.0] + +Reasoning = Literal["off", "low", "medium", "high"] +# `reasoning` -> OpenAI `reasoning.effort`. +REASONING_EFFORT = {"off": "none", "low": "low", "medium": "medium", "high": "high"} + + +def _pricing_row(v: list[float], where: str) -> list[float]: + if len(v) != 3 or any(x < 0 for x in v): + raise ValueError(f"{where}: pricing must be [input, output, cached] USD per 1M tokens, >= 0") + return [float(x) for x in v] + + +class ProviderSpec(BaseModel): + """Where a model is served (design.md 'Providers'). Field names follow swarmlab's + provider params so a `providers:` block moves between the two projects. + + `api_key_env` names a secret / env var; the value is never in the spec. The controller + sends that secret to the provider's jobs and uses it for preflight; the worker hands it to + the harness.""" + + type: Literal["openai_compat", "anthropic"] + base_url: str | None = None # openai_compat: required, ends in /v1; anthropic: API root + # Several servers of one model (openai_compat): preflight probes each and health scrapes each + # one's metrics; agents call `base_url`, which defaults to the first. + base_urls: list[str] | None = None + api_key_env: str + self_hosted: bool = False # price defaults to [0, 0, 0]; real cost is the GPU job's time + # Max agents of this swarm on this provider that may be in a turn at once. Enforced at + # prompt admission by the controller (FLOCK_MAX_WORKING_ENFORCE=0: report only). + max_working: int | None = None + pricing: dict[str, list[float]] = Field(default_factory=dict) # model id ("*" = any) -> row + timeout_s: float | None = None # passthrough to the harness / preflight + max_retries: int | None = None # passthrough to the harness + # How the key is sent. `anthropic` providers: "x-api-key" (default) or "bearer" + # (`Authorization: Bearer`), for gateways and proxies that only take a bearer token. `openai_compat` is always bearer. + auth: Literal["x-api-key", "bearer"] | None = None + # Scrape `/metrics` (vLLM Prometheus text) of each base URL into the swarm's + # health snapshots: num_requests_waiting / running, KV cache usage (docs/health.md). + metrics: bool = False + + @field_validator("base_urls", mode="before") + @classmethod + def _url_list(cls, v: Any) -> Any: + """A comma-separated string is a list (`base_urls: ${OPENAI_BASE_URLS:-}`); "" is none.""" + if isinstance(v, str): + return [u.strip() for u in v.split(",") if u.strip()] or None + return v + + @field_validator("api_key_env") + @classmethod + def _env_name(cls, v: str) -> str: + if not ENV_NAME_RE.match(v): + raise ValueError(f"api_key_env {v!r} must be an env var name (the key itself never goes in the spec)") + return v + + @field_validator("pricing") + @classmethod + def _rows(cls, v: dict[str, list[float]]) -> dict[str, list[float]]: + return {k: _pricing_row(row, f"pricing[{k!r}]") for k, row in v.items()} + + @field_validator("max_working") + @classmethod + def _positive(cls, v: int | None) -> int | None: + if v is not None and v < 1: + raise ValueError("max_working must be >= 1") + return v + + @model_validator(mode="after") + def _url(self) -> ProviderSpec: + if self.base_urls is not None: + urls = [u.strip().rstrip("/") for u in self.base_urls if u and u.strip()] + if not urls: + raise ValueError("base_urls must list at least one URL") + if len(set(urls)) != len(urls): + raise ValueError("base_urls must not repeat a URL") + if self.type != "openai_compat": + raise ValueError("base_urls is for openai_compat providers") + self.base_urls = urls + if self.base_url is None: + self.base_url = urls[0] + if self.type == "openai_compat" and not self.base_url: + raise ValueError("base_url is required for type openai_compat (e.g. https://router.huggingface.co/v1)") + if self.type == "openai_compat" and self.auth == "x-api-key": + raise ValueError("auth: x-api-key is for anthropic providers; openai_compat always sends a bearer token") + if self.base_url is not None: + self.base_url = self.base_url.rstrip("/") + return self + + @property + def endpoints(self) -> list[str]: + """The servers to spread agents over: `base_urls`, else `[base_url]`.""" + return list(self.base_urls) if self.base_urls else ([self.base_url] if self.base_url else []) + + +class ModelSpec(BaseModel): + """An alias under `models:`: a provider-prefixed model plus per-model settings.""" + + model: str # ":" + reasoning: Reasoning | None = None + # Raw request-body fields (swarmlab's `extra`). Not sent (Harbor's Pi cannot); kept for + # spec portability, with a warning at launch. + extra: dict[str, Any] | None = None + pricing: list[float] | None = None # overrides the provider's pricing for this alias + + @field_validator("pricing") + @classmethod + def _row(cls, v: list[float] | None) -> list[float] | None: + return None if v is None else _pricing_row(v, "pricing") + + +class ResolvedModel(BaseModel): + """A type's model after resolution, pinned into the stored spec at apply time.""" + + provider_name: str + provider: ProviderSpec + model_id: str # what the harness sends as `model` + reasoning: Reasoning | None = None + extra: dict[str, Any] | None = None + pricing: list[float] # [input, output, cached] USD per 1M tokens, pinned + + @property + def qualified(self) -> str: + return f"{self.provider_name}:{self.model_id}" + + +# --------------------------------------------------------------------------- comms (docs/comms.md) + +# Built-in comms tools a type may list in `tools:`; the model sees the bare name (`post`). +COMMS_TOOLS = ("comms:post", "comms:read", "comms:search") +EXTENDED_COMMS_TOOLS = ("comms:channels", "comms:create_channel", "comms:join_channel", + "comms:dm", "comms:read_dms", "comms:react", "comms:votes", "comms:doc", + "comms:edit_doc") +ALL_COMMS_TOOLS = COMMS_TOOLS + EXTENDED_COMMS_TOOLS +COMMS_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$") + + +def normalize_board_url(url: str) -> str: + """The one spelling of a board url, used wherever board urls are stored or compared (spec, + identities, board clients, message sources): scheme and host lowercased, default port and + trailing slashes dropped, IPv6 brackets and userinfo kept, so it is idempotent. + `http://Board.invalid:80/` -> `http://board.invalid`; `http://[::1]:8080/` -> `http://[::1]:8080`.""" + from urllib.parse import urlsplit, urlunsplit + + u = urlsplit(url.strip()) + scheme, host = u.scheme.lower(), (u.hostname or "").lower() + if ":" in host: # an IPv6 literal keeps its brackets: `http://[::1]:8080` + host = f"[{host}]" + port = u.port + netloc = host if port is None or (scheme, port) in (("http", 80), ("https", 443)) else f"{host}:{port}" + if u.username or u.password: + netloc = u.netloc.rsplit("@", 1)[0] + "@" + netloc + return urlunsplit((scheme, netloc, u.path.rstrip("/"), u.query, "")) + + +def comms_name(entry: str) -> str: + """`comms:post` -> `post`, the name the model sees.""" + return entry.split(":", 1)[1] + + +class CommsRules(BaseModel): + """Enforced by the worker before it calls the board; a refused post is a tool result + ("refused: ..."), never a board request. Live: a re-apply reaches workers by heartbeat.""" + + model_config = {"extra": "forbid"} + + min_post_gap: str | None = None # per agent, e.g. 20s + max_posts: int | None = None # per agent, for the run (kept in the agent's synced state) + max_len: int | None = None # characters per post + threads: Literal["per_topic"] | None = None # posts must say thread: new or a root id + max_channels_per_agent: int = Field(default=3, ge=1, le=100) + max_channels: int = Field(default=60, ge=1, le=100) + no_group_mentions: bool = False # refuse @all / @agents / @humans (and @everyone, @people) + + @field_validator("min_post_gap") + @classmethod + def _gap(cls, v: str | None) -> str | None: + if v is not None: + parse_duration(v) + return v + + @field_validator("max_posts", "max_len") + @classmethod + def _positive(cls, v: int | None) -> int | None: + if v is not None and v < 1: + raise ValueError("must be >= 1") + return v + + @property + def gap_s(self) -> float: + return parse_duration(self.min_post_gap).total_seconds() if self.min_post_gap else 0.0 + + +class CommsSpec(BaseModel): + """Swarm-level `comms:` (docs/comms.md). `url`, `invite_env` and `channel` are resolved + once by the controller at apply (channel name -> `channel_id`); `kickoff_file` and + `protocols` are files next to the spec that `flock launch` inlines (`kickoff`, + `protocols_text`), because the controller and workers cannot read the caller's files.""" + + model_config = {"extra": "forbid"} + + kind: Literal["msgboard"] = "msgboard" + extended: bool = False # multi-channel tools and serialized per-identity activity polling + # extended: each agent identity's feed is polled about once per this many seconds; the + # worker's poll interval is max(2 s, poll_cycle_s / its agents). + poll_cycle_s: float | None = Field(default=None, ge=10, le=3600) # unset: 300 + url: str + # `space`: `flock init` duplicates `template` into a private per-run Space (`space`, default + # `