cmpatino HF Staff Claude Opus 5.5 commited on
Commit
4c782d0
·
1 Parent(s): ece467c

pybot client: answer slow calls with a ticket for pybot_wait; capture in a private object store; run the client isolated

Browse files
tasks/pybot-agent/pybot_mcp.py CHANGED
@@ -3,6 +3,8 @@
3
  Reads WORLD_URL and WORLD_TOKEN. tools/list is GET $WORLD_URL/manifest; tools/call is
4
  POST $WORLD_URL/tools/<name> with {"args": ...}. open_pr and run_bot get the caller's clone
5
  added as `workspace`: a binary patch against its merge-base with origin/main.
 
 
6
  `python3 pybot_mcp.py --self-test` runs the checks at the end of this file.
7
  """
8
 
@@ -16,6 +18,7 @@ import threading
16
  import time
17
  import urllib.error
18
  import urllib.request
 
19
 
20
  PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") # newest first
21
  MAX_PATCH = 750_000 # raw bytes; base64 and JSON must stay under the world's 1 MiB body cap
@@ -24,11 +27,19 @@ MAX_BYTES, MAX_FILES = 128 << 20, 10000 # the world's caps on the resulting tre
24
  CLONE_ARGS = {"open_pr": ("path", "pybot", ()), "run_bot": ("ref_or_path", "main", ("main",))}
25
  RETRY_STATUS, TRIES, RETRY_BUDGET_S = (429, 503), 3, 60
26
  CALL_TIMEOUT_S = 360 # run_bot may take 300 s plus the upload
 
 
 
 
 
 
 
27
  # Never run a command the clone configured, or let its diff settings change the patch format.
28
  SAFE_GIT = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false",
29
  "-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false")
30
 
31
  _out = threading.Lock()
 
32
 
33
 
34
  def log(msg):
@@ -69,8 +80,14 @@ def capture(path):
69
  root = _git(path, "rev-parse", "--show-toplevel").decode().strip()
70
  base = _git(root, "merge-base", "HEAD", "refs/remotes/origin/main").decode().strip()
71
  with tempfile.TemporaryDirectory() as tmp:
72
- # A private index of what the world gets: the clone's own index stays as it is.
73
- env = {**os.environ, "GIT_INDEX_FILE": os.path.join(tmp, "index")}
 
 
 
 
 
 
74
  _git(root, "read-tree", "HEAD", env=env)
75
  _git(root, "add", "--all", env=env)
76
  count, total = 0, 0
@@ -168,6 +185,45 @@ def tools():
168
 
169
 
170
  def call(name, args):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  args = dict(args or {})
172
  args.pop("workspace", None) # only this file captures it
173
  if name in CLONE_ARGS:
@@ -194,7 +250,7 @@ def handle(msg):
194
  answer = {}
195
  elif method == "tools/list":
196
  try:
197
- answer = {"tools": tools()}
198
  except ToolFailure as e:
199
  send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}})
200
  return
@@ -270,6 +326,7 @@ def self_test():
270
  assert self.path.startswith("/world/tools/"), self.path
271
  assert self.headers["X-World-Token"] == token
272
  seen.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
 
273
  status, headers, body = script.pop(0) if script else (200, (), {"ok": True,
274
  "result": "done"})
275
  self._answer(status, body, headers)
@@ -298,7 +355,11 @@ def self_test():
298
 
299
  env = {**os.environ, "WORLD_URL": f"http://127.0.0.1:{server.server_port}/world",
300
  "WORLD_TOKEN": token}
301
- proc = subprocess.Popen([sys.executable, os.path.abspath(__file__)], cwd=tmp, env=env,
 
 
 
 
302
  stdin=subprocess.PIPE, stdout=subprocess.PIPE,
303
  stderr=subprocess.PIPE, text=True)
304
 
@@ -322,8 +383,14 @@ def self_test():
322
  schema = listed["open_pr"]["inputSchema"]
323
  assert "workspace" not in schema["properties"] and schema["required"] == ["title"]
324
 
325
- # open_pr: the patch applies to the base and reproduces the clone
 
 
 
 
 
326
  out = tool(4, "open_pr", {"title": "t"})
 
327
  assert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, out
328
  ws = seen[-1]["args"]["workspace"]
329
  check = os.path.join(tmp, "check")
@@ -364,7 +431,19 @@ def self_test():
364
  assert out["isError"] and "split the change" in out["content"][0]["text"], out
365
  assert len(seen) == n
366
 
367
- assert rpc(9, "nope")["error"]["code"] == -32601
 
 
 
 
 
 
 
 
 
 
 
 
368
  proc.stdin.close()
369
  proc.wait(10)
370
  assert token not in proc.stderr.read()
 
3
  Reads WORLD_URL and WORLD_TOKEN. tools/list is GET $WORLD_URL/manifest; tools/call is
4
  POST $WORLD_URL/tools/<name> with {"args": ...}. open_pr and run_bot get the caller's clone
5
  added as `workspace`: a binary patch against its merge-base with origin/main.
6
+ A world call still running after WAIT_S answers with a ticket that pybot_wait redeems: MCP
7
+ hosts may give up on a tool call after 60 s.
8
  `python3 pybot_mcp.py --self-test` runs the checks at the end of this file.
9
  """
10
 
 
18
  import time
19
  import urllib.error
20
  import urllib.request
21
+ from concurrent.futures import Future, TimeoutError as FutureTimeout
22
 
23
  PROTOCOLS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") # newest first
24
  MAX_PATCH = 750_000 # raw bytes; base64 and JSON must stay under the world's 1 MiB body cap
 
27
  CLONE_ARGS = {"open_pr": ("path", "pybot", ()), "run_bot": ("ref_or_path", "main", ("main",))}
28
  RETRY_STATUS, TRIES, RETRY_BUDGET_S = (429, 503), 3, 60
29
  CALL_TIMEOUT_S = 360 # run_bot may take 300 s plus the upload
30
+ WAIT_S = 50 # longest a tools/call answer may take; the self-test lowers it
31
+ MAX_TICKETS = 32
32
+ WAIT_TOOL = {"name": "pybot_wait", "description": (
33
+ "Wait up to 50 s for a pybot call that answered {\"status\": \"running\", \"ticket\": N} "
34
+ "and return its result, or the same running answer. Tickets last until your turn ends."),
35
+ "inputSchema": {"type": "object", "required": ["ticket"],
36
+ "properties": {"ticket": {"type": "integer"}}}}
37
  # Never run a command the clone configured, or let its diff settings change the patch format.
38
  SAFE_GIT = ("-c", "core.fsmonitor=false", "-c", "diff.noprefix=false",
39
  "-c", "diff.mnemonicPrefix=false", "-c", "diff.relative=false")
40
 
41
  _out = threading.Lock()
42
+ _tickets, _tickets_lock, _next_ticket = {}, threading.Lock(), [1] # ticket -> Future
43
 
44
 
45
  def log(msg):
 
80
  root = _git(path, "rev-parse", "--show-toplevel").decode().strip()
81
  base = _git(root, "merge-base", "HEAD", "refs/remotes/origin/main").decode().strip()
82
  with tempfile.TemporaryDirectory() as tmp:
83
+ # A private index and object store for what the world gets: the clone's own index and
84
+ # .git/objects stay as they are (git add writes a blob for every untracked file).
85
+ objects = os.path.abspath(os.path.join(
86
+ root, _git(root, "rev-parse", "--git-path", "objects").decode().strip()))
87
+ os.mkdir(os.path.join(tmp, "objects"))
88
+ env = {**os.environ, "GIT_INDEX_FILE": os.path.join(tmp, "index"),
89
+ "GIT_OBJECT_DIRECTORY": os.path.join(tmp, "objects"),
90
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": objects}
91
  _git(root, "read-tree", "HEAD", env=env)
92
  _git(root, "add", "--all", env=env)
93
  count, total = 0, 0
 
185
 
186
 
187
  def call(name, args):
188
+ if name == WAIT_TOOL["name"]:
189
+ return wait((args or {}).get("ticket"))
190
+ with _tickets_lock:
191
+ if len(_tickets) >= MAX_TICKETS:
192
+ raise ToolFailure(f"{MAX_TICKETS} pybot calls are still running: call pybot_wait "
193
+ f"on their tickets ({sorted(_tickets)}) before starting more")
194
+ ticket, _next_ticket[0] = _next_ticket[0], _next_ticket[0] + 1
195
+ _tickets[ticket] = Future()
196
+ threading.Thread(target=_run, args=(ticket, name, args), daemon=True).start()
197
+ return wait(ticket)
198
+
199
+
200
+ def _run(ticket, name, args):
201
+ future = _tickets[ticket]
202
+ try:
203
+ future.set_result(world_call(name, args))
204
+ except BaseException as e: # ToolFailure, or a bug: either is the ticket's answer
205
+ future.set_exception(e)
206
+
207
+
208
+ def wait(ticket):
209
+ """The ticket's result (forgetting the ticket), or a "running" answer after WAIT_S."""
210
+ future = _tickets.get(ticket) if isinstance(ticket, int) else None
211
+ if future is None:
212
+ raise ToolFailure(f"unknown ticket {ticket!r}: tickets last until your turn ends; "
213
+ "call the tool again")
214
+ try:
215
+ out = future.result(WAIT_S)
216
+ except FutureTimeout:
217
+ return {"status": "running", "ticket": ticket,
218
+ "message": "still running; call pybot_wait with this ticket to get the result"}
219
+ except BaseException:
220
+ _tickets.pop(ticket, None)
221
+ raise
222
+ _tickets.pop(ticket, None)
223
+ return out
224
+
225
+
226
+ def world_call(name, args):
227
  args = dict(args or {})
228
  args.pop("workspace", None) # only this file captures it
229
  if name in CLONE_ARGS:
 
250
  answer = {}
251
  elif method == "tools/list":
252
  try:
253
+ answer = {"tools": tools() + [WAIT_TOOL]}
254
  except ToolFailure as e:
255
  send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32603, "message": str(e)}})
256
  return
 
326
  assert self.path.startswith("/world/tools/"), self.path
327
  assert self.headers["X-World-Token"] == token
328
  seen.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
329
+ time.sleep(seen[-1]["args"].get("delay", 0))
330
  status, headers, body = script.pop(0) if script else (200, (), {"ok": True,
331
  "result": "done"})
332
  self._answer(status, body, headers)
 
355
 
356
  env = {**os.environ, "WORLD_URL": f"http://127.0.0.1:{server.server_port}/world",
357
  "WORLD_TOKEN": token}
358
+ # Short waits so a slow call gets a ticket quickly; one ticket at most to test the cap.
359
+ here = os.path.dirname(os.path.abspath(__file__))
360
+ code = (f"import sys; sys.path.insert(0, {here!r}); import pybot_mcp as m; "
361
+ "m.WAIT_S, m.MAX_TICKETS = 3, 1; m.serve()")
362
+ proc = subprocess.Popen([sys.executable, "-c", code], cwd=tmp, env=env,
363
  stdin=subprocess.PIPE, stdout=subprocess.PIPE,
364
  stderr=subprocess.PIPE, text=True)
365
 
 
383
  schema = listed["open_pr"]["inputSchema"]
384
  assert "workspace" not in schema["properties"] and schema["required"] == ["title"]
385
 
386
+ # open_pr: the patch applies to the base and reproduces the clone, whose objects and
387
+ # index stay untouched
388
+ def state():
389
+ return [(d, sorted(fs)) for d, _, fs in os.walk(os.path.join(clone, ".git", "objects"))
390
+ ] + [os.stat(os.path.join(clone, ".git", "index")).st_mtime_ns]
391
+ before = state()
392
  out = tool(4, "open_pr", {"title": "t"})
393
+ assert state() == before
394
  assert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, out
395
  ws = seen[-1]["args"]["workspace"]
396
  check = os.path.join(tmp, "check")
 
431
  assert out["isError"] and "split the change" in out["content"][0]["text"], out
432
  assert len(seen) == n
433
 
434
+ # a call slower than WAIT_S answers with a ticket that pybot_wait redeems
435
+ assert "pybot_wait" in listed
436
+ out = tool(9, "list_prs", {"delay": 5})
437
+ running = json.loads(out["content"][0]["text"])
438
+ assert not out["isError"] and running["status"] == "running", out
439
+ out = tool(10, "list_prs", {})
440
+ assert out["isError"] and "still running" in out["content"][0]["text"], out
441
+ out = tool(11, "pybot_wait", {"ticket": running["ticket"]})
442
+ assert out == {"content": [{"type": "text", "text": '"done"'}], "isError": False}, out
443
+ out = tool(12, "pybot_wait", {"ticket": running["ticket"]})
444
+ assert out["isError"] and "unknown ticket" in out["content"][0]["text"], out
445
+
446
+ assert rpc(13, "nope")["error"]["code"] == -32601
447
  proc.stdin.close()
448
  proc.wait(10)
449
  assert token not in proc.stderr.read()
tasks/pybot-agent/task.toml CHANGED
@@ -36,4 +36,4 @@ GIT_CONFIG_PARAMETERS = "'pack.windowMemory=256m' 'pack.threads=1' 'gc.auto=0'"
36
  name = "pybot"
37
  transport = "stdio"
38
  command = "sh"
39
- 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"']
 
36
  name = "pybot"
37
  transport = "stdio"
38
  command = "sh"
39
+ 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"']