cmpatino HF Staff Claude Opus 5.5 commited on
Commit
bd4a7bb
·
1 Parent(s): 8b9329d

world: serve a plain HTTP API without external world libraries

Browse files

The world now runs on its own small HTTP server (server.py, standard library)
with per-seat agent credentials from PYBOT_TOKEN_<seat> (Bearer or
X-World-Token): POST /v1/tools/<name> with flat arguments, the direct
GET /world/manifest and POST /world/tools/<name> routes with the
{"ok", ...} envelope, /healthz, and /metrics and /admin behind
PYBOT_ADMIN_TOKEN. Admission control (429 + Retry-After) and parked mode
are kept.

open_pr and run_bot take the agent's change as a workspace argument
{base_sha, patch} (patch only); a missing base is fetched from the Hub,
else the call fails with unknown_base. Tool schemas come from the tool
methods' type hints and docstrings (api.py). The lanes, state store and
process isolation are vendored; bucket snapshots use huggingface_hub
directly. requirements.txt lists only huggingface_hub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

world/Dockerfile CHANGED
@@ -1,26 +1,20 @@
1
- # pybot world image: World API v1 on $PORT (7860). Build from this directory:
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
- # 3.12+); Python deps are legion's own uv.lock (exact versions + hashes), and legion itself is
6
- # installed at the commit that lock comes from (README, "The legion pin").
7
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
8
 
9
- # git: the world's bare repo, fetches and pushes to the Hub, and pip's legion checkout.
10
- # util-linux (unshare) ships in the base.
11
  RUN apt-get update \
12
  && apt-get install -y --no-install-recommends git \
13
  && rm -rf /var/lib/apt/lists/*
14
 
15
  COPY requirements.txt /opt/world/requirements.txt
16
- RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
17
 
18
- # legion's World API library, pinned to a commit (pip cannot hash a git requirement, so it gets its
19
- # own install). --no-deps: its deps are the hashed ones above; the world needs no Harbor or board.
20
- RUN pip install --no-cache-dir --no-deps \
21
- "legion @ git+https://github.com/huggingface/legion@803873b114d5e04a3a01fea5e2e9084a03596fab"
22
-
23
- COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/
24
  COPY seed/ /opt/world/seed/
25
  COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
26
 
 
1
+ # pybot world image: its HTTP API (server.py) on $PORT (7860). Build from this directory:
2
  # docker build -t <registry>/pybot-world:<tag> world/
3
  # The same image runs the bot sandbox sidecar (command `python sandbox.py serve`). The base is
4
  # pinned by digest (3.12: the seed's bot imports `copy`, which the bot sandbox allows only on
5
+ # 3.12+). The world's only Python dependency is huggingface_hub (requirements.txt).
 
6
  FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
7
 
8
+ # git: the world's bare repo, fetches and pushes to the Hub.
9
+ # util-linux (unshare, prlimit) ships in the base.
10
  RUN apt-get update \
11
  && apt-get install -y --no-install-recommends git \
12
  && rm -rf /var/lib/apt/lists/*
13
 
14
  COPY requirements.txt /opt/world/requirements.txt
15
+ RUN pip install --no-cache-dir -r /opt/world/requirements.txt
16
 
17
+ COPY *.py /opt/world/
 
 
 
 
 
18
  COPY seed/ /opt/world/seed/
19
  COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
20
 
world/api.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The world's tool layer: `@tool` methods of a `World` subclass, their JSON schemas (from the type
2
+ hints and the docstring's first paragraph), argument checks, runtime knobs and lane pauses
3
+ (the admin API, saved in `knobs.json`), and secret redaction. `server.py` serves it over HTTP.
4
+
5
+ A parameter named `agent` (or annotated `Agent`) receives the caller and is never shown in the
6
+ schema.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import inspect
11
+ import json
12
+ import logging
13
+ import os
14
+ import re
15
+ import threading
16
+ import types
17
+ import typing
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ log = logging.getLogger(__name__)
24
+ POOLS = ("fast", "slow")
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Agent:
29
+ """Who calls: the agent's name (from its credential) and the request id, if one was sent."""
30
+
31
+ name: str
32
+ request_id: str = ""
33
+
34
+
35
+ class ToolError(Exception):
36
+ """Raise from a tool: the agent reads `message` as the tool's error result.
37
+ `retry_after_s`: the call cannot succeed before then (a budget, a busy backend)."""
38
+
39
+ def __init__(self, message: str, code: str = "tool_error",
40
+ retry_after_s: float | None = None) -> None:
41
+ super().__init__(message)
42
+ self.code = code
43
+ self.message = message
44
+ self.retry_after_s = retry_after_s
45
+
46
+
47
+ def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = False) -> Any:
48
+ """Mark a method as a tool: `@tool`, or `@tool(pool="slow", read_only=True)`. `pool`: the
49
+ server's thread pool for the call ("slow" for tools that block for seconds). `read_only`:
50
+ the tool changes nothing (manifest `annotations.readOnlyHint`)."""
51
+ if pool not in POOLS:
52
+ raise ValueError(f"pool {pool!r} must be one of {POOLS}")
53
+
54
+ def mark(f: Callable) -> Callable:
55
+ f.world_tool = {"pool": pool, "read_only": read_only} # type: ignore[attr-defined]
56
+ return f
57
+
58
+ return mark if fn is None else mark(fn)
59
+
60
+
61
+ # ------------------------------------------------------------------ schemas and argument checks
62
+
63
+ def _is_agent(name: str, hint: Any) -> bool:
64
+ return name == "agent" or hint is Agent
65
+
66
+
67
+ def type_schema(hint: Any) -> dict[str, Any]:
68
+ """The JSON schema of a type hint: str, int, float, bool, list[...], dict, Literal[...],
69
+ X | None (accepts null too)."""
70
+ origin, args = typing.get_origin(hint), typing.get_args(hint)
71
+ if origin in (typing.Union, types.UnionType):
72
+ rest = [a for a in args if a is not type(None)]
73
+ if len(rest) != 1 or len(rest) == len(args):
74
+ raise TypeError(f"unions other than `X | None` are not supported: {hint!r}")
75
+ schema = type_schema(rest[0])
76
+ schema["type"] = [schema["type"], "null"]
77
+ if "enum" in schema:
78
+ schema["enum"] = [*schema["enum"], None]
79
+ return schema
80
+ simple = {str: "string", bool: "boolean", int: "integer", float: "number", dict: "object"}
81
+ if hint in simple or origin is dict:
82
+ return {"type": simple[dict if origin is dict else hint]}
83
+ if origin is list:
84
+ return {"type": "array", "items": type_schema(args[0]) if args else {}}
85
+ if origin is typing.Literal:
86
+ kinds = {type(a) for a in args}
87
+ return {"type": "string" if kinds == {str} else "integer", "enum": list(args)}
88
+ raise TypeError(f"unsupported type {hint!r}")
89
+
90
+
91
+ def tool_schema(fn: Callable) -> dict[str, Any]:
92
+ """{name, description, parameters} of a tool function or method."""
93
+ hints = typing.get_type_hints(fn)
94
+ props, required = {}, []
95
+ for p in inspect.signature(fn).parameters.values():
96
+ if p.name == "self" or _is_agent(p.name, hints.get(p.name)):
97
+ continue
98
+ props[p.name] = schema = type_schema(hints[p.name])
99
+ if p.default is p.empty:
100
+ required.append(p.name)
101
+ elif p.default is not None:
102
+ schema["default"] = p.default
103
+ params: dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False}
104
+ if required:
105
+ params["required"] = required
106
+ doc = inspect.getdoc(fn) or ""
107
+ return {"name": fn.__name__, "description": " ".join(doc.split("\n\n")[0].split()),
108
+ "parameters": params}
109
+
110
+
111
+ _JSON_TYPES = {"string": (str,), "integer": (int,), "number": (int, float), "boolean": (bool,),
112
+ "array": (list,), "object": (dict,), "null": (type(None),)}
113
+
114
+
115
+ def _check(schema: dict[str, Any], value: Any, where: str) -> str | None:
116
+ t = schema.get("type")
117
+ types_ = [t] if isinstance(t, str) else t or []
118
+ if types_ and not any(isinstance(value, _JSON_TYPES[x]) and not (
119
+ x in ("integer", "number") and isinstance(value, bool)) for x in types_):
120
+ return f"{where} must be {' or '.join(types_)}, got {json.dumps(value)[:60]}"
121
+ if "enum" in schema and value not in schema["enum"]:
122
+ return f"{where} must be one of {schema['enum']}, got {json.dumps(value)[:60]}"
123
+ if isinstance(value, list) and schema.get("items"):
124
+ for i, v in enumerate(value):
125
+ if err := _check(schema["items"], v, f"{where}[{i}]"):
126
+ return err
127
+ return None
128
+
129
+
130
+ def check_args(params: dict[str, Any], args: Any) -> str | None:
131
+ """An error message for arguments that do not fit the tool's schema, else None."""
132
+ if not isinstance(args, dict):
133
+ return f"arguments must be a JSON object, got {type(args).__name__}"
134
+ props = params["properties"]
135
+ if unknown := [k for k in args if k not in props]:
136
+ return f"unknown argument(s) {', '.join(unknown)}; expected: {', '.join(props) or 'none'}"
137
+ if missing := [k for k in params.get("required", ()) if k not in args]:
138
+ return f"missing required argument(s): {', '.join(missing)}"
139
+ return next((err for k, v in args.items() if (err := _check(props[k], v, k))), None)
140
+
141
+
142
+ # ------------------------------------------------------------------ secrets
143
+
144
+ _SECRET_NAME = re.compile(r"TOKEN|SECRET|PASSWORD|INVITE|API_KEY|_KEY$", re.IGNORECASE)
145
+
146
+
147
+ def redact(value: Any) -> Any:
148
+ """`value` (JSON-able) with the value of every secret-looking environment variable (8+
149
+ characters) replaced by "[redacted]"."""
150
+ secrets = sorted({v for k, v in os.environ.items() if _SECRET_NAME.search(k) and len(v) >= 8},
151
+ key=len, reverse=True)
152
+ text = json.dumps(value, default=str)
153
+ if not any(s in text for s in secrets):
154
+ return value
155
+ for s in secrets:
156
+ text = text.replace(json.dumps(s)[1:-1], "[redacted]")
157
+ return json.loads(text)
158
+
159
+
160
+ # ------------------------------------------------------------------ admin: knobs and lane pauses
161
+
162
+ LANE_RE = re.compile(r"^[a-z][a-z0-9_.-]{0,63}$")
163
+ KNOB_TYPES = (int, float, bool, str)
164
+
165
+
166
+ @dataclass
167
+ class Knob:
168
+ name: str
169
+ type: type
170
+ default: Any
171
+ min: float | None = None
172
+ max: float | None = None
173
+ doc: str = ""
174
+ on_change: Callable[[Any], None] | None = None
175
+
176
+ def check(self, value: Any) -> Any:
177
+ """`value` as this knob's type (raises ValueError)."""
178
+ t = self.type
179
+ if t is bool or t is str:
180
+ ok = isinstance(value, t)
181
+ else: # int or float: JSON numbers, not booleans; 2.0 is an int, 2.5 is not
182
+ ok = isinstance(value, int | float) and not isinstance(value, bool) and (
183
+ t is float or float(value).is_integer())
184
+ if not ok:
185
+ raise ValueError(f"{self.name}: expected {t.__name__}, got {json.dumps(value)}")
186
+ value = t(value)
187
+ if self.min is not None and value < self.min:
188
+ raise ValueError(f"{self.name}: {value} is below the minimum {self.min:g}")
189
+ if self.max is not None and value > self.max:
190
+ raise ValueError(f"{self.name}: {value} is above the maximum {self.max:g}")
191
+ return value
192
+
193
+
194
+ class Admin:
195
+ """Knobs (name -> value) and paused lanes (lane -> reason), saved in `<state dir>/knobs.json`
196
+ and read back at the next start. Thread-safe."""
197
+
198
+ def __init__(self, state_dir: str | os.PathLike | None = None) -> None:
199
+ self.path = Path(state_dir) / "knobs.json" if state_dir is not None else None
200
+ self.knobs: dict[str, Knob] = {}
201
+ self.values: dict[str, Any] = {}
202
+ self.stored: dict[str, Any] = {} # values set through the admin API
203
+ self.paused: dict[str, str] = {}
204
+ self.lock = threading.RLock()
205
+ try:
206
+ data = json.loads(self.path.read_text()) if self.path else {}
207
+ knobs, paused = data.get("knobs") or {}, data.get("paused") or {}
208
+ if not isinstance(knobs, dict) or not isinstance(paused, dict) or not all(
209
+ isinstance(k, str) and isinstance(v, str) for k, v in paused.items()):
210
+ raise ValueError('expected {"knobs": {name: value}, "paused": {lane: reason}}')
211
+ self.stored, self.paused = dict(knobs), dict(paused)
212
+ except FileNotFoundError:
213
+ pass
214
+ except (OSError, ValueError, AttributeError) as e: # never fail the start over this file
215
+ log.warning("%s: unreadable (%s); starting from the defaults", self.path, e)
216
+
217
+ def register(self, knob: Knob) -> Any:
218
+ with self.lock:
219
+ value = knob.check(knob.default)
220
+ if knob.name in self.stored:
221
+ try:
222
+ value = knob.check(self.stored[knob.name])
223
+ except ValueError as e:
224
+ log.warning("knobs.json: stored value ignored: %s", e)
225
+ self.knobs[knob.name] = knob
226
+ self.values[knob.name] = value
227
+ return value
228
+
229
+ def describe(self) -> dict[str, dict[str, Any]]:
230
+ with self.lock:
231
+ return {n: {"value": self.values[n], "default": k.default, "type": k.type.__name__,
232
+ "min": k.min, "max": k.max, "doc": k.doc} for n, k in self.knobs.items()}
233
+
234
+ def set(self, updates: dict[str, Any]) -> list[dict[str, Any]]:
235
+ """Validate every update, apply them (on_change callbacks included) and save, all or
236
+ nothing. Returns [{name, old, new}]; raises ValueError (nothing changed) on a bad value
237
+ or a failing on_change (those already applied get on_change(old) back)."""
238
+ if not isinstance(updates, dict) or not updates:
239
+ raise ValueError("expected {knob: value, ...}")
240
+ with self.lock:
241
+ if unknown := sorted(set(updates) - set(self.knobs)):
242
+ raise ValueError(f"unknown knob(s) {', '.join(unknown)}; knobs: "
243
+ f"{', '.join(self.knobs) or 'none'}")
244
+ checked = {n: self.knobs[n].check(v) for n, v in updates.items()}
245
+ changes: list[dict[str, Any]] = []
246
+ for n, v in checked.items():
247
+ try:
248
+ if self.knobs[n].on_change is not None:
249
+ self.knobs[n].on_change(v)
250
+ except Exception as e: # noqa: BLE001 (any refusal rolls the patch back)
251
+ for c in reversed(changes):
252
+ try:
253
+ if self.knobs[c["name"]].on_change is not None:
254
+ self.knobs[c["name"]].on_change(c["old"])
255
+ except Exception:
256
+ log.exception("knob %s: restoring %r failed", c["name"], c["old"])
257
+ raise ValueError(f"{n}: the world refused {json.dumps(v)}: {e}") from None
258
+ changes.append({"name": n, "old": self.values[n], "new": v})
259
+ for c in changes:
260
+ self.values[c["name"]] = self.stored[c["name"]] = c["new"]
261
+ self._save()
262
+ return changes
263
+
264
+ def pause(self, lanes: list[str], reason: str = "") -> None:
265
+ self._lanes(lanes)
266
+ with self.lock:
267
+ self.paused.update(dict.fromkeys(lanes, reason))
268
+ self._save()
269
+
270
+ def resume(self, lanes: list[str]) -> None:
271
+ self._lanes(lanes)
272
+ with self.lock:
273
+ for lane in lanes:
274
+ self.paused.pop(lane, None)
275
+ self._save()
276
+
277
+ @staticmethod
278
+ def _lanes(lanes: Any) -> None:
279
+ if not isinstance(lanes, list) or not lanes or not all(
280
+ isinstance(x, str) and LANE_RE.match(x) for x in lanes):
281
+ raise ValueError(f"lanes: expected a list of names matching {LANE_RE.pattern}")
282
+
283
+ def _save(self) -> None:
284
+ if self.path is None:
285
+ return
286
+ tmp = self.path.with_suffix(".tmp")
287
+ tmp.write_text(json.dumps({"knobs": self.stored, "paused": self.paused}, indent=1))
288
+ tmp.replace(self.path)
289
+
290
+
291
+ # ------------------------------------------------------------------ the base class
292
+
293
+ class World:
294
+ """Base class. Class attributes: `name`, `description` (shown to the agents); `concurrent`
295
+ is informational (the server always runs calls concurrently: the world guards its state)."""
296
+
297
+ name: typing.ClassVar[str] = "world"
298
+ description: typing.ClassVar[str] = ""
299
+
300
+ @classmethod
301
+ def tool_functions(cls) -> dict[str, Callable]:
302
+ """The `@tool` functions of the class, by name (in definition order)."""
303
+ found = {}
304
+ for klass in reversed(cls.__mro__):
305
+ for attr, value in vars(klass).items():
306
+ if hasattr(value, "world_tool"):
307
+ found[attr] = value
308
+ return found
309
+
310
+ @classmethod
311
+ def manifest(cls) -> dict[str, Any]:
312
+ """{"name", "description", "tools": [{name, description, parameters, annotations?}]},
313
+ built once per class (it depends on the code only)."""
314
+ if "_manifest" not in cls.__dict__:
315
+ tools = []
316
+ for fn in cls.tool_functions().values():
317
+ t = tool_schema(fn)
318
+ if fn.world_tool["read_only"]:
319
+ t["annotations"] = {"readOnlyHint": True}
320
+ tools.append(t)
321
+ cls._manifest = {"name": cls.name, "description": cls.description, "tools": tools}
322
+ return json.loads(json.dumps(cls._manifest))
323
+
324
+ def tools(self) -> dict[str, Callable]:
325
+ """The bound `@tool` methods, by name."""
326
+ return {name: getattr(self, name) for name in self.tool_functions()}
327
+
328
+ @classmethod
329
+ def pool(cls, tool: str) -> str:
330
+ fn = cls.tool_functions().get(tool)
331
+ return fn.world_tool["pool"] if fn is not None else "fast"
332
+
333
+ def call(self, tool: str, args: dict[str, Any], agent: Agent) -> Any:
334
+ """Run `tool` for `agent` (KeyError for an unknown tool; ToolError for a refusal)."""
335
+ fn = self.tool_functions()[tool]
336
+ hints = typing.get_type_hints(fn)
337
+ extra = {p.name: agent for p in inspect.signature(fn).parameters.values()
338
+ if p.name != "self" and _is_agent(p.name, hints.get(p.name))}
339
+ return fn(self, **args, **extra)
340
+
341
+ def metrics(self) -> dict[str, float]:
342
+ """World-specific numbers for `GET /metrics`."""
343
+ return {}
344
+
345
+ def state_dir(self) -> str | os.PathLike | None:
346
+ """Where `knobs.json` lives (None: in memory only)."""
347
+ return None
348
+
349
+ @property
350
+ def admin(self) -> Admin:
351
+ if "_admin" not in self.__dict__:
352
+ self.__dict__["_admin"] = Admin(self.state_dir())
353
+ return self.__dict__["_admin"]
354
+
355
+ def knob(self, name: str, type: type, default: Any, *, min: float | None = None,
356
+ max: float | None = None, doc: str = "",
357
+ on_change: Callable[[Any], None] | None = None) -> Any:
358
+ """Register a runtime knob (int, float, bool or str) and return its current value: the
359
+ value set through `PATCH /admin/knobs` if any (it survives restarts), else `default`.
360
+ A change calls `on_change(value)` (raise to refuse it)."""
361
+ if type not in KNOB_TYPES:
362
+ raise ValueError(f"knob {name}: type must be one of int, float, bool, str")
363
+ return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
364
+
365
+ @property
366
+ def knobs(self) -> dict[str, Any]:
367
+ """The knobs' current values, by name."""
368
+ return self.admin.values
369
+
370
+ def paused(self, lane: str) -> bool:
371
+ """Did an operator pause `lane` (`POST /admin/pause`)?"""
372
+ return lane in self.admin.paused
world/entrypoint.sh CHANGED
@@ -8,17 +8,18 @@
8
  #
9
  # Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless.
10
  #
11
- # Required env: HF_TOKEN LEGION_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET
12
- # (hf://buckets/<ns>/<bucket>/<prefix>, or "off" for no restore and no pushes: smoke tests only).
13
- # Optional: PORT (7860), LEGION_WORLD_HOST_FILE (writes host:port there: the file legion's controller
14
- # follows), WORLD_HOST ($HOSTNAME), PYBOT_WORK (/work), every PYBOT_* world setting, and
15
- # PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here).
16
  set -euo pipefail
17
  die() { printf '%s pybot-entrypoint: FATAL: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 2; }
18
 
19
- for v in HF_TOKEN LEGION_WORLD_TOKEN PYBOT_REPO PYBOT_BUCKET; do
20
  [ -n "${!v:-}" ] || die "$v is not set"
21
  done
 
22
  [ -z "${PYBOT_SANDBOX_URL:-}" ] || [ -n "${PYBOT_SANDBOX_TOKEN:-}" ] \
23
  || die "PYBOT_SANDBOX_URL is set but PYBOT_SANDBOX_TOKEN is not (the sidecar would refuse every run)"
24
  case ${PYBOT_BUCKET%/} in
@@ -32,16 +33,11 @@ case $PORT in ''|*[!0-9]*|0) die "PORT=$PORT must be a positive integer";; esac
32
  WORLD=${WORLD_DIR:-/opt/world}
33
  WORK=${PYBOT_WORK:-/work}
34
  # Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container.
35
- # A host PYTHONPATH must not shadow the image's installed legion.
36
  unset PYTHONPATH
37
  export HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp
38
  export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
39
  mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
40
 
41
- if [ -n "${LEGION_WORLD_HOST_FILE:-}" ]; then # atomic: legion's controller re-reads it every 15 s
42
- { echo "${WORLD_HOST:-$HOSTNAME}:$PORT" > "$LEGION_WORLD_HOST_FILE.tmp" && mv "$LEGION_WORLD_HOST_FILE.tmp" "$LEGION_WORLD_HOST_FILE"; } \
43
- || echo "pybot-entrypoint: cannot write $LEGION_WORLD_HOST_FILE" >&2
44
- fi
45
-
46
  cd "$WORLD" || die "cannot cd $WORLD"
47
- exec python pybot.py # serve() on 0.0.0.0:$PORT; the token comes from LEGION_WORLD_TOKEN, never argv
 
8
  #
9
  # Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless.
10
  #
11
+ # Required env: HF_TOKEN PYBOT_REPO PYBOT_BUCKET
12
+ # (hf://buckets/<ns>/<bucket>/<prefix>, or "off" for no restore and no pushes: smoke tests only),
13
+ # and PYBOT_TOKEN_<seat> for seats 0, 1, ... (agent-001, agent-002, ...): each agent's credential.
14
+ # Optional: PORT (7860), PYBOT_ADMIN_TOKEN (/metrics and /admin), PYBOT_WORK (/work), every PYBOT_*
15
+ # world setting, and PYBOT_SANDBOX_URL + PYBOT_SANDBOX_TOKEN (bots run in the sidecar, not under unshare here).
16
  set -euo pipefail
17
  die() { printf '%s pybot-entrypoint: FATAL: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; exit 2; }
18
 
19
+ for v in HF_TOKEN PYBOT_REPO PYBOT_BUCKET; do
20
  [ -n "${!v:-}" ] || die "$v is not set"
21
  done
22
+ [ -n "${PYBOT_TOKEN_0:-}" ] || die "PYBOT_TOKEN_0 is not set (the agents' credentials: PYBOT_TOKEN_<seat>)"
23
  [ -z "${PYBOT_SANDBOX_URL:-}" ] || [ -n "${PYBOT_SANDBOX_TOKEN:-}" ] \
24
  || die "PYBOT_SANDBOX_URL is set but PYBOT_SANDBOX_TOKEN is not (the sidecar would refuse every run)"
25
  case ${PYBOT_BUCKET%/} in
 
33
  WORLD=${WORLD_DIR:-/opt/world}
34
  WORK=${PYBOT_WORK:-/work}
35
  # Set here, not in the image: pyxis passes the host env (HOME, PYTHONPATH) into the container.
36
+ # A host PYTHONPATH must not shadow the image's installed packages.
37
  unset PYTHONPATH
38
  export HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp
39
  export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
40
  mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
41
 
 
 
 
 
 
42
  cd "$WORLD" || die "cannot cd $WORLD"
43
+ exec python pybot.py # serves on 0.0.0.0:$PORT; credentials come from the env, never argv
world/isolation.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Linux process isolation for bot and test subprocesses. Setup errors abort; there is no unsandboxed fallback.
2
+
3
+ unshare creates a user/PID/mount namespace and private procfs. The trusted setup
4
+ then builds a small root with read-only runtimes and only the caller's data,
5
+ chroots and drops capabilities before executing any agent-supplied code.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import ctypes
11
+ import json
12
+ import os
13
+ import re
14
+ import shutil
15
+ import sys
16
+ from collections.abc import Iterator
17
+ from pathlib import Path
18
+
19
+ MS_RDONLY, MS_NOSUID, MS_NODEV, MS_NOEXEC = 1, 2, 4, 8
20
+ MS_REMOUNT, MS_BIND = 32, 4096
21
+ MS_NOATIME, MS_NODIRATIME, MS_REC, MS_RELATIME, MS_STRICTATIME = 1024, 2048, 16384, 1 << 21, 1 << 24
22
+ # statvfs flags of a mount that an unprivileged namespace cannot clear (they are locked) ->
23
+ # the mount(2) flags a read-only remount must repeat.
24
+ _LOCKED = ((os.ST_RDONLY, MS_RDONLY), (os.ST_NOSUID, MS_NOSUID), (os.ST_NODEV, MS_NODEV),
25
+ (os.ST_NOEXEC, MS_NOEXEC), (os.ST_NOATIME, MS_NOATIME),
26
+ (os.ST_NODIRATIME, MS_NODIRATIME), (os.ST_RELATIME, MS_RELATIME))
27
+
28
+
29
+ DEV_NODES = ("/dev/null", "/dev/zero", "/dev/urandom", "/dev/random")
30
+ # The chroot's root is a tmpfs: RAM that counts against the job's memory. Only mount points
31
+ # and stray writes outside the bound dirs land there; the cap bounds each sandbox.
32
+ TMPFS_SIZE_ENV, TMPFS_SIZE_DEFAULT = "PYBOT_ISOLATION_TMPFS_SIZE", "256m"
33
+ SANDBOX_TMP = "/tmp" # where `command(tmp=...)` binds the caller's disk-backed temp dir
34
+ _SIZE = re.compile(r"[1-9][0-9]*[kmg]?", re.IGNORECASE)
35
+ MOUNT_ATTR_RDONLY, AT_FDCWD, AT_RECURSIVE, SYS_MOUNT_SETATTR = 0x1, -100, 0x8000, 442
36
+
37
+
38
+ class IsolationSetupError(OSError):
39
+ """A sandbox setup step failed: names the step and path (never argv or the env)."""
40
+
41
+
42
+ class IsolationMountError(IsolationSetupError):
43
+ """A mount(2) call of the sandbox setup failed: names the target and flags, no argv."""
44
+
45
+
46
+ @contextlib.contextmanager
47
+ def _step(step: str, path) -> Iterator[None]:
48
+ """Turn a plain OSError of one setup step into an IsolationSetupError naming it."""
49
+ try:
50
+ yield
51
+ except IsolationSetupError:
52
+ raise
53
+ except OSError as e:
54
+ raise IsolationSetupError(e.errno, f"isolation {step} failed: "
55
+ f"{e.strerror or type(e).__name__}: path={path}") from None
56
+
57
+
58
+ def _libc():
59
+ return ctypes.CDLL(None, use_errno=True)
60
+
61
+
62
+ def protect_supervisor() -> None:
63
+ """Deny same-UID ptrace and /proc/<pid>/{environ,mem,root} on the world."""
64
+ if not sys.platform.startswith("linux") or _libc().prctl(4, 0, 0, 0, 0) != 0:
65
+ raise RuntimeError("PR_SET_DUMPABLE=0 is required for process isolation")
66
+
67
+
68
+ def tmpfs_size(env=os.environ) -> str:
69
+ """The size cap of a sandbox's tmpfs root: $PYBOT_ISOLATION_TMPFS_SIZE (bytes, or with a
70
+ k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default."""
71
+ value = (env.get(TMPFS_SIZE_ENV) or "").strip()
72
+ if _SIZE.fullmatch(value):
73
+ return value.lower()
74
+ if value:
75
+ print(f"isolation: ignoring {TMPFS_SIZE_ENV}={value!r}; using {TMPFS_SIZE_DEFAULT}",
76
+ file=sys.stderr)
77
+ return TMPFS_SIZE_DEFAULT
78
+
79
+
80
+ def runtime_paths(command: list[str], *, python_only=False) -> list[str]:
81
+ paths = ["/usr", "/bin", "/sbin", "/lib", "/lib64", sys.prefix, sys.base_prefix]
82
+ # Config files needed by Python, Node, TLS, DNS and git; never a host home or the shared-disk root.
83
+ paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf",
84
+ "/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"]
85
+ if not python_only:
86
+ for binary in (command[0], "node"):
87
+ found = shutil.which(binary)
88
+ if not found:
89
+ continue
90
+ target = Path(found).resolve()
91
+ modules = next((p for p in target.parents if p.name == "node_modules"), None)
92
+ paths.append(str(modules or target.parent))
93
+ return sorted({str(Path(p).absolute()) for p in paths if Path(p).exists()}, key=lambda p: (len(p), p))
94
+
95
+
96
+ def symlink_chain(path: str | Path) -> tuple[list[tuple[str, str]], str]:
97
+ """Resolve `path` one hop at a time: every symlink met on the way (as `(link, target)`,
98
+ the target exactly as stored) and the final real path. Components that do not exist are
99
+ kept as they are. A loop or more than 40 hops raises."""
100
+ links: list[tuple[str, str]] = []
101
+ pending = list(Path(os.path.abspath(path)).parts[1:])
102
+ current = Path("/")
103
+ while pending:
104
+ name = pending.pop(0)
105
+ if name in ("", "."):
106
+ continue
107
+ if name == "..":
108
+ current = current.parent
109
+ continue
110
+ candidate = current / name
111
+ if not candidate.is_symlink():
112
+ current = candidate
113
+ continue
114
+ target = os.readlink(candidate)
115
+ links.append((str(candidate), target))
116
+ if len(links) > 40:
117
+ raise RuntimeError(f"isolation: too many symlinks resolving {path}")
118
+ if os.path.isabs(target):
119
+ current = Path("/")
120
+ pending = list(Path(target).parts[1:]) + pending
121
+ else:
122
+ pending = list(Path(target).parts) + pending
123
+ return links, str(current)
124
+
125
+
126
+ def _within(path: str, roots: list[str]) -> bool:
127
+ return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
128
+
129
+
130
+ def plan(argv: list[str], *, cwd: Path, readonly=(), writable=(), python_only=False,
131
+ private_dirs=(), tmp=None) -> dict:
132
+ """Mounts and symlinks for the chroot. Every path is bound at its real location, and each
133
+ symlink hop on the way to it (and to the interpreter, the command and node) is recreated
134
+ inside, so the original spelling resolves there too (a uv venv's python links through
135
+ `cpython-3.12-...` to `cpython-3.12.14-...`)."""
136
+ links: dict[str, str] = {}
137
+
138
+ def real(p) -> str:
139
+ hops, final = symlink_chain(p)
140
+ links.update(hops)
141
+ return final
142
+
143
+ ro = [real(p) for p in runtime_paths(argv, python_only=python_only) + [str(p) for p in readonly]]
144
+ rw = [real(p) for p in writable]
145
+ probes = [sys.executable, argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])]
146
+ if not python_only:
147
+ probes.append(shutil.which("node"))
148
+ for probe in filter(None, probes):
149
+ final = real(probe)
150
+ if not _within(final, ro + rw):
151
+ raise RuntimeError(f"isolation cannot represent {probe}: it resolves to {final}, "
152
+ "outside every mounted path")
153
+ real(cwd)
154
+ def ordered(paths: list[str]) -> list[str]: # parents before nested mounts
155
+ return sorted(dict.fromkeys(paths), key=lambda p: (len(p), p))
156
+
157
+ # `tmp` (a disk-backed dir) is bound over the sandbox's /tmp, so files written there do not
158
+ # fill the tmpfs root. Not when a planned path lives under /tmp itself (a test's tmp_path):
159
+ # the bind would hide it, and /tmp stays on the size-capped tmpfs.
160
+ tmp_dir = real(tmp) if tmp is not None else None
161
+ if tmp_dir is not None and any(_within(p, [SANDBOX_TMP]) for p in [*ro, *rw, *links, real(cwd)]):
162
+ tmp_dir = None
163
+ return {"readonly": ordered(ro), "writable": list(dict.fromkeys(rw)),
164
+ "symlinks": sorted(links.items(), key=lambda kv: (len(kv[0]), kv[0])),
165
+ "private_dirs": [str(Path(p).absolute()) for p in private_dirs], "tmp": tmp_dir}
166
+
167
+
168
+ def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(), network=False,
169
+ python_only=False, private_dirs=(), tmp=None) -> list[str]:
170
+ """Build a trusted invocation. Only explicitly mounted paths survive the chroot. `tmp`: a
171
+ disk-backed directory bound writable at the sandbox's /tmp (see `plan`)."""
172
+ unshare = shutil.which("unshare")
173
+ if not unshare:
174
+ raise RuntimeError("unshare is required for process isolation")
175
+ config = {"root": str(root.absolute()), "cwd": str(cwd.absolute()),
176
+ "readonly_root": not network, "tmpfs_size": tmpfs_size(),
177
+ **plan(argv, cwd=cwd, readonly=readonly, writable=writable, python_only=python_only,
178
+ private_dirs=private_dirs, tmp=tmp)}
179
+ # A reclaim may send USR1 to every process. Only the world handles it; an unshare
180
+ # wrapper must survive long enough for its bounded drain.
181
+ return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "pybot-isolate",
182
+ unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL",
183
+ "--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--",
184
+ sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
185
+
186
+
187
+ def _mount(source, target, kind=None, flags=0, data=None):
188
+ def encoded(value):
189
+ return os.fsencode(value) if value is not None else None
190
+ libc = _libc()
191
+ libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,
192
+ ctypes.c_ulong, ctypes.c_char_p]
193
+ if libc.mount(encoded(source), encoded(target), encoded(kind), flags, encoded(data)) != 0:
194
+ errno = ctypes.get_errno()
195
+ raise IsolationMountError(errno, f"isolation mount failed: {os.strerror(errno)}: "
196
+ f"source={source} target={target} type={kind} "
197
+ f"flags={flags:#x}")
198
+
199
+
200
+ def readonly_remount_flags(target) -> int:
201
+ """MS_REMOUNT|MS_BIND|MS_RDONLY plus nosuid/nodev, and every locked flag the bound mount
202
+ already has (statvfs of the bind target): a user namespace cannot clear them, and
203
+ leaving them out fails with EPERM. No atime flag on the source means strictatime."""
204
+ inherited = os.statvfs(target).f_flag
205
+ flags = MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV
206
+ for flag, mount_flag in _LOCKED:
207
+ if inherited & flag:
208
+ flags |= mount_flag
209
+ if not inherited & (os.ST_NOATIME | os.ST_RELATIME):
210
+ flags |= MS_STRICTATIME
211
+ return flags
212
+
213
+
214
+ def _readonly_recursive(target) -> bool:
215
+ """mount_setattr(AT_RECURSIVE, MOUNT_ATTR_RDONLY): make every submount of a recursive
216
+ bind read-only too (a remount only changes the top one). False if the kernel lacks it
217
+ (before 5.12); the mountinfo check still refuses a writable submount."""
218
+ libc = _libc()
219
+ attr = (ctypes.c_uint64 * 4)(MOUNT_ATTR_RDONLY, 0, 0, 0)
220
+ libc.syscall.restype = ctypes.c_long
221
+ rc = libc.syscall(ctypes.c_long(SYS_MOUNT_SETATTR), ctypes.c_int(AT_FDCWD),
222
+ ctypes.c_char_p(os.fsencode(target)), ctypes.c_uint(AT_RECURSIVE),
223
+ ctypes.byref(attr), ctypes.c_size_t(ctypes.sizeof(attr)))
224
+ # Any failure (ENOSYS before 5.12, EPERM on a locked mount): the mountinfo check that
225
+ # follows the binds still refuses a writable submount.
226
+ return rc == 0
227
+
228
+
229
+ def _unescape(field: str) -> str:
230
+ return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field)
231
+
232
+
233
+ def parse_mountinfo(text: str) -> list[tuple[str, set[str]]]:
234
+ """(mount point, per-mount options) of each /proc/self/mountinfo line."""
235
+ out = []
236
+ for line in text.splitlines():
237
+ fields = line.split()
238
+ if len(fields) >= 6:
239
+ out.append((_unescape(fields[4]), set(fields[5].split(","))))
240
+ return out
241
+
242
+
243
+ def check_mounts(mounts: list[tuple[str, set[str]]], root: str, readonly: list[str],
244
+ writable: list[str] = (), extra: list[str] = ()) -> None:
245
+ """Fail closed after the binds. Every mount under `root` must be a planned target (or
246
+ `extra`: proc, the /dev nodes), or a submount a recursive bind of one brought along
247
+ (e.g. a container's zoneinfo file bound over /usr's); and every mount at or under a
248
+ read-only target, outside a writable one, must be `ro`."""
249
+ def under(path: str, roots) -> bool:
250
+ return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
251
+
252
+ planned = [*readonly, *writable, *extra]
253
+ for point, opts in mounts:
254
+ if point == root or not under(point, [root]):
255
+ continue
256
+ if not under(point, planned):
257
+ raise IsolationMountError(1, f"isolation: unexpected mount {point} in the sandbox root")
258
+ if under(point, readonly) and not under(point, writable) and "ro" not in opts:
259
+ raise IsolationMountError(30, f"isolation: {point} is mounted writable under a "
260
+ "read-only path")
261
+
262
+
263
+ def _bind(root: Path, source: str, *, readonly: bool, target: Path | None = None):
264
+ """Bind `source` at its own path under `root` (or at `target`, a path under `root`)."""
265
+ path = Path(source)
266
+ if not path.exists():
267
+ raise IsolationSetupError(2, f"isolation bind failed: required path is missing: path={source}")
268
+ target = target if target is not None else root / path.relative_to("/")
269
+ # Create the mount point only when missing: it may already exist on a read-only bind
270
+ # (/etc/localtime -> /usr/share/zoneinfo/... under the /usr bind), where touch()'s utime
271
+ # fails with EROFS.
272
+ with _step("mount point creation", target):
273
+ target.parent.mkdir(parents=True, exist_ok=True)
274
+ if path.is_dir():
275
+ if not target.is_dir():
276
+ target.mkdir()
277
+ elif not target.exists():
278
+ target.touch()
279
+ # Recursive: a user namespace refuses (EINVAL) a non-recursive bind of a tree that has
280
+ # locked submounts, since it would uncover what they hide. Only explicitly listed paths
281
+ # are bound, so a submount comes in only under a path that was asked for.
282
+ _mount(source, target, flags=MS_BIND | MS_REC)
283
+ if readonly:
284
+ # Step two: read-only only works as a remount of the bind, with the locked flags;
285
+ # then the submounts the recursive bind brought along, where the kernel can.
286
+ _mount(None, target, flags=readonly_remount_flags(target))
287
+ _readonly_recursive(target)
288
+
289
+
290
+ def _drop_privileges():
291
+ libc = _libc()
292
+ # NOROOT + locked: exec as namespace uid 0 must never regain capabilities.
293
+ if libc.prctl(28, 3, 0, 0, 0) or libc.prctl(38, 1, 0, 0, 0):
294
+ raise RuntimeError("cannot lock sandbox privileges")
295
+ # All currently defined capabilities fit below 64. EINVAL marks unsupported bits.
296
+ for cap in range(64):
297
+ if libc.prctl(24, cap, 0, 0, 0) != 0 and ctypes.get_errno() != 22:
298
+ raise RuntimeError("cannot drop sandbox capability bounding set")
299
+ class Header(ctypes.Structure):
300
+ _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)]
301
+ class Data(ctypes.Structure):
302
+ _fields_ = [("effective", ctypes.c_uint32), ("permitted", ctypes.c_uint32),
303
+ ("inheritable", ctypes.c_uint32)]
304
+ if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()) != 0:
305
+ raise RuntimeError("cannot clear sandbox capabilities")
306
+
307
+
308
+ OOM_SCORE_ADJ = 800 # sandboxed processes die before the world (which keeps 0) on an OOM kill
309
+
310
+
311
+ def set_oom_score_adj(value: int = OOM_SCORE_ADJ, path: str = "/proc/self/oom_score_adj") -> bool:
312
+ """Raise this process's OOM score (inherited by what it execs). Raising needs no
313
+ privilege; False when /proc refuses it."""
314
+ try:
315
+ Path(path).write_text(str(value))
316
+ return True
317
+ except OSError:
318
+ return False
319
+
320
+
321
+ def _enter(config, argv):
322
+ # Never share a process group with a supervisor outside the PID namespace.
323
+ if os.getpgrp() != os.getpid():
324
+ os.setsid()
325
+ set_oom_score_adj()
326
+ root = Path(config["root"])
327
+ with _step("root creation", root):
328
+ root.mkdir(parents=True, exist_ok=True)
329
+ size = config.get("tmpfs_size") or TMPFS_SIZE_DEFAULT
330
+ if not _SIZE.fullmatch(size):
331
+ raise IsolationSetupError(22, f"isolation tmpfs size is invalid: path={root}")
332
+ _mount("tmpfs", root, "tmpfs", MS_NOSUID | MS_NODEV, f"mode=755,size={size}")
333
+ for path in config["readonly"]:
334
+ _bind(root, path, readonly=True)
335
+ for path in config["writable"]:
336
+ _bind(root, path, readonly=False)
337
+ for link, target in config.get("symlinks", ()):
338
+ inside = root / Path(link).relative_to("/")
339
+ if os.path.lexists(inside):
340
+ continue # already visible through a bind mount
341
+ with _step("symlink creation", inside):
342
+ inside.parent.mkdir(parents=True, exist_ok=True)
343
+ inside.symlink_to(target)
344
+ for path in config["private_dirs"]:
345
+ with _step("private directory creation", path):
346
+ (root / Path(path).relative_to("/")).mkdir(parents=True, exist_ok=True)
347
+ for path in ("tmp", "proc", "dev"):
348
+ with _step("directory creation", root / path):
349
+ (root / path).mkdir(exist_ok=True)
350
+ if config.get("tmp"): # the sandbox's /tmp on the caller's disk-backed dir, not the tmpfs
351
+ _bind(root, config["tmp"], readonly=False, target=root / SANDBOX_TMP.lstrip("/"))
352
+ for path in DEV_NODES:
353
+ _bind(root, path, readonly=False)
354
+ with _step("symlink creation", root / "dev/fd"):
355
+ (root / "dev/fd").symlink_to("/proc/self/fd")
356
+ _mount("proc", root / "proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC)
357
+ inside = lambda p: os.path.realpath(root / Path(p).relative_to("/"))
358
+ check_mounts(parse_mountinfo(Path("/proc/self/mountinfo").read_text()), os.path.realpath(root),
359
+ [inside(p) for p in config["readonly"]],
360
+ [inside(p) for p in (*config["writable"], *([SANDBOX_TMP] if config.get("tmp") else []))],
361
+ [inside(p) for p in ("/proc", *DEV_NODES)])
362
+ if config["readonly_root"]:
363
+ _mount(None, root, flags=MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV)
364
+ with _step("chroot", root):
365
+ os.chroot(root)
366
+ with _step("chdir", config["cwd"]):
367
+ os.chdir(config["cwd"])
368
+ _drop_privileges()
369
+ os.execvpe(argv[0], argv, dict(os.environ))
370
+
371
+
372
+ if __name__ == "__main__":
373
+ try:
374
+ _enter(json.loads(sys.argv[1]), sys.argv[2:])
375
+ except IsolationSetupError as e: # step, path and flags only, never argv or the env
376
+ print(f"process isolation failed during setup: {e.strerror}", file=sys.stderr)
377
+ raise SystemExit(125) from None
378
+ except Exception: # noqa: BLE001 - fail closed, without leaking arguments or paths
379
+ # Paths, argv and errors could contain credentials. Fail closed without their values.
380
+ print("process isolation failed during setup", file=sys.stderr)
381
+ raise SystemExit(125) from None
world/lanes.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """External-write lanes for worlds: bounded concurrency, a circuit breaker and a persistent outbox.
2
+
3
+ A world that writes to an outside service (a Git host, an API with one token) gives each kind
4
+ of write its own lane, so one kind never starves another:
5
+
6
+ lanes = Lanes({"push": Lane(slots=1), "merge": Lane(slots=1),
7
+ "comment": Lane(slots=1, gap_s=1.0)}, dir=state_dir)
8
+ with lanes.hold("push", deadline=time.monotonic() + 20) as slot: # LaneBusy past deadline
9
+ ...write...; slot.ok() # or slot.fail("transient") / slot.fail("final")
10
+ lanes.outbox("comment", drain=post).put(key=pr, payload=text) # persistent, never drops
11
+
12
+ `Lane.slots`, `Lane.gap_s` and `Lane.paused` are plain attributes (`Lane.configure()` changes
13
+ the first two and wakes waiters); the breaker never changes them, it only lowers what is
14
+ effective while tripped.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import collections
19
+ import contextlib
20
+ import json
21
+ import logging
22
+ import os
23
+ import threading
24
+ import time
25
+ import uuid
26
+ from pathlib import Path
27
+
28
+ log = logging.getLogger(__name__)
29
+ POLL_S = 0.25 # longest single wait: notices pause flips, configure() and a test's fake clock
30
+
31
+
32
+ class LaneBusy(Exception):
33
+ """No slot within the deadline; `reason` is "slots", "gap" or "paused"."""
34
+
35
+ def __init__(self, lane: str, reason: str, retry_after_s: float) -> None:
36
+ super().__init__(f"lane {lane} busy ({reason}); retry in {retry_after_s:.0f} s")
37
+ self.lane, self.reason, self.retry_after_s = lane, reason, retry_after_s
38
+
39
+
40
+ class Breaker:
41
+ """Transient failures of one lane, or of a group of lanes that trip together."""
42
+
43
+ def __init__(self, trip_after: int, trip_window_s: float, quiet_s: float) -> None:
44
+ self.trip_after, self.trip_window_s, self.quiet_s = trip_after, trip_window_s, quiet_s
45
+ self.name = ""
46
+ self.lock = threading.Lock() # a leaf lock: taken with a lane's cond held
47
+ self.failures = collections.deque() # clock times of recent transient failures
48
+ self.tripped = False
49
+
50
+ def failure(self, now: float) -> None:
51
+ with self.lock:
52
+ self.failures.append(now)
53
+ while self.failures and self.failures[0] < now - self.trip_window_s:
54
+ self.failures.popleft()
55
+ if not self.tripped and len(self.failures) >= self.trip_after:
56
+ self.tripped = True
57
+ log.warning("lanes %s: tripped after %d transient failures in %.0f s; 1 slot and "
58
+ "a gap until %.0f quiet s", self.name, len(self.failures),
59
+ self.trip_window_s, self.quiet_s)
60
+
61
+ def is_tripped(self, now: float) -> bool:
62
+ """Ends a trip after quiet_s without a transient failure."""
63
+ with self.lock:
64
+ if self.tripped and now - self.failures[-1] >= self.quiet_s:
65
+ self.tripped = False
66
+ self.failures.clear()
67
+ log.warning("lanes %s: recovered after %.0f quiet s", self.name, self.quiet_s)
68
+ return self.tripped
69
+
70
+
71
+ class Lane:
72
+ """One kind of external write.
73
+
74
+ Breaker: `trip_after` transient failures within `trip_window_s` trip the lane to
75
+ min(slots, 1) slot and at least `trip_gap_s` between writes; after `quiet_s` without a
76
+ transient failure it returns to `slots` and `gap_s`. `Lanes(breaker_groups=)` makes lanes
77
+ share one breaker (the first lane's trip_after, trip_window_s and quiet_s)."""
78
+
79
+ def __init__(self, slots: int = 1, gap_s: float = 0.0, *, trip_after: int = 3,
80
+ trip_window_s: float = 900.0, trip_gap_s: float = 5.0, quiet_s: float = 600.0,
81
+ retry_after_s: float = 60.0) -> None:
82
+ self.slots, self.gap_s, self.paused = slots, gap_s, False
83
+ self.breaker = Breaker(trip_after, trip_window_s, quiet_s)
84
+ self.trip_gap_s, self.retry_after_s = trip_gap_s, retry_after_s
85
+ self.name, self.clock, self.paused_fn = "", time.monotonic, None # set by Lanes
86
+ self.cond = threading.Condition()
87
+ self.in_flight, self.last_at = 0, float("-inf")
88
+ self.stats = {"waits_total": 0, "wait_s_total": 0.0, "ok": 0, "transient": 0, "final": 0}
89
+
90
+ def configure(self, slots: int | None = None, gap_s: float | None = None) -> None:
91
+ with self.cond:
92
+ if slots is not None:
93
+ self.slots = slots
94
+ if gap_s is not None:
95
+ self.gap_s = gap_s
96
+ self.cond.notify_all()
97
+
98
+ def is_paused(self) -> bool:
99
+ return self.paused or bool(self.paused_fn and self.paused_fn(self.name))
100
+
101
+ def _effective(self, now):
102
+ """(slots, gap_s) in force now (cond held)."""
103
+ if self.breaker.is_tripped(now):
104
+ return min(self.slots, 1), max(self.gap_s, self.trip_gap_s)
105
+ return self.slots, self.gap_s
106
+
107
+ def acquire(self, deadline: float | None, pausable: bool = True) -> None:
108
+ with self.cond:
109
+ start = now = self.clock()
110
+ while True:
111
+ slots, gap = self._effective(now)
112
+ reason = ("paused" if pausable and self.is_paused() else
113
+ "slots" if self.in_flight >= slots else
114
+ "gap" if now < self.last_at + gap else None)
115
+ if reason is None:
116
+ break
117
+ if deadline is not None and now >= deadline:
118
+ self.stats["waits_total"] += 1
119
+ self.stats["wait_s_total"] += now - start
120
+ retry = (self.last_at + gap - now) if reason == "gap" else self.retry_after_s
121
+ raise LaneBusy(self.name, reason, max(1.0, retry))
122
+ self.cond.wait(POLL_S if deadline is None else min(POLL_S, deadline - now))
123
+ now = self.clock()
124
+ if now > start:
125
+ self.stats["waits_total"] += 1
126
+ self.stats["wait_s_total"] += now - start
127
+ self.in_flight += 1
128
+ self.last_at = now
129
+
130
+ def release(self) -> None:
131
+ with self.cond:
132
+ self.in_flight -= 1
133
+ self.cond.notify_all()
134
+
135
+ def report(self, kind: str) -> None:
136
+ """Count an outcome: "ok", "transient" (feeds the breaker) or "final"."""
137
+ with self.cond:
138
+ self.stats[kind] += 1
139
+ if kind == "transient":
140
+ self.breaker.failure(self.clock())
141
+
142
+ def metrics(self) -> dict:
143
+ with self.cond:
144
+ now = self.clock()
145
+ slots, _ = self._effective(now)
146
+ return {"slots": self.slots, "effective_slots": slots, "in_flight": self.in_flight,
147
+ **self.stats, "tripped": int(self.breaker.is_tripped(now)),
148
+ "paused": int(self.is_paused())}
149
+
150
+
151
+ class Slot:
152
+ """A held slot: report the write's outcome with ok() or fail()."""
153
+
154
+ def __init__(self, lane: Lane) -> None:
155
+ self.lane = lane
156
+
157
+ def ok(self) -> None:
158
+ self.lane.report("ok")
159
+
160
+ def fail(self, kind: str = "transient") -> None:
161
+ if kind not in ("transient", "final"):
162
+ raise ValueError("kind must be transient or final")
163
+ self.lane.report(kind)
164
+
165
+
166
+ class Outbox:
167
+ """Writes for one lane that must happen eventually, drained by a background thread.
168
+
169
+ `drain(key, payloads)` makes one write of the queued payloads of `key` (more than one when
170
+ they piled up: the world joins them; at most max_batch of them and max_chars characters,
171
+ or one) and returns "ok", "transient" or "final" (an exception counts as transient), or
172
+ "split": retry the key's payloads one per write (e.g. the service refused a joined write). Transient failures retry forever with capped doubling backoff; only
173
+ ok and final remove payloads. Stored as JSON lines in `path` (keys: str or int), compacted
174
+ on load and when mostly settled."""
175
+
176
+ def __init__(self, lanes: Lanes, name: str, path: Path, drain, backoff=(5.0, 600.0),
177
+ max_batch: int = 10, max_chars: int = 60_000) -> None:
178
+ self.lanes, self.name, self.path, self.drain = lanes, name, path, drain
179
+ self.backoff, self.max_batch, self.max_chars = backoff, max_batch, max_chars
180
+ self.lock = threading.Lock()
181
+ self.entries = {} # key -> {"payloads", "queued_at", "tries", "next_at"} in put order
182
+ self.lines = 0 # lines in the file
183
+ self._load()
184
+ self.stop, self.wake = threading.Event(), threading.Event()
185
+ self.thread = threading.Thread(target=self._run, name=f"lane-{name}-outbox", daemon=True)
186
+ if drain is not None:
187
+ self.thread.start()
188
+
189
+ def _entry(self, key, ts):
190
+ return self.entries.setdefault(key, {"payloads": [], "queued_at": ts, "tries": 0,
191
+ "next_at": 0.0, "batch": self.max_batch})
192
+
193
+ def _load(self):
194
+ if self.path.exists():
195
+ for line in self.path.read_text().splitlines():
196
+ try:
197
+ op = json.loads(line)
198
+ if "put" in op:
199
+ self._entry(op["put"], op["ts"])["payloads"].append(op["payload"])
200
+ elif op["done"] in self.entries:
201
+ entry = self.entries[op["done"]]
202
+ del entry["payloads"][:op["n"]]
203
+ if not entry["payloads"]:
204
+ del self.entries[op["done"]]
205
+ except (ValueError, KeyError, TypeError): # a line cut by a crash
206
+ log.warning("lane %s outbox: skipped an unreadable line", self.name)
207
+ self._compact()
208
+
209
+ def _compact(self):
210
+ """Rewrite the file with the pending payloads only (lock held, or during __init__)."""
211
+ self.path.parent.mkdir(parents=True, exist_ok=True)
212
+ tmp = self.path.with_name(f"{self.path.name}.{uuid.uuid4().hex}.tmp")
213
+ with open(tmp, "w") as out:
214
+ for key, e in self.entries.items():
215
+ out.writelines(json.dumps({"put": key, "payload": payload, "ts": e["queued_at"]}) + "\n" for payload in e["payloads"])
216
+ out.flush()
217
+ os.fsync(out.fileno()) # the data is on disk before the name points at it
218
+ os.replace(tmp, self.path)
219
+ self.lines = sum(len(e["payloads"]) for e in self.entries.values())
220
+
221
+ def _append(self, op):
222
+ with open(self.path, "a") as out:
223
+ out.write(json.dumps(op) + "\n")
224
+ self.lines += 1
225
+
226
+ def put(self, key, payload) -> None:
227
+ """Queue payload for key; joins payloads of the same key still waiting."""
228
+ with self.lock:
229
+ ts = self.lanes.wall()
230
+ self._append({"put": key, "payload": payload, "ts": ts})
231
+ self._entry(key, ts)["payloads"].append(payload)
232
+ self.wake.set()
233
+
234
+ def depth(self) -> tuple[int, float]:
235
+ """(pending payloads, age in seconds of the oldest)."""
236
+ with self.lock:
237
+ now = self.lanes.wall()
238
+ return (sum(len(e["payloads"]) for e in self.entries.values()),
239
+ max((now - e["queued_at"] for e in self.entries.values()), default=0.0))
240
+
241
+ def _settle(self, key, n, kind):
242
+ with self.lock:
243
+ entry = self.entries.get(key)
244
+ if entry is None:
245
+ return
246
+ if kind == "split":
247
+ entry["batch"] = 1
248
+ return
249
+ if kind == "transient":
250
+ entry["tries"] += 1
251
+ delay = min(self.backoff[1], self.backoff[0] * 2 ** (entry["tries"] - 1))
252
+ entry["next_at"] = self.lanes.wall() + delay
253
+ log.warning("lane %s outbox: write for %r failed; retry %d in %.0f s",
254
+ self.name, key, entry["tries"], delay)
255
+ return
256
+ if kind == "final":
257
+ log.warning("lane %s outbox: dropped %d payload(s) for %r: final", self.name, n, key)
258
+ del entry["payloads"][:n]
259
+ entry["tries"], entry["next_at"] = 0, 0.0
260
+ if kind != "ok":
261
+ entry["batch"] = 1 # the rest of a refused batch goes one by one
262
+ if not entry["payloads"]:
263
+ del self.entries[key]
264
+ self._append({"done": key, "n": n})
265
+ pending = sum(len(e["payloads"]) for e in self.entries.values())
266
+ if self.lines > 2 * pending + 1000:
267
+ self._compact()
268
+
269
+ def _batch(self, key):
270
+ """The payloads of key for the next write (lock held): oldest first, within the
271
+ entry's batch size and max_chars, at least one."""
272
+ entry = self.entries.get(key)
273
+ if entry is None:
274
+ return []
275
+ out, chars = [], 0
276
+ for payload in entry["payloads"][:entry["batch"]]:
277
+ chars += len(payload if isinstance(payload, str) else json.dumps(payload))
278
+ if out and chars > self.max_chars:
279
+ break
280
+ out.append(payload)
281
+ return out
282
+
283
+ def _run(self):
284
+ while not self.stop.is_set():
285
+ try:
286
+ self._step()
287
+ except Exception: # keep the thread alive: a disk error, a bad drain result
288
+ log.exception("lane %s outbox: drain loop failed", self.name)
289
+ self.stop.wait(POLL_S)
290
+
291
+ def _step(self):
292
+ with self.lock:
293
+ now = self.lanes.wall()
294
+ due = [(e["queued_at"], i, k) for i, (k, e) in enumerate(self.entries.items())
295
+ if e["next_at"] <= now]
296
+ key = min(due)[2] if due else None
297
+ if key is None:
298
+ self.wake.wait(POLL_S)
299
+ self.wake.clear()
300
+ return
301
+ try:
302
+ with self.lanes.hold(self.name, deadline=self.lanes.clock() + 1.0) as slot:
303
+ with self.lock: # taken with the slot held: joins what piled up meanwhile
304
+ payloads = self._batch(key)
305
+ if not payloads:
306
+ return
307
+ try:
308
+ kind = self.drain(key, payloads) or "ok"
309
+ except Exception:
310
+ log.exception("lane %s outbox: drain failed", self.name)
311
+ kind = "transient"
312
+ if kind not in ("ok", "transient", "final", "split"):
313
+ raise ValueError(f"drain returned {kind!r}")
314
+ if kind == "split" and len(payloads) == 1:
315
+ kind = "transient"
316
+ if kind == "ok":
317
+ slot.ok()
318
+ elif kind != "split":
319
+ slot.fail(kind)
320
+ except LaneBusy:
321
+ self.stop.wait(POLL_S)
322
+ return
323
+ self._settle(key, len(payloads), kind)
324
+
325
+ def close(self, timeout: float = 5.0) -> None:
326
+ self.stop.set()
327
+ self.wake.set()
328
+ if self.thread.is_alive() and self.thread is not threading.current_thread():
329
+ self.thread.join(timeout)
330
+
331
+
332
+ class Lanes:
333
+ """Named lanes sharing a clock, an optional `paused(name)` callback and a state dir for
334
+ outboxes (`<dir>/outbox-<name>.jsonl`). `breaker_groups`: tuples of lane names that share
335
+ one breaker (writes that fail together, e.g. two kinds that move the same refs)."""
336
+
337
+ def __init__(self, lanes: dict[str, Lane], dir: str | Path | None = None,
338
+ clock=time.monotonic, wall=time.time, paused=None,
339
+ breaker_groups: list[tuple[str, ...]] = ()) -> None:
340
+ self.lanes, self.dir, self.clock, self.wall = lanes, Path(dir) if dir else None, clock, wall
341
+ self.outboxes: dict[str, Outbox] = {}
342
+ for name, lane in lanes.items():
343
+ lane.name, lane.clock, lane.paused_fn = name, clock, paused
344
+ lane.breaker.name = name
345
+ for group in breaker_groups: # a transient failure in any of them trips them all
346
+ shared = lanes[group[0]].breaker
347
+ shared.name = "+".join(group)
348
+ for name in group[1:]:
349
+ lanes[name].breaker = shared
350
+
351
+ def __getitem__(self, name: str) -> Lane:
352
+ return self.lanes[name]
353
+
354
+ @contextlib.contextmanager
355
+ def hold(self, name: str, deadline: float | None = None, pausable: bool = True):
356
+ """Hold a slot of lane `name`, waiting until `deadline` (on `clock`; None: no limit);
357
+ raises LaneBusy. `pausable=False` ignores the pause (e.g. closing what was opened)."""
358
+ lane = self.lanes[name]
359
+ lane.acquire(deadline, pausable)
360
+ try:
361
+ yield Slot(lane)
362
+ finally:
363
+ lane.release()
364
+
365
+ def outbox(self, name: str, drain=None, **kwargs) -> Outbox:
366
+ """The lane's outbox; the first call with `drain` starts its drainer thread."""
367
+ if name not in self.outboxes:
368
+ if self.dir is None:
369
+ raise ValueError("Lanes(dir=...) is needed for an outbox")
370
+ self.outboxes[name] = Outbox(self, name, self.dir / f"outbox-{name}.jsonl", drain, **kwargs)
371
+ return self.outboxes[name]
372
+
373
+ def metrics(self) -> dict[str, dict]:
374
+ out = {}
375
+ for name, lane in self.lanes.items():
376
+ box = self.outboxes.get(name)
377
+ depth, age = box.depth() if box else (0, 0.0)
378
+ out[name] = {**lane.metrics(), "outbox_depth": depth, "outbox_oldest_age_s": age}
379
+ return out
380
+
381
+ def close(self, timeout: float = 5.0) -> None:
382
+ """Stop the drainer threads; what is queued stays on disk for the next start."""
383
+ end = time.monotonic() + timeout
384
+ for box in self.outboxes.values():
385
+ box.close(max(0.0, end - time.monotonic()))
world/pybot.py CHANGED
@@ -1,4 +1,5 @@
1
- """Run-4 world: local snapshots, native Hub PRs and independent reviews."""
 
2
  from __future__ import annotations
3
 
4
  import atexit
@@ -6,7 +7,6 @@ import base64
6
  import collections
7
  import concurrent.futures
8
  import contextlib
9
- import contextvars
10
  import functools
11
  import hashlib
12
  import inspect
@@ -24,25 +24,23 @@ from pathlib import Path, PurePosixPath
24
  from typing import ClassVar, Literal
25
 
26
  import snapshot
 
 
 
27
  from repository import Hub, Repository
28
  from sandbox import run, run_tests
29
-
30
- from legion.isolation import protect_supervisor
31
- from legion.world import Agent, ToolError, World, tool
32
- from legion.world.lanes import Lane, LaneBusy, Lanes
33
- from legion.world.store import Store
34
- from legion.world.workspace import apply_patch, unpack
35
 
36
  HERE = Path(__file__).resolve().parent
37
- UPLOAD = contextvars.ContextVar("workspace", default=None)
38
  FIXED = ("bot/__init__.py", "bot/__main__.py", "bot/runtime.py", "bot/modules/__init__.py")
39
  # A module the loader finds: bot/modules/<name>.py or a package bot/modules/<name>/__init__.py.
40
  MODULE_FILE = re.compile(r"bot/modules/(?:[^/]+\.py|[^/]+/__init__\.py)")
41
  MAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20)))
42
  EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/",
43
  "*.egg-info/", ".DS_Store")
44
- MAX_REQUESTS = 5000 # open_pr idempotency keys kept for worker retries (oldest dropped)
45
- # ... and for at most this long (a worker retries within minutes).
46
  REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600"))
47
  # state.db (and prs.json, see save.legacy_json) is written by a background thread at most once
48
  # per this many seconds while the state changed (0: write synchronously on every change).
@@ -50,7 +48,7 @@ REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600"))
50
  SAVE_INTERVAL = float(os.environ.get("PYBOT_SAVE_INTERVAL_S", "2.0"))
51
  FETCH_TTL = float(os.environ.get("PYBOT_FETCH_TTL_S", "60"))
52
  NAME = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
53
- # A world tool call must answer within about 55 s (the worker's deadline); Hub waits and push
54
  # retries stay inside this budget, counted from the start of the call.
55
  CALL_BUDGET = float(os.environ.get("PYBOT_CALL_BUDGET_S", "50"))
56
  PUSH_RETRY_DELAYS = (2, 5)
@@ -72,7 +70,7 @@ TRANSIENT_CODES = ("git_error", "hub_error")
72
  COMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub post
73
  # get_pr: diff bytes returned (cut at a line end, with truncated: true beyond this).
74
  MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))
75
- # State rows in state.db (legion.world.store): these top-level dicts get one row per entry;
76
  # every other top-level value (pr_opens, pr_merges) is one row of kind "_".
77
  KINDS = ("prs", "requests", "drafts", "inbox")
78
  COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this
@@ -133,9 +131,7 @@ def logs_refusals(fn):
133
 
134
 
135
  class PybotWorld(World):
136
- name, version = "pybot", "1.0.0"
137
- concurrent = True
138
- capabilities: ClassVar[list[str]] = ["workspace-upload-v1", "workspace-upload-v2"]
139
  description = ("Edit your local git clone, then submit with open_pr. Another agent must "
140
  "approve the PR's current change (a clean rebase keeps the approval) before merge; "
141
  "merge_pr queues a PR and the world merges the queue in order, rebasing each PR "
@@ -145,21 +141,8 @@ class PybotWorld(World):
145
  "merges and refused merges, closes, updates); handle it first. New PRs are limited swarm-wide to "
146
  "about the merge rate (pr_budget).")
147
 
148
- # The worker uploads the caller's local clone for these calls (workspace-upload-v1).
149
- WORKSPACE: ClassVar[dict] = {
150
- "open_pr": {"arg": "path", "default": "pybot"},
151
- "run_bot": {"arg": "ref_or_path", "default": "main", "skip": ["main"], "skip_prefix": "pr:"},
152
- }
153
  MERGER: ClassVar[bool] = True # start the merge queue's thread (tests run it by hand: _merge_next)
154
 
155
- def manifest(self) -> dict:
156
- m = super().manifest()
157
- for t in m["tools"]:
158
- t["x-legion-timeout_s"] = 330 # a 300 s run_bot conversation plus the upload
159
- if t["name"] in self.WORKSPACE:
160
- t["x-legion-workspace"] = self.WORKSPACE[t["name"]]
161
- return m
162
-
163
  def __init__(self, ws=None, repository=None):
164
  protect_supervisor()
165
  self.ws = Path(ws or os.environ.get("PYBOT_WS", HERE / "ws"))
@@ -193,7 +176,7 @@ class PybotWorld(World):
193
  # Saving (see _save): every change marks its rows dirty (_dirty) and bumps save_gen;
194
  # the saver writes the dirty rows to state.db and, while save.legacy_json is on, the
195
  # whole state to prs.json (written_gen is the generation in prs.json).
196
- self.save_interval = self.knob( # admin knobs (legion.world.admin): the env sets the default
197
  "save.interval_s", float, float(os.environ.get("PYBOT_SAVE_INTERVAL_S", SAVE_INTERVAL)),
198
  min=0, doc="Seconds between state saves (0: write on every change).",
199
  on_change=lambda v: setattr(self, "save_interval", v))
@@ -270,7 +253,7 @@ class PybotWorld(World):
270
  # agents at once): "push" for creating, pushing, readying and closing PRs, "merge" for
271
  # merges (never queued behind pushes, whose wait would let main or the PR move under
272
  # its checks), "comment" for review comments, posted from the outbox. Each lane has a
273
- # breaker (legion.world.lanes); the pause covers push and merge. Lock order: see self.lock.
274
  # Admin pauses (POST /admin/pause) apply per lane; the pause flag pauses push and merge.
275
  self.lanes = Lanes({"push": Lane(), "merge": Lane(), "comment": Lane()}, dir=self.ws,
276
  paused=lambda lane: self.paused(lane) or (
@@ -521,7 +504,7 @@ class PybotWorld(World):
521
  setattr(self, name, getattr(self, name) + n)
522
 
523
  def metrics(self):
524
- """World numbers for GET /metrics (legion.world.server)."""
525
  now = time.time()
526
  with self.lock:
527
  budget = self._budget()
@@ -980,8 +963,6 @@ class PybotWorld(World):
980
  inbox is non-empty. open_pr, review_pr, merge_pr and close_pr results carry pr_budget.
981
  A ToolError leaves the inbox untouched."""
982
  result = super().call(tool, args, agent)
983
- if inspect.isawaitable(result):
984
- return result
985
  if isinstance(result, dict) and tool in ("open_pr", "review_pr", "merge_pr", "close_pr"):
986
  with self.lock:
987
  result = {**result, "pr_budget": self._budget()}
@@ -1006,100 +987,56 @@ class PybotWorld(World):
1006
  if not NAME.fullmatch(agent.name):
1007
  raise ToolError("invalid agent identity")
1008
 
1009
- def call_workspace(self, name, args, agent, snapshot):
1010
- if name not in ("open_pr", "run_bot"):
1011
- raise ToolError("this tool does not accept workspace uploads")
1012
- token = UPLOAD.set(snapshot)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1013
  try:
1014
- return self.call(name, args, agent)
1015
- finally:
1016
- UPLOAD.reset(token)
1017
-
1018
- def _files(self, snapshot, tree):
1019
- """Apply an upload over tree (a checkout of its base, or an empty directory).
1020
-
1021
- Byte-identical files are not rewritten; tracked files missing from the upload are
1022
- deleted. Returns the paths that differ from the tree, for the compile check.
1023
- A v2 upload (a patch) applies only on a checkout of its base.
1024
- """
1025
- if (tree / ".git").is_dir():
1026
- # Default excludes even if an agent drops .gitignore: caches are never committed.
1027
- (tree / ".git/info").mkdir(exist_ok=True)
1028
- (tree / ".git/info/exclude").write_text("\n".join(EXCLUDE) + "\n")
1029
- if "patch" in snapshot:
1030
- try:
1031
- names = apply_patch(snapshot, tree)
1032
- except (ValueError, OSError) as exc:
1033
- raise ToolError(f"invalid workspace upload: {exc}"[:300], "bad_workspace") from exc
1034
- for name in names:
1035
- f = tree / name
1036
- if f.is_file() and f.stat().st_size > MAX_FILE_BYTES:
1037
- raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; "
1038
- "remove it from the clone or add it to .gitignore", "file_too_large")
1039
- return names
1040
- files = snapshot.get("files")
1041
- if not isinstance(files, dict):
1042
- raise ToolError("invalid workspace upload", "bad_workspace")
1043
- changed = {}
1044
- for name, encoded in files.items():
1045
- rel = PurePosixPath(name) if isinstance(name, str) else None
1046
- if (rel is None or rel.is_absolute() or ".." in rel.parts or ".git" in rel.parts
1047
- or "\\" in name or not isinstance(encoded, str)):
1048
- raise ToolError("invalid workspace upload", "bad_workspace")
1049
- if len(encoded) > (MAX_FILE_BYTES + 2) // 3 * 4:
1050
- raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; "
1051
- "remove it from the clone or add it to .gitignore", "file_too_large")
1052
- target = tree / rel
1053
- try:
1054
- data = base64.b64decode(encoded, validate=True)
1055
- except ValueError as exc:
1056
- raise ToolError("invalid workspace upload", "bad_workspace") from exc
1057
- if len(data) > MAX_FILE_BYTES:
1058
  raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; "
1059
  "remove it from the clone or add it to .gitignore", "file_too_large")
1060
- if target.is_file() and not target.is_symlink() and target.read_bytes() == data:
1061
- continue
1062
- changed[name] = encoded
1063
- if (tree / ".git").is_dir():
1064
- tracked = self.repo.git("ls-files", "-z", at=tree).split("\0")
1065
- for name in tracked:
1066
- if name and name not in files:
1067
- (tree / name).unlink(missing_ok=True)
1068
- changed.setdefault(name, None)
1069
- try:
1070
- unpack({"files": {k: v for k, v in changed.items() if v is not None}}, tree)
1071
- except (ValueError, TypeError, OSError) as exc:
1072
- raise ToolError("invalid workspace upload", "bad_workspace") from exc
1073
- return sorted(changed)
1074
-
1075
- def _adds_module(self, snapshot, base):
1076
- """Does an upload add a module the loader finds (MODULE_FILE, new or renamed to)?
1077
- Anything unreadable counts as adding one, so the budget still applies to it."""
1078
- if "patch" in snapshot:
1079
- try:
1080
- patch = base64.b64decode(snapshot.get("patch") or "", validate=True)
1081
- except (ValueError, TypeError):
1082
- return True
1083
- for block in re.split(rb"^diff --git ", patch, flags=re.MULTILINE)[1:]:
1084
- header = block.split(b"\n@@", 1)[0].decode(errors="replace")
1085
- names = re.match(r"a/(\S+) b/(\S+)\n", header)
1086
- if names is None: # a quoted path (spaces, non-ASCII): count it if it may be one
1087
- if "bot/modules/" in header.split("\n", 1)[0]:
1088
- return True
1089
- continue
1090
- old, new = names.groups()
1091
- if MODULE_FILE.fullmatch(new) and ("\nnew file mode" in header or old != new):
1092
- return True
1093
- return False
1094
- files = snapshot.get("files")
1095
- if not isinstance(files, dict):
1096
- return True
1097
  try:
1098
- tracked = set(self.repo.git("ls-tree", "-r", "--name-only", base, "--", "bot/modules")
1099
- .splitlines())
1100
- except ToolError:
1101
  return True
1102
- return any(isinstance(n, str) and MODULE_FILE.fullmatch(n) and n not in tracked for n in files)
 
 
 
 
 
 
 
 
 
 
1103
 
1104
  def _contract(self, tree, names=None):
1105
  """Check the fixed interface, and that names (default: every .py file) compile."""
@@ -1145,10 +1082,10 @@ class PybotWorld(World):
1145
  @tool(pool="slow")
1146
  @logs_refusals
1147
  def open_pr(self, agent: Agent, branch: str, title: str, description: str,
1148
- path: str = "pybot", pr: int | None = None) -> dict:
1149
  """Submit your local clone, or update your existing PR with pr:<number>.
1150
 
1151
- The worker uploads path from your private workspace. Include tests and run_bot
1152
  evidence in description. At most two open PRs per agent. Read CONTRIBUTING.md.
1153
  branch is a short slug like my-topic; the world stores it as agents/<you>/<slug>.
1154
  New PRs are budgeted swarm-wide: one is refused (code open_budget) while the swarm
@@ -1165,12 +1102,12 @@ class PybotWorld(World):
1165
  raise ToolError(f"title must be 3–200 characters (got {len(title) if isinstance(title, str) else 0})")
1166
  if not isinstance(description, str) or not description.strip():
1167
  raise ToolError("description must not be empty")
1168
- snapshot = UPLOAD.get()
1169
  if not isinstance(snapshot, dict):
1170
- raise ToolError("submit a local clone through legion-tool; the worker uploads it")
1171
- # Scope new_modules: a PR that adds no module is outside the budget (git runs unlocked).
1172
- exempt = (self.budget_scope == "new_modules"
1173
- and not self._adds_module(snapshot, snapshot.get("base_sha", "")))
1174
  key = agent.request_id
1175
  branch_ref = f"agents/{agent.name}/{branch}"
1176
  with self.lock:
@@ -1181,7 +1118,7 @@ class PybotWorld(World):
1181
  # The lock is held only for state and the main check; fetches, copies, compiles,
1182
  # Hub calls and pushes run outside it. A reservation keeps the cap and slugs exact.
1183
  self.repo.refresh(FETCH_TTL)
1184
- base = snapshot.get("base_sha", "")
1185
  token = object()
1186
  with self.lock:
1187
  if key and key in self.state["requests"]:
@@ -1307,7 +1244,7 @@ class PybotWorld(World):
1307
  self.last_create = max(self.last_create, time.monotonic())
1308
  sha, main = self._land(agent, snapshot, base, title, branch_ref, pr, sha, main,
1309
  started, slot)
1310
- self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/legion/pr/{pr}/{sha}", sha))
1311
  return pr, sha, main, old_head
1312
  raise ToolError("main kept moving while opening the PR; open it again", "busy")
1313
 
@@ -1687,7 +1624,7 @@ class PybotWorld(World):
1687
  with _timed(steps, "push"):
1688
  self._lease_push(agent, pr, new, head, time.monotonic())
1689
  with _timed(steps, "update_ref"): # waits for refs_lock
1690
- self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/legion/pr/{pr}/{new}", new))
1691
  with self.lock: # reviews stay: they match the rebased head by patch-id
1692
  rec.update(base_sha=main, head_sha=new)
1693
  self._dirty("prs", pr)
@@ -2162,30 +2099,24 @@ class PybotWorld(World):
2162
  "changes_requested": len(changes), "changes_requested_prs": changes[:STATUS_QUEUE_MAX]}
2163
 
2164
  @tool(pool="slow")
2165
- def run_bot(self, ref_or_path: str, lines: list[str]) -> dict:
2166
  """Run main, pr:<number>, or a local clone path. 300 seconds for the whole conversation."""
2167
  with tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp:
2168
  tree = Path(tmp) / "tree"
2169
- snapshot = UPLOAD.get()
2170
  if hub_ref := ref_or_path == "main" or ref_or_path.startswith("pr:"):
2171
- self.repo.refresh(FETCH_TTL) # outside the checkout slot: a fetch holds no permit
 
 
 
 
2172
  with self._checkout_slot(): # released before the run, which has its own slots
2173
  if hub_ref:
2174
  sha = self.repo.sha(ref_or_path)
2175
  self.repo.checkout(sha, tree)
2176
- elif isinstance(snapshot, dict):
2177
- sha = snapshot.get("base_sha")
2178
- if isinstance(sha, str) and self.repo.ancestor(sha, "main"):
2179
- self.repo.checkout(sha, tree) # then only changed files are written/compiled
2180
- self._contract(tree, self._files(snapshot, tree))
2181
- elif "patch" in snapshot:
2182
- raise ToolError("unknown base; send the full tree", "need_full")
2183
- else:
2184
- tree.mkdir()
2185
- self._files(snapshot, tree)
2186
- self._contract(tree)
2187
  else:
2188
- raise ToolError("use main, pr:<number>, or a clone path inside your workspace")
 
2189
  return {"ref": ref_or_path, "sha": sha, **self._run(tree, lines)}
2190
 
2191
  @contextlib.contextmanager
@@ -2207,11 +2138,10 @@ class PybotWorld(World):
2207
 
2208
 
2209
  if __name__ == "__main__":
2210
- from legion.world.server import serve
 
2211
  # Nothing else configures logging in the world process: this handler sends its warnings and
2212
  # INFO lines (merge_pr timings) to stderr.
2213
  logging.getLogger("pybot").addHandler(logging.StreamHandler())
2214
  logging.getLogger("pybot").setLevel(logging.INFO)
2215
- # LEGION_WORLD_PORT: the free port legion picked (a local run, a Slurm world job)
2216
- serve("pybot:PybotWorld", host="0.0.0.0",
2217
- port=int(os.environ.get("LEGION_WORLD_PORT") or os.environ.get("PORT") or 7860))
 
1
+ """The pybot world: local snapshots, native Hub PRs and independent reviews (`python pybot.py`
2
+ serves it on $PORT, server.py)."""
3
  from __future__ import annotations
4
 
5
  import atexit
 
7
  import collections
8
  import concurrent.futures
9
  import contextlib
 
10
  import functools
11
  import hashlib
12
  import inspect
 
24
  from typing import ClassVar, Literal
25
 
26
  import snapshot
27
+ from api import Agent, ToolError, World, tool
28
+ from isolation import protect_supervisor
29
+ from lanes import Lane, LaneBusy, Lanes
30
  from repository import Hub, Repository
31
  from sandbox import run, run_tests
32
+ from store import Store
33
+ from workspace import apply_patch
 
 
 
 
34
 
35
  HERE = Path(__file__).resolve().parent
 
36
  FIXED = ("bot/__init__.py", "bot/__main__.py", "bot/runtime.py", "bot/modules/__init__.py")
37
  # A module the loader finds: bot/modules/<name>.py or a package bot/modules/<name>/__init__.py.
38
  MODULE_FILE = re.compile(r"bot/modules/(?:[^/]+\.py|[^/]+/__init__\.py)")
39
  MAX_FILE_BYTES = int(os.environ.get("PYBOT_MAX_FILE_BYTES", str(1 << 20)))
40
  EXCLUDE = ("__pycache__/", "*.pyc", ".venv/", ".pytest_cache/", ".mypy_cache/", ".ruff_cache/",
41
  "*.egg-info/", ".DS_Store")
42
+ MAX_REQUESTS = 5000 # open_pr idempotency keys (X-Request-Id) kept for retries (oldest dropped)
43
+ # ... and for at most this long (a client retries within minutes).
44
  REQUEST_TTL = float(os.environ.get("PYBOT_REQUEST_TTL_S", "21600"))
45
  # state.db (and prs.json, see save.legacy_json) is written by a background thread at most once
46
  # per this many seconds while the state changed (0: write synchronously on every change).
 
48
  SAVE_INTERVAL = float(os.environ.get("PYBOT_SAVE_INTERVAL_S", "2.0"))
49
  FETCH_TTL = float(os.environ.get("PYBOT_FETCH_TTL_S", "60"))
50
  NAME = re.compile(r"^[a-z][a-z0-9-]{0,63}$")
51
+ # A world tool call must answer within about a minute (a caller's deadline); Hub waits and push
52
  # retries stay inside this budget, counted from the start of the call.
53
  CALL_BUDGET = float(os.environ.get("PYBOT_CALL_BUDGET_S", "50"))
54
  PUSH_RETRY_DELAYS = (2, 5)
 
70
  COMMENT_SEPARATOR = "\n\n---\n\n" # between review comments joined into one Hub post
71
  # get_pr: diff bytes returned (cut at a line end, with truncated: true beyond this).
72
  MAX_DIFF_BYTES = int(os.environ.get("PYBOT_GET_PR_DIFF_BYTES", "60000"))
73
+ # State rows in state.db (store.py): these top-level dicts get one row per entry;
74
  # every other top-level value (pr_opens, pr_merges) is one row of kind "_".
75
  KINDS = ("prs", "requests", "drafts", "inbox")
76
  COLD_AFTER = 3600.0 # merged/closed PR records leave memory for the cold table after this
 
131
 
132
 
133
  class PybotWorld(World):
134
+ name = "pybot"
 
 
135
  description = ("Edit your local git clone, then submit with open_pr. Another agent must "
136
  "approve the PR's current change (a clean rebase keeps the approval) before merge; "
137
  "merge_pr queues a PR and the world merges the queue in order, rebasing each PR "
 
141
  "merges and refused merges, closes, updates); handle it first. New PRs are limited swarm-wide to "
142
  "about the merge rate (pr_budget).")
143
 
 
 
 
 
 
144
  MERGER: ClassVar[bool] = True # start the merge queue's thread (tests run it by hand: _merge_next)
145
 
 
 
 
 
 
 
 
 
146
  def __init__(self, ws=None, repository=None):
147
  protect_supervisor()
148
  self.ws = Path(ws or os.environ.get("PYBOT_WS", HERE / "ws"))
 
176
  # Saving (see _save): every change marks its rows dirty (_dirty) and bumps save_gen;
177
  # the saver writes the dirty rows to state.db and, while save.legacy_json is on, the
178
  # whole state to prs.json (written_gen is the generation in prs.json).
179
+ self.save_interval = self.knob( # admin knobs (api.py): the env sets the default
180
  "save.interval_s", float, float(os.environ.get("PYBOT_SAVE_INTERVAL_S", SAVE_INTERVAL)),
181
  min=0, doc="Seconds between state saves (0: write on every change).",
182
  on_change=lambda v: setattr(self, "save_interval", v))
 
253
  # agents at once): "push" for creating, pushing, readying and closing PRs, "merge" for
254
  # merges (never queued behind pushes, whose wait would let main or the PR move under
255
  # its checks), "comment" for review comments, posted from the outbox. Each lane has a
256
+ # breaker (lanes.py); the pause covers push and merge. Lock order: see self.lock.
257
  # Admin pauses (POST /admin/pause) apply per lane; the pause flag pauses push and merge.
258
  self.lanes = Lanes({"push": Lane(), "merge": Lane(), "comment": Lane()}, dir=self.ws,
259
  paused=lambda lane: self.paused(lane) or (
 
504
  setattr(self, name, getattr(self, name) + n)
505
 
506
  def metrics(self):
507
+ """World numbers for GET /metrics (server.py)."""
508
  now = time.time()
509
  with self.lock:
510
  budget = self._budget()
 
963
  inbox is non-empty. open_pr, review_pr, merge_pr and close_pr results carry pr_budget.
964
  A ToolError leaves the inbox untouched."""
965
  result = super().call(tool, args, agent)
 
 
966
  if isinstance(result, dict) and tool in ("open_pr", "review_pr", "merge_pr", "close_pr"):
967
  with self.lock:
968
  result = {**result, "pr_budget": self._budget()}
 
987
  if not NAME.fullmatch(agent.name):
988
  raise ToolError("invalid agent identity")
989
 
990
+ def _workspace(self, workspace):
991
+ """Check a workspace's shape and that its base is in the repository (fetched from the
992
+ Hub when missing: unknown_base if still not there). Returns its base sha."""
993
+ base = workspace.get("base_sha") if isinstance(workspace, dict) else None
994
+ if not (isinstance(base, str) and re.fullmatch(r"[0-9a-f]{40}", base)
995
+ and isinstance(workspace.get("patch"), str)):
996
+ raise ToolError('workspace must be {"base_sha": "<40 hex>", "patch": "<base64>"}',
997
+ "bad_workspace")
998
+ if not self.repo.has_commit(base):
999
+ self.repo.refresh(0)
1000
+ if not self.repo.has_commit(base):
1001
+ raise ToolError(f"unknown base {base[:12]}: fetch origin/main and rebase your branch",
1002
+ "unknown_base")
1003
+ return base
1004
+
1005
+ def _files(self, workspace, tree):
1006
+ """Apply a workspace's patch on tree, a checkout of its base. Returns the paths that
1007
+ differ from the base, for the compile check."""
1008
+ # Default excludes even if an agent drops .gitignore: caches are never committed.
1009
+ (tree / ".git/info").mkdir(exist_ok=True)
1010
+ (tree / ".git/info/exclude").write_text("\n".join(EXCLUDE) + "\n")
1011
  try:
1012
+ names = apply_patch(workspace, tree)
1013
+ except (ValueError, OSError) as exc:
1014
+ raise ToolError(f"invalid workspace: {exc}"[:300], "bad_workspace") from exc
1015
+ for name in names:
1016
+ f = tree / name
1017
+ if f.is_file() and f.stat().st_size > MAX_FILE_BYTES:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1018
  raise ToolError(f"file too large: {name[:200]} is over {MAX_FILE_BYTES} bytes; "
1019
  "remove it from the clone or add it to .gitignore", "file_too_large")
1020
+ return names
1021
+
1022
+ def _adds_module(self, workspace):
1023
+ """Does a workspace's patch add a module the loader finds (MODULE_FILE, new or renamed
1024
+ to)? Anything unreadable counts as adding one, so the budget still applies to it."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
  try:
1026
+ patch = base64.b64decode(workspace.get("patch") or "", validate=True)
1027
+ except (ValueError, TypeError, AttributeError):
 
1028
  return True
1029
+ for block in re.split(rb"^diff --git ", patch, flags=re.MULTILINE)[1:]:
1030
+ header = block.split(b"\n@@", 1)[0].decode(errors="replace")
1031
+ names = re.match(r"a/(\S+) b/(\S+)\n", header)
1032
+ if names is None: # a quoted path (spaces, non-ASCII): count it if it may be one
1033
+ if "bot/modules/" in header.split("\n", 1)[0]:
1034
+ return True
1035
+ continue
1036
+ old, new = names.groups()
1037
+ if MODULE_FILE.fullmatch(new) and ("\nnew file mode" in header or old != new):
1038
+ return True
1039
+ return False
1040
 
1041
  def _contract(self, tree, names=None):
1042
  """Check the fixed interface, and that names (default: every .py file) compile."""
 
1082
  @tool(pool="slow")
1083
  @logs_refusals
1084
  def open_pr(self, agent: Agent, branch: str, title: str, description: str,
1085
+ path: str = "pybot", pr: int | None = None, workspace: dict | None = None) -> dict:
1086
  """Submit your local clone, or update your existing PR with pr:<number>.
1087
 
1088
+ path is your clone; the pybot tools send its change as workspace. Include tests and run_bot
1089
  evidence in description. At most two open PRs per agent. Read CONTRIBUTING.md.
1090
  branch is a short slug like my-topic; the world stores it as agents/<you>/<slug>.
1091
  New PRs are budgeted swarm-wide: one is refused (code open_budget) while the swarm
 
1102
  raise ToolError(f"title must be 3–200 characters (got {len(title) if isinstance(title, str) else 0})")
1103
  if not isinstance(description, str) or not description.strip():
1104
  raise ToolError("description must not be empty")
1105
+ snapshot = workspace
1106
  if not isinstance(snapshot, dict):
1107
+ raise ToolError("open_pr needs your clone's change: call it through the pybot tools, "
1108
+ "which send it as workspace", "bad_workspace")
1109
+ # Scope new_modules: a PR that adds no module is outside the budget.
1110
+ exempt = self.budget_scope == "new_modules" and not self._adds_module(snapshot)
1111
  key = agent.request_id
1112
  branch_ref = f"agents/{agent.name}/{branch}"
1113
  with self.lock:
 
1118
  # The lock is held only for state and the main check; fetches, copies, compiles,
1119
  # Hub calls and pushes run outside it. A reservation keeps the cap and slugs exact.
1120
  self.repo.refresh(FETCH_TTL)
1121
+ base = self._workspace(snapshot)
1122
  token = object()
1123
  with self.lock:
1124
  if key and key in self.state["requests"]:
 
1244
  self.last_create = max(self.last_create, time.monotonic())
1245
  sha, main = self._land(agent, snapshot, base, title, branch_ref, pr, sha, main,
1246
  started, slot)
1247
+ self.repo.update_refs((f"refs/pr/{pr}", sha), (f"refs/pybot/pr/{pr}/{sha}", sha))
1248
  return pr, sha, main, old_head
1249
  raise ToolError("main kept moving while opening the PR; open it again", "busy")
1250
 
 
1624
  with _timed(steps, "push"):
1625
  self._lease_push(agent, pr, new, head, time.monotonic())
1626
  with _timed(steps, "update_ref"): # waits for refs_lock
1627
+ self.repo.update_refs((f"refs/pr/{pr}", new), (f"refs/pybot/pr/{pr}/{new}", new))
1628
  with self.lock: # reviews stay: they match the rebased head by patch-id
1629
  rec.update(base_sha=main, head_sha=new)
1630
  self._dirty("prs", pr)
 
2099
  "changes_requested": len(changes), "changes_requested_prs": changes[:STATUS_QUEUE_MAX]}
2100
 
2101
  @tool(pool="slow")
2102
+ def run_bot(self, ref_or_path: str, lines: list[str], workspace: dict | None = None) -> dict:
2103
  """Run main, pr:<number>, or a local clone path. 300 seconds for the whole conversation."""
2104
  with tempfile.TemporaryDirectory(dir=self.tmp_dir) as tmp:
2105
  tree = Path(tmp) / "tree"
2106
+ # Fetches run outside the checkout slot: a fetch holds no permit.
2107
  if hub_ref := ref_or_path == "main" or ref_or_path.startswith("pr:"):
2108
+ self.repo.refresh(FETCH_TTL)
2109
+ elif workspace is None:
2110
+ raise ToolError("use main, pr:<number>, or a clone path inside your workspace")
2111
+ else:
2112
+ sha = self._workspace(workspace)
2113
  with self._checkout_slot(): # released before the run, which has its own slots
2114
  if hub_ref:
2115
  sha = self.repo.sha(ref_or_path)
2116
  self.repo.checkout(sha, tree)
 
 
 
 
 
 
 
 
 
 
 
2117
  else:
2118
+ self.repo.checkout(sha, tree) # then only changed files are written/compiled
2119
+ self._contract(tree, self._files(workspace, tree))
2120
  return {"ref": ref_or_path, "sha": sha, **self._run(tree, lines)}
2121
 
2122
  @contextlib.contextmanager
 
2138
 
2139
 
2140
  if __name__ == "__main__":
2141
+ import pybot # the module by its own name: its logger is "pybot", and its atexit hook saves
2142
+ from server import serve
2143
  # Nothing else configures logging in the world process: this handler sends its warnings and
2144
  # INFO lines (merge_pr timings) to stderr.
2145
  logging.getLogger("pybot").addHandler(logging.StreamHandler())
2146
  logging.getLogger("pybot").setLevel(logging.INFO)
2147
+ serve(pybot.PybotWorld, host="0.0.0.0", port=int(os.environ.get("PORT") or 7860))
 
 
world/pytest.ini CHANGED
@@ -1,4 +1,2 @@
1
  [pytest]
2
- asyncio_mode = auto
3
- asyncio_default_fixture_loop_scope = function
4
  testpaths = tests
 
1
  [pytest]
 
 
2
  testpaths = tests
world/repository.py CHANGED
@@ -14,8 +14,7 @@ from urllib.parse import urlsplit
14
  from huggingface_hub import HfApi
15
  from huggingface_hub.errors import HfHubHTTPError
16
 
17
- from legion.world import ToolError
18
- from legion.world.server import redact
19
 
20
  log = logging.getLogger(__name__)
21
  # Loose objects packed per maintenance pass at most: every pass finishes; a backlog drains over passes.
@@ -318,7 +317,7 @@ class Repository:
318
  def commit(self, tree, parent, author, title, onto=None, union=False):
319
  """Commit tree on parent; with onto != parent, replay that commit onto it (with union,
320
  PYBOT_UNION_PATHS merge as merge=union: only where a changed diff is refused)."""
321
- who = ("-c", f"user.name={author}", "-c", f"user.email={author}@legion.invalid")
322
  self.git("add", "-A", at=tree)
323
  self.git(*who, "commit", "--allow-empty", "-m", title, at=tree)
324
  sha = self.git("rev-parse", "HEAD", at=tree)
 
14
  from huggingface_hub import HfApi
15
  from huggingface_hub.errors import HfHubHTTPError
16
 
17
+ from api import ToolError, redact
 
18
 
19
  log = logging.getLogger(__name__)
20
  # Loose objects packed per maintenance pass at most: every pass finishes; a backlog drains over passes.
 
317
  def commit(self, tree, parent, author, title, onto=None, union=False):
318
  """Commit tree on parent; with onto != parent, replay that commit onto it (with union,
319
  PYBOT_UNION_PATHS merge as merge=union: only where a changed diff is refused)."""
320
+ who = ("-c", f"user.name={author}", "-c", f"user.email={author}@pybot.invalid")
321
  self.git("add", "-A", at=tree)
322
  self.git(*who, "commit", "--allow-empty", "-m", title, at=tree)
323
  sha = self.git("rev-parse", "HEAD", at=tree)
world/requirements.txt CHANGED
@@ -1,660 +1 @@
1
- annotated-doc==0.0.5 \
2
- --hash=sha256:117bac03a25ede5df5440e855b32d556049ca169ead221505badf432fed4b101 \
3
- --hash=sha256:c7e58ce09192557605d8bbd92836d7e1d520ac9580096042c0bfd197efacf1bb
4
- # via
5
- # fastapi
6
- # typer
7
- annotated-types==0.8.0 \
8
- --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \
9
- --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
10
- # via pydantic
11
- anyio==4.15.1 \
12
- --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \
13
- --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94
14
- # via
15
- # httpx
16
- # starlette
17
- # watchfiles
18
- certifi==2026.10.23 \
19
- --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \
20
- --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
21
- # via
22
- # httpcore
23
- # httpx
24
- click==8.5.0 \
25
- --hash=sha256:255bc9599cf7748b4b1a446ccc735421bd08a2ae529a8b88597d3de5664ee360 \
26
- --hash=sha256:ba0d2089de75ea0310e2dde03160e6ca10009947fb95a182f9b54021bb272e34
27
- # via
28
- # huggingface-hub
29
- # uvicorn
30
- colorama==0.4.6 ; sys_platform == 'win32' \
31
- --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \
32
- --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6
33
- # via
34
- # tqdm
35
- # typer
36
- exceptiongroup==1.3.1 \
37
- --hash=sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219 \
38
- --hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598
39
- # via legion
40
- fastapi==0.143.1 \
41
- --hash=sha256:4cafaab64df8534758bf0fce61947f5e27e6cd512798ccbbaad5425086c3b664 \
42
- --hash=sha256:687beb445804e4c4dbe2a76fd83c25e9b973ac48c267defb86f791e099baecc4
43
- # via legion
44
- filelock==3.32.7 \
45
- --hash=sha256:37b8a3d9811b0f9aef7e5ec5c71bb320de52df51e6ca9bcd6f5ad81187660da7 \
46
- --hash=sha256:65ff0d0190ea42038b32bda4b77834fb05be2cad4c5b9b01aa4dfb3614536e52
47
- # via huggingface-hub
48
- fsspec==2026.9.0 \
49
- --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \
50
- --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f
51
- # via huggingface-hub
52
- h11==0.16.0 \
53
- --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \
54
- --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
55
- # via
56
- # httpcore
57
- # uvicorn
58
- 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' \
59
- --hash=sha256:0a9e802f33bf50c851abe45fc5380e61f959e2d369647d6742b79ad9d6c27cab \
60
- --hash=sha256:19c0e64f14175ccb6a1aff69e0d2ab9ec5269a560e6687abaf2b3fa4f73de7cd \
61
- --hash=sha256:2814a6e999d13464c4d679b788cc5d784eb5a4edfc638a31f10e9a11ab531ef8 \
62
- --hash=sha256:2b7bb5727889b0f2436dbaaad8fc4c3e66b8240d992716989e0c086b4278b1bc \
63
- --hash=sha256:4ee5e05a627f5ab5bad7a86582277d645556ea1e199903aae19e033a392aa13a \
64
- --hash=sha256:57bc157b8b7fe3bee9dcb9af7f3da8de41801c3b31a9ef68a77a33c6a6be382f \
65
- --hash=sha256:59fba37039233c7fcbe196817d6cdcf1b40dfb17b410f229d85b0cf0a1848da4 \
66
- --hash=sha256:757168feb5679647c0bb13ee5d0faebe799c4dff9051419885a566ebd79f949d \
67
- --hash=sha256:80f79dae613ce9e0ea1fd1ae15616ca9ac74aed4c770aabc199c4f03ebecc863 \
68
- --hash=sha256:87dab080f8f7d32781c2586904e3603f4e60d09bfc727706c3ae419e0829beeb \
69
- --hash=sha256:acc3851cf2576a8fb2ae926da863f4efabe21303cf292e9a44332802ab0dcc6a \
70
- --hash=sha256:b01fe18dbbd151a2403d2c64ed30dc6547b00d6babab9a617d77c7acdb81ee66 \
71
- --hash=sha256:b91569d5f1b61c34b043687da02c05dd3604f3d329e7868510bf3f7971599006 \
72
- --hash=sha256:d406ec79053c0871817f700c2ac8c36ba0d87f9c34b7458b0f0063bb218b0466 \
73
- --hash=sha256:e3e88a7a75d7d95cbee1f37dc31341d6201124cf21c6c4b1dfab8ccba9b09e0f \
74
- --hash=sha256:fa029678be1ba7f953c409b0b27bf15cc69cd1c9b3a674fbd78856ebefca1052 \
75
- --hash=sha256:fcfd6c22418e57dd5b3aea649e813b2e2cfb2aebf317b210d90f1fe4b3018b52
76
- # via huggingface-hub
77
- httpcore==1.0.9 \
78
- --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \
79
- --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8
80
- # via httpx
81
- httptools==0.9.0 \
82
- --hash=sha256:02bc5b3dcb6394b9d825fd62a7bfa0b2943063a3c89abc4492ad45e334a20eb5 \
83
- --hash=sha256:050f7ab098121873c8f13e35857f97ab60a76185c8302bde9a384939bb7c3b96 \
84
- --hash=sha256:050f84b7ec46a6efe0e5f521cf8729e3397c1cef4384f62ed8d5d68ca0045776 \
85
- --hash=sha256:06bfe7fad972a417269d8a5fc53b87e4eca970354abf5e9e24336fd06d64292e \
86
- --hash=sha256:088de1738e1af624466a01c35d652dbe6fb825be887c76d68aa850621d81db88 \
87
- --hash=sha256:0adc974916efe1fbf89d0363a86dcb2c746727643e362ff398de1a4b50b6bc77 \
88
- --hash=sha256:0cc339a807c156d840b54f8bf050ba0fc265eb81692c24bca8535b52fbd797c6 \
89
- --hash=sha256:130635fea6e611a6b2026120037965ddb88b3dafd11bb64e264b101a70a76630 \
90
- --hash=sha256:18d800aaa2d6bff7d889df810d1b19a5fde72b1f6c0ca96e8d9f28a692fe5460 \
91
- --hash=sha256:1a4050a651e1f2faf05eb028ce9f2168abbcee9e24b209f5c1f2eb96d8c569e4 \
92
- --hash=sha256:1a7f1df31829c258158be01bb04eb668c4fba7df1ddf2262131a972962e651b6 \
93
- --hash=sha256:1f6da814aeecbc6cb8872d6d3e85ed16e8ab1653f9557cea8658725ce212348a \
94
- --hash=sha256:2095207b75a83c9e947346da9c127fb7e4fb29f41589df2643764f06b750989c \
95
- --hash=sha256:2319858018eedd0c0b2f950a620413c0a9d1352607be4267eb28209eca8b1e3f \
96
- --hash=sha256:26e1d9629f3bf70d23f0d22238152aec51c837a7c9e384cb74f356fdccad7eb3 \
97
- --hash=sha256:29b0d823e3c1e7cd1093a5dc889245db693ef13ada624cd66e2262421ef38867 \
98
- --hash=sha256:34266cec8c1d4e3e91fcca7efe38971d6bdda64a7944f2a46ab576da15173680 \
99
- --hash=sha256:36fac804b8cfd6b935ae64f71349f833d2b6298404626d017a2c57bb942bc643 \
100
- --hash=sha256:3af4e45ff455fce5511fdf2653c1ce428ef09c56fe37a83eb4d924c2d474f31e \
101
- --hash=sha256:3e3201fe4d46e0d15d7ff9fafc94a605da9eb82d2c5b9837f0368acb325481f1 \
102
- --hash=sha256:45b3002392948dcf578029c89f6318e1289a993a1a5ec38a4161560fab60f811 \
103
- --hash=sha256:465bc1526debf53a3be92022a16ca0c38f891ea3b5c1587af4f52e44020f8a07 \
104
- --hash=sha256:4a4d8c2c7e73ba5967be74d7c3a5ff81fde815ee1b48d9c5c0f14de8463a847b \
105
- --hash=sha256:4c58dc91aefb31adad500aa68054334f429b840b36dd29e34e834101044cb2ef \
106
- --hash=sha256:4efbee349138a3fee7a4cc3a95abd2d499fae70dd5bff9fed9138d6f570f4283 \
107
- --hash=sha256:4fb995082fe41ec410b33c48b54fb1d44abb8a6ee762c31e8c42519e8c3a30a9 \
108
- --hash=sha256:52fe0176682a25b15370f23f5b0f1366a84771df89144fb0cd979cb72a94b5ca \
109
- --hash=sha256:58a1b0ec4cbb930e69669f9771715b2c7898d3cdf064d9811f7a66afef96b544 \
110
- --hash=sha256:63d38e9a9a10a20fb57593742e63c6b1e78dd7f6ef5472de8e0b1e4cf4f3db26 \
111
- --hash=sha256:6b1ac7f1bc6c0dbf90684b77571a51a21b2463909fd916ce0ac9bfc4d566dc75 \
112
- --hash=sha256:6b900073e7b8481ef1aaf4f6c1789d210a1db01a9da8789821578cfeb4c2d540 \
113
- --hash=sha256:6c12d0393a903b58bc5f5a7406d6c5290acfb8284290d68547ce620c06f7d133 \
114
- --hash=sha256:6ebd39ee26db460cfe5ab8b71a15d1149b289139a0d3981522757d6af620887e \
115
- --hash=sha256:6f9549ca354a1d6d6167c458a1f1b12147726b968f02dd64b6a5801dba91ae0f \
116
- --hash=sha256:6ff0145b34610e57c9fae20df4e133c8d54266447387de6fcc0bdabfe4db4569 \
117
- --hash=sha256:6ff5f0ed70783dcb9562dbd20edca51c3d4d277f128223709e3da6b75986d1d4 \
118
- --hash=sha256:714bf348f468532d86bed670837e7d5ddff3834dd7f5d3c08066da400c86f088 \
119
- --hash=sha256:757e3f79cb865a7db94e0db5f4d0ed3284a69e39d53568f433982ea13c60cac1 \
120
- --hash=sha256:7e32b83bd8c2f8b6fa726ef34e63e21c4d7eddc277d40d4ef7245ea3ed28e5b6 \
121
- --hash=sha256:805b0f2618e5d4c3e28f45b731eb1a0539691ae4a2f97b4ce014de0bf96a1ff5 \
122
- --hash=sha256:80eae881cfb69383303e9a4d7961a478025b89c24f38f2e69b30c516fa0d57f2 \
123
- --hash=sha256:813a32f94991b9627795528053c73a57d2ce3eb98ede89f0e1c7a31095938e81 \
124
- --hash=sha256:8463b34ebde3f000627e9dbd8a545f995ad49fbf7ff9dd5abc0cd507da98a603 \
125
- --hash=sha256:8d90d10e9b6594c28f27896a68fab97fd784c43804e9fe419dab8e8dcfcf4b02 \
126
- --hash=sha256:8e1e037bb57dbc549c6fe20370b763ea74bdb09413cdcf857e4f14d9e4e2fb13 \
127
- --hash=sha256:931f45f84e15daafec5f82cc92e6710569e1f50933f3253d206eab4132bec678 \
128
- --hash=sha256:995b52f7c260ac7023640221f27472303968753cb6fc6fce1ddfb0e9db59a398 \
129
- --hash=sha256:9b4da5789d7cf576c7e81f0088c632f6ee3786d87d17f08e90e703c22ce15633 \
130
- --hash=sha256:b2ab3aad55d75d0b8df8d8a1b5920baaec9b161112cd5e95984848b4d2cd3dfe \
131
- --hash=sha256:b2cc6991f16f6d666d48e4b57318104e7b29109e32e2f6b86e9d44c4e6a27f4e \
132
- --hash=sha256:b5a3f5f70967a1aa2bc47fec42a1e19d2fb38c61700e3ee62b63a4af4f4fd001 \
133
- --hash=sha256:b6ee42112d785a913dd63ec0335435a3dddbea5040c151252db815b0095cf066 \
134
- --hash=sha256:b928ab0ecaa664e8caecc529dcb8bc881b6b35bb2b74bf9a39ae25f982ee8812 \
135
- --hash=sha256:b9430f65db521db7962ad951571d446171213686f96c998a54dc18ed574821e2 \
136
- --hash=sha256:b9cd15cb7cf0d5cc41f649fd789aae12c56c3b83eff593f8e095c1d4555ad5c3 \
137
- --hash=sha256:bb1533541c729ad422f870a780d8b4af924f9817d45b5f580390418cda72eaa2 \
138
- --hash=sha256:bca180cbe84e4fba7807eb408a8655295f697928512324517e30a091ede522a8 \
139
- --hash=sha256:beb2c8a34cc90fb4d862b7284eafdb322030d6a8b2ee5eb6a744f84205beedc3 \
140
- --hash=sha256:bfdabac0c6d3d6a5be8c2a100a001c92c14a39bbafd5999545a675c493626e64 \
141
- --hash=sha256:c0e45def4d9ce7073e2226535572442d9d6efb4047c7a5fd8960807e877ce70a \
142
- --hash=sha256:c0f537e5e8152e8d9cae82804024790cb973061abd3b7ef8f66f46e2b5c7bb51 \
143
- --hash=sha256:c42424213c28804f8d0e20f5692106cfb57bf72e1dbc4092b8481fb2f9e4c707 \
144
- --hash=sha256:cb2bb3ac0af7fdab2311b895c9eb95442b45deb14cc949b9e65545e74aa0be69 \
145
- --hash=sha256:cd3e55223a77d6e08d5730ebacb4930ecca5d2ce7c57e7ba10833be7e52903f1 \
146
- --hash=sha256:ce8e723b4637034b76f5382a30a6b725518c332273e8d62a6c7d46e90837c947 \
147
- --hash=sha256:d1e329a1866981efe0201d05a374617f6c6cf14434a501d78ab22793d1ab1fa6 \
148
- --hash=sha256:d3906b5c549ff2ad2473cb711e1fc65d76715c2726a402108fbf55eab6c6b49d \
149
- --hash=sha256:d484ebb7e3a3f3597b0f645fbd1b85633674ca808c1f5ba11c2caf7c66f5c8b6 \
150
- --hash=sha256:db735a23ecb0f0450d2b24e0a05fb00a8a35c9db172919c4d3e023e7c7ee4c9b \
151
- --hash=sha256:dbc9fd1521e573045d71b6afab7398439c5cc259e8cb9d416fe62d485c4899c6 \
152
- --hash=sha256:df3867518b205be3648e2fbd522bf380c851b5c2500588047505afdd786b6669 \
153
- --hash=sha256:e0acbd474d0af4afacc6e66c4273f8a19e25f8af4379fc816388095ea6b01371 \
154
- --hash=sha256:eae4e9c7a0785a1a715de0a74fb822ab40084c060f444f18f075d05e322aa7ef \
155
- --hash=sha256:edd5aa045fa3cc57143db018dd32ce7962bd5b525d05230709015d7e570100aa \
156
- --hash=sha256:f67db0ba2bedafec15b8e5330d40da1e1c7921559fa715af021252bfef81a6f8 \
157
- --hash=sha256:f78f7ae1c2e5aabf29583fc0d302d8081a663776f84578025662eb6f5d63a921 \
158
- --hash=sha256:f9489c1d87160c126f73b004742fe8654fa1ce37ed89e9e01330a1c10aaecde4 \
159
- --hash=sha256:f9ccc9884241efceb4547a92955d128574c864681f11b7ea3ecbde295fafbe8b \
160
- --hash=sha256:fc1a4f9d18d32a6e0a0a0a382986a60a2126f5144dd08715be7adb8df18e8a46
161
- # via uvicorn
162
- httpx==0.28.1 \
163
- --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \
164
- --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
165
- # via
166
- # huggingface-hub
167
- # legion
168
- huggingface-hub==1.33.0 \
169
- --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \
170
- --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e
171
- # via legion
172
- idna==3.20 \
173
- --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
174
- --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
175
- # via
176
- # anyio
177
- # httpx
178
- jinja2==3.1.6 \
179
- --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \
180
- --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67
181
- # via legion
182
- markdown-it-py==4.2.0 \
183
- --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
184
- --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
185
- # via rich
186
- markupsafe==3.0.4 \
187
- --hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \
188
- --hash=sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b \
189
- --hash=sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653 \
190
- --hash=sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c \
191
- --hash=sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e \
192
- --hash=sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc \
193
- --hash=sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92 \
194
- --hash=sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f \
195
- --hash=sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4 \
196
- --hash=sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7 \
197
- --hash=sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691 \
198
- --hash=sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc \
199
- --hash=sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde \
200
- --hash=sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99 \
201
- --hash=sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9 \
202
- --hash=sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df \
203
- --hash=sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5 \
204
- --hash=sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17 \
205
- --hash=sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8 \
206
- --hash=sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea \
207
- --hash=sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248 \
208
- --hash=sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741 \
209
- --hash=sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6 \
210
- --hash=sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7 \
211
- --hash=sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1 \
212
- --hash=sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67 \
213
- --hash=sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f \
214
- --hash=sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9 \
215
- --hash=sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c \
216
- --hash=sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc \
217
- --hash=sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba \
218
- --hash=sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17 \
219
- --hash=sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6 \
220
- --hash=sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2 \
221
- --hash=sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163 \
222
- --hash=sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b \
223
- --hash=sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634 \
224
- --hash=sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38 \
225
- --hash=sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed \
226
- --hash=sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c \
227
- --hash=sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148 \
228
- --hash=sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a \
229
- --hash=sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f \
230
- --hash=sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811 \
231
- --hash=sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2 \
232
- --hash=sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6 \
233
- --hash=sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed \
234
- --hash=sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0 \
235
- --hash=sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b \
236
- --hash=sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96 \
237
- --hash=sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59 \
238
- --hash=sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2 \
239
- --hash=sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65 \
240
- --hash=sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72 \
241
- --hash=sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8 \
242
- --hash=sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e \
243
- --hash=sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a \
244
- --hash=sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2 \
245
- --hash=sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453 \
246
- --hash=sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6 \
247
- --hash=sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977 \
248
- --hash=sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978 \
249
- --hash=sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581 \
250
- --hash=sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369 \
251
- --hash=sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a \
252
- --hash=sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916 \
253
- --hash=sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b \
254
- --hash=sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f \
255
- --hash=sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c \
256
- --hash=sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464 \
257
- --hash=sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9 \
258
- --hash=sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee \
259
- --hash=sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300 \
260
- --hash=sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6 \
261
- --hash=sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d \
262
- --hash=sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46 \
263
- --hash=sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97 \
264
- --hash=sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733 \
265
- --hash=sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe \
266
- --hash=sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429 \
267
- --hash=sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39 \
268
- --hash=sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894 \
269
- --hash=sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c \
270
- --hash=sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c \
271
- --hash=sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77 \
272
- --hash=sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe \
273
- --hash=sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad \
274
- --hash=sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85 \
275
- --hash=sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e \
276
- --hash=sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34 \
277
- --hash=sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c \
278
- --hash=sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749 \
279
- --hash=sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214 \
280
- --hash=sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932 \
281
- --hash=sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494 \
282
- --hash=sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1 \
283
- --hash=sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0 \
284
- --hash=sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786 \
285
- --hash=sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78 \
286
- --hash=sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e \
287
- --hash=sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289 \
288
- --hash=sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c \
289
- --hash=sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe \
290
- --hash=sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237 \
291
- --hash=sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19 \
292
- --hash=sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977
293
- # via jinja2
294
- mdurl==0.1.2 \
295
- --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
296
- --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
297
- # via markdown-it-py
298
- opentelemetry-api==1.45.1 \
299
- --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \
300
- --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb
301
- # via fastapi
302
- packaging==26.3 \
303
- --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
304
- --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
305
- # via
306
- # huggingface-hub
307
- # legion
308
- pydantic==2.14.1 \
309
- --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \
310
- --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26
311
- # via
312
- # fastapi
313
- # legion
314
- pydantic-core==2.50.1 \
315
- --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \
316
- --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \
317
- --hash=sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019 \
318
- --hash=sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685 \
319
- --hash=sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b \
320
- --hash=sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482 \
321
- --hash=sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658 \
322
- --hash=sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498 \
323
- --hash=sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec \
324
- --hash=sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a \
325
- --hash=sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b \
326
- --hash=sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4 \
327
- --hash=sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a \
328
- --hash=sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8 \
329
- --hash=sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb \
330
- --hash=sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e \
331
- --hash=sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8 \
332
- --hash=sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7 \
333
- --hash=sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a \
334
- --hash=sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e \
335
- --hash=sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396 \
336
- --hash=sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255 \
337
- --hash=sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899 \
338
- --hash=sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43 \
339
- --hash=sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb \
340
- --hash=sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f \
341
- --hash=sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d \
342
- --hash=sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415 \
343
- --hash=sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c \
344
- --hash=sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea \
345
- --hash=sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2 \
346
- --hash=sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e \
347
- --hash=sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568 \
348
- --hash=sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6 \
349
- --hash=sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a \
350
- --hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9 \
351
- --hash=sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1 \
352
- --hash=sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff \
353
- --hash=sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f \
354
- --hash=sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5 \
355
- --hash=sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb \
356
- --hash=sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4 \
357
- --hash=sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0 \
358
- --hash=sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597 \
359
- --hash=sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b \
360
- --hash=sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa \
361
- --hash=sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242 \
362
- --hash=sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f \
363
- --hash=sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc \
364
- --hash=sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f \
365
- --hash=sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c \
366
- --hash=sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61 \
367
- --hash=sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102 \
368
- --hash=sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4 \
369
- --hash=sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e \
370
- --hash=sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54 \
371
- --hash=sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070 \
372
- --hash=sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed \
373
- --hash=sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb \
374
- --hash=sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5 \
375
- --hash=sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19 \
376
- --hash=sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5 \
377
- --hash=sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112 \
378
- --hash=sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9 \
379
- --hash=sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5 \
380
- --hash=sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72 \
381
- --hash=sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2 \
382
- --hash=sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8 \
383
- --hash=sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295 \
384
- --hash=sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e \
385
- --hash=sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe \
386
- --hash=sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290 \
387
- --hash=sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea \
388
- --hash=sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662 \
389
- --hash=sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41 \
390
- --hash=sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44 \
391
- --hash=sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807 \
392
- --hash=sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78 \
393
- --hash=sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c \
394
- --hash=sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3 \
395
- --hash=sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831 \
396
- --hash=sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86 \
397
- --hash=sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2 \
398
- --hash=sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f \
399
- --hash=sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f \
400
- --hash=sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10 \
401
- --hash=sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5 \
402
- --hash=sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b \
403
- --hash=sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09 \
404
- --hash=sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a \
405
- --hash=sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e \
406
- --hash=sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459 \
407
- --hash=sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08 \
408
- --hash=sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709 \
409
- --hash=sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a \
410
- --hash=sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20
411
- # via pydantic
412
- pygments==2.21.0 \
413
- --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
414
- --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
415
- # via rich
416
- python-dotenv==1.2.4 \
417
- --hash=sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc \
418
- --hash=sha256:f0d53e69935a851c0dcc78f3ab7aaccd8cabef0b92382b576b824212902873c0
419
- # via uvicorn
420
- pyyaml==6.0.3 \
421
- --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \
422
- --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \
423
- --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \
424
- --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \
425
- --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \
426
- --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \
427
- --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \
428
- --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \
429
- --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \
430
- --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \
431
- --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \
432
- --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \
433
- --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \
434
- --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \
435
- --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \
436
- --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \
437
- --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \
438
- --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \
439
- --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \
440
- --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \
441
- --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \
442
- --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \
443
- --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \
444
- --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \
445
- --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \
446
- --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \
447
- --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \
448
- --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \
449
- --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \
450
- --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \
451
- --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \
452
- --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \
453
- --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \
454
- --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \
455
- --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \
456
- --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \
457
- --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \
458
- --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \
459
- --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0
460
- # via
461
- # huggingface-hub
462
- # legion
463
- # uvicorn
464
- rich==15.0.0 \
465
- --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
466
- --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36
467
- # via typer
468
- shellingham==1.5.4 \
469
- --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \
470
- --hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de
471
- # via typer
472
- starlette==1.8.0 \
473
- --hash=sha256:1565dc0b35d5737a271ed1e0e04e949f4e81198799f216d2667b0a0fb9cf9522 \
474
- --hash=sha256:dfdd6b29c26483288088d990eee59631dedadd66ce20d203402a7ca8e3c4656f
475
- # via fastapi
476
- tomli==2.5.0 \
477
- --hash=sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea \
478
- --hash=sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd \
479
- --hash=sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0 \
480
- --hash=sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391 \
481
- --hash=sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df \
482
- --hash=sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9 \
483
- --hash=sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066 \
484
- --hash=sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f \
485
- --hash=sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57 \
486
- --hash=sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6 \
487
- --hash=sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b \
488
- --hash=sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3 \
489
- --hash=sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043 \
490
- --hash=sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01 \
491
- --hash=sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646 \
492
- --hash=sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859 \
493
- --hash=sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b \
494
- --hash=sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc \
495
- --hash=sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5 \
496
- --hash=sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0 \
497
- --hash=sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb \
498
- --hash=sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84 \
499
- --hash=sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6 \
500
- --hash=sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b \
501
- --hash=sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b \
502
- --hash=sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52 \
503
- --hash=sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd \
504
- --hash=sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75 \
505
- --hash=sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142 \
506
- --hash=sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03 \
507
- --hash=sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea \
508
- --hash=sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374 \
509
- --hash=sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3 \
510
- --hash=sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276 \
511
- --hash=sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b \
512
- --hash=sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc \
513
- --hash=sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68 \
514
- --hash=sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a \
515
- --hash=sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f \
516
- --hash=sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b \
517
- --hash=sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7 \
518
- --hash=sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0 \
519
- --hash=sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb \
520
- --hash=sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7 \
521
- --hash=sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7 \
522
- --hash=sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105 \
523
- --hash=sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5 \
524
- --hash=sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d \
525
- --hash=sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2 \
526
- --hash=sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4 \
527
- --hash=sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7 \
528
- --hash=sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1 \
529
- --hash=sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571 \
530
- --hash=sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a \
531
- --hash=sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442 \
532
- --hash=sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc
533
- # via legion
534
- tqdm==4.70.1 \
535
- --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \
536
- --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4
537
- # via huggingface-hub
538
- typer==0.27.3 \
539
- --hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \
540
- --hash=sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff
541
- # via legion
542
- typing-extensions==4.16.0 \
543
- --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
544
- --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
545
- # via
546
- # anyio
547
- # exceptiongroup
548
- # fastapi
549
- # huggingface-hub
550
- # opentelemetry-api
551
- # pydantic
552
- # pydantic-core
553
- # starlette
554
- # typing-inspection
555
- typing-inspection==0.4.4 \
556
- --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \
557
- --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147
558
- # via
559
- # fastapi
560
- # pydantic
561
- uvicorn==0.54.0 \
562
- --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \
563
- --hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620
564
- # via legion
565
- uvloop==0.23.0 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \
566
- --hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \
567
- --hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \
568
- --hash=sha256:12634f15e6625f78b3f2922f91404c4d7173487eba11746764153f556e9852dc \
569
- --hash=sha256:1748321e3c59a14a75404b1ae8d5a8d81c4e201803ea0e14c1b6fd84421024b5 \
570
- --hash=sha256:19c64108b507cd0bc140e400e3396bacebd9d504956aa7726272bf6de7d9aabb \
571
- --hash=sha256:1e84575f11873c109cf3962ad0bdf679094466184125f4cadcc41a73febff41f \
572
- --hash=sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27 \
573
- --hash=sha256:2dcff2d69be43e6559e5dad2c5a7a2dbfb60e05a77311b6c4b7a4a8123d86c65 \
574
- --hash=sha256:31e0cf90bc8fd88784f6802cdba968a51fb1aec1cc3feec74d862b2d371d1330 \
575
- --hash=sha256:378188efbb1524f2219d05246a3e1e5907217848d2882144dff59585f1b81d55 \
576
- --hash=sha256:4448e9124537620f9c25d004c227bb5104440b58955c19bbd312d910af919a63 \
577
- --hash=sha256:4a08875543bbd4519faf30497506c9cda8a48470467ffdf967c7313c7a5981a8 \
578
- --hash=sha256:4b8e207c67d207a8608fec57e116511030af3495dc0109b8c333cf9cb412b16f \
579
- --hash=sha256:4f1798f56c6f4ba5ac11fa2869e5717926e4470d97a1dd42b4f59219d43b5027 \
580
- --hash=sha256:5a2bbad3a63007f7e9524d4903ba04fee252557c2acd86f9a3d4f91786695254 \
581
- --hash=sha256:5bb9be71d9ee39b4359b832f9569518ec9bc08704194034e79e4958e6bc4d46d \
582
- --hash=sha256:6b3cbc4f96ddfa1fb88a78a69dd851369825b7816d9702eee8c4461505ba172e \
583
- --hash=sha256:6c7ef4701a96553514b2688e342ef1bf2beae6cfd172d89a76c768292aabf405 \
584
- --hash=sha256:7337b06a9f9ed9ea3049f04b76f65819db9b19bb832ee598e97b388eadf25e5f \
585
- --hash=sha256:76345f51367fb1f23e08605c6efb18374f669be5b223658fbab6b17627950507 \
586
- --hash=sha256:7e35c9bc977760981693e1a7a51493b58ee5a501f9ebb1e547565ee40b6c6208 \
587
- --hash=sha256:93935ab27b6eaef4c3e5489aebc84284f0644592f7ab516df60ee1b27eaf5eb3 \
588
- --hash=sha256:a6ac96da66c35bf789bdcde78a88dc7d56b7907d8379648c54adc1c61594575d \
589
- --hash=sha256:b90397a50ad6332ed3e459c648ac20d182cce24a557354363ad85fc9ea4a17cd \
590
- --hash=sha256:bbbdb8fcd5e7062e546eec1ac78c28bb21ae7df54c18f8e4b06e15a18d661a49 \
591
- --hash=sha256:bd6f2f81c7b9da99d301c0b16b82044e76fe887086e42e1590ecf520b94dbdac \
592
- --hash=sha256:be53e1d5f83de43dc175c87612ecc128d444b38e5c56cb3f807f5a73d6887476 \
593
- --hash=sha256:c3f23f403a273900d57de6ee5ca0614c650f7f58563065dad1a4744498960e53 \
594
- --hash=sha256:cbe8d03d4efcccdb7fcedecbaa1e1fa02913eaf3a74cb933634a6bc6d2ea9e2a \
595
- --hash=sha256:dc61e4f9e37b507069dc7e659ae28bca7adcb04c993c3508214315d12c63f848 \
596
- --hash=sha256:e095f9e105af76593b4c183bb0bcbdae64bd913a59ec595732dc108b48730ab5 \
597
- --hash=sha256:e2cba180d6451822763eda8364f342435a873bcfb3849cbd82fdeca248ca65eb \
598
- --hash=sha256:f1341c6abcee1c31277cfe28d34e46196f2143ec3d755e6efe7452126e1f626d \
599
- --hash=sha256:f3fbfe82829d8e381426a289b87e59e585278728361db9ce975b88b51f64f410 \
600
- --hash=sha256:f673d835bdb1a60229cc3609a113fd2c9ce3f4a3c75ad4eaed111180c00199d2 \
601
- --hash=sha256:f7548ede3ee908cfabc0d068106e303a9a2d811af959cdf6ab85676344cedcda \
602
- --hash=sha256:fa8ed556fcc87a4091cf61587ef172fa104323dc89ecc085a618ba7ff8629a8f
603
- # via uvicorn
604
- watchfiles==1.3.0 \
605
- --hash=sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441 \
606
- --hash=sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95 \
607
- --hash=sha256:04c5500faa725d69a99b0f63750e80795e455bb951849e9c98a811b4324997c4 \
608
- --hash=sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61 \
609
- --hash=sha256:26b81bc515a0f03f66a69a6fea86eea54c8eca4173c46dd7222569f79dd2f977 \
610
- --hash=sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509 \
611
- --hash=sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5 \
612
- --hash=sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661 \
613
- --hash=sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30 \
614
- --hash=sha256:7c1125e99f84934a92996ae343501285617373acd66f16b59fd5654b27ad8d80 \
615
- --hash=sha256:81c989d7267bfb7b676cd32c83bec97914e396870983cbf493e29415037bff5e \
616
- --hash=sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207 \
617
- --hash=sha256:a5b631db08fd3032db57ec6a92d1777cd60f88803287e4e941a4858c53aab1e0 \
618
- --hash=sha256:a85e243c87109d9f48a2e0d10d6abdee8768cc114848b32281ec83d7f81d86ef \
619
- --hash=sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1 \
620
- --hash=sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c \
621
- --hash=sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29 \
622
- --hash=sha256:ca39661934749df580d89f3dde266f2af7c6968f4c21c72ce2dc387d299e6aa7 \
623
- --hash=sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935 \
624
- --hash=sha256:d4593392e87669836670f87d62fc754059eaeb0e6157af44060a46558cebe5a3 \
625
- --hash=sha256:d754e049006e81a9be49dc78ba7802081cee426e968cbc63ee19e164fa2d0e39 \
626
- --hash=sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc \
627
- --hash=sha256:da213822ec9082b62cadf3008e07a8c690ec7a3c89f6dc5e55a8cf07b56a1b26 \
628
- --hash=sha256:dd538c71766c59c732e2c5cedc39323c99c11897b99f93eac773438e54af206a \
629
- --hash=sha256:e0204f90677b7fb8d3a824279a71a01166bea9f6e53923b8056592d87b33b0b6 \
630
- --hash=sha256:e5871d4a7f788a9f64fb06f5793389d29d171e5c32d37c3ebfd520b017cc7694 \
631
- --hash=sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca \
632
- --hash=sha256:ec3cd4bb181a7b6329134204c2277c7144ab5f62cce9c5335d6f901ee7ce8d6a \
633
- --hash=sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3
634
- # via uvicorn
635
- websockets==15.0.1 \
636
- --hash=sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2 \
637
- --hash=sha256:0af68c55afbd5f07986df82831c7bff04846928ea8d1fd7f30052638788bc9b5 \
638
- --hash=sha256:0f3c1e2ab208db911594ae5b4f79addeb3501604a165019dd221c0bdcabe4db8 \
639
- --hash=sha256:229cf1d3ca6c1804400b0a9790dc66528e08a6a1feec0d5040e8b9eb14422375 \
640
- --hash=sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597 \
641
- --hash=sha256:3c714d2fc58b5ca3e285461a4cc0c9a66bd0e24c5da9911e30158286c9b5be7f \
642
- --hash=sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3 \
643
- --hash=sha256:558d023b3df0bffe50a04e710bc87742de35060580a293c2a984299ed83bc4e4 \
644
- --hash=sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665 \
645
- --hash=sha256:595b6c3969023ecf9041b2936ac3827e4623bfa3ccf007575f04c5a6aa318c22 \
646
- --hash=sha256:5a939de6b7b4e18ca683218320fc67ea886038265fd1ed30173f5ce3f8e85675 \
647
- --hash=sha256:5d54b09eba2bada6011aea5375542a157637b91029687eb4fdb2dab11059c1b4 \
648
- --hash=sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65 \
649
- --hash=sha256:746ee8dba912cd6fc889a8147168991d50ed70447bf18bcda7039f7d2e3d9151 \
650
- --hash=sha256:756c56e867a90fb00177d530dca4b097dd753cde348448a1012ed6c5131f8b7d \
651
- --hash=sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee \
652
- --hash=sha256:ba9e56e8ceeeedb2e080147ba85ffcd5cd0711b89576b83784d8605a7df455fa \
653
- --hash=sha256:c338ffa0520bdb12fbc527265235639fb76e7bc7faafbb93f6ba80d9c06578a9 \
654
- --hash=sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe \
655
- --hash=sha256:e09473f095a819042ecb2ab9465aee615bd9c2028e4ef7d933600a8401c79561 \
656
- --hash=sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215 \
657
- --hash=sha256:ee443ef070bb3b6ed74514f5efaa37a252af57c90eb33b956d35c8e9c10a1931 \
658
- --hash=sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f \
659
- --hash=sha256:fcd5cf9e305d7b8338754470cf69cf81f420459dbae8a3b40cee57417f4614a7
660
- # via uvicorn
 
1
+ huggingface_hub==1.33.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
world/sandbox.py CHANGED
@@ -18,8 +18,8 @@ import urllib.request
18
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
  from pathlib import Path
20
 
21
- from legion.isolation import command as isolate_command
22
- from legion.world import ToolError
23
 
24
  # The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree
25
  # for the shared tests: main grows by about one file per merge, so the cap allows a long run.
@@ -228,6 +228,6 @@ class _Handler(BaseHTTPRequestHandler):
228
  if __name__ == "__main__" and sys.argv[1:] == ["serve"]:
229
  if not os.environ.get("PYBOT_SANDBOX_TOKEN"):
230
  sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused
231
- from legion.isolation import protect_supervisor
232
  protect_supervisor() # a bot under this uid cannot read this process's env or memory
233
  ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever()
 
18
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
  from pathlib import Path
20
 
21
+ from api import ToolError
22
+ from isolation import command as isolate_command
23
 
24
  # The sidecar's caps: a request, and an extracted tree. Merges send main + the PR's whole tree
25
  # for the shared tests: main grows by about one file per merge, so the cap allows a long run.
 
228
  if __name__ == "__main__" and sys.argv[1:] == ["serve"]:
229
  if not os.environ.get("PYBOT_SANDBOX_TOKEN"):
230
  sys.exit("sandbox.py serve: PYBOT_SANDBOX_TOKEN is not set") # else every call is refused
231
+ from isolation import protect_supervisor
232
  protect_supervisor() # a bot under this uid cannot read this process's env or memory
233
  ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "8000"))), _Handler).serve_forever()
world/scripts/check-sidecar.py CHANGED
@@ -7,7 +7,7 @@ along), and a test cannot import socket or write a file; a tree of 3,000 more fi
7
  main) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logs
8
  its HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeout
9
  works.
10
- Local path without `unshare` (blocked on many boxes). Needs requirements.txt and legion, 3.12+.
11
  """
12
  import base64
13
  import io
@@ -54,7 +54,7 @@ def member(name, size=4, kind=tarfile.REGTYPE, link=""):
54
 
55
  def main():
56
  import sandbox
57
- from legion.world import ToolError
58
 
59
  with socket.socket() as s:
60
  s.bind(("127.0.0.1", 0))
 
7
  main) goes through for both; a bad token or an unreachable sidecar is `busy`, and a refusal logs
8
  its HTTP status; a tar with `../`, a link, too many members or too many bytes is a 400; a timeout
9
  works.
10
+ Local path without `unshare` (blocked on many boxes). Needs requirements.txt, 3.12+.
11
  """
12
  import base64
13
  import io
 
54
 
55
  def main():
56
  import sandbox
57
+ from api import ToolError
58
 
59
  with socket.socket() as s:
60
  s.bind(("127.0.0.1", 0))
world/scripts/smoke-local.py CHANGED
@@ -2,11 +2,11 @@
2
 
3
  Starts PybotWorld from world/ with plain Python on a free port, backed by a FAKE
4
  in-process hub (a local bare git repo + LocalHub, injected as `repository`; the shipped code still
5
- defaults to the real Hub). Checks /healthz, the token (and a per-agent one), /manifest's tools and
6
- one run_bot call.
7
  With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only its
8
  token) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no network
9
- calls beyond localhost. Needs the deps in requirements.txt, legion (README) and git.
10
  """
11
  import json
12
  import os
@@ -24,7 +24,7 @@ SRC = Path(__file__).resolve().parent.parent # world/
24
  sys.path.insert(0, str(SRC))
25
  TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict",
26
  "verdicts", "run_bot", "world_status"}
27
- TOKEN = "smoke-token"
28
 
29
 
30
  def git(path, *args):
@@ -47,11 +47,11 @@ class LocalHub: # tests/test_pybot.py's fake: PRs are refs/pr/N in the bare rem
47
  def merge(self, pr, comment): raise NotImplementedError("not used by this smoke")
48
 
49
 
50
- def call(port, method, path, body=None, token=TOKEN, agent="smoke"):
51
  req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method,
52
  data=None if body is None else json.dumps(body).encode(),
53
- headers={"Content-Type": "application/json", "X-Legion-Agent": agent,
54
- **({"X-World-Token": token} if token else {})})
55
  try:
56
  with urllib.request.urlopen(req, timeout=60) as r:
57
  return r.status, json.loads(r.read())
@@ -84,11 +84,9 @@ def start_sidecar(tmp):
84
 
85
 
86
  def main(sidecar=False):
87
- import uvicorn
88
  from pybot import PybotWorld
89
  from repository import Repository
90
-
91
- from legion.world.server import create_app
92
 
93
  tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-"))
94
  os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="") # the fake hub ignores both
@@ -96,7 +94,7 @@ def main(sidecar=False):
96
  subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True)
97
  git(seed, "init", "-q", "-b", "main")
98
  git(seed, "add", ".")
99
- git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-qm", "seed")
100
  remote = tmp / "remote.git"
101
  git(tmp, "clone", "-q", "--bare", str(seed), str(remote))
102
  repo = Repository(tmp / "ws" / "repo.git", str(remote))
@@ -106,9 +104,8 @@ def main(sidecar=False):
106
  port = free_port()
107
  if sidecar:
108
  sidecar_proc, sidecar_log = start_sidecar(tmp)
109
- server = uvicorn.Server(uvicorn.Config(create_app(world, TOKEN), host="127.0.0.1", port=port,
110
- log_level="warning"))
111
- threading.Thread(target=server.run, daemon=True).start()
112
  for _ in range(100):
113
  try:
114
  if call(port, "GET", "/healthz", token=None) == (200, {"status": "ready"}):
@@ -120,24 +117,24 @@ def main(sidecar=False):
120
  sys.exit("FAIL: /healthz never said ready")
121
  print(f"ok GET /healthz on 127.0.0.1:{port}: ready")
122
 
123
- assert call(port, "GET", "/manifest", token="wrong")[0] == 401
124
- print("ok GET /manifest with a wrong X-World-Token: 401")
125
- from legion.world.protocol import agent_token
126
- own = agent_token(TOKEN, "smoke")
127
- assert call(port, "GET", "/manifest", token=own)[0] == 200
128
- assert call(port, "GET", "/manifest", token=own, agent="other")[0] == 401
129
- print("ok GET /manifest with the agent's own token: 200; as another agent: 401")
130
- status, m = call(port, "GET", "/manifest")
131
  names = {t["name"] for t in m["tools"]}
132
  assert status == 200 and names == TOOLS, (status, names)
133
- print(f"ok GET /manifest: {m['name']} {m['version']}, {len(names)} tools: {', '.join(sorted(names))}")
134
 
135
- status, r = call(port, "POST", "/tools/run_bot",
136
  {"args": {"ref_or_path": "main", "lines": ["Hello"]}})
137
- ran = status == 200 and r["result"]["ok"] # False where unshare is not permitted (README)
138
- print(f"{'ok ' if ran else 'note'} POST /tools/run_bot main ['Hello']: {status} "
139
  f"{json.dumps(r)[:300]}")
140
- server.should_exit = True
 
 
 
141
  if sidecar:
142
  sidecar_proc.terminate()
143
  sidecar_proc.wait(10)
 
2
 
3
  Starts PybotWorld from world/ with plain Python on a free port, backed by a FAKE
4
  in-process hub (a local bare git repo + LocalHub, injected as `repository`; the shipped code still
5
+ defaults to the real Hub). Checks /healthz, the agent credentials, /world/manifest's tools and
6
+ one run_bot call on each route.
7
  With --sidecar, the bot sandbox runs as a 2nd local process (`sandbox.py serve`, given only its
8
  token) and run_bot must succeed through it. Writes nothing outside a temp dir and makes no network
9
+ calls beyond localhost. Needs the deps in requirements.txt and git.
10
  """
11
  import json
12
  import os
 
24
  sys.path.insert(0, str(SRC))
25
  TOOLS = {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr", "record_verdict",
26
  "verdicts", "run_bot", "world_status"}
27
+ TOKEN, OTHER = "smoke-credential-0", "smoke-credential-1" # agent-001, agent-002
28
 
29
 
30
  def git(path, *args):
 
47
  def merge(self, pr, comment): raise NotImplementedError("not used by this smoke")
48
 
49
 
50
+ def call(port, method, path, body=None, token=TOKEN):
51
  req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", method=method,
52
  data=None if body is None else json.dumps(body).encode(),
53
+ headers={"Content-Type": "application/json",
54
+ **({"Authorization": f"Bearer {token}"} if token else {})})
55
  try:
56
  with urllib.request.urlopen(req, timeout=60) as r:
57
  return r.status, json.loads(r.read())
 
84
 
85
 
86
  def main(sidecar=False):
 
87
  from pybot import PybotWorld
88
  from repository import Repository
89
+ from server import App, Server
 
90
 
91
  tmp = Path(tempfile.mkdtemp(prefix="pybot-smoke-"))
92
  os.environ.update(PYBOT_REPO="smoke/never-used", HF_TOKEN="") # the fake hub ignores both
 
94
  subprocess.run(["cp", "-r", str(SRC / os.environ.get("PYBOT_SEED_DIR", "seed")), str(seed)], check=True)
95
  git(seed, "init", "-q", "-b", "main")
96
  git(seed, "add", ".")
97
+ git(seed, "-c", "user.name=seed", "-c", "user.email=seed@pybot.invalid", "commit", "-qm", "seed")
98
  remote = tmp / "remote.git"
99
  git(tmp, "clone", "-q", "--bare", str(seed), str(remote))
100
  repo = Repository(tmp / "ws" / "repo.git", str(remote))
 
104
  port = free_port()
105
  if sidecar:
106
  sidecar_proc, sidecar_log = start_sidecar(tmp)
107
+ server = Server(App(world, {TOKEN: "agent-001", OTHER: "agent-002"}), "127.0.0.1", port)
108
+ threading.Thread(target=server.serve_forever, daemon=True).start()
 
109
  for _ in range(100):
110
  try:
111
  if call(port, "GET", "/healthz", token=None) == (200, {"status": "ready"}):
 
117
  sys.exit("FAIL: /healthz never said ready")
118
  print(f"ok GET /healthz on 127.0.0.1:{port}: ready")
119
 
120
+ assert call(port, "GET", "/world/manifest", token="wrong")[0] == 401
121
+ assert call(port, "GET", "/world/manifest", token=None)[0] == 401
122
+ print("ok GET /world/manifest with a wrong or no credential: 401")
123
+ assert call(port, "GET", "/world/manifest", token=OTHER)[0] == 200
124
+ status, m = call(port, "GET", "/world/manifest")
 
 
 
125
  names = {t["name"] for t in m["tools"]}
126
  assert status == 200 and names == TOOLS, (status, names)
127
+ print(f"ok GET /world/manifest: {m['name']}, {len(names)} tools: {', '.join(sorted(names))}")
128
 
129
+ status, r = call(port, "POST", "/world/tools/run_bot",
130
  {"args": {"ref_or_path": "main", "lines": ["Hello"]}})
131
+ ran = status == 200 and r["result"]["ok"] # False where unshare is not permitted
132
+ print(f"{'ok ' if ran else 'note'} POST /world/tools/run_bot main ['Hello']: {status} "
133
  f"{json.dumps(r)[:300]}")
134
+ status, r = call(port, "POST", "/v1/tools/run_bot", {"ref_or_path": "main", "lines": ["Hello"]})
135
+ assert status == 200 and r["ok"] == ran, (status, r)
136
+ print(f"ok POST /v1/tools/run_bot main ['Hello']: {status} {json.dumps(r)[:200]}")
137
+ server.shutdown()
138
  if sidecar:
139
  sidecar_proc.terminate()
140
  sidecar_proc.wait(10)
world/server.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HTTP API of a `World` (api.py), on the standard library's threaded server.
2
+
3
+ Agents (seat i is `agent-<i+1, 3 digits>`) authenticate with their credential from
4
+ `PYBOT_TOKEN_<seat>`, sent as `Authorization: Bearer <c>` or `X-World-Token: <c>`:
5
+
6
+ POST /v1/tools/<name> body: the arguments (flat JSON object)
7
+ 200 the result as JSON; refusal 4xx {"error": {"code", "message"}};
8
+ busy 429 (or 503 while starting) with Retry-After
9
+ GET /world/manifest {"name", "description", "tools": [{name, description, parameters}]}
10
+ POST /world/tools/<name> body {"args": {...}}: 200 {"ok": true, "result": ...} or
11
+ {"ok": false, "error": {"code", "message", "retry_after_s"?}}
12
+ GET /healthz no credential: {"status": "ready"} or {"status": "parked"}
13
+
14
+ Operators use `PYBOT_ADMIN_TOKEN` (never an agent credential; unset: 403) for `GET /metrics` and
15
+ `/admin/*`: GET/PATCH /admin/knobs, GET /admin/paused, POST /admin/pause, POST /admin/resume.
16
+
17
+ Admission control: the fast pool (40 threads) refuses a call that waited 2 s for a thread, the
18
+ slow pool (`@tool(pool="slow")`, 64 threads) one that finds 64 running and 8 queued: 429 with
19
+ Retry-After 30. Parked mode: the port is bound first and the world is built in a thread, again
20
+ after 30 s (doubling to 10 min) while that raises; tool calls meanwhile answer 503.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import hmac
25
+ import json
26
+ import logging
27
+ import math
28
+ import os
29
+ import re
30
+ import signal
31
+ import threading
32
+ import time
33
+ import uuid
34
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
35
+ from typing import Any
36
+
37
+ from api import Agent, ToolError, World, check_args, redact
38
+
39
+ log = logging.getLogger(__name__)
40
+ MAX_BODY = 1 << 20 # a tool call's request body
41
+ ADMIN_MAX_BODY = 64 << 10
42
+ FAST_THREADS, FAST_MAX_WAIT_S = 40, 2.0
43
+ SLOW_THREADS, SLOW_QUEUE = 64, 8
44
+ RETRY_AFTER_S = 30
45
+ PARK_FIRST_S, PARK_CAP_S = 30.0, 600.0
46
+ SEAT_ENV = re.compile(r"PYBOT_TOKEN_(\d+)")
47
+
48
+
49
+ def seat_credentials(env=os.environ) -> dict[str, str]:
50
+ """credential -> agent name, from PYBOT_TOKEN_<seat> (seat 0 is agent-001)."""
51
+ return {v: f"agent-{int(m[1]) + 1:03d}" for k, v in env.items()
52
+ if (m := SEAT_ENV.fullmatch(k)) and v}
53
+
54
+
55
+ def _credential(headers) -> str:
56
+ """`X-World-Token`, else the `Authorization: Bearer` value ("" when neither)."""
57
+ auth = headers.get("Authorization") or ""
58
+ return headers.get("X-World-Token") or (auth[7:].strip() if auth[:7].lower() == "bearer " else "")
59
+
60
+
61
+ class Refused(Exception):
62
+ """A protocol-level refusal: HTTP status, code, message, optional retry-after seconds."""
63
+
64
+ def __init__(self, status: int, code: str, message: str, retry_after_s: float | None = None):
65
+ super().__init__(message)
66
+ self.status, self.code, self.message, self.retry_after_s = status, code, message, retry_after_s
67
+
68
+
69
+ class Pool:
70
+ """A tool pool's threads with admission control (see the module docstring)."""
71
+
72
+ def __init__(self, threads: int, max_wait_s: float | None = None, queue: int | None = None):
73
+ self.slots = threading.BoundedSemaphore(threads)
74
+ self.threads, self.max_wait_s, self.queue = threads, max_wait_s, queue
75
+ self.lock = threading.Lock()
76
+ self.in_flight = self.refused = 0
77
+
78
+ def run(self, fn, *args):
79
+ with self.lock:
80
+ full = self.queue is not None and self.in_flight >= self.threads + self.queue
81
+ if not full:
82
+ self.in_flight += 1
83
+ try:
84
+ if full or not self.slots.acquire(timeout=self.max_wait_s):
85
+ with self.lock:
86
+ self.refused += 1
87
+ raise Refused(429, "overloaded", f"the world is overloaded; retry in {RETRY_AFTER_S} s",
88
+ RETRY_AFTER_S)
89
+ try:
90
+ return fn(*args)
91
+ finally:
92
+ self.slots.release()
93
+ finally:
94
+ if not full:
95
+ with self.lock:
96
+ self.in_flight -= 1
97
+
98
+
99
+ class App:
100
+ """The routes of a world: an instance, or its class (built in parked mode, `builder`)."""
101
+
102
+ def __init__(self, world: World | type[World], credentials: dict[str, str], admin_token: str = ""):
103
+ self.cls = world if isinstance(world, type) else type(world)
104
+ self.world = None if isinstance(world, type) else world
105
+ self.credentials, self.admin_token = credentials, admin_token
106
+ self.pools = {"fast": Pool(FAST_THREADS, FAST_MAX_WAIT_S), "slow": Pool(SLOW_THREADS, None, SLOW_QUEUE)}
107
+ self.manifest = self.cls.manifest()
108
+ self.schemas = {t["name"]: t["parameters"] for t in self.manifest["tools"]}
109
+ self.park = {"error": "the world is starting", "attempt": 0, "retry_at": 0.0}
110
+ self.started = time.monotonic()
111
+ self.stop = threading.Event()
112
+
113
+ def builder(self) -> None:
114
+ """Build the world, again with backoff while that raises (parked mode)."""
115
+ delay = PARK_FIRST_S
116
+ while self.world is None and not self.stop.is_set():
117
+ self.park["attempt"] += 1
118
+ try:
119
+ self.world = self.cls()
120
+ log.warning("world %s: ready after %d attempt(s)", self.cls.name, self.park["attempt"])
121
+ except BaseException as e: # SystemExit too: a parked error, not a dead thread
122
+ log.exception("world: construction failed (attempt %d); retrying in %g s",
123
+ self.park["attempt"], delay)
124
+ line = (f"{type(e).__name__}: {e}".strip().splitlines() or [""])[0][:300]
125
+ self.park.update(error=redact(line), retry_at=time.monotonic() + delay)
126
+ self.stop.wait(delay)
127
+ delay = min(delay * 2, PARK_CAP_S)
128
+
129
+ def agent(self, headers) -> str:
130
+ """The caller's agent name from its credential (401 when missing or unknown)."""
131
+ got = _credential(headers)
132
+ # Compare with every credential: the time taken does not depend on which one matched.
133
+ name = None
134
+ for credential, who in self.credentials.items():
135
+ if hmac.compare_digest(got.encode(), credential.encode()):
136
+ name = who
137
+ if not got or name is None:
138
+ raise Refused(401, "unauthorized", "missing or unknown credential")
139
+ return name
140
+
141
+ def check_admin(self, headers) -> None:
142
+ if not self.admin_token:
143
+ raise Refused(403, "forbidden", "no admin token: set PYBOT_ADMIN_TOKEN on the world")
144
+ if not hmac.compare_digest(_credential(headers).encode(), self.admin_token.encode()):
145
+ raise Refused(401, "unauthorized", "missing or wrong admin token")
146
+
147
+ def ready(self) -> World:
148
+ if self.world is None:
149
+ left = max(0.0, self.park["retry_at"] - time.monotonic())
150
+ raise Refused(503, "parked", f"the world is not ready ({self.park['error']}); attempt "
151
+ f"{self.park['attempt']}", max(1, math.ceil(left)))
152
+ return self.world
153
+
154
+ def dispatch(self, name: str, args: Any, agent: Agent) -> Any:
155
+ """Run tool `name`: its result (redacted), or ToolError / Refused."""
156
+ if name not in self.schemas:
157
+ raise Refused(404, "unknown_tool", f"no tool {name!r}; tools: {', '.join(self.schemas)}")
158
+ if err := check_args(self.schemas[name], args):
159
+ raise ToolError(f"{name}: {err}", "bad_args")
160
+ world = self.ready()
161
+ try:
162
+ result = self.pools[self.cls.pool(name)].run(world.call, name, args, agent)
163
+ return redact(json.loads(json.dumps(result, default=str)))
164
+ except (ToolError, Refused):
165
+ raise
166
+ except Exception:
167
+ # The exception text can hold paths, command output or credentials: it stays in
168
+ # the world's log, under an id the agent can quote.
169
+ ref = uuid.uuid4().hex[:8]
170
+ log.exception("tool %s failed for %s (error id %s)", name, agent.name, ref)
171
+ raise Refused(500, "internal", f"the tool failed with an internal error (error id {ref})")
172
+
173
+ def metrics(self) -> dict[str, Any]:
174
+ world = self.world
175
+ try:
176
+ custom = world.metrics() if world is not None else {}
177
+ except Exception:
178
+ log.exception("world.metrics() failed")
179
+ custom = {}
180
+ pools = {name: {"in_flight": p.in_flight, "limit": p.threads, "overloaded_429_total": p.refused}
181
+ for name, p in self.pools.items()}
182
+ return {"uptime_s": time.monotonic() - self.started, "parked": int(world is None),
183
+ "attempt": self.park["attempt"], "pools": pools, "world": custom}
184
+
185
+
186
+ class Server(ThreadingHTTPServer):
187
+ daemon_threads = True
188
+ request_queue_size = 128 # many agents connect at once
189
+
190
+ def __init__(self, app: App, host: str, port: int):
191
+ self.app = app
192
+ super().__init__((host, port), Handler)
193
+
194
+
195
+ class Handler(BaseHTTPRequestHandler):
196
+ protocol_version = "HTTP/1.1" # keep-alive: every answer has a Content-Length
197
+
198
+ def log_message(self, format, *args): # no access log
199
+ pass
200
+
201
+ def send(self, status: int, body: Any, retry_after_s: float | None = None) -> None:
202
+ data = json.dumps(body).encode()
203
+ self.send_response(status)
204
+ self.send_header("Content-Type", "application/json")
205
+ self.send_header("Content-Length", str(len(data)))
206
+ if retry_after_s is not None and status in (429, 503):
207
+ self.send_header("Retry-After", str(max(1, math.ceil(retry_after_s))))
208
+ self.end_headers()
209
+ self.wfile.write(data)
210
+
211
+ def body(self, limit: int) -> Any:
212
+ """The JSON body ({} when empty); 413 over `limit` bytes, 400 if it is not JSON."""
213
+ try:
214
+ n = int(self.headers.get("Content-Length") or 0)
215
+ except ValueError:
216
+ n = -1
217
+ if n < 0 or n > limit or "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
218
+ self.close_connection = True # the body is never read
219
+ raise Refused(413, "too_large", f"the request body must be at most {limit} bytes "
220
+ "(with Content-Length)")
221
+ data = self.rfile.read(n)
222
+ try:
223
+ return json.loads(data) if data.strip() else {}
224
+ except ValueError:
225
+ raise Refused(400, "bad_request", "the body must be JSON") from None
226
+
227
+ def do_GET(self):
228
+ self.route("GET")
229
+
230
+ def do_POST(self):
231
+ self.route("POST")
232
+
233
+ def do_PATCH(self):
234
+ self.route("PATCH")
235
+
236
+ def route(self, method: str) -> None:
237
+ app, path = self.server.app, self.path.split("?", 1)[0]
238
+ upstream = path.startswith("/v1/tools/")
239
+ try:
240
+ if method == "GET" and path == "/healthz":
241
+ return self.send(200, {"status": "parked" if app.world is None else "ready"})
242
+ if path == "/metrics" or path.startswith("/admin/"):
243
+ app.check_admin(self.headers)
244
+ return self.admin(method, path)
245
+ if method == "GET" and path == "/world/manifest":
246
+ app.agent(self.headers)
247
+ return self.send(200, app.manifest)
248
+ if method == "POST" and (upstream or path.startswith("/world/tools/")):
249
+ agent = Agent(app.agent(self.headers), self.headers.get("X-Request-Id") or "")
250
+ body = self.body(MAX_BODY)
251
+ if upstream:
252
+ args = body
253
+ elif not isinstance(body, dict) or not isinstance(body.get("args", {}), dict):
254
+ raise ToolError('the body must be {"args": {...}}', "bad_request")
255
+ else:
256
+ args = body.get("args", {})
257
+ result = app.dispatch(path.rsplit("/", 1)[1], args, agent)
258
+ return self.send(200, result if upstream else {"ok": True, "result": result})
259
+ raise Refused(404, "not_found", f"no route {method} {path}")
260
+ except ToolError as e:
261
+ error = {"code": e.code, "message": redact(e.message)}
262
+ if e.retry_after_s is not None:
263
+ error["retry_after_s"] = e.retry_after_s
264
+ if upstream: # with a retry time: busy (429), else a refusal (400)
265
+ status = 429 if e.retry_after_s is not None else 400
266
+ return self.send(status, {"error": error}, e.retry_after_s)
267
+ return self.send(200, {"ok": False, "error": error})
268
+ except Refused as e:
269
+ error = {"code": e.code, "message": e.message}
270
+ if e.retry_after_s is not None:
271
+ error["retry_after_s"] = e.retry_after_s
272
+ if e.status == 500 and not upstream: # a tool's internal error is a tool error
273
+ return self.send(200, {"ok": False, "error": error})
274
+ return self.send(e.status, {"error": error} if upstream else {"ok": False, "error": error},
275
+ e.retry_after_s)
276
+
277
+ def admin(self, method: str, path: str) -> None:
278
+ app = self.server.app
279
+ if method == "GET" and path == "/metrics":
280
+ return self.send(200, app.metrics())
281
+ admin = app.ready().admin
282
+ try:
283
+ if method == "GET" and path == "/admin/knobs":
284
+ return self.send(200, admin.describe())
285
+ if method == "PATCH" and path == "/admin/knobs":
286
+ changes = admin.set(self.body(ADMIN_MAX_BODY))
287
+ return self.send(200, {"ok": True, "changes": changes, "knobs": admin.describe()})
288
+ if method == "GET" and path == "/admin/paused":
289
+ return self.send(200, {"paused": dict(admin.paused)})
290
+ if method == "POST" and path in ("/admin/pause", "/admin/resume"):
291
+ body = self.body(ADMIN_MAX_BODY)
292
+ body = body if isinstance(body, dict) else {}
293
+ if path == "/admin/pause":
294
+ admin.pause(body.get("lanes"), str(body.get("reason") or ""))
295
+ else:
296
+ admin.resume(body.get("lanes"))
297
+ return self.send(200, {"ok": True, "paused": dict(admin.paused)})
298
+ except ValueError as e:
299
+ raise Refused(400, "bad_request", str(e)) from None
300
+ raise Refused(404, "not_found", f"no route {method} {path}")
301
+
302
+
303
+ def serve(cls: type[World], host: str = "0.0.0.0", port: int = 7860) -> None:
304
+ """Serve `cls` until SIGTERM or SIGUSR1 (a reclaim notice); then return, so the world's
305
+ atexit hooks (a final save) run."""
306
+ credentials = seat_credentials()
307
+ if not credentials:
308
+ raise SystemExit("no PYBOT_TOKEN_<seat> is set: the world needs the agents' credentials")
309
+ app = App(cls, credentials, os.environ.get("PYBOT_ADMIN_TOKEN", ""))
310
+ server = Server(app, host, port)
311
+
312
+ def stop(signum, frame):
313
+ if not app.stop.is_set():
314
+ log.warning("world: signal %d: shutting down", signum)
315
+ app.stop.set()
316
+ threading.Thread(target=server.shutdown, daemon=True).start()
317
+
318
+ signal.signal(signal.SIGTERM, stop)
319
+ signal.signal(signal.SIGUSR1, stop)
320
+ threading.Thread(target=app.builder, name="world-build", daemon=True).start()
321
+ log.warning("world %s on http://%s:%d (%d agent credentials)", cls.name, host, port, len(credentials))
322
+ server.serve_forever()
323
+ server.server_close()
world/snapshot.py CHANGED
@@ -1,4 +1,4 @@
1
- """One archive for world state; agent clones live in their own worker snapshots."""
2
  from __future__ import annotations
3
 
4
  import argparse
@@ -9,16 +9,42 @@ import tarfile
9
  import tempfile
10
  from pathlib import Path, PurePosixPath
11
 
12
- from legion.worker.sync import HubBucketStore
13
- from legion.world.store import backup_to
14
 
15
  # state.db is copied with the online backup API (consistent while the world writes it).
16
  FILES = ("repo.bundle", "state.db", "prs.json", "prs.jsonl", "eval-queue.jsonl", "knobs.json",
17
  "outbox-comment.jsonl")
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def transfer(mode, workspace, bucket, store=None):
21
- store = store or HubBucketStore(bucket, token=os.environ.get("HF_TOKEN"))
22
  if mode == "restore" and "world.tar.gz" not in store.list("world.tar.gz"):
23
  return False # a first start; permission/network/invalid-archive failures still raise
24
  workspace = Path(workspace)
 
1
+ """One archive for world state (world.tar.gz in PYBOT_BUCKET); agent clones live with the agents."""
2
  from __future__ import annotations
3
 
4
  import argparse
 
9
  import tempfile
10
  from pathlib import Path, PurePosixPath
11
 
12
+ from store import backup_to
 
13
 
14
  # state.db is copied with the online backup API (consistent while the world writes it).
15
  FILES = ("repo.bundle", "state.db", "prs.json", "prs.jsonl", "eval-queue.jsonl", "knobs.json",
16
  "outbox-comment.jsonl")
17
 
18
 
19
+ class Bucket:
20
+ """Files under hf://buckets/<ns>/<name>[/<prefix>], through huggingface_hub's bucket API."""
21
+
22
+ def __init__(self, url, token=None):
23
+ from huggingface_hub import HfApi
24
+
25
+ parts = url.removeprefix("hf://buckets/").strip("/").split("/")
26
+ if len(parts) < 2:
27
+ raise ValueError(f"bad bucket url {url!r}; expected hf://buckets/<namespace>/<name>[/prefix]")
28
+ self.bucket_id, self.base = "/".join(parts[:2]), "".join(f"{p}/" for p in parts[2:])
29
+ self.api = HfApi(token=token)
30
+
31
+ def list(self, prefix):
32
+ from huggingface_hub import BucketFile
33
+
34
+ full = self.base + prefix
35
+ return [f.path[len(self.base):] for f in self.api.list_bucket_tree(
36
+ self.bucket_id, prefix=full, recursive=True)
37
+ if isinstance(f, BucketFile) and f.path.startswith(full)]
38
+
39
+ def upload(self, files):
40
+ self.api.batch_bucket_files(self.bucket_id, add=[(str(p), self.base + r) for p, r in files])
41
+
42
+ def download(self, files):
43
+ self.api.download_bucket_files(self.bucket_id, [(self.base + r, str(p)) for r, p in files])
44
+
45
+
46
  def transfer(mode, workspace, bucket, store=None):
47
+ store = store or Bucket(bucket, token=os.environ.get("HF_TOKEN"))
48
  if mode == "restore" and "world.tar.gz" not in store.list("world.tar.gz"):
49
  return False # a first start; permission/network/invalid-archive failures still raise
50
  workspace = Path(workspace)
world/store.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A small `(kind, key) -> JSON` table on SQLite in WAL mode.
2
+
3
+ For worlds that keep their state in memory and want saves that cost O(changes): the world reads
4
+ its own dicts, marks the rows it changed with `dirty(kind, key)`, and a saver calls
5
+ `flush(read)`, which upserts (or deletes) only those rows in one transaction. `backup_to(path)`
6
+ writes a consistent copy while others write (SQLite online backup API), for archives.
7
+
8
+ Rows moved out of the hot set (`put(..., cold=True)`) stay readable with `get` and
9
+ `iter(kind, cold=True)`; `iter(kind)` (the hot rows) is what a world loads at start.
10
+
11
+ store = Store(ws / "state.db")
12
+ state = {key: value for key, value in store.iter("prs")}
13
+ state["7"] = {...}; store.dirty("prs", "7")
14
+ store.flush(lambda kind, key: state.get(key)) # None deletes the row
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import contextlib
20
+ import json
21
+ import sqlite3
22
+ import threading
23
+ import time
24
+ from collections.abc import Callable, Iterator
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ SCHEMA = """
29
+ CREATE TABLE IF NOT EXISTS rows (
30
+ kind TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
31
+ cold INTEGER NOT NULL DEFAULT 0, ts REAL NOT NULL,
32
+ PRIMARY KEY (kind, key));
33
+ """
34
+ UPSERT = ("INSERT INTO rows (kind, key, value, cold, ts) VALUES (?, ?, ?, ?, ?) "
35
+ "ON CONFLICT (kind, key) DO UPDATE SET value = excluded.value, cold = excluded.cold, "
36
+ "ts = excluded.ts")
37
+
38
+
39
+ class Store:
40
+ """Thread-safe: one connection behind a lock (writes are short: dirty rows only)."""
41
+
42
+ def __init__(self, path: str | Path) -> None:
43
+ self.path = Path(path)
44
+ self._lock = threading.Lock()
45
+ # (kind, key) -> generation of its newest change; _written: generation last committed,
46
+ # so a flush that lost a race never commits an older value over a newer one.
47
+ self._dirty: dict[tuple[str, str], int] = {}
48
+ self._written: dict[tuple[str, str], int] = {}
49
+ self._gen = 0
50
+ self._flushing = 0 # flushes between their read and their commit
51
+ self._db = sqlite3.connect(self.path, check_same_thread=False, isolation_level=None)
52
+ self._db.execute("PRAGMA journal_mode=WAL")
53
+ self._db.execute("PRAGMA synchronous=NORMAL") # WAL: durable at checkpoints, never corrupt
54
+ self._db.execute("PRAGMA journal_size_limit=4194304") # truncate the WAL after big writes
55
+ self._db.executescript(SCHEMA)
56
+
57
+ def get(self, kind: str, key: str) -> Any:
58
+ """The row's value (hot or cold), or None."""
59
+ with self._lock:
60
+ row = self._db.execute("SELECT value FROM rows WHERE kind = ? AND key = ?",
61
+ (kind, key)).fetchone()
62
+ return None if row is None else json.loads(row[0])
63
+
64
+ def iter(self, kind: str, cold: bool = False) -> Iterator[tuple[str, Any]]:
65
+ """(key, value) of the hot rows of `kind` (cold=True: the cold rows), in first-write
66
+ order."""
67
+ with self._lock:
68
+ rows = self._db.execute("SELECT key, value FROM rows WHERE kind = ? AND cold = ? "
69
+ "ORDER BY rowid", (kind, int(cold))).fetchall()
70
+ for key, value in rows:
71
+ yield key, json.loads(value)
72
+
73
+ def put(self, kind: str, key: str, value: Any, cold: bool = False) -> None:
74
+ """Write one row now (and drop its dirty mark: this is its newest value)."""
75
+ self.write([(kind, key, value)], cold=cold)
76
+
77
+ def delete(self, kind: str, key: str) -> None:
78
+ self.write([(kind, key, None)])
79
+
80
+ def write(self, rows: list[tuple[str, str, Any]], cold: bool = False) -> None:
81
+ """Upsert (value None: delete) several rows in one transaction."""
82
+ with self._lock:
83
+ self._gen += 1
84
+ encoded = [(kind, key, self._gen, None if value is None else json.dumps(value))
85
+ for kind, key, value in rows]
86
+ self._commit(encoded, cold)
87
+
88
+ def dirty(self, kind: str, key: str) -> None:
89
+ """Mark a row changed; the next flush writes it."""
90
+ with self._lock:
91
+ self._gen += 1
92
+ self._dirty.pop((kind, key), None) # re-insert: keeps the newest change last
93
+ self._dirty[(kind, key)] = self._gen
94
+
95
+ @property
96
+ def pending(self) -> int:
97
+ """Rows marked dirty and not yet flushed."""
98
+ return len(self._dirty)
99
+
100
+ def flush(self, read: Callable[[str, str], Any], lock=None) -> int:
101
+ """Write every dirty row in one transaction: `read(kind, key)` gives its current value
102
+ (None: delete it). `lock` guards what `read` reads: it is held only while the rows are
103
+ read and encoded, not during the commit. A row changed again meanwhile stays dirty. On a
104
+ failed commit nothing is written and the rows stay dirty. Returns the rows written."""
105
+ with lock or contextlib.nullcontext(), self._lock:
106
+ rows = []
107
+ for (kind, key), gen in self._dirty.items():
108
+ value = read(kind, key)
109
+ rows.append((kind, key, gen, None if value is None else json.dumps(value)))
110
+ if not rows:
111
+ return 0
112
+ self._flushing += 1
113
+ with self._lock:
114
+ try:
115
+ self._commit(rows, False)
116
+ finally:
117
+ self._flushing -= 1
118
+ if not self._flushing: # no older read left in flight: nothing to guard against
119
+ self._written.clear()
120
+ return len(rows)
121
+
122
+ def _commit(self, rows, cold):
123
+ """Write rows (kind, key, generation, encoded value or None) in one transaction,
124
+ skipping any already written at a newer generation; then drop their dirty marks."""
125
+ rows = [r for r in rows if self._written.get(r[:2], 0) < r[2]]
126
+ now = time.time()
127
+ self._db.execute("BEGIN IMMEDIATE")
128
+ try:
129
+ for kind, key, _, value in rows:
130
+ if value is None:
131
+ self._db.execute("DELETE FROM rows WHERE kind = ? AND key = ?", (kind, key))
132
+ else:
133
+ self._db.execute(UPSERT, (kind, key, value, int(cold), now))
134
+ self._db.execute("COMMIT")
135
+ except BaseException:
136
+ self._db.execute("ROLLBACK")
137
+ raise
138
+ for kind, key, gen, _ in rows:
139
+ self._written[(kind, key)] = gen
140
+ if self._dirty.get((kind, key), gen + 1) <= gen:
141
+ del self._dirty[(kind, key)]
142
+
143
+ def backup_to(self, path: str | Path) -> None:
144
+ """Consistent copy of the database, WAL included (SQLite online backup API). Holds the
145
+ store's lock for the copy: writers wait."""
146
+ backup_to(self._db, path, self._lock)
147
+
148
+ def size(self) -> int:
149
+ """Bytes on disk (database plus WAL)."""
150
+ return sum(p.stat().st_size for p in (self.path, self.path.with_name(self.path.name + "-wal"))
151
+ if p.exists())
152
+
153
+ def checkpoint(self) -> None:
154
+ """Fold the WAL into the database file and truncate it."""
155
+ with self._lock:
156
+ self._db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
157
+
158
+ def close(self) -> None:
159
+ self.checkpoint()
160
+ with self._lock:
161
+ self._db.close()
162
+
163
+
164
+ def backup_to(db: sqlite3.Connection | str | Path, path: str | Path, lock=None) -> None:
165
+ """Copy database `db` (a connection, or a file another process may be writing) to `path`."""
166
+ path = Path(path)
167
+ path.unlink(missing_ok=True)
168
+ src = db if isinstance(db, sqlite3.Connection) else sqlite3.connect(db)
169
+ dst = sqlite3.connect(path)
170
+ try:
171
+ if lock is None:
172
+ src.backup(dst)
173
+ else:
174
+ with lock:
175
+ src.backup(dst)
176
+ finally:
177
+ dst.close()
178
+ if src is not db:
179
+ src.close()
world/tests/conftest.py CHANGED
@@ -1,8 +1,12 @@
1
- """Puts the world's modules on sys.path (legion is the installed package, README); test helpers."""
2
  from __future__ import annotations
3
 
 
 
4
  import shutil
 
5
  import sys
 
6
  from pathlib import Path
7
 
8
  ROOT = Path(__file__).resolve().parents[1] # world/
@@ -35,3 +39,17 @@ class FakeBucket:
35
  self.ops.append("delete")
36
  for rel in paths:
37
  (self.root / rel).unlink()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Puts the world's modules on sys.path; test helpers."""
2
  from __future__ import annotations
3
 
4
+ import base64
5
+ import os
6
  import shutil
7
+ import subprocess
8
  import sys
9
+ import tempfile
10
  from pathlib import Path
11
 
12
  ROOT = Path(__file__).resolve().parents[1] # world/
 
39
  self.ops.append("delete")
40
  for rel in paths:
41
  (self.root / rel).unlink()
42
+
43
+
44
+ def capture(clone: Path) -> dict:
45
+ """A clone's change as the pybot tools send it: {"base_sha": its merge base with origin/main,
46
+ "patch": base64 of the binary diff of every tracked and nonignored file against it}."""
47
+ def git(*args, env=None):
48
+ return subprocess.run(["git", "-C", str(clone), *args], check=True, capture_output=True,
49
+ env=env).stdout
50
+ base = git("merge-base", "HEAD", "refs/remotes/origin/main").decode().strip()
51
+ with tempfile.TemporaryDirectory() as tmp: # a temporary index: the clone's stays as it is
52
+ env = {**os.environ, "GIT_INDEX_FILE": str(Path(tmp) / "index")}
53
+ git("add", "-A", env=env)
54
+ patch = git("diff", "--cached", "--binary", "--full-index", "--find-renames", base, env=env)
55
+ return {"base_sha": base, "patch": base64.b64encode(patch).decode()}
world/tests/fixtures/seed-basic/CONTRIBUTING.md CHANGED
@@ -10,12 +10,11 @@
10
  `respond(text, memory) -> str | None`; optional integer `PRIORITY` orders modules.
11
  Claim different modules so teams can work without editing the same files.
12
  4. Run `python -m unittest discover -s tests` in the clone, and test the whole bot:
13
- `legion-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.
14
- 5. Submit a small PR using `legion-tool open_pr --json
15
- '{"path":"pybot","branch":"your-topic","title":"Your change",
16
- "description":"What changed, why, and test evidence"}'`.
17
- The worker uploads the clone's tracked and nonignored files, including working
18
- edits and deletions, with its git base. Keep tokens, notes and generated data
19
  outside the clone. Use the world tools for every repository write.
20
  The world commits as your agent and publishes the
21
  native Hub PR ref `refs/pr/<number>`. At most two open PRs per agent.
@@ -38,8 +37,8 @@
38
  until those reviewers approve or the author updates the PR for a fresh review.
39
  The world checks the frozen interface and the bot's output/crash/time contract.
40
 
41
- All world and board tools use `legion-tool <name> --json '<arguments>'`.
42
- Run `legion-tool --list` for their current parameters. Board tools include channels,
43
  create_channel, join_channel, post, read, search, dm, read_dms and react. Mention,
44
  reply, DM and joined-channel notifications arrive between rounds; run no pollers.
45
  Keep status and test logs in your notes. Use the board for short conversations.
 
10
  `respond(text, memory) -> str | None`; optional integer `PRIORITY` orders modules.
11
  Claim different modules so teams can work without editing the same files.
12
  4. Run `python -m unittest discover -s tests` in the clone, and test the whole bot:
13
+ call run_bot with `{"ref_or_path":"pybot","lines":["Hello","Bye"]}`.
14
+ 5. Submit a small PR: call open_pr with `{"path":"pybot","branch":"your-topic",
15
+ "title":"Your change","description":"What changed, why, and test evidence"}`.
16
+ The pybot tools send the clone's tracked and nonignored files, including working
17
+ edits and deletions, as a patch against its git base. Keep tokens, notes and generated data
 
18
  outside the clone. Use the world tools for every repository write.
19
  The world commits as your agent and publishes the
20
  native Hub PR ref `refs/pr/<number>`. At most two open PRs per agent.
 
37
  until those reviewers approve or the author updates the PR for a fresh review.
38
  The world checks the frozen interface and the bot's output/crash/time contract.
39
 
40
+ Use the pybot tools (open_pr, review_pr, ...) and the message board tools; their
41
+ descriptions list the current parameters. Board tools include channels,
42
  create_channel, join_channel, post, read, search, dm, read_dms and react. Mention,
43
  reply, DM and joined-channel notifications arrive between rounds; run no pollers.
44
  Keep status and test logs in your notes. Use the board for short conversations.
world/tests/test_pybot.py CHANGED
@@ -15,11 +15,8 @@ from pathlib import Path
15
  import httpx
16
  import pytest
17
 
18
- from legion.world import Agent, ToolError
19
- from legion.world.server import create_app
20
- from legion.world.workspace import capture
21
-
22
- from conftest import ROOT, FakeBucket
23
 
24
  import pybot
25
  from pybot import PybotWorld
@@ -53,7 +50,7 @@ class LocalHub:
53
  def merge(self, pr, comment): # like the Hub: a three-way merge of refs/pr/N into main
54
  main, head = git(self.remote, "rev-parse", "main"), git(self.remote, "rev-parse", f"refs/pr/{pr}")
55
  tree = git(self.remote, "merge-tree", "--write-tree", main, head).split()[0]
56
- sha = git(self.remote, "-c", "user.name=world", "-c", "user.email=world@legion.invalid",
57
  "commit-tree", tree, "-p", main, "-p", head, "-m", comment)
58
  git(self.remote, "update-ref", "refs/heads/main", sha, main)
59
 
@@ -88,7 +85,7 @@ def _setup(tmp_path, monkeypatch, seed_dir, **env):
88
  shutil.copytree(ROOT / seed_dir, seed, ignore=shutil.ignore_patterns("__pycache__"))
89
  git(seed, "init", "-b", "main")
90
  git(seed, "add", ".")
91
- git(seed, "-c", "user.name=seed", "-c", "user.email=seed@legion.invalid", "commit", "-m", "seed")
92
  remote = tmp_path / "remote.git"
93
  git(tmp_path, "clone", "--bare", str(seed), str(remote))
94
  repo = Repository(tmp_path / "world.git", str(remote))
@@ -108,9 +105,14 @@ def _write_archive(world, state):
108
 
109
 
110
  def submit(world, clone, author="cedar", branch="greeting", pr=None):
111
- return world.call_workspace("open_pr", {"branch": branch, "title": "Improve greetings",
112
  "description": "Tested a conversation and the interface.", "pr": pr},
113
- Agent(author), capture(clone.parent, clone.name))
 
 
 
 
 
114
 
115
 
116
  def merge(world, agent, pr):
@@ -187,13 +189,22 @@ def test_limits_interface_and_failed_contract(setup):
187
  merge(world, Agent("pine"), rec["pr"])
188
 
189
 
190
- def test_upload_rejects_escape_and_symlink(setup):
191
- _, clone, _ = setup
192
- with pytest.raises(ValueError, match="inside"):
193
- capture(clone, "../..")
194
  (clone / "leak").symlink_to("/etc/passwd")
195
- with pytest.raises(ValueError, match="symlinks"):
196
- capture(clone.parent, clone.name)
 
 
 
 
 
 
 
 
 
 
 
197
 
198
 
199
  def test_seed_module_loading_and_sandbox(setup):
@@ -207,20 +218,75 @@ def test_seed_module_loading_and_sandbox(setup):
207
  assert world.run_bot("main", ["hi"])["timeout_s"] == 300
208
 
209
 
210
- async def test_http_upload_is_outside_model_args(setup):
211
- world, clone, _ = setup
212
- app = create_app(world, "secret")
213
- async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://world") as client:
214
- payload = {"args": {"branch": "hello", "title": "Hello bot", "description": "tested"},
215
- "workspace": capture(clone.parent, clone.name)}
216
- headers = {"X-World-Token": "secret", "X-Legion-Agent": "cedar"}
217
- r = await client.post("/tools/open_pr", json=payload, headers=headers)
218
- assert r.json()["ok"], r.text
219
- assert "secret" not in r.text
220
- payload["workspace"]["files"]["../leak"] = base64.b64encode(b"leak").decode()
221
- payload["args"]["branch"] = "bad"
222
- r = await client.post("/tools/open_pr", json=payload, headers=headers)
223
- assert not r.json()["ok"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
 
226
  def test_bot_cannot_read_world_credentials_or_write_files(setup, monkeypatch):
@@ -271,7 +337,7 @@ def test_bucket_restores_an_empty_workspace_and_pushes_at_close(setup, tmp_path,
271
  world, clone, remote = setup
272
  world.close()
273
  bucket, hub = FakeBucket(tmp_path / "bucket"), LocalHub(remote)
274
- monkeypatch.setattr("snapshot.HubBucketStore", lambda url, token=None: bucket)
275
  monkeypatch.setattr(pybot, "Hub", lambda repo_id: hub)
276
  monkeypatch.setattr(pybot, "Repository", lambda root, url, hub: Repository(root, str(remote), hub))
277
  monkeypatch.setenv("PYBOT_BUCKET", "hf://buckets/fake/run")
@@ -316,16 +382,19 @@ def test_bot_cannot_send_signals_to_other_processes(setup):
316
  def test_upload_respects_ignores_size_limit_and_compiles_only_changes(setup, monkeypatch):
317
  world, clone, remote = setup
318
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
319
- snapshot = capture(clone.parent, clone.name)
320
  junk = {".venv/lib/broken.py": b"def (:\n", "bot/__pycache__/x.cpython-312.pyc": b"\0junk",
321
  ".pytest_cache/v/cache/lastfailed": b"{}"}
322
- snapshot["files"].update({k: base64.b64encode(v).decode() for k, v in junk.items()})
323
- snapshot["files"].pop(".gitignore") # the world's default excludes still apply
 
 
 
 
324
  checked = []
325
  real = world._contract
326
  monkeypatch.setattr(world, "_contract", lambda tree, names=None: (checked.append(names),
327
  real(tree, names)))
328
- rec = world.call_workspace("open_pr", {"branch": "topic", "title": "Topic module",
329
  "description": "tested"}, Agent("cedar"), snapshot)
330
  committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines()
331
  assert "bot/modules/topic.py" in committed and ".gitignore" not in committed
@@ -336,8 +405,8 @@ def test_upload_respects_ignores_size_limit_and_compiles_only_changes(setup, mon
336
  with pytest.raises(ToolError, match="file too large: bot/modules/data.py"):
337
  submit(world, clone, branch="big")
338
  with pytest.raises(ToolError, match="file too large"):
339
- world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
340
- Agent("cedar"), capture(clone.parent, clone.name))
341
  assert world.repo.hub.n == 1 # the refused upload created no Hub PR
342
 
343
 
@@ -481,7 +550,7 @@ def test_concurrent_open_prs_never_run_two_hub_pushes_at_once(setup, monkeypatch
481
  for name in ("open", "ready", "close"): # the push lane; comments and merges have their own
482
  monkeypatch.setattr(hub, name, tracked(getattr(hub, name)))
483
  monkeypatch.setattr(world.repo, "push", tracked(world.repo.push))
484
- snapshot, errors = capture(clone.parent, clone.name), []
485
 
486
  def call(fn):
487
  try:
@@ -489,7 +558,7 @@ def test_concurrent_open_prs_never_run_two_hub_pushes_at_once(setup, monkeypatch
489
  except Exception as exc: # noqa: BLE001
490
  errors.append(exc)
491
 
492
- threads = [threading.Thread(target=call, args=(lambda who=who: world.call_workspace(
493
  "open_pr", {"branch": "topic", "title": "Topic", "description": "tested"},
494
  Agent(who), snapshot),)) for who in ("birch", "pine", "oak", "elm", "ash")]
495
  threads.append(threading.Thread(target=call, args=(lambda: approve(world, rec, "fir"),)))
@@ -649,8 +718,8 @@ def test_open_pr_work_runs_outside_the_world_lock(setup, monkeypatch):
649
  return real(snapshot, tree)
650
 
651
  monkeypatch.setattr(world, "_files", slow_files)
652
- snapshot = capture(clone.parent, clone.name)
653
- slow = threading.Thread(name="slow", target=lambda: results.update(slow=world.call_workspace(
654
  "open_pr", {"branch": "slow", "title": "Slow upload", "description": "tested"},
655
  Agent("cedar"), snapshot)))
656
  slow.start()
@@ -732,15 +801,15 @@ def test_refusals_are_logged_and_request_keys_are_bounded(setup, monkeypatch):
732
  refused = [(e["event"], e["agent"], e["pr"], e["code"]) for e in events if e["event"].endswith("_refused")]
733
  assert refused == [("review_pr_refused", "cedar", rec["pr"], "tool_error"),
734
  ("merge_pr_refused", "birch", rec["pr"], "tool_error")]
735
- from legion.world import tool_schema
736
 
737
  schema = tool_schema(world.tools()["merge_pr"])
738
  assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema
739
  monkeypatch.setattr(pybot, "MAX_REQUESTS", 2)
740
  for i in range(3):
741
- world.call_workspace("open_pr", {"branch": "greeting", "title": "Bounded keys",
742
  "description": "x", "pr": rec["pr"]},
743
- Agent("cedar", request_id=f"req-{i}"), capture(clone.parent, clone.name))
744
  assert list(world.state["requests"]) == ["req-1", "req-2"]
745
 
746
 
@@ -790,11 +859,11 @@ def test_open_pr_branch_prefix_and_specific_errors(setup):
790
  for bad, msg in (("hi", r"title must be 3–200 characters \(got 2\)"),
791
  ("t" * 201, r"\(got 201\)")):
792
  with pytest.raises(ToolError, match=msg):
793
- world.call_workspace("open_pr", {"branch": "other", "title": bad, "description": "d"},
794
- Agent("cedar"), capture(clone.parent, clone.name))
795
  with pytest.raises(ToolError, match="description must not be empty"):
796
- world.call_workspace("open_pr", {"branch": "other", "title": "Fine title", "description": " "},
797
- Agent("cedar"), capture(clone.parent, clone.name))
798
 
799
 
800
  def _module(clone, name, reply):
@@ -803,12 +872,12 @@ def _module(clone, name, reply):
803
 
804
  def _commit(clone, message="change"):
805
  git(clone, "add", "-A")
806
- git(clone, "-c", "user.name=a", "-c", "user.email=a@legion.invalid", "commit", "-qm", message)
807
 
808
 
809
  def _rebase(clone):
810
  git(clone, "fetch", "-q", "origin")
811
- git(clone, "-c", "user.name=a", "-c", "user.email=a@legion.invalid", "rebase", "-q", "origin/main")
812
 
813
 
814
  def _two_prs(setup, edit_one, edit_two):
@@ -1437,10 +1506,10 @@ def test_update_refs_writes_both_refs_at_once(setup):
1437
  rec = submit(world, clone)
1438
  pr, head = rec["pr"], rec["head_sha"]
1439
  assert world.repo.sha(f"pr:{pr}") == head
1440
- assert world.repo.git("rev-parse", f"refs/legion/pr/{pr}/{head}") == head
1441
  main = world.repo.sha()
1442
- world.repo.update_refs((f"refs/pr/{pr}", main), (f"refs/legion/pr/{pr}/{main}", main))
1443
- assert world.repo.sha(f"pr:{pr}") == main == world.repo.git("rev-parse", f"refs/legion/pr/{pr}/{main}")
1444
 
1445
 
1446
  def _deck_line(clone, deck_id, *turns):
@@ -1541,7 +1610,7 @@ def test_git_maintenance_packs_refs_and_all_loose_objects_without_rewriting_pack
1541
  repo = world.repo
1542
  rec = submit(world, clone)
1543
  _module(clone, "weather", "sunny")
1544
- rec = submit(world, clone, pr=rec["pr"]) # a superseded head keeps its refs/legion/pr ref
1545
  assert repo.git("config", "maintenance.auto") == "false" # fetches start no background gc
1546
  assert repo.git("config", "gc.auto") == "0" # no git command starts gc --auto either
1547
  orphans = [repo.git("hash-object", "-w", "--stdin", data=f"orphan {i}".encode())
@@ -1561,7 +1630,7 @@ def test_git_maintenance_packs_refs_and_all_loose_objects_without_rewriting_pack
1561
  assert set(info) == {"loose_before", "pack_refs_s", "pack_loose_s", "packs", "loose_after"}
1562
  assert info["loose_after"] == "0"
1563
  assert not [f for f in (repo.root / "refs").rglob("*") if f.is_file()] # all in packed-refs
1564
- assert len(repo.git("for-each-ref", "--format=%(refname)", f"refs/legion/pr/{rec['pr']}/").split()) == 2
1565
  assert re.search(r"^count: 0$", repo.git("count-objects", "-v"), re.MULTILINE)
1566
  repo.git("cat-file", "-e", orphans[0]) # packed, not pruned
1567
  after = set(pack_dir.glob("pack-*.pack"))
@@ -1690,9 +1759,9 @@ def test_update_after_request_changes_tells_the_reviewer_and_approval_tells_merg
1690
  _review(world, rec, "birch", "request_changes")
1691
  _review(world, rec, "aspen", "approve")
1692
  (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hi!"\n')
1693
- new = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings",
1694
  "description": "Added a test.", "pr": rec["pr"]},
1695
- Agent("cedar"), capture(clone.parent, clone.name))
1696
  assert len(new["inbox"]) == 2 # birch's and aspen's reviews, no mergeable (changes requested)
1697
  assert not any("ready to merge_pr" in line for line in new["inbox"])
1698
  assert "cedar" not in world.state["inbox"]
@@ -1755,14 +1824,14 @@ def test_inbox_age_and_idempotent_retry_keep_the_cached_result(setup):
1755
  world, clone, _ = setup
1756
  assert [PybotWorld._age(s) for s in (5, 180, 7200, 200000)] == [
1757
  "just now", "3 min ago", "2 h ago", "2 d ago"]
1758
- first = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings",
1759
  "description": "Tested."}, Agent("cedar", request_id="k1"),
1760
- capture(clone.parent, clone.name))
1761
  with world.lock:
1762
  world._notify("cedar", 99, "merged", "news")
1763
- retry = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings",
1764
  "description": "Tested."}, Agent("cedar", request_id="k1"),
1765
- capture(clone.parent, clone.name))
1766
  assert retry["inbox"] == ["news (just now)"] and retry["pr"] == first["pr"]
1767
  assert "inbox" not in world.state["requests"]["k1"]
1768
 
@@ -1783,8 +1852,8 @@ def test_new_pr_budget_floor_refuses_before_the_hub_and_logs(setup, monkeypatch,
1783
  world, clone, _ = setup
1784
  world = PybotWorld(world.ws, world.repo)
1785
  assert submit(world, clone, "cedar", "one")["pr"] == 1
1786
- second = world.call_workspace("open_pr", {"branch": "two", "title": "Two", "description": "t"},
1787
- Agent("birch"), capture(clone.parent, clone.name))
1788
  assert second["pr_budget"] == {"mode": "merges", "opened_last_hour": 2, "merged_last_hour": 0,
1789
  "limit": 2, "available": 0, "next_slot_min": 60}
1790
  with caplog.at_level("WARNING"), pytest.raises(ToolError) as exc:
@@ -2379,9 +2448,9 @@ def test_saves_are_never_torn_under_concurrent_changes(setup):
2379
 
2380
 
2381
  def _open(world, clone, key, description="Tested a conversation.", pr=None, author="cedar"):
2382
- result = world.call_workspace("open_pr", {"branch": "greeting", "title": "Improve greetings",
2383
  "description": description, "pr": pr},
2384
- Agent(author, request_id=key), capture(clone.parent, clone.name))
2385
  return {k: v for k, v in result.items() if k not in ("pr_budget", "inbox")}
2386
 
2387
 
@@ -2598,15 +2667,15 @@ def test_get_pr_is_a_registered_tool(setup):
2598
  assert got["content"].startswith("PRIORITY")
2599
 
2600
 
2601
- def test_manifest_declares_workspace_uploads_and_timeouts(setup):
2602
- from legion.world.protocol import WorldManifest
2603
-
2604
- tools = {t.name: t for t in WorldManifest.model_validate(setup[0].manifest()).tools}
2605
- assert tools["open_pr"].workspace.arg == "path" and tools["open_pr"].workspace.default == "pybot"
2606
- run = tools["run_bot"].workspace
2607
- assert (run.arg, run.default, run.skip, run.skip_prefix) == ("ref_or_path", "main", ["main"], "pr:")
2608
- assert tools["review_pr"].workspace is None
2609
- assert {t.timeout_s for t in tools.values()} == {330}
2610
 
2611
 
2612
  def test_a_slow_hub_merge_does_not_block_reads(setup, monkeypatch):
@@ -2885,7 +2954,7 @@ def test_an_import_cut_before_its_commit_is_redone(setup):
2885
  world.store.close()
2886
  for f in world.ws.glob("state.db*"):
2887
  f.unlink()
2888
- from legion.world.store import Store
2889
 
2890
  Store(world.ws / "state.db").close() # a kill during the first import: schema, no rows
2891
  again = PybotWorld(world.ws, world.repo)
@@ -2919,55 +2988,54 @@ def test_old_merged_and_closed_prs_move_to_the_cold_table(setup):
2919
  submit(w, clone, branch="one")
2920
 
2921
 
2922
- def submit_v2(world, clone, author="cedar", branch="greeting", pr=None):
2923
- from legion.world.workspace import capture_v2
2924
- snapshot = capture_v2(clone.parent, clone.name)
2925
- assert "patch" in snapshot
2926
- return world.call_workspace("open_pr", {"branch": branch, "title": "Improve greetings",
2927
- "description": "Tested a conversation and the interface.", "pr": pr}, Agent(author), snapshot)
2928
-
2929
-
2930
- def test_open_pr_and_run_bot_through_a_v2_patch(setup):
2931
  world, clone, remote = setup
2932
- assert "workspace-upload-v2" in world.manifest()["capabilities"]
2933
  (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n')
2934
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
2935
  (clone / "bot/__pycache__").mkdir(exist_ok=True)
2936
  (clone / "bot/__pycache__/x.pyc").write_bytes(b"\0junk")
2937
- rec = submit_v2(world, clone)
2938
  committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines()
2939
  assert "bot/modules/topic.py" in committed and not [n for n in committed if "__pycache__" in n]
2940
  assert git(remote, "show", f"{rec['head_sha']}:bot/modules/greeting.py").endswith('"Hey!"')
2941
- from legion.world.workspace import capture_v2
2942
- out = world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
2943
- Agent("cedar"), capture_v2(clone.parent, clone.name))
2944
  assert out["replies"] == ["Hey!"]
2945
  (clone / "bot/modules/data.py").write_text("X = 1\n" + "#" * (2 << 20))
2946
  with pytest.raises(ToolError, match="file too large"):
2947
- submit_v2(world, clone, branch="big")
2948
 
2949
 
2950
- def test_v2_with_an_unknown_base_asks_for_the_full_tree(setup, monkeypatch):
2951
- world, clone, _ = setup
2952
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
2953
- from legion.world.workspace import capture_v2
2954
- v2 = {**capture_v2(clone.parent, clone.name), "base_sha": "1" * 40}
2955
  args = {"branch": "topic", "title": "Topic module", "description": "tested"}
2956
- with pytest.raises(ToolError, match="base is not a main commit"): # a v1 resend can't help
2957
- world.call_workspace("open_pr", args, Agent("cedar"), v2)
2958
- with pytest.raises(ToolError) as e:
2959
- world.call_workspace("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
2960
- Agent("cedar"), v2)
2961
- assert e.value.code == "need_full"
2962
- v1 = {**capture(clone.parent, clone.name), "base_sha": "1" * 40}
2963
- with pytest.raises(ToolError, match="base is not a main commit"):
2964
- world.call_workspace("open_pr", args, Agent("cedar"), v1)
 
 
 
 
 
 
 
 
 
 
2965
  # the budget is checked before any apply
2966
  monkeypatch.setattr(world, "_check_budget", lambda agent: (_ for _ in ()).throw(
2967
  ToolError("budget", "open_budget")))
2968
  monkeypatch.setattr(pybot, "apply_patch", lambda *a: pytest.fail("applied"))
2969
  with pytest.raises(ToolError, match="budget"):
2970
- world.call_workspace("open_pr", args, Agent("cedar"), capture_v2(clone.parent, clone.name))
2971
 
2972
 
2973
  # ---------------------------------------------------------------- reviewer cap, budget scope, seed (off in BASIC)
@@ -2992,27 +3060,23 @@ def test_reviewer_cap_refuses_one_more_reviewer_and_hides_full_prs(setup, monkey
2992
  merge(world, Agent("cedar"), rec["pr"])
2993
 
2994
 
2995
- def test_adds_module_reads_v1_and_v2_uploads(setup):
2996
- from legion.world.workspace import capture_v2
2997
-
2998
  world, clone, _ = setup
2999
- base = git(clone, "rev-parse", "HEAD")
3000
 
3001
  def adds():
3002
- return (world._adds_module(capture(clone.parent, clone.name), base),
3003
- world._adds_module(capture_v2(clone.parent, clone.name), base))
3004
 
3005
- assert adds() == (False, False)
3006
  (clone / "tests/test_more.py").write_text("x = 1\n")
3007
  (clone / "bot/modules/greeting.py").write_text('PRIORITY = -1000\n\ndef respond(text, memory):\n return "Hi!"\n')
3008
- assert adds() == (False, False) # a test and an edit of an existing module
3009
  (clone / "bot/modules/helpers").mkdir()
3010
  (clone / "bot/modules/helpers/__init__.py").write_text("")
3011
- assert adds() == (True, True) # a new package
3012
  shutil.rmtree(clone / "bot/modules/helpers")
3013
  git(clone, "mv", "bot/modules/greeting.py", "bot/modules/hello.py")
3014
- assert adds() == (True, True) # renamed to a new module name
3015
- assert world._adds_module({"files": None}, base) and world._adds_module({"patch": "%%"}, base)
3016
 
3017
 
3018
  def test_new_modules_scope_rations_only_prs_that_add_a_module(setup, monkeypatch):
@@ -3181,7 +3245,7 @@ def test_a_create_whose_gap_wait_sees_main_move_opens_on_its_build(setup, monkey
3181
  gaps.append(deadline)
3182
  real_gap(agent, deadline)
3183
  tree = git(remote, "rev-parse", "main^{tree}")
3184
- moved = git(remote, "-c", "user.name=x", "-c", "user.email=x@legion.invalid",
3185
  "commit-tree", tree, "-p", "main", "-m", "a merge elsewhere")
3186
  git(remote, "update-ref", "refs/heads/main", moved)
3187
  world.repo.fetch()
 
15
  import httpx
16
  import pytest
17
 
18
+ from api import Agent, ToolError
19
+ from conftest import ROOT, FakeBucket, capture
 
 
 
20
 
21
  import pybot
22
  from pybot import PybotWorld
 
50
  def merge(self, pr, comment): # like the Hub: a three-way merge of refs/pr/N into main
51
  main, head = git(self.remote, "rev-parse", "main"), git(self.remote, "rev-parse", f"refs/pr/{pr}")
52
  tree = git(self.remote, "merge-tree", "--write-tree", main, head).split()[0]
53
+ sha = git(self.remote, "-c", "user.name=world", "-c", "user.email=world@pybot.invalid",
54
  "commit-tree", tree, "-p", main, "-p", head, "-m", comment)
55
  git(self.remote, "update-ref", "refs/heads/main", sha, main)
56
 
 
85
  shutil.copytree(ROOT / seed_dir, seed, ignore=shutil.ignore_patterns("__pycache__"))
86
  git(seed, "init", "-b", "main")
87
  git(seed, "add", ".")
88
+ git(seed, "-c", "user.name=seed", "-c", "user.email=seed@pybot.invalid", "commit", "-m", "seed")
89
  remote = tmp_path / "remote.git"
90
  git(tmp_path, "clone", "--bare", str(seed), str(remote))
91
  repo = Repository(tmp_path / "world.git", str(remote))
 
105
 
106
 
107
  def submit(world, clone, author="cedar", branch="greeting", pr=None):
108
+ return call_workspace(world, "open_pr", {"branch": branch, "title": "Improve greetings",
109
  "description": "Tested a conversation and the interface.", "pr": pr},
110
+ Agent(author), capture(clone))
111
+
112
+
113
+ def call_workspace(world, name, args, agent, workspace):
114
+ """A tool call with the clone's change, as the pybot tools send it."""
115
+ return world.call(name, {**args, "workspace": workspace}, agent)
116
 
117
 
118
  def merge(world, agent, pr):
 
189
  merge(world, Agent("pine"), rec["pr"])
190
 
191
 
192
+ def test_workspace_rejects_escape_and_symlink(setup):
193
+ world, clone, _ = setup
 
 
194
  (clone / "leak").symlink_to("/etc/passwd")
195
+ with pytest.raises(ToolError, match="symlinks") as e:
196
+ submit(world, clone)
197
+ assert e.value.code == "bad_workspace"
198
+ (clone / "leak").unlink()
199
+ args = {"branch": "topic", "title": "Escape", "description": "tested"}
200
+ for path in ("../leak", ".git/hooks/post-commit"):
201
+ patch = (f"diff --git a/{path} b/{path}\nnew file mode 100644\n--- /dev/null\n+++ b/{path}\n"
202
+ "@@ -0,0 +1 @@\n+leak\n").encode()
203
+ with pytest.raises(ToolError) as e:
204
+ call_workspace(world, "open_pr", args, Agent("cedar"),
205
+ {**capture(clone), "patch": base64.b64encode(patch).decode()})
206
+ assert e.value.code == "bad_workspace", path
207
+ assert world.repo.hub.n == 0
208
 
209
 
210
  def test_seed_module_loading_and_sandbox(setup):
 
218
  assert world.run_bot("main", ["hi"])["timeout_s"] == 300
219
 
220
 
221
+ def test_http_routes_credentials_and_workspace(setup, monkeypatch):
222
+ import server
223
+
224
+ world, clone, remote = setup
225
+ monkeypatch.setenv("WORLD_TEST_TOKEN", "c" * 40) # a secret-looking env value is redacted
226
+ creds = {"c" * 40: "cedar", "b" * 40: "birch"}
227
+ httpd = server.Server(server.App(world, creds, admin_token="a" * 40), "127.0.0.1", 0)
228
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
229
+ cedar, birch = {"Authorization": "Bearer " + "c" * 40}, {"X-World-Token": "b" * 40}
230
+ try:
231
+ with httpx.Client(base_url=f"http://127.0.0.1:{httpd.server_port}", timeout=60) as c:
232
+ assert c.get("/healthz").json() == {"status": "ready"}
233
+ for headers in ({}, {"X-World-Token": "wrong"}, {"Authorization": "Bearer " + "a" * 40}):
234
+ assert c.get("/world/manifest", headers=headers).status_code == 401
235
+ m = c.get("/world/manifest", headers=birch).json()
236
+ assert m["name"] == "pybot" and len(m["tools"]) == 10
237
+ # upstream route: flat args with the clone's change; the result as is
238
+ (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
239
+ args = {"branch": "hello", "title": "Hello bot", "description": "tested"}
240
+ r = c.post("/v1/tools/open_pr", json={**args, "workspace": capture(clone)}, headers=cedar)
241
+ assert r.status_code == 200 and r.json()["author"] == "cedar", r.text
242
+ assert "bot/modules/topic.py" in git(remote, "ls-tree", "-r", "--name-only", r.json()["head_sha"])
243
+ assert "c" * 40 not in r.text
244
+ pr, head = r.json()["pr"], r.json()["head_sha"]
245
+ review = {"pr": pr, "head_sha": head, "verdict": "approve", "comment": "ok"}
246
+ r = c.post("/v1/tools/review_pr", json=review, headers=cedar) # a refusal: 4xx
247
+ assert r.status_code == 400 and "self-review" in r.json()["error"]["message"]
248
+ assert c.post("/v1/tools/nope", json={}, headers=cedar).status_code == 404
249
+ r = c.post("/v1/tools/merge_pr", json={"pr": "1"}, headers=cedar)
250
+ assert r.status_code == 400 and r.json()["error"]["code"] == "bad_args"
251
+ # direct route: the {"ok", ...} envelope, the same dispatch
252
+ r = c.post("/world/tools/review_pr", json={"args": review}, headers=birch)
253
+ assert r.json()["ok"] and r.json()["result"]["reviewer"] == "birch"
254
+ r = c.post("/world/tools/merge_pr", json={"args": {"pr": "1"}}, headers=birch)
255
+ assert r.status_code == 200 and r.json()["error"]["code"] == "bad_args"
256
+ bad = {"base_sha": git(remote, "rev-parse", "main"), "patch": "not base64!"}
257
+ r = c.post("/world/tools/open_pr", json={"args": {**args, "branch": "bad", "workspace": bad}},
258
+ headers=birch)
259
+ assert not r.json()["ok"] and r.json()["error"]["code"] == "bad_workspace", r.text
260
+ big = {"args": {"ref_or_path": "main", "lines": ["x" * (1 << 20)]}}
261
+ for route in ("/v1/tools/run_bot", "/world/tools/run_bot"):
262
+ assert c.post(route, json=big, headers=birch).status_code == 413
263
+ # a refusal with a retry time: 429 with Retry-After upstream, retry_after_s in the envelope
264
+ monkeypatch.setattr(world, "_check_budget", lambda agent: (_ for _ in ()).throw(
265
+ ToolError("budget", "open_budget", retry_after_s=60)))
266
+ r = c.post("/v1/tools/open_pr", json={**args, "branch": "two", "workspace": capture(clone)},
267
+ headers=birch)
268
+ assert r.status_code == 429 and r.headers["Retry-After"] == "60", r.text
269
+ r = c.post("/world/tools/open_pr", json={"args": {**args, "branch": "two",
270
+ "workspace": capture(clone)}}, headers=birch)
271
+ assert r.json()["error"]["retry_after_s"] == 60
272
+ # operators: their own token, never an agent's
273
+ assert c.get("/metrics", headers=cedar).status_code == 401
274
+ assert c.get("/metrics", headers={"X-World-Token": "a" * 40}).json()["world"]["open_prs"] == 1
275
+ r = c.patch("/admin/knobs", json={"pr.open_floor": 3}, headers={"X-World-Token": "a" * 40})
276
+ assert r.json()["ok"] and world.budget_floor == 3
277
+ finally:
278
+ httpd.shutdown()
279
+ httpd.server_close()
280
+ # admission control: a pool past its threads (and queue) answers 429
281
+ with pytest.raises(server.Refused) as e:
282
+ busy = server.Pool(1, max_wait_s=0.01)
283
+ busy.slots.acquire()
284
+ busy.run(lambda: None)
285
+ assert (e.value.status, e.value.retry_after_s) == (429, server.RETRY_AFTER_S)
286
+ full = server.Pool(1, queue=0)
287
+ full.in_flight = 1
288
+ with pytest.raises(server.Refused):
289
+ full.run(lambda: None)
290
 
291
 
292
  def test_bot_cannot_read_world_credentials_or_write_files(setup, monkeypatch):
 
337
  world, clone, remote = setup
338
  world.close()
339
  bucket, hub = FakeBucket(tmp_path / "bucket"), LocalHub(remote)
340
+ monkeypatch.setattr("snapshot.Bucket", lambda url, token=None: bucket)
341
  monkeypatch.setattr(pybot, "Hub", lambda repo_id: hub)
342
  monkeypatch.setattr(pybot, "Repository", lambda root, url, hub: Repository(root, str(remote), hub))
343
  monkeypatch.setenv("PYBOT_BUCKET", "hf://buckets/fake/run")
 
382
  def test_upload_respects_ignores_size_limit_and_compiles_only_changes(setup, monkeypatch):
383
  world, clone, remote = setup
384
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
 
385
  junk = {".venv/lib/broken.py": b"def (:\n", "bot/__pycache__/x.cpython-312.pyc": b"\0junk",
386
  ".pytest_cache/v/cache/lastfailed": b"{}"}
387
+ for name, data in junk.items():
388
+ (clone / name).parent.mkdir(parents=True, exist_ok=True)
389
+ (clone / name).write_bytes(data)
390
+ (clone / ".gitignore").unlink() # the junk goes along; the world's default excludes still apply
391
+ snapshot = capture(clone)
392
+ assert all(name.encode() in base64.b64decode(snapshot["patch"]) for name in junk)
393
  checked = []
394
  real = world._contract
395
  monkeypatch.setattr(world, "_contract", lambda tree, names=None: (checked.append(names),
396
  real(tree, names)))
397
+ rec = call_workspace(world, "open_pr", {"branch": "topic", "title": "Topic module",
398
  "description": "tested"}, Agent("cedar"), snapshot)
399
  committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines()
400
  assert "bot/modules/topic.py" in committed and ".gitignore" not in committed
 
405
  with pytest.raises(ToolError, match="file too large: bot/modules/data.py"):
406
  submit(world, clone, branch="big")
407
  with pytest.raises(ToolError, match="file too large"):
408
+ call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
409
+ Agent("cedar"), capture(clone))
410
  assert world.repo.hub.n == 1 # the refused upload created no Hub PR
411
 
412
 
 
550
  for name in ("open", "ready", "close"): # the push lane; comments and merges have their own
551
  monkeypatch.setattr(hub, name, tracked(getattr(hub, name)))
552
  monkeypatch.setattr(world.repo, "push", tracked(world.repo.push))
553
+ snapshot, errors = capture(clone), []
554
 
555
  def call(fn):
556
  try:
 
558
  except Exception as exc: # noqa: BLE001
559
  errors.append(exc)
560
 
561
+ threads = [threading.Thread(target=call, args=(lambda who=who: call_workspace(world,
562
  "open_pr", {"branch": "topic", "title": "Topic", "description": "tested"},
563
  Agent(who), snapshot),)) for who in ("birch", "pine", "oak", "elm", "ash")]
564
  threads.append(threading.Thread(target=call, args=(lambda: approve(world, rec, "fir"),)))
 
718
  return real(snapshot, tree)
719
 
720
  monkeypatch.setattr(world, "_files", slow_files)
721
+ snapshot = capture(clone)
722
+ slow = threading.Thread(name="slow", target=lambda: results.update(slow=call_workspace(world,
723
  "open_pr", {"branch": "slow", "title": "Slow upload", "description": "tested"},
724
  Agent("cedar"), snapshot)))
725
  slow.start()
 
801
  refused = [(e["event"], e["agent"], e["pr"], e["code"]) for e in events if e["event"].endswith("_refused")]
802
  assert refused == [("review_pr_refused", "cedar", rec["pr"], "tool_error"),
803
  ("merge_pr_refused", "birch", rec["pr"], "tool_error")]
804
+ from api import tool_schema
805
 
806
  schema = tool_schema(world.tools()["merge_pr"])
807
  assert list(schema["parameters"]["properties"]) == ["pr"] # the wrapper keeps the schema
808
  monkeypatch.setattr(pybot, "MAX_REQUESTS", 2)
809
  for i in range(3):
810
+ call_workspace(world, "open_pr", {"branch": "greeting", "title": "Bounded keys",
811
  "description": "x", "pr": rec["pr"]},
812
+ Agent("cedar", request_id=f"req-{i}"), capture(clone))
813
  assert list(world.state["requests"]) == ["req-1", "req-2"]
814
 
815
 
 
859
  for bad, msg in (("hi", r"title must be 3–200 characters \(got 2\)"),
860
  ("t" * 201, r"\(got 201\)")):
861
  with pytest.raises(ToolError, match=msg):
862
+ call_workspace(world, "open_pr", {"branch": "other", "title": bad, "description": "d"},
863
+ Agent("cedar"), capture(clone))
864
  with pytest.raises(ToolError, match="description must not be empty"):
865
+ call_workspace(world, "open_pr", {"branch": "other", "title": "Fine title", "description": " "},
866
+ Agent("cedar"), capture(clone))
867
 
868
 
869
  def _module(clone, name, reply):
 
872
 
873
  def _commit(clone, message="change"):
874
  git(clone, "add", "-A")
875
+ git(clone, "-c", "user.name=a", "-c", "user.email=a@pybot.invalid", "commit", "-qm", message)
876
 
877
 
878
  def _rebase(clone):
879
  git(clone, "fetch", "-q", "origin")
880
+ git(clone, "-c", "user.name=a", "-c", "user.email=a@pybot.invalid", "rebase", "-q", "origin/main")
881
 
882
 
883
  def _two_prs(setup, edit_one, edit_two):
 
1506
  rec = submit(world, clone)
1507
  pr, head = rec["pr"], rec["head_sha"]
1508
  assert world.repo.sha(f"pr:{pr}") == head
1509
+ assert world.repo.git("rev-parse", f"refs/pybot/pr/{pr}/{head}") == head
1510
  main = world.repo.sha()
1511
+ world.repo.update_refs((f"refs/pr/{pr}", main), (f"refs/pybot/pr/{pr}/{main}", main))
1512
+ assert world.repo.sha(f"pr:{pr}") == main == world.repo.git("rev-parse", f"refs/pybot/pr/{pr}/{main}")
1513
 
1514
 
1515
  def _deck_line(clone, deck_id, *turns):
 
1610
  repo = world.repo
1611
  rec = submit(world, clone)
1612
  _module(clone, "weather", "sunny")
1613
+ rec = submit(world, clone, pr=rec["pr"]) # a superseded head keeps its refs/pybot/pr ref
1614
  assert repo.git("config", "maintenance.auto") == "false" # fetches start no background gc
1615
  assert repo.git("config", "gc.auto") == "0" # no git command starts gc --auto either
1616
  orphans = [repo.git("hash-object", "-w", "--stdin", data=f"orphan {i}".encode())
 
1630
  assert set(info) == {"loose_before", "pack_refs_s", "pack_loose_s", "packs", "loose_after"}
1631
  assert info["loose_after"] == "0"
1632
  assert not [f for f in (repo.root / "refs").rglob("*") if f.is_file()] # all in packed-refs
1633
+ assert len(repo.git("for-each-ref", "--format=%(refname)", f"refs/pybot/pr/{rec['pr']}/").split()) == 2
1634
  assert re.search(r"^count: 0$", repo.git("count-objects", "-v"), re.MULTILINE)
1635
  repo.git("cat-file", "-e", orphans[0]) # packed, not pruned
1636
  after = set(pack_dir.glob("pack-*.pack"))
 
1759
  _review(world, rec, "birch", "request_changes")
1760
  _review(world, rec, "aspen", "approve")
1761
  (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hi!"\n')
1762
+ new = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
1763
  "description": "Added a test.", "pr": rec["pr"]},
1764
+ Agent("cedar"), capture(clone))
1765
  assert len(new["inbox"]) == 2 # birch's and aspen's reviews, no mergeable (changes requested)
1766
  assert not any("ready to merge_pr" in line for line in new["inbox"])
1767
  assert "cedar" not in world.state["inbox"]
 
1824
  world, clone, _ = setup
1825
  assert [PybotWorld._age(s) for s in (5, 180, 7200, 200000)] == [
1826
  "just now", "3 min ago", "2 h ago", "2 d ago"]
1827
+ first = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
1828
  "description": "Tested."}, Agent("cedar", request_id="k1"),
1829
+ capture(clone))
1830
  with world.lock:
1831
  world._notify("cedar", 99, "merged", "news")
1832
+ retry = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
1833
  "description": "Tested."}, Agent("cedar", request_id="k1"),
1834
+ capture(clone))
1835
  assert retry["inbox"] == ["news (just now)"] and retry["pr"] == first["pr"]
1836
  assert "inbox" not in world.state["requests"]["k1"]
1837
 
 
1852
  world, clone, _ = setup
1853
  world = PybotWorld(world.ws, world.repo)
1854
  assert submit(world, clone, "cedar", "one")["pr"] == 1
1855
+ second = call_workspace(world, "open_pr", {"branch": "two", "title": "Two", "description": "t"},
1856
+ Agent("birch"), capture(clone))
1857
  assert second["pr_budget"] == {"mode": "merges", "opened_last_hour": 2, "merged_last_hour": 0,
1858
  "limit": 2, "available": 0, "next_slot_min": 60}
1859
  with caplog.at_level("WARNING"), pytest.raises(ToolError) as exc:
 
2448
 
2449
 
2450
  def _open(world, clone, key, description="Tested a conversation.", pr=None, author="cedar"):
2451
+ result = call_workspace(world, "open_pr", {"branch": "greeting", "title": "Improve greetings",
2452
  "description": description, "pr": pr},
2453
+ Agent(author, request_id=key), capture(clone))
2454
  return {k: v for k, v in result.items() if k not in ("pr_budget", "inbox")}
2455
 
2456
 
 
2667
  assert got["content"].startswith("PRIORITY")
2668
 
2669
 
2670
+ def test_manifest_lists_the_tools_and_the_workspace_argument(setup):
2671
+ m = setup[0].manifest()
2672
+ assert m["name"] == "pybot" and m["description"]
2673
+ tools = {t["name"]: t for t in m["tools"]}
2674
+ assert set(tools) == {"open_pr", "review_pr", "merge_pr", "close_pr", "list_prs", "get_pr",
2675
+ "record_verdict", "verdicts", "world_status", "run_bot"}
2676
+ assert {n for n, t in tools.items() if "workspace" in t["parameters"]["properties"]} == {
2677
+ "open_pr", "run_bot"}
2678
+ assert tools["list_prs"]["annotations"] == {"readOnlyHint": True}
2679
 
2680
 
2681
  def test_a_slow_hub_merge_does_not_block_reads(setup, monkeypatch):
 
2954
  world.store.close()
2955
  for f in world.ws.glob("state.db*"):
2956
  f.unlink()
2957
+ from store import Store
2958
 
2959
  Store(world.ws / "state.db").close() # a kill during the first import: schema, no rows
2960
  again = PybotWorld(world.ws, world.repo)
 
2988
  submit(w, clone, branch="one")
2989
 
2990
 
2991
+ def test_open_pr_and_run_bot_through_a_patch(setup):
 
 
 
 
 
 
 
 
2992
  world, clone, remote = setup
 
2993
  (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n')
2994
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
2995
  (clone / "bot/__pycache__").mkdir(exist_ok=True)
2996
  (clone / "bot/__pycache__/x.pyc").write_bytes(b"\0junk")
2997
+ rec = submit(world, clone)
2998
  committed = git(remote, "ls-tree", "-r", "--name-only", rec["head_sha"]).splitlines()
2999
  assert "bot/modules/topic.py" in committed and not [n for n in committed if "__pycache__" in n]
3000
  assert git(remote, "show", f"{rec['head_sha']}:bot/modules/greeting.py").endswith('"Hey!"')
3001
+ out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
3002
+ Agent("cedar"), capture(clone))
 
3003
  assert out["replies"] == ["Hey!"]
3004
  (clone / "bot/modules/data.py").write_text("X = 1\n" + "#" * (2 << 20))
3005
  with pytest.raises(ToolError, match="file too large"):
3006
+ submit(world, clone, branch="big")
3007
 
3008
 
3009
+ def test_a_missing_base_is_fetched_from_the_hub_or_refused(setup, monkeypatch):
3010
+ world, clone, remote = setup
3011
  (clone / "bot/modules/topic.py").write_text('def respond(text, memory):\n return None\n')
3012
+ unknown = {**capture(clone), "base_sha": "1" * 40}
 
3013
  args = {"branch": "topic", "title": "Topic module", "description": "tested"}
3014
+ for name, call_args in (("open_pr", args), ("run_bot", {"ref_or_path": "pybot", "lines": ["hi"]})):
3015
+ with pytest.raises(ToolError) as e:
3016
+ call_workspace(world, name, call_args, Agent("cedar"), unknown)
3017
+ assert e.value.code == "unknown_base"
3018
+ with pytest.raises(ToolError) as e: # not a workspace
3019
+ call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]}, Agent("cedar"),
3020
+ {"base_sha": "x", "files": {}})
3021
+ assert e.value.code == "bad_workspace"
3022
+ # main moved on the Hub: the world fetches the agent's newer base
3023
+ (clone / "bot/modules/topic.py").unlink()
3024
+ _module(clone, "weather", "Sunny!")
3025
+ _commit(clone, "weather")
3026
+ git(clone, "push", "-q", "origin", "HEAD:main")
3027
+ git(clone, "fetch", "-q")
3028
+ (clone / "bot/modules/greeting.py").write_text('def respond(text, memory):\n return "Hey!"\n')
3029
+ assert not world.repo.has_commit(capture(clone)["base_sha"])
3030
+ out = call_workspace(world, "run_bot", {"ref_or_path": "pybot", "lines": ["hi"]},
3031
+ Agent("cedar"), capture(clone))
3032
+ assert out["replies"] == ["Hey!"] and out["sha"] == git(remote, "rev-parse", "main")
3033
  # the budget is checked before any apply
3034
  monkeypatch.setattr(world, "_check_budget", lambda agent: (_ for _ in ()).throw(
3035
  ToolError("budget", "open_budget")))
3036
  monkeypatch.setattr(pybot, "apply_patch", lambda *a: pytest.fail("applied"))
3037
  with pytest.raises(ToolError, match="budget"):
3038
+ call_workspace(world, "open_pr", args, Agent("cedar"), capture(clone))
3039
 
3040
 
3041
  # ---------------------------------------------------------------- reviewer cap, budget scope, seed (off in BASIC)
 
3060
  merge(world, Agent("cedar"), rec["pr"])
3061
 
3062
 
3063
+ def test_adds_module_reads_the_patch(setup):
 
 
3064
  world, clone, _ = setup
 
3065
 
3066
  def adds():
3067
+ return world._adds_module(capture(clone))
 
3068
 
3069
+ assert not adds()
3070
  (clone / "tests/test_more.py").write_text("x = 1\n")
3071
  (clone / "bot/modules/greeting.py").write_text('PRIORITY = -1000\n\ndef respond(text, memory):\n return "Hi!"\n')
3072
+ assert not adds() # a test and an edit of an existing module
3073
  (clone / "bot/modules/helpers").mkdir()
3074
  (clone / "bot/modules/helpers/__init__.py").write_text("")
3075
+ assert adds() # a new package
3076
  shutil.rmtree(clone / "bot/modules/helpers")
3077
  git(clone, "mv", "bot/modules/greeting.py", "bot/modules/hello.py")
3078
+ assert adds() # renamed to a new module name
3079
+ assert world._adds_module({"patch": "%%"}) # unreadable: counted
3080
 
3081
 
3082
  def test_new_modules_scope_rations_only_prs_that_add_a_module(setup, monkeypatch):
 
3245
  gaps.append(deadline)
3246
  real_gap(agent, deadline)
3247
  tree = git(remote, "rev-parse", "main^{tree}")
3248
+ moved = git(remote, "-c", "user.name=x", "-c", "user.email=x@pybot.invalid",
3249
  "commit-tree", tree, "-p", "main", "-m", "a merge elsewhere")
3250
  git(remote, "update-ref", "refs/heads/main", moved)
3251
  world.repo.fetch()
world/workspace.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """An agent's change, sent as `workspace: {"base_sha", "patch"}` with open_pr and run_bot.
2
+
3
+ `patch` is the base64 of `git diff --cached --binary --full-index --find-renames <base_sha>` of
4
+ the agent's clone; the world applies it on its own checkout of `base_sha` (`apply_patch`).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import os
10
+ import re
11
+ import subprocess
12
+ import threading
13
+ from pathlib import Path
14
+
15
+ MAX_BYTES = 128 << 20
16
+ MAX_FILES = 10000
17
+ APPLY_MAX_MEMORY = 2 << 30 # address space of `git apply`: a binary delta can expand a lot
18
+ APPLY_SLOTS = threading.BoundedSemaphore(4) # `git apply` runs at once, world-wide
19
+
20
+
21
+ def git(root: Path, *args: str) -> str:
22
+ p = subprocess.run(["git", "-C", str(root), *args], capture_output=True, timeout=30, check=False)
23
+ if p.returncode:
24
+ raise ValueError("git failed on the world's checkout")
25
+ return p.stdout.decode().strip()
26
+
27
+
28
+ # git reads modes as octal and keeps only the type bits (0120000, 120755 are symlinks): any
29
+ # new mode that is not exactly a regular file's is refused.
30
+ _MODES = re.compile(rb"^(?:new file mode |new mode |index \S+ )(.*)$", re.MULTILINE)
31
+ _SIZES = re.compile(rb"^(?:literal|delta) (\d+)$", re.MULTILINE)
32
+
33
+
34
+ def apply_patch(workspace: dict, tree: Path) -> list[str]:
35
+ """Apply the patch onto `tree`, a git checkout of its `base_sha` (the world's own), in the
36
+ worktree (not the index), so the world's excludes apply when it stages the tree. Returns
37
+ the paths that differ from the base (added, modified, deleted). ValueError for an invalid
38
+ patch; symlinks and submodules are refused."""
39
+ try:
40
+ patch = base64.b64decode(workspace.get("patch") or "", validate=True)
41
+ except (ValueError, TypeError) as exc:
42
+ raise ValueError("invalid workspace patch") from exc
43
+ if git(tree, "rev-parse", "HEAD") != workspace.get("base_sha"):
44
+ raise ValueError("the tree is not a checkout of the patch's base")
45
+ if any(m not in (b"100644", b"100755") for m in _MODES.findall(patch)):
46
+ raise ValueError("symlinks are not supported")
47
+ # shortcut: a binary delta can expand past its declared size, up to the file-size and
48
+ # memory limits below, with at most APPLY_SLOTS applies at once; decode delta headers if
49
+ # that bound is too loose.
50
+ if (patch.count(b"\ndiff --git ") + patch.startswith(b"diff --git ") > MAX_FILES
51
+ or sum(int(n) for n in _SIZES.findall(patch)) > MAX_BYTES):
52
+ raise ValueError("workspace snapshot exceeds 128 MiB or 10,000 files")
53
+ if patch: # prlimit, not preexec_fn: the world's server is threaded
54
+ with APPLY_SLOTS:
55
+ p = subprocess.run(["prlimit", f"--fsize={MAX_BYTES}", f"--as={APPLY_MAX_MEMORY}",
56
+ "git", "-C", str(tree), "apply", "--binary",
57
+ "--whitespace=nowarn", "-"],
58
+ input=patch, capture_output=True, timeout=120, check=False)
59
+ if p.returncode:
60
+ raise ValueError("the workspace patch does not apply to its base")
61
+ for top, dirs, files in os.walk(tree):
62
+ if top == str(tree) and ".git" in dirs:
63
+ dirs.remove(".git")
64
+ if any(os.path.islink(os.path.join(top, n)) for n in dirs + files):
65
+ raise ValueError("symlinks are not supported")
66
+ names = git(tree, "ls-files", "-z", "--modified", "--deleted", "--others", "--exclude-standard")
67
+ return sorted({n for n in names.split("\0") if n})