pybot client: answer slow calls with a ticket for pybot_wait; capture in a private object store; run the client isolated
Browse filesFiles changed (2)
2 unmodified lines3456787 unmodified lines1617181920212 unmodified lines242526272829303132333434 unmodified lines697071727374757691 unmodified lines16816917017117217320 unmodified lines19419519619719819920069 unmodified lines27027127227327427522 unmodified lines29829930030130230330417 unmodified lines32232332432532632732832934 unmodified lines3643653663673683693702 unmodified linesReads WORLD_URL and WORLD_TOKEN. tools/list is GET $WORLD_URL/manifest; tools/call isPOST $WORLD_URL/tools/<name> with {"args": ...}. open_pr and run_bot get the caller's cloneadded as `workspace`: a binary patch against its merge-base with origin/main.`python3 pybot_mcp.py --self-test` runs the checks at the end of this file."""7 unmodified linesimport timeimport urllib.errorimport urllib.requestPROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") # newest firstMAX_PATCH = 750_000 # raw bytes; base64 and JSON must stay under the world's 1 MiB body cap2 unmodified linesCLONE_ARGS = {"open_pr": ("path", "pybot", ()), "run_bot": ("ref_or_path", "main", ("main",))}RETRY_STATUS, TRIES, RETRY_BUDGET_S = (429, 503), 3, 60CALL_TIMEOUT_S = 360 # run_bot may take 300 s plus the upload# Never run a command the clone configured, or let its diff settings change the patch format.SAFE_GIT = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false","-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false")_out = threading.Lock()def log(msg):34 unmodified linesroot = _git(path, "rev-parse", "--show-toplevel").decode().strip()base = _git(root, "merge-base", "HEAD", "refs/remotes/origin/main").decode().strip()with tempfile.TemporaryDirectory() as tmp:# A private index of what the world gets: the clone's own index stays as it is.env = {**os.environ, "GIT_INDEX_FILE": os.path.join(tmp, "index")}_git(root, "read-tree", "HEAD", env=env)_git(root, "add", "--all", env=env)count, total = 0, 091 unmodified linesdef call(name, args):args = dict(args or {})args.pop("workspace", None) # only this file captures itif name in CLONE_ARGS:20 unmodified linesanswer = {}elif method == "tools/list":try:answer = {"tools": tools()}except ToolFailure as e:send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}})return69 unmodified linesassert self.path.startswith("/world/tools/"), self.pathassert self.headers["X-World-Token"] == tokenseen.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))status, headers, body = script.pop(0) if script else (200, (), {"ok": True,"result": "done"})self._answer(status, body, headers)22 unmodified linesenv = {**os.environ, "WORLD_URL": f"http://127.0.0.1:{server.server_port}/world","WORLD_TOKEN": token}proc = subprocess.Popen([sys.executable, os.path.abspath(__file__)], cwd=tmp, env=env,stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, text=True)17 unmodified linesschema = listed["open_pr"]["inputSchema"]assert "workspace" not in schema["properties"] and schema["required"] == ["title"]# open_pr: the patch applies to the base and reproduces the cloneout = tool(4, "open_pr", {"title": "t"})assert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, outws = seen[-1]["args"]["workspace"]check = os.path.join(tmp, "check")34 unmodified linesassert out["isError"] and "split the change" in out["content"][0]["text"], outassert len(seen) == nassert rpc(9, "nope")["error"]["code"] == -32601proc.stdin.close()proc.wait(10)assert token not in proc.stderr.read()2 unmodified lines3456789107 unmodified lines181920212223242 unmodified lines2728293031323334353637383940414243444534 unmodified lines808182838485868788899091929391 unmodified lines18518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822920 unmodified lines25025125225325425525669 unmodified lines32632732832933033133222 unmodified lines35535635735835936036136236336436517 unmodified lines38338438538638738838939039139239339439539634 unmodified lines4314324334344354364374384394404414424434444454464474484492 unmodified linesReads WORLD_URL and WORLD_TOKEN. tools/list is GET $WORLD_URL/manifest; tools/call isPOST $WORLD_URL/tools/<name> with {"args": ...}. open_pr and run_bot get the caller's cloneadded as `workspace`: a binary patch against its merge-base with origin/main.A world call still running after WAIT_S answers with a ticket that pybot_wait redeems: MCPhosts may give up on a tool call after 60 s.`python3 pybot_mcp.py --self-test` runs the checks at the end of this file."""7 unmodified linesimport timeimport urllib.errorimport urllib.requestfrom concurrent.futures import Future, TimeoutError as FutureTimeoutPROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") # newest firstMAX_PATCH = 750_000 # raw bytes; base64 and JSON must stay under the world's 1 MiB body cap2 unmodified linesCLONE_ARGS = {"open_pr": ("path", "pybot", ()), "run_bot": ("ref_or_path", "main", ("main",))}RETRY_STATUS, TRIES, RETRY_BUDGET_S = (429, 503), 3, 60CALL_TIMEOUT_S = 360 # run_bot may take 300 s plus the uploadWAIT_S = 50 # longest a tools/call answer may take; the self-test lowers itMAX_TICKETS = 32WAIT_TOOL = {"name": "pybot_wait", "description": ("Wait up to 50 s for a pybot call that answered {\"status\": \"running\", \"ticket\": N} ""and return its result, or the same running answer. Tickets last until your turn ends."),"inputSchema": {"type": "object", "required": ["ticket"],"properties": {"ticket": {"type": "integer"}}}}# Never run a command the clone configured, or let its diff settings change the patch format.SAFE_GIT = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false","-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false")_out = threading.Lock()_tickets, _tickets_lock, _next_ticket = {}, threading.Lock(), [1] # ticket -> Futuredef log(msg):34 unmodified linesroot = _git(path, "rev-parse", "--show-toplevel").decode().strip()base = _git(root, "merge-base", "HEAD", "refs/remotes/origin/main").decode().strip()with tempfile.TemporaryDirectory() as tmp:# A private index and object store for what the world gets: the clone's own index and# .git/objects stay as they are (git add writes a blob for every untracked file).objects = os.path.abspath(os.path.join(root, _git(root, "rev-parse", "--git-path", "objects").decode().strip()))os.mkdir(os.path.join(tmp, "objects"))env = {**os.environ, "GIT_INDEX_FILE": os.path.join(tmp, "index"),"GIT_OBJECT_DIRECTORY": os.path.join(tmp, "objects"),"GIT_ALTERNATE_OBJECT_DIRECTORIES": objects}_git(root, "read-tree", "HEAD", env=env)_git(root, "add", "--all", env=env)count, total = 0, 091 unmodified linesdef call(name, args):if name == WAIT_TOOL["name"]:return wait((args or {}).get("ticket"))with _tickets_lock:if len(_tickets) >= MAX_TICKETS:raise ToolFailure(f"{MAX_TICKETS} pybot calls are still running: call pybot_wait "f"on their tickets ({sorted(_tickets)}) before starting more")ticket, _next_ticket[0] = _next_ticket[0], _next_ticket[0] + 1_tickets[ticket] = Future()threading.Thread(target=_run, args=(ticket, name, args), daemon=True).start()return wait(ticket)def _run(ticket, name, args):future = _tickets[ticket]try:future.set_result(world_call(name, args))except BaseException as e: # ToolFailure, or a bug: either is the ticket's answerfuture.set_exception(e)def wait(ticket):"""The ticket's result (forgetting the ticket), or a "running" answer after WAIT_S."""future = _tickets.get(ticket) if isinstance(ticket, int) else Noneif future is None:raise ToolFailure(f"unknown ticket {ticket!r}: tickets last until your turn ends; ""call the tool again")try:out = future.result(WAIT_S)except FutureTimeout:return {"status": "running", "ticket": ticket,"message": "still running; call pybot_wait with this ticket to get the result"}except BaseException:_tickets.pop(ticket, None)raise_tickets.pop(ticket, None)return outdef world_call(name, args):args = dict(args or {})args.pop("workspace", None) # only this file captures itif name in CLONE_ARGS:20 unmodified linesanswer = {}elif method == "tools/list":try:answer = {"tools": tools() + [WAIT_TOOL]}except ToolFailure as e:send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}})return69 unmodified linesassert self.path.startswith("/world/tools/"), self.pathassert self.headers["X-World-Token"] == tokenseen.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))time.sleep(seen[-1]["args"].get("delay", 0))status, headers, body = script.pop(0) if script else (200, (), {"ok": True,"result": "done"})self._answer(status, body, headers)22 unmodified linesenv = {**os.environ, "WORLD_URL": f"http://127.0.0.1:{server.server_port}/world","WORLD_TOKEN": token}# Short waits so a slow call gets a ticket quickly; one ticket at most to test the cap.here = os.path.dirname(os.path.abspath(__file__))code = (f"import sys; sys.path.insert(0, {here!r}); import pybot_mcp as m; ""m.WAIT_S, m.MAX_TICKETS = 3, 1; m.serve()")proc = subprocess.Popen([sys.executable, "-c", code], cwd=tmp, env=env,stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, text=True)17 unmodified linesschema = listed["open_pr"]["inputSchema"]assert "workspace" not in schema["properties"] and schema["required"] == ["title"]# open_pr: the patch applies to the base and reproduces the clone, whose objects and# index stay untoucheddef state():return [(d, sorted(fs)) for d, _, fs in os.walk(os.path.join(clone, ".git", "objects"))] + [os.stat(os.path.join(clone, ".git", "index")).st_mtime_ns]before = state()out = tool(4, "open_pr", {"title": "t"})assert state() == beforeassert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, outws = seen[-1]["args"]["workspace"]check = os.path.join(tmp, "check")34 unmodified linesassert out["isError"] and "split the change" in out["content"][0]["text"], outassert len(seen) == n# a call slower than WAIT_S answers with a ticket that pybot_wait redeemsassert "pybot_wait" in listedout = tool(9, "list_prs", {"delay": 5})running = json.loads(out["content"][0]["text"])assert not out["isError"] and running["status"] == "running", outout = tool(10, "list_prs", {})assert out["isError"] and "still running" in out["content"][0]["text"], outout = tool(11, "pybot_wait", {"ticket": running["ticket"]})assert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, outout = tool(12, "pybot_wait", {"ticket": running["ticket"]})assert out["isError"] and "unknown ticket" in out["content"][0]["text"], outassert rpc(13, "nope")["error"]["code"] == -32601proc.stdin.close()proc.wait(10)assert token not in proc.stderr.read()
35 unmodified lines3637383935 unmodified linesname = "pybot"transport = "stdio"command = "sh"args = ["-c", 'set -e; f=/tmp/pybot_mcp-aff1fbab24c4039b32c903618c837c6390f7794d.py; s=949d852427bbceddaee4efa5db7bcbde8127c1fe08d99cac200d12cf82452aac; if ! echo "$s $f" | sha256sum -c --status 2>/dev/null; then t=$(mktemp); curl -fsSL --retry 3 -o "$t" https://huggingface.co/datasets/HuggingFaceSwarms/pybot/resolve/aff1fbab24c4039b32c903618c837c6390f7794d/tasks/pybot-agent/pybot_mcp.py; if echo "$s $t" | sha256sum -c --status; then mv "$t" "$f"; else rm -f "$t"; echo "pybot_mcp.py: checksum mismatch" >&2; exit 1; fi; fi; exec python3 "$f"']35 unmodified lines3637383935 unmodified linesname = "pybot"transport = "stdio"command = "sh"args = ["-c", 'set -e; f=/tmp/pybot_mcp-aff1fbab24c4039b32c903618c837c6390f7794d.py; s=949d852427bbceddaee4efa5db7bcbde8127c1fe08d99cac200d12cf82452aac; if ! echo "$s $f" | sha256sum -c --status 2>/dev/null; then t=$(mktemp); curl -fsSL --retry 3 -o "$t" https://huggingface.co/datasets/HuggingFaceSwarms/pybot/resolve/aff1fbab24c4039b32c903618c837c6390f7794d/tasks/pybot-agent/pybot_mcp.py || { rm -f "$t"; exit 1; }; if echo "$s $t" | sha256sum -c --status; then mv "$t" "$f"; else rm -f "$t"; echo "pybot_mcp.py: checksum mismatch" >&2; exit 1; fi; fi; exec python3 -I "$f"']
tasks/pybot-agent/pybot_mcp.py+85-6
tasks/pybot-agent/task.toml+1-1