Download world/scripts/smoke-local.py from HuggingFaceSwarms/pybot: direct link, hf CLI and curl.
- Browser
- Download file 6.44 kB
-
https://huggingface.co/datasets/HuggingFaceSwarms/pybot/resolve/main/world/scripts/smoke-local.py
- Command line
-
hf download hf://datasets/HuggingFaceSwarms/pybot/world/scripts/smoke-local.py
-
curl -L -o smoke-local.py https://huggingface.co/datasets/HuggingFaceSwarms/pybot/resolve/main/world/scripts/smoke-local.py
6.44 kB
| """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-Legion-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 legion.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@legion.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 legion.world.protocol import agent_token | |
| own = agent_token(TOKEN, "smoke") | |
| assert call(port, "GET", "/manifest", token=own)[0] == 200 | |
| assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401 | |
| print("ok GET /manifest with the agent's own token: 200; as another agent: 401") | |
| status, m = call(port, "GET", "/manifest") | |
| 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:]) | |