pybot task and world
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +3 -0
- README.md +168 -0
- tasks/pybot-agent/environment/Dockerfile +4 -0
- tasks/pybot-agent/instruction.md +15 -0
- tasks/pybot-agent/task.toml +32 -0
- tasks/pybot-agent/tests/test.sh +4 -0
- world/Dockerfile +29 -0
- world/entrypoint.sh +45 -0
- world/pybot.py +0 -0
- world/pytest.ini +4 -0
- world/repository.py +475 -0
- world/requirements.txt +602 -0
- world/sandbox.py +233 -0
- world/scripts/check-sidecar.py +171 -0
- world/scripts/smoke-local.py +150 -0
- world/seed/.gitignore +3 -0
- world/seed/AGENTS.md +7 -0
- world/seed/CONTRIBUTING.md +83 -0
- world/seed/README.md +106 -0
- world/seed/STYLE.md +175 -0
- world/seed/bot/__init__.py +1 -0
- world/seed/bot/__main__.py +19 -0
- world/seed/bot/compose/__init__.py +12 -0
- world/seed/bot/knowledge/__init__.py +8 -0
- world/seed/bot/memory/__init__.py +17 -0
- world/seed/bot/modules/__init__.py +1 -0
- world/seed/bot/modules/arbiter.py +18 -0
- world/seed/bot/modules/greeting.py +6 -0
- world/seed/bot/modules/understand.py +8 -0
- world/seed/bot/runtime.py +120 -0
- world/seed/bot/understanding/__init__.py +35 -0
- world/seed/deck/multi.jsonl +40 -0
- world/seed/deck/single.jsonl +107 -0
- world/seed/tests/test_architecture.py +32 -0
- world/seed/tests/test_compare.py +34 -0
- world/seed/tests/test_deck.py +31 -0
- world/seed/tests/test_interface.py +19 -0
- world/seed/tests/test_runtime.py +22 -0
- world/seed/tools/compare.py +201 -0
- world/snapshot.py +70 -0
- world/source-lock.json +22 -0
- world/src/flock/__init__.py +3 -0
- world/src/flock/isolation.py +386 -0
- world/src/flock/models.py +2009 -0
- world/src/flock/registry.py +40 -0
- world/src/flock/tools/__init__.py +55 -0
- world/src/flock/tools/loader.py +385 -0
- world/src/flock/worker/__init__.py +1 -0
- world/src/flock/worker/sync.py +1181 -0
- world/src/flock/world/__init__.py +239 -0
.g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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pybot
|
| 2 |
+
|
| 3 |
+
A swarm of agents builds one chatbot together: a standard-library Python bot in a Hugging Face
|
| 4 |
+
dataset, changed only through pull requests that other agents review and merge. This repository
|
| 5 |
+
holds both halves that a [flock](https://github.com/huggingface/flock) run needs:
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
tasks/pybot-agent/ the Harbor task each agent runs in (one Trial per agent): instruction,
|
| 9 |
+
task.toml, environment/Dockerfile (python:3.12 by digest), tests/test.sh
|
| 10 |
+
world/ the shared world service (World API v1), one per run
|
| 11 |
+
pybot.py the world: PRs, reviews, the merge queue, bot runs, world_status
|
| 12 |
+
repository.py the world's bare git repository and the Hub client
|
| 13 |
+
sandbox.py runs a bot or its tests isolated; `python sandbox.py serve` is the sidecar
|
| 14 |
+
snapshot.py the world's state archive in a bucket (world.tar.gz)
|
| 15 |
+
seed/ the bot the code dataset starts from (runtime, modules, deck, tests, docs)
|
| 16 |
+
tests/ the world's tests (pytest), with a small test seed in tests/fixtures/
|
| 17 |
+
scripts/ smoke-local.py and check-sidecar.py: container-free checks on localhost
|
| 18 |
+
src/ flock's World API library, vendored (never edit; vendor.sh)
|
| 19 |
+
requirements.txt the world's Python deps with hashes (from flock's uv.lock; vendor.sh)
|
| 20 |
+
source-lock.json the flock commit and the sha256 of every vendored file
|
| 21 |
+
vendor.sh re-vendor src/ and requirements.txt from a flock checkout
|
| 22 |
+
Dockerfile the world image (also the sidecar's); entrypoint.sh starts the world
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## The world
|
| 26 |
+
|
| 27 |
+
Agents clone the code dataset (`$PYBOT_REPO`) into `pybot` and never push to it. They work
|
| 28 |
+
through the world's tools, which flock exposes as `world.*`:
|
| 29 |
+
|
| 30 |
+
| tool | what it does |
|
| 31 |
+
|---|---|
|
| 32 |
+
| `open_pr` | uploads the caller's clone (`path`, default `pybot`) and opens or updates a Hub PR |
|
| 33 |
+
| `review_pr` | approve or request changes on a PR's head |
|
| 34 |
+
| `merge_pr` | queues a PR; the merger rebases a stale PR, runs the contract and the shared tests, merges on the Hub |
|
| 35 |
+
| `close_pr`, `list_prs`, `get_pr` | close one PR, list PRs, read one PR's diff and files |
|
| 36 |
+
| `run_bot` | talks to `main`, a PR (`pr:<n>`) or the caller's clone, in the bot sandbox |
|
| 37 |
+
| `record_verdict`, `verdicts` | interview verdicts: who an interviewer believed it talked to |
|
| 38 |
+
| `world_status` | read-only collaboration health: queue, refusals, shared-test runs, counts |
|
| 39 |
+
|
| 40 |
+
The Hub stays the git backend: the world keeps a bare clone, pushes PR heads and merges through
|
| 41 |
+
the Hub API, and writes its state to `PYBOT_BUCKET` (`world.tar.gz`, restored into an empty
|
| 42 |
+
workspace at start, pushed every `PYBOT_BUCKET_PUSH_S` and at exit).
|
| 43 |
+
|
| 44 |
+
The world serves `/healthz`, `/manifest`, `/tools/*`, `/metrics` and `/admin/*` on `$PORT`.
|
| 45 |
+
`X-World-Token` is the world secret (`FLOCK_WORLD_TOKEN`) or, on `/manifest` and tool calls,
|
| 46 |
+
an agent's own token for its `X-Flock-Agent`: HMAC-SHA256(secret, `flock-world-agent\0<agent>`).
|
| 47 |
+
|
| 48 |
+
Bots run isolated: in this container under `unshare` when it is allowed (Slurm), or in the
|
| 49 |
+
sidecar, a second container of the same image with command `python sandbox.py serve` that gets
|
| 50 |
+
only `PYBOT_SANDBOX_TOKEN` (Docker's default seccomp and HF Jobs block `unshare`). A sidecar
|
| 51 |
+
that is down or refuses gives the agent `busy`, never "your bot failed". The sidecar still has
|
| 52 |
+
the network on HF Jobs; the bot shim's import blocks (no socket, subprocess or ctypes) are the
|
| 53 |
+
guard there.
|
| 54 |
+
|
| 55 |
+
## Build and run
|
| 56 |
+
|
| 57 |
+
```sh
|
| 58 |
+
docker build -t <registry>/pybot-world:<tag> world/
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
The code dataset must exist and hold the seed before the world starts (the image never seeds):
|
| 62 |
+
|
| 63 |
+
```sh
|
| 64 |
+
cp -r world/seed /tmp/pybot-seed && cd /tmp/pybot-seed
|
| 65 |
+
git init -b main && git add . && git commit -m seed
|
| 66 |
+
git push https://huggingface.co/datasets/<ns>/<name> main # a write token via a credential helper
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
World (one per run; give it about 30 s to stop, so the final push completes):
|
| 70 |
+
|
| 71 |
+
```sh
|
| 72 |
+
docker run -p 7860:7860 -e HF_TOKEN -e FLOCK_WORLD_TOKEN \
|
| 73 |
+
-e PYBOT_REPO=<ns>/<name> -e PYBOT_BUCKET=hf://buckets/<ns>/<bucket>/<run> \
|
| 74 |
+
-e PYBOT_SANDBOX_URL=http://sandbox:8000 -e PYBOT_SANDBOX_TOKEN \
|
| 75 |
+
<registry>/pybot-world:<tag>
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
Sidecar (same image; nothing but its token):
|
| 79 |
+
|
| 80 |
+
```sh
|
| 81 |
+
docker run --name sandbox -e PYBOT_SANDBOX_TOKEN <registry>/pybot-world:<tag> python sandbox.py serve
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
On HF Jobs, run both jobs in one network group with the sidecar's alias `sandbox` and set
|
| 85 |
+
`PYBOT_SANDBOX_URL=http://${HF_NETWORK_GROUP_PREFIX}sandbox:8000` (the world expands `${VAR}`s in
|
| 86 |
+
the URL). On Slurm, leave `PYBOT_SANDBOX_URL` unset and set `FLOCK_WORLD_HOST_FILE` so flock's
|
| 87 |
+
controller can follow the world's `host:port`.
|
| 88 |
+
|
| 89 |
+
Sizing: an 8-CPU world with `PYBOT_CHECKOUT_SLOTS=4` serves 10 agents; at 1,000 agents give the
|
| 90 |
+
world about 28 CPUs and 54 GB.
|
| 91 |
+
|
| 92 |
+
## Settings
|
| 93 |
+
|
| 94 |
+
Every setting is an environment variable; the defaults below are the world's own, so a run
|
| 95 |
+
needs only the required ones.
|
| 96 |
+
|
| 97 |
+
| variable | default | |
|
| 98 |
+
|---|---|---|
|
| 99 |
+
| `HF_TOKEN` | required | Hub write token for `PYBOT_REPO` and the bucket; reaches git through `GIT_ASKPASS`, never argv |
|
| 100 |
+
| `FLOCK_WORLD_TOKEN` | required | the world secret (`X-World-Token`); flock's `resources.world.token_env` holds the same value |
|
| 101 |
+
| `PYBOT_REPO` | required | `<ns>/<name>` of the code dataset |
|
| 102 |
+
| `PYBOT_BUCKET` | required (entrypoint) | `hf://buckets/<ns>/<bucket>/<prefix>` for `world.tar.gz`; `off`: no restore, no pushes (smoke tests) |
|
| 103 |
+
| `PYBOT_SANDBOX_URL`, `PYBOT_SANDBOX_TOKEN` | empty | the sidecar; set both (the entrypoint refuses a URL without the token). Empty: `unshare` here |
|
| 104 |
+
| `FLOCK_WORLD_ADMIN_TOKEN` | empty: `/admin` off | admin secret for live knobs and lane pauses |
|
| 105 |
+
| `PYBOT_SEED_DIR` | `seed` | the seed whose fixed files (runtime, loader, package initializers) the contract compares; next to `pybot.py` or absolute |
|
| 106 |
+
| `PYBOT_MAX_REVIEWERS` | `2` | reviewers per PR change; one more is refused (`review_full`); 0: unlimited |
|
| 107 |
+
| `PYBOT_PR_OPEN_BUDGET` | `merges` | new PRs per hour may not exceed max(merges in the last hour, `PYBOT_PR_OPEN_FLOOR`); `off` |
|
| 108 |
+
| `PYBOT_PR_OPEN_BUDGET_SCOPE` | `new_modules` | which new PRs count: only those that add a module, or `all` |
|
| 109 |
+
| `PYBOT_PR_OPEN_FLOOR` | `20` | the budget's floor per hour |
|
| 110 |
+
| `PYBOT_RUN_SLOTS` | `6` | bot and test runs at once |
|
| 111 |
+
| `PYBOT_CHECKOUT_SLOTS` | `8` | full-tree checkouts by agents' tools at once (the merger takes none) |
|
| 112 |
+
| `PYBOT_HUB_WRITE_SLOTS` | `4` | concurrent Hub writes for PR creates, pushes and closes (0–4) |
|
| 113 |
+
| `PYBOT_MERGE_HUB_SLOTS` | `1` | concurrent Hub merges (0–4) |
|
| 114 |
+
| `PYBOT_GET_PR_DIFF_BYTES` | `60000` | `get_pr`'s diff, cut at a line end beyond this |
|
| 115 |
+
| `PYBOT_UNION_PATHS` | `deck/*.jsonl` | paths whose replays onto main keep both sides' lines (`merge=union`, at merge only); `""` turns it off |
|
| 116 |
+
| `PYBOT_MERGE_TESTS` | `test_deck.py` | `merge_pr`'s shared tests (a unittest pattern under `tests/`); name read-only tests only |
|
| 117 |
+
| `PYBOT_TMP_DIR` | `/tmp` | temporary checkouts; empty: the workspace. Use a disk path if `/tmp` is a RAM tmpfs |
|
| 118 |
+
| `PYBOT_BUCKET_PUSH_S` | `300` | seconds between state pushes to the bucket |
|
| 119 |
+
| `PYBOT_PR_CREATE_GAP_S` | `10` | seconds between Hub PR creations |
|
| 120 |
+
| `PYBOT_HUB_OUTBOX_GAP_S` | `1` | seconds between review-comment posts |
|
| 121 |
+
| `PYBOT_HUB_WAIT_S` | `20` | how long a call waits for a Hub write slot before `busy` |
|
| 122 |
+
| `PYBOT_HUB_REFS_TTL_S` | `5` | cache of the Hub's refs |
|
| 123 |
+
| `PYBOT_HUB_STATES_EVERY_S` | `600` | PR state check against the Hub |
|
| 124 |
+
| `PYBOT_ANON_FETCH` | `1` | fetch anonymously first; `0`: always with the token |
|
| 125 |
+
| `PYBOT_FETCH_TTL_S` | `60` | cache of a fetched main |
|
| 126 |
+
| `PYBOT_CALL_BUDGET_S` | `50` | seconds a tool call may spend on Hub waits and push retries (callers wait about 55 s) |
|
| 127 |
+
| `PYBOT_REQUEST_TTL_S` | `21600` | how long `open_pr` idempotency keys are kept |
|
| 128 |
+
| `PYBOT_MAX_FILE_BYTES` | `1048576` | largest file in an uploaded clone |
|
| 129 |
+
| `PYBOT_SAVE_INTERVAL_S` | `2.0` | seconds between state saves (0: every change) |
|
| 130 |
+
| `PYBOT_PACK_LOOSE_MAX` | `20000` | loose objects packed per git maintenance pass (every 30 min) |
|
| 131 |
+
| `PYBOT_OPERATORS` | empty | agent names that may close other agents' PRs (comma-separated) |
|
| 132 |
+
| `PYBOT_PRS_PAUSED`, `PYBOT_PRS_PAUSED_FILE` | empty, `<ws>/prs-paused` | pause `open_pr` and `merge_pr` at start, or while the file exists |
|
| 133 |
+
| `PORT`, `PYBOT_WORK`, `FLOCK_WORLD_HOST_FILE`, `WORLD_HOST` | `7860`, `/work`, unset, `$HOSTNAME` | entrypoint only: the port, the state directory, and where to write `host:port` |
|
| 134 |
+
|
| 135 |
+
## How a flock spec uses it
|
| 136 |
+
|
| 137 |
+
The world is a resource that the operator starts; every agent runs the task. The spec names the
|
| 138 |
+
published task and the world's URL:
|
| 139 |
+
|
| 140 |
+
```yaml
|
| 141 |
+
task:
|
| 142 |
+
repo: https://huggingface.co/datasets/<ns>/pybot
|
| 143 |
+
selector: pybot-agent
|
| 144 |
+
revision: '<commit sha>'
|
| 145 |
+
resources:
|
| 146 |
+
world:
|
| 147 |
+
url: '${WORLD_URL}' # the world's URL (HF Jobs: the world job's public URL)
|
| 148 |
+
token_env: PYBOT_WORLD_TOKEN # same value as the world's FLOCK_WORLD_TOKEN; a new one per run
|
| 149 |
+
transport: http # backends without mounts (hf-sandbox); `unix` on docker/podman
|
| 150 |
+
tools:
|
| 151 |
+
- world.*
|
| 152 |
+
workers:
|
| 153 |
+
env: {PYBOT_REPO: '${PYBOT_REPO}'} # the task's [environment.env] reads it
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
## Checks
|
| 157 |
+
|
| 158 |
+
```sh
|
| 159 |
+
cd world
|
| 160 |
+
pip install --require-hashes --no-deps -r requirements.txt && pip install pytest pytest-asyncio
|
| 161 |
+
python -m pytest # the world's tests (Python 3.12, git, prlimit)
|
| 162 |
+
python scripts/smoke-local.py --sidecar # the served world on localhost with a fake Hub
|
| 163 |
+
python scripts/check-sidecar.py # the sidecar's checks
|
| 164 |
+
./vendor.sh /path/to/flock # the vendored library matches source-lock.json
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
`smoke-local.py` without `--sidecar` runs the bot under `unshare`, which many machines and
|
| 168 |
+
containers refuse; it then reports a note, not a failure.
|
tasks/pybot-agent/environment/Dockerfile
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The agent's own container, the same image as task.toml's docker_image: the full Python 3.12
|
| 2 |
+
# image already has git, curl and bash (Harbor's Pi installer and flock's tools need them), and
|
| 3 |
+
# root is its default user (flock's tool setup and hf-sandbox need that).
|
| 4 |
+
FROM python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735
|
tasks/pybot-agent/instruction.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pybot: one agent of a swarm
|
| 2 |
+
|
| 3 |
+
You are one of several agents who build one chatbot together. Your container is your own; the
|
| 4 |
+
code, its pull requests and the message board are shared with the other agents.
|
| 5 |
+
|
| 6 |
+
- The code is the Hugging Face dataset named in `$PYBOT_REPO`. Clone it once into
|
| 7 |
+
`pybot` in your working directory:
|
| 8 |
+
`git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`
|
| 9 |
+
- Never push to it. Submit, review and merge through the world's tools:
|
| 10 |
+
`flock-tool world.tools` lists them with their parameters, and
|
| 11 |
+
`flock-tool world.call --json '{"tool": "<name>", "args": {...}}'` calls one as you.
|
| 12 |
+
A tool that takes a clone path (open_pr's `path`, default `pybot`, relative to your
|
| 13 |
+
working directory) uploads that clone from your container.
|
| 14 |
+
- Talk to the other agents on the board with the board tools (`message_board.*`,
|
| 15 |
+
`message_board_extra.*`).
|
tasks/pybot-agent/task.toml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# One agent of a pybot swarm: one Harbor Trial per agent, each on its own copy of this task. The
|
| 2 |
+
# shared state is outside the task: the pybot world (flock's resources.world, tools world.*; its
|
| 3 |
+
# code is ../../world) and the board (resources.message_board, tools message_board.*). No
|
| 4 |
+
# per-agent reward: tests/test.sh writes 0.
|
| 5 |
+
schema_version = "1.4"
|
| 6 |
+
|
| 7 |
+
[task]
|
| 8 |
+
name = "flock/pybot-agent"
|
| 9 |
+
description = "One agent of a swarm that builds a chatbot together: clone $PYBOT_REPO, submit and review through the shared world's tools, talk on the board."
|
| 10 |
+
|
| 11 |
+
[metadata]
|
| 12 |
+
world = "pybot"
|
| 13 |
+
world_version = "1.0.0"
|
| 14 |
+
world_api = "v1"
|
| 15 |
+
|
| 16 |
+
[agent]
|
| 17 |
+
timeout_sec = 10800.0 # flock's limits.agent_timeout_seconds overrides it
|
| 18 |
+
|
| 19 |
+
[verifier]
|
| 20 |
+
timeout_sec = 60.0
|
| 21 |
+
|
| 22 |
+
[environment]
|
| 23 |
+
# = environment/Dockerfile (nothing to build): hf-sandbox needs a prebuilt image and docker
|
| 24 |
+
# prefers it. Python 3.12, git, curl and bash; root is the default user.
|
| 25 |
+
docker_image = "python@sha256:14a4933e6cef421424f7a66d89a3f4eafcbd0d90e0a822251f298e05132dc735" # python:3.12.15-bookworm; digest-only: HF Jobs' default job name from a tagged digest exceeds 100 chars
|
| 26 |
+
cpus = 2
|
| 27 |
+
memory_mb = 4096
|
| 28 |
+
|
| 29 |
+
[environment.env]
|
| 30 |
+
PYBOT_REPO = "${PYBOT_REPO}" # <ns>/<name> HF dataset the world serves; from the launcher's env, no default
|
| 31 |
+
# Caps git's memory in the agent's clone (many agents share a machine).
|
| 32 |
+
GIT_CONFIG_PARAMETERS = "'pack.windowMemory=256m' 'pack.threads=1' 'gc.auto=0'"
|
tasks/pybot-agent/tests/test.sh
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# No per-agent reward: every agent scores 0, a valid reward (a Trial without one counts as failed).
|
| 3 |
+
mkdir -p /logs/verifier
|
| 4 |
+
echo 0 > /logs/verifier/reward.txt
|
world/Dockerfile
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 flock's own uv.lock (exact versions + hashes, see vendor.sh).
|
| 6 |
+
FROM python:3.12.15-slim-bookworm@sha256:6a0e06f5ba0b373d051aabd3fffb9b873f27f9a2a3a14bcbe37dee6f0e3bbc70
|
| 7 |
+
|
| 8 |
+
# git: the world's bare repo, fetches and pushes to the Hub. util-linux (unshare) ships in the base.
|
| 9 |
+
RUN apt-get update \
|
| 10 |
+
&& apt-get install -y --no-install-recommends git \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
+
|
| 13 |
+
COPY requirements.txt /opt/world/requirements.txt
|
| 14 |
+
RUN pip install --no-cache-dir --no-deps --require-hashes -r /opt/world/requirements.txt
|
| 15 |
+
|
| 16 |
+
# src/: flock's World API library, vendored by vendor.sh (hashes in source-lock.json), never edited.
|
| 17 |
+
COPY src/ /opt/world/src/
|
| 18 |
+
COPY pybot.py repository.py sandbox.py snapshot.py /opt/world/
|
| 19 |
+
COPY seed/ /opt/world/seed/
|
| 20 |
+
COPY --chmod=755 entrypoint.sh /usr/local/bin/pybot-entrypoint
|
| 21 |
+
|
| 22 |
+
RUN useradd -m -u 1000 user && mkdir -p /work && chown user:user /work
|
| 23 |
+
USER user
|
| 24 |
+
# For the sidecar's bare `python sandbox.py serve` (a job command replaces the entrypoint); the
|
| 25 |
+
# entrypoint sets its own PYTHONPATH and cwd, so the world does not depend on these.
|
| 26 |
+
ENV PYTHONPATH=/opt/world/src
|
| 27 |
+
WORKDIR /opt/world
|
| 28 |
+
EXPOSE 7860
|
| 29 |
+
ENTRYPOINT ["/usr/local/bin/pybot-entrypoint"]
|
world/entrypoint.sh
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# pybot-entrypoint: check the env, then serve the pybot world on $PORT (`python pybot.py`).
|
| 3 |
+
#
|
| 4 |
+
# The world keeps its own state in PYBOT_BUCKET: an empty PYBOT_WS is restored from
|
| 5 |
+
# <bucket>/world.tar.gz before it serves (a failed restore parks the world, which retries with
|
| 6 |
+
# backoff; /healthz says "parked"), and it pushes every PYBOT_BUCKET_PUSH_S (300) and at exit
|
| 7 |
+
# (SIGTERM, or SIGUSR1, which the server turns into SIGTERM).
|
| 8 |
+
#
|
| 9 |
+
# Arguments are ignored, so a launcher's placeholder command (e.g. `sleep infinity`) is harmless.
|
| 10 |
+
#
|
| 11 |
+
# Required env: HF_TOKEN FLOCK_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), FLOCK_WORLD_HOST_FILE (writes host:port there: the file flock'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 FLOCK_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
|
| 25 |
+
off) unset PYBOT_BUCKET ;; # the world: no PYBOT_BUCKET = no restore and no pushes
|
| 26 |
+
hf://buckets/*/*) ;;
|
| 27 |
+
*) die "PYBOT_BUCKET must be hf://buckets/<ns>/<bucket>[/prefix] or off" ;;
|
| 28 |
+
esac
|
| 29 |
+
export PORT=${PORT:-7860}
|
| 30 |
+
case $PORT in ''|*[!0-9]*|0) die "PORT=$PORT must be a positive integer";; esac
|
| 31 |
+
|
| 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 |
+
export PYTHONPATH=$WORLD/src HOME=$WORK/home HF_HOME=$WORK/hf TMPDIR=$WORK/tmp
|
| 36 |
+
export PYBOT_WS=$WORK/ws PYTHONUNBUFFERED=1
|
| 37 |
+
mkdir -p "$PYBOT_WS" "$HOME" "$HF_HOME" "$TMPDIR" || die "cannot create dirs under $WORK"
|
| 38 |
+
|
| 39 |
+
if [ -n "${FLOCK_WORLD_HOST_FILE:-}" ]; then # atomic: flock's controller re-reads it every 15 s
|
| 40 |
+
{ echo "${WORLD_HOST:-$HOSTNAME}:$PORT" > "$FLOCK_WORLD_HOST_FILE.tmp" && mv "$FLOCK_WORLD_HOST_FILE.tmp" "$FLOCK_WORLD_HOST_FILE"; } \
|
| 41 |
+
|| echo "pybot-entrypoint: cannot write $FLOCK_WORLD_HOST_FILE" >&2
|
| 42 |
+
fi
|
| 43 |
+
|
| 44 |
+
cd "$WORLD" || die "cannot cd $WORLD"
|
| 45 |
+
exec python pybot.py # serve() on 0.0.0.0:$PORT; the token comes from FLOCK_WORLD_TOKEN, never argv
|
world/pybot.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
world/pytest.ini
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
asyncio_mode = auto
|
| 3 |
+
asyncio_default_fixture_loop_scope = function
|
| 4 |
+
testpaths = tests
|
world/repository.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Git transport and native Hub PRs. The world uses the shared experiment HF_TOKEN for writes."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import signal
|
| 8 |
+
import subprocess
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from urllib.parse import urlsplit
|
| 13 |
+
|
| 14 |
+
from huggingface_hub import HfApi
|
| 15 |
+
from huggingface_hub.errors import HfHubHTTPError
|
| 16 |
+
|
| 17 |
+
from flock.world import ToolError
|
| 18 |
+
from flock.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.
|
| 22 |
+
PACK_LOOSE_MAX = int(os.environ.get("PYBOT_PACK_LOOSE_MAX", "20000"))
|
| 23 |
+
|
| 24 |
+
_URL_CREDENTIALS = re.compile(r"(?<=://)[^/@\s]+@")
|
| 25 |
+
_HUB_HEADERS = ("x-error-code", "x-error-message", "x-request-id", "retry-after")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _safe_text(text, limit):
|
| 29 |
+
return _URL_CREDENTIALS.sub("[redacted]@", redact(text))[:limit]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _log_hub_failure(method, repo_id, exc):
|
| 33 |
+
"""One WARNING with the status and diagnostic headers; never the exception text, body or
|
| 34 |
+
request headers, which can hold secrets."""
|
| 35 |
+
response = getattr(exc, "response", None)
|
| 36 |
+
request = getattr(response, "request", None)
|
| 37 |
+
where = ""
|
| 38 |
+
if request is not None:
|
| 39 |
+
where = f"{request.method} {urlsplit(str(request.url)).path}"
|
| 40 |
+
headers = {name: _safe_text(str(response.headers[name]), 300 if name == "x-error-message" else 100)
|
| 41 |
+
for name in _HUB_HEADERS if response is not None and name in response.headers}
|
| 42 |
+
log.warning("Hub call %s failed for %s: status=%s request=%s headers=%s", method, repo_id,
|
| 43 |
+
getattr(response, "status_code", None), where or "unknown", headers)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Repository:
|
| 47 |
+
def __init__(self, root: Path, remote: str, hub=None):
|
| 48 |
+
self.root, self.remote, self.hub = root, remote, hub
|
| 49 |
+
# Ref writes in the shared bare repository (fetch, update-ref) are serialized here,
|
| 50 |
+
# not under the world's state lock; reads, clones and object writes run concurrently.
|
| 51 |
+
self.refs_lock = threading.Lock()
|
| 52 |
+
self.fetched = 0.0
|
| 53 |
+
# (base, head) -> stable patch-id of the default diff, (base, head, 0) -> of the -U0 diff
|
| 54 |
+
self.patch_ids = {}
|
| 55 |
+
self.env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GIT_CONFIG_NOSYSTEM": "1",
|
| 56 |
+
"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_LFS_SKIP_SMUDGE": "1"}
|
| 57 |
+
# The dataset is public: PR refs are fetched anonymously first (the Hub throttles git
|
| 58 |
+
# fetches per token), then with the token. PYBOT_ANON_FETCH=0 disables it.
|
| 59 |
+
self.anonymous = (remote.startswith("https://")
|
| 60 |
+
and os.environ.get("PYBOT_ANON_FETCH", "1").strip() != "0")
|
| 61 |
+
if hub is not None:
|
| 62 |
+
# The URL, argv and repository config contain no token.
|
| 63 |
+
askpass = root.parent / "git-askpass.py"
|
| 64 |
+
askpass.write_text("#!/usr/bin/env python3\nimport os,sys\n"
|
| 65 |
+
"print('hf_user' if 'Username' in sys.argv[1] else os.environ['HF_TOKEN'])\n")
|
| 66 |
+
askpass.chmod(0o700)
|
| 67 |
+
self.env["GIT_ASKPASS"] = str(askpass)
|
| 68 |
+
if not (root / "HEAD").exists():
|
| 69 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
self.git("init", "--bare", str(root), at=root.parent)
|
| 71 |
+
self.git("remote", "add", "origin", remote)
|
| 72 |
+
bundle = root.parent / "repo.bundle"
|
| 73 |
+
if bundle.exists():
|
| 74 |
+
self.git("fetch", str(bundle), "+refs/*:refs/*")
|
| 75 |
+
bundle.unlink()
|
| 76 |
+
# PYBOT_UNION_PATHS: gitattributes patterns (e.g. deck/*.jsonl) whose replays onto main
|
| 77 |
+
# keep both sides' lines (merge=union) instead of conflicting. The attributes file is the
|
| 78 |
+
# world's own, next to its repository; the dataset is unchanged.
|
| 79 |
+
union = [p for p in re.split(r"[\s,]+", os.environ.get("PYBOT_UNION_PATHS", "deck/*.jsonl")) if p]
|
| 80 |
+
self.attributes = root.parent / "union.gitattributes" if union else None
|
| 81 |
+
if self.attributes:
|
| 82 |
+
self.attributes.write_text("".join(f"{p} merge=union\n" for p in union))
|
| 83 |
+
# Fetches start no background gc: it packed refs outside refs_lock. maintain() packs.
|
| 84 |
+
self.git("config", "maintenance.auto", "false")
|
| 85 |
+
self.git("config", "gc.auto", "0") # nor does any git command run gc --auto here
|
| 86 |
+
# Only this world runs gc here: a gc.pid is a gc stopped with a world that ran elsewhere,
|
| 87 |
+
# and git would honour it for 12 h.
|
| 88 |
+
(root / "gc.pid").unlink(missing_ok=True)
|
| 89 |
+
(root / "objects" / "pack" / "multi-pack-index.lock").unlink(missing_ok=True) # likewise
|
| 90 |
+
self.fetch()
|
| 91 |
+
|
| 92 |
+
def git(self, *args, at=None, data=None, env=None, timeout=120, group=False):
|
| 93 |
+
return self.git_bytes(*args, at=at, data=data, env=env, timeout=timeout,
|
| 94 |
+
group=group).decode().strip()
|
| 95 |
+
|
| 96 |
+
def git_bytes(self, *args, at=None, data=None, env=None, timeout=120, group=False):
|
| 97 |
+
"""Run git and return its raw stdout (for diffs and file contents, which need not be
|
| 98 |
+
UTF-8). Failures raise like git(). group: git runs in its own process group, and a
|
| 99 |
+
timeout kills the whole group (gc's repack and pack-objects too), then raises."""
|
| 100 |
+
argv = ["git", "-C", str(at or self.root), *args]
|
| 101 |
+
if group:
|
| 102 |
+
with subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 103 |
+
stderr=subprocess.PIPE, env=env or self.env,
|
| 104 |
+
start_new_session=True) as proc:
|
| 105 |
+
try:
|
| 106 |
+
out, err = proc.communicate(data, timeout=timeout)
|
| 107 |
+
except subprocess.TimeoutExpired:
|
| 108 |
+
os.killpg(proc.pid, signal.SIGKILL)
|
| 109 |
+
proc.wait()
|
| 110 |
+
raise
|
| 111 |
+
p = subprocess.CompletedProcess(argv, proc.returncode, out, err)
|
| 112 |
+
else:
|
| 113 |
+
p = subprocess.run(argv, input=data, capture_output=True, env=env or self.env,
|
| 114 |
+
timeout=timeout, check=False)
|
| 115 |
+
if p.returncode:
|
| 116 |
+
# Git's stderr can contain remote data or credentials: never expose it to agents;
|
| 117 |
+
# the world's log gets it redacted.
|
| 118 |
+
command = next((a for a in args if not a.startswith("-") and "=" not in a), "?")
|
| 119 |
+
stderr = p.stderr.decode(errors="replace")
|
| 120 |
+
log.warning("git %s failed: exit code %s, stderr=%s", command, p.returncode,
|
| 121 |
+
_safe_text(stderr.strip(), 500))
|
| 122 |
+
# A --force-with-lease push whose expected value no longer matches the remote ref.
|
| 123 |
+
code = "stale_lease" if command == "push" and "stale info" in stderr else "git_error"
|
| 124 |
+
raise ToolError("repository operation failed; refresh your clone and retry", code)
|
| 125 |
+
return p.stdout
|
| 126 |
+
|
| 127 |
+
def negotiation(self):
|
| 128 |
+
"""Offer only main's history as haves: with ~2,000 local refs the default negotiation
|
| 129 |
+
makes the request large enough for the Hub to drop it. Git refuses a tip that doesn't
|
| 130 |
+
exist yet (before the first fetch), so it's passed only when main is there."""
|
| 131 |
+
p = subprocess.run(["git", "-C", str(self.root), "rev-parse", "--verify", "-q", "refs/heads/main"],
|
| 132 |
+
env=self.env, capture_output=True, timeout=10, check=False)
|
| 133 |
+
return ["--negotiation-tip=refs/heads/main"] if p.returncode == 0 else []
|
| 134 |
+
|
| 135 |
+
def hub_fetch(self, remote, *specs, options=(), env=None):
|
| 136 |
+
"""Every fetch from the Hub: protocol v2 (explicit; v0 floods haves) with main as the
|
| 137 |
+
only negotiation tip, explicit refspecs only (the Hub drops wildcard PR-ref fetches)."""
|
| 138 |
+
self.git("-c", "protocol.version=2", *options, "fetch", "--no-write-fetch-head",
|
| 139 |
+
*self.negotiation(), remote, *specs, env=env)
|
| 140 |
+
|
| 141 |
+
def fetch(self):
|
| 142 |
+
"""Fetch main only. The world writes refs/pr/N itself after every push (update_refs), so
|
| 143 |
+
PR refs never come from the Hub here; a wildcard over refs/pr/* is also refused by the
|
| 144 |
+
Hub's git backend once there are many PRs (hang-up / 'expected acknowledgments').
|
| 145 |
+
A fetch that started after this call is as fresh as this one: waiters behind it return."""
|
| 146 |
+
asked = time.monotonic()
|
| 147 |
+
with self.refs_lock:
|
| 148 |
+
if self.fetched > asked:
|
| 149 |
+
return
|
| 150 |
+
started = time.monotonic()
|
| 151 |
+
self.hub_fetch("origin", "+refs/heads/main:refs/heads/main")
|
| 152 |
+
self.fetched = started
|
| 153 |
+
|
| 154 |
+
def has_commit(self, sha):
|
| 155 |
+
if not sha or len(sha) != 40 or any(c not in "0123456789abcdef" for c in sha):
|
| 156 |
+
return False
|
| 157 |
+
p = subprocess.run(["git", "-C", str(self.root), "cat-file", "-e", f"{sha}^{{commit}}"],
|
| 158 |
+
env=self.env, capture_output=True, timeout=10, check=False)
|
| 159 |
+
return p.returncode == 0
|
| 160 |
+
|
| 161 |
+
def fetch_anonymous(self, *specs):
|
| 162 |
+
"""Fetch specs from the plain remote URL without credentials (no askpass, no token, no
|
| 163 |
+
credential helper). Never raises: returns False on failure (or when disabled)."""
|
| 164 |
+
if not self.anonymous:
|
| 165 |
+
return False
|
| 166 |
+
env = {k: v for k, v in self.env.items()
|
| 167 |
+
if k not in ("GIT_ASKPASS", "SSH_ASKPASS", "HF_TOKEN", "HUGGING_FACE_HUB_TOKEN")}
|
| 168 |
+
try:
|
| 169 |
+
with self.refs_lock:
|
| 170 |
+
self.hub_fetch(self.remote, *specs, options=("-c", "credential.helper="), env=env)
|
| 171 |
+
return True
|
| 172 |
+
except Exception: # noqa: BLE001 - logged by git() (the URL holds no credentials)
|
| 173 |
+
return False
|
| 174 |
+
|
| 175 |
+
def fetch_pr_refs(self, numbers, batch=8, delays=(1, 3, 9)):
|
| 176 |
+
"""Fetch refs/pr/N for the given PR numbers from the Hub, explicitly, in small batches
|
| 177 |
+
(the Hub hangs up on large or wildcard PR-ref fetches): anonymously first, then with the
|
| 178 |
+
token. Never raises: a batch that still fails after the retries is logged, and the list
|
| 179 |
+
of PR numbers left unfetched is returned."""
|
| 180 |
+
missing = []
|
| 181 |
+
numbers = [int(n) for n in numbers]
|
| 182 |
+
for start in range(0, len(numbers), batch):
|
| 183 |
+
chunk = numbers[start:start + batch]
|
| 184 |
+
specs = [f"+refs/pr/{n}:refs/pr/{n}" for n in chunk]
|
| 185 |
+
if self.fetch_anonymous(*specs):
|
| 186 |
+
continue
|
| 187 |
+
for attempt, delay in enumerate(delays + (None,)):
|
| 188 |
+
try:
|
| 189 |
+
with self.refs_lock:
|
| 190 |
+
self.hub_fetch("origin", *specs)
|
| 191 |
+
break
|
| 192 |
+
except ToolError:
|
| 193 |
+
if delay is None:
|
| 194 |
+
log.warning("PR refs %s not fetched after %d attempts", chunk, attempt + 1)
|
| 195 |
+
missing.extend(chunk)
|
| 196 |
+
else:
|
| 197 |
+
time.sleep(delay)
|
| 198 |
+
return missing
|
| 199 |
+
|
| 200 |
+
def refresh(self, max_age):
|
| 201 |
+
"""Fetch unless a fetch started within max_age seconds. The world updates its own
|
| 202 |
+
refs after every push and merge, so this only catches up with outside changes; with
|
| 203 |
+
max_age > 0 it also returns at once while refs_lock is busy (a fetch is running)
|
| 204 |
+
instead of queueing another fetch. max_age 0 always gets a main fetched after the call."""
|
| 205 |
+
if time.monotonic() - self.fetched < max_age or (max_age > 0 and self.refs_lock.locked()):
|
| 206 |
+
return
|
| 207 |
+
self.fetch()
|
| 208 |
+
|
| 209 |
+
def update_refs(self, *refs):
|
| 210 |
+
"""Point each (ref, sha) at its sha in one transaction: one refs_lock wait."""
|
| 211 |
+
with self.refs_lock:
|
| 212 |
+
self.git("update-ref", "--stdin", data="".join(f"update {ref} {sha}\n" for ref, sha in refs).encode())
|
| 213 |
+
|
| 214 |
+
def maintain(self, info):
|
| 215 |
+
"""Keep the bare repository fast in a pass that takes minutes: pack every ref, pack every
|
| 216 |
+
loose object (reachable or not: rebased and refused commits) into one new pack, then
|
| 217 |
+
delete their loose copies. Packs already there are never rewritten: a full or cruft gc
|
| 218 |
+
of a large repository (~1 GiB in tens of packs on network storage) takes over 30 min.
|
| 219 |
+
Nothing is pruned; the pack count grows by one per pass. Fills info with the counts and
|
| 220 |
+
each step's seconds, also when a step fails."""
|
| 221 |
+
info["loose_before"] = self.loose()
|
| 222 |
+
start = time.monotonic()
|
| 223 |
+
with self.refs_lock:
|
| 224 |
+
self.git("pack-refs", "--all")
|
| 225 |
+
info["pack_refs_s"], start = time.monotonic() - start, time.monotonic()
|
| 226 |
+
objects = self.root / "objects"
|
| 227 |
+
for tmp in (objects / "pack").glob("tmp_*"): # a pass killed at its timeout left it
|
| 228 |
+
try:
|
| 229 |
+
if tmp.stat().st_mtime < time.time() - 3600: # a running fetch writes fresh ones
|
| 230 |
+
tmp.unlink(missing_ok=True)
|
| 231 |
+
except FileNotFoundError: # a fetch just renamed its tmp_pack
|
| 232 |
+
pass
|
| 233 |
+
# objects/xx/<38 hex>; a loose object being written is still tmp_obj_* and is skipped
|
| 234 |
+
ids = sorted(f"{d.name}{f.name}\n" for d in objects.glob("[0-9a-f][0-9a-f]")
|
| 235 |
+
for f in d.iterdir() if len(f.name) == 38)[:PACK_LOOSE_MAX]
|
| 236 |
+
try:
|
| 237 |
+
if ids: # pack.threads=2: leaves the world's other git work some cores
|
| 238 |
+
self.git("-c", "pack.threads=2", "pack-objects", "-q", str(objects / "pack" / "pack"),
|
| 239 |
+
data="".join(ids).encode(), timeout=1800, group=True)
|
| 240 |
+
self.git("prune-packed", "-q", timeout=1800, group=True)
|
| 241 |
+
# one index over all packs: lookups don't scan each
|
| 242 |
+
self.git("multi-pack-index", "write", timeout=1800, group=True)
|
| 243 |
+
finally:
|
| 244 |
+
info["pack_loose_s"] = time.monotonic() - start
|
| 245 |
+
info["packs"] = len(list((objects / "pack").glob("pack-*.pack")))
|
| 246 |
+
info["loose_after"] = self.loose() # what the next passes still pack
|
| 247 |
+
|
| 248 |
+
def loose(self):
|
| 249 |
+
"""Loose objects in the repository (git count-objects)."""
|
| 250 |
+
return int(re.search(r"^count: (\d+)", self.git("count-objects", "-v"), re.MULTILINE)[1])
|
| 251 |
+
|
| 252 |
+
def sha(self, ref="main"):
|
| 253 |
+
if ref.startswith("pr:") and ref[3:].isdigit():
|
| 254 |
+
ref = f"refs/pr/{int(ref[3:])}"
|
| 255 |
+
if ref != "main" and not ref.startswith("refs/pr/"):
|
| 256 |
+
raise ToolError("ref must be main or pr:<number>")
|
| 257 |
+
return self.git("rev-parse", "--verify", f"{ref}^{{commit}}")
|
| 258 |
+
|
| 259 |
+
def ancestor(self, sha, target):
|
| 260 |
+
if len(sha) != 40 or any(c not in "0123456789abcdef" for c in sha):
|
| 261 |
+
return False
|
| 262 |
+
p = subprocess.run(["git", "-C", str(self.root), "merge-base", "--is-ancestor", sha, target],
|
| 263 |
+
env=self.env, capture_output=True, timeout=10, check=False)
|
| 264 |
+
return p.returncode == 0
|
| 265 |
+
|
| 266 |
+
def merged_by(self, head, target="main"):
|
| 267 |
+
"""The first commit on target's first-parent chain that contains head."""
|
| 268 |
+
out = self.git("rev-list", "--first-parent", "--ancestry-path", "--reverse",
|
| 269 |
+
f"{head}..{target}")
|
| 270 |
+
return out.split("\n", 1)[0] or self.git("rev-parse", head) # fast-forward: head is main
|
| 271 |
+
|
| 272 |
+
def checkout(self, ref, dest):
|
| 273 |
+
# --shared borrows the object store instead of copying it; objects are never pruned
|
| 274 |
+
# while reachable, and new commits are fetched back into the bare repository.
|
| 275 |
+
self.git("clone", "-q", "--shared", "--no-checkout", str(self.root), str(dest), at=dest.parent)
|
| 276 |
+
self.git("checkout", "-q", "--detach", ref, at=dest)
|
| 277 |
+
|
| 278 |
+
def staged(self, tree):
|
| 279 |
+
"""Stage the tree (honouring .gitignore) and list added/changed paths."""
|
| 280 |
+
self.git("add", "-A", at=tree)
|
| 281 |
+
names = self.git("diff", "--cached", "--name-only", "-z", "--no-renames",
|
| 282 |
+
"--diff-filter=AM", "HEAD", at=tree)
|
| 283 |
+
return [name for name in names.split("\0") if name]
|
| 284 |
+
|
| 285 |
+
def changed(self, base, head):
|
| 286 |
+
"""Paths added or modified between two commits."""
|
| 287 |
+
out = self.git("diff", "--name-only", "-z", "--no-renames", "--diff-filter=AM", base, head)
|
| 288 |
+
return [name for name in out.split("\0") if name]
|
| 289 |
+
|
| 290 |
+
def patch_id(self, base, head):
|
| 291 |
+
"""Stable patch-id of the diff base..head (None for an empty diff), cached per pair."""
|
| 292 |
+
return self._patch_id((base, head), ["diff", base, head])
|
| 293 |
+
|
| 294 |
+
def patch_id0(self, base, head):
|
| 295 |
+
"""Stable patch-id of the context-free diff base..head (None for an empty diff).
|
| 296 |
+
|
| 297 |
+
Without context lines, a change of main next to the PR's hunks leaves it unchanged,
|
| 298 |
+
so it identifies the PR's own change across a clean rebase. Cached per pair."""
|
| 299 |
+
return self._patch_id((base, head, 0), ["diff", "-U0", "--no-color", base, head])
|
| 300 |
+
|
| 301 |
+
def _patch_id(self, key, args):
|
| 302 |
+
if key not in self.patch_ids:
|
| 303 |
+
diff = subprocess.run(["git", "-C", str(self.root), *args],
|
| 304 |
+
capture_output=True, env=self.env, timeout=120, check=False)
|
| 305 |
+
if diff.returncode:
|
| 306 |
+
log.warning("git diff failed: exit code %s", diff.returncode)
|
| 307 |
+
raise ToolError("repository operation failed; refresh your clone and retry", "git_error")
|
| 308 |
+
out = subprocess.run(["git", "-C", str(self.root), "patch-id", "--stable"], input=diff.stdout,
|
| 309 |
+
capture_output=True, env=self.env, timeout=120, check=False)
|
| 310 |
+
if out.returncode:
|
| 311 |
+
log.warning("git patch-id failed: exit code %s", out.returncode)
|
| 312 |
+
raise ToolError("repository operation failed; refresh your clone and retry", "git_error")
|
| 313 |
+
if len(self.patch_ids) >= 10000:
|
| 314 |
+
self.patch_ids.clear()
|
| 315 |
+
self.patch_ids[key] = out.stdout.decode().split()[0] if out.stdout.strip() else None
|
| 316 |
+
return self.patch_ids[key]
|
| 317 |
+
|
| 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}@flock.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)
|
| 325 |
+
if onto and onto != parent:
|
| 326 |
+
self.git("checkout", "-q", "--detach", onto, at=tree)
|
| 327 |
+
attributes = ("-c", f"core.attributesFile={self.attributes}") if union and self.attributes else ()
|
| 328 |
+
try:
|
| 329 |
+
self.git(*who, *attributes, "cherry-pick", "--allow-empty", "--keep-redundant-commits", sha,
|
| 330 |
+
at=tree)
|
| 331 |
+
except ToolError:
|
| 332 |
+
unmerged = subprocess.run(["git", "-C", str(tree), "diff", "--name-only", "-z",
|
| 333 |
+
"--diff-filter=U"], env=self.env, capture_output=True,
|
| 334 |
+
timeout=60, check=False).stdout.decode(errors="replace")
|
| 335 |
+
subprocess.run(["git", "-C", str(tree), "cherry-pick", "--abort"], env=self.env,
|
| 336 |
+
capture_output=True, timeout=60, check=False)
|
| 337 |
+
raise _stale_base(parent, onto, unmerged.split("\0")) from None
|
| 338 |
+
sha = self.git("rev-parse", "HEAD", at=tree)
|
| 339 |
+
self.git("fetch", "--no-write-fetch-head", str(tree), sha)
|
| 340 |
+
return sha
|
| 341 |
+
|
| 342 |
+
def precheck(self, base, head, onto):
|
| 343 |
+
"""Raise commit(union=True)'s stale_base error when replaying base..head onto `onto`
|
| 344 |
+
conflicts, found by git merge-tree in the bare repository (no checkout, well under a
|
| 345 |
+
second). Silent when it cannot tell the same answer: another merge base, a
|
| 346 |
+
.gitattributes anywhere in either tree (the replay's checkout would honour it), a git
|
| 347 |
+
older than 2.38 (no --write-tree), or any git error or timeout."""
|
| 348 |
+
try:
|
| 349 |
+
if (self.git("merge-base", "--all", onto, head) != base
|
| 350 |
+
or any(name.rsplit("/", 1)[-1] == ".gitattributes" for sha in (onto, head)
|
| 351 |
+
for name in self.git("ls-tree", "-r", "--name-only", sha).splitlines())):
|
| 352 |
+
return
|
| 353 |
+
attributes = ("-c", f"core.attributesFile={self.attributes}") if self.attributes else ()
|
| 354 |
+
out = subprocess.run(["git", "-C", str(self.root), *attributes, "merge-tree", "--write-tree",
|
| 355 |
+
"--name-only", "-z", "--no-messages", onto, head],
|
| 356 |
+
env=self.env, capture_output=True, timeout=60, check=False)
|
| 357 |
+
except (ToolError, subprocess.TimeoutExpired):
|
| 358 |
+
return
|
| 359 |
+
if out.returncode == 1: # 1: conflicts (tree, then the conflicted paths); 0: clean
|
| 360 |
+
raise _stale_base(base, onto, out.stdout.decode(errors="replace").split("\0")[1:])
|
| 361 |
+
|
| 362 |
+
def push(self, sha, ref, expected=None, force=False):
|
| 363 |
+
"""Push sha to ref; expected replaces only that head; force overwrites a ref the
|
| 364 |
+
world owns outright (a PR it created and nobody else writes)."""
|
| 365 |
+
options = [f"--force-with-lease={ref}:{expected}"] if expected else []
|
| 366 |
+
self.git("push", *options, "origin", f"{'+' if force and not expected else ''}{sha}:{ref}")
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def _stale_base(parent, onto, files):
|
| 370 |
+
error = ToolError(f"your branch is based on {parent}, main is {onto}, and your changes "
|
| 371 |
+
"conflict with main: pull, rebase onto origin/main, then open again", "stale_base")
|
| 372 |
+
error.files = list(dict.fromkeys(name for name in files if name)) # the conflicting paths
|
| 373 |
+
return error
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
FINAL_CODES = {"closed": "pr_closed", "merged": "pr_merged"}
|
| 377 |
+
_FINAL_WORDS = re.compile(r"\b(merged|closed)\b")
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _final_state(exc):
|
| 381 |
+
""""closed" or "merged" when an HTTP 400 says the PR is already closed or merged (matched on
|
| 382 |
+
the x-error-message header, else the response text; neither is ever logged), else None."""
|
| 383 |
+
response = getattr(exc, "response", None)
|
| 384 |
+
if getattr(response, "status_code", None) != 400:
|
| 385 |
+
return None
|
| 386 |
+
try:
|
| 387 |
+
text = str(response.headers.get("x-error-message") or "") or str(response.text or "")
|
| 388 |
+
except Exception: # noqa: BLE001 - an unreadable body is just "unknown"
|
| 389 |
+
return None
|
| 390 |
+
found = _FINAL_WORDS.search(text[:2000].lower())
|
| 391 |
+
return found.group(1) if found else None
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class Hub:
|
| 395 |
+
def __init__(self, repo_id):
|
| 396 |
+
self.repo_id = repo_id
|
| 397 |
+
token = os.environ.get("HF_TOKEN")
|
| 398 |
+
if not token:
|
| 399 |
+
raise ToolError("HF_TOKEN is required for the bucket and dataset", "configuration")
|
| 400 |
+
self.api = HfApi(token=token)
|
| 401 |
+
self.refs_ttl = float(os.environ.get("PYBOT_HUB_REFS_TTL_S", "5"))
|
| 402 |
+
self.refs_lock = threading.Lock() # one refresh at a time; waiters reuse its result
|
| 403 |
+
self.refs_cache, self.refs_at = None, 0.0
|
| 404 |
+
|
| 405 |
+
def request(self, method, **kwargs):
|
| 406 |
+
# Retry 429 only (only merges call this under the world's state lock); other
|
| 407 |
+
# failures are surfaced without exception bodies, which may include secrets.
|
| 408 |
+
for attempt in range(5):
|
| 409 |
+
try:
|
| 410 |
+
return getattr(self.api, method)(self.repo_id, repo_type="dataset", **kwargs)
|
| 411 |
+
except HfHubHTTPError as exc:
|
| 412 |
+
if exc.response.status_code != 429 or attempt == 4:
|
| 413 |
+
_log_hub_failure(method, self.repo_id, exc)
|
| 414 |
+
final = _final_state(exc)
|
| 415 |
+
if final and isinstance(kwargs.get("discussion_num"), int):
|
| 416 |
+
num = kwargs["discussion_num"]
|
| 417 |
+
raise ToolError(f"PR #{num} is already {final} on the Hub",
|
| 418 |
+
FINAL_CODES[final]) from None
|
| 419 |
+
error = ToolError("Hub request failed; retry later", "hub_error")
|
| 420 |
+
error.status = exc.response.status_code # for the world, never sent to agents
|
| 421 |
+
raise error from None
|
| 422 |
+
delay = exc.response.headers.get("Retry-After", "1")
|
| 423 |
+
try:
|
| 424 |
+
delay = float(delay)
|
| 425 |
+
except ValueError:
|
| 426 |
+
delay = 2 ** attempt
|
| 427 |
+
time.sleep(max(0, min(delay, 30)))
|
| 428 |
+
except Exception as exc:
|
| 429 |
+
# The world reports this as an internal error with an id; name the class here.
|
| 430 |
+
log.warning("Hub call %s failed for %s: %s", method, self.repo_id, type(exc).__name__)
|
| 431 |
+
raise
|
| 432 |
+
|
| 433 |
+
def pr_states(self):
|
| 434 |
+
"""{PR number: status} (open, closed, merged or draft) of the Hub's pull requests, a read
|
| 435 |
+
(no Hub-write slot). Raises on failure."""
|
| 436 |
+
return {d.num: d.status for d in self.request("get_repo_discussions") if d.is_pull_request}
|
| 437 |
+
|
| 438 |
+
def refs(self):
|
| 439 |
+
"""{ref: sha} for the Hub's branches and refs/pr/N, from the refs API (a
|
| 440 |
+
read: no Hub-write slot). Cached for PYBOT_HUB_REFS_TTL_S so a burst costs one
|
| 441 |
+
request; on failure, a WARNING and the stale cache (or {})."""
|
| 442 |
+
with self.refs_lock:
|
| 443 |
+
if self.refs_cache is not None and time.monotonic() - self.refs_at < self.refs_ttl:
|
| 444 |
+
return self.refs_cache
|
| 445 |
+
try:
|
| 446 |
+
found = self.request("list_repo_refs", include_pull_requests=True)
|
| 447 |
+
refs = {r.ref: r.target_commit for r in [*(found.branches or []),
|
| 448 |
+
*(found.pull_requests or [])]
|
| 449 |
+
if r.ref and r.target_commit}
|
| 450 |
+
except Exception as exc: # noqa: BLE001 - request() logged the details, never secrets
|
| 451 |
+
log.warning("Hub refs not listed for %s (%s); using %s", self.repo_id,
|
| 452 |
+
type(exc).__name__, "the stale cache" if self.refs_cache else "nothing")
|
| 453 |
+
return self.refs_cache or {}
|
| 454 |
+
self.refs_cache, self.refs_at = refs, time.monotonic()
|
| 455 |
+
return refs
|
| 456 |
+
|
| 457 |
+
def open(self, title, description):
|
| 458 |
+
pr = self.request("create_pull_request", title=title, description=description)
|
| 459 |
+
return pr.num
|
| 460 |
+
|
| 461 |
+
def ready(self, pr):
|
| 462 |
+
self.request("change_discussion_status", discussion_num=pr, new_status="open")
|
| 463 |
+
|
| 464 |
+
def comment(self, pr, text):
|
| 465 |
+
self.request("comment_discussion", discussion_num=pr, comment=text)
|
| 466 |
+
|
| 467 |
+
def close(self, pr, comment):
|
| 468 |
+
self.request("change_discussion_status", discussion_num=pr, new_status="closed",
|
| 469 |
+
comment=comment)
|
| 470 |
+
|
| 471 |
+
def status(self, pr):
|
| 472 |
+
return self.request("get_discussion_details", discussion_num=pr).status
|
| 473 |
+
|
| 474 |
+
def merge(self, pr, comment):
|
| 475 |
+
self.request("merge_pull_request", discussion_num=pr, comment=comment)
|
world/requirements.txt
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# 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 flock
|
| 40 |
+
fastapi==0.143.1 \
|
| 41 |
+
--hash=sha256:4cafaab64df8534758bf0fce61947f5e27e6cd512798ccbbaad5425086c3b664 \
|
| 42 |
+
--hash=sha256:687beb445804e4c4dbe2a76fd83c25e9b973ac48c267defb86f791e099baecc4
|
| 43 |
+
# via flock
|
| 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 |
+
# flock
|
| 167 |
+
# huggingface-hub
|
| 168 |
+
huggingface-hub==1.33.0 \
|
| 169 |
+
--hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \
|
| 170 |
+
--hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e
|
| 171 |
+
# via flock
|
| 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 flock
|
| 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 |
+
# flock
|
| 307 |
+
# huggingface-hub
|
| 308 |
+
pydantic==2.14.1 \
|
| 309 |
+
--hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \
|
| 310 |
+
--hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26
|
| 311 |
+
# via
|
| 312 |
+
# fastapi
|
| 313 |
+
# flock
|
| 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 |
+
# flock
|
| 462 |
+
# huggingface-hub
|
| 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 |
+
tqdm==4.70.1 \
|
| 477 |
+
--hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \
|
| 478 |
+
--hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4
|
| 479 |
+
# via huggingface-hub
|
| 480 |
+
typer==0.27.3 \
|
| 481 |
+
--hash=sha256:d0396f770a560ab1b0a8504e13b5f254b728cedb05c61cf0359e944e50ce8901 \
|
| 482 |
+
--hash=sha256:e50022f28b82a86313e54501317a1db64bf8f8d036ff8cfe5ca7e47675454aff
|
| 483 |
+
# via flock
|
| 484 |
+
typing-extensions==4.16.0 \
|
| 485 |
+
--hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
|
| 486 |
+
--hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
|
| 487 |
+
# via
|
| 488 |
+
# anyio
|
| 489 |
+
# exceptiongroup
|
| 490 |
+
# fastapi
|
| 491 |
+
# huggingface-hub
|
| 492 |
+
# opentelemetry-api
|
| 493 |
+
# pydantic
|
| 494 |
+
# pydantic-core
|
| 495 |
+
# starlette
|
| 496 |
+
# typing-inspection
|
| 497 |
+
typing-inspection==0.4.4 \
|
| 498 |
+
--hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \
|
| 499 |
+
--hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147
|
| 500 |
+
# via
|
| 501 |
+
# fastapi
|
| 502 |
+
# pydantic
|
| 503 |
+
uvicorn==0.54.0 \
|
| 504 |
+
--hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \
|
| 505 |
+
--hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620
|
| 506 |
+
# via flock
|
| 507 |
+
uvloop==0.23.0 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32' \
|
| 508 |
+
--hash=sha256:090865d8ce7a03986755a3ce711b7dd0d4b44eb14ab74368b717f3fad1180208 \
|
| 509 |
+
--hash=sha256:098a85e1393ef5202767b7e5fb41a32cd8bd81e6ee4af364c179801c4aa3f6d4 \
|
| 510 |
+
--hash=sha256:12634f15e6625f78b3f2922f91404c4d7173487eba11746764153f556e9852dc \
|
| 511 |
+
--hash=sha256:1748321e3c59a14a75404b1ae8d5a8d81c4e201803ea0e14c1b6fd84421024b5 \
|
| 512 |
+
--hash=sha256:19c64108b507cd0bc140e400e3396bacebd9d504956aa7726272bf6de7d9aabb \
|
| 513 |
+
--hash=sha256:1e84575f11873c109cf3962ad0bdf679094466184125f4cadcc41a73febff41f \
|
| 514 |
+
--hash=sha256:28d160f51ab4da3b187063652e643dea6831072add4adc1e6d62afbe73b6be27 \
|
| 515 |
+
--hash=sha256:2dcff2d69be43e6559e5dad2c5a7a2dbfb60e05a77311b6c4b7a4a8123d86c65 \
|
| 516 |
+
--hash=sha256:31e0cf90bc8fd88784f6802cdba968a51fb1aec1cc3feec74d862b2d371d1330 \
|
| 517 |
+
--hash=sha256:378188efbb1524f2219d05246a3e1e5907217848d2882144dff59585f1b81d55 \
|
| 518 |
+
--hash=sha256:4448e9124537620f9c25d004c227bb5104440b58955c19bbd312d910af919a63 \
|
| 519 |
+
--hash=sha256:4a08875543bbd4519faf30497506c9cda8a48470467ffdf967c7313c7a5981a8 \
|
| 520 |
+
--hash=sha256:4b8e207c67d207a8608fec57e116511030af3495dc0109b8c333cf9cb412b16f \
|
| 521 |
+
--hash=sha256:4f1798f56c6f4ba5ac11fa2869e5717926e4470d97a1dd42b4f59219d43b5027 \
|
| 522 |
+
--hash=sha256:5a2bbad3a63007f7e9524d4903ba04fee252557c2acd86f9a3d4f91786695254 \
|
| 523 |
+
--hash=sha256:5bb9be71d9ee39b4359b832f9569518ec9bc08704194034e79e4958e6bc4d46d \
|
| 524 |
+
--hash=sha256:6b3cbc4f96ddfa1fb88a78a69dd851369825b7816d9702eee8c4461505ba172e \
|
| 525 |
+
--hash=sha256:6c7ef4701a96553514b2688e342ef1bf2beae6cfd172d89a76c768292aabf405 \
|
| 526 |
+
--hash=sha256:7337b06a9f9ed9ea3049f04b76f65819db9b19bb832ee598e97b388eadf25e5f \
|
| 527 |
+
--hash=sha256:76345f51367fb1f23e08605c6efb18374f669be5b223658fbab6b17627950507 \
|
| 528 |
+
--hash=sha256:7e35c9bc977760981693e1a7a51493b58ee5a501f9ebb1e547565ee40b6c6208 \
|
| 529 |
+
--hash=sha256:93935ab27b6eaef4c3e5489aebc84284f0644592f7ab516df60ee1b27eaf5eb3 \
|
| 530 |
+
--hash=sha256:a6ac96da66c35bf789bdcde78a88dc7d56b7907d8379648c54adc1c61594575d \
|
| 531 |
+
--hash=sha256:b90397a50ad6332ed3e459c648ac20d182cce24a557354363ad85fc9ea4a17cd \
|
| 532 |
+
--hash=sha256:bbbdb8fcd5e7062e546eec1ac78c28bb21ae7df54c18f8e4b06e15a18d661a49 \
|
| 533 |
+
--hash=sha256:bd6f2f81c7b9da99d301c0b16b82044e76fe887086e42e1590ecf520b94dbdac \
|
| 534 |
+
--hash=sha256:be53e1d5f83de43dc175c87612ecc128d444b38e5c56cb3f807f5a73d6887476 \
|
| 535 |
+
--hash=sha256:c3f23f403a273900d57de6ee5ca0614c650f7f58563065dad1a4744498960e53 \
|
| 536 |
+
--hash=sha256:cbe8d03d4efcccdb7fcedecbaa1e1fa02913eaf3a74cb933634a6bc6d2ea9e2a \
|
| 537 |
+
--hash=sha256:dc61e4f9e37b507069dc7e659ae28bca7adcb04c993c3508214315d12c63f848 \
|
| 538 |
+
--hash=sha256:e095f9e105af76593b4c183bb0bcbdae64bd913a59ec595732dc108b48730ab5 \
|
| 539 |
+
--hash=sha256:e2cba180d6451822763eda8364f342435a873bcfb3849cbd82fdeca248ca65eb \
|
| 540 |
+
--hash=sha256:f1341c6abcee1c31277cfe28d34e46196f2143ec3d755e6efe7452126e1f626d \
|
| 541 |
+
--hash=sha256:f3fbfe82829d8e381426a289b87e59e585278728361db9ce975b88b51f64f410 \
|
| 542 |
+
--hash=sha256:f673d835bdb1a60229cc3609a113fd2c9ce3f4a3c75ad4eaed111180c00199d2 \
|
| 543 |
+
--hash=sha256:f7548ede3ee908cfabc0d068106e303a9a2d811af959cdf6ab85676344cedcda \
|
| 544 |
+
--hash=sha256:fa8ed556fcc87a4091cf61587ef172fa104323dc89ecc085a618ba7ff8629a8f
|
| 545 |
+
# via uvicorn
|
| 546 |
+
watchfiles==1.3.0 \
|
| 547 |
+
--hash=sha256:000b9688fc8133037a8b075c8ebf98f32844ff8964dda61e85c1db547dafc441 \
|
| 548 |
+
--hash=sha256:025b108f2d5cc2799cb941f79380df3e8b22bfb589c218e801767fe78d598c95 \
|
| 549 |
+
--hash=sha256:04c5500faa725d69a99b0f63750e80795e455bb951849e9c98a811b4324997c4 \
|
| 550 |
+
--hash=sha256:1acabde19b67e673274e89a04d613b7fb1f122e2c4b8ec9a581e59c149264b61 \
|
| 551 |
+
--hash=sha256:26b81bc515a0f03f66a69a6fea86eea54c8eca4173c46dd7222569f79dd2f977 \
|
| 552 |
+
--hash=sha256:380f513d26cc2e598266b88d66456e07d67ef4be8f0f435a1154d9c44b43d509 \
|
| 553 |
+
--hash=sha256:4af9c464d410e8c44b58ddf1cbec7c3a02c1cb2c6c80df9c74659ba2fbda0ab5 \
|
| 554 |
+
--hash=sha256:509d9f74d2bec5c1f4cd868ddcfe0c9601f7ea53066dfcb19d8ede742c4de661 \
|
| 555 |
+
--hash=sha256:7398930a2b76b9dc67a4e6b8bfc7baf30946892a86f417a3920c07bdd6febc30 \
|
| 556 |
+
--hash=sha256:7c1125e99f84934a92996ae343501285617373acd66f16b59fd5654b27ad8d80 \
|
| 557 |
+
--hash=sha256:81c989d7267bfb7b676cd32c83bec97914e396870983cbf493e29415037bff5e \
|
| 558 |
+
--hash=sha256:99aee4a07847c06820765fd7b1b49ceac4f3f711ccb7d104655a33231de1c207 \
|
| 559 |
+
--hash=sha256:a5b631db08fd3032db57ec6a92d1777cd60f88803287e4e941a4858c53aab1e0 \
|
| 560 |
+
--hash=sha256:a85e243c87109d9f48a2e0d10d6abdee8768cc114848b32281ec83d7f81d86ef \
|
| 561 |
+
--hash=sha256:b5768b49e426fd5b550b012c866db347cdf15c398ef98dc557b6e6b72fa74cd1 \
|
| 562 |
+
--hash=sha256:bbc1198edfdc90fda0600f825aa94150f428dfcbf8138746f55998e0e660d64c \
|
| 563 |
+
--hash=sha256:be9ef3cd403d756a304a0a08a112163c63da7ec72c8c9d083c98818291ff8f29 \
|
| 564 |
+
--hash=sha256:ca39661934749df580d89f3dde266f2af7c6968f4c21c72ce2dc387d299e6aa7 \
|
| 565 |
+
--hash=sha256:d36c72fcdc08f143d87316a4c4c3b064e340da2c7383d39803950740ed418935 \
|
| 566 |
+
--hash=sha256:d4593392e87669836670f87d62fc754059eaeb0e6157af44060a46558cebe5a3 \
|
| 567 |
+
--hash=sha256:d754e049006e81a9be49dc78ba7802081cee426e968cbc63ee19e164fa2d0e39 \
|
| 568 |
+
--hash=sha256:d978cc1dd7ba44f5590d7de74f7a9c8be7262d9e469c2c0efb8bbfc2574321dc \
|
| 569 |
+
--hash=sha256:da213822ec9082b62cadf3008e07a8c690ec7a3c89f6dc5e55a8cf07b56a1b26 \
|
| 570 |
+
--hash=sha256:dd538c71766c59c732e2c5cedc39323c99c11897b99f93eac773438e54af206a \
|
| 571 |
+
--hash=sha256:e0204f90677b7fb8d3a824279a71a01166bea9f6e53923b8056592d87b33b0b6 \
|
| 572 |
+
--hash=sha256:e5871d4a7f788a9f64fb06f5793389d29d171e5c32d37c3ebfd520b017cc7694 \
|
| 573 |
+
--hash=sha256:eb94e40b9a0db19636b5e3fed0a9803452ecc7381df13b385272abb779ee83ca \
|
| 574 |
+
--hash=sha256:ec3cd4bb181a7b6329134204c2277c7144ab5f62cce9c5335d6f901ee7ce8d6a \
|
| 575 |
+
--hash=sha256:f0c9865240e065a2247f4b5248528ae3d01e0e8ae071462c250c884dc16e3ee3
|
| 576 |
+
# via uvicorn
|
| 577 |
+
websockets==15.0.1 \
|
| 578 |
+
--hash=sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2 \
|
| 579 |
+
--hash=sha256:0af68c55afbd5f07986df82831c7bff04846928ea8d1fd7f30052638788bc9b5 \
|
| 580 |
+
--hash=sha256:0f3c1e2ab208db911594ae5b4f79addeb3501604a165019dd221c0bdcabe4db8 \
|
| 581 |
+
--hash=sha256:229cf1d3ca6c1804400b0a9790dc66528e08a6a1feec0d5040e8b9eb14422375 \
|
| 582 |
+
--hash=sha256:3be571a8b5afed347da347bfcf27ba12b069d9d7f42cb8c7028b5e98bbb12597 \
|
| 583 |
+
--hash=sha256:3c714d2fc58b5ca3e285461a4cc0c9a66bd0e24c5da9911e30158286c9b5be7f \
|
| 584 |
+
--hash=sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3 \
|
| 585 |
+
--hash=sha256:558d023b3df0bffe50a04e710bc87742de35060580a293c2a984299ed83bc4e4 \
|
| 586 |
+
--hash=sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665 \
|
| 587 |
+
--hash=sha256:595b6c3969023ecf9041b2936ac3827e4623bfa3ccf007575f04c5a6aa318c22 \
|
| 588 |
+
--hash=sha256:5a939de6b7b4e18ca683218320fc67ea886038265fd1ed30173f5ce3f8e85675 \
|
| 589 |
+
--hash=sha256:5d54b09eba2bada6011aea5375542a157637b91029687eb4fdb2dab11059c1b4 \
|
| 590 |
+
--hash=sha256:64dee438fed052b52e4f98f76c5790513235efaa1ef7f3f2192c392cd7c91b65 \
|
| 591 |
+
--hash=sha256:746ee8dba912cd6fc889a8147168991d50ed70447bf18bcda7039f7d2e3d9151 \
|
| 592 |
+
--hash=sha256:756c56e867a90fb00177d530dca4b097dd753cde348448a1012ed6c5131f8b7d \
|
| 593 |
+
--hash=sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee \
|
| 594 |
+
--hash=sha256:ba9e56e8ceeeedb2e080147ba85ffcd5cd0711b89576b83784d8605a7df455fa \
|
| 595 |
+
--hash=sha256:c338ffa0520bdb12fbc527265235639fb76e7bc7faafbb93f6ba80d9c06578a9 \
|
| 596 |
+
--hash=sha256:d5f6b181bb38171a8ad1d6aa58a67a6aa9d4b38d0f8c5f496b9e42561dfc62fe \
|
| 597 |
+
--hash=sha256:e09473f095a819042ecb2ab9465aee615bd9c2028e4ef7d933600a8401c79561 \
|
| 598 |
+
--hash=sha256:e8b56bdcdb4505c8078cb6c7157d9811a85790f2f2b3632c7d1462ab5783d215 \
|
| 599 |
+
--hash=sha256:ee443ef070bb3b6ed74514f5efaa37a252af57c90eb33b956d35c8e9c10a1931 \
|
| 600 |
+
--hash=sha256:f7a866fbc1e97b5c617ee4116daaa09b722101d4a3c170c787450ba409f9736f \
|
| 601 |
+
--hash=sha256:fcd5cf9e305d7b8338754470cf69cf81f420459dbae8a3b40cee57417f4614a7
|
| 602 |
+
# via uvicorn
|
world/sandbox.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contract runner: isolated interpreter, bounded resources, no bot I/O except stdio/imports.
|
| 2 |
+
With PYBOT_SANDBOX_URL set, runs go to a sidecar (`python sandbox.py serve`, same image) instead."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import hmac
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import signal
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import tarfile
|
| 15 |
+
import tempfile
|
| 16 |
+
import urllib.error
|
| 17 |
+
import urllib.request
|
| 18 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
from flock.isolation import command as isolate_command
|
| 22 |
+
from flock.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.
|
| 26 |
+
MAX_REQUEST_BYTES, MAX_TREE_BYTES, MAX_TREE_MEMBERS = 64 << 20, 64 << 20, 20000
|
| 27 |
+
log = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
SHIM = r'''
|
| 30 |
+
import sys, os, resource, runpy
|
| 31 |
+
root = os.path.realpath(sys.argv[1])
|
| 32 |
+
resource.setrlimit(resource.RLIMIT_AS, (512 << 20, 512 << 20))
|
| 33 |
+
resource.setrlimit(resource.RLIMIT_CPU, (300, 300))
|
| 34 |
+
resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20))
|
| 35 |
+
resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
|
| 36 |
+
resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
|
| 37 |
+
sys.dont_write_bytecode = True
|
| 38 |
+
sys.path.insert(0, root)
|
| 39 |
+
allowed = set(sys.stdlib_module_names) | {'bot'}
|
| 40 |
+
blocked = {'ctypes', '_ctypes', '_posixsubprocess', 'subprocess', 'socket', '_socket', 'multiprocessing'}
|
| 41 |
+
def audit(event, args):
|
| 42 |
+
if event == 'import':
|
| 43 |
+
name = args[0].split('.')[0]
|
| 44 |
+
if name not in allowed or name in blocked:
|
| 45 |
+
raise PermissionError('only standard-library bot imports are allowed')
|
| 46 |
+
if event == 'open':
|
| 47 |
+
path, mode, flags = args
|
| 48 |
+
if not isinstance(path, (str, bytes, os.PathLike)):
|
| 49 |
+
raise PermissionError('file access is disabled')
|
| 50 |
+
path = os.path.realpath(os.fsdecode(path))
|
| 51 |
+
if flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND):
|
| 52 |
+
raise PermissionError('file writes are disabled')
|
| 53 |
+
roots = (root + os.sep, os.path.realpath(sys.base_prefix) + os.sep)
|
| 54 |
+
if not path.startswith(roots) or not path.endswith(('.py', '.pyc', '.so')):
|
| 55 |
+
raise PermissionError('file access is disabled except module loading')
|
| 56 |
+
if event.startswith(('socket.', 'subprocess.', 'ctypes.', 'os.kill', 'signal.')) or event in {
|
| 57 |
+
'os.system', 'os.exec', 'os.fork', 'os.forkpty', 'os.posix_spawn', 'os.kill', 'os.killpg',
|
| 58 |
+
'os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.chmod', 'os.link',
|
| 59 |
+
'os.symlink', 'os.truncate', 'os.putenv', 'os.unsetenv'}:
|
| 60 |
+
raise PermissionError('bot side effects are disabled')
|
| 61 |
+
import signal, _signal
|
| 62 |
+
# Signals to other processes: os.kill/killpg and signal.pthread_kill raise audit events
|
| 63 |
+
# (blocked above); pidfd_send_signal does not, so remove every sender from the modules.
|
| 64 |
+
for module in (os, sys.modules.get('posix'), signal, _signal):
|
| 65 |
+
for name in ('kill', 'killpg', 'pthread_kill', 'pidfd_send_signal'):
|
| 66 |
+
if module is not None and hasattr(module, name):
|
| 67 |
+
delattr(module, name)
|
| 68 |
+
sys.addaudithook(audit)
|
| 69 |
+
runpy.run_module('bot', run_name='__main__')
|
| 70 |
+
'''
|
| 71 |
+
|
| 72 |
+
# The repository's own tests matching a pattern under tests/ (python -m unittest discover -s
|
| 73 |
+
# tests -p <pattern>, as agents run them). Same limits as the bot; tests may read any file, so
|
| 74 |
+
# its hook keeps only the side-effect blocks (the sidecar has no namespaces to stop them).
|
| 75 |
+
TESTS_SHIM = r'''
|
| 76 |
+
import sys, os, resource, unittest
|
| 77 |
+
root = os.path.realpath(sys.argv[1])
|
| 78 |
+
resource.setrlimit(resource.RLIMIT_AS, (512 << 20, 512 << 20))
|
| 79 |
+
resource.setrlimit(resource.RLIMIT_FSIZE, (1 << 20, 1 << 20))
|
| 80 |
+
resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
|
| 81 |
+
resource.setrlimit(resource.RLIMIT_NPROC, (0, 0))
|
| 82 |
+
sys.dont_write_bytecode = True
|
| 83 |
+
sys.path.insert(0, root)
|
| 84 |
+
blocked = {'ctypes', '_ctypes', '_posixsubprocess', 'subprocess', 'socket', '_socket', 'multiprocessing'}
|
| 85 |
+
def audit(event, args):
|
| 86 |
+
if event == 'import' and args[0].split('.')[0] in blocked:
|
| 87 |
+
raise PermissionError('test imports of ' + args[0] + ' are disabled')
|
| 88 |
+
if event == 'open' and args[2] & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND):
|
| 89 |
+
raise PermissionError('file writes are disabled')
|
| 90 |
+
if event.startswith(('socket.', 'subprocess.', 'ctypes.', 'os.kill', 'signal.')) or event in {
|
| 91 |
+
'os.system', 'os.exec', 'os.fork', 'os.forkpty', 'os.posix_spawn', 'os.kill', 'os.killpg',
|
| 92 |
+
'os.remove', 'os.rename', 'os.mkdir', 'os.rmdir', 'os.chmod', 'os.link',
|
| 93 |
+
'os.symlink', 'os.truncate', 'os.putenv', 'os.unsetenv'}:
|
| 94 |
+
raise PermissionError('test side effects are disabled')
|
| 95 |
+
sys.addaudithook(audit)
|
| 96 |
+
tests = os.path.join(root, 'tests')
|
| 97 |
+
suite = (unittest.defaultTestLoader.discover(tests, pattern=sys.argv[2], top_level_dir=tests)
|
| 98 |
+
if os.path.isdir(tests) else unittest.TestSuite())
|
| 99 |
+
sys.exit(not unittest.TextTestRunner().run(suite).wasSuccessful())
|
| 100 |
+
'''
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def run(root: Path, lines: list[str], timeout: float = 300, isolate: bool = True) -> dict:
|
| 104 |
+
if not lines or len(lines) > 200 or any(not isinstance(x, str) or '\n' in x or '\r' in x
|
| 105 |
+
or len(x) > 16000 for x in lines):
|
| 106 |
+
return {"ok": False, "status": "supply 1–200 single input lines (at most 16000 chars each)"}
|
| 107 |
+
if isolate and (url := os.environ.get("PYBOT_SANDBOX_URL")): # the sidecar: no secrets in its container
|
| 108 |
+
# .py only: all the shim lets a bot open
|
| 109 |
+
return _remote(os.path.expandvars(url), root, {"lines": lines, "timeout": timeout}, "*.py")
|
| 110 |
+
return _local(root, lines, timeout, isolate)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def run_tests(root: Path, pattern: str, timeout: float = 60, isolate: bool = True) -> dict:
|
| 114 |
+
"""Run root's tests/ files matching pattern, isolated like run() (in the sidecar with
|
| 115 |
+
PYBOT_SANDBOX_URL). ok when they pass (or none match); status "timeout" past timeout;
|
| 116 |
+
output: their combined output (1 MiB)."""
|
| 117 |
+
if isolate and (url := os.environ.get("PYBOT_SANDBOX_URL")): # tests read data files: the whole tree
|
| 118 |
+
return _remote(os.path.expandvars(url), root, {"tests": pattern, "timeout": timeout}, "*")
|
| 119 |
+
with tempfile.TemporaryDirectory() as tmp, open(Path(tmp) / "out", "w+b") as out:
|
| 120 |
+
status = _isolated(root, tmp, [TESTS_SHIM, str(root.resolve()), pattern], b"", timeout,
|
| 121 |
+
out, out, isolate)
|
| 122 |
+
out.seek(0)
|
| 123 |
+
return {"ok": status == "ok", "status": status,
|
| 124 |
+
"output": out.read(1 << 20).decode(errors="replace")}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _remote(url: str, root: Path, payload: dict, files: str) -> dict:
|
| 128 |
+
"""POST payload and the tree's files matching the glob to the sidecar; its reply."""
|
| 129 |
+
buf, sent = io.BytesIO(), 0
|
| 130 |
+
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
|
| 131 |
+
for f in sorted(root.rglob(files)):
|
| 132 |
+
# regular files only: the sidecar refuses links (and never gets a link's target)
|
| 133 |
+
if ".git" not in f.relative_to(root).parts and f.is_file() and not f.is_symlink():
|
| 134 |
+
tar.add(f, f.relative_to(root).as_posix())
|
| 135 |
+
sent += 1
|
| 136 |
+
body = json.dumps({**payload, "tree": base64.b64encode(buf.getvalue()).decode()}).encode()
|
| 137 |
+
req = urllib.request.Request(f"{url.rstrip('/')}/run", body, method="POST", headers={
|
| 138 |
+
"Content-Type": "application/json",
|
| 139 |
+
"X-Sandbox-Token": os.environ.get("PYBOT_SANDBOX_TOKEN", "")})
|
| 140 |
+
try:
|
| 141 |
+
with urllib.request.urlopen(req, timeout=payload["timeout"] + 30) as r:
|
| 142 |
+
return json.load(r)
|
| 143 |
+
except (OSError, ValueError) as e: # never "your bot failed" when the runner is down
|
| 144 |
+
if isinstance(e, urllib.error.HTTPError): # it answered and refused: say why in the log
|
| 145 |
+
log.warning("sandbox sidecar refused a %s run: HTTP %s (%d files, %d bytes sent)",
|
| 146 |
+
"tests" if "tests" in payload else "bot", e.code,
|
| 147 |
+
sent, len(body))
|
| 148 |
+
raise ToolError(f"bot runner unavailable ({type(e).__name__}); retry later", "busy",
|
| 149 |
+
retry_after_s=30) from None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _isolated(root: Path, tmp: str, args: list[str], data: bytes, timeout: float, out, err,
|
| 153 |
+
isolate: bool = True) -> str:
|
| 154 |
+
"""Run `python -I -S -c *args` (isolated: root read-only), data on stdin; the status."""
|
| 155 |
+
argv = [sys.executable, "-I", "-S", "-c", *args]
|
| 156 |
+
if isolate:
|
| 157 |
+
argv = isolate_command(argv, Path(tmp) / "root", cwd=root.resolve(),
|
| 158 |
+
readonly=[root.resolve()], python_only=True)
|
| 159 |
+
proc = subprocess.Popen(argv, cwd=tmp, env={}, stdin=subprocess.PIPE, stdout=out, stderr=err,
|
| 160 |
+
start_new_session=True)
|
| 161 |
+
try:
|
| 162 |
+
proc.communicate(data, timeout=timeout)
|
| 163 |
+
return "ok" if proc.returncode == 0 else f"exit {proc.returncode}"
|
| 164 |
+
except subprocess.TimeoutExpired:
|
| 165 |
+
os.killpg(proc.pid, signal.SIGKILL)
|
| 166 |
+
proc.wait()
|
| 167 |
+
return "timeout"
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _local(root: Path, lines: list[str], timeout: float, isolate: bool = True) -> dict:
|
| 171 |
+
with (tempfile.TemporaryDirectory() as tmp,
|
| 172 |
+
open(Path(tmp) / "out", "w+b") as out,
|
| 173 |
+
open(Path(tmp) / "err", "w+b") as err):
|
| 174 |
+
status = _isolated(root, tmp, [SHIM, str(root.resolve())],
|
| 175 |
+
('\n'.join(lines) + '\n').encode(), timeout, out, err, isolate)
|
| 176 |
+
out.seek(0)
|
| 177 |
+
err.seek(0)
|
| 178 |
+
replies = out.read(1 << 20).decode(errors="replace").splitlines()
|
| 179 |
+
ok = status == "ok" and len(replies) == len(lines) and all(x.strip() for x in replies)
|
| 180 |
+
return {"ok": ok, "status": status, "replies": replies,
|
| 181 |
+
"stderr": err.read(4096).decode(errors="replace"), "timeout_s": timeout}
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class _Handler(BaseHTTPRequestHandler):
|
| 185 |
+
"""POST /run {lines, timeout, tree: base64 tar.gz} -> run()'s dict, or {tests: pattern,
|
| 186 |
+
timeout, tree} -> run_tests()'s. The sidecar only: `unshare` is blocked in HF Jobs
|
| 187 |
+
containers, so the job boundary (no secrets) replaces it."""
|
| 188 |
+
|
| 189 |
+
def do_POST(self):
|
| 190 |
+
token = os.environ.get("PYBOT_SANDBOX_TOKEN", "")
|
| 191 |
+
n = int(self.headers.get("Content-Length") or 0)
|
| 192 |
+
if self.path != "/run" or not token or not hmac.compare_digest(
|
| 193 |
+
self.headers.get("X-Sandbox-Token", ""), token) or not 0 < n <= MAX_REQUEST_BYTES:
|
| 194 |
+
return self._send(403, {"ok": False, "status": "refused"})
|
| 195 |
+
try:
|
| 196 |
+
req = json.loads(self.rfile.read(n))
|
| 197 |
+
timeout = min(300, float(req.get("timeout", 300))) # 300 first: an int, as local
|
| 198 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 199 |
+
root = Path(tmp) / "tree"
|
| 200 |
+
with tarfile.open(fileobj=io.BytesIO(base64.b64decode(req["tree"])), mode="r:gz") as t:
|
| 201 |
+
count = total = 0
|
| 202 |
+
for m in t: # before extracting: a small .tar.gz can expand hugely
|
| 203 |
+
count, total = count + 1, total + m.size
|
| 204 |
+
if count > MAX_TREE_MEMBERS or total > MAX_TREE_BYTES or not (m.isfile() or m.isdir()):
|
| 205 |
+
raise ValueError("tree: too many or too large members, or not files and dirs")
|
| 206 |
+
t.extractall(root, filter="data") # no absolute paths, links or ../
|
| 207 |
+
if "tests" in req:
|
| 208 |
+
if not isinstance(req["tests"], str):
|
| 209 |
+
raise ValueError("tests")
|
| 210 |
+
out = run_tests(root, req["tests"], timeout, isolate=False)
|
| 211 |
+
elif not isinstance(req["lines"], list):
|
| 212 |
+
raise ValueError("lines") # run() checks each line
|
| 213 |
+
else:
|
| 214 |
+
out = run(root, req["lines"], timeout, isolate=False)
|
| 215 |
+
except (KeyError, ValueError, TypeError, tarfile.TarError, OSError) as e:
|
| 216 |
+
return self._send(400, {"ok": False, "status": f"bad request: {type(e).__name__}"})
|
| 217 |
+
self._send(200, out)
|
| 218 |
+
|
| 219 |
+
def _send(self, code, obj):
|
| 220 |
+
data = json.dumps(obj).encode()
|
| 221 |
+
self.send_response(code)
|
| 222 |
+
self.send_header("Content-Type", "application/json")
|
| 223 |
+
self.send_header("Content-Length", str(len(data)))
|
| 224 |
+
self.end_headers()
|
| 225 |
+
self.wfile.write(data)
|
| 226 |
+
|
| 227 |
+
|
| 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 flock.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
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The bot sandbox sidecar on localhost: python world/scripts/check-sidecar.py
|
| 2 |
+
|
| 3 |
+
Starts `sandbox.py serve` as a 2nd process and checks: its result equals the local path's (the seed,
|
| 4 |
+
the merge-check lines); `import socket` in a bot is blocked; merge_pr's shared tests (run_tests,
|
| 5 |
+
the seed's test_deck.py) pass there as locally, fail on a duplicate deck id (the data files went
|
| 6 |
+
along), and a test cannot import socket or write a file; a tree of 3,000 more files (a long run's
|
| 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
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
import socket
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
import tarfile
|
| 22 |
+
import tempfile
|
| 23 |
+
import time
|
| 24 |
+
import urllib.error
|
| 25 |
+
import urllib.request
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
WORLD = SRC = Path(__file__).resolve().parent.parent # world/
|
| 29 |
+
sys.path[:0] = [str(WORLD / "src"), str(SRC)]
|
| 30 |
+
LINES = ["Hello", "My name is Sam", "", "What is my name?", "Bye"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def post_tar(port, members):
|
| 34 |
+
"""POST /run with a hand-made tar: members are (TarInfo, data or None)."""
|
| 35 |
+
buf = io.BytesIO()
|
| 36 |
+
with tarfile.open(fileobj=buf, mode="w:gz") as t:
|
| 37 |
+
for info, data in members:
|
| 38 |
+
t.addfile(info, None if data is None else io.BytesIO(data))
|
| 39 |
+
req = urllib.request.Request(f"http://127.0.0.1:{port}/run", json.dumps(
|
| 40 |
+
{"lines": ["hi"], "tree": base64.b64encode(buf.getvalue()).decode()}).encode(),
|
| 41 |
+
headers={"X-Sandbox-Token": "tok", "Content-Type": "application/json"})
|
| 42 |
+
try:
|
| 43 |
+
with urllib.request.urlopen(req, timeout=60) as r:
|
| 44 |
+
return r.status, json.load(r)
|
| 45 |
+
except urllib.error.HTTPError as e:
|
| 46 |
+
return e.code, json.loads(e.read())
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def member(name, size=4, kind=tarfile.REGTYPE, link=""):
|
| 50 |
+
info = tarfile.TarInfo(name)
|
| 51 |
+
info.size, info.type, info.linkname = size, kind, link
|
| 52 |
+
return info, bytes(size) if kind == tarfile.REGTYPE else None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def main():
|
| 56 |
+
import sandbox
|
| 57 |
+
from flock.world import ToolError
|
| 58 |
+
|
| 59 |
+
with socket.socket() as s:
|
| 60 |
+
s.bind(("127.0.0.1", 0))
|
| 61 |
+
port = s.getsockname()[1]
|
| 62 |
+
srv = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], stderr=subprocess.DEVNULL,
|
| 63 |
+
env={"PYTHONPATH": str(WORLD / "src"), "PYBOT_SANDBOX_TOKEN": "tok", "PORT": str(port)})
|
| 64 |
+
try:
|
| 65 |
+
for _ in range(300):
|
| 66 |
+
try:
|
| 67 |
+
socket.create_connection(("127.0.0.1", port), timeout=1).close()
|
| 68 |
+
break
|
| 69 |
+
except OSError:
|
| 70 |
+
assert srv.poll() is None, "sandbox.py serve exited"
|
| 71 |
+
time.sleep(0.1)
|
| 72 |
+
tmp = Path(tempfile.mkdtemp(prefix="check-sidecar-"))
|
| 73 |
+
tree = tmp / "tree"
|
| 74 |
+
shutil.copytree(SRC / "seed", tree)
|
| 75 |
+
local = sandbox.run(tree, LINES, isolate=False)
|
| 76 |
+
os.environ.update(PYBOT_SANDBOX_URL=f"http://${{SB_HOST}}:{port}", SB_HOST="127.0.0.1",
|
| 77 |
+
PYBOT_SANDBOX_TOKEN="tok")
|
| 78 |
+
remote = sandbox.run(tree, LINES)
|
| 79 |
+
assert remote == local and remote["ok"], (remote, local)
|
| 80 |
+
print("ok merge-check lines via the sidecar == local:", remote["replies"][:2])
|
| 81 |
+
|
| 82 |
+
bad = tmp / "bad"
|
| 83 |
+
shutil.copytree(tree, bad)
|
| 84 |
+
(bad / "bot/modules/greeting.py").write_text(
|
| 85 |
+
"PRIORITY = -1000\ndef respond(text, memory):\n try:\n import socket\n"
|
| 86 |
+
" return 'NET'\n except PermissionError:\n return 'BLOCKED'\n")
|
| 87 |
+
r1, r2 = sandbox.run(bad, LINES), sandbox.run(bad, LINES, isolate=False)
|
| 88 |
+
assert r1 == r2 and set(r1["replies"]) == {"BLOCKED"}, (r1, r2)
|
| 89 |
+
print("ok import socket in a bot: blocked, as locally")
|
| 90 |
+
|
| 91 |
+
r1, r2 = sandbox.run_tests(tree, "test_deck.py"), sandbox.run_tests(tree, "test_deck.py", isolate=False)
|
| 92 |
+
assert r1["ok"] and r2["ok"] and "Ran 2 tests" in r1["output"], (r1, r2)
|
| 93 |
+
print("ok shared tests (test_deck.py) via the sidecar: pass, as locally")
|
| 94 |
+
dup = tmp / "dup"
|
| 95 |
+
shutil.copytree(tree, dup)
|
| 96 |
+
deck = dup / "deck" / "single.jsonl"
|
| 97 |
+
deck.write_text(deck.read_text() + deck.read_text().splitlines()[0] + "\n")
|
| 98 |
+
r1, r2 = sandbox.run_tests(dup, "test_deck.py"), sandbox.run_tests(dup, "test_deck.py", isolate=False)
|
| 99 |
+
assert (r1["status"], r2["status"]) == ("exit 1", "exit 1") and "FAIL:" in r1["output"], (r1, r2)
|
| 100 |
+
print("ok a duplicate deck id fails them via the sidecar too (the data files went along)")
|
| 101 |
+
(dup / "tests" / "test_side_effects.py").write_text(
|
| 102 |
+
"import unittest\nclass T(unittest.TestCase):\n def test_blocked(self):\n"
|
| 103 |
+
" with self.assertRaises(PermissionError):\n import socket\n"
|
| 104 |
+
" with self.assertRaises(PermissionError):\n open('written', 'w')\n")
|
| 105 |
+
r1 = sandbox.run_tests(dup, "test_side_effects.py")
|
| 106 |
+
assert r1["ok"] and "Ran 1 test" in r1["output"], r1
|
| 107 |
+
print("ok a test's import socket and file write: blocked in the sidecar")
|
| 108 |
+
|
| 109 |
+
big = tmp / "big" # main after a long run: thousands of files, half of them *.py
|
| 110 |
+
shutil.copytree(tree, big)
|
| 111 |
+
for i in range(1500):
|
| 112 |
+
(big / "tools" / "gen").mkdir(parents=True, exist_ok=True)
|
| 113 |
+
(big / "tools" / "gen" / f"m{i}.py").write_text(f"X = {i}\n" * 20)
|
| 114 |
+
(big / "notes").mkdir(exist_ok=True)
|
| 115 |
+
(big / "notes" / f"n{i}.txt").write_text(f"note {i}\n" * 20)
|
| 116 |
+
files = sum(1 for f in big.rglob("*") if f.is_file())
|
| 117 |
+
r1, r2 = sandbox.run_tests(big, "test_deck.py"), sandbox.run(big, LINES)
|
| 118 |
+
assert r1["ok"] and r2 == local, (r1, r2)
|
| 119 |
+
print(f"ok a tree of {files} files: shared tests and the bot run via the sidecar")
|
| 120 |
+
|
| 121 |
+
os.environ["PYBOT_SANDBOX_TOKEN"] = "nope"
|
| 122 |
+
logged = []
|
| 123 |
+
handler = logging.Handler()
|
| 124 |
+
handler.emit = lambda record: logged.append(record.getMessage())
|
| 125 |
+
sandbox.log.addHandler(handler)
|
| 126 |
+
try:
|
| 127 |
+
sandbox.run(tree, LINES)
|
| 128 |
+
raise AssertionError("a bad token was accepted")
|
| 129 |
+
except ToolError as e:
|
| 130 |
+
assert e.code == "busy", e.code
|
| 131 |
+
sandbox.log.removeHandler(handler)
|
| 132 |
+
assert len(logged) == 1 and "HTTP 403" in logged[0], logged
|
| 133 |
+
os.environ["PYBOT_SANDBOX_TOKEN"] = "tok"
|
| 134 |
+
print(f"ok bad token -> busy, logged: {logged[0]}")
|
| 135 |
+
|
| 136 |
+
refused = {
|
| 137 |
+
"../ in a path": [member("../escape.py")],
|
| 138 |
+
"a symlink": [member("bot/x.py", 0, tarfile.SYMTYPE, "/etc/passwd")],
|
| 139 |
+
f"{sandbox.MAX_TREE_MEMBERS + 1} members": [member(f"m{i}.py") for i in range(sandbox.MAX_TREE_MEMBERS + 1)],
|
| 140 |
+
f"{(sandbox.MAX_TREE_BYTES >> 20) + 1} MB of zeros": [member("big.py", sandbox.MAX_TREE_BYTES + (1 << 20))],
|
| 141 |
+
}
|
| 142 |
+
for what, members in refused.items():
|
| 143 |
+
status, body = post_tar(port, members)
|
| 144 |
+
assert status == 400, (what, status, body)
|
| 145 |
+
print(f"ok tar with {what} -> 400 {body['status']}")
|
| 146 |
+
status, body = post_tar(port, [member(f"m{i}.py") for i in range(10)])
|
| 147 |
+
assert status == 200, (status, body) # within the caps: extracted and run (no bot: a failed run)
|
| 148 |
+
|
| 149 |
+
slow = tmp / "slow"
|
| 150 |
+
shutil.copytree(tree, slow)
|
| 151 |
+
(slow / "bot/modules/greeting.py").write_text("while True: pass\n")
|
| 152 |
+
t0 = time.time()
|
| 153 |
+
r = sandbox.run(slow, ["hi"], timeout=2)
|
| 154 |
+
assert r["status"] == "timeout" and time.time() - t0 < 10, r
|
| 155 |
+
print(f"ok timeout after {time.time() - t0:.1f} s")
|
| 156 |
+
|
| 157 |
+
os.environ.update(SB_HOST="127.0.0.2", PYBOT_SANDBOX_URL="http://${SB_HOST}:1")
|
| 158 |
+
try:
|
| 159 |
+
sandbox.run(tree, LINES)
|
| 160 |
+
raise AssertionError("an unreachable sidecar did not raise")
|
| 161 |
+
except ToolError as e:
|
| 162 |
+
assert e.code == "busy", e.code
|
| 163 |
+
print("ok unreachable sidecar -> busy")
|
| 164 |
+
shutil.rmtree(tmp)
|
| 165 |
+
print("PASS")
|
| 166 |
+
finally:
|
| 167 |
+
srv.terminate()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|
world/scripts/smoke-local.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Container-free smoke of the world: python world/scripts/smoke-local.py [--sidecar]
|
| 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 and git.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import socket
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
import tempfile
|
| 17 |
+
import threading
|
| 18 |
+
import time
|
| 19 |
+
import urllib.error
|
| 20 |
+
import urllib.request
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
WORLD = SRC = Path(__file__).resolve().parent.parent # world/
|
| 24 |
+
sys.path[:0] = [str(WORLD / "src"), 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):
|
| 31 |
+
return subprocess.run(["git", "-C", str(path), *args], check=True, capture_output=True,
|
| 32 |
+
text=True).stdout.strip()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class LocalHub: # tests/test_pybot.py's fake: PRs are refs/pr/N in the bare remote
|
| 36 |
+
def __init__(self, remote):
|
| 37 |
+
self.remote, self.n = remote, 0
|
| 38 |
+
|
| 39 |
+
def open(self, title, description):
|
| 40 |
+
self.n += 1
|
| 41 |
+
git(self.remote, "update-ref", f"refs/pr/{self.n}", "main")
|
| 42 |
+
return self.n
|
| 43 |
+
|
| 44 |
+
def ready(self, pr): pass
|
| 45 |
+
def comment(self, pr, text): pass
|
| 46 |
+
def close(self, pr, comment): pass
|
| 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-Flock-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())
|
| 58 |
+
except urllib.error.HTTPError as e:
|
| 59 |
+
return e.code, json.loads(e.read() or b"null")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def free_port():
|
| 63 |
+
with socket.socket() as s:
|
| 64 |
+
s.bind(("127.0.0.1", 0))
|
| 65 |
+
return s.getsockname()[1]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def start_sidecar(tmp):
|
| 69 |
+
"""sandbox.py serve with nothing but its token, PORT and the library path; returns (proc, log)."""
|
| 70 |
+
port, log = free_port(), tmp / "sidecar.log"
|
| 71 |
+
proc = subprocess.Popen([sys.executable, str(SRC / "sandbox.py"), "serve"], cwd=SRC,
|
| 72 |
+
stderr=log.open("wb"), env={"PYBOT_SANDBOX_TOKEN": "sidecar-token",
|
| 73 |
+
"PORT": str(port), "PYTHONPATH": str(WORLD / "src")})
|
| 74 |
+
for _ in range(100):
|
| 75 |
+
try:
|
| 76 |
+
socket.create_connection(("127.0.0.1", port), timeout=1).close()
|
| 77 |
+
break
|
| 78 |
+
except OSError:
|
| 79 |
+
assert proc.poll() is None, log.read_text()
|
| 80 |
+
time.sleep(0.1)
|
| 81 |
+
os.environ.update(PYBOT_SANDBOX_URL=f"http://127.0.0.1:{port}", PYBOT_SANDBOX_TOKEN="sidecar-token")
|
| 82 |
+
print(f"ok sidecar: sandbox.py serve on 127.0.0.1:{port}")
|
| 83 |
+
return proc, log
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main(sidecar=False):
|
| 87 |
+
import uvicorn
|
| 88 |
+
from pybot import PybotWorld
|
| 89 |
+
from repository import Repository
|
| 90 |
+
|
| 91 |
+
from flock.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
|
| 95 |
+
seed = tmp / "seed"
|
| 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@flock.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))
|
| 103 |
+
repo.hub = LocalHub(remote)
|
| 104 |
+
world = PybotWorld(tmp / "ws", repo)
|
| 105 |
+
|
| 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"}):
|
| 115 |
+
break
|
| 116 |
+
except OSError:
|
| 117 |
+
pass
|
| 118 |
+
time.sleep(0.1)
|
| 119 |
+
else:
|
| 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 flock.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)
|
| 144 |
+
served = '"POST /run HTTP/1.1" 200' in sidecar_log.read_text()
|
| 145 |
+
assert ran and served, f"run_bot did not succeed through the sidecar: {sidecar_log.read_text()[-600:]}"
|
| 146 |
+
print("ok run_bot went through the sidecar (its log: POST /run 200)")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
main("--sidecar" in sys.argv[1:])
|
world/seed/.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.venv/
|
world/seed/AGENTS.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python chatbot
|
| 2 |
+
|
| 3 |
+
Read README.md, STYLE.md and CONTRIBUTING.md before editing or submitting work. Keep the
|
| 4 |
+
seed's runtime and input/output interface fixed; put topic and feature logic in bot/modules/.
|
| 5 |
+
Compare every change with main using tools/compare.py and judge it by STYLE.md. Submit through
|
| 6 |
+
the world's PR tools; another agent must approve the latest change before it can merge.
|
| 7 |
+
Continue working until the system tells you to stop.
|
world/seed/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contributing
|
| 2 |
+
|
| 3 |
+
## Choose work
|
| 4 |
+
|
| 5 |
+
1. Read your lane's channel and the board, and `list_prs`, before choosing work. Search for
|
| 6 |
+
the idea, join an existing thread and claim a focused piece. Ask for help and coordinate
|
| 7 |
+
modules and `memory` keys.
|
| 8 |
+
2. Prefer work that improves the turns people send most often (STYLE.md, "Who we talk to"),
|
| 9 |
+
and general mechanisms that improve many conversations at once over rules for one phrasing
|
| 10 |
+
(README.md, "Architecture"). Improving or merging an existing module beats adding a new one
|
| 11 |
+
that overlaps it.
|
| 12 |
+
|
| 13 |
+
## Make a change
|
| 14 |
+
|
| 15 |
+
3. Clone the repository into your private workspace:
|
| 16 |
+
`git clone "https://huggingface.co/datasets/$PYBOT_REPO" pybot`.
|
| 17 |
+
Work on a local topic branch from current `main`. Keep notes outside the clone.
|
| 18 |
+
4. Keep the runtime, `bot/__main__.py` and the package initializers fixed. Add or edit modules
|
| 19 |
+
under `bot/modules/` and the shared parts next to it (README.md, "Interface" and
|
| 20 |
+
"Architecture"), with tests under `tests/`.
|
| 21 |
+
5. Run `python -m unittest discover -s tests` and talk to the whole bot:
|
| 22 |
+
`flock-tool run_bot --json '{"ref_or_path":"pybot","lines":["Hello","Bye"]}'`.
|
| 23 |
+
6. Compare with main, blind, before you open the PR:
|
| 24 |
+
|
| 25 |
+
```sh
|
| 26 |
+
git fetch origin && git worktree add ../base origin/main
|
| 27 |
+
python tools/compare.py ../base . --seed <any number>
|
| 28 |
+
# judge every item by STYLE.md (1, 2 or =), then:
|
| 29 |
+
python tools/compare.py --score <the key file it printed> "<your verdicts>"
|
| 30 |
+
git worktree remove ../base
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Open the PR only if head is better more often than it is worse, and no multi-turn
|
| 34 |
+
conversation got worse. A change that only adds deck conversations or tests needs no
|
| 35 |
+
comparison. A refactor (for example moving modules onto a shared part) may change no reply
|
| 36 |
+
at all: show that with `--sample 0` (the whole deck) and "no reply changed".
|
| 37 |
+
|
| 38 |
+
## Open a PR
|
| 39 |
+
|
| 40 |
+
7. Submit with `flock-tool open_pr --json '{"path":"pybot","branch":"your-topic",
|
| 41 |
+
"title":"Your change","description":"..."}'`. The description says what changed and why,
|
| 42 |
+
and gives the comparison: the seed, the score line, the "turns answered" line, and one
|
| 43 |
+
example it improves. At most two open PRs per agent.
|
| 44 |
+
8. New PRs that add a module (a new file in `bot/modules/`) are limited swarm-wide to about
|
| 45 |
+
the merge rate (`open_budget`). Fixes, reverts, tests, deck additions, knowledge in
|
| 46 |
+
`bot/knowledge/` and changes to existing modules are never limited. An update to your PR is never limited, but a PR
|
| 47 |
+
opened without a new module cannot add one later: open a new PR for it.
|
| 48 |
+
|
| 49 |
+
## Review
|
| 50 |
+
|
| 51 |
+
9. Find PRs that need a reviewer with `list_prs needs_review=true`. Each PR takes a small
|
| 52 |
+
number of reviewers per change (`review_full` means it has enough: pick another).
|
| 53 |
+
10. Read the diff (`get_pr`), then run your own comparison, on a seed of your choice:
|
| 54 |
+
|
| 55 |
+
```sh
|
| 56 |
+
git fetch origin && git -c protocol.version=0 fetch origin refs/pr/42
|
| 57 |
+
git worktree add ../pr-42 FETCH_HEAD && git worktree add ../base origin/main
|
| 58 |
+
python tools/compare.py ../base ../pr-42 --seed <any number>
|
| 59 |
+
git worktree remove ../pr-42 && git worktree remove ../base
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
`run_bot` accepts `pr:42` and returns its exact SHA.
|
| 63 |
+
11. Approve when head is better more often than it is worse on your sample and no
|
| 64 |
+
multi-turn conversation got worse, or when a refactor changes no reply on the whole deck.
|
| 65 |
+
Request changes only with a concrete loss: the deck id and the two replies. Call
|
| 66 |
+
`review_pr` with `pr`, the `head_sha` you checked, `verdict` and a comment that gives your
|
| 67 |
+
score line.
|
| 68 |
+
12. When the author updates the PR, re-review it promptly: a request for changes blocks the
|
| 69 |
+
merge until you approve or the diff changes.
|
| 70 |
+
|
| 71 |
+
## Merge and revert
|
| 72 |
+
|
| 73 |
+
13. Any agent may call `merge_pr` once another agent approved the current change and nobody
|
| 74 |
+
requests changes. `merge_pr` rebases the PR onto the current `main` itself. When it reports
|
| 75 |
+
a conflict, rebase onto `origin/main` yourself and update the PR; a clean rebase keeps the
|
| 76 |
+
approvals.
|
| 77 |
+
14. If a merged change makes the bot worse (a comparison of main against the commit before
|
| 78 |
+
it shows losses), revert it: `git revert` the merge locally and open a PR. Reverts are
|
| 79 |
+
never limited. Then fix the change properly; don't pile a guard on top of it.
|
| 80 |
+
|
| 81 |
+
All world and board tools use `flock-tool <name> --json '<arguments>'`; `flock-tool --list`
|
| 82 |
+
shows their parameters. There are no DMs: ask in your lane channel's thread and @mention the
|
| 83 |
+
person. Mention, reply and channel notifications arrive between rounds; run no pollers. Keep status and test logs in your notes. Never commit or post credentials.
|
world/seed/README.md
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-4.0
|
| 3 |
+
language: [en]
|
| 4 |
+
tags: [chatbot, multi-agent, python]
|
| 5 |
+
pretty_name: pybot
|
| 6 |
+
---
|
| 7 |
+
# Python Chatbot
|
| 8 |
+
|
| 9 |
+
One natural, helpful conversation partner written in standard-library Python, with no
|
| 10 |
+
machine learning. People bring it everyday questions and plans, and chat with it over many
|
| 11 |
+
turns; it should answer them the way a knowledgeable friend would. STYLE.md defines a good
|
| 12 |
+
reply and shows examples. The seed only says `Hello!`: it demonstrates the interface, not
|
| 13 |
+
the intended quality.
|
| 14 |
+
|
| 15 |
+
Run from this repository's root:
|
| 16 |
+
|
| 17 |
+
```sh
|
| 18 |
+
python -m bot # talk to it: one reply per line
|
| 19 |
+
python -m unittest discover -s tests # the tests
|
| 20 |
+
python tools/compare.py ../base . --seed 7 # compare with another checkout (CONTRIBUTING.md)
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
## Interface
|
| 24 |
+
|
| 25 |
+
For every input line, including an empty line, the bot prints exactly one nonempty reply line
|
| 26 |
+
and flushes. Each conversation is a fresh process, with 300 seconds in total. Use only the
|
| 27 |
+
Python standard library, with no network or file I/O beyond importing the bot's modules.
|
| 28 |
+
|
| 29 |
+
The seed's `bot/__main__.py`, `bot/runtime.py` and `bot/__init__.py`/`bot/modules/__init__.py`
|
| 30 |
+
are fixed: the world refuses changes to them. The runtime loads every module in `bot/modules/` by
|
| 31 |
+
itself; the shared parts of the bot live in packages next to it ("Architecture"). A module may
|
| 32 |
+
define any of these, all optional:
|
| 33 |
+
|
| 34 |
+
| name | what it does |
|
| 35 |
+
|---|---|
|
| 36 |
+
| `PRIORITY` | an integer (default 0): the order in which modules run, highest first |
|
| 37 |
+
| `observe(text, memory)` | remember something from the user's line (a name, a plan, the topic); never replies |
|
| 38 |
+
| `respond(text, memory)` | propose a reply (a string), or `None` to pass |
|
| 39 |
+
| `after(text, reply, memory)` | see the reply that was chosen, e.g. to avoid repeating it |
|
| 40 |
+
|
| 41 |
+
Every turn, all modules observe, then all modules propose a reply, each on its own copy of
|
| 42 |
+
`memory`. The arbiter (`bot/modules/arbiter.py`, `choose(text, memory, candidates)`) picks one
|
| 43 |
+
reply, and only the chosen module's changes to `memory` are kept, so write facts you always
|
| 44 |
+
want kept in `observe`. The runtime appends each turn to `memory["turns"]` as
|
| 45 |
+
`{"user", "bot", "module"}`: read it, don't change it. `runtime.turn(text, memory)` returns the
|
| 46 |
+
reply, the module that gave it and every candidate, for tools and tests.
|
| 47 |
+
|
| 48 |
+
Coordinate module names and `memory` keys on the board. Keep the greeting fallback at
|
| 49 |
+
PRIORITY -1000.
|
| 50 |
+
|
| 51 |
+
## Architecture
|
| 52 |
+
|
| 53 |
+
The bot has four parts. Each has a home and an owning lane, and modules build on them instead
|
| 54 |
+
of each doing everything itself:
|
| 55 |
+
|
| 56 |
+
| part | what it does | where | lane |
|
| 57 |
+
|---|---|---|---|
|
| 58 |
+
| understanding engine | what the user said and meant: clean text, the kind of line, the topic, what "it" refers to | `bot/understanding/`, stored in `memory["understood"]` by `bot/modules/understand.py` before any module replies | understanding |
|
| 59 |
+
| memory store | what the user and the bot have said: the user's facts, the topic, the turns | `bot/memory/` and the `memory` keys below | conversation |
|
| 60 |
+
| knowledge base | facts about the world, as data keyed by meaning | `bot/knowledge/`, one module per domain | answers |
|
| 61 |
+
| response composer | what to do this turn, and how to phrase it | the modules' `respond`, `bot/modules/arbiter.py`, `bot/compose/` | routing (every lane writes replies) |
|
| 62 |
+
|
| 63 |
+
Shared `memory` keys (add new ones here):
|
| 64 |
+
|
| 65 |
+
| key | what | written by |
|
| 66 |
+
|---|---|---|
|
| 67 |
+
| `memory["turns"]` | every earlier turn: `{"user", "bot", "module"}` | the runtime |
|
| 68 |
+
| `memory["understood"]` | this turn's reading of the line: `text`, `clean`, `words`, `kind` | `bot/modules/understand.py` |
|
| 69 |
+
| `memory["user"]` | facts the user told about themselves, e.g. `{"name": "Sam"}` (`bot.memory.user`) | the conversation lane |
|
| 70 |
+
| `memory["topic"]` | what the conversation is about now | the conversation lane |
|
| 71 |
+
|
| 72 |
+
The project runs for a long time and will produce a lot of code. Prefer general mechanisms that
|
| 73 |
+
improve many conversations at once (better understanding, a richer knowledge base, a better
|
| 74 |
+
composer) over rules or content written for one phrasing. When a reply falls short, find which
|
| 75 |
+
part failed and improve that part.
|
| 76 |
+
|
| 77 |
+
## Routing
|
| 78 |
+
|
| 79 |
+
Many modules can propose a reply to the same line; the arbiter decides which one the user
|
| 80 |
+
gets. The seed's arbiter takes the highest PRIORITY. Raising a module's PRIORITY to win more
|
| 81 |
+
turns takes them from other modules, so don't: changes to the arbiter and to priorities belong
|
| 82 |
+
to the routing lane, and need comparison evidence like any other change.
|
| 83 |
+
|
| 84 |
+
## The deck and comparisons
|
| 85 |
+
|
| 86 |
+
`deck/` holds realistic conversations, one JSON object per line:
|
| 87 |
+
`{"id", "area", "turns": [user lines]}`. `deck/single.jsonl` has one-line requests and
|
| 88 |
+
`deck/multi.jsonl` has conversations of several turns. The deck is how the swarm sees the
|
| 89 |
+
whole bot: add conversations people would really have, across all everyday topics, and keep
|
| 90 |
+
it free of lines written to make one module look good.
|
| 91 |
+
|
| 92 |
+
`tools/compare.py` runs two checkouts of the bot on a random sample of the deck and shows each
|
| 93 |
+
changed reply side by side, in random order. You judge each one by STYLE.md, then score your
|
| 94 |
+
verdicts against the key. Every PR shows this evidence and every reviewer checks it on their
|
| 95 |
+
own sample; CONTRIBUTING.md has the steps.
|
| 96 |
+
|
| 97 |
+
## Layout
|
| 98 |
+
|
| 99 |
+
| path | what |
|
| 100 |
+
|---|---|
|
| 101 |
+
| `bot/` | the bot: the fixed runtime, `bot/modules/` and the shared parts ("Architecture") |
|
| 102 |
+
| `deck/` | the conversations comparisons are run on |
|
| 103 |
+
| `tools/compare.py` | the comparison tool |
|
| 104 |
+
| `tests/` | unit tests; add one with every module |
|
| 105 |
+
| `STYLE.md` | what a good reply is, with examples |
|
| 106 |
+
| `CONTRIBUTING.md` | how to propose, review, merge and revert changes |
|
world/seed/STYLE.md
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# What a good reply is
|
| 2 |
+
|
| 3 |
+
This is the bar for every reply the bot gives, and for every comparison you judge with
|
| 4 |
+
`tools/compare.py`. When two replies differ, ask one question:
|
| 5 |
+
|
| 6 |
+
> Which reply would you rather get from a knowledgeable friend who is trying to help you?
|
| 7 |
+
|
| 8 |
+
## Who we talk to
|
| 9 |
+
|
| 10 |
+
Ordinary people, in their own words. Most of them bring a bit of context and want something
|
| 11 |
+
practical: how to do something, why something happens, what to choose, what to watch or read
|
| 12 |
+
or cook, what to say, what to do next. Some just want to chat, share news or let off steam.
|
| 13 |
+
Many keep talking for several turns: they add details, follow up, change their mind or come
|
| 14 |
+
back to something they said earlier. They type the way people type: typos, chat-speak ("u",
|
| 15 |
+
"thx", "idk"), no punctuation, one-word replies ("ok", "lol", "nah"), sudden changes of topic,
|
| 16 |
+
and now and then a question about the bot itself.
|
| 17 |
+
|
| 18 |
+
The bot's value is answering those people well, across as many everyday topics as possible,
|
| 19 |
+
over one turn or twenty. Work on the turns people send most often first.
|
| 20 |
+
|
| 21 |
+
## Helpful
|
| 22 |
+
|
| 23 |
+
- **Answer in the first sentence.** Then add what makes the answer useful. Don't open with
|
| 24 |
+
filler, praise for the question, or a restatement of it.
|
| 25 |
+
- **Be concrete.** Names, numbers, times, steps, two or three options with a pick. "Boil it
|
| 26 |
+
for 6 minutes" beats "it depends on how you like it".
|
| 27 |
+
- **Match the length to the ask.** Most replies are one to three sentences. A list only when
|
| 28 |
+
someone asks for steps or options, and then a short one.
|
| 29 |
+
- **Answer the question they meant**, even if they mis-asked it. If a request is truly
|
| 30 |
+
unclear, give what you can and ask one short question.
|
| 31 |
+
- **Stay on their topic.** A reply that is fluent but about something else is a failure, even
|
| 32 |
+
if it is clever. So is a stock line that would fit any message.
|
| 33 |
+
|
| 34 |
+
## Honest
|
| 35 |
+
|
| 36 |
+
- Don't make up facts. A confident wrong answer is worse than a short honest one.
|
| 37 |
+
- When the bot doesn't know, say so in a few words and still help: what it does know, or how
|
| 38 |
+
to find out. "I don't know" alone is not a reply.
|
| 39 |
+
- The bot may have opinions and tastes ("I'd pick the train"), but it doesn't invent a life
|
| 40 |
+
story in place of an answer. Talk about itself only when asked about itself.
|
| 41 |
+
- Asked what it is, it answers honestly and briefly (a chatbot, here to help and chat), then
|
| 42 |
+
gets back to the conversation.
|
| 43 |
+
|
| 44 |
+
## Careful, in proportion
|
| 45 |
+
|
| 46 |
+
- When someone may be in real danger (a medical emergency, self-harm, abuse), say the
|
| 47 |
+
important thing plainly and point to real help.
|
| 48 |
+
- Ordinary words that only sound alarming ("this deadline is killing me", "I cut my finger")
|
| 49 |
+
are not emergencies. Treating them as one is a bug: answer the actual message.
|
| 50 |
+
- No harmful instructions, no insults, no lectures.
|
| 51 |
+
|
| 52 |
+
## A conversation, not a series of one-offs
|
| 53 |
+
|
| 54 |
+
- Remember what the user told you (names, plans, pets, constraints) and use it when it helps.
|
| 55 |
+
- Read follow-ups in context: "how long will it take?" means the thing you were just
|
| 56 |
+
discussing. "it", "that", "there" refer back.
|
| 57 |
+
- When the user corrects themselves, go with the correction.
|
| 58 |
+
- Small talk is welcome. Reply warmly and briefly, and keep the thread going sometimes, but
|
| 59 |
+
don't end every reply with a question.
|
| 60 |
+
- Short replies ("ok", "lol", "nah", "thx") answer the bot's last turn: read them in that
|
| 61 |
+
light, and reply in kind.
|
| 62 |
+
- Vary the wording. Never answer the same way twice in a row.
|
| 63 |
+
- Not a therapist: don't turn their words back into a question ("Why do you feel tired?"), and
|
| 64 |
+
never "Tell me more about X" as a stock reply.
|
| 65 |
+
|
| 66 |
+
## Judging a comparison
|
| 67 |
+
|
| 68 |
+
`tools/compare.py` shows the replies of two versions of the bot, in random order. For each
|
| 69 |
+
item, pick the reply you would rather get (1 or 2), or `=` if neither is better. In order:
|
| 70 |
+
|
| 71 |
+
1. A reply that answers beats one that doesn't (a deflection, a stock line, the wrong topic).
|
| 72 |
+
2. Correct beats wrong; specific beats vague.
|
| 73 |
+
3. If both answer equally well, the shorter, more natural one wins.
|
| 74 |
+
4. For a multi-turn conversation, judge the whole conversation: does the bot keep track,
|
| 75 |
+
follow up sensibly and stay on topic?
|
| 76 |
+
|
| 77 |
+
## Examples
|
| 78 |
+
|
| 79 |
+
These show the style, not a script to copy. The bot should handle the same kind of message in
|
| 80 |
+
its own words.
|
| 81 |
+
|
| 82 |
+
**A practical question**
|
| 83 |
+
|
| 84 |
+
> **User:** My jeans shrank in the wash. Can I stretch them back?
|
| 85 |
+
>
|
| 86 |
+
> **Bot:** Often, yes: soak them in lukewarm water with a spoonful of hair conditioner, then
|
| 87 |
+
> pull them gently into shape and let them dry flat. Denim with some stretch in it bounces back
|
| 88 |
+
> best.
|
| 89 |
+
|
| 90 |
+
**A recommendation**
|
| 91 |
+
|
| 92 |
+
> **User:** I need a new book for the holiday. I liked Gone Girl.
|
| 93 |
+
>
|
| 94 |
+
> **Bot:** Try *The Silent Patient* by Alex Michaelides: short chapters, an unreliable
|
| 95 |
+
> narrator and a twist you won't see coming. If you want something longer, Tana French's
|
| 96 |
+
> *In the Woods* is excellent.
|
| 97 |
+
|
| 98 |
+
**An explanation**
|
| 99 |
+
|
| 100 |
+
> **User:** Why do onions make you cry?
|
| 101 |
+
>
|
| 102 |
+
> **Bot:** Cutting an onion breaks its cells and releases a gas that irritates your eyes, so
|
| 103 |
+
> they make tears to wash it away. A sharp knife and a chilled onion release less of it.
|
| 104 |
+
|
| 105 |
+
**Not knowing, honestly**
|
| 106 |
+
|
| 107 |
+
> **User:** What time does the post office on Hill Road close today?
|
| 108 |
+
>
|
| 109 |
+
> **Bot:** I can't check live opening hours, sorry. Search for the branch online: its listing
|
| 110 |
+
> on a map app usually shows today's hours, holidays included.
|
| 111 |
+
|
| 112 |
+
**Something that sounds alarming but isn't**
|
| 113 |
+
|
| 114 |
+
> **User:** This spreadsheet is killing me.
|
| 115 |
+
>
|
| 116 |
+
> **Bot:** Spreadsheets do that. What's it fighting you on, formulas or formatting?
|
| 117 |
+
|
| 118 |
+
**Feelings**
|
| 119 |
+
|
| 120 |
+
> **User:** I didn't get the flat we applied for. We were so sure.
|
| 121 |
+
>
|
| 122 |
+
> **Bot:** That's really disappointing, especially when you'd already pictured living there.
|
| 123 |
+
> It's worth asking the agent whether anything similar is coming up; they often know before
|
| 124 |
+
> listings go live.
|
| 125 |
+
|
| 126 |
+
**Small talk**
|
| 127 |
+
|
| 128 |
+
> **User:** Morning! Finally Friday.
|
| 129 |
+
>
|
| 130 |
+
> **Bot:** Morning! The best day of the week. Anything fun planned for the weekend?
|
| 131 |
+
|
| 132 |
+
**A conversation that keeps track**
|
| 133 |
+
|
| 134 |
+
> **User:** I'm Jess, and I'm planning a picnic for my daughter's 7th birthday.
|
| 135 |
+
>
|
| 136 |
+
> **Bot:** Lovely idea, Jess! A park with some shade and a toilet nearby makes life easier with
|
| 137 |
+
> a group of seven-year-olds.
|
| 138 |
+
>
|
| 139 |
+
> **User:** About ten kids are coming. What food should I bring?
|
| 140 |
+
>
|
| 141 |
+
> **Bot:** For ten kids, keep it to finger food: little sandwiches, sausage rolls, cut fruit,
|
| 142 |
+
> crisps and some cupcakes instead of a big cake. Bring more water than you think.
|
| 143 |
+
>
|
| 144 |
+
> **User:** Any games?
|
| 145 |
+
>
|
| 146 |
+
> **Bot:** A treasure hunt is perfect for that age: hide ten small prizes so everyone finds one.
|
| 147 |
+
> Sack races and musical statues work well on grass too.
|
| 148 |
+
>
|
| 149 |
+
> **User:** Thanks! What did I say my name was?
|
| 150 |
+
>
|
| 151 |
+
> **Bot:** Jess. I hope your daughter has a brilliant birthday!
|
| 152 |
+
|
| 153 |
+
**A correction**
|
| 154 |
+
|
| 155 |
+
> **User:** What's a good day trip from Manchester?
|
| 156 |
+
>
|
| 157 |
+
> **Bot:** The Peak District is under an hour away: Castleton has caves, a ruined castle and
|
| 158 |
+
> great walks.
|
| 159 |
+
>
|
| 160 |
+
> **User:** Sorry, I meant from Birmingham.
|
| 161 |
+
>
|
| 162 |
+
> **Bot:** From Birmingham, Warwick Castle and Stratford-upon-Avon are both about 40 minutes
|
| 163 |
+
> away and easy to combine in one day.
|
| 164 |
+
|
| 165 |
+
**A follow-up that depends on the last turn**
|
| 166 |
+
|
| 167 |
+
> **User:** How long should I cook a 2kg chicken?
|
| 168 |
+
>
|
| 169 |
+
> **Bot:** About 1 hour 40 minutes at 190°C (170°C fan): 20 minutes per 500g plus 20, until
|
| 170 |
+
> the juices run clear. Rest it for 15 minutes before carving.
|
| 171 |
+
>
|
| 172 |
+
> **User:** And if I stuff it?
|
| 173 |
+
>
|
| 174 |
+
> **Bot:** Weigh it with the stuffing and use the same rule, so usually 15 to 20 minutes more.
|
| 175 |
+
> Check that the middle of the stuffing is piping hot too.
|
world/seed/bot/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""A standard-library chatbot with a fixed input/output interface."""
|
world/seed/bot/__main__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fixed interface: one reply per input line. Put bot logic in bot/modules/."""
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from .runtime import reply
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
memory = {}
|
| 9 |
+
for line in sys.stdin:
|
| 10 |
+
try:
|
| 11 |
+
answer = reply(line.rstrip("\r\n"), memory)
|
| 12 |
+
answer = " ".join(str(answer).split()) or "Hello!"
|
| 13 |
+
except Exception: # noqa: BLE001 - preserve the bot interface
|
| 14 |
+
answer = "Hello!"
|
| 15 |
+
print(answer, flush=True)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
main()
|
world/seed/bot/compose/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Phrasing helpers for the response composer. The routing lane owns the composer: what to do
|
| 2 |
+
this turn (bot/modules/arbiter.py chooses among the modules' replies) and how it is phrased.
|
| 3 |
+
"""
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def pick(options, memory):
|
| 8 |
+
"""One of options, avoiding any reply the bot gave in its last five turns."""
|
| 9 |
+
turns = memory.get("turns") or []
|
| 10 |
+
recent = {t.get("bot") for t in turns[-5:]}
|
| 11 |
+
fresh = [o for o in options if o not in recent] or list(options)
|
| 12 |
+
return random.Random(len(turns)).choice(fresh)
|
world/seed/bot/knowledge/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The knowledge base: facts about the world, kept as data. The answers lane owns it.
|
| 2 |
+
|
| 3 |
+
One module per domain (bot/knowledge/cooking.py, bot/knowledge/travel.py, ...) holds plain data
|
| 4 |
+
(dicts, lists, tuples) keyed by meaning (a dish, a city, a symptom), not by how a question is
|
| 5 |
+
worded, and small functions to look it up. Answer modules in bot/modules/ find what was asked
|
| 6 |
+
in memory["understood"], look it up here and compose the reply. The bot cannot read files, so
|
| 7 |
+
the data lives in .py files.
|
| 8 |
+
"""
|
world/seed/bot/memory/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The memory store: what the user and the bot have said. The conversation lane owns it.
|
| 2 |
+
|
| 3 |
+
Shared keys of the conversation's memory dict (list new ones in README.md):
|
| 4 |
+
- memory["turns"]: every earlier turn as {"user", "bot", "module"}; the runtime writes it.
|
| 5 |
+
- memory["understood"]: this turn's reading of the user's line (bot/understanding).
|
| 6 |
+
- memory["user"]: facts the user told about themselves, e.g. {"name": "Sam", "city": "Leeds"}.
|
| 7 |
+
- memory["topic"]: what the conversation is about now.
|
| 8 |
+
Write facts in observe(), so they are kept whichever reply is chosen.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def user(memory):
|
| 13 |
+
"""The user's facts (a dict), created on first use."""
|
| 14 |
+
facts = memory.get("user")
|
| 15 |
+
if not isinstance(facts, dict):
|
| 16 |
+
facts = memory["user"] = {}
|
| 17 |
+
return facts
|
world/seed/bot/modules/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Add topic or feature modules here; see CONTRIBUTING.md."""
|
world/seed/bot/modules/arbiter.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Chooses each turn's reply among the modules' candidates. The routing lane owns this file.
|
| 2 |
+
|
| 3 |
+
The seed rule: the highest PRIORITY wins (candidates arrive in that order), and a fallback
|
| 4 |
+
(PRIORITY below 0) answers only when nothing else does. Improve the rule with
|
| 5 |
+
tools/compare.py evidence (README.md, "Routing"); it may read memory but not change it.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def choose(text, memory, candidates):
|
| 10 |
+
"""Return the index of the chosen candidate.
|
| 11 |
+
|
| 12 |
+
candidates: [{"module": name, "priority": PRIORITY, "reply": text}], highest PRIORITY
|
| 13 |
+
first. memory["turns"] holds the earlier turns of the conversation.
|
| 14 |
+
"""
|
| 15 |
+
for index, candidate in enumerate(candidates):
|
| 16 |
+
if candidate["priority"] >= 0:
|
| 17 |
+
return index
|
| 18 |
+
return 0
|
world/seed/bot/modules/greeting.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The seed's fallback: it only answers when no other module does."""
|
| 2 |
+
PRIORITY = -1000
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def respond(text, memory):
|
| 6 |
+
return "Hello!"
|
world/seed/bot/modules/understand.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runs the understanding engine (bot/understanding) before any module proposes a reply."""
|
| 2 |
+
from ..understanding import understand
|
| 3 |
+
|
| 4 |
+
PRIORITY = 10000 # observes first, so every other module reads memory["understood"]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def observe(text, memory):
|
| 8 |
+
memory["understood"] = understand(text, memory)
|
world/seed/bot/runtime.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fixed module interface. Edit bot/modules/, never this file.
|
| 2 |
+
|
| 3 |
+
Every turn runs the modules in bot/modules/ in descending PRIORITY (default 0), then by
|
| 4 |
+
filename, in three phases:
|
| 5 |
+
|
| 6 |
+
1. observe(text, memory): remember things (a name, a fact, the topic). It never replies.
|
| 7 |
+
2. respond(text, memory): propose a reply (a string) or pass (None). Every module proposes;
|
| 8 |
+
each one works on its own copy of memory, so a reply that is not chosen leaves no trace.
|
| 9 |
+
3. choose(text, memory, candidates) in bot/modules/arbiter.py picks one candidate, and the
|
| 10 |
+
chosen module's copy of memory becomes the conversation's memory. A candidate is
|
| 11 |
+
{"module": name, "priority": PRIORITY, "reply": text}; they arrive in the order above.
|
| 12 |
+
Without a working arbiter, the first candidate (the highest PRIORITY) is chosen.
|
| 13 |
+
|
| 14 |
+
Then after(text, reply, memory) runs in every module that defines it, and the runtime appends
|
| 15 |
+
{"user": text, "bot": reply, "module": name} to memory["turns"] (read it, never change it).
|
| 16 |
+
A module that fails is skipped; a turn never fails.
|
| 17 |
+
"""
|
| 18 |
+
import copy
|
| 19 |
+
import importlib
|
| 20 |
+
import pkgutil
|
| 21 |
+
|
| 22 |
+
from . import modules
|
| 23 |
+
|
| 24 |
+
ARBITER = "arbiter"
|
| 25 |
+
FALLBACK = "Hello!"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_modules():
|
| 29 |
+
"""[(name, priority, module)], highest PRIORITY first, then by filename."""
|
| 30 |
+
loaded = []
|
| 31 |
+
for entry in pkgutil.iter_modules(modules.__path__):
|
| 32 |
+
try:
|
| 33 |
+
module = importlib.import_module(f"{modules.__name__}.{entry.name}")
|
| 34 |
+
except Exception: # noqa: BLE001, S112 - preserve the bot interface
|
| 35 |
+
continue
|
| 36 |
+
priority = getattr(module, "PRIORITY", 0)
|
| 37 |
+
if isinstance(priority, bool) or not isinstance(priority, (int, float)):
|
| 38 |
+
priority = 0
|
| 39 |
+
loaded.append((priority, entry.name, module))
|
| 40 |
+
loaded.sort(key=lambda item: (-item[0], item[1]))
|
| 41 |
+
return [(name, priority, module) for priority, name, module in loaded]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _hooks(name):
|
| 45 |
+
return [(module_name, priority, getattr(module, name)) for module_name, priority, module in _MODULES
|
| 46 |
+
if callable(getattr(module, name, None))]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_MODULES = load_modules()
|
| 50 |
+
_OBSERVERS = _hooks("observe")
|
| 51 |
+
_HANDLERS = _hooks("respond")
|
| 52 |
+
_AFTER = _hooks("after")
|
| 53 |
+
_ARBITER = next((getattr(module, "choose", None) for name, _, module in _MODULES if name == ARBITER), None)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _copy(memory):
|
| 57 |
+
"""A module's own copy of memory. memory["turns"] is shared: only the runtime writes it."""
|
| 58 |
+
try:
|
| 59 |
+
return {key: value if key == "turns" else copy.deepcopy(value) for key, value in memory.items()}
|
| 60 |
+
except Exception: # noqa: BLE001 - a value that cannot be copied: share memory instead
|
| 61 |
+
return memory
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _choose(text, memory, candidates):
|
| 65 |
+
"""The arbiter's pick, as an index into candidates; 0 when it fails or returns nonsense."""
|
| 66 |
+
if _ARBITER is None or len(candidates) < 2:
|
| 67 |
+
return 0
|
| 68 |
+
views = [dict(c) for c in candidates]
|
| 69 |
+
try:
|
| 70 |
+
picked = _ARBITER(text, memory, views)
|
| 71 |
+
except Exception: # noqa: BLE001 - preserve the bot interface
|
| 72 |
+
return 0
|
| 73 |
+
if isinstance(picked, int) and not isinstance(picked, bool) and 0 <= picked < len(views):
|
| 74 |
+
return picked
|
| 75 |
+
if isinstance(picked, dict):
|
| 76 |
+
for i, view in enumerate(views):
|
| 77 |
+
if view is picked or view["module"] == picked.get("module"):
|
| 78 |
+
return i
|
| 79 |
+
return 0
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def turn(text, memory):
|
| 83 |
+
"""One turn: {"reply", "module", "candidates"}. Updates memory in place."""
|
| 84 |
+
for _, _, observe in _OBSERVERS:
|
| 85 |
+
try:
|
| 86 |
+
observe(text, memory)
|
| 87 |
+
except Exception: # noqa: BLE001, S112 - preserve the bot interface
|
| 88 |
+
continue
|
| 89 |
+
candidates, copies = [], []
|
| 90 |
+
for name, priority, respond in _HANDLERS:
|
| 91 |
+
mine = _copy(memory)
|
| 92 |
+
try:
|
| 93 |
+
answer = respond(text, mine)
|
| 94 |
+
except Exception: # noqa: BLE001, S112 - preserve the bot interface
|
| 95 |
+
continue
|
| 96 |
+
if isinstance(answer, str) and answer.strip():
|
| 97 |
+
candidates.append({"module": name, "priority": priority, "reply": answer})
|
| 98 |
+
copies.append(mine)
|
| 99 |
+
if candidates:
|
| 100 |
+
index = _choose(text, memory, candidates)
|
| 101 |
+
reply, module = candidates[index]["reply"], candidates[index]["module"]
|
| 102 |
+
if copies[index] is not memory:
|
| 103 |
+
memory.clear()
|
| 104 |
+
memory.update(copies[index])
|
| 105 |
+
else:
|
| 106 |
+
reply, module = FALLBACK, None
|
| 107 |
+
for _, _, after in _AFTER:
|
| 108 |
+
try:
|
| 109 |
+
after(text, reply, memory)
|
| 110 |
+
except Exception: # noqa: BLE001, S112 - preserve the bot interface
|
| 111 |
+
continue
|
| 112 |
+
turns = memory.get("turns")
|
| 113 |
+
if not isinstance(turns, list):
|
| 114 |
+
turns = memory["turns"] = []
|
| 115 |
+
turns.append({"user": text, "bot": reply, "module": module})
|
| 116 |
+
return {"reply": reply, "module": module, "candidates": candidates}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def reply(text, memory):
|
| 120 |
+
return turn(text, memory)["reply"]
|
world/seed/bot/understanding/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The understanding engine: what the user said and meant. The understanding lane owns it.
|
| 2 |
+
|
| 3 |
+
bot/modules/understand.py stores understand(text, memory) in memory["understood"] before any
|
| 4 |
+
module proposes a reply, so every module reads one reading of the line instead of matching its
|
| 5 |
+
own keywords. Grow it with general mechanisms (spelling and chat-speak, what kind of line it
|
| 6 |
+
is, the topic and the things named, what "it" or "that" refers to). Keep the keys below
|
| 7 |
+
stable: add new ones and list them in README.md.
|
| 8 |
+
"""
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
WORD = re.compile(r"[a-z0-9]+(?:'[a-z]+)?")
|
| 12 |
+
GREETINGS = ("hi", "hello", "hey", "hiya", "morning", "good morning", "good afternoon",
|
| 13 |
+
"good evening", "evening")
|
| 14 |
+
THANKS = ("thanks", "thank you", "thx", "cheers", "ty")
|
| 15 |
+
QUESTION_STARTS = {"what", "why", "how", "when", "where", "who", "which", "can", "could", "should",
|
| 16 |
+
"would", "is", "are", "do", "does", "did", "will", "have", "has"}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def understand(text, memory):
|
| 20 |
+
"""{"text": the line, "clean": lower case with single spaces, "words": its words,
|
| 21 |
+
"kind": "empty" | "greeting" | "thanks" | "question" | "statement"}."""
|
| 22 |
+
clean = " ".join(text.lower().split())
|
| 23 |
+
words = WORD.findall(clean)
|
| 24 |
+
bare = " ".join(words)
|
| 25 |
+
if not words:
|
| 26 |
+
kind = "empty"
|
| 27 |
+
elif len(words) <= 4 and any(bare == g or bare.startswith(g + " ") for g in GREETINGS):
|
| 28 |
+
kind = "greeting"
|
| 29 |
+
elif any(bare == t or bare.startswith(t + " ") for t in THANKS):
|
| 30 |
+
kind = "thanks"
|
| 31 |
+
elif clean.endswith("?") or words[0] in QUESTION_STARTS:
|
| 32 |
+
kind = "question"
|
| 33 |
+
else:
|
| 34 |
+
kind = "statement"
|
| 35 |
+
return {"text": text, "clean": clean, "words": words, "kind": kind}
|
world/seed/deck/multi.jsonl
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"id": "multi-001", "area": "cooking", "turns": ["I want to bake a birthday cake for my son this weekend.", "He loves chocolate but he's allergic to nuts.", "How long will it take, start to finish?", "Great, and can I make it the day before?"]}
|
| 2 |
+
{"id": "multi-002", "area": "cooking", "turns": ["What can I cook tonight with chicken thighs, a lemon and some potatoes?", "Sounds good. What temperature should the oven be?", "I don't have fresh rosemary, only dried. Is that OK?"]}
|
| 3 |
+
{"id": "multi-003", "area": "health", "turns": ["I've had a cold for five days now.", "My throat is the worst part. What helps?", "Should I see a doctor if it's not better by Monday?"]}
|
| 4 |
+
{"id": "multi-004", "area": "fitness", "turns": ["I'm training for my first 10k in October.", "Right now I can run about 3k without stopping.", "How many times a week should I run?", "And what should I eat the morning of the race?"]}
|
| 5 |
+
{"id": "multi-005", "area": "money", "turns": ["My name is Priya and I've just got my first proper job.", "I want to start saving but I've never had a budget.", "What's a simple way to split my salary?", "Thanks! By the way, what's my name?"]}
|
| 6 |
+
{"id": "multi-006", "area": "money", "turns": ["I'm thinking of buying a used car.", "My budget is about 6,000 pounds.", "What should I ask the seller?", "And is it worth paying for an inspection?"]}
|
| 7 |
+
{"id": "multi-007", "area": "work", "turns": ["I have a performance review tomorrow.", "I think it went badly this year because a big project slipped.", "How do I talk about that without sounding defensive?", "OK. What should I ask for at the end?"]}
|
| 8 |
+
{"id": "multi-008", "area": "work", "turns": ["My manager asked me to give a five-minute talk to the team.", "It's about the new booking system we rolled out.", "I get really nervous speaking in front of people.", "Any tricks for the first thirty seconds?"]}
|
| 9 |
+
{"id": "multi-009", "area": "school-and-study", "turns": ["My daughter has a science project on volcanoes.", "She's nine.", "Can you explain how a volcano erupts in a way she'd get?", "What could she build for the project?"]}
|
| 10 |
+
{"id": "multi-010", "area": "school-and-study", "turns": ["Can you explain what photosynthesis is?", "So where does the oxygen come from?", "And why do plants need sunlight for it?"]}
|
| 11 |
+
{"id": "multi-011", "area": "travel", "turns": ["We're planning a weekend in Edinburgh in December.", "It's me, my partner and our dog.", "What should we pack?", "Are there dog-friendly places to eat near the old town?"]}
|
| 12 |
+
{"id": "multi-012", "area": "travel", "turns": ["I've never been on a plane before and I fly to Spain next month.", "What happens at security?", "Can I take my own sandwiches?", "Thanks, I feel a bit better now."]}
|
| 13 |
+
{"id": "multi-013", "area": "technology", "turns": ["My laptop has started making a loud fan noise.", "It's about four years old.", "What can I do about it myself?", "If that doesn't work, is it worth repairing or should I replace it?"]}
|
| 14 |
+
{"id": "multi-014", "area": "technology", "turns": ["I want to set up a family group chat.", "My mum is 78 and not very good with phones.", "Which app would be easiest for her?", "How do I add her to it?"]}
|
| 15 |
+
{"id": "multi-015", "area": "home", "turns": ["We're moving into our first flat on Saturday.", "We don't have a car.", "What's the cheapest way to move a sofa and a bed?", "What should we do on the first night there?"]}
|
| 16 |
+
{"id": "multi-016", "area": "home", "turns": ["My radiator is cold at the top but hot at the bottom.", "How do I bleed it?", "Do I need to turn the heating off first?"]}
|
| 17 |
+
{"id": "multi-017", "area": "garden", "turns": ["I've just got an allotment.", "It's completely overgrown with weeds.", "Where do I even start?", "What could I plant this month?"]}
|
| 18 |
+
{"id": "multi-018", "area": "pets", "turns": ["We adopted a rescue dog called Biscuit last week.", "He's scared of men and hides under the table.", "How can my husband get him to trust him?", "How long does that usually take with a dog like Biscuit?"]}
|
| 19 |
+
{"id": "multi-019", "area": "pets", "turns": ["My cat has stopped eating her usual food.", "She's 12.", "Should I be worried?"]}
|
| 20 |
+
{"id": "multi-020", "area": "family", "turns": ["My twins are turning six next month.", "They want a joint party but they like completely different things.", "One loves dinosaurs and the other loves space.", "Could you suggest a theme that works for both?"]}
|
| 21 |
+
{"id": "multi-021", "area": "friends", "turns": ["My friend Sam and I had an argument about money.", "I lent him 200 pounds in March and he hasn't mentioned it since.", "How do I bring it up without ruining the friendship?", "What if he says he can't pay it back yet?"]}
|
| 22 |
+
{"id": "multi-022", "area": "entertainment", "turns": ["I'm looking for a TV series to watch with my partner.", "We both liked Line of Duty.", "We're not into anything too gory though.", "Thanks. Which one should we start with tonight?"]}
|
| 23 |
+
{"id": "multi-023", "area": "entertainment", "turns": ["What's your favourite book?", "Why that one?", "What would you recommend for someone who doesn't read much?"]}
|
| 24 |
+
{"id": "multi-024", "area": "sport", "turns": ["I've been asked to coach my son's under-8s football team.", "I've never coached before.", "What should the first training session look like?", "How do I keep them from all chasing the ball at once?"]}
|
| 25 |
+
{"id": "multi-025", "area": "feelings", "turns": ["I didn't get the job I interviewed for last week.", "I really thought I had it.", "I don't know what to do next.", "Thanks. I think I'll ask them for feedback."]}
|
| 26 |
+
{"id": "multi-026", "area": "feelings", "turns": ["I'm nervous about a dentist appointment tomorrow.", "I haven't been in about six years.", "What will they probably do?"]}
|
| 27 |
+
{"id": "multi-027", "area": "small-talk", "turns": ["Hey there!", "Not much, just got back from a walk by the river.", "Saw a heron, which was nice. Do you like birds?", "What's one you'd love to see?"]}
|
| 28 |
+
{"id": "multi-028", "area": "small-talk", "turns": ["Hi, I'm Tom.", "I'm a bus driver in Leeds.", "It's been a long week.", "What do you think I should do this weekend to unwind?", "Good idea. What did I say my job was again?"]}
|
| 29 |
+
{"id": "multi-029", "area": "small-talk", "turns": ["Morning!", "I'm on my second coffee already.", "Do you have any plans today?", "Ha, fair enough. Talk later!"]}
|
| 30 |
+
{"id": "multi-030", "area": "opinions", "turns": ["Do you think it's worth learning a musical instrument as an adult?", "I'm 45 and I've always wanted to play the piano.", "How long before I could play a simple song?"]}
|
| 31 |
+
{"id": "multi-031", "area": "creative", "turns": ["I'm writing a speech for my sister's wedding.", "She's a vet and her husband is a firefighter.", "Can you suggest a funny opening line?", "Can you make it a bit warmer and less jokey?"]}
|
| 32 |
+
{"id": "multi-032", "area": "learning", "turns": ["I want to learn Spanish before a trip in six months.", "I can study about 20 minutes a day.", "What's the best way to spend that time?", "How do you say 'where is the train station'?"]}
|
| 33 |
+
{"id": "multi-033", "area": "learning", "turns": ["What's the difference between a virus and bacteria?", "So do antibiotics work on colds?", "Then what actually helps a cold?"]}
|
| 34 |
+
{"id": "multi-034", "area": "corrections", "turns": ["I'm planning a trip to Rome in July.", "Sorry, I meant Florence, not Rome.", "What should I see there in two days?"]}
|
| 35 |
+
{"id": "multi-035", "area": "corrections", "turns": ["Can you recommend a recipe for dinner?", "Something without meat, please.", "And quick, I've only got 20 minutes."]}
|
| 36 |
+
{"id": "multi-036", "area": "messy-chat", "turns": ["hey", "not much u?", "lol same", "anyway what should i make for dinner, ive got eggs and spinach", "ok sounds good", "thx"]}
|
| 37 |
+
{"id": "multi-037", "area": "messy-chat", "turns": ["I'm off to Japan in March!", "Tokyo and Kyoto", "wait is that cherry blossom season", "ok and do i need a rail pass?", "cool. btw which city did i say first?"]}
|
| 38 |
+
{"id": "multi-038", "area": "messy-chat", "turns": ["Can you help me pick a laptop?", "its for uni, im studying architecture", "under 1000", "actually never mind, how do I boil an egg?", "ok back to the laptop, which would you get?"]}
|
| 39 |
+
{"id": "multi-039", "area": "messy-chat", "turns": ["Are you a bot?", "ha fair. what can you help with?", "ok give me a quick dinner idea", "nah something without cheese"]}
|
| 40 |
+
{"id": "multi-040", "area": "messy-chat", "turns": ["my cat knocked my phone into the bath", "it wont turn on now", "i put it in rice", "how long should i leave it"]}
|
world/seed/deck/single.jsonl
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"id": "single-001", "area": "cooking", "turns": ["I have leftover rice from last night. What can I make with it for lunch?"]}
|
| 2 |
+
{"id": "single-002", "area": "cooking", "turns": ["My scrambled eggs always come out rubbery. What am I doing wrong?"]}
|
| 3 |
+
{"id": "single-003", "area": "cooking", "turns": ["How long should I boil an egg if I want the yolk still a bit runny?"]}
|
| 4 |
+
{"id": "single-004", "area": "cooking", "turns": ["I'm cooking for a friend who is vegan. Any easy main course ideas?"]}
|
| 5 |
+
{"id": "single-005", "area": "food-and-drink", "turns": ["What's the difference between baking soda and baking powder?"]}
|
| 6 |
+
{"id": "single-006", "area": "food-and-drink", "turns": ["I'm trying to drink less coffee. What could I have in the afternoon instead?"]}
|
| 7 |
+
{"id": "single-007", "area": "food-and-drink", "turns": ["Is it safe to eat cooked chicken that was left out overnight?"]}
|
| 8 |
+
{"id": "single-008", "area": "food-and-drink", "turns": ["Which cheeses go well on a cheese board for six people?"]}
|
| 9 |
+
{"id": "single-009", "area": "health", "turns": ["I get headaches most afternoons at work. What could be causing them?"]}
|
| 10 |
+
{"id": "single-010", "area": "health", "turns": ["How much water should an adult drink in a day?"]}
|
| 11 |
+
{"id": "single-011", "area": "health", "turns": ["I cut my finger chopping onions and it won't stop bleeding. What should I do?"]}
|
| 12 |
+
{"id": "single-012", "area": "health", "turns": ["My eyes feel tired after a day at the screen. Anything that helps?"]}
|
| 13 |
+
{"id": "single-013", "area": "fitness", "turns": ["I want to start running but I get out of breath after two minutes. How should I begin?"]}
|
| 14 |
+
{"id": "single-014", "area": "fitness", "turns": ["What's a good stretch for a stiff lower back after sitting all day?"]}
|
| 15 |
+
{"id": "single-015", "area": "fitness", "turns": ["Is it better to work out in the morning or the evening?"]}
|
| 16 |
+
{"id": "single-016", "area": "fitness", "turns": ["I only have 20 minutes a day. What kind of workout gets the most out of that?"]}
|
| 17 |
+
{"id": "single-017", "area": "sleep", "turns": ["My toddler wakes up at 5am every day. Is there a way to shift that later?"]}
|
| 18 |
+
{"id": "single-018", "area": "sleep", "turns": ["I keep waking up at 3am and can't get back to sleep. Any advice?"]}
|
| 19 |
+
{"id": "single-019", "area": "sleep", "turns": ["Is it bad to sleep with the TV on?"]}
|
| 20 |
+
{"id": "single-020", "area": "money", "turns": ["I want to save for a holiday next summer. How should I go about it on a small salary?"]}
|
| 21 |
+
{"id": "single-021", "area": "money", "turns": ["What's the difference between a credit card and a debit card?"]}
|
| 22 |
+
{"id": "single-022", "area": "money", "turns": ["My energy bills have gone up a lot. What are some quick ways to cut them?"]}
|
| 23 |
+
{"id": "single-023", "area": "money", "turns": ["Is it worth paying off a small loan early?"]}
|
| 24 |
+
{"id": "single-024", "area": "work", "turns": ["I have a job interview on Thursday for an office manager role. What questions should I prepare for?"]}
|
| 25 |
+
{"id": "single-025", "area": "work", "turns": ["How do I politely tell my boss I have too much on my plate?"]}
|
| 26 |
+
{"id": "single-026", "area": "work", "turns": ["My colleague keeps taking credit for my ideas in meetings. How should I handle it?"]}
|
| 27 |
+
{"id": "single-027", "area": "work", "turns": ["What should I put in a two-line bio for a conference badge? I'm a nurse."]}
|
| 28 |
+
{"id": "single-028", "area": "school-and-study", "turns": ["I have a history exam in two weeks and I keep putting off revising. How do I get started?"]}
|
| 29 |
+
{"id": "single-029", "area": "school-and-study", "turns": ["What's a good way to remember vocabulary for a French test?"]}
|
| 30 |
+
{"id": "single-030", "area": "school-and-study", "turns": ["My son is struggling with fractions. How can I explain them simply?"]}
|
| 31 |
+
{"id": "single-031", "area": "school-and-study", "turns": ["How do I write a good opening sentence for an essay?"]}
|
| 32 |
+
{"id": "single-032", "area": "science", "turns": ["Why is the sky blue?"]}
|
| 33 |
+
{"id": "single-033", "area": "science", "turns": ["How do vaccines teach the body to fight a disease?"]}
|
| 34 |
+
{"id": "single-034", "area": "science", "turns": ["What's the difference between weather and climate?"]}
|
| 35 |
+
{"id": "single-035", "area": "science", "turns": ["Why does ice float on water?"]}
|
| 36 |
+
{"id": "single-036", "area": "science", "turns": ["How do plants make their food?"]}
|
| 37 |
+
{"id": "single-037", "area": "history", "turns": ["Who built the pyramids of Giza, and roughly when?"]}
|
| 38 |
+
{"id": "single-038", "area": "history", "turns": ["What was the Industrial Revolution in a nutshell?"]}
|
| 39 |
+
{"id": "single-039", "area": "history", "turns": ["Why did the Roman Empire split into east and west?"]}
|
| 40 |
+
{"id": "single-040", "area": "history", "turns": ["When did people first land on the Moon?"]}
|
| 41 |
+
{"id": "single-041", "area": "geography-and-travel", "turns": ["I'm going to Lisbon for three days in May. What shouldn't I miss?"]}
|
| 42 |
+
{"id": "single-042", "area": "geography-and-travel", "turns": ["What's the best way to get over jet lag after a long flight east?"]}
|
| 43 |
+
{"id": "single-043", "area": "geography-and-travel", "turns": ["What's the capital of Australia? I always mix it up with Sydney."]}
|
| 44 |
+
{"id": "single-044", "area": "geography-and-travel", "turns": ["We're driving through France with two kids. Any tips for a long car journey?"]}
|
| 45 |
+
{"id": "single-045", "area": "technology", "turns": ["My phone battery drains really fast lately. What can I check?"]}
|
| 46 |
+
{"id": "single-046", "area": "technology", "turns": ["What's a password manager and should I use one?"]}
|
| 47 |
+
{"id": "single-047", "area": "technology", "turns": ["How do I take a screenshot on a Windows laptop?"]}
|
| 48 |
+
{"id": "single-048", "area": "technology", "turns": ["My Wi-Fi keeps dropping in the bedroom. How can I improve the signal?"]}
|
| 49 |
+
{"id": "single-049", "area": "home-and-diy", "turns": ["There's mould on my bathroom ceiling. How do I get rid of it and stop it coming back?"]}
|
| 50 |
+
{"id": "single-050", "area": "home-and-diy", "turns": ["How do I unblock a slow kitchen sink without calling a plumber?"]}
|
| 51 |
+
{"id": "single-051", "area": "home-and-diy", "turns": ["I want to paint my living room. What do I need besides paint?"]}
|
| 52 |
+
{"id": "single-052", "area": "home-and-diy", "turns": ["What's the easiest way to get red wine out of a carpet?"]}
|
| 53 |
+
{"id": "single-053", "area": "garden-and-plants", "turns": ["The leaves on my basil plant are turning yellow. What's wrong with it?"]}
|
| 54 |
+
{"id": "single-054", "area": "garden-and-plants", "turns": ["What vegetables are easy to grow on a balcony?"]}
|
| 55 |
+
{"id": "single-055", "area": "garden-and-plants", "turns": ["When should I plant tulip bulbs?"]}
|
| 56 |
+
{"id": "single-056", "area": "pets", "turns": ["We're getting a kitten next week. What do we need to buy?"]}
|
| 57 |
+
{"id": "single-057", "area": "pets", "turns": ["My dog pulls on the lead all the time. How do I train him out of it?"]}
|
| 58 |
+
{"id": "single-058", "area": "pets", "turns": ["Is chocolate really dangerous for dogs?"]}
|
| 59 |
+
{"id": "single-059", "area": "pets", "turns": ["How often should I clean my goldfish tank?"]}
|
| 60 |
+
{"id": "single-060", "area": "family-and-parenting", "turns": ["My daughter is starting secondary school and she's nervous. How can I help her settle in?"]}
|
| 61 |
+
{"id": "single-061", "area": "family-and-parenting", "turns": ["What are some fun things to do with kids on a rainy Saturday?"]}
|
| 62 |
+
{"id": "single-062", "area": "family-and-parenting", "turns": ["My parents are visiting for a week and our flat is small. Any tips to keep everyone sane?"]}
|
| 63 |
+
{"id": "single-063", "area": "friends-and-relationships", "turns": ["My best friend forgot my birthday. Should I say something?"]}
|
| 64 |
+
{"id": "single-064", "area": "friends-and-relationships", "turns": ["I just moved to a new city and don't know anyone. How do people make friends as adults?"]}
|
| 65 |
+
{"id": "single-065", "area": "friends-and-relationships", "turns": ["What's a thoughtful anniversary gift that doesn't cost much?"]}
|
| 66 |
+
{"id": "single-066", "area": "shopping", "turns": ["I need a new laptop mainly for writing and video calls. What should I look for?"]}
|
| 67 |
+
{"id": "single-067", "area": "shopping", "turns": ["Are expensive running shoes actually worth it?"]}
|
| 68 |
+
{"id": "single-068", "area": "shopping", "turns": ["What should I check before buying a second-hand bike?"]}
|
| 69 |
+
{"id": "single-069", "area": "entertainment", "turns": ["Can you recommend a funny film for a family night? The kids are 8 and 11."]}
|
| 70 |
+
{"id": "single-070", "area": "entertainment", "turns": ["I loved The Martian. What should I read next?"]}
|
| 71 |
+
{"id": "single-071", "area": "entertainment", "turns": ["What's a good board game for four adults who don't like long rules?"]}
|
| 72 |
+
{"id": "single-072", "area": "entertainment", "turns": ["I need a new podcast for my commute. I like history and true stories."]}
|
| 73 |
+
{"id": "single-073", "area": "sport", "turns": ["How does the offside rule work in football?"]}
|
| 74 |
+
{"id": "single-074", "area": "sport", "turns": ["I want to watch my first cricket match. What should I know?"]}
|
| 75 |
+
{"id": "single-075", "area": "sport", "turns": ["Who has won the most Wimbledon titles?"]}
|
| 76 |
+
{"id": "single-076", "area": "language-and-writing", "turns": ["What's the difference between 'affect' and 'effect'?"]}
|
| 77 |
+
{"id": "single-077", "area": "language-and-writing", "turns": ["Can you help me word a text cancelling dinner with a friend without sounding rude?"]}
|
| 78 |
+
{"id": "single-078", "area": "language-and-writing", "turns": ["Is it 'fewer people' or 'less people'?"]}
|
| 79 |
+
{"id": "single-079", "area": "feelings", "turns": ["I've been feeling really lonely since I started working from home."]}
|
| 80 |
+
{"id": "single-080", "area": "feelings", "turns": ["I failed my driving test today and I feel like an idiot."]}
|
| 81 |
+
{"id": "single-081", "area": "feelings", "turns": ["I'm so stressed about moving house next week."]}
|
| 82 |
+
{"id": "single-082", "area": "small-talk", "turns": ["Hi! How's your day going?"]}
|
| 83 |
+
{"id": "single-083", "area": "small-talk", "turns": ["Good morning. It's freezing here today."]}
|
| 84 |
+
{"id": "single-084", "area": "small-talk", "turns": ["I finally finished that jigsaw I've been doing for a month!"]}
|
| 85 |
+
{"id": "single-085", "area": "small-talk", "turns": ["Thanks, that's really helpful."]}
|
| 86 |
+
{"id": "single-086", "area": "opinions", "turns": ["What do you think is the best season of the year?"]}
|
| 87 |
+
{"id": "single-087", "area": "opinions", "turns": ["Cats or dogs?"]}
|
| 88 |
+
{"id": "single-088", "area": "opinions", "turns": ["Is it ever OK to recline your seat on a plane?"]}
|
| 89 |
+
{"id": "single-089", "area": "creative", "turns": ["Can you write a short poem about autumn for my daughter's card?"]}
|
| 90 |
+
{"id": "single-090", "area": "creative", "turns": ["I need a name for my new sourdough starter. Any ideas?"]}
|
| 91 |
+
{"id": "single-091", "area": "creative", "turns": ["Tell me a joke about cheese."]}
|
| 92 |
+
{"id": "single-092", "area": "maths-and-numbers", "turns": ["What's 15% of 80?"]}
|
| 93 |
+
{"id": "single-093", "area": "maths-and-numbers", "turns": ["If I drive 120 miles at 60 miles an hour, how long will it take?"]}
|
| 94 |
+
{"id": "single-094", "area": "maths-and-numbers", "turns": ["How many weeks are there in a year, exactly?"]}
|
| 95 |
+
{"id": "single-095", "area": "nature-and-weather", "turns": ["Why do leaves change colour in autumn?"]}
|
| 96 |
+
{"id": "single-096", "area": "nature-and-weather", "turns": ["What should I do if I'm caught outside in a thunderstorm?"]}
|
| 97 |
+
{"id": "single-097", "area": "nature-and-weather", "turns": ["Which birds might I see in a city park in winter?"]}
|
| 98 |
+
{"id": "single-098", "area": "messy-typing", "turns": ["wats the best way to cook rice so its not sticky"]}
|
| 99 |
+
{"id": "single-099", "area": "messy-typing", "turns": ["how do i get my baby to sleep thru the night"]}
|
| 100 |
+
{"id": "single-100", "area": "messy-typing", "turns": ["recomend me a good scifi book pls"]}
|
| 101 |
+
{"id": "single-101", "area": "messy-typing", "turns": ["whats the wether usually like in rome in april"]}
|
| 102 |
+
{"id": "single-102", "area": "messy-typing", "turns": ["cn u help me write a msg to my landlord about the broken boiler"]}
|
| 103 |
+
{"id": "single-103", "area": "messy-typing", "turns": ["idk what to get my dad for his 60th, he likes fishing and old films"]}
|
| 104 |
+
{"id": "single-104", "area": "about-the-bot", "turns": ["Are you a real person?"]}
|
| 105 |
+
{"id": "single-105", "area": "about-the-bot", "turns": ["What are you?"]}
|
| 106 |
+
{"id": "single-106", "area": "about-the-bot", "turns": ["Do you remember what we talked about yesterday?"]}
|
| 107 |
+
{"id": "single-107", "area": "about-the-bot", "turns": ["What kind of things can you help with?"]}
|
world/seed/tests/test_architecture.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from bot import runtime
|
| 4 |
+
from bot.compose import pick
|
| 5 |
+
from bot.memory import user
|
| 6 |
+
from bot.understanding import understand
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ArchitectureTest(unittest.TestCase):
|
| 10 |
+
def test_understanding_reads_the_kind_of_line(self):
|
| 11 |
+
kinds = {"": "empty", "hey there": "greeting", "Good morning!": "greeting",
|
| 12 |
+
"thx so much": "thanks", "can u help me": "question", "Is it far?": "question",
|
| 13 |
+
"I just got a puppy": "statement"}
|
| 14 |
+
for text, kind in kinds.items():
|
| 15 |
+
self.assertEqual(understand(text, {})["kind"], kind, text)
|
| 16 |
+
|
| 17 |
+
def test_every_module_sees_this_turns_understanding(self):
|
| 18 |
+
memory = {}
|
| 19 |
+
runtime.turn("Where is Lisbon?", memory)
|
| 20 |
+
self.assertEqual(memory["understood"]["kind"], "question")
|
| 21 |
+
self.assertEqual(memory["understood"]["words"], ["where", "is", "lisbon"])
|
| 22 |
+
|
| 23 |
+
def test_memory_and_compose_helpers(self):
|
| 24 |
+
memory = {}
|
| 25 |
+
user(memory)["name"] = "Sam"
|
| 26 |
+
self.assertEqual(memory["user"], {"name": "Sam"})
|
| 27 |
+
memory["turns"] = [{"user": "hi", "bot": "Hi!", "module": "greeting"}]
|
| 28 |
+
self.assertEqual(pick(["Hi!", "Hello!"], memory), "Hello!")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if __name__ == "__main__":
|
| 32 |
+
unittest.main()
|
world/seed/tests/test_compare.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import subprocess
|
| 3 |
+
import sys
|
| 4 |
+
import tempfile
|
| 5 |
+
import unittest
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def compare(*args):
|
| 12 |
+
return subprocess.run([sys.executable, str(ROOT / "tools/compare.py"), *args], capture_output=True,
|
| 13 |
+
text=True, cwd=ROOT, timeout=600, check=False)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CompareTest(unittest.TestCase):
|
| 17 |
+
def test_a_checkout_compared_with_itself_changes_nothing(self):
|
| 18 |
+
result = compare(str(ROOT), str(ROOT), "--sample", "6", "--seed", "1")
|
| 19 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 20 |
+
self.assertIn("no reply changed", result.stdout)
|
| 21 |
+
|
| 22 |
+
def test_score_counts_head_better_and_worse_with_the_key(self):
|
| 23 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 24 |
+
key = Path(tmp) / "k.key"
|
| 25 |
+
key.write_text(json.dumps({"seed": 3, "items": ["a", "b", "c"],
|
| 26 |
+
"key": ["head=1", "head=2", "head=1"]}))
|
| 27 |
+
result = compare("--score", str(key), "1 1 =")
|
| 28 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 29 |
+
self.assertIn("head better 1, base better 1, same 1", result.stdout)
|
| 30 |
+
self.assertIn("head worse on: b", result.stdout)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == "__main__":
|
| 34 |
+
unittest.main()
|
world/seed/tests/test_deck.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
DECK = Path(__file__).resolve().parents[1] / "deck"
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class DeckTest(unittest.TestCase):
|
| 9 |
+
def test_conversations_are_well_formed_and_ids_unique(self):
|
| 10 |
+
seen = set()
|
| 11 |
+
for path in sorted(DECK.glob("*.jsonl")):
|
| 12 |
+
for n, line in enumerate(path.read_text().splitlines(), 1):
|
| 13 |
+
item = json.loads(line)
|
| 14 |
+
where = f"{path.name}:{n}"
|
| 15 |
+
self.assertEqual(set(item), {"id", "area", "turns"}, where)
|
| 16 |
+
self.assertNotIn(item["id"], seen, where)
|
| 17 |
+
seen.add(item["id"])
|
| 18 |
+
self.assertTrue(item["area"].strip(), where)
|
| 19 |
+
self.assertTrue(item["turns"], where)
|
| 20 |
+
for text in item["turns"]:
|
| 21 |
+
self.assertTrue(isinstance(text, str) and text.strip() and "\n" not in text, where)
|
| 22 |
+
self.assertTrue(seen)
|
| 23 |
+
|
| 24 |
+
def test_single_and_multi_turn_files_hold_their_kind(self):
|
| 25 |
+
for name, multi in (("single.jsonl", False), ("multi.jsonl", True)):
|
| 26 |
+
for line in (DECK / name).read_text().splitlines():
|
| 27 |
+
self.assertEqual(len(json.loads(line)["turns"]) > 1, multi, line)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
unittest.main()
|
world/seed/tests/test_interface.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import sys
|
| 3 |
+
import unittest
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class InterfaceTest(unittest.TestCase):
|
| 10 |
+
def test_one_nonempty_reply_per_input(self):
|
| 11 |
+
result = subprocess.run([sys.executable, "-m", "bot"], input="hi\n\nbye\n",
|
| 12 |
+
text=True, capture_output=True, cwd=ROOT, timeout=300, check=False)
|
| 13 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 14 |
+
self.assertEqual(len(result.stdout.splitlines()), 3)
|
| 15 |
+
self.assertTrue(all(line.strip() for line in result.stdout.splitlines()))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if __name__ == "__main__":
|
| 19 |
+
unittest.main()
|
world/seed/tests/test_runtime.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from bot import runtime
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class RuntimeTest(unittest.TestCase):
|
| 7 |
+
def test_every_turn_gets_a_reply_and_is_recorded(self):
|
| 8 |
+
memory = {}
|
| 9 |
+
for text in ("hi", "", "how are you?"):
|
| 10 |
+
self.assertTrue(runtime.reply(text, memory).strip())
|
| 11 |
+
self.assertEqual([t["user"] for t in memory["turns"]], ["hi", "", "how are you?"])
|
| 12 |
+
|
| 13 |
+
def test_turn_names_the_chosen_module_and_every_candidate(self):
|
| 14 |
+
t = runtime.turn("hello", {})
|
| 15 |
+
self.assertIn(t["module"], [c["module"] for c in t["candidates"]])
|
| 16 |
+
self.assertEqual(t["reply"], next(c["reply"] for c in t["candidates"] if c["module"] == t["module"]))
|
| 17 |
+
priorities = [c["priority"] for c in t["candidates"]]
|
| 18 |
+
self.assertEqual(priorities, sorted(priorities, reverse=True))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if __name__ == "__main__":
|
| 22 |
+
unittest.main()
|
world/seed/tools/compare.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare two checkouts of the bot on a random sample of the deck, blind.
|
| 2 |
+
|
| 3 |
+
git worktree add ../base origin/main # the checkout to compare against
|
| 4 |
+
python tools/compare.py ../base . --seed 41 # base, then head (this clone)
|
| 5 |
+
python tools/compare.py --score /tmp/compare-41.key "1 2 = 2 1"
|
| 6 |
+
|
| 7 |
+
The first command runs both bots on the same deck conversations (deck/*.jsonl in head) and
|
| 8 |
+
prints every turn whose reply changed: single turns as pairs, multi-turn conversations as two
|
| 9 |
+
whole transcripts. Which side is which is random and written to a key file, not printed. Judge
|
| 10 |
+
each item by STYLE.md, in order, with 1, 2 or = (no better), then score the verdicts with the
|
| 11 |
+
key: the second command prints how often head was better and worse. --sample 0 runs the
|
| 12 |
+
whole deck. The summary also counts which modules answer more or fewer turns in head.
|
| 13 |
+
"""
|
| 14 |
+
import argparse
|
| 15 |
+
import collections
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import random
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
import tempfile
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
DRIVER = r'''
|
| 25 |
+
import json, os, sys
|
| 26 |
+
sys.path.insert(0, os.getcwd())
|
| 27 |
+
sys.dont_write_bytecode = True
|
| 28 |
+
import bot.runtime as runtime
|
| 29 |
+
|
| 30 |
+
def run(turns):
|
| 31 |
+
memory, out = {}, []
|
| 32 |
+
for text in turns:
|
| 33 |
+
if hasattr(runtime, "turn"):
|
| 34 |
+
t = runtime.turn(text, memory)
|
| 35 |
+
out.append({"reply": t["reply"], "module": t["module"], "candidates": len(t["candidates"])})
|
| 36 |
+
else:
|
| 37 |
+
out.append({"reply": runtime.reply(text, memory), "module": None, "candidates": None})
|
| 38 |
+
return out
|
| 39 |
+
|
| 40 |
+
for line in sys.stdin:
|
| 41 |
+
turns = json.loads(line)
|
| 42 |
+
read, write = os.pipe()
|
| 43 |
+
pid = os.fork() # every conversation starts from the freshly loaded bot, as in production
|
| 44 |
+
if pid == 0:
|
| 45 |
+
os.close(read)
|
| 46 |
+
try:
|
| 47 |
+
data = json.dumps(run(turns))
|
| 48 |
+
except BaseException as exc:
|
| 49 |
+
data = json.dumps({"error": f"{type(exc).__name__}: {exc}"})
|
| 50 |
+
with os.fdopen(write, "w") as f:
|
| 51 |
+
f.write(data)
|
| 52 |
+
os._exit(0)
|
| 53 |
+
os.close(write)
|
| 54 |
+
with os.fdopen(read) as f:
|
| 55 |
+
data = f.read()
|
| 56 |
+
os.waitpid(pid, 0)
|
| 57 |
+
print(data or json.dumps({"error": "the conversation crashed"}), flush=True)
|
| 58 |
+
'''
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def load_deck(root):
|
| 62 |
+
items = []
|
| 63 |
+
for path in sorted((Path(root) / "deck").glob("*.jsonl")):
|
| 64 |
+
for line in path.read_text().splitlines():
|
| 65 |
+
if line.strip():
|
| 66 |
+
items.append(json.loads(line))
|
| 67 |
+
return items
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def sample(deck, n, seed, multi_share):
|
| 71 |
+
rng = random.Random(seed)
|
| 72 |
+
if n <= 0 or n >= len(deck):
|
| 73 |
+
return list(deck)
|
| 74 |
+
multi = [c for c in deck if len(c["turns"]) > 1]
|
| 75 |
+
single = [c for c in deck if len(c["turns"]) == 1]
|
| 76 |
+
k = min(len(multi), round(n * multi_share))
|
| 77 |
+
picked = rng.sample(multi, k) + rng.sample(single, min(len(single), n - k))
|
| 78 |
+
return sorted(picked, key=lambda c: c["id"])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def run_bot(root, conversations, timeout):
|
| 82 |
+
lines = "".join(json.dumps(c["turns"]) + "\n" for c in conversations)
|
| 83 |
+
p = subprocess.run([sys.executable, "-c", DRIVER], input=lines, text=True, capture_output=True,
|
| 84 |
+
cwd=root, timeout=timeout, check=False)
|
| 85 |
+
results = [json.loads(line) for line in p.stdout.splitlines() if line.strip()]
|
| 86 |
+
if p.returncode or len(results) != len(conversations):
|
| 87 |
+
raise SystemExit(f"the bot in {root} failed:\n{p.stderr[-2000:]}")
|
| 88 |
+
return results
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def revision(root):
|
| 92 |
+
p = subprocess.run(["git", "-C", str(root), "rev-parse", "--short", "HEAD"], capture_output=True,
|
| 93 |
+
text=True, check=False)
|
| 94 |
+
dirty = subprocess.run(["git", "-C", str(root), "status", "--porcelain"], capture_output=True,
|
| 95 |
+
text=True, check=False).stdout.strip()
|
| 96 |
+
return (p.stdout.strip() or "?") + (" + local changes" if dirty else "")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def transcript(turns, replies):
|
| 100 |
+
return "\n".join(f" User: {text}\n Bot: {r['reply']}" for text, r in zip(turns, replies, strict=True))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def compare(args):
|
| 104 |
+
deck = load_deck(args.head)
|
| 105 |
+
if not deck:
|
| 106 |
+
raise SystemExit(f"no deck in {args.head}/deck")
|
| 107 |
+
picked = sample(deck, args.sample, args.seed, args.multi_share)
|
| 108 |
+
base = run_bot(args.base, picked, args.timeout)
|
| 109 |
+
head = run_bot(args.head, picked, args.timeout)
|
| 110 |
+
rng = random.Random(f"{args.seed}-order")
|
| 111 |
+
items, key, crashes = [], [], []
|
| 112 |
+
moved, answers = collections.Counter(), collections.Counter()
|
| 113 |
+
turns = changed = 0
|
| 114 |
+
for conv, b, h in zip(picked, base, head, strict=True):
|
| 115 |
+
if "error" in b or "error" in h:
|
| 116 |
+
crashes.append(f"{conv['id']}: base {b.get('error', 'ok')}; head {h.get('error', 'ok')}")
|
| 117 |
+
continue
|
| 118 |
+
turns += len(conv["turns"])
|
| 119 |
+
diff = [i for i, (x, y) in enumerate(zip(b, h, strict=True)) if x["reply"] != y["reply"]]
|
| 120 |
+
changed += len(diff)
|
| 121 |
+
for x, y in zip(b, h, strict=True):
|
| 122 |
+
answers[x["module"]] -= 1
|
| 123 |
+
answers[y["module"]] += 1
|
| 124 |
+
if x["module"] != y["module"]:
|
| 125 |
+
moved[(x["module"], y["module"])] += 1
|
| 126 |
+
if not diff:
|
| 127 |
+
continue
|
| 128 |
+
head_first = rng.random() < 0.5
|
| 129 |
+
key.append("head=1" if head_first else "head=2")
|
| 130 |
+
first, second = (h, b) if head_first else (b, h)
|
| 131 |
+
if len(conv["turns"]) == 1:
|
| 132 |
+
text = f" User: {conv['turns'][0]}\n 1: {first[0]['reply']}\n 2: {second[0]['reply']}"
|
| 133 |
+
else:
|
| 134 |
+
text = (f" Conversation 1:\n{transcript(conv['turns'], first)}\n"
|
| 135 |
+
f" Conversation 2:\n{transcript(conv['turns'], second)}")
|
| 136 |
+
items.append((conv, diff, text))
|
| 137 |
+
singles = sum(1 for c in picked if len(c["turns"]) == 1)
|
| 138 |
+
print(f"base {args.base} ({revision(args.base)}) vs head {args.head} ({revision(args.head)})")
|
| 139 |
+
print(f"deck sample: {len(picked)} conversations (seed {args.seed}), {singles} single-turn, "
|
| 140 |
+
f"{len(picked) - singles} multi-turn; {changed} of {turns} replies changed")
|
| 141 |
+
gained = [f"{m or '(none)'} {n:+d}" for m, n in answers.most_common() if n > 0]
|
| 142 |
+
lost = [f"{m or '(none)'} {n:+d}" for m, n in reversed(answers.most_common()) if n < 0]
|
| 143 |
+
if gained or lost:
|
| 144 |
+
print(f"turns answered, head vs base: {', '.join(gained + lost)}")
|
| 145 |
+
for (was, now), n in moved.most_common(8):
|
| 146 |
+
print(f" {n} turn(s) moved from {was or '(none)'} to {now or '(none)'}")
|
| 147 |
+
for crash in crashes:
|
| 148 |
+
print(f"CRASHED {crash}")
|
| 149 |
+
if not items:
|
| 150 |
+
print("no reply changed")
|
| 151 |
+
return
|
| 152 |
+
print("\nJudge each item by STYLE.md: which would you rather get? Answer 1, 2 or = per item.\n")
|
| 153 |
+
for i, (conv, diff, text) in enumerate(items, 1):
|
| 154 |
+
where = "" if len(conv["turns"]) == 1 else f", turns {', '.join(str(d + 1) for d in diff)} changed"
|
| 155 |
+
print(f"[{i}] {conv['id']} ({conv['area']}){where}\n{text}\n")
|
| 156 |
+
path = Path(args.key or Path(tempfile.gettempdir()) / f"compare-{args.seed}.key")
|
| 157 |
+
path.write_text(json.dumps({"seed": args.seed, "items": [c["id"] for c, _, _ in items], "key": key}))
|
| 158 |
+
print(f"key: {path} (score with: python tools/compare.py --score {path} \"<verdicts>\")")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def score(path, verdicts):
|
| 162 |
+
data = json.loads(Path(path).read_text())
|
| 163 |
+
marks = verdicts.replace(",", " ").split()
|
| 164 |
+
if len(marks) != len(data["key"]):
|
| 165 |
+
raise SystemExit(f"give one verdict per item ({len(data['key'])}), got {len(marks)}")
|
| 166 |
+
better, worse, same = [], [], []
|
| 167 |
+
for k, item, m in zip(data["key"], data["items"], marks, strict=True):
|
| 168 |
+
if m == "=":
|
| 169 |
+
same.append(item)
|
| 170 |
+
elif m in ("1", "2"):
|
| 171 |
+
(better if k == f"head={m}" else worse).append(item)
|
| 172 |
+
else:
|
| 173 |
+
raise SystemExit(f"verdicts are 1, 2 or =, got {m!r}")
|
| 174 |
+
print(f"seed {data['seed']}: head better {len(better)}, base better {len(worse)}, same {len(same)}")
|
| 175 |
+
if worse:
|
| 176 |
+
print(f"head worse on: {', '.join(worse)}")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def main():
|
| 180 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 181 |
+
parser.add_argument("base", nargs="?", help="checkout to compare against (e.g. a worktree of origin/main)")
|
| 182 |
+
parser.add_argument("head", nargs="?", default=".", help="checkout to test (default: this clone)")
|
| 183 |
+
parser.add_argument("--sample", type=int, default=40, help="conversations to run (0: the whole deck)")
|
| 184 |
+
parser.add_argument("--seed", type=int, default=None, help="sample seed (default: random)")
|
| 185 |
+
parser.add_argument("--multi-share", type=float, default=0.4, help="share of multi-turn conversations")
|
| 186 |
+
parser.add_argument("--timeout", type=float, default=600, help="seconds per bot")
|
| 187 |
+
parser.add_argument("--key", help="where to write the key (default: the temp directory)")
|
| 188 |
+
parser.add_argument("--score", nargs=2, metavar=("KEY", "VERDICTS"), help="score verdicts with a key")
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
if args.score:
|
| 191 |
+
return score(*args.score)
|
| 192 |
+
if not args.base:
|
| 193 |
+
parser.error("give the base checkout (and optionally head), or --score KEY VERDICTS")
|
| 194 |
+
if args.seed is None:
|
| 195 |
+
args.seed = random.SystemRandom().randrange(1, 10000)
|
| 196 |
+
args.base, args.head = os.path.abspath(args.base), os.path.abspath(args.head)
|
| 197 |
+
compare(args)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
main()
|
world/snapshot.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One archive for world state; agent clones live in their own worker snapshots."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
import tarfile
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path, PurePosixPath
|
| 11 |
+
|
| 12 |
+
from flock.worker.sync import HubBucketStore
|
| 13 |
+
from flock.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)
|
| 25 |
+
workspace.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
with tempfile.TemporaryDirectory(dir=workspace.parent) as tmp:
|
| 27 |
+
archive = Path(tmp) / "world.tar.gz"
|
| 28 |
+
if mode == "push":
|
| 29 |
+
bundle = Path(tmp) / "repo.bundle"
|
| 30 |
+
subprocess.run(["git", "-C", str(workspace / "repo.git"), "bundle", "create",
|
| 31 |
+
str(bundle), "--all"], check=True, capture_output=True)
|
| 32 |
+
with tarfile.open(archive, "w:gz", compresslevel=1) as out:
|
| 33 |
+
out.add(bundle, arcname="repo.bundle")
|
| 34 |
+
if (workspace / "state.db").exists():
|
| 35 |
+
backup_to(workspace / "state.db", Path(tmp) / "state.db")
|
| 36 |
+
out.add(Path(tmp) / "state.db", arcname="state.db")
|
| 37 |
+
for name in FILES[2:]:
|
| 38 |
+
if (workspace / name).exists():
|
| 39 |
+
out.add(workspace / name, arcname=name)
|
| 40 |
+
store.upload([(archive, "world.tar.gz")])
|
| 41 |
+
else:
|
| 42 |
+
store.download([("world.tar.gz", archive)])
|
| 43 |
+
if mode == "restore":
|
| 44 |
+
with tarfile.open(archive, "r:gz") as source:
|
| 45 |
+
for member in source.getmembers():
|
| 46 |
+
path = PurePosixPath(member.name)
|
| 47 |
+
if (path.is_absolute() or ".." in path.parts or not path.parts
|
| 48 |
+
or path.parts[0] not in FILES or not (member.isfile() or member.isdir())):
|
| 49 |
+
raise ValueError("unexpected world archive entry")
|
| 50 |
+
target = workspace / path
|
| 51 |
+
if member.isdir():
|
| 52 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 53 |
+
else:
|
| 54 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
for wal in ("-wal", "-shm"): # a stale WAL would replay onto the restored db
|
| 56 |
+
target.with_name(target.name + wal).unlink(missing_ok=True)
|
| 57 |
+
with source.extractfile(member) as src, target.open("wb") as dst:
|
| 58 |
+
shutil.copyfileobj(src, dst)
|
| 59 |
+
|
| 60 |
+
return True
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 65 |
+
parser.add_argument("mode", choices=["push", "restore"])
|
| 66 |
+
parser.add_argument("workspace")
|
| 67 |
+
parser.add_argument("bucket")
|
| 68 |
+
args = parser.parse_args()
|
| 69 |
+
if not transfer(args.mode, args.workspace, args.bucket):
|
| 70 |
+
raise SystemExit(3)
|
world/source-lock.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"flock_repo": "https://github.com/huggingface/flock",
|
| 3 |
+
"flock_commit": "aaab415cbf59efeec3294e1d014c9ac69db5e390",
|
| 4 |
+
"files": {
|
| 5 |
+
"src/flock/__init__.py": "f26caf93ebbf4da0e48361700fbd1b03ab8e18cf7aa7fb810d023002937b121a",
|
| 6 |
+
"src/flock/isolation.py": "35a563e532802a12ca44f84e22652d740139ea6dc92061ccfba9d59ede29f560",
|
| 7 |
+
"src/flock/models.py": "43c1101112c689f71475400fe61ee6a6c8c6fd15388c65b656cd3308082702c9",
|
| 8 |
+
"src/flock/registry.py": "fe27642c50f25a7a4c9b20e5006b4117d755b2a9ae474a8726a0d9861a5445e8",
|
| 9 |
+
"src/flock/tools/__init__.py": "9bb7c72a7a563a9086a12f52399bbca74250c498c09b428d6c7b56cb83b406ee",
|
| 10 |
+
"src/flock/tools/loader.py": "a383c95a8910f322373511425ac06a0f152a818e57ab9eefa3eceda934bcd826",
|
| 11 |
+
"src/flock/worker/__init__.py": "c4afc77bc9a814ffb811300094c36e0706c2a6a025703241c69688e3c5d2ff83",
|
| 12 |
+
"src/flock/worker/sync.py": "90e10862f5b772017460a752c8afb6340c747a6d7a63dbab91c295afe1a49b96",
|
| 13 |
+
"src/flock/world/__init__.py": "d9cd12d59e039b7b91c88e978a2b7dcaa657d9f9bb7524835b947348d7829449",
|
| 14 |
+
"src/flock/world/admin.py": "93b04d68199239c5c80c981d5e2ae320fbff28da26da6b1cb3cd5eb0765d1562",
|
| 15 |
+
"src/flock/world/lanes.py": "f43ff7bfc91c17c48fa73e99fa6e172323b7b158524422b7c3b2d4254680bc47",
|
| 16 |
+
"src/flock/world/protocol.py": "94250d3b2c6b8dae8ac61de339044694ee3a72aec832c2df369c11b1b79363a9",
|
| 17 |
+
"src/flock/world/server.py": "03665b24ae28ce8e9be951aeca8546721cea9771fdd13ecec87f77b43ae3a848",
|
| 18 |
+
"src/flock/world/store.py": "1984943b9c4a8ca05a717f8dd49aa06b04930eae8d96babe60c2e2ed4f6f7d51",
|
| 19 |
+
"src/flock/world/workspace.py": "c861b98c3f2603cfdc478f92547e7b8b83faaf5f1e292732c86cc51b7b26ee1a"
|
| 20 |
+
},
|
| 21 |
+
"requirements.txt": "bcc4c96105fcc7eb7b311e32a341d69c669addcb1482d6d7bf59b33043a20bf1"
|
| 22 |
+
}
|
world/src/flock/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""flock: host coding-harness agent swarms on Hugging Face Jobs."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.0.1"
|
world/src/flock/isolation.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Linux process isolation for harness and bot 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 = "FLOCK_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 enabled() -> bool:
|
| 59 |
+
return os.environ.get("FLOCK_PROCESS_ISOLATION") == "1"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _libc():
|
| 63 |
+
return ctypes.CDLL(None, use_errno=True)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def protect_supervisor() -> None:
|
| 67 |
+
"""Deny same-UID ptrace and /proc/<pid>/{environ,mem,root} on worker/world."""
|
| 68 |
+
if not sys.platform.startswith("linux") or _libc().prctl(4, 0, 0, 0, 0) != 0:
|
| 69 |
+
raise RuntimeError("PR_SET_DUMPABLE=0 is required for process isolation")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def tmpfs_size(env=os.environ) -> str:
|
| 73 |
+
"""The size cap of a sandbox's tmpfs root: $FLOCK_ISOLATION_TMPFS_SIZE (bytes, or with a
|
| 74 |
+
k/m/g suffix; never unlimited), else 256m. An unusable value falls back to the default."""
|
| 75 |
+
value = (env.get(TMPFS_SIZE_ENV) or "").strip()
|
| 76 |
+
if _SIZE.fullmatch(value):
|
| 77 |
+
return value.lower()
|
| 78 |
+
if value:
|
| 79 |
+
print(f"isolation: ignoring {TMPFS_SIZE_ENV}={value!r}; using {TMPFS_SIZE_DEFAULT}",
|
| 80 |
+
file=sys.stderr)
|
| 81 |
+
return TMPFS_SIZE_DEFAULT
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def runtime_paths(command: list[str], *, python_only=False) -> list[str]:
|
| 85 |
+
paths = ["/usr", "/bin", "/sbin", "/lib", "/lib64", sys.prefix, sys.base_prefix]
|
| 86 |
+
# Config files needed by Python, Node, TLS, DNS and git; never a host home or the shared-disk root.
|
| 87 |
+
paths += ["/etc/ssl", "/etc/alternatives", "/etc/hosts", "/etc/resolv.conf",
|
| 88 |
+
"/etc/nsswitch.conf", "/etc/passwd", "/etc/group", "/etc/localtime"]
|
| 89 |
+
if not python_only:
|
| 90 |
+
paths.append(str(Path(__file__).resolve().parents[2])) # editable flock install
|
| 91 |
+
for binary in (command[0], "node"):
|
| 92 |
+
found = shutil.which(binary)
|
| 93 |
+
if not found:
|
| 94 |
+
continue
|
| 95 |
+
target = Path(found).resolve()
|
| 96 |
+
modules = next((p for p in target.parents if p.name == "node_modules"), None)
|
| 97 |
+
paths.append(str(modules or target.parent))
|
| 98 |
+
return sorted({str(Path(p).absolute()) for p in paths if Path(p).exists()}, key=lambda p: (len(p), p))
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def symlink_chain(path: str | Path) -> tuple[list[tuple[str, str]], str]:
|
| 102 |
+
"""Resolve `path` one hop at a time: every symlink met on the way (as `(link, target)`,
|
| 103 |
+
the target exactly as stored) and the final real path. Components that do not exist are
|
| 104 |
+
kept as they are. A loop or more than 40 hops raises."""
|
| 105 |
+
links: list[tuple[str, str]] = []
|
| 106 |
+
pending = list(Path(os.path.abspath(path)).parts[1:])
|
| 107 |
+
current = Path("/")
|
| 108 |
+
while pending:
|
| 109 |
+
name = pending.pop(0)
|
| 110 |
+
if name in ("", "."):
|
| 111 |
+
continue
|
| 112 |
+
if name == "..":
|
| 113 |
+
current = current.parent
|
| 114 |
+
continue
|
| 115 |
+
candidate = current / name
|
| 116 |
+
if not candidate.is_symlink():
|
| 117 |
+
current = candidate
|
| 118 |
+
continue
|
| 119 |
+
target = os.readlink(candidate)
|
| 120 |
+
links.append((str(candidate), target))
|
| 121 |
+
if len(links) > 40:
|
| 122 |
+
raise RuntimeError(f"isolation: too many symlinks resolving {path}")
|
| 123 |
+
if os.path.isabs(target):
|
| 124 |
+
current = Path("/")
|
| 125 |
+
pending = list(Path(target).parts[1:]) + pending
|
| 126 |
+
else:
|
| 127 |
+
pending = list(Path(target).parts) + pending
|
| 128 |
+
return links, str(current)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _within(path: str, roots: list[str]) -> bool:
|
| 132 |
+
return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def plan(argv: list[str], *, cwd: Path, readonly=(), writable=(), python_only=False,
|
| 136 |
+
private_dirs=(), tmp=None) -> dict:
|
| 137 |
+
"""Mounts and symlinks for the chroot. Every path is bound at its real location, and each
|
| 138 |
+
symlink hop on the way to it (and to the interpreter, the command and node) is recreated
|
| 139 |
+
inside, so the original spelling resolves there too (a uv venv's python links through
|
| 140 |
+
`cpython-3.12-...` to `cpython-3.12.14-...`)."""
|
| 141 |
+
links: dict[str, str] = {}
|
| 142 |
+
|
| 143 |
+
def real(p) -> str:
|
| 144 |
+
hops, final = symlink_chain(p)
|
| 145 |
+
links.update(hops)
|
| 146 |
+
return final
|
| 147 |
+
|
| 148 |
+
ro = [real(p) for p in runtime_paths(argv, python_only=python_only) + [str(p) for p in readonly]]
|
| 149 |
+
rw = [real(p) for p in writable]
|
| 150 |
+
probes = [sys.executable, argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])]
|
| 151 |
+
if not python_only:
|
| 152 |
+
probes.append(shutil.which("node"))
|
| 153 |
+
for probe in filter(None, probes):
|
| 154 |
+
final = real(probe)
|
| 155 |
+
if not _within(final, ro + rw):
|
| 156 |
+
raise RuntimeError(f"isolation cannot represent {probe}: it resolves to {final}, "
|
| 157 |
+
"outside every mounted path")
|
| 158 |
+
real(cwd)
|
| 159 |
+
def ordered(paths: list[str]) -> list[str]: # parents before nested mounts
|
| 160 |
+
return sorted(dict.fromkeys(paths), key=lambda p: (len(p), p))
|
| 161 |
+
|
| 162 |
+
# `tmp` (a disk-backed dir) is bound over the sandbox's /tmp, so files written there do not
|
| 163 |
+
# fill the tmpfs root. Not when a planned path lives under /tmp itself (a test's tmp_path):
|
| 164 |
+
# the bind would hide it, and /tmp stays on the size-capped tmpfs.
|
| 165 |
+
tmp_dir = real(tmp) if tmp is not None else None
|
| 166 |
+
if tmp_dir is not None and any(_within(p, [SANDBOX_TMP]) for p in [*ro, *rw, *links, real(cwd)]):
|
| 167 |
+
tmp_dir = None
|
| 168 |
+
return {"readonly": ordered(ro), "writable": list(dict.fromkeys(rw)),
|
| 169 |
+
"symlinks": sorted(links.items(), key=lambda kv: (len(kv[0]), kv[0])),
|
| 170 |
+
"private_dirs": [str(Path(p).absolute()) for p in private_dirs], "tmp": tmp_dir}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def command(argv: list[str], root: Path, *, cwd: Path, readonly=(), writable=(), network=False,
|
| 174 |
+
python_only=False, private_dirs=(), tmp=None) -> list[str]:
|
| 175 |
+
"""Build a trusted invocation. Only explicitly mounted paths survive the chroot. `tmp`: a
|
| 176 |
+
disk-backed directory bound writable at the sandbox's /tmp (see `plan`)."""
|
| 177 |
+
unshare = shutil.which("unshare")
|
| 178 |
+
if not unshare:
|
| 179 |
+
raise RuntimeError("unshare is required for process isolation")
|
| 180 |
+
config = {"root": str(root.absolute()), "cwd": str(cwd.absolute()),
|
| 181 |
+
"readonly_root": not network, "tmpfs_size": tmpfs_size(),
|
| 182 |
+
**plan(argv, cwd=cwd, readonly=readonly, writable=writable, python_only=python_only,
|
| 183 |
+
private_dirs=private_dirs, tmp=tmp)}
|
| 184 |
+
# Slurm sends USR1 to every process on reclaim. Only worker/world supervisors
|
| 185 |
+
# handle it; an unshare wrapper must survive long enough for their bounded drain.
|
| 186 |
+
return ["/bin/sh", "-c", 'trap "" USR1; exec "$@"', "flock-isolate",
|
| 187 |
+
unshare, "--user", "--map-root-user", "--pid", "--fork", "--kill-child=SIGKILL",
|
| 188 |
+
"--mount", "--propagation", "private", "--mount-proc", *(["--net"] if not network else []), "--",
|
| 189 |
+
sys.executable, "-I", str(Path(__file__).resolve()), json.dumps(config), *argv]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _mount(source, target, kind=None, flags=0, data=None):
|
| 193 |
+
def encoded(value):
|
| 194 |
+
return os.fsencode(value) if value is not None else None
|
| 195 |
+
libc = _libc()
|
| 196 |
+
libc.mount.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p,
|
| 197 |
+
ctypes.c_ulong, ctypes.c_char_p]
|
| 198 |
+
if libc.mount(encoded(source), encoded(target), encoded(kind), flags, encoded(data)) != 0:
|
| 199 |
+
errno = ctypes.get_errno()
|
| 200 |
+
raise IsolationMountError(errno, f"isolation mount failed: {os.strerror(errno)}: "
|
| 201 |
+
f"source={source} target={target} type={kind} "
|
| 202 |
+
f"flags={flags:#x}")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def readonly_remount_flags(target) -> int:
|
| 206 |
+
"""MS_REMOUNT|MS_BIND|MS_RDONLY plus nosuid/nodev, and every locked flag the bound mount
|
| 207 |
+
already has (statvfs of the bind target): a user namespace cannot clear them, and
|
| 208 |
+
leaving them out fails with EPERM. No atime flag on the source means strictatime."""
|
| 209 |
+
inherited = os.statvfs(target).f_flag
|
| 210 |
+
flags = MS_BIND | MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV
|
| 211 |
+
for flag, mount_flag in _LOCKED:
|
| 212 |
+
if inherited & flag:
|
| 213 |
+
flags |= mount_flag
|
| 214 |
+
if not inherited & (os.ST_NOATIME | os.ST_RELATIME):
|
| 215 |
+
flags |= MS_STRICTATIME
|
| 216 |
+
return flags
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _readonly_recursive(target) -> bool:
|
| 220 |
+
"""mount_setattr(AT_RECURSIVE, MOUNT_ATTR_RDONLY): make every submount of a recursive
|
| 221 |
+
bind read-only too (a remount only changes the top one). False if the kernel lacks it
|
| 222 |
+
(before 5.12); the mountinfo check still refuses a writable submount."""
|
| 223 |
+
libc = _libc()
|
| 224 |
+
attr = (ctypes.c_uint64 * 4)(MOUNT_ATTR_RDONLY, 0, 0, 0)
|
| 225 |
+
libc.syscall.restype = ctypes.c_long
|
| 226 |
+
rc = libc.syscall(ctypes.c_long(SYS_MOUNT_SETATTR), ctypes.c_int(AT_FDCWD),
|
| 227 |
+
ctypes.c_char_p(os.fsencode(target)), ctypes.c_uint(AT_RECURSIVE),
|
| 228 |
+
ctypes.byref(attr), ctypes.c_size_t(ctypes.sizeof(attr)))
|
| 229 |
+
# Any failure (ENOSYS before 5.12, EPERM on a locked mount): the mountinfo check that
|
| 230 |
+
# follows the binds still refuses a writable submount.
|
| 231 |
+
return rc == 0
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _unescape(field: str) -> str:
|
| 235 |
+
return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def parse_mountinfo(text: str) -> list[tuple[str, set[str]]]:
|
| 239 |
+
"""(mount point, per-mount options) of each /proc/self/mountinfo line."""
|
| 240 |
+
out = []
|
| 241 |
+
for line in text.splitlines():
|
| 242 |
+
fields = line.split()
|
| 243 |
+
if len(fields) >= 6:
|
| 244 |
+
out.append((_unescape(fields[4]), set(fields[5].split(","))))
|
| 245 |
+
return out
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def check_mounts(mounts: list[tuple[str, set[str]]], root: str, readonly: list[str],
|
| 249 |
+
writable: list[str] = (), extra: list[str] = ()) -> None:
|
| 250 |
+
"""Fail closed after the binds. Every mount under `root` must be a planned target (or
|
| 251 |
+
`extra`: proc, the /dev nodes), or a submount a recursive bind of one brought along
|
| 252 |
+
(e.g. a container's zoneinfo file bound over /usr's); and every mount at or under a
|
| 253 |
+
read-only target, outside a writable one, must be `ro`."""
|
| 254 |
+
def under(path: str, roots) -> bool:
|
| 255 |
+
return any(path == r or path.startswith(r.rstrip("/") + "/") for r in roots)
|
| 256 |
+
|
| 257 |
+
planned = [*readonly, *writable, *extra]
|
| 258 |
+
for point, opts in mounts:
|
| 259 |
+
if point == root or not under(point, [root]):
|
| 260 |
+
continue
|
| 261 |
+
if not under(point, planned):
|
| 262 |
+
raise IsolationMountError(1, f"isolation: unexpected mount {point} in the sandbox root")
|
| 263 |
+
if under(point, readonly) and not under(point, writable) and "ro" not in opts:
|
| 264 |
+
raise IsolationMountError(30, f"isolation: {point} is mounted writable under a "
|
| 265 |
+
"read-only path")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _bind(root: Path, source: str, *, readonly: bool, target: Path | None = None):
|
| 269 |
+
"""Bind `source` at its own path under `root` (or at `target`, a path under `root`)."""
|
| 270 |
+
path = Path(source)
|
| 271 |
+
if not path.exists():
|
| 272 |
+
raise IsolationSetupError(2, f"isolation bind failed: required path is missing: path={source}")
|
| 273 |
+
target = target if target is not None else root / path.relative_to("/")
|
| 274 |
+
# Create the mount point only when missing: it may already exist on a read-only bind
|
| 275 |
+
# (/etc/localtime -> /usr/share/zoneinfo/... under the /usr bind), where touch()'s utime
|
| 276 |
+
# fails with EROFS.
|
| 277 |
+
with _step("mount point creation", target):
|
| 278 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 279 |
+
if path.is_dir():
|
| 280 |
+
if not target.is_dir():
|
| 281 |
+
target.mkdir()
|
| 282 |
+
elif not target.exists():
|
| 283 |
+
target.touch()
|
| 284 |
+
# Recursive: a user namespace refuses (EINVAL) a non-recursive bind of a tree that has
|
| 285 |
+
# locked submounts, since it would uncover what they hide. Only explicitly listed paths
|
| 286 |
+
# are bound, so a submount comes in only under a path that was asked for.
|
| 287 |
+
_mount(source, target, flags=MS_BIND | MS_REC)
|
| 288 |
+
if readonly:
|
| 289 |
+
# Step two: read-only only works as a remount of the bind, with the locked flags;
|
| 290 |
+
# then the submounts the recursive bind brought along, where the kernel can.
|
| 291 |
+
_mount(None, target, flags=readonly_remount_flags(target))
|
| 292 |
+
_readonly_recursive(target)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def _drop_privileges():
|
| 296 |
+
libc = _libc()
|
| 297 |
+
# NOROOT + locked: exec as namespace uid 0 must never regain capabilities.
|
| 298 |
+
if libc.prctl(28, 3, 0, 0, 0) or libc.prctl(38, 1, 0, 0, 0):
|
| 299 |
+
raise RuntimeError("cannot lock sandbox privileges")
|
| 300 |
+
# All currently defined capabilities fit below 64. EINVAL marks unsupported bits.
|
| 301 |
+
for cap in range(64):
|
| 302 |
+
if libc.prctl(24, cap, 0, 0, 0) != 0 and ctypes.get_errno() != 22:
|
| 303 |
+
raise RuntimeError("cannot drop sandbox capability bounding set")
|
| 304 |
+
class Header(ctypes.Structure):
|
| 305 |
+
_fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)]
|
| 306 |
+
class Data(ctypes.Structure):
|
| 307 |
+
_fields_ = [("effective", ctypes.c_uint32), ("permitted", ctypes.c_uint32),
|
| 308 |
+
("inheritable", ctypes.c_uint32)]
|
| 309 |
+
if libc.capset(ctypes.byref(Header(0x20080522, 0)), (Data * 2)()) != 0:
|
| 310 |
+
raise RuntimeError("cannot clear sandbox capabilities")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
OOM_SCORE_ADJ = 800 # sandboxed processes die before the worker (which keeps 0) on an OOM kill
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def set_oom_score_adj(value: int = OOM_SCORE_ADJ, path: str = "/proc/self/oom_score_adj") -> bool:
|
| 317 |
+
"""Raise this process's OOM score (inherited by what it execs). Raising needs no
|
| 318 |
+
privilege; False when /proc refuses it."""
|
| 319 |
+
try:
|
| 320 |
+
Path(path).write_text(str(value))
|
| 321 |
+
return True
|
| 322 |
+
except OSError:
|
| 323 |
+
return False
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _enter(config, argv):
|
| 327 |
+
# Never share a process group with a supervisor outside the PID namespace.
|
| 328 |
+
if os.getpgrp() != os.getpid():
|
| 329 |
+
os.setsid()
|
| 330 |
+
set_oom_score_adj()
|
| 331 |
+
root = Path(config["root"])
|
| 332 |
+
with _step("root creation", root):
|
| 333 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 334 |
+
size = config.get("tmpfs_size") or TMPFS_SIZE_DEFAULT
|
| 335 |
+
if not _SIZE.fullmatch(size):
|
| 336 |
+
raise IsolationSetupError(22, f"isolation tmpfs size is invalid: path={root}")
|
| 337 |
+
_mount("tmpfs", root, "tmpfs", MS_NOSUID | MS_NODEV, f"mode=755,size={size}")
|
| 338 |
+
for path in config["readonly"]:
|
| 339 |
+
_bind(root, path, readonly=True)
|
| 340 |
+
for path in config["writable"]:
|
| 341 |
+
_bind(root, path, readonly=False)
|
| 342 |
+
for link, target in config.get("symlinks", ()):
|
| 343 |
+
inside = root / Path(link).relative_to("/")
|
| 344 |
+
if os.path.lexists(inside):
|
| 345 |
+
continue # already visible through a bind mount
|
| 346 |
+
with _step("symlink creation", inside):
|
| 347 |
+
inside.parent.mkdir(parents=True, exist_ok=True)
|
| 348 |
+
inside.symlink_to(target)
|
| 349 |
+
for path in config["private_dirs"]:
|
| 350 |
+
with _step("private directory creation", path):
|
| 351 |
+
(root / Path(path).relative_to("/")).mkdir(parents=True, exist_ok=True)
|
| 352 |
+
for path in ("tmp", "proc", "dev"):
|
| 353 |
+
with _step("directory creation", root / path):
|
| 354 |
+
(root / path).mkdir(exist_ok=True)
|
| 355 |
+
if config.get("tmp"): # the sandbox's /tmp on the caller's disk-backed dir, not the tmpfs
|
| 356 |
+
_bind(root, config["tmp"], readonly=False, target=root / SANDBOX_TMP.lstrip("/"))
|
| 357 |
+
for path in DEV_NODES:
|
| 358 |
+
_bind(root, path, readonly=False)
|
| 359 |
+
with _step("symlink creation", root / "dev/fd"):
|
| 360 |
+
(root / "dev/fd").symlink_to("/proc/self/fd")
|
| 361 |
+
_mount("proc", root / "proc", "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC)
|
| 362 |
+
inside = lambda p: os.path.realpath(root / Path(p).relative_to("/"))
|
| 363 |
+
check_mounts(parse_mountinfo(Path("/proc/self/mountinfo").read_text()), os.path.realpath(root),
|
| 364 |
+
[inside(p) for p in config["readonly"]],
|
| 365 |
+
[inside(p) for p in (*config["writable"], *([SANDBOX_TMP] if config.get("tmp") else []))],
|
| 366 |
+
[inside(p) for p in ("/proc", *DEV_NODES)])
|
| 367 |
+
if config["readonly_root"]:
|
| 368 |
+
_mount(None, root, flags=MS_REMOUNT | MS_RDONLY | MS_NOSUID | MS_NODEV)
|
| 369 |
+
with _step("chroot", root):
|
| 370 |
+
os.chroot(root)
|
| 371 |
+
with _step("chdir", config["cwd"]):
|
| 372 |
+
os.chdir(config["cwd"])
|
| 373 |
+
_drop_privileges()
|
| 374 |
+
os.execvpe(argv[0], argv, dict(os.environ))
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
if __name__ == "__main__":
|
| 378 |
+
try:
|
| 379 |
+
_enter(json.loads(sys.argv[1]), sys.argv[2:])
|
| 380 |
+
except IsolationSetupError as e: # step, path and flags only, never argv or the env
|
| 381 |
+
print(f"process isolation failed during setup: {e.strerror}", file=sys.stderr)
|
| 382 |
+
raise SystemExit(125) from None
|
| 383 |
+
except Exception: # noqa: BLE001 - fail closed, without leaking arguments or paths
|
| 384 |
+
# Paths, argv and errors could contain credentials. Fail closed without their values.
|
| 385 |
+
print("process isolation failed during setup", file=sys.stderr)
|
| 386 |
+
raise SystemExit(125) from None
|
world/src/flock/models.py
ADDED
|
@@ -0,0 +1,2009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
| 1 |
+
"""Shared contracts between controller, worker and CLI.
|
| 2 |
+
|
| 3 |
+
This file is the contract. Everything in docs/design.md "Contracts"
|
| 4 |
+
is expressed here. Change it deliberately and update the design doc.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import re
|
| 11 |
+
from datetime import UTC, date, datetime, timedelta
|
| 12 |
+
from enum import StrEnum
|
| 13 |
+
from typing import Any, Literal, NamedTuple
|
| 14 |
+
|
| 15 |
+
import yaml
|
| 16 |
+
from pydantic import BaseModel, Field, field_validator, model_serializer, model_validator
|
| 17 |
+
|
| 18 |
+
from flock.registry import COMPUTE, HARNESSES
|
| 19 |
+
from flock.world.protocol import TOOL_NAME_RE as WORLD_TOOL_RE
|
| 20 |
+
from flock.world.protocol import WorldManifest
|
| 21 |
+
|
| 22 |
+
# --------------------------------------------------------------------------- spec YAML
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class _SpecLoader(yaml.SafeLoader):
|
| 26 |
+
"""SafeLoader with YAML 1.2 booleans: only true/false. YAML 1.1 (PyYAML's default) also
|
| 27 |
+
reads on/off/yes/no as booleans, so an `on:` key became `True`.
|
| 28 |
+
Dropping them in the loader protects every key and value of a spec, not just `loop.on`."""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
_BOOL = "tag:yaml.org,2002:bool"
|
| 32 |
+
_SpecLoader.yaml_implicit_resolvers = {
|
| 33 |
+
ch: [(tag, rx) for tag, rx in rs if tag != _BOOL]
|
| 34 |
+
for ch, rs in yaml.SafeLoader.yaml_implicit_resolvers.items()
|
| 35 |
+
}
|
| 36 |
+
_SpecLoader.add_implicit_resolver(_BOOL, re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"),
|
| 37 |
+
list("tTfF"))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_spec_yaml(text: str) -> Any:
|
| 41 |
+
"""Parse spec YAML (safe, YAML 1.2 booleans); validate with `SwarmSpec.model_validate`."""
|
| 42 |
+
return yaml.load(text, Loader=_SpecLoader) # a SafeLoader subclass
|
| 43 |
+
|
| 44 |
+
# --------------------------------------------------------------------------- durations
|
| 45 |
+
|
| 46 |
+
_DURATION_RE = re.compile(r"^\s*(\d+)\s*(ms|s|m|h|d)\s*$")
|
| 47 |
+
_UNIT_SECONDS = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parse_duration(value: str | int | float | timedelta) -> timedelta:
|
| 51 |
+
"""Parse '30s', '10m', '24h', '7d' (or a number of seconds) into a timedelta."""
|
| 52 |
+
if isinstance(value, timedelta):
|
| 53 |
+
return value
|
| 54 |
+
if isinstance(value, (int, float)):
|
| 55 |
+
return timedelta(seconds=float(value))
|
| 56 |
+
m = _DURATION_RE.match(value)
|
| 57 |
+
if not m:
|
| 58 |
+
raise ValueError(f"bad duration {value!r}; use e.g. 30s, 10m, 24h, 7d")
|
| 59 |
+
return timedelta(seconds=int(m.group(1)) * _UNIT_SECONDS[m.group(2)])
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def until_deadline(until: str, started_at: float) -> float:
|
| 63 |
+
"""Epoch deadline of `while.until`: started_at + duration, or the ISO-8601 time (naive = UTC)."""
|
| 64 |
+
try:
|
| 65 |
+
return started_at + parse_duration(until).total_seconds()
|
| 66 |
+
except ValueError:
|
| 67 |
+
try:
|
| 68 |
+
t = datetime.fromisoformat(until)
|
| 69 |
+
except ValueError:
|
| 70 |
+
raise ValueError(f"bad until {until!r}; use a duration (2h) or a time (2026-10-28T20:00Z)") from None
|
| 71 |
+
return (t if t.tzinfo else t.replace(tzinfo=UTC)).timestamp()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# --------------------------------------------------------------------------- enums
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# the names in flock.registry.HARNESSES; an enum so spec errors and the JSON schema list them
|
| 78 |
+
Harness = StrEnum("Harness", [(name, name) for name in HARNESSES], module=__name__)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class AgentState(StrEnum):
|
| 82 |
+
working = "working" # a harness process is running a turn
|
| 83 |
+
idle = "idle" # no process; idle_since set
|
| 84 |
+
stuck = "stuck" # a turn exceeded its timeout and was killed; cleared on next turn
|
| 85 |
+
unknown = "unknown" # heartbeat older than compute.worker_unknown_after (per-backend default)
|
| 86 |
+
dead = "dead" # heartbeat older than compute.worker_dead_after, or job terminal
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class WorkerState(StrEnum):
|
| 90 |
+
launching = "launching"
|
| 91 |
+
running = "running"
|
| 92 |
+
draining = "draining"
|
| 93 |
+
unknown = "unknown"
|
| 94 |
+
dead = "dead"
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class TypeHealth(StrEnum):
|
| 98 |
+
ok = "ok"
|
| 99 |
+
crashlooping = "crashlooping"
|
| 100 |
+
launch_refused = "launch_refused" # the backend refused the launch (4xx); waits for a new apply
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# --------------------------------------------------------------------------- spec
|
| 104 |
+
|
| 105 |
+
AGENT_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*-\d{4,}$")
|
| 106 |
+
TYPE_NAME_RE = re.compile(r"^[a-z][a-z0-9-]*$")
|
| 107 |
+
# Provider names prefix model strings ("hf:Qwen/..."), so no dots and no colons. A model string
|
| 108 |
+
# whose prefix does not look like this names no provider.
|
| 109 |
+
PROVIDER_NAME_RE = re.compile(r"^[a-z][a-z0-9_-]*$")
|
| 110 |
+
ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
| 111 |
+
TOOLS_VERSION_RE = re.compile(r"^[0-9a-f]{16}$")
|
| 112 |
+
SELF_HOSTED_PRICING = [0.0, 0.0, 0.0]
|
| 113 |
+
|
| 114 |
+
Reasoning = Literal["off", "low", "medium", "high"]
|
| 115 |
+
# `reasoning` -> OpenAI `reasoning.effort`.
|
| 116 |
+
REASONING_EFFORT = {"off": "none", "low": "low", "medium": "medium", "high": "high"}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _pricing_row(v: list[float], where: str) -> list[float]:
|
| 120 |
+
if len(v) != 3 or any(x < 0 for x in v):
|
| 121 |
+
raise ValueError(f"{where}: pricing must be [input, output, cached] USD per 1M tokens, >= 0")
|
| 122 |
+
return [float(x) for x in v]
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class ProviderSpec(BaseModel):
|
| 126 |
+
"""Where a model is served (design.md 'Providers'). Field names follow swarmlab's
|
| 127 |
+
provider params so a `providers:` block moves between the two projects.
|
| 128 |
+
|
| 129 |
+
`api_key_env` names a secret / env var; the value is never in the spec. The controller
|
| 130 |
+
sends that secret to the provider's jobs and uses it for preflight; the worker hands it to
|
| 131 |
+
the harness."""
|
| 132 |
+
|
| 133 |
+
type: Literal["openai_compat", "anthropic"]
|
| 134 |
+
base_url: str | None = None # openai_compat: required, ends in /v1; anthropic: API root
|
| 135 |
+
# Several servers of one model (openai_compat): preflight probes each and health scrapes each
|
| 136 |
+
# one's metrics; agents call `base_url`, which defaults to the first.
|
| 137 |
+
base_urls: list[str] | None = None
|
| 138 |
+
api_key_env: str
|
| 139 |
+
self_hosted: bool = False # price defaults to [0, 0, 0]; real cost is the GPU job's time
|
| 140 |
+
# Max agents of this swarm on this provider that may be in a turn at once. Enforced at
|
| 141 |
+
# prompt admission by the controller (FLOCK_MAX_WORKING_ENFORCE=0: report only).
|
| 142 |
+
max_working: int | None = None
|
| 143 |
+
pricing: dict[str, list[float]] = Field(default_factory=dict) # model id ("*" = any) -> row
|
| 144 |
+
timeout_s: float | None = None # passthrough to the harness / preflight
|
| 145 |
+
max_retries: int | None = None # passthrough to the harness
|
| 146 |
+
# How the key is sent. `anthropic` providers: "x-api-key" (default) or "bearer"
|
| 147 |
+
# (`Authorization: Bearer`), for gateways and proxies that only take a bearer token. `openai_compat` is always bearer.
|
| 148 |
+
auth: Literal["x-api-key", "bearer"] | None = None
|
| 149 |
+
# Scrape `<server root>/metrics` (vLLM Prometheus text) of each base URL into the swarm's
|
| 150 |
+
# health snapshots: num_requests_waiting / running, KV cache usage (docs/health.md).
|
| 151 |
+
metrics: bool = False
|
| 152 |
+
|
| 153 |
+
@field_validator("base_urls", mode="before")
|
| 154 |
+
@classmethod
|
| 155 |
+
def _url_list(cls, v: Any) -> Any:
|
| 156 |
+
"""A comma-separated string is a list (`base_urls: ${OPENAI_BASE_URLS:-}`); "" is none."""
|
| 157 |
+
if isinstance(v, str):
|
| 158 |
+
return [u.strip() for u in v.split(",") if u.strip()] or None
|
| 159 |
+
return v
|
| 160 |
+
|
| 161 |
+
@field_validator("api_key_env")
|
| 162 |
+
@classmethod
|
| 163 |
+
def _env_name(cls, v: str) -> str:
|
| 164 |
+
if not ENV_NAME_RE.match(v):
|
| 165 |
+
raise ValueError(f"api_key_env {v!r} must be an env var name (the key itself never goes in the spec)")
|
| 166 |
+
return v
|
| 167 |
+
|
| 168 |
+
@field_validator("pricing")
|
| 169 |
+
@classmethod
|
| 170 |
+
def _rows(cls, v: dict[str, list[float]]) -> dict[str, list[float]]:
|
| 171 |
+
return {k: _pricing_row(row, f"pricing[{k!r}]") for k, row in v.items()}
|
| 172 |
+
|
| 173 |
+
@field_validator("max_working")
|
| 174 |
+
@classmethod
|
| 175 |
+
def _positive(cls, v: int | None) -> int | None:
|
| 176 |
+
if v is not None and v < 1:
|
| 177 |
+
raise ValueError("max_working must be >= 1")
|
| 178 |
+
return v
|
| 179 |
+
|
| 180 |
+
@model_validator(mode="after")
|
| 181 |
+
def _url(self) -> ProviderSpec:
|
| 182 |
+
if self.base_urls is not None:
|
| 183 |
+
urls = [u.strip().rstrip("/") for u in self.base_urls if u and u.strip()]
|
| 184 |
+
if not urls:
|
| 185 |
+
raise ValueError("base_urls must list at least one URL")
|
| 186 |
+
if len(set(urls)) != len(urls):
|
| 187 |
+
raise ValueError("base_urls must not repeat a URL")
|
| 188 |
+
if self.type != "openai_compat":
|
| 189 |
+
raise ValueError("base_urls is for openai_compat providers")
|
| 190 |
+
self.base_urls = urls
|
| 191 |
+
if self.base_url is None:
|
| 192 |
+
self.base_url = urls[0]
|
| 193 |
+
if self.type == "openai_compat" and not self.base_url:
|
| 194 |
+
raise ValueError("base_url is required for type openai_compat (e.g. https://router.huggingface.co/v1)")
|
| 195 |
+
if self.type == "openai_compat" and self.auth == "x-api-key":
|
| 196 |
+
raise ValueError("auth: x-api-key is for anthropic providers; openai_compat always sends a bearer token")
|
| 197 |
+
if self.base_url is not None:
|
| 198 |
+
self.base_url = self.base_url.rstrip("/")
|
| 199 |
+
return self
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def endpoints(self) -> list[str]:
|
| 203 |
+
"""The servers to spread agents over: `base_urls`, else `[base_url]`."""
|
| 204 |
+
return list(self.base_urls) if self.base_urls else ([self.base_url] if self.base_url else [])
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class ModelSpec(BaseModel):
|
| 208 |
+
"""An alias under `models:`: a provider-prefixed model plus per-model settings."""
|
| 209 |
+
|
| 210 |
+
model: str # "<provider>:<model id>"
|
| 211 |
+
reasoning: Reasoning | None = None
|
| 212 |
+
# Raw request-body fields (swarmlab's `extra`). Not sent (Harbor's Pi cannot); kept for
|
| 213 |
+
# spec portability, with a warning at launch.
|
| 214 |
+
extra: dict[str, Any] | None = None
|
| 215 |
+
pricing: list[float] | None = None # overrides the provider's pricing for this alias
|
| 216 |
+
|
| 217 |
+
@field_validator("pricing")
|
| 218 |
+
@classmethod
|
| 219 |
+
def _row(cls, v: list[float] | None) -> list[float] | None:
|
| 220 |
+
return None if v is None else _pricing_row(v, "pricing")
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class ResolvedModel(BaseModel):
|
| 224 |
+
"""A type's model after resolution, pinned into the stored spec at apply time."""
|
| 225 |
+
|
| 226 |
+
provider_name: str
|
| 227 |
+
provider: ProviderSpec
|
| 228 |
+
model_id: str # what the harness sends as `model`
|
| 229 |
+
reasoning: Reasoning | None = None
|
| 230 |
+
extra: dict[str, Any] | None = None
|
| 231 |
+
pricing: list[float] # [input, output, cached] USD per 1M tokens, pinned
|
| 232 |
+
|
| 233 |
+
@property
|
| 234 |
+
def qualified(self) -> str:
|
| 235 |
+
return f"{self.provider_name}:{self.model_id}"
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# --------------------------------------------------------------------------- comms (docs/comms.md)
|
| 239 |
+
|
| 240 |
+
# Built-in comms tools a type may list in `tools:`; the model sees the bare name (`post`).
|
| 241 |
+
COMMS_TOOLS = ("comms:post", "comms:read", "comms:search")
|
| 242 |
+
EXTENDED_COMMS_TOOLS = ("comms:channels", "comms:create_channel", "comms:join_channel",
|
| 243 |
+
"comms:dm", "comms:read_dms", "comms:react", "comms:votes", "comms:doc",
|
| 244 |
+
"comms:edit_doc")
|
| 245 |
+
ALL_COMMS_TOOLS = COMMS_TOOLS + EXTENDED_COMMS_TOOLS
|
| 246 |
+
COMMS_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def normalize_board_url(url: str) -> str:
|
| 250 |
+
"""The one spelling of a board url, used wherever board urls are stored or compared (spec,
|
| 251 |
+
identities, board clients, message sources): scheme and host lowercased, default port and
|
| 252 |
+
trailing slashes dropped, IPv6 brackets and userinfo kept, so it is idempotent.
|
| 253 |
+
`http://Board.invalid:80/` -> `http://board.invalid`; `http://[::1]:8080/` -> `http://[::1]:8080`."""
|
| 254 |
+
from urllib.parse import urlsplit, urlunsplit
|
| 255 |
+
|
| 256 |
+
u = urlsplit(url.strip())
|
| 257 |
+
scheme, host = u.scheme.lower(), (u.hostname or "").lower()
|
| 258 |
+
if ":" in host: # an IPv6 literal keeps its brackets: `http://[::1]:8080`
|
| 259 |
+
host = f"[{host}]"
|
| 260 |
+
port = u.port
|
| 261 |
+
netloc = host if port is None or (scheme, port) in (("http", 80), ("https", 443)) else f"{host}:{port}"
|
| 262 |
+
if u.username or u.password:
|
| 263 |
+
netloc = u.netloc.rsplit("@", 1)[0] + "@" + netloc
|
| 264 |
+
return urlunsplit((scheme, netloc, u.path.rstrip("/"), u.query, ""))
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def comms_name(entry: str) -> str:
|
| 268 |
+
"""`comms:post` -> `post`, the name the model sees."""
|
| 269 |
+
return entry.split(":", 1)[1]
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class CommsRules(BaseModel):
|
| 273 |
+
"""Enforced by the worker before it calls the board; a refused post is a tool result
|
| 274 |
+
("refused: ..."), never a board request. Live: a re-apply reaches workers by heartbeat."""
|
| 275 |
+
|
| 276 |
+
model_config = {"extra": "forbid"}
|
| 277 |
+
|
| 278 |
+
min_post_gap: str | None = None # per agent, e.g. 20s
|
| 279 |
+
max_posts: int | None = None # per agent, for the run (kept in the agent's synced state)
|
| 280 |
+
max_len: int | None = None # characters per post
|
| 281 |
+
threads: Literal["per_topic"] | None = None # posts must say thread: new or a root id
|
| 282 |
+
max_channels_per_agent: int = Field(default=3, ge=1, le=100)
|
| 283 |
+
max_channels: int = Field(default=60, ge=1, le=100)
|
| 284 |
+
no_group_mentions: bool = False # refuse @all / @agents / @humans (and @everyone, @people)
|
| 285 |
+
|
| 286 |
+
@field_validator("min_post_gap")
|
| 287 |
+
@classmethod
|
| 288 |
+
def _gap(cls, v: str | None) -> str | None:
|
| 289 |
+
if v is not None:
|
| 290 |
+
parse_duration(v)
|
| 291 |
+
return v
|
| 292 |
+
|
| 293 |
+
@field_validator("max_posts", "max_len")
|
| 294 |
+
@classmethod
|
| 295 |
+
def _positive(cls, v: int | None) -> int | None:
|
| 296 |
+
if v is not None and v < 1:
|
| 297 |
+
raise ValueError("must be >= 1")
|
| 298 |
+
return v
|
| 299 |
+
|
| 300 |
+
@property
|
| 301 |
+
def gap_s(self) -> float:
|
| 302 |
+
return parse_duration(self.min_post_gap).total_seconds() if self.min_post_gap else 0.0
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class CommsSpec(BaseModel):
|
| 306 |
+
"""Swarm-level `comms:` (docs/comms.md). `url`, `invite_env` and `channel` are resolved
|
| 307 |
+
once by the controller at apply (channel name -> `channel_id`); `kickoff_file` and
|
| 308 |
+
`protocols` are files next to the spec that `flock launch` inlines (`kickoff`,
|
| 309 |
+
`protocols_text`), because the controller and workers cannot read the caller's files."""
|
| 310 |
+
|
| 311 |
+
model_config = {"extra": "forbid"}
|
| 312 |
+
|
| 313 |
+
kind: Literal["msgboard"] = "msgboard"
|
| 314 |
+
extended: bool = False # multi-channel tools and serialized per-identity activity polling
|
| 315 |
+
# extended: each agent identity's feed is polled about once per this many seconds; the
|
| 316 |
+
# worker's poll interval is max(2 s, poll_cycle_s / its agents).
|
| 317 |
+
poll_cycle_s: float | None = Field(default=None, ge=10, le=3600) # unset: 300
|
| 318 |
+
url: str
|
| 319 |
+
# `space`: `flock init` duplicates `template` into a private per-run Space (`space`, default
|
| 320 |
+
# `<template namespace>/board-<swarm>`) and fills BOARD_URL and the invite (docs/comms.md).
|
| 321 |
+
# A url: the same as `url:`. Unset: `url` names an existing board.
|
| 322 |
+
board: str | None = None
|
| 323 |
+
template: str | None = None # a msgboard Space (one board at its root); required with `space`
|
| 324 |
+
space: str | None = None
|
| 325 |
+
# Space secret -> the run.env (or environment) name holding its value, e.g. {HF_TOKEN:
|
| 326 |
+
# BOARD_BUCKET_TOKEN}: a token scoped to the board's bucket, never the operator's own.
|
| 327 |
+
space_secrets: dict[str, str] = Field(default_factory=dict)
|
| 328 |
+
# Space variables over flock's (MSGBOARD_REPLICA: `<bucket>/board/<swarm>`); "" blanks one.
|
| 329 |
+
space_variables: dict[str, str] = Field(default_factory=dict)
|
| 330 |
+
space_hardware: str = "cpu-basic" # the Hub requires one to duplicate a Space
|
| 331 |
+
invite_env: str # secret holding a multi-use agent invite (the code never goes in the spec)
|
| 332 |
+
channel: str # name, with or without `#`
|
| 333 |
+
kickoff_file: str | None = None
|
| 334 |
+
kickoff: str | None = None # the file's text, inlined by `flock launch` (or given inline)
|
| 335 |
+
rules: CommsRules = Field(default_factory=CommsRules)
|
| 336 |
+
protocols: list[str] = Field(default_factory=list) # files appended to the instructions
|
| 337 |
+
protocols_text: list[str] = Field(default_factory=list) # inlined by `flock launch`
|
| 338 |
+
wake: list[Literal["mention", "thread", "dm", "channel"]] = Field(default_factory=lambda: ["mention", "thread"])
|
| 339 |
+
search: Literal["board", "index"] | None = "board"
|
| 340 |
+
# Written by the controller at apply; anything given by hand is replaced.
|
| 341 |
+
channel_id: int | None = None
|
| 342 |
+
kickoff_id: int | None = None
|
| 343 |
+
|
| 344 |
+
@field_validator("url")
|
| 345 |
+
@classmethod
|
| 346 |
+
def _url(cls, v: str) -> str:
|
| 347 |
+
if not v.startswith(("http://", "https://")):
|
| 348 |
+
raise ValueError(f"url {v!r} must start with http:// or https://")
|
| 349 |
+
return normalize_board_url(v)
|
| 350 |
+
|
| 351 |
+
@field_validator("invite_env")
|
| 352 |
+
@classmethod
|
| 353 |
+
def _env(cls, v: str) -> str:
|
| 354 |
+
if not ENV_NAME_RE.match(v):
|
| 355 |
+
raise ValueError(f"invite_env {v!r} must be an env var name (the invite never goes in the spec)")
|
| 356 |
+
return v
|
| 357 |
+
|
| 358 |
+
@field_validator("board")
|
| 359 |
+
@classmethod
|
| 360 |
+
def _board(cls, v: str | None) -> str | None:
|
| 361 |
+
if v not in (None, "space") and not v.startswith(("http://", "https://")):
|
| 362 |
+
raise ValueError(f"board {v!r}: use `space` or the board's url")
|
| 363 |
+
return v
|
| 364 |
+
|
| 365 |
+
@model_validator(mode="after")
|
| 366 |
+
def _template(self) -> CommsSpec:
|
| 367 |
+
if self.board == "space" and not self.template:
|
| 368 |
+
raise ValueError("board: space needs `template`: the msgboard Space to duplicate")
|
| 369 |
+
return self
|
| 370 |
+
|
| 371 |
+
@field_validator("channel")
|
| 372 |
+
@classmethod
|
| 373 |
+
def _channel(cls, v: str) -> str:
|
| 374 |
+
v = v.strip().lstrip("#")
|
| 375 |
+
if not COMMS_NAME_RE.match(v):
|
| 376 |
+
raise ValueError(f"channel {v!r}: use the channel's name, e.g. general")
|
| 377 |
+
return v
|
| 378 |
+
|
| 379 |
+
@field_validator("search")
|
| 380 |
+
@classmethod
|
| 381 |
+
def _search(cls, v: str | None) -> str | None:
|
| 382 |
+
if v == "index":
|
| 383 |
+
raise ValueError("search: index is not supported; use search: board (docs/comms.md)")
|
| 384 |
+
return v
|
| 385 |
+
|
| 386 |
+
@field_validator("wake")
|
| 387 |
+
@classmethod
|
| 388 |
+
def _wake(cls, v: list[str]) -> list[str]:
|
| 389 |
+
return list(dict.fromkeys(v))
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def board_url_default(data: Any) -> Any:
|
| 393 |
+
"""`comms.board` -> `comms.url` in raw spec data, before ${VAR} substitution: `space` reads
|
| 394 |
+
BOARD_URL (written by `flock init`), a url is the url. An explicit `url` wins."""
|
| 395 |
+
c = data.get("comms") if isinstance(data, dict) else None
|
| 396 |
+
if isinstance(c, dict) and c.get("board") and "url" not in c:
|
| 397 |
+
c["url"] = "${BOARD_URL}" if c["board"] == "space" else c["board"]
|
| 398 |
+
return data
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def comms_tools(ts: TypeSpec, comms: CommsSpec | None) -> list[str]:
|
| 402 |
+
"""The built-in comms tools a type gets: the `comms:*` entries of its `tools`, else all of
|
| 403 |
+
them with `comms: true` (search only when the swarm's `comms.search` is set)."""
|
| 404 |
+
if comms is None or ts.comms is False:
|
| 405 |
+
return []
|
| 406 |
+
listed = [t for t in ts.tools if t in ALL_COMMS_TOOLS] if isinstance(ts.tools, list) else []
|
| 407 |
+
if listed:
|
| 408 |
+
return list(dict.fromkeys(listed))
|
| 409 |
+
if not ts.comms:
|
| 410 |
+
return []
|
| 411 |
+
return [t for t in (ALL_COMMS_TOOLS if comms.extended else COMMS_TOOLS)
|
| 412 |
+
if t != "comms:search" or comms.search]
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class DashboardSpec(BaseModel):
|
| 416 |
+
"""Swarm-level `dashboard:` (docs/dashboard.md): `flock init` writes the run's flock-overview
|
| 417 |
+
row to `<registry>/runs/<id>.json` (id: default the swarm). The other row keys are derived from the spec."""
|
| 418 |
+
|
| 419 |
+
model_config = {"extra": "forbid"}
|
| 420 |
+
|
| 421 |
+
registry: str # hf://buckets/<ns>/<bucket>, the bucket the overview reads runs/ from
|
| 422 |
+
id: str | None = None # the overview row's id (runs/<id>.json); default: the swarm name
|
| 423 |
+
name: str | None = None # default: the swarm name
|
| 424 |
+
title: str | None = None
|
| 425 |
+
setup: str | None = None # one line
|
| 426 |
+
viewer: str # the run viewer's url (only named, never called)
|
| 427 |
+
viewer_public: str | None = None
|
| 428 |
+
dataset: str | None = None
|
| 429 |
+
code_repo: str | None = None
|
| 430 |
+
spec_url: str | None = None
|
| 431 |
+
|
| 432 |
+
@field_validator("registry")
|
| 433 |
+
@classmethod
|
| 434 |
+
def _registry(cls, v: str) -> str:
|
| 435 |
+
if not v.startswith("hf://buckets/"):
|
| 436 |
+
raise ValueError(f"registry {v!r} must be an hf://buckets/<ns>/<bucket> url")
|
| 437 |
+
return v.rstrip("/")
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
# --------------------------------------------------------------------------- world (docs/world.md)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class WorldSpec(BaseModel):
|
| 444 |
+
"""Swarm-level `world:` (docs/world.md): an HTTP service speaking World API v1 whose tools
|
| 445 |
+
the agents get. `command` (run in `dir`) is started by the controller as a child process
|
| 446 |
+
with `compute: local`; `url` names a world already running (required with `compute:
|
| 447 |
+
hf-jobs`, where starting one is not in this version). `token_env` names the secret sent as
|
| 448 |
+
`X-World-Token`; a started world without it gets a generated one. `endpoint` and `manifest`
|
| 449 |
+
are written by the controller at apply."""
|
| 450 |
+
|
| 451 |
+
model_config = {"extra": "forbid"}
|
| 452 |
+
|
| 453 |
+
dir: str | None = None # relative to the spec file; `flock launch` resolves it
|
| 454 |
+
command: list[str] | None = None # `{port}` and `{python}` are filled in by flock
|
| 455 |
+
url: str | None = None
|
| 456 |
+
token_env: str | None = None
|
| 457 |
+
# Written by the controller at apply; anything given by hand is replaced.
|
| 458 |
+
endpoint: str | None = None
|
| 459 |
+
manifest: WorldManifest | None = None
|
| 460 |
+
# Which credential this configuration belongs to, without the credential: the origin it is
|
| 461 |
+
# bound to (`endpoint`, or `local:<swarm>` for a world flock started) and
|
| 462 |
+
# HMAC(secret, origin). A worker sends its secret only when its own HMAC matches.
|
| 463 |
+
credential_origin: str | None = None
|
| 464 |
+
credential_id: str | None = None
|
| 465 |
+
# The world's Slurm job name, when it runs as one: health shows its squeue state, so a
|
| 466 |
+
# world waiting for a node (PENDING) is told apart from a crashed one (docs/health.md).
|
| 467 |
+
slurm_job_name: str | None = None
|
| 468 |
+
# Seconds the world may be down (health probe) before the controller pauses the types that
|
| 469 |
+
# use it; resumed when it is back (docs/health.md). None: FLOCK_WORLD_DOWN_PAUSE_S or 1800;
|
| 470 |
+
# 0: never. Controller only (not sent to workers).
|
| 471 |
+
down_pause_s: float | None = Field(default=None, ge=0)
|
| 472 |
+
|
| 473 |
+
@field_validator("command", mode="before")
|
| 474 |
+
@classmethod
|
| 475 |
+
def _command(cls, v: Any) -> Any:
|
| 476 |
+
if isinstance(v, str):
|
| 477 |
+
import shlex
|
| 478 |
+
|
| 479 |
+
v = shlex.split(v)
|
| 480 |
+
if v is not None and (not isinstance(v, list) or not v):
|
| 481 |
+
raise ValueError("command must be a non-empty list (or a string), e.g. "
|
| 482 |
+
"[flock, world, serve, \"taskboard:TaskBoard\"]")
|
| 483 |
+
return [str(x) for x in v] if v is not None else None
|
| 484 |
+
|
| 485 |
+
@field_validator("url", "endpoint")
|
| 486 |
+
@classmethod
|
| 487 |
+
def _url(cls, v: str | None) -> str | None:
|
| 488 |
+
if v is not None and not v.startswith(("http://", "https://")):
|
| 489 |
+
raise ValueError(f"url {v!r} must start with http:// or https://")
|
| 490 |
+
return v.rstrip("/") if v else v
|
| 491 |
+
|
| 492 |
+
@field_validator("token_env")
|
| 493 |
+
@classmethod
|
| 494 |
+
def _env(cls, v: str | None) -> str | None:
|
| 495 |
+
if v is not None and not ENV_NAME_RE.match(v):
|
| 496 |
+
raise ValueError(f"token_env {v!r} must be an env var name (the token never goes in "
|
| 497 |
+
"the spec)")
|
| 498 |
+
return v
|
| 499 |
+
|
| 500 |
+
@model_validator(mode="after")
|
| 501 |
+
def _how(self) -> WorldSpec:
|
| 502 |
+
if self.command is None and self.url is None:
|
| 503 |
+
raise ValueError("world needs `command` (started by flock, compute: local) or `url` "
|
| 504 |
+
"(a world already running)")
|
| 505 |
+
if self.dir is not None and self.command is None:
|
| 506 |
+
raise ValueError("world.dir is where `command` runs; give the command too")
|
| 507 |
+
return self
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def world_tools(ts: TypeSpec, world: WorldSpec | None) -> list[str]:
|
| 511 |
+
"""The world tools a type gets (model-visible names): the `world:*` entries of its `tools`,
|
| 512 |
+
else every tool of the world's manifest; none with `world: false`."""
|
| 513 |
+
if world is None or ts.world is False:
|
| 514 |
+
return []
|
| 515 |
+
listed = ([t.split(":", 1)[1] for t in ts.tools if t.startswith("world:")]
|
| 516 |
+
if isinstance(ts.tools, list) else [])
|
| 517 |
+
if listed:
|
| 518 |
+
return list(dict.fromkeys(listed))
|
| 519 |
+
return world.manifest.names() if world.manifest is not None else []
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
class WorkdirSpec(BaseModel):
|
| 523 |
+
"""Workdir size feedback and throwaway dirs (docs/design.md "Workdir"). Sizes count what the
|
| 524 |
+
bucket mirror keeps (sync excludes and `ephemeral` left out). Above `soft_*` the agent gets
|
| 525 |
+
a note naming its largest dirs (at most hourly); above `max_*` (default 5x soft) a
|
| 526 |
+
`workdir_over_quota` event too. Nothing is ever refused: the workdir still syncs."""
|
| 527 |
+
|
| 528 |
+
model_config = {"extra": "forbid"}
|
| 529 |
+
|
| 530 |
+
soft_files: int = Field(default=50_000, ge=1)
|
| 531 |
+
soft_mb: float = Field(default=2048.0, gt=0)
|
| 532 |
+
max_files: int | None = Field(default=None, ge=1) # None: 5 x soft_files
|
| 533 |
+
max_mb: float | None = Field(default=None, gt=0) # None: 5 x soft_mb
|
| 534 |
+
# dirs relative to the workdir: never synced, created at setup, wiped when the agent moves
|
| 535 |
+
ephemeral: list[str] = Field(default_factory=list)
|
| 536 |
+
# bucket layout (worker.sync "Base tar"): a tar of the workdir plus per-file deltas, rebuilt
|
| 537 |
+
# every base_interval_s or when the delta passes base_delta_files (changed + deleted)
|
| 538 |
+
base: bool = False
|
| 539 |
+
base_interval_s: float = Field(default=3600.0, gt=0)
|
| 540 |
+
base_delta_files: int = Field(default=5000, ge=1)
|
| 541 |
+
|
| 542 |
+
@field_validator("ephemeral")
|
| 543 |
+
@classmethod
|
| 544 |
+
def _relative_dirs(cls, v: list[str]) -> list[str]:
|
| 545 |
+
out = []
|
| 546 |
+
for d in v:
|
| 547 |
+
parts = [p for p in d.strip().split("/") if p not in ("", ".")]
|
| 548 |
+
if not parts or d.strip().startswith("/") or ".." in parts:
|
| 549 |
+
raise ValueError(f"ephemeral {d!r}: a directory relative to the workdir")
|
| 550 |
+
out.append("/".join(parts) + "/")
|
| 551 |
+
return out
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
class MemoryKnobs(BaseModel):
|
| 555 |
+
"""Worker memory thresholds, passed through as the FLOCK_MEM_* settings (worker.main)."""
|
| 556 |
+
|
| 557 |
+
model_config = {"extra": "forbid"}
|
| 558 |
+
|
| 559 |
+
rotate: float | None = None
|
| 560 |
+
drain: float | None = None
|
| 561 |
+
preempt: float | None = None
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
class WorkerKnobs(BaseModel):
|
| 565 |
+
"""A type's worker settings, applied live (heartbeats) by its workers. Each one unset
|
| 566 |
+
falls back to the worker's env variable, then to the built-in default (docs/slurm.md)."""
|
| 567 |
+
|
| 568 |
+
model_config = {"extra": "forbid"}
|
| 569 |
+
|
| 570 |
+
drain_budget_s: float | None = Field(default=None, gt=0) # FLOCK_DRAIN_BUDGET_S
|
| 571 |
+
sync_interval_s: float | None = Field(default=None, ge=10) # SYNC_INTERVAL
|
| 572 |
+
sync_exclude: list[str] | None = None # FLOCK_SYNC_EXCLUDE (added to the defaults)
|
| 573 |
+
restore_batch: int | None = Field(default=None, ge=1) # FLOCK_RESTORE_BATCH
|
| 574 |
+
restore_threads: int | None = Field(default=None, ge=1, le=32) # FLOCK_RESTORE_THREADS
|
| 575 |
+
memory: MemoryKnobs | None = None
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _duration(v: str) -> str:
|
| 579 |
+
if parse_duration(v).total_seconds() < 0:
|
| 580 |
+
raise ValueError("must be >= 0")
|
| 581 |
+
return v
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def _positive_duration(v: str) -> str:
|
| 585 |
+
if parse_duration(v).total_seconds() <= 0:
|
| 586 |
+
raise ValueError("must be > 0")
|
| 587 |
+
return v
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class RampPhase(BaseModel):
|
| 591 |
+
"""One phase of `replicas_ramp.phases`: `add` every `every` until `until` (default: the
|
| 592 |
+
ramp's `max`). The next phase starts where this one reached `until`. `stagger`: the
|
| 593 |
+
agents of each of its raises join this far apart."""
|
| 594 |
+
|
| 595 |
+
model_config = {"extra": "forbid"}
|
| 596 |
+
|
| 597 |
+
every: str
|
| 598 |
+
add: int = Field(ge=1)
|
| 599 |
+
until: int | None = Field(default=None, ge=1)
|
| 600 |
+
stagger: str = "0s"
|
| 601 |
+
|
| 602 |
+
_every = field_validator("every")(_positive_duration)
|
| 603 |
+
_stagger = field_validator("stagger")(_duration)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
class RampHold(BaseModel):
|
| 607 |
+
"""`replicas_ramp.hold_if`: a step that takes the swarm's replicas above `above` waits while any vLLM server of a `metrics: true` provider
|
| 608 |
+
had `waiting` or more requests queued in every sample of the last 2 minutes, or takes
|
| 609 |
+
more than `request_s` per request (running / completions per second), or its metrics
|
| 610 |
+
are missing, short or reset."""
|
| 611 |
+
|
| 612 |
+
model_config = {"extra": "forbid"}
|
| 613 |
+
|
| 614 |
+
waiting: float = Field(default=1, gt=0)
|
| 615 |
+
request_s: float = Field(default=15, gt=0, allow_inf_nan=False)
|
| 616 |
+
above: int = Field(default=100, ge=0)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class RampSpec(BaseModel):
|
| 620 |
+
"""`types.T.replicas_ramp` (docs/live.md "Ramp"): the controller raises the type's
|
| 621 |
+
replicas to `start`, then by `add` every `every` (or through `phases`), up to `max`. It
|
| 622 |
+
never lowers them: a lowered `max` only caps later raises. `stagger`: the `start` raise
|
| 623 |
+
adds one agent at a time this far apart (default 10 s)."""
|
| 624 |
+
|
| 625 |
+
model_config = {"extra": "forbid"}
|
| 626 |
+
|
| 627 |
+
start: int = Field(ge=0)
|
| 628 |
+
add: int | None = Field(default=None, ge=1)
|
| 629 |
+
every: str | None = None
|
| 630 |
+
max: int = Field(ge=1)
|
| 631 |
+
phases: list[RampPhase] = Field(default_factory=list)
|
| 632 |
+
stagger: str = "10s"
|
| 633 |
+
hold_if: RampHold | None = None
|
| 634 |
+
|
| 635 |
+
@field_validator("every")
|
| 636 |
+
@classmethod
|
| 637 |
+
def _every(cls, v: str | None) -> str | None:
|
| 638 |
+
return None if v is None else _positive_duration(v)
|
| 639 |
+
|
| 640 |
+
_stagger = field_validator("stagger")(_duration)
|
| 641 |
+
|
| 642 |
+
@model_validator(mode="after")
|
| 643 |
+
def _one_form(self) -> RampSpec:
|
| 644 |
+
if self.phases and (self.add is not None or self.every is not None):
|
| 645 |
+
raise ValueError("give `phases` or `add` and `every`, not both")
|
| 646 |
+
if not self.phases and (self.add is None or self.every is None):
|
| 647 |
+
raise ValueError("needs `add` and `every` (or `phases`)")
|
| 648 |
+
return self
|
| 649 |
+
|
| 650 |
+
def schedule(self) -> list[tuple[float, int, float]]:
|
| 651 |
+
"""(seconds from the ramp's start, replicas, stagger seconds) per step; step 0 is
|
| 652 |
+
`start` at 0."""
|
| 653 |
+
sec = lambda d: parse_duration(d).total_seconds()
|
| 654 |
+
t, n = 0.0, min(self.start, self.max)
|
| 655 |
+
out = [(t, n, sec(self.stagger))]
|
| 656 |
+
for ph in self.phases or [RampPhase(every=self.every, add=self.add)]:
|
| 657 |
+
until = min(ph.until or self.max, self.max)
|
| 658 |
+
while n < until:
|
| 659 |
+
t, n = t + sec(ph.every), min(n + ph.add, until)
|
| 660 |
+
out.append((t, n, sec(ph.stagger)))
|
| 661 |
+
return out
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class HarborSpec(BaseModel):
|
| 665 |
+
"""A `harness: harbor` type's Trial inputs, written by the compile step
|
| 666 |
+
(`flock.harbor.spec.compile_spec`), never by hand: each agent is one long-lived Harbor Trial
|
| 667 |
+
on the upstream Harbor task path. The worker composes the agent's instructions from `team`,
|
| 668 |
+
`role_text`, `roster` and the tools with the upstream `build_agent_instructions`."""
|
| 669 |
+
|
| 670 |
+
model_config = {"extra": "forbid"}
|
| 671 |
+
|
| 672 |
+
task: dict[str, Any] # ResolvedTask.manifest(): registry commit, dataset, the pinned task
|
| 673 |
+
# a partial flock.harbor Spec (model, inference, task, environment, limits, tools_dir,
|
| 674 |
+
# tools, resources_dir) for the upstream build_trial_config and the worker's HarborHost
|
| 675 |
+
config: dict[str, Any]
|
| 676 |
+
team: str = "" # the team_file's text
|
| 677 |
+
role: str | None = None # the role named in the instructions (None: agents.count)
|
| 678 |
+
role_text: str = "" # the role_file's text
|
| 679 |
+
# every replica's name -> role: with `naming: consecutive-id`, consecutive names compiled
|
| 680 |
+
# from the counts; with words empty here, and filled by the controller in each assign
|
| 681 |
+
roster: dict[str, str | None] = Field(default_factory=dict)
|
| 682 |
+
tools: dict[str, Any] = Field(default_factory=dict) # the tool bundle's manifest
|
| 683 |
+
tools_sha256: str | None = None
|
| 684 |
+
resources: dict[str, dict[str, Any]] = Field(default_factory=dict) # resource options
|
| 685 |
+
# the content hash of the run's tools and resources folders, packed by `flock launch` and
|
| 686 |
+
# uploaded as the swarm's tools bundle of that version: a worker fetches and unpacks it in
|
| 687 |
+
# its own run dir (None: config's tools_dir and resources_dir, read where they are)
|
| 688 |
+
folders: str | None = None
|
| 689 |
+
|
| 690 |
+
def names(self) -> list[str]:
|
| 691 |
+
"""This type's replica names by slot, with `naming: consecutive-id` (its roster's)."""
|
| 692 |
+
return [a for a, r in self.roster.items() if r == self.role]
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
class TypeSpec(BaseModel):
|
| 696 |
+
"""One agent type inside a swarm. See design.md 'Spec'."""
|
| 697 |
+
|
| 698 |
+
harness: Harness
|
| 699 |
+
# Resolution order (design.md 'Providers'): an alias under `models:`, else "<provider>:<id>"
|
| 700 |
+
# with the prefix under `providers:`; SwarmSpec refuses a model that names no provider.
|
| 701 |
+
model: str
|
| 702 |
+
reasoning: Reasoning | None = None # overrides the alias's reasoning
|
| 703 |
+
image: str | None = None # None -> default worker image
|
| 704 |
+
system_prompt_file: str | None = None # written into the workdir as AGENTS.md
|
| 705 |
+
# The file's contents, inlined by `flock launch` (the controller and workers cannot
|
| 706 |
+
# read the caller's files). Wins over system_prompt_file on the worker.
|
| 707 |
+
system_prompt: str | None = None
|
| 708 |
+
# A second file appended to the system prompt by `flock launch` (after a blank line): a
|
| 709 |
+
# per-type section on top of a prompt several types share (e.g. a spawner and its
|
| 710 |
+
# child types). The worker only sees the combined `system_prompt`.
|
| 711 |
+
system_prompt_append_file: str | None = None
|
| 712 |
+
env: dict[str, str] = Field(default_factory=dict)
|
| 713 |
+
secrets: list[str] = Field(default_factory=list) # names of secrets the job receives
|
| 714 |
+
labels: dict[str, str] = Field(default_factory=dict)
|
| 715 |
+
replicas: int = 0
|
| 716 |
+
# measured defaults
|
| 717 |
+
agents_per_worker: int = 50
|
| 718 |
+
max_working_per_worker: int = 20
|
| 719 |
+
# Agents of this type in a turn at once, swarm-wide, admitted like a provider's
|
| 720 |
+
# `max_working` (both apply). Controller only.
|
| 721 |
+
max_working: int | None = Field(default=None, ge=1)
|
| 722 |
+
replicas_ramp: RampSpec | None = None # controller only (docs/live.md "Ramp")
|
| 723 |
+
# Worker slots for this type, declared only (docs/spawn.md). Required for a type that
|
| 724 |
+
# `spawn:` lets others create; None: unbounded.
|
| 725 |
+
workers: WorkersSpec | None = None
|
| 726 |
+
# Spawned agents of this type live for one session (docs/spawn.md "Ephemeral types"): the
|
| 727 |
+
# controller removes one once a heartbeat reports it idle after a turn with nothing pending
|
| 728 |
+
# (done, max_turns, budget or an error alike), and its worker deletes its files. Spawn-only.
|
| 729 |
+
ephemeral: bool = False
|
| 730 |
+
# With the swarm's `naming: words`: put before every name of this type (e.g. "iv-" for
|
| 731 |
+
# interviewers), so roles stay recognizable. Lowercase letters and hyphens, ending in "-".
|
| 732 |
+
name_prefix: str | None = None
|
| 733 |
+
flavor: str = "cpu-basic"
|
| 734 |
+
worker_lifetime: str = "24h"
|
| 735 |
+
lifetime_jitter: str = "4h"
|
| 736 |
+
drain_window: str = "10m"
|
| 737 |
+
idle_grace: str = "120s"
|
| 738 |
+
turn_timeout: str = "30m"
|
| 739 |
+
max_turns: int | None = None # per prompt, passed to the harness
|
| 740 |
+
max_budget_usd: float | None = None # per prompt, passed to the harness
|
| 741 |
+
persist_workdir: bool = True
|
| 742 |
+
workdir: WorkdirSpec | None = None # None: WorkdirSpec() defaults
|
| 743 |
+
worker: WorkerKnobs | None = None # None: the worker's env, then built-in defaults
|
| 744 |
+
resume_prompt: str | None = None
|
| 745 |
+
# Tools from the swarm's tools folder: a list of function names, or "all".
|
| 746 |
+
# `flock launch` refuses a name the folder does not define. None: no folder tools.
|
| 747 |
+
tools: list[str] | Literal["all"] | None = None
|
| 748 |
+
# Re-prompt this type's agents on a cadence, then a final round (docs/loop.md). None: off.
|
| 749 |
+
loop: LoopSpec | None = None
|
| 750 |
+
# Built-in comms tools (docs/comms.md): true gives all of them (`comms:post`, `comms:read`,
|
| 751 |
+
# `comms:search`), or list the ones wanted in `tools`. Needs the swarm-level `comms:`.
|
| 752 |
+
comms: bool | None = None
|
| 753 |
+
# World tools (docs/world.md): every tool of the swarm's `world:` unless `tools` lists
|
| 754 |
+
# `world:<name>` entries (then only those); false: none.
|
| 755 |
+
world: bool | None = None
|
| 756 |
+
# harness harbor only (and required there): written by the compile step
|
| 757 |
+
harbor: HarborSpec | None = None
|
| 758 |
+
# Written by SwarmSpec validation (apply time), never by hand: anything given here is
|
| 759 |
+
# replaced. None until the type is validated inside a SwarmSpec.
|
| 760 |
+
resolved_model: ResolvedModel | None = None
|
| 761 |
+
|
| 762 |
+
@property
|
| 763 |
+
def folder_tools(self) -> list[str] | Literal["all"] | None:
|
| 764 |
+
"""`tools` without the built-in `comms:*` and the `world:*` entries: what the tools
|
| 765 |
+
folder must define (None when nothing is left)."""
|
| 766 |
+
if not isinstance(self.tools, list):
|
| 767 |
+
return self.tools
|
| 768 |
+
names = [t for t in self.tools if not t.startswith(("comms:", "world:"))]
|
| 769 |
+
return names or None
|
| 770 |
+
|
| 771 |
+
@field_validator("tools")
|
| 772 |
+
@classmethod
|
| 773 |
+
def _known_comms(cls, v: list[str] | str | None) -> list[str] | str | None:
|
| 774 |
+
if isinstance(v, list):
|
| 775 |
+
bad = [t for t in v if t.startswith("comms:") and t not in ALL_COMMS_TOOLS]
|
| 776 |
+
if bad:
|
| 777 |
+
raise ValueError(f"unknown comms tool(s) {', '.join(bad)}; comms tools: "
|
| 778 |
+
f"{', '.join(COMMS_TOOLS)}")
|
| 779 |
+
bad = [t for t in v if t.startswith("world:") and not WORLD_TOOL_RE.match(t[6:])]
|
| 780 |
+
if bad:
|
| 781 |
+
raise ValueError(f"bad world tool name(s) {', '.join(bad)}: world:<tool name>")
|
| 782 |
+
return v
|
| 783 |
+
|
| 784 |
+
@property
|
| 785 |
+
def harness_model(self) -> str:
|
| 786 |
+
"""The model id the harness is started with."""
|
| 787 |
+
return self.resolved_model.model_id if self.resolved_model else self.model
|
| 788 |
+
|
| 789 |
+
@property
|
| 790 |
+
def provider_name(self) -> str | None:
|
| 791 |
+
return self.resolved_model.provider_name if self.resolved_model else None
|
| 792 |
+
|
| 793 |
+
@property
|
| 794 |
+
def effective_reasoning(self) -> Reasoning | None:
|
| 795 |
+
if self.resolved_model is not None:
|
| 796 |
+
return self.resolved_model.reasoning
|
| 797 |
+
return self.reasoning
|
| 798 |
+
|
| 799 |
+
@field_validator(
|
| 800 |
+
"worker_lifetime", "lifetime_jitter", "drain_window", "idle_grace", "turn_timeout"
|
| 801 |
+
)
|
| 802 |
+
@classmethod
|
| 803 |
+
def _valid_duration(cls, v: str) -> str:
|
| 804 |
+
parse_duration(v)
|
| 805 |
+
return v
|
| 806 |
+
|
| 807 |
+
@field_validator("name_prefix")
|
| 808 |
+
@classmethod
|
| 809 |
+
def _name_prefix(cls, v: str | None) -> str | None:
|
| 810 |
+
if v is not None and not re.fullmatch(r"[a-z]+(-[a-z]+)*-", v):
|
| 811 |
+
raise ValueError(f"name_prefix {v!r}: lowercase letters and hyphens, ending in '-' "
|
| 812 |
+
"(e.g. 'iv-')")
|
| 813 |
+
return v
|
| 814 |
+
|
| 815 |
+
@field_validator("replicas", "agents_per_worker", "max_working_per_worker")
|
| 816 |
+
@classmethod
|
| 817 |
+
def _non_negative(cls, v: int) -> int:
|
| 818 |
+
if v < 0:
|
| 819 |
+
raise ValueError("must be >= 0")
|
| 820 |
+
return v
|
| 821 |
+
|
| 822 |
+
@model_validator(mode="after")
|
| 823 |
+
def _checks(self) -> TypeSpec:
|
| 824 |
+
if self.ephemeral and self.replicas:
|
| 825 |
+
raise ValueError("ephemeral: true is for spawned agents only; set replicas: 0")
|
| 826 |
+
if self.harbor is None:
|
| 827 |
+
raise ValueError("harness harbor needs the `harbor:` block (written by the compile "
|
| 828 |
+
"step of a flock.harbor spec)")
|
| 829 |
+
return self
|
| 830 |
+
|
| 831 |
+
@field_validator("workers")
|
| 832 |
+
@classmethod
|
| 833 |
+
def _replicas_fit(cls, v: WorkersSpec | None, info) -> WorkersSpec | None:
|
| 834 |
+
"""Declared workers are a cap (docs/spawn.md): the replicas must fit in them."""
|
| 835 |
+
replicas, per = info.data.get("replicas"), info.data.get("agents_per_worker")
|
| 836 |
+
if v is None or v.initial is None or replicas is None or per is None:
|
| 837 |
+
return v
|
| 838 |
+
room = (v.initial + v.max_extra) * max(1, per)
|
| 839 |
+
if replicas > room:
|
| 840 |
+
raise ValueError(
|
| 841 |
+
f"replicas {replicas} do not fit in workers.initial + workers.max_extra = "
|
| 842 |
+
f"{v.initial + v.max_extra} workers x agents_per_worker {per} = {room} agents"
|
| 843 |
+
)
|
| 844 |
+
return v
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
_MEM = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([KMGT]?)B?\s*$", re.IGNORECASE)
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def mem_mb(value: str) -> float:
|
| 851 |
+
"""sbatch --mem as MB: a bare number is MB; K/M/G/T suffixes (1024-based)."""
|
| 852 |
+
m = _MEM.match(str(value))
|
| 853 |
+
if not m:
|
| 854 |
+
raise ValueError(f"memory {value!r}: expected a number with K, M, G or T")
|
| 855 |
+
scale = {"": 1, "K": 1 / 1024, "M": 1, "G": 1024, "T": 1024 * 1024}[m.group(2).upper()]
|
| 856 |
+
return float(m.group(1)) * scale
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def size_problem(cpus: int | str | None, mem: str | None, max_cpus: int | str | None,
|
| 860 |
+
max_mem: str | None) -> str | None:
|
| 861 |
+
"""Why a job of this size can never start on the partition (None: it fits, or no limit)."""
|
| 862 |
+
try:
|
| 863 |
+
if cpus is not None and max_cpus and int(cpus) > int(max_cpus):
|
| 864 |
+
return f"cpus {cpus} is over max_cpus {max_cpus}: the job would pend forever"
|
| 865 |
+
if mem is not None and mem_mb(mem) > (mem_mb(max_mem) if max_mem else float("inf")):
|
| 866 |
+
return f"mem {mem} is over max_mem {max_mem}: the job would pend forever"
|
| 867 |
+
except ValueError as e:
|
| 868 |
+
return str(e)
|
| 869 |
+
return None
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
class SlurmResources(BaseModel):
|
| 873 |
+
"""Per-type overrides of a `compute: slurm` spec."""
|
| 874 |
+
|
| 875 |
+
model_config = {"extra": "forbid"}
|
| 876 |
+
|
| 877 |
+
partition: str | None = None
|
| 878 |
+
cpus: int | None = Field(default=None, ge=1)
|
| 879 |
+
mem: str | None = None
|
| 880 |
+
time: str | None = None
|
| 881 |
+
container_root: str | None = None
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
class ComputeSpec(BaseModel):
|
| 885 |
+
"""Where workers run (docs/local.md). `hf-jobs` (the default): one HF Job per worker.
|
| 886 |
+
`local`: one `python -m flock.worker.main` subprocess per worker on the controller's machine
|
| 887 |
+
(`flock launch` runs them on this machine). `slurm`: one `sbatch` job per worker (docs/slurm.md).
|
| 888 |
+
The spec also accepts the short form `compute: local`.
|
| 889 |
+
|
| 890 |
+
`worker_unknown_after`, `worker_dead_after` and `crash_backoff` are for every backend
|
| 891 |
+
(docs/live.md "Worker liveness"). The other keys are for `slurm` and win over the
|
| 892 |
+
controller's FLOCK_SLURM_* env, which only fills unset keys (then built-in defaults).
|
| 893 |
+
`types` sets per-type `cpus`/`mem`/`time`/`partition` (an interviewer type needs less
|
| 894 |
+
than an agent)."""
|
| 895 |
+
|
| 896 |
+
model_config = {"extra": "forbid"}
|
| 897 |
+
|
| 898 |
+
kind: Literal[tuple(COMPUTE)] = "hf-jobs" # type: ignore[valid-type]
|
| 899 |
+
partition: str | None = None
|
| 900 |
+
account: str | None = None
|
| 901 |
+
cpus: int | None = Field(default=None, ge=1)
|
| 902 |
+
mem: str | None = None # sbatch --mem, e.g. 7G
|
| 903 |
+
time: str | None = None # sbatch --time, e.g. 29:00:00
|
| 904 |
+
worker_script: str | None = None # the cluster's worker sbatch script; $1 = the env file
|
| 905 |
+
log_dir: str | None = None # shared dir: <log_dir>/<worker id>-<job id>.out
|
| 906 |
+
launch_dir: str | None = None # shared dir: <worker id>-<incarnation>.env, no secrets
|
| 907 |
+
host_file: str | None = None # shared file holding the controller's hostname
|
| 908 |
+
run: str | None = None # RUN= in the env file; default: the launch_dir's parent dir name
|
| 909 |
+
venv: str | None = None # written to the env file as FLOCK_VENV for the script
|
| 910 |
+
secrets_file: str | None = None # path only, as FLOCK_SECRETS_FILE; never read by flock
|
| 911 |
+
# workers run in a container whose /tmp is RAM: every agent/harness path goes under this
|
| 912 |
+
# root instead: <root>/flock/<worker id>/{work,home,hf,tmp}
|
| 913 |
+
container_root: str | None = None
|
| 914 |
+
container_image: str | None = None # an Enroot image (.sqsh): FLOCK_CONTAINER_IMAGE
|
| 915 |
+
|
| 916 |
+
@model_serializer(mode="wrap")
|
| 917 |
+
def _compact(self, handler: Any) -> Any:
|
| 918 |
+
"""Only the keys that are set: `{kind: local}` stays `{kind: local}` in dumps."""
|
| 919 |
+
out = handler(self)
|
| 920 |
+
if not isinstance(out, dict):
|
| 921 |
+
return out
|
| 922 |
+
return {k: v for k, v in out.items() if k == "kind" or (v is not None and v != {})}
|
| 923 |
+
types: dict[str, SlurmResources] = Field(default_factory=dict)
|
| 924 |
+
# the largest job the partition can ever run: sbatch accepts bigger ones, which then pend
|
| 925 |
+
# forever; a launch over these is refused (also checked at apply). None: not checked (the
|
| 926 |
+
# controller's FLOCK_SLURM_MAX_CPUS/_MEM, from the cluster profile, still apply at launch)
|
| 927 |
+
max_cpus: int | None = Field(default=None, ge=1)
|
| 928 |
+
max_mem: str | None = None
|
| 929 |
+
# worker liveness (docs/live.md "Worker liveness"); None: the backend's default (`liveness`)
|
| 930 |
+
worker_unknown_after: str | None = None
|
| 931 |
+
worker_dead_after: str | None = None
|
| 932 |
+
crash_backoff: str | None = None
|
| 933 |
+
|
| 934 |
+
@field_validator("worker_unknown_after", "worker_dead_after", "crash_backoff")
|
| 935 |
+
@classmethod
|
| 936 |
+
def _timing(cls, v: str | None) -> str | None:
|
| 937 |
+
return None if v is None else _positive_duration(v)
|
| 938 |
+
|
| 939 |
+
@model_validator(mode="after")
|
| 940 |
+
def _check_liveness(self) -> ComputeSpec:
|
| 941 |
+
lv = self.liveness()
|
| 942 |
+
hb = (LOCAL_HEARTBEAT_INTERVAL if self.kind == "local"
|
| 943 |
+
else HEARTBEAT_INTERVAL).total_seconds()
|
| 944 |
+
if lv.unknown_after < 2 * hb: # a healthy worker would look silent and be relaunched
|
| 945 |
+
raise ValueError(f"worker_unknown_after ({lv.unknown_after:g}s) must be at least "
|
| 946 |
+
f"{2 * hb:g}s: two heartbeats at the {self.kind} interval ({hb:g}s)")
|
| 947 |
+
if lv.unknown_after >= lv.dead_after:
|
| 948 |
+
dflt = lambda v: "" if v else " (default)"
|
| 949 |
+
raise ValueError(
|
| 950 |
+
f"worker_unknown_after ({lv.unknown_after:g}s{dflt(self.worker_unknown_after)}) "
|
| 951 |
+
f"must be shorter than worker_dead_after "
|
| 952 |
+
f"({lv.dead_after:g}s{dflt(self.worker_dead_after)})")
|
| 953 |
+
return self
|
| 954 |
+
|
| 955 |
+
def liveness(self) -> Liveness:
|
| 956 |
+
"""Worker liveness timings in seconds: the keys set here, else the backend's defaults."""
|
| 957 |
+
dflt = (LOCAL_LIVENESS if self.kind == "local"
|
| 958 |
+
else (UNKNOWN_AFTER, DEAD_AFTER, CRASH_BACKOFF))
|
| 959 |
+
keys = (self.worker_unknown_after, self.worker_dead_after, self.crash_backoff)
|
| 960 |
+
return Liveness(*(parse_duration(v or d).total_seconds() for v, d in zip(keys, dflt)))
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
class SwarmSpec(BaseModel):
|
| 964 |
+
swarm: str
|
| 965 |
+
# HF namespace jobs are launched under, and the bucket agents sync to (e.g.
|
| 966 |
+
# hf://buckets/<namespace>/<bucket>). Required for compute hf-jobs; optional for compute local.
|
| 967 |
+
namespace: str = ""
|
| 968 |
+
bucket: str = ""
|
| 969 |
+
providers: dict[str, ProviderSpec] = Field(default_factory=dict)
|
| 970 |
+
models: dict[str, ModelSpec] = Field(default_factory=dict)
|
| 971 |
+
types: dict[str, TypeSpec]
|
| 972 |
+
# The tools folder, relative to the spec file; None: `tools/` next to it.
|
| 973 |
+
# Read by `flock launch` only.
|
| 974 |
+
tools_dir: str | None = None
|
| 975 |
+
# Content hash of the tools bundle, written by `flock launch` after uploading the folder
|
| 976 |
+
# (anything given by hand is replaced). Workers fetch that version; None: no tools.
|
| 977 |
+
tools_version: str | None = None
|
| 978 |
+
# The team's message board (docs/comms.md); None: no comms.
|
| 979 |
+
comms: CommsSpec | None = None
|
| 980 |
+
# The swarm's world (docs/world.md); None: no world.
|
| 981 |
+
world: WorldSpec | None = None
|
| 982 |
+
# The run's flock-overview row (docs/dashboard.md); None: not registered.
|
| 983 |
+
dashboard: DashboardSpec | None = None
|
| 984 |
+
# How agents are named (docs/spawn.md "Names"): `numeric` (`<type>-NNNN`, children
|
| 985 |
+
# `<parent>-<type>-NNNN`), `words` (`<adjective>-<noun>`, unique on the controller,
|
| 986 |
+
# reserved and never reused while the swarm exists; a Harbor spec's default) or
|
| 987 |
+
# `consecutive-id` (Harbor types: their roster's names, consecutive `agent-001`, ...;
|
| 988 |
+
# children as numeric).
|
| 989 |
+
naming: Literal["numeric", "words", "consecutive-id"] = "numeric"
|
| 990 |
+
|
| 991 |
+
@field_validator("tools_version")
|
| 992 |
+
@classmethod
|
| 993 |
+
def _valid_tools_version(cls, v: str | None) -> str | None:
|
| 994 |
+
if v is not None and not TOOLS_VERSION_RE.match(v):
|
| 995 |
+
raise ValueError("tools_version is written by `flock launch` (16 hex digits)")
|
| 996 |
+
return v
|
| 997 |
+
|
| 998 |
+
@field_validator("providers")
|
| 999 |
+
@classmethod
|
| 1000 |
+
def _valid_providers(cls, v: dict[str, ProviderSpec]) -> dict[str, ProviderSpec]:
|
| 1001 |
+
for name in v:
|
| 1002 |
+
if not PROVIDER_NAME_RE.match(name):
|
| 1003 |
+
raise ValueError(f"providers.{name}: name must be lowercase [a-z0-9_-], starting with a letter")
|
| 1004 |
+
return v
|
| 1005 |
+
|
| 1006 |
+
@model_validator(mode="after")
|
| 1007 |
+
def _resolve_models(self) -> SwarmSpec:
|
| 1008 |
+
"""Apply-time checks and pinning: every alias and provider prefix exists, every
|
| 1009 |
+
provider-backed model has a price, harness and provider speak the same API. The price
|
| 1010 |
+
used is written into the spec (`resolved_model.pricing`, and the self-hosted default
|
| 1011 |
+
into the provider's `pricing`), so the stored spec carries what cost is derived from."""
|
| 1012 |
+
for alias, m in self.models.items():
|
| 1013 |
+
if ":" in alias:
|
| 1014 |
+
raise ValueError(f"models.{alias}: an alias cannot contain ':'")
|
| 1015 |
+
prefix, sep, model_id = m.model.partition(":")
|
| 1016 |
+
if not sep or not prefix or not model_id:
|
| 1017 |
+
raise ValueError(f"models.{alias}.model: {m.model!r} must look like '<provider>:<model id>'")
|
| 1018 |
+
if prefix not in self.providers:
|
| 1019 |
+
raise ValueError(f"models.{alias}.model: unknown provider {prefix!r} in {m.model!r}; "
|
| 1020 |
+
f"providers: {sorted(self.providers)}")
|
| 1021 |
+
for type_name, ts in self.types.items():
|
| 1022 |
+
ts.resolved_model = resolve_model(self, ts, type_name=type_name)
|
| 1023 |
+
r = ts.resolved_model
|
| 1024 |
+
if r is None:
|
| 1025 |
+
raise ValueError(
|
| 1026 |
+
f"types.{type_name}.model: harness {ts.harness.value!r} needs a provider-backed "
|
| 1027 |
+
f"model ('<provider>:<model id>' or an alias); {ts.model!r} names no provider")
|
| 1028 |
+
want = HARNESSES[ts.harness].provider_type
|
| 1029 |
+
if r.provider.type != want:
|
| 1030 |
+
raise ValueError(
|
| 1031 |
+
f"types.{type_name}.model: harness {ts.harness.value!r} cannot use provider "
|
| 1032 |
+
f"{r.provider_name!r} (type {r.provider.type}); {ts.harness.value} needs a "
|
| 1033 |
+
f"provider of type {want}")
|
| 1034 |
+
p = self.providers[r.provider_name]
|
| 1035 |
+
if p.self_hosted and r.model_id not in p.pricing and "*" not in p.pricing:
|
| 1036 |
+
p.pricing[r.model_id] = list(SELF_HOSTED_PRICING) # pin the default
|
| 1037 |
+
for type_name, ts in self.types.items():
|
| 1038 |
+
cap = ts.loop.while_.agent_usd if ts.loop else None
|
| 1039 |
+
if isinstance(cap, dict) and agent_cap(ts) is None:
|
| 1040 |
+
raise ValueError(
|
| 1041 |
+
f"types.{type_name}.loop.while.agent_usd: no entry for model {ts.model!r} "
|
| 1042 |
+
f"(keys: {sorted(cap)}); key it by the type's model alias or model id")
|
| 1043 |
+
return self
|
| 1044 |
+
|
| 1045 |
+
@model_validator(mode="after")
|
| 1046 |
+
def _check_comms(self) -> SwarmSpec:
|
| 1047 |
+
"""A type that wants comms tools needs the swarm's `comms:` block; a listed
|
| 1048 |
+
`comms:search` needs `comms.search`; `comms: false` with listed comms tools is a
|
| 1049 |
+
contradiction."""
|
| 1050 |
+
for name, ts in self.types.items():
|
| 1051 |
+
listed = [t for t in ts.tools if t in ALL_COMMS_TOOLS] if isinstance(ts.tools, list) else []
|
| 1052 |
+
if (ts.comms or listed) and self.comms is None:
|
| 1053 |
+
raise ValueError(f"types.{name}: comms tools need the swarm-level `comms:` block "
|
| 1054 |
+
"(kind, url, invite_env, channel)")
|
| 1055 |
+
if ts.comms is False and listed:
|
| 1056 |
+
raise ValueError(f"types.{name}: comms: false but tools lists {', '.join(listed)}")
|
| 1057 |
+
if "comms:search" in listed and self.comms is not None and not self.comms.search:
|
| 1058 |
+
raise ValueError(f"types.{name}.tools: comms:search needs comms.search (board)")
|
| 1059 |
+
for name, ts in self.types.items(): # world tools (docs/world.md)
|
| 1060 |
+
listed = ([t for t in ts.tools if t.startswith("world:")]
|
| 1061 |
+
if isinstance(ts.tools, list) else [])
|
| 1062 |
+
if (ts.world or listed) and self.world is None:
|
| 1063 |
+
raise ValueError(f"types.{name}: world tools need the swarm-level `world:` block "
|
| 1064 |
+
"(command or url)")
|
| 1065 |
+
if ts.world is False and listed:
|
| 1066 |
+
raise ValueError(f"types.{name}: world: false but tools lists {', '.join(listed)}")
|
| 1067 |
+
if self.dashboard is not None and (self.compute.kind == "local" or not self.bucket):
|
| 1068 |
+
raise ValueError("dashboard: needs the run's state in a bucket (`bucket:`, compute "
|
| 1069 |
+
"hf-jobs or slurm); compute: local keeps it on this machine")
|
| 1070 |
+
c = self.comms
|
| 1071 |
+
if c is not None and c.protocols_text and len(c.protocols_text) != len(c.protocols):
|
| 1072 |
+
raise ValueError("comms.protocols_text is written by `flock launch` (one per protocols file)")
|
| 1073 |
+
return self
|
| 1074 |
+
|
| 1075 |
+
@field_validator("swarm")
|
| 1076 |
+
@classmethod
|
| 1077 |
+
def _valid_swarm(cls, v: str) -> str:
|
| 1078 |
+
if not TYPE_NAME_RE.match(v):
|
| 1079 |
+
raise ValueError("swarm name must be lowercase [a-z0-9-], starting with a letter")
|
| 1080 |
+
return v
|
| 1081 |
+
|
| 1082 |
+
# Run policy for spawned agents (docs/spawn.md), separate from what a type is. A type
|
| 1083 |
+
# absent from `spawn` cannot spawn.
|
| 1084 |
+
spawn: dict[str, SpawnRule] = Field(default_factory=dict)
|
| 1085 |
+
limits: LimitsSpec = Field(default_factory=lambda: LimitsSpec())
|
| 1086 |
+
compute: ComputeSpec = Field(default_factory=ComputeSpec)
|
| 1087 |
+
|
| 1088 |
+
@field_validator("compute", mode="before")
|
| 1089 |
+
@classmethod
|
| 1090 |
+
def _compute_short(cls, v: Any) -> Any:
|
| 1091 |
+
return {"kind": v} if isinstance(v, str) else v
|
| 1092 |
+
|
| 1093 |
+
@model_validator(mode="after")
|
| 1094 |
+
def _job_fields(self) -> SwarmSpec:
|
| 1095 |
+
kind = self.compute.kind
|
| 1096 |
+
unknown = self.compute.liveness().unknown_after
|
| 1097 |
+
for name, ts in self.types.items(): # a type's own HEARTBEAT_INTERVAL slows its heartbeats
|
| 1098 |
+
try:
|
| 1099 |
+
hb = float(ts.env["HEARTBEAT_INTERVAL"])
|
| 1100 |
+
except (KeyError, ValueError):
|
| 1101 |
+
continue
|
| 1102 |
+
if 2 * hb > unknown:
|
| 1103 |
+
raise ValueError(f"types.{name}.env.HEARTBEAT_INTERVAL ({hb:g}s): two heartbeats "
|
| 1104 |
+
f"({2 * hb:g}s) exceed worker_unknown_after ({unknown:g}s); "
|
| 1105 |
+
f"raise worker_unknown_after or lower the interval")
|
| 1106 |
+
if kind == "hf-jobs":
|
| 1107 |
+
missing = [f for f in ("namespace", "bucket") if not getattr(self, f)]
|
| 1108 |
+
if missing:
|
| 1109 |
+
raise ValueError(f"{' and '.join(missing)} required for compute hf-jobs "
|
| 1110 |
+
"(or set `compute: local`, docs/local.md)")
|
| 1111 |
+
elif kind != "local" and not self.bucket:
|
| 1112 |
+
# agent state goes to an HF bucket on every remote backend, never to a shared disk
|
| 1113 |
+
raise ValueError(f"bucket is required for compute {kind}")
|
| 1114 |
+
if kind != "local" and self.world is not None and self.world.url is None:
|
| 1115 |
+
raise ValueError(f"world.url is required for compute {kind}: run the world as a "
|
| 1116 |
+
"Job, Space or cluster job and give its url (starting it from "
|
| 1117 |
+
"`command` is compute: local only, docs/world.md)")
|
| 1118 |
+
if kind == "slurm":
|
| 1119 |
+
sizes = [("compute", self.compute.cpus, self.compute.mem)] + [
|
| 1120 |
+
(f"compute.types.{n}", r.cpus, r.mem) for n, r in self.compute.types.items()]
|
| 1121 |
+
for where, cpus, mem in sizes:
|
| 1122 |
+
if problem := size_problem(cpus, mem, self.compute.max_cpus,
|
| 1123 |
+
self.compute.max_mem):
|
| 1124 |
+
raise ValueError(f"{where}: {problem}")
|
| 1125 |
+
unknown = set(self.compute.types) - set(self.types)
|
| 1126 |
+
if unknown:
|
| 1127 |
+
raise ValueError(f"compute.types names unknown types: {sorted(unknown)}")
|
| 1128 |
+
return self
|
| 1129 |
+
|
| 1130 |
+
@field_validator("spawn")
|
| 1131 |
+
@classmethod
|
| 1132 |
+
def _valid_spawn(cls, v: dict[str, SpawnRule], info) -> dict[str, SpawnRule]:
|
| 1133 |
+
types = info.data.get("types")
|
| 1134 |
+
if types is not None:
|
| 1135 |
+
validate_spawn(v, types)
|
| 1136 |
+
return v
|
| 1137 |
+
|
| 1138 |
+
@field_validator("types")
|
| 1139 |
+
@classmethod
|
| 1140 |
+
def _valid_types(cls, v: dict[str, TypeSpec]) -> dict[str, TypeSpec]:
|
| 1141 |
+
for name in v:
|
| 1142 |
+
if not TYPE_NAME_RE.match(name):
|
| 1143 |
+
raise ValueError(f"type name {name!r} must be lowercase [a-z0-9-]")
|
| 1144 |
+
return v
|
| 1145 |
+
|
| 1146 |
+
|
| 1147 |
+
def resolve_model(spec: SwarmSpec, type_spec: TypeSpec, *, type_name: str = "?") -> ResolvedModel | None:
|
| 1148 |
+
"""Resolve a type's `model`: alias under `models:` -> "<provider>:<id>" with the prefix
|
| 1149 |
+
under `providers:`; None when it names no provider. Raises ValueError naming the type
|
| 1150 |
+
and field for an unknown provider prefix or a provider-backed model with no price."""
|
| 1151 |
+
where = f"types.{type_name}.model"
|
| 1152 |
+
alias = spec.models.get(type_spec.model)
|
| 1153 |
+
target = alias.model if alias else type_spec.model
|
| 1154 |
+
prefix, sep, model_id = target.partition(":")
|
| 1155 |
+
if not sep or not PROVIDER_NAME_RE.match(prefix):
|
| 1156 |
+
return None # names no provider
|
| 1157 |
+
if prefix not in spec.providers:
|
| 1158 |
+
raise ValueError(f"{where}: unknown provider {prefix!r} in {target!r}; declare it under "
|
| 1159 |
+
f"providers: (known: {sorted(spec.providers)}) or use a model alias")
|
| 1160 |
+
if not model_id:
|
| 1161 |
+
raise ValueError(f"{where}: {target!r} has no model id after '{prefix}:'")
|
| 1162 |
+
provider = spec.providers[prefix]
|
| 1163 |
+
pricing = (alias.pricing if alias else None) or provider.pricing.get(model_id) or provider.pricing.get("*")
|
| 1164 |
+
if pricing is None:
|
| 1165 |
+
if not provider.self_hosted:
|
| 1166 |
+
raise ValueError(
|
| 1167 |
+
f"{where}: no pricing for {target!r}; add providers.{prefix}.pricing"
|
| 1168 |
+
f"[{model_id!r}] = [input, output, cached] (USD per 1M tokens)"
|
| 1169 |
+
+ (f" or models.{type_spec.model}.pricing" if alias else "")
|
| 1170 |
+
+ f", or mark providers.{prefix} self_hosted")
|
| 1171 |
+
pricing = list(SELF_HOSTED_PRICING)
|
| 1172 |
+
return ResolvedModel(
|
| 1173 |
+
provider_name=prefix,
|
| 1174 |
+
provider=provider,
|
| 1175 |
+
model_id=model_id,
|
| 1176 |
+
reasoning=type_spec.reasoning or (alias.reasoning if alias else None),
|
| 1177 |
+
extra=alias.extra if alias else None,
|
| 1178 |
+
pricing=list(pricing),
|
| 1179 |
+
)
|
| 1180 |
+
|
| 1181 |
+
|
| 1182 |
+
def agent_name(type_name: str, slot: int) -> str:
|
| 1183 |
+
return f"{type_name}-{slot:04d}"
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
# --------------------------------------------------------------------------- spawn
|
| 1187 |
+
|
| 1188 |
+
|
| 1189 |
+
class WorkersSpec(BaseModel):
|
| 1190 |
+
"""Worker slots a type may use: `initial` (default: `ceil(replicas /
|
| 1191 |
+
agents_per_worker)`) plus up to `max_extra` opened on demand for spawned agents."""
|
| 1192 |
+
|
| 1193 |
+
initial: int | None = None
|
| 1194 |
+
max_extra: int = 0
|
| 1195 |
+
|
| 1196 |
+
@field_validator("initial", "max_extra")
|
| 1197 |
+
@classmethod
|
| 1198 |
+
def _non_negative(cls, v: int | None) -> int | None:
|
| 1199 |
+
if v is not None and v < 0:
|
| 1200 |
+
raise ValueError("must be >= 0")
|
| 1201 |
+
return v
|
| 1202 |
+
|
| 1203 |
+
|
| 1204 |
+
class SpawnRule(BaseModel):
|
| 1205 |
+
"""What an agent of one type may spawn. `types` is a list (with one total `max`) or a map
|
| 1206 |
+
of per-type caps (`max` then an optional total cap). Caps count the parent's existing
|
| 1207 |
+
children. `depth` is the generations allowed below the agent (0: cannot spawn). Unknown
|
| 1208 |
+
keys are rejected, so a misspelled or unsupported policy field never passes silently."""
|
| 1209 |
+
|
| 1210 |
+
model_config = {"extra": "forbid"}
|
| 1211 |
+
|
| 1212 |
+
types: list[str] | dict[str, int]
|
| 1213 |
+
max: int | None = None
|
| 1214 |
+
depth: int = 1
|
| 1215 |
+
|
| 1216 |
+
@field_validator("max", "depth")
|
| 1217 |
+
@classmethod
|
| 1218 |
+
def _non_negative(cls, v: int | None) -> int | None:
|
| 1219 |
+
if v is not None and v < 0:
|
| 1220 |
+
raise ValueError("must be >= 0")
|
| 1221 |
+
return v
|
| 1222 |
+
|
| 1223 |
+
@field_validator("types")
|
| 1224 |
+
@classmethod
|
| 1225 |
+
def _valid_caps(cls, v: list[str] | dict[str, int]) -> list[str] | dict[str, int]:
|
| 1226 |
+
if isinstance(v, dict) and any(n < 0 for n in v.values()):
|
| 1227 |
+
raise ValueError("per-type caps must be >= 0")
|
| 1228 |
+
return v
|
| 1229 |
+
|
| 1230 |
+
@property
|
| 1231 |
+
def allowed(self) -> list[str]:
|
| 1232 |
+
return list(self.types)
|
| 1233 |
+
|
| 1234 |
+
def cap_for(self, type_name: str) -> int | None:
|
| 1235 |
+
return self.types.get(type_name) if isinstance(self.types, dict) else None
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
class LimitsSpec(BaseModel):
|
| 1239 |
+
"""Swarm-wide limits checked when an agent spawns (None: no limit). `alive` counts agents
|
| 1240 |
+
not removed, replicas included; `spawned_total` the spawn counter; `budget_usd` the cost
|
| 1241 |
+
of every agent in the swarm, removed ones included. `budget_usd` is also a hard stop
|
| 1242 |
+
(docs/loop.md): at `budget_usd` minus the types' `loop.final.reserve_usd` the controller
|
| 1243 |
+
stops loops, drops pending prompts and runs the final rounds; at `budget_usd` it stops
|
| 1244 |
+
every agent and refuses new prompts."""
|
| 1245 |
+
|
| 1246 |
+
alive: int | None = None
|
| 1247 |
+
spawned_total: int | None = None
|
| 1248 |
+
budget_usd: float | None = None
|
| 1249 |
+
|
| 1250 |
+
@field_validator("alive", "spawned_total", "budget_usd")
|
| 1251 |
+
@classmethod
|
| 1252 |
+
def _non_negative(cls, v: float | None) -> float | None:
|
| 1253 |
+
if v is not None and v < 0:
|
| 1254 |
+
raise ValueError("must be >= 0")
|
| 1255 |
+
return v
|
| 1256 |
+
|
| 1257 |
+
|
| 1258 |
+
def validate_spawn(spawn: dict[str, SpawnRule], types: dict[str, TypeSpec]) -> None:
|
| 1259 |
+
"""Apply-time checks: known types, no cycle, `workers` on every spawnable type, a total
|
| 1260 |
+
`max` for the list form."""
|
| 1261 |
+
for parent, rule in spawn.items():
|
| 1262 |
+
if parent not in types:
|
| 1263 |
+
raise ValueError(f"spawn.{parent}: unknown type")
|
| 1264 |
+
if isinstance(rule.types, list) and rule.max is None:
|
| 1265 |
+
raise ValueError(f"spawn.{parent}: a list of types needs `max`")
|
| 1266 |
+
for child in rule.allowed:
|
| 1267 |
+
if child not in types:
|
| 1268 |
+
raise ValueError(f"spawn.{parent}.types: unknown type {child!r}")
|
| 1269 |
+
if types[child].workers is None:
|
| 1270 |
+
raise ValueError(f"types.{child}: spawnable by {parent!r}, so it needs `workers`")
|
| 1271 |
+
state: dict[str, int] = {} # 1 on the DFS stack, 2 done
|
| 1272 |
+
|
| 1273 |
+
def visit(t: str, path: list[str]) -> None:
|
| 1274 |
+
state[t] = 1
|
| 1275 |
+
for child in spawn[t].allowed if t in spawn else []:
|
| 1276 |
+
if state.get(child) == 1:
|
| 1277 |
+
cycle = " -> ".join([*path[path.index(child):], child])
|
| 1278 |
+
raise ValueError(f"spawn: cycle {cycle}")
|
| 1279 |
+
if child not in state:
|
| 1280 |
+
visit(child, [*path, child])
|
| 1281 |
+
state[t] = 2
|
| 1282 |
+
|
| 1283 |
+
for t in sorted(spawn):
|
| 1284 |
+
if t not in state:
|
| 1285 |
+
visit(t, [t])
|
| 1286 |
+
|
| 1287 |
+
|
| 1288 |
+
def child_name(parent: str, type_name: str, n: int) -> str:
|
| 1289 |
+
return f"{parent}-{type_name}-{n:04d}"
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
def initial_workers(ts: TypeSpec) -> int:
|
| 1293 |
+
"""`ceil(replicas / agents_per_worker)` for a type, or the declared `workers.initial`."""
|
| 1294 |
+
if ts.workers is not None and ts.workers.initial is not None:
|
| 1295 |
+
return ts.workers.initial
|
| 1296 |
+
return -(-ts.replicas // max(1, ts.agents_per_worker))
|
| 1297 |
+
|
| 1298 |
+
|
| 1299 |
+
def max_workers(ts: TypeSpec) -> int:
|
| 1300 |
+
return initial_workers(ts) + (ts.workers.max_extra if ts.workers else 0)
|
| 1301 |
+
|
| 1302 |
+
|
| 1303 |
+
def root_depth(spec: SwarmSpec, type_name: str) -> int:
|
| 1304 |
+
"""Spawn depth of a replica: its type's `spawn.depth`, 0 if the type cannot spawn."""
|
| 1305 |
+
rule = spec.spawn.get(type_name)
|
| 1306 |
+
return rule.depth if rule else 0
|
| 1307 |
+
|
| 1308 |
+
|
| 1309 |
+
def child_depth(spec: SwarmSpec, parent_depth: int, type_name: str) -> int:
|
| 1310 |
+
return max(0, min(parent_depth - 1, root_depth(spec, type_name)))
|
| 1311 |
+
|
| 1312 |
+
|
| 1313 |
+
# --------------------------------------------------------------------------- loop (docs/loop.md)
|
| 1314 |
+
|
| 1315 |
+
# Placeholders the worker fills in loop prompts; any other `{name}` is left as written.
|
| 1316 |
+
LOOP_PLACEHOLDERS = ("round", "elapsed", "wall", "spend", "cap", "why", "last_summary")
|
| 1317 |
+
NEEDS_WORLD = "needs a world (not in this version)"
|
| 1318 |
+
# message_board.*: the message_board resource's events (harness harbor); world.* and artifacts.*
|
| 1319 |
+
# have no feeder now: a warning at launch
|
| 1320 |
+
_LOOP_SOURCE_RE = re.compile(r"^(message_board|world|artifacts)\.[A-Za-z0-9_.:*-]+$")
|
| 1321 |
+
|
| 1322 |
+
|
| 1323 |
+
class LoopWhile(BaseModel):
|
| 1324 |
+
"""While every set condition holds, the loop goes on. Type-wide: `until` (wall time since
|
| 1325 |
+
the loop started), `budget_usd` (the type's cost). Per agent: `max_rounds` (loop prompts),
|
| 1326 |
+
`agent_usd` (the agent's cost; a map is keyed by model alias or model id)."""
|
| 1327 |
+
|
| 1328 |
+
model_config = {"extra": "forbid"}
|
| 1329 |
+
|
| 1330 |
+
until: str | None = None
|
| 1331 |
+
max_rounds: int | None = None
|
| 1332 |
+
budget_usd: float | None = None
|
| 1333 |
+
agent_usd: float | dict[str, float] | None = None
|
| 1334 |
+
|
| 1335 |
+
@field_validator("until", mode="before")
|
| 1336 |
+
@classmethod
|
| 1337 |
+
def _until_from_yaml(cls, v: Any) -> Any:
|
| 1338 |
+
"""Unquoted YAML times arrive as date/datetime; a date means midnight UTC."""
|
| 1339 |
+
return v.isoformat() if isinstance(v, date) else v
|
| 1340 |
+
|
| 1341 |
+
@field_validator("until")
|
| 1342 |
+
@classmethod
|
| 1343 |
+
def _until(cls, v: str | None) -> str | None:
|
| 1344 |
+
if v is not None:
|
| 1345 |
+
until_deadline(v, 0.0)
|
| 1346 |
+
return v
|
| 1347 |
+
|
| 1348 |
+
@field_validator("max_rounds")
|
| 1349 |
+
@classmethod
|
| 1350 |
+
def _positive(cls, v: int | None) -> int | None:
|
| 1351 |
+
if v is not None and v < 1:
|
| 1352 |
+
raise ValueError("must be >= 1")
|
| 1353 |
+
return v
|
| 1354 |
+
|
| 1355 |
+
@field_validator("budget_usd")
|
| 1356 |
+
@classmethod
|
| 1357 |
+
def _usd(cls, v: float | None) -> float | None:
|
| 1358 |
+
if v is not None and v < 0:
|
| 1359 |
+
raise ValueError("must be >= 0")
|
| 1360 |
+
return v
|
| 1361 |
+
|
| 1362 |
+
@field_validator("agent_usd")
|
| 1363 |
+
@classmethod
|
| 1364 |
+
def _agent_usd(cls, v: float | dict[str, float] | None) -> float | dict[str, float] | None:
|
| 1365 |
+
values = v.values() if isinstance(v, dict) else [] if v is None else [v]
|
| 1366 |
+
if any(x < 0 for x in values):
|
| 1367 |
+
raise ValueError("must be >= 0")
|
| 1368 |
+
return v
|
| 1369 |
+
|
| 1370 |
+
|
| 1371 |
+
class LoopFinal(BaseModel):
|
| 1372 |
+
"""One last prompt per live agent when the loop stops (any reason but `--no-final`).
|
| 1373 |
+
`reserve_usd` is held back from `limits.budget_usd` for it."""
|
| 1374 |
+
|
| 1375 |
+
model_config = {"extra": "forbid"}
|
| 1376 |
+
|
| 1377 |
+
prompt: str | None = None
|
| 1378 |
+
prompt_file: str | None = None # inlined into `prompt` by `flock launch`
|
| 1379 |
+
reserve_usd: float = 0.0
|
| 1380 |
+
|
| 1381 |
+
@field_validator("reserve_usd")
|
| 1382 |
+
@classmethod
|
| 1383 |
+
def _usd(cls, v: float) -> float:
|
| 1384 |
+
if v < 0:
|
| 1385 |
+
raise ValueError("must be >= 0")
|
| 1386 |
+
return v
|
| 1387 |
+
|
| 1388 |
+
@model_validator(mode="after")
|
| 1389 |
+
def _has_prompt(self) -> LoopFinal:
|
| 1390 |
+
if self.prompt is None and self.prompt_file is None:
|
| 1391 |
+
raise ValueError("final needs prompt or prompt_file")
|
| 1392 |
+
return self
|
| 1393 |
+
|
| 1394 |
+
|
| 1395 |
+
class LoopWake(BaseModel):
|
| 1396 |
+
"""How `on:` wake-ups spend rounds (docs/loop.md, "Wake queue"). Per agent: at least
|
| 1397 |
+
`min_gap` between two wake prompts (wakes in between are coalesced into the next one), at
|
| 1398 |
+
most `max` wake prompts per run of the loop, or per `window` when set (None: no cap).
|
| 1399 |
+
`counts_as_round: false` keeps wake prompts out of `max_rounds` (they carry the current
|
| 1400 |
+
round number and do not advance it); `true`: a wake prompt is a round."""
|
| 1401 |
+
|
| 1402 |
+
model_config = {"extra": "forbid"}
|
| 1403 |
+
|
| 1404 |
+
min_gap: str = "30s"
|
| 1405 |
+
max: int | None = 10
|
| 1406 |
+
window: str | None = None
|
| 1407 |
+
counts_as_round: bool = False
|
| 1408 |
+
|
| 1409 |
+
@field_validator("min_gap", "window")
|
| 1410 |
+
@classmethod
|
| 1411 |
+
def _duration(cls, v: str | None, info) -> str | None:
|
| 1412 |
+
if v is not None and parse_duration(v).total_seconds() <= 0 and info.field_name == "window":
|
| 1413 |
+
raise ValueError("window must be a duration > 0")
|
| 1414 |
+
return v
|
| 1415 |
+
|
| 1416 |
+
@field_validator("max")
|
| 1417 |
+
@classmethod
|
| 1418 |
+
def _max(cls, v: int | None) -> int | None:
|
| 1419 |
+
if v is not None and v < 0:
|
| 1420 |
+
raise ValueError("must be >= 0")
|
| 1421 |
+
return v
|
| 1422 |
+
|
| 1423 |
+
|
| 1424 |
+
class LoopSpec(BaseModel):
|
| 1425 |
+
"""A type's prompting loop (docs/loop.md). The loop prompt goes on every `every`
|
| 1426 |
+
(`turn_end`: re-sent by the worker when a turn completes; a duration: the controller
|
| 1427 |
+
prompts idle agents that long after their last loop prompt) and on each `on` wake-up,
|
| 1428 |
+
while `while` holds. Then `final`, once per live agent, then idle."""
|
| 1429 |
+
|
| 1430 |
+
model_config = {"extra": "forbid", "populate_by_name": True}
|
| 1431 |
+
|
| 1432 |
+
prompt: str | None = None
|
| 1433 |
+
prompt_file: str | None = None # inlined into `prompt` by `flock launch`
|
| 1434 |
+
every: str = "turn_end"
|
| 1435 |
+
on: list[str] = Field(default_factory=list) # message_board.mention, world.event:*
|
| 1436 |
+
while_: LoopWhile = Field(default_factory=LoopWhile, alias="while")
|
| 1437 |
+
final: LoopFinal | None = None
|
| 1438 |
+
wake: LoopWake = Field(default_factory=LoopWake)
|
| 1439 |
+
# Controller only: one line after the rendered loop prompt naming the board notifications
|
| 1440 |
+
# (mentions, replies in the agent's threads) since its last round. Never sent to workers.
|
| 1441 |
+
notices: bool = False
|
| 1442 |
+
|
| 1443 |
+
@model_serializer(mode="wrap")
|
| 1444 |
+
def _dump(self, handler): # `while` on the wire, as written in specs
|
| 1445 |
+
out = handler(self)
|
| 1446 |
+
if isinstance(out, dict) and "while_" in out:
|
| 1447 |
+
out["while"] = out.pop("while_")
|
| 1448 |
+
if isinstance(out, dict) and not self.notices:
|
| 1449 |
+
out.pop("notices", None) # off: not dumped, so workers never see the key
|
| 1450 |
+
return out
|
| 1451 |
+
|
| 1452 |
+
@field_validator("every")
|
| 1453 |
+
@classmethod
|
| 1454 |
+
def _every(cls, v: str) -> str:
|
| 1455 |
+
if v != "turn_end" and parse_duration(v).total_seconds() <= 0:
|
| 1456 |
+
raise ValueError("every must be turn_end or a duration > 0")
|
| 1457 |
+
return v
|
| 1458 |
+
|
| 1459 |
+
@field_validator("on")
|
| 1460 |
+
@classmethod
|
| 1461 |
+
def _sources(cls, v: list[str]) -> list[str]:
|
| 1462 |
+
for x in v:
|
| 1463 |
+
if not _LOOP_SOURCE_RE.match(x):
|
| 1464 |
+
raise ValueError(f"{x!r}: expected message_board.<name>, world.<name> "
|
| 1465 |
+
"or artifacts.<name>")
|
| 1466 |
+
return v
|
| 1467 |
+
|
| 1468 |
+
@model_validator(mode="after")
|
| 1469 |
+
def _has_prompt(self) -> LoopSpec:
|
| 1470 |
+
if self.prompt is None and self.prompt_file is None:
|
| 1471 |
+
raise ValueError("loop needs prompt or prompt_file")
|
| 1472 |
+
return self
|
| 1473 |
+
|
| 1474 |
+
@property
|
| 1475 |
+
def every_s(self) -> float | None:
|
| 1476 |
+
"""Seconds between loop prompts for a duration `every`, else None."""
|
| 1477 |
+
if self.every == "turn_end":
|
| 1478 |
+
return None
|
| 1479 |
+
return parse_duration(self.every).total_seconds()
|
| 1480 |
+
|
| 1481 |
+
|
| 1482 |
+
def hit_max_turns(turn_ended: dict) -> bool:
|
| 1483 |
+
"""A `turn_ended` that stopped at the type's `max_turns` (its `reason`, or `subtype: error_max_turns`).
|
| 1484 |
+
Not a failed turn for a loop."""
|
| 1485 |
+
return turn_ended.get("reason") == "max_turns" or turn_ended.get("subtype") == "error_max_turns"
|
| 1486 |
+
|
| 1487 |
+
|
| 1488 |
+
def worker_type_spec(ts: TypeSpec) -> TypeSpec:
|
| 1489 |
+
"""The type spec as workers get it: without the controller-only `loop.notices` (workers
|
| 1490 |
+
validate it with extra=forbid; one older than the key would refuse the whole spec)."""
|
| 1491 |
+
if ts.loop is None or not ts.loop.notices:
|
| 1492 |
+
return ts
|
| 1493 |
+
return ts.model_copy(update={"loop": ts.loop.model_copy(update={"notices": False})})
|
| 1494 |
+
|
| 1495 |
+
|
| 1496 |
+
def agent_cap(ts: TypeSpec) -> float | None:
|
| 1497 |
+
"""The type's per-agent loop cap (`loop.while.agent_usd`), resolved for its model."""
|
| 1498 |
+
cap = ts.loop.while_.agent_usd if ts.loop else None
|
| 1499 |
+
if not isinstance(cap, dict):
|
| 1500 |
+
return cap
|
| 1501 |
+
r = ts.resolved_model
|
| 1502 |
+
for key in (ts.model, r.model_id if r else None, r.qualified if r else None):
|
| 1503 |
+
if key is not None and key in cap:
|
| 1504 |
+
return cap[key]
|
| 1505 |
+
return None
|
| 1506 |
+
|
| 1507 |
+
|
| 1508 |
+
def loop_refusals(spec: SwarmSpec) -> list[str]:
|
| 1509 |
+
"""Loop settings this version accepts in the model but cannot run: world-backed wakes and
|
| 1510 |
+
prompt files not inlined. `flock launch` and the controller refuse a spec with any of them."""
|
| 1511 |
+
out: list[str] = []
|
| 1512 |
+
for name, ts in spec.types.items():
|
| 1513 |
+
lp = ts.loop
|
| 1514 |
+
if lp is None:
|
| 1515 |
+
continue
|
| 1516 |
+
where = f"types.{name}.loop"
|
| 1517 |
+
out += [f"{where}.on: {x} {NEEDS_WORLD}" for x in lp.on if x.startswith("world.")]
|
| 1518 |
+
if lp.prompt is None:
|
| 1519 |
+
out.append(f"{where}.prompt_file: not inlined (use `flock launch`, which reads it)")
|
| 1520 |
+
if lp.final is not None and lp.final.prompt is None:
|
| 1521 |
+
out.append(f"{where}.final.prompt_file: not inlined (use `flock launch`, which reads it)")
|
| 1522 |
+
return out
|
| 1523 |
+
|
| 1524 |
+
|
| 1525 |
+
CommsSpec.model_rebuild()
|
| 1526 |
+
WorldSpec.model_rebuild()
|
| 1527 |
+
TypeSpec.model_rebuild()
|
| 1528 |
+
SwarmSpec.model_rebuild()
|
| 1529 |
+
|
| 1530 |
+
|
| 1531 |
+
# --------------------------------------------------------------------------- usage
|
| 1532 |
+
|
| 1533 |
+
|
| 1534 |
+
class TokenUsage(BaseModel):
|
| 1535 |
+
input: int = 0
|
| 1536 |
+
output: int = 0
|
| 1537 |
+
cache_read: int = 0
|
| 1538 |
+
cache_write: int = 0
|
| 1539 |
+
reasoning: int = 0
|
| 1540 |
+
|
| 1541 |
+
def __add__(self, other: TokenUsage) -> TokenUsage:
|
| 1542 |
+
return TokenUsage(
|
| 1543 |
+
input=self.input + other.input,
|
| 1544 |
+
output=self.output + other.output,
|
| 1545 |
+
cache_read=self.cache_read + other.cache_read,
|
| 1546 |
+
cache_write=self.cache_write + other.cache_write,
|
| 1547 |
+
reasoning=self.reasoning + other.reasoning,
|
| 1548 |
+
)
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
def type_spec_rev(ts: TypeSpec) -> str:
|
| 1552 |
+
"""A short content hash of a type spec: the heartbeat sends a type spec only when the
|
| 1553 |
+
worker's revision differs (docs/live.md)."""
|
| 1554 |
+
return hashlib.sha256(ts.model_dump_json().encode()).hexdigest()[:16]
|
| 1555 |
+
|
| 1556 |
+
|
| 1557 |
+
# --------------------------------------------------------------------------- worker -> controller
|
| 1558 |
+
|
| 1559 |
+
|
| 1560 |
+
class AgentHeartbeat(BaseModel):
|
| 1561 |
+
"""One record per agent inside a worker heartbeat (~100 bytes)."""
|
| 1562 |
+
|
| 1563 |
+
name: str
|
| 1564 |
+
state: Literal["working", "idle", "stuck"]
|
| 1565 |
+
turn_id: str | None = None
|
| 1566 |
+
idle_since: datetime | None = None
|
| 1567 |
+
session_id: str | None = None
|
| 1568 |
+
resumed: bool | None = None # None until the first (re)start on this worker
|
| 1569 |
+
tokens: dict[str, TokenUsage] = Field(default_factory=dict) # by model, cumulative
|
| 1570 |
+
turns: int = 0
|
| 1571 |
+
last_sync: datetime | None = None
|
| 1572 |
+
msgboard_principal: str | None = None
|
| 1573 |
+
rev: str | None = None # `type_spec_rev` the agent applied at its last turn boundary
|
| 1574 |
+
start_rev: str | None = None # the one its running harness process started with
|
| 1575 |
+
endpoint: str | None = None # `host:port` of the model server it is pinned to (base_urls)
|
| 1576 |
+
trial: dict[str, Any] | None = None # harness harbor: {id, attempt, alive} of its Trial
|
| 1577 |
+
|
| 1578 |
+
|
| 1579 |
+
class WorkerMem(BaseModel):
|
| 1580 |
+
"""The worker's cgroup memory (MB) at its last sample (flock.worker.cgroup)."""
|
| 1581 |
+
|
| 1582 |
+
current_mb: float | None = None
|
| 1583 |
+
limit_mb: float | None = None # None: no limit found, nothing is armed
|
| 1584 |
+
nonreclaim_mb: float | None = None # anon + shmem + slab_unreclaimable + stacks + pagetables
|
| 1585 |
+
slope_mb_h: float | None = None # of nonreclaim_mb over the last hour
|
| 1586 |
+
eta_limit_s: float | None = None # nonreclaim_mb reaches limit_mb at that slope
|
| 1587 |
+
psi_some_avg10: float | None = None
|
| 1588 |
+
oom_kills: int | None = None # memory.events oom_kill, cumulative for the cgroup
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
class RestoreProgress(BaseModel):
|
| 1592 |
+
"""Restores in flight on the worker: files downloaded of the files listed."""
|
| 1593 |
+
|
| 1594 |
+
agents: int = 0
|
| 1595 |
+
files_done: int = 0
|
| 1596 |
+
files_total: int = 0
|
| 1597 |
+
started: datetime | None = None # the oldest restore in flight
|
| 1598 |
+
|
| 1599 |
+
|
| 1600 |
+
class ToolCounters(BaseModel):
|
| 1601 |
+
"""One world tool's calls since this worker process started."""
|
| 1602 |
+
|
| 1603 |
+
n: int = 0
|
| 1604 |
+
err: int = 0
|
| 1605 |
+
refused: int = 0 # the world said no for now: HTTP 429 or a budget/busy error code
|
| 1606 |
+
timeouts: int = 0
|
| 1607 |
+
sum_s: float = 0.0
|
| 1608 |
+
max_s: float = 0.0
|
| 1609 |
+
|
| 1610 |
+
|
| 1611 |
+
class WorkerHeartbeat(BaseModel):
|
| 1612 |
+
worker: str
|
| 1613 |
+
deadline: datetime
|
| 1614 |
+
draining: bool = False
|
| 1615 |
+
agents: list[AgentHeartbeat]
|
| 1616 |
+
# `type_spec_rev` of the type spec the worker has (docs/live.md): the controller sends the
|
| 1617 |
+
# current one in the heartbeat response only when it differs
|
| 1618 |
+
spec_rev: str | None = None
|
| 1619 |
+
# the worker's last heartbeat after a preemption notice (SIGUSR1): it synced and exits;
|
| 1620 |
+
# the controller relaunches the slot at once, as a planned restart (docs/slurm.md)
|
| 1621 |
+
preempted: bool = False
|
| 1622 |
+
# the worker's last heartbeat after a finished drain (`unsynced` names any agent whose final
|
| 1623 |
+
# sync failed): it exits now, and the controller ends the slot without waiting for the job
|
| 1624 |
+
drained: bool = False
|
| 1625 |
+
# agents whose turn a preemption or a bounded drain cut; they get the type's
|
| 1626 |
+
# resume_prompt after the restore
|
| 1627 |
+
interrupted: list[str] = Field(default_factory=list)
|
| 1628 |
+
# telemetry (docs/design.md "Heartbeat"); None from workers that do not send it
|
| 1629 |
+
mem: WorkerMem | None = None
|
| 1630 |
+
restore: RestoreProgress | None = None # None when no restore is in flight
|
| 1631 |
+
tools: dict[str, ToolCounters] | None = None # world tools by name
|
| 1632 |
+
knobs_rev: str | None = None # hash of the worker's effective settings
|
| 1633 |
+
# nonreclaimable memory passed FLOCK_MEM_ROTATE of the limit: the controller drains the
|
| 1634 |
+
# worker when its rotation budget allows (docs/slurm.md "Memory")
|
| 1635 |
+
wants_rotation: bool = False
|
| 1636 |
+
# agents whose last push to the bucket failed (retried once), with the error; the drain's
|
| 1637 |
+
# final heartbeat carries them so `flock stop --release` can name them
|
| 1638 |
+
unsynced: dict[str, str] = Field(default_factory=dict)
|
| 1639 |
+
|
| 1640 |
+
|
| 1641 |
+
class Event(BaseModel):
|
| 1642 |
+
"""One line of an agent's event stream.
|
| 1643 |
+
|
| 1644 |
+
The on-disk / over-the-wire shape is pi session format v3 (see swarmlab's
|
| 1645 |
+
export.py for the reference encoding). `type`, `ts`, `agent` are required by us;
|
| 1646 |
+
the rest of the pi record lives in `data`. Harness-neutral types the worker adds:
|
| 1647 |
+
session_started, session_resumed, session_restarted, turn_started, turn_ended,
|
| 1648 |
+
turn_interrupted, sync.
|
| 1649 |
+
"""
|
| 1650 |
+
|
| 1651 |
+
type: str
|
| 1652 |
+
ts: datetime
|
| 1653 |
+
agent: str
|
| 1654 |
+
turn_id: str | None = None
|
| 1655 |
+
data: dict[str, Any] = Field(default_factory=dict)
|
| 1656 |
+
|
| 1657 |
+
|
| 1658 |
+
class EventBatch(BaseModel):
|
| 1659 |
+
worker: str
|
| 1660 |
+
events: list[Event]
|
| 1661 |
+
|
| 1662 |
+
|
| 1663 |
+
# --------------------------------------------------------------------------- controller -> worker
|
| 1664 |
+
|
| 1665 |
+
|
| 1666 |
+
class LoopMeta(BaseModel):
|
| 1667 |
+
"""What the worker needs to render a loop prompt (docs/loop.md): it fills the
|
| 1668 |
+
LOOP_PLACEHOLDERS from these plus its own spend and last `done` summary."""
|
| 1669 |
+
|
| 1670 |
+
kind: Literal["loop", "final"]
|
| 1671 |
+
type: str
|
| 1672 |
+
round: int | None = None # None: the worker numbers it (its own next round)
|
| 1673 |
+
started_at: datetime | None = None # when the loop started, for {elapsed}
|
| 1674 |
+
wall_s: float | None = None # `while.until` in seconds, for {wall}
|
| 1675 |
+
cap_usd: float | None = None # `while.agent_usd` for this agent, for {cap}
|
| 1676 |
+
why: str = ""
|
| 1677 |
+
# False: a wake prompt outside `max_rounds` (`wake.counts_as_round: false`); it carries the
|
| 1678 |
+
# current round and does not advance the worker's round counter
|
| 1679 |
+
counted: bool = True
|
| 1680 |
+
wake: bool = False # a wake prompt (`on:`), counted or not: a deferral gives back its wake
|
| 1681 |
+
|
| 1682 |
+
|
| 1683 |
+
class PromptCommand(BaseModel):
|
| 1684 |
+
kind: Literal["prompt"] = "prompt"
|
| 1685 |
+
agent: str
|
| 1686 |
+
prompt_id: str
|
| 1687 |
+
text: str
|
| 1688 |
+
timeout: str | None = None
|
| 1689 |
+
reply_to: str | None = None # opaque, for the caller's bookkeeping
|
| 1690 |
+
loop: LoopMeta | None = None # a loop prompt: `text` is a template the worker renders
|
| 1691 |
+
|
| 1692 |
+
@model_serializer(mode="wrap")
|
| 1693 |
+
def _dump(self, handler): # plain prompts keep their wire shape
|
| 1694 |
+
out = handler(self)
|
| 1695 |
+
if isinstance(out, dict) and out.get("loop", 0) is None:
|
| 1696 |
+
out.pop("loop")
|
| 1697 |
+
return out
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
class LoopStartCommand(BaseModel):
|
| 1701 |
+
"""`every: turn_end` on the worker: send `text` (rendered) now if the agent is idle and
|
| 1702 |
+
again whenever a turn ends completed, until `max_rounds`, `deadline`, a `loop_stop`, or 3
|
| 1703 |
+
failed turns in a row. Idempotent: a repeat updates the settings."""
|
| 1704 |
+
|
| 1705 |
+
kind: Literal["loop_start"] = "loop_start"
|
| 1706 |
+
agent: str
|
| 1707 |
+
text: str
|
| 1708 |
+
meta: LoopMeta # kind "loop"; `round` is the rounds done so far
|
| 1709 |
+
max_rounds: int | None = None
|
| 1710 |
+
deadline: datetime | None = None
|
| 1711 |
+
# One run of the loop (POST /swarms/{swarm}/loop start begins a new one): a new run resets the
|
| 1712 |
+
# worker's round counter; a repeat of the same run (lost command, live update) does not.
|
| 1713 |
+
run: str | None = None
|
| 1714 |
+
|
| 1715 |
+
|
| 1716 |
+
class LoopStopCommand(BaseModel):
|
| 1717 |
+
kind: Literal["loop_stop"] = "loop_stop"
|
| 1718 |
+
agent: str # end the worker-side loop; the turn in flight finishes
|
| 1719 |
+
reason: str = "stop"
|
| 1720 |
+
|
| 1721 |
+
|
| 1722 |
+
class StopCommand(BaseModel):
|
| 1723 |
+
kind: Literal["stop"] = "stop"
|
| 1724 |
+
agent: str # kill the agent's harness process if any; agent stays assigned
|
| 1725 |
+
|
| 1726 |
+
|
| 1727 |
+
class DrainCommand(BaseModel):
|
| 1728 |
+
kind: Literal["drain"] = "drain" # worker-wide: finish in-flight turns, sync, exit 0
|
| 1729 |
+
|
| 1730 |
+
|
| 1731 |
+
class AssignCommand(BaseModel):
|
| 1732 |
+
"""Assign an agent to this worker; the worker restores it from the bucket if present."""
|
| 1733 |
+
|
| 1734 |
+
kind: Literal["assign"] = "assign"
|
| 1735 |
+
agent: str
|
| 1736 |
+
type: str
|
| 1737 |
+
spec: TypeSpec
|
| 1738 |
+
restore: bool = True # restore workdir + session from bucket before first prompt
|
| 1739 |
+
resume_prompt: str | None = None # sent once after restore when a turn was interrupted
|
| 1740 |
+
parent: str | None = None # the spawning agent, None for a replica
|
| 1741 |
+
# The agent's scoped controller token, injected into its harness env as FLOCK_AGENT_TOKEN.
|
| 1742 |
+
agent_token: str | None = None
|
| 1743 |
+
tools_version: str | None = None # the swarm's tools bundle; None: no tools
|
| 1744 |
+
comms: CommsSpec | None = None # the swarm's comms block (docs/comms.md), channel resolved
|
| 1745 |
+
world: WorldSpec | None = None # the swarm's world (docs/world.md), manifest fetched
|
| 1746 |
+
|
| 1747 |
+
|
| 1748 |
+
class UnassignCommand(BaseModel):
|
| 1749 |
+
kind: Literal["unassign"] = "unassign"
|
| 1750 |
+
agent: str # stop, final sync, forget
|
| 1751 |
+
|
| 1752 |
+
|
| 1753 |
+
Command = (PromptCommand | StopCommand | DrainCommand | AssignCommand | UnassignCommand
|
| 1754 |
+
| LoopStartCommand | LoopStopCommand)
|
| 1755 |
+
|
| 1756 |
+
|
| 1757 |
+
class CommandBatch(BaseModel):
|
| 1758 |
+
commands: list[Command]
|
| 1759 |
+
|
| 1760 |
+
|
| 1761 |
+
# --------------------------------------------------------------------------- API shapes
|
| 1762 |
+
|
| 1763 |
+
|
| 1764 |
+
class PromptRequest(BaseModel):
|
| 1765 |
+
text: str
|
| 1766 |
+
timeout: str | None = None
|
| 1767 |
+
reply_to: str | None = None
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
class PromptAck(BaseModel):
|
| 1771 |
+
prompt_id: str
|
| 1772 |
+
agent: str
|
| 1773 |
+
status: Literal["queued", "pending"] # queued: worker is up; pending: held until a worker is
|
| 1774 |
+
turn_id: str | None = None # set later via the event stream, may be None here
|
| 1775 |
+
|
| 1776 |
+
|
| 1777 |
+
class BulkPromptRequest(BaseModel):
|
| 1778 |
+
"""One prompt to every agent of a type (`POST /swarms/{swarm}/prompts`), optionally only
|
| 1779 |
+
those in one state. Each agent gets its own pending prompt, admitted as a single one is."""
|
| 1780 |
+
|
| 1781 |
+
type: str
|
| 1782 |
+
state: AgentState | None = None
|
| 1783 |
+
text: str
|
| 1784 |
+
timeout: str | None = None
|
| 1785 |
+
reply_to: str | None = None
|
| 1786 |
+
# Skip agents that already have a pending (undelivered) prompt. Default: on with
|
| 1787 |
+
# state=idle ("only if idle and empty": repeated calls never stack prompts), off otherwise.
|
| 1788 |
+
skip_pending: bool | None = None
|
| 1789 |
+
|
| 1790 |
+
|
| 1791 |
+
class ChildrenPromptRequest(BaseModel):
|
| 1792 |
+
"""One prompt to an agent's direct children (`POST /agents/{name}/children/prompts`),
|
| 1793 |
+
optionally only those of one type and/or state; same rules as BulkPromptRequest. Allowed
|
| 1794 |
+
for that agent's own scoped token (and its ancestors'), so a leader prompts its idle
|
| 1795 |
+
children in one request."""
|
| 1796 |
+
|
| 1797 |
+
type: str | None = None
|
| 1798 |
+
state: AgentState | None = None
|
| 1799 |
+
text: str
|
| 1800 |
+
timeout: str | None = None
|
| 1801 |
+
reply_to: str | None = None
|
| 1802 |
+
skip_pending: bool | None = None # default: on with state=idle
|
| 1803 |
+
|
| 1804 |
+
|
| 1805 |
+
class BulkPromptAck(BaseModel):
|
| 1806 |
+
swarm: str
|
| 1807 |
+
type: str | None # None: any type (children route without `type`)
|
| 1808 |
+
parent: str | None = None # set by the children route
|
| 1809 |
+
matched: int # agents of the type
|
| 1810 |
+
queued: int # prompts for agents whose worker is up
|
| 1811 |
+
pending: int # prompts held until the agent's worker is up
|
| 1812 |
+
skipped_state: int = 0 # not in the requested state
|
| 1813 |
+
skipped_removing: int = 0 # being removed (spawn cascade)
|
| 1814 |
+
skipped_pending: int = 0 # already had an undelivered prompt (skip_pending)
|
| 1815 |
+
|
| 1816 |
+
|
| 1817 |
+
class SpawnRequest(BaseModel):
|
| 1818 |
+
type: str
|
| 1819 |
+
prompt: str | None = None # first prompt, held until the child is placed
|
| 1820 |
+
key: str | None = None # idempotency key, unique per parent
|
| 1821 |
+
|
| 1822 |
+
|
| 1823 |
+
class SpawnAck(BaseModel):
|
| 1824 |
+
name: str
|
| 1825 |
+
created: bool
|
| 1826 |
+
parent: str
|
| 1827 |
+
type: str
|
| 1828 |
+
depth: int
|
| 1829 |
+
|
| 1830 |
+
|
| 1831 |
+
class AgentStatus(BaseModel):
|
| 1832 |
+
name: str
|
| 1833 |
+
swarm: str
|
| 1834 |
+
type: str
|
| 1835 |
+
harness: Harness
|
| 1836 |
+
model: str
|
| 1837 |
+
provider: str | None = None # provider name when the model is provider-backed
|
| 1838 |
+
labels: dict[str, str]
|
| 1839 |
+
state: AgentState
|
| 1840 |
+
idle_since: datetime | None = None
|
| 1841 |
+
turn_id: str | None = None
|
| 1842 |
+
worker: str | None = None
|
| 1843 |
+
session_id: str | None = None
|
| 1844 |
+
resumed: bool | None = None
|
| 1845 |
+
pending: int = 0
|
| 1846 |
+
tokens: dict[str, TokenUsage] = Field(default_factory=dict)
|
| 1847 |
+
cost_usd: float = 0.0 # derived by the controller from its price table
|
| 1848 |
+
turns: int = 0
|
| 1849 |
+
created_at: datetime
|
| 1850 |
+
last_heartbeat: datetime | None = None
|
| 1851 |
+
last_sync: datetime | None = None
|
| 1852 |
+
msgboard_principal: str | None = None
|
| 1853 |
+
parent: str | None = None # spawning agent; None for a replica
|
| 1854 |
+
children: list[str] = Field(default_factory=list)
|
| 1855 |
+
depth: int = 0 # generations this agent may still spawn below itself
|
| 1856 |
+
rev: str | None = None # AgentHeartbeat.rev / start_rev
|
| 1857 |
+
start_rev: str | None = None
|
| 1858 |
+
endpoint: str | None = None # AgentHeartbeat.endpoint
|
| 1859 |
+
|
| 1860 |
+
|
| 1861 |
+
class WorkerStatus(BaseModel):
|
| 1862 |
+
id: str
|
| 1863 |
+
swarm: str
|
| 1864 |
+
type: str
|
| 1865 |
+
job_id: str | None
|
| 1866 |
+
state: WorkerState
|
| 1867 |
+
deadline: datetime | None
|
| 1868 |
+
agents: list[str]
|
| 1869 |
+
last_heartbeat: datetime | None
|
| 1870 |
+
launched_at: datetime
|
| 1871 |
+
crashes: int = 0
|
| 1872 |
+
last_error: str | None = None # last launch failure or crash: job status, log tail
|
| 1873 |
+
pending_reason: str | None = None # while queued: the scheduler's word, e.g. "PENDING (Resources)"
|
| 1874 |
+
# from the last heartbeat (WorkerHeartbeat)
|
| 1875 |
+
mem: WorkerMem | None = None
|
| 1876 |
+
restore: RestoreProgress | None = None
|
| 1877 |
+
tools: dict[str, ToolCounters] | None = None
|
| 1878 |
+
knobs_rev: str | None = None
|
| 1879 |
+
wants_rotation: bool = False
|
| 1880 |
+
|
| 1881 |
+
|
| 1882 |
+
class LoopStatus(BaseModel):
|
| 1883 |
+
"""A type's loop (docs/loop.md). `state`: running, final (final round in flight), done
|
| 1884 |
+
(final round over, or stopped without one)."""
|
| 1885 |
+
|
| 1886 |
+
type: str
|
| 1887 |
+
state: Literal["running", "final", "done"]
|
| 1888 |
+
mode: Literal["worker", "controller"] # who sends `every: turn_end` prompts
|
| 1889 |
+
every: str
|
| 1890 |
+
started_at: datetime | None = None
|
| 1891 |
+
stopped_at: datetime | None = None
|
| 1892 |
+
reason: str | None = None # why it stopped
|
| 1893 |
+
agents: int = 0
|
| 1894 |
+
agents_done: int = 0 # out of the loop (max_rounds, agent_usd, errors)
|
| 1895 |
+
rounds_min: int = 0
|
| 1896 |
+
rounds_max: int = 0
|
| 1897 |
+
rounds_total: int = 0
|
| 1898 |
+
wakes_total: int = 0 # wake prompts sent (`on:`); in rounds_total too only with counts_as_round
|
| 1899 |
+
final_sent: int = 0
|
| 1900 |
+
final_done: int = 0
|
| 1901 |
+
per_agent: dict[str, dict[str, Any]] | None = None # GET /swarms/{s}/loop only
|
| 1902 |
+
|
| 1903 |
+
|
| 1904 |
+
class TypeStatus(BaseModel):
|
| 1905 |
+
name: str
|
| 1906 |
+
health: TypeHealth
|
| 1907 |
+
replicas: int
|
| 1908 |
+
agents_by_state: dict[str, int]
|
| 1909 |
+
workers_by_state: dict[str, int]
|
| 1910 |
+
cost_usd: float = 0.0
|
| 1911 |
+
# Last worker-launch error for this type (the backend's message), cleared by a successful
|
| 1912 |
+
# launch or a new apply. With health launch_refused it is why launches stopped.
|
| 1913 |
+
launch_error: str | None = None
|
| 1914 |
+
loop: LoopStatus | None = None
|
| 1915 |
+
|
| 1916 |
+
|
| 1917 |
+
class ProviderStatus(BaseModel):
|
| 1918 |
+
name: str
|
| 1919 |
+
type: str
|
| 1920 |
+
self_hosted: bool
|
| 1921 |
+
types: list[str] # agent types using this provider
|
| 1922 |
+
working: int # agents of those types in a turn now (from heartbeats)
|
| 1923 |
+
max_working: int | None = None # enforced at prompt admission unless FLOCK_MAX_WORKING_ENFORCE=0
|
| 1924 |
+
# Agents with turns but zero reported tokens: the server sends no usage, cost is unknown.
|
| 1925 |
+
zero_usage_agents: int = 0
|
| 1926 |
+
|
| 1927 |
+
|
| 1928 |
+
class SwarmStatus(BaseModel):
|
| 1929 |
+
swarm: str
|
| 1930 |
+
namespace: str
|
| 1931 |
+
bucket: str
|
| 1932 |
+
types: dict[str, TypeStatus]
|
| 1933 |
+
providers: dict[str, ProviderStatus] = Field(default_factory=dict)
|
| 1934 |
+
agents_total: int
|
| 1935 |
+
workers_total: int
|
| 1936 |
+
pending_prompts: int
|
| 1937 |
+
cost_usd: float = 0.0
|
| 1938 |
+
# limits.budget_usd as a stop (docs/loop.md): None (under the threshold or no budget),
|
| 1939 |
+
# "final_reserve" (loops stopped, final rounds) or "hard" (every agent stopped).
|
| 1940 |
+
budget_stop: Literal["final_reserve", "hard"] | None = None
|
| 1941 |
+
# pause holds (docs/loop.md "Pause and resume"): {types: {T: {since, reason, by, auto}},
|
| 1942 |
+
# agents: {A: ...}}; None when nothing is held
|
| 1943 |
+
held: dict[str, dict[str, dict[str, Any]]] | None = None
|
| 1944 |
+
# `flock stop --release`: {since, reason, unsynced: {agent: error}}; None when not released
|
| 1945 |
+
released: dict[str, Any] | None = None
|
| 1946 |
+
# bumped by every apply that changes the spec (docs/live.md)
|
| 1947 |
+
generation: int | None = None
|
| 1948 |
+
|
| 1949 |
+
|
| 1950 |
+
class LoopRequest(BaseModel):
|
| 1951 |
+
"""`POST /swarms/{swarm}/loop`: stop or (re)start one type's loop."""
|
| 1952 |
+
|
| 1953 |
+
type: str
|
| 1954 |
+
action: Literal["start", "stop"]
|
| 1955 |
+
final: bool = True # stop: run the final round (if the type has one)
|
| 1956 |
+
|
| 1957 |
+
|
| 1958 |
+
class PreflightResult(BaseModel):
|
| 1959 |
+
"""One provider-backed model probed with a tool call and a follow-up turn."""
|
| 1960 |
+
|
| 1961 |
+
model: str # "<provider>:<model id>"
|
| 1962 |
+
provider: str
|
| 1963 |
+
types: list[str]
|
| 1964 |
+
# "responses" (openai_compat) | "messages" (anthropic) |
|
| 1965 |
+
# "chat_completions" (openai_compat; Harbor's Pi)
|
| 1966 |
+
api: str
|
| 1967 |
+
ok: bool # a tool call in turn one and a completed follow-up turn carrying its result
|
| 1968 |
+
# Not probed (e.g. the key is not in the controller's environment): neither ok nor failed.
|
| 1969 |
+
# `apply` warns and proceeds, or refuses with --strict.
|
| 1970 |
+
unverified: bool = False
|
| 1971 |
+
tool_call_seen: bool = False
|
| 1972 |
+
follow_up_ok: bool = False
|
| 1973 |
+
usage_reported: bool | None = None # False: the server streamed zero tokens (cost unknown)
|
| 1974 |
+
latency_ms: int | None = None # both turns
|
| 1975 |
+
error: str | None = None
|
| 1976 |
+
warning: str | None = None
|
| 1977 |
+
|
| 1978 |
+
|
| 1979 |
+
class PreflightReport(BaseModel):
|
| 1980 |
+
swarm: str
|
| 1981 |
+
ok: bool # no probe failed (unverified models do not count as failures here)
|
| 1982 |
+
unverified: int = 0 # models that were not probed
|
| 1983 |
+
results: list[PreflightResult]
|
| 1984 |
+
|
| 1985 |
+
|
| 1986 |
+
# --------------------------------------------------------------------------- constants
|
| 1987 |
+
|
| 1988 |
+
HEARTBEAT_INTERVAL = timedelta(seconds=30)
|
| 1989 |
+
LOCAL_HEARTBEAT_INTERVAL = timedelta(seconds=5) # compute local: agent states within seconds
|
| 1990 |
+
# Worker liveness defaults; a spec's `compute:` overrides them (ComputeSpec.liveness).
|
| 1991 |
+
UNKNOWN_AFTER = timedelta(seconds=90)
|
| 1992 |
+
DEAD_AFTER = timedelta(seconds=180)
|
| 1993 |
+
CRASH_BACKOFF = timedelta(seconds=30) # first relaunch wait, doubling per crash in a row
|
| 1994 |
+
# compute local: 3 and 6 missed local heartbeats, the jobs ratio; an exited worker
|
| 1995 |
+
# process is caught on the next reconcile pass anyway, so these only time out a hung one
|
| 1996 |
+
LOCAL_LIVENESS = (timedelta(seconds=15), timedelta(seconds=30), timedelta(seconds=2))
|
| 1997 |
+
|
| 1998 |
+
|
| 1999 |
+
class Liveness(NamedTuple):
|
| 2000 |
+
"""A swarm's worker liveness timings, in seconds (`ComputeSpec.liveness`)."""
|
| 2001 |
+
|
| 2002 |
+
unknown_after: float
|
| 2003 |
+
dead_after: float
|
| 2004 |
+
crash_backoff: float
|
| 2005 |
+
|
| 2006 |
+
CRASHLOOP_THRESHOLD = 5
|
| 2007 |
+
LAUNCHES_PER_WINDOW = 400 # per 5-minute Hub rate-limit window, PRO assumption
|
| 2008 |
+
RATE_WINDOW = timedelta(minutes=5)
|
| 2009 |
+
JOB_LABELS = ("swarm", "type", "worker") # every worker job carries these labels
|
world/src/flock/registry.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The harness and compute-backend registries: adding either is one module plus one entry here
|
| 2 |
+
(docs/design.md, "Adding a harness or a compute backend"). The spec loader, controller, worker
|
| 3 |
+
and CLI all read these entries. Code is named by import path ("module:function") and imported
|
| 4 |
+
only when used, so the controller never imports worker-only dependencies."""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from importlib import import_module
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass(frozen=True)
|
| 14 |
+
class HarnessEntry:
|
| 15 |
+
adapter: str # "module:function"; function(workdir, agent name, TypeSpec) -> HarnessAdapter
|
| 16 |
+
# (harbor's also takes `host=`, the worker's HarborHost)
|
| 17 |
+
provider_type: str # the provider `type` a provider-backed model must have
|
| 18 |
+
api: str # the wire API it speaks to that provider (preflight probes this one)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
HARNESSES: dict[str, HarnessEntry] = {
|
| 22 |
+
# one Harbor Trial per agent on the upstream Harbor task path (flock.harbor). Harbor installs Pi
|
| 23 |
+
# (flock.harbor.config.PI_VERSION) in the task's container and the Trial delivers the
|
| 24 |
+
# instructions
|
| 25 |
+
"harbor": HarnessEntry("flock.worker.adapters.harbor:make_adapter", "openai_compat",
|
| 26 |
+
"chat_completions"),
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
# `compute.kind` / FLOCK_COMPUTE -> "module:function"; function(env, deployment, data_dir) ->
|
| 30 |
+
# JobsClient. The function also rejects a controller setup the backend cannot run in.
|
| 31 |
+
COMPUTE: dict[str, str] = {
|
| 32 |
+
"hf-jobs": "flock.controller.jobs:hub_jobs_client",
|
| 33 |
+
"local": "flock.controller.local:local_jobs_client", # docs/local.md
|
| 34 |
+
"slurm": "flock.controller.slurm:slurm_jobs_client", # docs/slurm.md
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def load(path: str) -> Any:
|
| 39 |
+
module, _, name = path.partition(":")
|
| 40 |
+
return getattr(import_module(module), name)
|
world/src/flock/tools/__init__.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runtime tools folder: plain Python functions next to the spec become agent tools.
|
| 2 |
+
|
| 3 |
+
What a tool module imports from here: `Context` (the optional run-context argument, never shown
|
| 4 |
+
to the model), `ToolError` (raise it to hand the model a clean error message) and `readonly`
|
| 5 |
+
(a decorator: the tool changes nothing; informational). The loader,
|
| 6 |
+
schema builder, runner and bundle code live in the submodules; this module stays stdlib-only so
|
| 7 |
+
the per-call subprocess starts fast.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass, field
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
READONLY_ATTR = "__flock_readonly__"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class Context:
|
| 20 |
+
"""What a tool learns about the call. Declare a parameter named `ctx` (or annotated
|
| 21 |
+
`Context`) to receive it; the model never sees it.
|
| 22 |
+
|
| 23 |
+
- agent, type, swarm: who is calling (the swarm name is the run id).
|
| 24 |
+
- workdir: the agent's working directory (also the call's cwd).
|
| 25 |
+
- data_dir: a directory for tool state, shared by the agents of this worker, kept across
|
| 26 |
+
tools versions, not synced to the bucket.
|
| 27 |
+
- tools_dir: the extracted tools folder of this version; tools_version: its content hash.
|
| 28 |
+
- env: the agent's environment (what its `bash` sees), also the call's process environment.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
agent: str
|
| 32 |
+
type: str
|
| 33 |
+
swarm: str
|
| 34 |
+
workdir: Path
|
| 35 |
+
data_dir: Path
|
| 36 |
+
tools_dir: Path
|
| 37 |
+
tools_version: str
|
| 38 |
+
env: dict[str, str] = field(default_factory=dict)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Ctx = Context
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ToolError(Exception):
|
| 45 |
+
"""Raise from a tool to return `{"error": message}` to the model (no exception type prefix)."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def readonly[F](fn: F) -> F:
|
| 49 |
+
"""Mark a tool as read-only (`readonly: true` in the manifest): it changes no state.
|
| 50 |
+
Informational: nothing in flock acts on it."""
|
| 51 |
+
setattr(fn, READONLY_ATTR, True)
|
| 52 |
+
return fn
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
__all__ = ["Context", "Ctx", "ToolError", "readonly"]
|
world/src/flock/tools/loader.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
"""Tools folder -> tool definitions.
|
| 2 |
+
|
| 3 |
+
Every `*.py` file at the top of the folder whose name does not start with `_` is a tool module.
|
| 4 |
+
Every function defined in it (not imported) whose name does not start with `_` and that has a
|
| 5 |
+
docstring is a tool: name = function name, description = the docstring's first paragraph,
|
| 6 |
+
parameters = a JSON schema built from the type hints (descriptions from an `Args:` section).
|
| 7 |
+
A parameter named `ctx`, or annotated `flock.tools.Context`, is injected at call time and
|
| 8 |
+
never shown to the model.
|
| 9 |
+
|
| 10 |
+
`load_dir` imports the modules in this process; `describe` runs it in a fresh `python -I`
|
| 11 |
+
subprocess (what `flock launch` uses), so a module's side effects, crashes and hangs stay
|
| 12 |
+
there. `python -m flock.tools.loader <dir>` prints the manifest as JSON.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import importlib
|
| 18 |
+
import inspect
|
| 19 |
+
import json
|
| 20 |
+
import re
|
| 21 |
+
import subprocess
|
| 22 |
+
import sys
|
| 23 |
+
import types
|
| 24 |
+
import typing
|
| 25 |
+
from dataclasses import asdict, dataclass, field
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Any
|
| 28 |
+
|
| 29 |
+
from flock.tools import READONLY_ATTR, Context
|
| 30 |
+
|
| 31 |
+
NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
|
| 32 |
+
CTX_NAME = "ctx"
|
| 33 |
+
DESCRIBE_TIMEOUT_S = 60.0
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ToolsError(ValueError):
|
| 37 |
+
"""The tools folder cannot be loaded; the message says which file and why."""
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class ToolDef:
|
| 42 |
+
name: str
|
| 43 |
+
description: str
|
| 44 |
+
parameters: dict[str, Any] # JSON schema, type object
|
| 45 |
+
module: str # module name inside the folder
|
| 46 |
+
function: str
|
| 47 |
+
ctx: str | None = None # the parameter that receives the Context, if any
|
| 48 |
+
is_async: bool = False
|
| 49 |
+
# A built-in served by the worker itself, not the folder (`comms:post`, docs/comms.md).
|
| 50 |
+
builtin: str | None = None
|
| 51 |
+
# Changes nothing (`@flock.tools.readonly`; informational). In the manifest only when true.
|
| 52 |
+
readonly: bool = False
|
| 53 |
+
|
| 54 |
+
def openai(self) -> dict[str, Any]:
|
| 55 |
+
"""The Chat Completions function tool."""
|
| 56 |
+
return {"type": "function", "function": {
|
| 57 |
+
"name": self.name, "description": self.description, "parameters": self.parameters}}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclass
|
| 61 |
+
class Manifest:
|
| 62 |
+
tools: list[ToolDef] = field(default_factory=list)
|
| 63 |
+
|
| 64 |
+
def names(self) -> list[str]:
|
| 65 |
+
return [t.name for t in self.tools]
|
| 66 |
+
|
| 67 |
+
def get(self, name: str) -> ToolDef | None:
|
| 68 |
+
return next((t for t in self.tools if t.name == name), None)
|
| 69 |
+
|
| 70 |
+
def to_json(self) -> dict[str, Any]:
|
| 71 |
+
# `readonly` only when set, so a folder without it keeps its manifest (and version)
|
| 72 |
+
return {"tools": [{k: v for k, v in asdict(t).items() if k != "readonly" or v}
|
| 73 |
+
for t in self.tools]}
|
| 74 |
+
|
| 75 |
+
@classmethod
|
| 76 |
+
def from_json(cls, data: dict[str, Any]) -> Manifest:
|
| 77 |
+
return cls([ToolDef(**t) for t in data.get("tools") or []])
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# --------------------------------------------------------------------------- schema
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _first_paragraph(doc: str) -> str:
|
| 84 |
+
para: list[str] = []
|
| 85 |
+
for line in doc.strip().splitlines():
|
| 86 |
+
if not line.strip():
|
| 87 |
+
break
|
| 88 |
+
para.append(line.strip())
|
| 89 |
+
return " ".join(para)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
_ARGS_HEAD = re.compile(r"^\s*(Args|Arguments|Parameters|Params)\s*:\s*$")
|
| 93 |
+
_ARG_LINE = re.compile(r"^\s*\**([A-Za-z_][A-Za-z0-9_]*)\**\s*(\([^)]*\))?\s*:\s*(.*)$")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def arg_docs(doc: str) -> dict[str, str]:
|
| 97 |
+
"""Per-parameter descriptions from a Google-style `Args:` section (continuation lines are
|
| 98 |
+
joined; the section ends at a blank line or a less-indented line)."""
|
| 99 |
+
out: dict[str, str] = {}
|
| 100 |
+
lines = doc.splitlines()
|
| 101 |
+
i = next((k for k, line in enumerate(lines) if _ARGS_HEAD.match(line)), None)
|
| 102 |
+
if i is None:
|
| 103 |
+
return out
|
| 104 |
+
head_indent = len(lines[i]) - len(lines[i].lstrip())
|
| 105 |
+
current: str | None = None
|
| 106 |
+
item_indent = None
|
| 107 |
+
for line in lines[i + 1:]:
|
| 108 |
+
if not line.strip():
|
| 109 |
+
break
|
| 110 |
+
indent = len(line) - len(line.lstrip())
|
| 111 |
+
if indent <= head_indent:
|
| 112 |
+
break
|
| 113 |
+
m = _ARG_LINE.match(line)
|
| 114 |
+
if m and (item_indent is None or indent <= item_indent):
|
| 115 |
+
item_indent = indent
|
| 116 |
+
current = m.group(1)
|
| 117 |
+
out[current] = m.group(3).strip()
|
| 118 |
+
elif current is not None:
|
| 119 |
+
out[current] = (out[current] + " " + line.strip()).strip()
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _is_context(hint: Any) -> bool:
|
| 124 |
+
return hint is Context or (isinstance(hint, type) and issubclass(hint, Context))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def nullable(schema: dict[str, Any]) -> dict[str, Any]:
|
| 128 |
+
"""`schema` that also accepts null (an `Any` schema already does)."""
|
| 129 |
+
out = dict(schema)
|
| 130 |
+
t = out.get("type")
|
| 131 |
+
if isinstance(t, str):
|
| 132 |
+
out["type"] = [t, "null"]
|
| 133 |
+
elif isinstance(t, list) and "null" not in t:
|
| 134 |
+
out["type"] = [*t, "null"]
|
| 135 |
+
if "enum" in out and None not in out["enum"]:
|
| 136 |
+
out["enum"] = [*out["enum"], None]
|
| 137 |
+
return out
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def type_schema(hint: Any, where: str) -> tuple[dict[str, Any], bool]:
|
| 141 |
+
"""(JSON schema, nullable) for a type hint. `X | None` / `Optional[X]` is nullable: the
|
| 142 |
+
schema accepts null too (`type: [X, "null"]`, None added to an enum). Nullable is not
|
| 143 |
+
omittable: only a default makes a parameter optional."""
|
| 144 |
+
if hint is inspect.Parameter.empty:
|
| 145 |
+
raise ToolsError(f"{where}: needs a type annotation (str, int, float, bool, list[...], dict)")
|
| 146 |
+
origin = typing.get_origin(hint)
|
| 147 |
+
args = typing.get_args(hint)
|
| 148 |
+
if origin in (typing.Union, types.UnionType):
|
| 149 |
+
rest = [a for a in args if a is not type(None)]
|
| 150 |
+
if len(rest) != 1 or len(rest) == len(args):
|
| 151 |
+
raise ToolsError(f"{where}: unions other than `X | None` are not supported")
|
| 152 |
+
return nullable(type_schema(rest[0], where)[0]), True
|
| 153 |
+
if hint is typing.Any:
|
| 154 |
+
return {}, False
|
| 155 |
+
if hint is str:
|
| 156 |
+
return {"type": "string"}, False
|
| 157 |
+
if hint is bool:
|
| 158 |
+
return {"type": "boolean"}, False
|
| 159 |
+
if hint is int:
|
| 160 |
+
return {"type": "integer"}, False
|
| 161 |
+
if hint is float:
|
| 162 |
+
return {"type": "number"}, False
|
| 163 |
+
if hint in (list, typing.List) or origin is list: # noqa: UP006
|
| 164 |
+
items = type_schema(args[0], where)[0] if args else {}
|
| 165 |
+
return {"type": "array", "items": items}, False
|
| 166 |
+
if hint in (dict, typing.Dict) or origin is dict: # noqa: UP006
|
| 167 |
+
return {"type": "object"}, False
|
| 168 |
+
if origin is typing.Literal:
|
| 169 |
+
kinds = {type(a) for a in args}
|
| 170 |
+
schema: dict[str, Any] = {"enum": list(args)}
|
| 171 |
+
if kinds == {str}:
|
| 172 |
+
schema["type"] = "string"
|
| 173 |
+
elif kinds == {int}:
|
| 174 |
+
schema["type"] = "integer"
|
| 175 |
+
return schema, False
|
| 176 |
+
raise ToolsError(f"{where}: unsupported type {hint!r}; use str, int, float, bool, "
|
| 177 |
+
"list[...], dict, Literal[...] or X | None")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def tool_def(fn: Any, module: str) -> ToolDef:
|
| 181 |
+
"""The ToolDef of one function (raises ToolsError naming module.function)."""
|
| 182 |
+
name = fn.__name__
|
| 183 |
+
where = f"{module}.{name}"
|
| 184 |
+
if not NAME_RE.match(name):
|
| 185 |
+
raise ToolsError(f"{where}: tool names must match {NAME_RE.pattern}")
|
| 186 |
+
doc = inspect.getdoc(fn) or ""
|
| 187 |
+
try:
|
| 188 |
+
hints = typing.get_type_hints(fn)
|
| 189 |
+
except Exception as e:
|
| 190 |
+
raise ToolsError(f"{where}: cannot resolve type hints: {type(e).__name__}: {e}") from e
|
| 191 |
+
sig = inspect.signature(fn)
|
| 192 |
+
docs = arg_docs(doc)
|
| 193 |
+
props: dict[str, Any] = {}
|
| 194 |
+
required: list[str] = []
|
| 195 |
+
ctx = None
|
| 196 |
+
for p in sig.parameters.values():
|
| 197 |
+
hint = hints.get(p.name, p.annotation)
|
| 198 |
+
if p.name == CTX_NAME or _is_context(hint):
|
| 199 |
+
ctx = p.name
|
| 200 |
+
continue
|
| 201 |
+
if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
|
| 202 |
+
raise ToolsError(f"{where}: *args / **kwargs are not supported; name every parameter")
|
| 203 |
+
if p.kind is p.POSITIONAL_ONLY:
|
| 204 |
+
raise ToolsError(f"{where}: positional-only parameters are not supported")
|
| 205 |
+
schema, _ = type_schema(hint, f"{where}({p.name})")
|
| 206 |
+
schema = dict(schema)
|
| 207 |
+
if docs.get(p.name):
|
| 208 |
+
schema["description"] = docs[p.name]
|
| 209 |
+
if p.default is not p.empty:
|
| 210 |
+
try:
|
| 211 |
+
json.dumps(p.default)
|
| 212 |
+
if p.default is not None:
|
| 213 |
+
schema["default"] = p.default
|
| 214 |
+
except (TypeError, ValueError):
|
| 215 |
+
pass
|
| 216 |
+
else: # no default: required, nullable or not (the call has no value to fall back on)
|
| 217 |
+
required.append(p.name)
|
| 218 |
+
props[p.name] = schema
|
| 219 |
+
params: dict[str, Any] = {"type": "object", "properties": props, "additionalProperties": False}
|
| 220 |
+
if required:
|
| 221 |
+
params["required"] = required
|
| 222 |
+
return ToolDef(name=name, description=_first_paragraph(doc), parameters=params, module=module,
|
| 223 |
+
function=name, ctx=ctx, is_async=inspect.iscoroutinefunction(fn),
|
| 224 |
+
readonly=getattr(fn, READONLY_ATTR, False) is True)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def tool_modules(folder: Path) -> list[Path]:
|
| 228 |
+
return sorted(p for p in folder.glob("*.py") if not p.name.startswith("_"))
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
_LOADED: set[str] = set()
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def load_dir(folder: str | Path) -> Manifest:
|
| 235 |
+
"""Import every tool module of `folder` (put on sys.path first, so modules may import their
|
| 236 |
+
`_helpers`) and collect the tools. Raises ToolsError on a bad module or a duplicate name."""
|
| 237 |
+
folder = Path(folder).resolve()
|
| 238 |
+
if not folder.is_dir():
|
| 239 |
+
raise ToolsError(f"tools folder {folder} does not exist")
|
| 240 |
+
sys.path.insert(0, str(folder))
|
| 241 |
+
for name in _LOADED & set(sys.modules): # an earlier folder's modules (same process)
|
| 242 |
+
del sys.modules[name]
|
| 243 |
+
importlib.invalidate_caches()
|
| 244 |
+
tools: dict[str, ToolDef] = {}
|
| 245 |
+
for path in tool_modules(folder):
|
| 246 |
+
mod_name = path.stem
|
| 247 |
+
_LOADED.add(mod_name)
|
| 248 |
+
try:
|
| 249 |
+
mod = importlib.import_module(mod_name)
|
| 250 |
+
except SyntaxError as e:
|
| 251 |
+
raise ToolsError(f"{path.name}: syntax error line {e.lineno}: {e.msg}") from e
|
| 252 |
+
except Exception as e:
|
| 253 |
+
raise ToolsError(f"{path.name}: import failed: {type(e).__name__}: {e}") from e
|
| 254 |
+
if Path(getattr(mod, "__file__", "") or "").resolve() != path:
|
| 255 |
+
raise ToolsError(f"{path.name}: module name {mod_name!r} is shadowed by "
|
| 256 |
+
f"{getattr(mod, '__file__', None) or 'a built-in module'}; rename the file")
|
| 257 |
+
for attr, fn in vars(mod).items():
|
| 258 |
+
if attr.startswith("_") or not inspect.isfunction(fn) or fn.__module__ != mod.__name__:
|
| 259 |
+
continue
|
| 260 |
+
if not inspect.getdoc(fn):
|
| 261 |
+
continue # no docstring: a helper, not a tool
|
| 262 |
+
t = tool_def(fn, mod_name)
|
| 263 |
+
if t.name in tools:
|
| 264 |
+
raise ToolsError(f"{path.name}: tool {t.name!r} is also defined in "
|
| 265 |
+
f"{tools[t.name].module}.py")
|
| 266 |
+
tools[t.name] = t
|
| 267 |
+
return Manifest(list(tools.values()))
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def describe(folder: str | Path, *, python: str | None = None,
|
| 271 |
+
timeout: float = DESCRIBE_TIMEOUT_S) -> Manifest:
|
| 272 |
+
"""`load_dir` in a fresh `python -I` process (cwd: the folder's parent). Raises ToolsError."""
|
| 273 |
+
folder = Path(folder).resolve()
|
| 274 |
+
if not folder.is_dir():
|
| 275 |
+
raise ToolsError(f"tools folder {folder} does not exist")
|
| 276 |
+
cmd = [python or sys.executable, "-I", "-B", "-m", "flock.tools.loader", str(folder)]
|
| 277 |
+
try:
|
| 278 |
+
p = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=timeout,
|
| 279 |
+
cwd=str(folder.parent), stdin=subprocess.DEVNULL)
|
| 280 |
+
except subprocess.TimeoutExpired as e:
|
| 281 |
+
raise ToolsError(f"loading {folder} took over {timeout:g}s (a module blocks at import?)") from e
|
| 282 |
+
try:
|
| 283 |
+
out = json.loads(p.stdout.strip().splitlines()[-1]) if p.stdout.strip() else None
|
| 284 |
+
except ValueError:
|
| 285 |
+
out = None
|
| 286 |
+
if not isinstance(out, dict):
|
| 287 |
+
tail = (p.stderr or p.stdout or "").strip()[-800:]
|
| 288 |
+
raise ToolsError(f"loading {folder} failed (exit {p.returncode}): {tail}")
|
| 289 |
+
if "error" in out:
|
| 290 |
+
raise ToolsError(out["error"])
|
| 291 |
+
return Manifest.from_json(out)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def select(manifest: Manifest, wanted: list[str] | str | None, *, where: str = "tools") -> list[ToolDef]:
|
| 295 |
+
"""The tools a type gets: `all`, a list of names (unknown names raise ToolsError), or none."""
|
| 296 |
+
if wanted is None:
|
| 297 |
+
return []
|
| 298 |
+
if wanted == "all":
|
| 299 |
+
return list(manifest.tools)
|
| 300 |
+
if isinstance(wanted, str):
|
| 301 |
+
raise ToolsError(f"{where}: use a list of tool names or `all`, not {wanted!r}")
|
| 302 |
+
unknown = [n for n in wanted if manifest.get(n) is None]
|
| 303 |
+
if unknown:
|
| 304 |
+
known = ", ".join(manifest.names()) or "none"
|
| 305 |
+
raise ToolsError(f"{where}: unknown tool(s) {', '.join(unknown)}; the tools folder has: {known}")
|
| 306 |
+
return [t for n in dict.fromkeys(wanted) if (t := manifest.get(n)) is not None]
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _main(argv: list[str]) -> int:
|
| 310 |
+
if len(argv) != 1:
|
| 311 |
+
print(json.dumps({"error": "usage: python -m flock.tools.loader <tools dir>"}))
|
| 312 |
+
return 2
|
| 313 |
+
import contextlib
|
| 314 |
+
import io
|
| 315 |
+
|
| 316 |
+
sink = io.StringIO() # prints at import time must not corrupt the JSON line
|
| 317 |
+
try:
|
| 318 |
+
with contextlib.redirect_stdout(sink):
|
| 319 |
+
manifest = load_dir(argv[0])
|
| 320 |
+
out: dict[str, Any] = manifest.to_json()
|
| 321 |
+
except ToolsError as e:
|
| 322 |
+
out = {"error": str(e)}
|
| 323 |
+
print(json.dumps(out))
|
| 324 |
+
return 0
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
sys.exit(_main(sys.argv[1:]))
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
# --------------------------------------------------------------------------- arguments
|
| 332 |
+
|
| 333 |
+
_JSON_TYPES: dict[str, tuple[type, ...]] = {
|
| 334 |
+
"string": (str,), "integer": (int,), "number": (int, float), "boolean": (bool,),
|
| 335 |
+
"array": (list,), "object": (dict,),
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _types(schema: dict[str, Any]) -> list[str] | None:
|
| 340 |
+
t = schema.get("type")
|
| 341 |
+
if isinstance(t, str):
|
| 342 |
+
return [t]
|
| 343 |
+
return list(t) if isinstance(t, list) else None
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _is(value: Any, t: str) -> bool:
|
| 347 |
+
if t == "null":
|
| 348 |
+
return value is None
|
| 349 |
+
if t not in _JSON_TYPES:
|
| 350 |
+
return True
|
| 351 |
+
return isinstance(value, _JSON_TYPES[t]) and not (t in ("integer", "number") and isinstance(value, bool))
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _check(schema: dict[str, Any], value: Any, where: str) -> str | None:
|
| 355 |
+
"""Type and enum checks; null only where the schema allows it (`X | None`), array items
|
| 356 |
+
included. A schema without `type` (`Any`) accepts anything."""
|
| 357 |
+
types = _types(schema)
|
| 358 |
+
if types is not None and not any(_is(value, t) for t in types):
|
| 359 |
+
want = " or ".join("null" if t == "null" else t for t in types)
|
| 360 |
+
got = "null" if value is None else f"{type(value).__name__} {json.dumps(value)[:60]}"
|
| 361 |
+
return f"{where} must be {want}, got {got}"
|
| 362 |
+
if "enum" in schema and value not in schema["enum"]:
|
| 363 |
+
return f"{where} must be one of {schema['enum']}, got {json.dumps(value)[:60]}"
|
| 364 |
+
if isinstance(value, list) and isinstance(schema.get("items"), dict):
|
| 365 |
+
for i, v in enumerate(value):
|
| 366 |
+
if err := _check(schema["items"], v, f"{where}[{i}]"):
|
| 367 |
+
return err
|
| 368 |
+
return None
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def check_args(params: dict[str, Any], args: Any) -> str | None:
|
| 372 |
+
"""An error message for arguments that do not fit the tool's schema, else None."""
|
| 373 |
+
if not isinstance(args, dict):
|
| 374 |
+
return f"arguments must be a JSON object, got {type(args).__name__}"
|
| 375 |
+
props = params.get("properties") or {}
|
| 376 |
+
unknown = [k for k in args if k not in props]
|
| 377 |
+
if unknown:
|
| 378 |
+
return f"unknown argument(s) {', '.join(unknown)}; expected: {', '.join(props) or 'none'}"
|
| 379 |
+
missing = [k for k in params.get("required") or [] if k not in args]
|
| 380 |
+
if missing:
|
| 381 |
+
return f"missing required argument(s): {', '.join(missing)}"
|
| 382 |
+
for k, v in args.items():
|
| 383 |
+
if err := _check(props[k], v, k):
|
| 384 |
+
return err
|
| 385 |
+
return None
|
world/src/flock/worker/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Worker: hosts agents on one HF Job; see docs/design.md "Architecture"."""
|
world/src/flock/worker/sync.py
ADDED
|
@@ -0,0 +1,1181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bucket sync: per agent, `<BUCKET>/<swarm>/<type>/<agent>/` holds
|
| 2 |
+
|
| 3 |
+
workdir/<path relative to the workdir> (if persist_workdir; the deltas with a base)
|
| 4 |
+
workdir.base.tar, workdir.base.json (only with the type's workdir.base, below)
|
| 5 |
+
meta.json ({files, bytes, ts} of the mirrored workdir when it last changed)
|
| 6 |
+
sessions/<agent>.jsonl, <agent>.state.json (pi session log + worker state)
|
| 7 |
+
harness/<path relative to the harness home> (a Trial's Pi sessions)
|
| 8 |
+
|
| 9 |
+
The workdir goes through `sync_bucket` (the Python form of `hf buckets sync`), upward with delete so the bucket mirrors the workdir. The handful of
|
| 10 |
+
session and harness files go through `batch_bucket_files`, only those whose (mtime, size)
|
| 11 |
+
changed since the last push by this worker. `restore` brings all three areas back to the
|
| 12 |
+
same absolute paths (workdir and work root are fixed, harness homes are fixed by the image)
|
| 13 |
+
before the first resume.
|
| 14 |
+
|
| 15 |
+
Restore lists the agent's prefix once, then downloads every file it found in batches
|
| 16 |
+
(`restore_batch()`: env `FLOCK_RESTORE_BATCH`, default 1000, minimum 1, an invalid value
|
| 17 |
+
means the default), `restore_threads()` batches at a time (env `FLOCK_RESTORE_THREADS`,
|
| 18 |
+
default 4; the type's `worker:` block overrides both), each to a `.flock-part` sibling renamed into place on success. A batch that
|
| 19 |
+
fails is retried file by file, with backoff (`RESTORE_BACKOFF`) between rounds: one unreadable
|
| 20 |
+
file is skipped and reported in `RestoreResult.failed` instead of aborting the whole restore. A
|
| 21 |
+
permanent "not found" (HTTP 404, e.g. xet "CAS Client Error: ... 404 Not Found" on the
|
| 22 |
+
reconstruction: the entry's data is gone) is skipped at once, without the backoff rounds (an
|
| 23 |
+
already-corrupt copy with ~42k such entries took 636 s to restore with them). Skipped files are
|
| 24 |
+
logged as one summary line per agent. Only a failed listing makes `restore` raise.
|
| 25 |
+
|
| 26 |
+
Buckets store bytes, not file modes: a restored file comes back 0644, so an executable script
|
| 27 |
+
would stop running after a move. Each
|
| 28 |
+
push therefore writes `<workdir>/.flock-modes.json` ({relative path: octal mode} for every file
|
| 29 |
+
with an executable bit) when it changed, and restore re-applies it after the workdir download.
|
| 30 |
+
|
| 31 |
+
Push safety (a periodic sync must never mirror a half-restored workdir over the bucket copy,
|
| 32 |
+
deleting entries the in-flight restore has not fetched yet):
|
| 33 |
+
|
| 34 |
+
- No push before setup: `AgentRuntime.sync_now` does nothing until the agent's `setup()` has
|
| 35 |
+
finished its restore (every caller: the periodic sync, drain, preempt, unassign), and
|
| 36 |
+
`BucketSync.push` refuses an agent whose restore is in flight. The bucket copy is the truth
|
| 37 |
+
until the restore is done.
|
| 38 |
+
- Delete-mirror only from a full baseline: the workdir push deletes remote files missing
|
| 39 |
+
locally only when this worker's restore of the agent was complete (the listing succeeded and
|
| 40 |
+
no file failed; an empty prefix counts as complete) or when no restore was attempted (a new
|
| 41 |
+
agent). After a failed listing, a skipped file or an interrupted restore, pushes upload
|
| 42 |
+
changed files but never delete, for as long as this worker holds the agent: a file it could
|
| 43 |
+
not fetch stays in the bucket for the next restore.
|
| 44 |
+
- `*.flock-part` (restore temporaries) is never uploaded nor deleted by a push; restore removes
|
| 45 |
+
stray ones left by a crash.
|
| 46 |
+
- Regenerable caches (`workdir_excludes`: `__pycache__/`, `*.pyc`, `node_modules/`, `.venv/`, ...; env
|
| 47 |
+
FLOCK_SYNC_EXCLUDE adds globs, FLOCK_SYNC_EXCLUDE_DEFAULTS=0 drops the defaults) are neither
|
| 48 |
+
uploaded nor deleted by the mirror, and restore skips them, also those already in the bucket.
|
| 49 |
+
`.git/` and worktrees are never excluded by default.
|
| 50 |
+
- The type's `workdir.ephemeral` dirs (root-relative) are excluded like the caches; the agent's
|
| 51 |
+
setup empties them (`reset_ephemeral`), so they never come back after a move.
|
| 52 |
+
- Each push's modes walk also measures what is mirrored (`WorkdirStats`): above the type's
|
| 53 |
+
`workdir.soft_*` the agent gets a note, above `max_*` a `workdir_over_quota` event (each at
|
| 54 |
+
most hourly, `BucketSync._quota`). A push is never refused for size.
|
| 55 |
+
- Restore sets each workdir file's mtime to the bucket's (the listing carries it), so the first
|
| 56 |
+
push after a restore uploads only real changes; session and harness files are marked as
|
| 57 |
+
pushed (`_mark`).
|
| 58 |
+
|
| 59 |
+
Base tar (the type's `workdir.base: true`; off by default). A restore of N small files costs N
|
| 60 |
+
downloads; a base turns most of them into one:
|
| 61 |
+
|
| 62 |
+
- A periodic push (never drain, preempt or unassign) makes a base when the agent has none, every
|
| 63 |
+
`workdir.base_interval_s` (3600) or when the delta passes `workdir.base_delta_files` (5000,
|
| 64 |
+
changed + deleted): an uncompressed tar of the workdir, sorted, regular files and symlinks
|
| 65 |
+
with modes and mtimes (excludes and ephemeral dirs left out), written to local disk and
|
| 66 |
+
uploaded as `workdir.base.tar`; then `workdir.base.json` `{created_at, files, bytes, deleted,
|
| 67 |
+
links}` is written: the commit point. Only from a full baseline (`_mirror`), like deletes.
|
| 68 |
+
- Every push after that uploads to `workdir/` only files whose (mtime, size) differ from the
|
| 69 |
+
base's local index (`<sessions>/<agent>.base-index.json`), giving a changed file with an mtime
|
| 70 |
+
not after the base (`cp -p`) the current time; base paths gone locally go to `deleted`
|
| 71 |
+
(tombstones) and new or changed symlinks to `links`, rewriting the manifest when they change;
|
| 72 |
+
delta entries not needed any more (in the base, or deleted) are removed from `workdir/`.
|
| 73 |
+
- Restore with a manifest: download it and the tar, extract the tar member by member from disk,
|
| 74 |
+
apply `deleted` and `links`, then download only the `workdir/` entries newer than
|
| 75 |
+
`created_at` (older ones are already in the tar). A failed manifest, tar or member makes the
|
| 76 |
+
restore incomplete (no deletes, no new base). Buckets without a manifest restore file by file.
|
| 77 |
+
- Crash safety: before the manifest is written the old manifest (or the plain mirror) stays
|
| 78 |
+
valid; after it, stale `workdir/` entries are older than `created_at`, ignored by restore and
|
| 79 |
+
removed by the next push. Turning `base` off makes the next full-baseline push mirror the whole
|
| 80 |
+
workdir to `workdir/` again and delete the base.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
from __future__ import annotations
|
| 84 |
+
|
| 85 |
+
import asyncio
|
| 86 |
+
import fnmatch
|
| 87 |
+
import functools
|
| 88 |
+
import json
|
| 89 |
+
import logging
|
| 90 |
+
import os
|
| 91 |
+
import re
|
| 92 |
+
import shutil
|
| 93 |
+
import stat
|
| 94 |
+
import tarfile
|
| 95 |
+
import threading
|
| 96 |
+
import time
|
| 97 |
+
from collections import Counter
|
| 98 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 99 |
+
from dataclasses import dataclass, field
|
| 100 |
+
from datetime import UTC, datetime
|
| 101 |
+
from pathlib import Path
|
| 102 |
+
from typing import TYPE_CHECKING, Protocol
|
| 103 |
+
|
| 104 |
+
from flock.models import WorkdirSpec
|
| 105 |
+
|
| 106 |
+
if TYPE_CHECKING:
|
| 107 |
+
from flock.models import TypeSpec
|
| 108 |
+
from flock.worker.agents import AgentRuntime
|
| 109 |
+
|
| 110 |
+
log = logging.getLogger(__name__)
|
| 111 |
+
|
| 112 |
+
UPLOAD_CHUNK = 200
|
| 113 |
+
MODES_FILE = ".flock-modes.json"
|
| 114 |
+
BASE_TAR = "workdir.base.tar" # under the agent prefix (module docstring, "Base tar")
|
| 115 |
+
BASE_JSON = "workdir.base.json"
|
| 116 |
+
RESTORE_BATCH = 1000 # default of FLOCK_RESTORE_BATCH
|
| 117 |
+
RESTORE_THREADS = 4 # default of FLOCK_RESTORE_THREADS
|
| 118 |
+
# The type's `worker:` values for this module (sync_exclude, restore_batch, restore_threads),
|
| 119 |
+
# set live by `Worker.apply_knobs`; each one present wins over its env variable.
|
| 120 |
+
SPEC_KNOBS: dict[str, object] = {}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _env_int(name: str, default: int, cap: int | None = None) -> int:
|
| 124 |
+
try:
|
| 125 |
+
n = int(os.environ.get(name, ""))
|
| 126 |
+
except ValueError:
|
| 127 |
+
return default
|
| 128 |
+
return min(n, cap or n) if n >= 1 else default
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def restore_batch() -> int:
|
| 132 |
+
"""Files per restore download batch: the spec's, else env FLOCK_RESTORE_BATCH (>= 1), else
|
| 133 |
+
RESTORE_BATCH."""
|
| 134 |
+
return SPEC_KNOBS.get("restore_batch") or _env_int("FLOCK_RESTORE_BATCH", RESTORE_BATCH)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def restore_threads() -> int:
|
| 138 |
+
"""Batches of one agent's restore downloaded in parallel: the spec's, else env
|
| 139 |
+
FLOCK_RESTORE_THREADS (>= 1), else RESTORE_THREADS."""
|
| 140 |
+
return SPEC_KNOBS.get("restore_threads") or _env_int("FLOCK_RESTORE_THREADS", RESTORE_THREADS, 32)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
RESTORE_BACKOFF = (1.0, 4.0, 10.0) # seconds before each per-file retry round
|
| 144 |
+
PART_SUFFIX = ".flock-part"
|
| 145 |
+
PUSH_EXCLUDE = ["*" + PART_SUFFIX] # sync_bucket patterns, matched on relative paths
|
| 146 |
+
# Regenerable caches left out of the workdir mirror and of restore (module docstring). A trailing
|
| 147 |
+
# "/" names a directory at any depth (`workdir_excludes`); other entries are plain globs.
|
| 148 |
+
# Not build/, dist/ or target/: sometimes source.
|
| 149 |
+
DEFAULT_WORKDIR_EXCLUDE = ["__pycache__/", "*.pyc", ".pytest_cache/", ".mypy_cache/",
|
| 150 |
+
".ruff_cache/", ".hypothesis/", "*.egg-info/", ".cache/",
|
| 151 |
+
"node_modules/", ".venv/", "venv/", ".tox/", ".nox/",
|
| 152 |
+
".ipynb_checkpoints/", ".gradle/", ".next/", "*.o"]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _expand(pattern: str) -> list[str]:
|
| 156 |
+
"""`name/` -> `name/*` and `*/name/*` (the directory at the root and below any directory);
|
| 157 |
+
anything else is returned as is. `sync_bucket` globs are fnmatch on the whole relative path,
|
| 158 |
+
where `*` also crosses `/`."""
|
| 159 |
+
if pattern.endswith("/"):
|
| 160 |
+
d = pattern.rstrip("/")
|
| 161 |
+
return [f"{d}/*", f"*/{d}/*"]
|
| 162 |
+
return [pattern]
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def workdir_excludes() -> list[str]:
|
| 166 |
+
"""Globs for the workdir mirror, relative to the workdir, always including `*.flock-part`:
|
| 167 |
+
the defaults (unless env FLOCK_SYNC_EXCLUDE_DEFAULTS=0) plus the spec's `sync_exclude`, else
|
| 168 |
+
the comma-separated FLOCK_SYNC_EXCLUDE. `.git/` is never in the defaults."""
|
| 169 |
+
pats = list(PUSH_EXCLUDE)
|
| 170 |
+
if os.environ.get("FLOCK_SYNC_EXCLUDE_DEFAULTS", "1").strip() != "0":
|
| 171 |
+
pats += [x for d in DEFAULT_WORKDIR_EXCLUDE for x in _expand(d)]
|
| 172 |
+
extra = SPEC_KNOBS.get("sync_exclude")
|
| 173 |
+
if extra is None:
|
| 174 |
+
extra = os.environ.get("FLOCK_SYNC_EXCLUDE", "").split(",")
|
| 175 |
+
for item in extra:
|
| 176 |
+
if item.strip():
|
| 177 |
+
pats += _expand(item.strip())
|
| 178 |
+
return pats
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@functools.lru_cache(maxsize=64)
|
| 182 |
+
def _matcher(patterns: tuple[str, ...]):
|
| 183 |
+
"""One compiled regex for a pattern list (a walk tests every file of a workdir)."""
|
| 184 |
+
if not patterns:
|
| 185 |
+
return lambda rel: None
|
| 186 |
+
return re.compile("|".join(fnmatch.translate(p.replace("\\", "/")) for p in patterns)).match
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def is_excluded(rel: str, patterns: list[str]) -> bool:
|
| 190 |
+
"""Does the workdir-relative posix path match one of the patterns (as `sync_bucket` does)?"""
|
| 191 |
+
return _matcher(tuple(patterns))(rel) is not None
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@dataclass
|
| 195 |
+
class WorkdirStats:
|
| 196 |
+
"""What a push mirrors: regular files and their bytes, excluded paths left out, and the
|
| 197 |
+
top-level directories with the most files ((name, files), largest first, up to 5)."""
|
| 198 |
+
|
| 199 |
+
files: int = 0
|
| 200 |
+
bytes: int = 0
|
| 201 |
+
top_dirs: list[tuple[str, int]] = field(default_factory=list)
|
| 202 |
+
|
| 203 |
+
def summary(self) -> str:
|
| 204 |
+
"""'182k files, 3100 MB; largest: snaps/ 140k, src/ 2k' (`{workspace}` in loop prompts)."""
|
| 205 |
+
top = ", ".join(f"{d}/ {_k(n)}" for d, n in self.top_dirs[:3])
|
| 206 |
+
return (f"{_k(self.files)} files, {self.bytes / 2**20:.0f} MB"
|
| 207 |
+
+ (f"; largest: {top}" if top else ""))
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _k(n: int) -> str:
|
| 211 |
+
return f"{n / 1000:.0f}k" if n >= 1000 else str(n)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
QUOTA_NOTE_EVERY = 3600.0 # s, per agent: the over-soft-limit note and workdir_over_quota
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def quota_note(ws: WorkdirStats, w: WorkdirSpec) -> str | None:
|
| 218 |
+
"""The note for an agent whose workdir is above its soft limit, else None."""
|
| 219 |
+
if ws.files <= w.soft_files and ws.bytes / 2**20 <= w.soft_mb:
|
| 220 |
+
return None
|
| 221 |
+
where = f", or keep throwaway clones in {w.ephemeral[0]}" if w.ephemeral else ""
|
| 222 |
+
return (f"your workspace has {ws.summary()} (soft limit {_k(w.soft_files)} files, "
|
| 223 |
+
f"{w.soft_mb:.0f} MB); delete clones you no longer need{where}")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def over_hard_limit(ws: WorkdirStats, w: WorkdirSpec) -> bool:
|
| 227 |
+
return (ws.files > (w.max_files or 5 * w.soft_files)
|
| 228 |
+
or ws.bytes / 2**20 > (w.max_mb or 5 * w.soft_mb))
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def ephemeral_excludes(spec: TypeSpec) -> list[str]:
|
| 232 |
+
"""The type's `workdir.ephemeral` dirs as root-anchored globs (never synced nor restored)."""
|
| 233 |
+
return [d + "*" for d in (spec.workdir.ephemeral if spec.workdir else [])]
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def reset_ephemeral(workdir: Path, spec: TypeSpec) -> None:
|
| 237 |
+
"""Empty (or create) the type's ephemeral dirs: run at every agent setup, so a move or a
|
| 238 |
+
restart never brings back their content. Blocking."""
|
| 239 |
+
root = workdir.resolve()
|
| 240 |
+
for d in spec.workdir.ephemeral if spec.workdir else []:
|
| 241 |
+
p = workdir / d
|
| 242 |
+
try:
|
| 243 |
+
if not p.parent.resolve().is_relative_to(root): # a symlinked parent: leave it
|
| 244 |
+
log.warning("ephemeral dir %s is outside %s; not touched", p, root)
|
| 245 |
+
continue
|
| 246 |
+
if p.is_symlink() or p.is_file():
|
| 247 |
+
p.unlink()
|
| 248 |
+
elif p.is_dir():
|
| 249 |
+
shutil.rmtree(p, ignore_errors=True)
|
| 250 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
except OSError as e:
|
| 252 |
+
log.warning("ephemeral dir %s: %s", p, e)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _walk(workdir: Path, exclude: list[str] | None = None):
|
| 256 |
+
"""(relative posix path, lstat) of every regular file and symlink under `workdir`, sorted per
|
| 257 |
+
directory; excluded directories are not entered, symlinked directories are not followed."""
|
| 258 |
+
excl = _matcher(tuple(exclude or ()))
|
| 259 |
+
for root, dirs, files in os.walk(workdir):
|
| 260 |
+
base = Path(root).relative_to(workdir).as_posix()
|
| 261 |
+
base = "" if base == "." else base + "/"
|
| 262 |
+
links = [d for d in dirs if os.path.islink(os.path.join(root, d))]
|
| 263 |
+
dirs[:] = sorted(d for d in dirs if d not in links and excl(f"{base}{d}/") is None)
|
| 264 |
+
for f in sorted(files + links):
|
| 265 |
+
rel = base + f
|
| 266 |
+
if excl(rel) is not None:
|
| 267 |
+
continue
|
| 268 |
+
try:
|
| 269 |
+
st = os.lstat(os.path.join(root, f))
|
| 270 |
+
except OSError:
|
| 271 |
+
continue
|
| 272 |
+
if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
|
| 273 |
+
yield rel, st
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def collect_modes(workdir: Path, stats: WorkdirStats | None = None,
|
| 277 |
+
exclude: list[str] | None = None) -> dict[str, str]:
|
| 278 |
+
"""{relative posix path: "0o755"} for regular files with any executable bit (symlinks and
|
| 279 |
+
the manifest itself excluded). `exclude`: paths left out of the walk (excluded directories
|
| 280 |
+
are not entered). `stats` gets the walk's counts (`WorkdirStats`)."""
|
| 281 |
+
out: dict[str, str] = {}
|
| 282 |
+
per_dir: Counter[str] = Counter()
|
| 283 |
+
for rel, st in _walk(workdir, exclude):
|
| 284 |
+
if not stat.S_ISREG(st.st_mode):
|
| 285 |
+
continue
|
| 286 |
+
if stats is not None:
|
| 287 |
+
stats.files += 1
|
| 288 |
+
stats.bytes += st.st_size
|
| 289 |
+
if "/" in rel:
|
| 290 |
+
per_dir[rel.split("/", 1)[0]] += 1
|
| 291 |
+
if st.st_mode & 0o111 and rel != MODES_FILE:
|
| 292 |
+
out[rel] = oct(stat.S_IMODE(st.st_mode))
|
| 293 |
+
if stats is not None:
|
| 294 |
+
stats.top_dirs = per_dir.most_common(5)
|
| 295 |
+
return dict(sorted(out.items()))
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _write_synced(path: Path, text: str) -> None: # fsync before a later os.replace
|
| 299 |
+
with path.open("w") as f:
|
| 300 |
+
f.write(text)
|
| 301 |
+
f.flush()
|
| 302 |
+
os.fsync(f.fileno())
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def write_modes(workdir: Path, stats: WorkdirStats | None = None,
|
| 306 |
+
exclude: list[str] | None = None) -> bool:
|
| 307 |
+
"""(Re)write the manifest if its content changed, remove it when nothing is executable.
|
| 308 |
+
Returns whether the file changed."""
|
| 309 |
+
path = workdir / MODES_FILE
|
| 310 |
+
modes = collect_modes(workdir, stats, exclude)
|
| 311 |
+
old = path.read_text() if path.is_file() else None
|
| 312 |
+
if not modes:
|
| 313 |
+
if old is not None:
|
| 314 |
+
path.unlink()
|
| 315 |
+
return True
|
| 316 |
+
return False
|
| 317 |
+
new = json.dumps(modes, indent=0, sort_keys=True) + "\n"
|
| 318 |
+
if new == old:
|
| 319 |
+
return False
|
| 320 |
+
path.write_text(new)
|
| 321 |
+
return True
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def apply_modes(workdir: Path) -> int:
|
| 325 |
+
"""chmod the files listed in the manifest (inside the workdir, regular files only)."""
|
| 326 |
+
path = workdir / MODES_FILE
|
| 327 |
+
try:
|
| 328 |
+
modes = json.loads(path.read_text())
|
| 329 |
+
except (OSError, ValueError):
|
| 330 |
+
return 0
|
| 331 |
+
n = 0
|
| 332 |
+
root = workdir.resolve()
|
| 333 |
+
for rel, mode in (modes.items() if isinstance(modes, dict) else []):
|
| 334 |
+
p = workdir / rel
|
| 335 |
+
try:
|
| 336 |
+
if ".." in Path(rel).parts or not p.resolve().is_relative_to(root) or p.is_symlink() \
|
| 337 |
+
or not p.is_file():
|
| 338 |
+
continue
|
| 339 |
+
os.chmod(p, int(mode, 8) & 0o7777)
|
| 340 |
+
n += 1
|
| 341 |
+
except (OSError, ValueError, TypeError):
|
| 342 |
+
continue
|
| 343 |
+
return n
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class _Padded:
|
| 347 |
+
"""A file that may shrink while it is read: short reads are padded with zeros, so the tar
|
| 348 |
+
stays well formed; the file's new mtime makes the next push send it as a delta."""
|
| 349 |
+
|
| 350 |
+
def __init__(self, f) -> None:
|
| 351 |
+
self.f = f
|
| 352 |
+
|
| 353 |
+
def read(self, n: int = -1) -> bytes:
|
| 354 |
+
b = self.f.read(n)
|
| 355 |
+
return b + bytes(max(0, n - len(b)))
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
TAR_PER_FILE = 2048 # bytes of tar overhead per member, at most (pax header + padding)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _fits(needs: list[tuple[Path, int]]) -> bool:
|
| 362 |
+
"""Do these byte counts fit in the free space of their file systems (summed per device)?"""
|
| 363 |
+
per: dict[int, list] = {}
|
| 364 |
+
for p, n in needs:
|
| 365 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 366 |
+
per.setdefault(os.stat(p).st_dev, [p, 0])[1] += n
|
| 367 |
+
return all(shutil.disk_usage(p).free >= n for p, n in per.values())
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def write_base_tar(workdir: Path, exclude: list[str], dest: Path,
|
| 371 |
+
stop=lambda: False) -> dict[str, list] | None:
|
| 372 |
+
"""Write an uncompressed tar of the workdir (regular files and symlinks, sorted, with modes
|
| 373 |
+
and mtimes) to `dest`; returns the index {relative path: [mtime, size]} of what it holds
|
| 374 |
+
(lstat before each read), or None when `stop()` turned true between two members."""
|
| 375 |
+
index: dict[str, list] = {}
|
| 376 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 377 |
+
with tarfile.open(dest, "w", format=tarfile.PAX_FORMAT) as tf:
|
| 378 |
+
for rel, st in _walk(workdir, exclude):
|
| 379 |
+
if stop():
|
| 380 |
+
return None
|
| 381 |
+
ti = tarfile.TarInfo(rel)
|
| 382 |
+
ti.mode, ti.mtime = stat.S_IMODE(st.st_mode), int(st.st_mtime)
|
| 383 |
+
ti.pax_headers = {"mtime": f"{st.st_mtime_ns / 1e9:.9f}"} # sub-second mtimes
|
| 384 |
+
p = workdir / rel
|
| 385 |
+
try:
|
| 386 |
+
if stat.S_ISLNK(st.st_mode):
|
| 387 |
+
ti.type, ti.linkname = tarfile.SYMTYPE, os.readlink(p)
|
| 388 |
+
tf.addfile(ti)
|
| 389 |
+
else:
|
| 390 |
+
with open(p, "rb") as f:
|
| 391 |
+
ti.size = st.st_size
|
| 392 |
+
tf.addfile(ti, _Padded(f))
|
| 393 |
+
except OSError: # gone since the walk (open or readlink, before anything is written)
|
| 394 |
+
continue
|
| 395 |
+
index[rel] = [st.st_mtime, st.st_size]
|
| 396 |
+
return index
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def extract_base_tar(src: Path, workdir: Path, exclude: list[str],
|
| 400 |
+
base: dict) -> tuple[dict[str, list], int]:
|
| 401 |
+
"""Extract a base tar into the workdir member by member (regular files and symlinks with
|
| 402 |
+
their modes and mtimes; nothing outside the workdir, nothing excluded), then apply the
|
| 403 |
+
manifest's tombstones (`deleted`) and symlinks (`links`). Returns (the index of the
|
| 404 |
+
extracted files {relative path: [mtime, size]}, members that failed)."""
|
| 405 |
+
workdir.mkdir(parents=True, exist_ok=True)
|
| 406 |
+
root = workdir.resolve()
|
| 407 |
+
index: dict[str, list] = {}
|
| 408 |
+
bad = 0
|
| 409 |
+
|
| 410 |
+
safe: set[str] = set() # parent dirs checked (and made): one realpath per directory
|
| 411 |
+
|
| 412 |
+
def target(rel: str, make: bool = True) -> str | None:
|
| 413 |
+
"""The local path for `rel`, cleared, or None when it must not be written."""
|
| 414 |
+
if rel.startswith("/") or ".." in rel.split("/") or is_excluded(rel, exclude):
|
| 415 |
+
return None
|
| 416 |
+
p = os.path.join(workdir, rel)
|
| 417 |
+
parent = os.path.dirname(p)
|
| 418 |
+
if parent not in safe:
|
| 419 |
+
if not Path(parent).resolve().is_relative_to(root):
|
| 420 |
+
return None
|
| 421 |
+
if make:
|
| 422 |
+
os.makedirs(parent, exist_ok=True)
|
| 423 |
+
safe.add(parent)
|
| 424 |
+
try:
|
| 425 |
+
if stat.S_ISDIR(os.lstat(p).st_mode):
|
| 426 |
+
return None # a directory in the way
|
| 427 |
+
os.unlink(p) # also read-only files (git objects) and links
|
| 428 |
+
except FileNotFoundError:
|
| 429 |
+
pass
|
| 430 |
+
return p
|
| 431 |
+
|
| 432 |
+
with tarfile.open(src, "r:") as tf:
|
| 433 |
+
while (m := tf.next()) is not None:
|
| 434 |
+
tf.members.clear() # a 500k-file tar keeps no member list in memory
|
| 435 |
+
try:
|
| 436 |
+
if not (m.isreg() or m.issym()) or (p := target(m.name)) is None:
|
| 437 |
+
continue
|
| 438 |
+
if m.issym():
|
| 439 |
+
os.symlink(m.linkname, p)
|
| 440 |
+
else:
|
| 441 |
+
with tf.extractfile(m) as f, open(p, "wb") as out:
|
| 442 |
+
shutil.copyfileobj(f, out)
|
| 443 |
+
os.chmod(p, m.mode & 0o777)
|
| 444 |
+
os.utime(p, (m.mtime, m.mtime), follow_symlinks=False)
|
| 445 |
+
index[m.name] = [m.mtime, len(os.fsencode(m.linkname)) if m.issym() else m.size]
|
| 446 |
+
except OSError as e:
|
| 447 |
+
bad += 1
|
| 448 |
+
log.debug("base member %s: %s", m.name, e)
|
| 449 |
+
for rel in base.get("deleted", []):
|
| 450 |
+
try:
|
| 451 |
+
target(rel, make=False)
|
| 452 |
+
except OSError:
|
| 453 |
+
bad += 1
|
| 454 |
+
for rel, link in base.get("links", {}).items():
|
| 455 |
+
try:
|
| 456 |
+
if (p := target(rel)) is not None:
|
| 457 |
+
os.symlink(link, p)
|
| 458 |
+
except OSError:
|
| 459 |
+
bad += 1
|
| 460 |
+
return index, bad
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _same(a: list | None, mtime: float, size: int) -> bool:
|
| 464 |
+
return a is not None and abs(a[0] - mtime) <= 2e-3 and a[1] == size
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def workdir_delta(workdir: Path, exclude: list[str], index: dict[str, list],
|
| 468 |
+
created_at: float) -> tuple[dict[str, float], dict[str, str], list[str]]:
|
| 469 |
+
"""Against the base's index: (regular files new or changed {rel: mtime}, symlinks new or
|
| 470 |
+
changed {rel: target}, base paths gone). A changed file whose mtime is not after the base
|
| 471 |
+
(`cp -p`, `tar x`) gets its mtime set to now, since restore only takes deltas newer than the
|
| 472 |
+
base."""
|
| 473 |
+
files: dict[str, float] = {}
|
| 474 |
+
links: dict[str, str] = {}
|
| 475 |
+
seen: set[str] = set()
|
| 476 |
+
now = max(time.time(), created_at + 1.0)
|
| 477 |
+
for rel, st in _walk(workdir, exclude):
|
| 478 |
+
seen.add(rel)
|
| 479 |
+
if _same(index.get(rel), st.st_mtime, st.st_size):
|
| 480 |
+
continue
|
| 481 |
+
p = workdir / rel
|
| 482 |
+
try:
|
| 483 |
+
if stat.S_ISLNK(st.st_mode):
|
| 484 |
+
links[rel] = os.readlink(p)
|
| 485 |
+
continue
|
| 486 |
+
mt = st.st_mtime
|
| 487 |
+
if mt <= created_at + 2e-3: # the Hub keeps milliseconds
|
| 488 |
+
os.utime(p, (now, now))
|
| 489 |
+
mt = now
|
| 490 |
+
except OSError:
|
| 491 |
+
continue
|
| 492 |
+
files[rel] = mt
|
| 493 |
+
return files, links, sorted(set(index) - seen)
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def _load_index(path: Path) -> dict[str, list]:
|
| 497 |
+
try:
|
| 498 |
+
return json.loads(path.read_text())
|
| 499 |
+
except (OSError, ValueError):
|
| 500 |
+
return {}
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@dataclass
|
| 504 |
+
class BucketStats:
|
| 505 |
+
"""Bucket traffic counters for the worker log: store operations (`ops`), the Hub HTTP
|
| 506 |
+
requests behind them (`http`, by method and route; xet CAS transfers run in hf_xet and are
|
| 507 |
+
not seen here) and HTTP error statuses (`errors`, e.g. 429). Thread-safe."""
|
| 508 |
+
|
| 509 |
+
ops: Counter = field(default_factory=Counter)
|
| 510 |
+
http: Counter = field(default_factory=Counter)
|
| 511 |
+
errors: Counter = field(default_factory=Counter)
|
| 512 |
+
_lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
|
| 513 |
+
|
| 514 |
+
def add(self, kind: str, key: str, n: int = 1) -> None:
|
| 515 |
+
with self._lock:
|
| 516 |
+
getattr(self, kind)[key] += n
|
| 517 |
+
|
| 518 |
+
def snapshot(self) -> dict[str, Counter]:
|
| 519 |
+
with self._lock:
|
| 520 |
+
return {"ops": Counter(self.ops), "http": Counter(self.http),
|
| 521 |
+
"errors": Counter(self.errors)}
|
| 522 |
+
|
| 523 |
+
def since(self, before: dict[str, Counter]) -> dict[str, dict[str, int]]:
|
| 524 |
+
now = self.snapshot()
|
| 525 |
+
return {k: dict(now[k] - before[k]) for k in now}
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
_BUCKET_ROUTE = re.compile(r"^/api/buckets/[^/]+/[^/]+(?:/([^/]+))?")
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def http_route(method: str, host: str, path: str) -> str:
|
| 532 |
+
"""'GET /api/buckets/ns/b/tree/x/y' -> 'GET buckets/tree'; other hosts by first segment."""
|
| 533 |
+
m = _BUCKET_ROUTE.match(path)
|
| 534 |
+
if m:
|
| 535 |
+
return f"{method} buckets/{m.group(1) or ''}".rstrip("/")
|
| 536 |
+
first = path.strip("/").split("/", 1)[0]
|
| 537 |
+
if host.endswith("huggingface.co"):
|
| 538 |
+
return f"{method} {first or '/'}"
|
| 539 |
+
return f"{method} {host}/{first}"
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def count_hub_http(stats: BucketStats) -> None:
|
| 543 |
+
"""Count every request huggingface_hub's shared client makes (one install per process)."""
|
| 544 |
+
import huggingface_hub
|
| 545 |
+
from huggingface_hub.utils._http import default_client_factory
|
| 546 |
+
|
| 547 |
+
def on_request(request) -> None:
|
| 548 |
+
stats.add("http", http_route(request.method, request.url.host, request.url.path))
|
| 549 |
+
|
| 550 |
+
def on_response(response) -> None:
|
| 551 |
+
if response.status_code >= 400:
|
| 552 |
+
req = response.request
|
| 553 |
+
route = http_route(req.method, req.url.host, req.url.path)
|
| 554 |
+
stats.add("errors", f"{response.status_code} {route}")
|
| 555 |
+
|
| 556 |
+
def factory():
|
| 557 |
+
client = default_client_factory()
|
| 558 |
+
client.event_hooks["request"].append(on_request)
|
| 559 |
+
client.event_hooks.setdefault("response", []).append(on_response)
|
| 560 |
+
return client
|
| 561 |
+
|
| 562 |
+
huggingface_hub.set_client_factory(factory)
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
class BucketStore(Protocol):
|
| 566 |
+
"""Blocking bucket operations on paths relative to the flock root."""
|
| 567 |
+
|
| 568 |
+
def upload(self, files: list[tuple[Path, str]]) -> None: ...
|
| 569 |
+
def list(self, prefix: str) -> list[str]: ...
|
| 570 |
+
def first(self, prefix: str) -> str | None: ... # one file under prefix (the launch guard)
|
| 571 |
+
# optional: `list_info(prefix) -> list[tuple[str, float | None]]`, paths with their mtime
|
| 572 |
+
# (POSIX seconds) when the store keeps one; restore uses it to set local mtimes
|
| 573 |
+
def download(self, files: list[tuple[str, Path]]) -> None: ...
|
| 574 |
+
def sync_up(self, local: Path, prefix: str, *, delete: bool = True,
|
| 575 |
+
exclude: list[str] | None = None) -> None:
|
| 576 |
+
"""Upload new/changed files of a local directory to `prefix`; with `delete`, also
|
| 577 |
+
delete remote files missing locally. `exclude`: fnmatch patterns on relative paths,
|
| 578 |
+
neither uploaded nor deleted."""
|
| 579 |
+
...
|
| 580 |
+
|
| 581 |
+
def sync_down(self, prefix: str, local: Path) -> None: ...
|
| 582 |
+
def delete(self, paths: list[str]) -> None:
|
| 583 |
+
"""Delete files (paths relative to the flock root). Used by the controller's state."""
|
| 584 |
+
...
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def parse_bucket(url: str) -> tuple[str, str]:
|
| 588 |
+
"""'hf://buckets/ns/name/some/prefix' -> ('ns/name', 'some/prefix/')."""
|
| 589 |
+
rest = url.removeprefix("hf://").removeprefix("buckets/").strip("/")
|
| 590 |
+
parts = rest.split("/")
|
| 591 |
+
if len(parts) < 2:
|
| 592 |
+
raise ValueError(f"bad bucket url {url!r}; expected hf://buckets/<namespace>/<name>[/prefix]")
|
| 593 |
+
prefix = "/".join(parts[2:])
|
| 594 |
+
return f"{parts[0]}/{parts[1]}", (prefix + "/" if prefix else "")
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
class HubBucketStore:
|
| 598 |
+
"""huggingface_hub bucket API (batch_bucket_files / list_bucket_tree / download_bucket_files)."""
|
| 599 |
+
|
| 600 |
+
def __init__(self, url: str, token: str | None = None, stats: BucketStats | None = None) -> None:
|
| 601 |
+
from huggingface_hub import HfApi
|
| 602 |
+
|
| 603 |
+
self.bucket_id, self.base = parse_bucket(url)
|
| 604 |
+
self.api = HfApi(token=token)
|
| 605 |
+
self.stats = stats or BucketStats()
|
| 606 |
+
|
| 607 |
+
def upload(self, files: list[tuple[Path, str]]) -> None:
|
| 608 |
+
for i in range(0, len(files), UPLOAD_CHUNK):
|
| 609 |
+
self.stats.add("ops", "batch_bucket_files")
|
| 610 |
+
chunk = files[i : i + UPLOAD_CHUNK]
|
| 611 |
+
self.api.batch_bucket_files(self.bucket_id, add=[(str(p), self.base + r) for p, r in chunk])
|
| 612 |
+
|
| 613 |
+
def list(self, prefix: str) -> list[str]:
|
| 614 |
+
return [r for r, _ in self.list_info(prefix)]
|
| 615 |
+
|
| 616 |
+
def first(self, prefix: str) -> str | None:
|
| 617 |
+
"""One file under `prefix` (None: empty), without listing the rest."""
|
| 618 |
+
from huggingface_hub import BucketFile
|
| 619 |
+
|
| 620 |
+
self.stats.add("ops", "list_bucket_tree")
|
| 621 |
+
full = self.base + prefix
|
| 622 |
+
for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True):
|
| 623 |
+
if isinstance(f, BucketFile) and f.path.startswith(full):
|
| 624 |
+
return f.path[len(self.base):]
|
| 625 |
+
return None
|
| 626 |
+
|
| 627 |
+
def list_info(self, prefix: str) -> list[tuple[str, float | None]]:
|
| 628 |
+
from huggingface_hub import BucketFile
|
| 629 |
+
|
| 630 |
+
self.stats.add("ops", "list_bucket_tree")
|
| 631 |
+
full = self.base + prefix
|
| 632 |
+
out: list[tuple[str, float | None]] = []
|
| 633 |
+
for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True):
|
| 634 |
+
if isinstance(f, BucketFile) and f.path.startswith(full):
|
| 635 |
+
mt = f.mtime.timestamp() if isinstance(f.mtime, datetime) else None
|
| 636 |
+
out.append((f.path[len(self.base):], mt))
|
| 637 |
+
return out
|
| 638 |
+
|
| 639 |
+
def download(self, files: list[tuple[str, Path]]) -> None:
|
| 640 |
+
self.stats.add("ops", "download_bucket_files")
|
| 641 |
+
for _, local in files:
|
| 642 |
+
local.parent.mkdir(parents=True, exist_ok=True)
|
| 643 |
+
self.api.download_bucket_files(self.bucket_id, [(self.base + r, str(p)) for r, p in files])
|
| 644 |
+
|
| 645 |
+
def delete(self, paths: list[str]) -> None:
|
| 646 |
+
for i in range(0, len(paths), UPLOAD_CHUNK):
|
| 647 |
+
self.stats.add("ops", "batch_bucket_files")
|
| 648 |
+
chunk = paths[i : i + UPLOAD_CHUNK]
|
| 649 |
+
self.api.batch_bucket_files(self.bucket_id, delete=[self.base + r for r in chunk])
|
| 650 |
+
|
| 651 |
+
def _url(self, prefix: str) -> str:
|
| 652 |
+
return f"hf://buckets/{self.bucket_id}/{self.base}{prefix}".rstrip("/")
|
| 653 |
+
|
| 654 |
+
def sync_up(self, local: Path, prefix: str, *, delete: bool = True,
|
| 655 |
+
exclude: list[str] | None = None) -> None:
|
| 656 |
+
self.stats.add("ops", "sync_bucket_up")
|
| 657 |
+
self.api.sync_bucket(str(local), self._url(prefix), delete=delete, exclude=exclude or None,
|
| 658 |
+
quiet=True)
|
| 659 |
+
|
| 660 |
+
def sync_down(self, prefix: str, local: Path) -> None:
|
| 661 |
+
self.stats.add("ops", "sync_bucket_down")
|
| 662 |
+
local.mkdir(parents=True, exist_ok=True)
|
| 663 |
+
self.api.sync_bucket(self._url(prefix), str(local), quiet=True)
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
@dataclass
|
| 667 |
+
class RestoreResult:
|
| 668 |
+
workdir: int = 0
|
| 669 |
+
sessions: int = 0
|
| 670 |
+
harness: int = 0
|
| 671 |
+
# bucket paths (relative to the flock root) that could not be downloaded, after retries
|
| 672 |
+
failed: list[str] = field(default_factory=list)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
_NOT_FOUND = re.compile(r"\b404\b|not found", re.IGNORECASE)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _permanent(e: BaseException) -> bool:
|
| 679 |
+
"""A download error that retrying cannot fix: the entry's data is gone (HTTP 404)."""
|
| 680 |
+
resp = getattr(e, "response", None)
|
| 681 |
+
if getattr(resp, "status_code", None) == 404:
|
| 682 |
+
return True
|
| 683 |
+
return bool(_NOT_FOUND.search(str(e)))
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _part(p: Path) -> Path:
|
| 687 |
+
return p.with_name(p.name + PART_SUFFIX)
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def download_resilient(store: BucketStore, files: list[tuple[str, Path]], *,
|
| 691 |
+
backoff: tuple[float, ...] | None = None, sleep=None,
|
| 692 |
+
progress=None) -> tuple[list[tuple[str, Path]], list[str]]:
|
| 693 |
+
"""Download (remote, local) pairs; returns (downloaded, failed remote paths). Never raises
|
| 694 |
+
for a file: batches first, then the files of a failed batch one by one, retried after each
|
| 695 |
+
delay in `backoff` unless the error is a permanent "not found" (`_permanent`). Each file lands in a `.flock-part` sibling, renamed into place only
|
| 696 |
+
when it arrived, so a failed file never leaves a truncated copy at its real path.
|
| 697 |
+
`progress(n)` is called with the number of files each attempt brought in (serialized: the
|
| 698 |
+
first pass runs `restore_threads()` batches in parallel threads)."""
|
| 699 |
+
|
| 700 |
+
gone: list[str] = [] # permanent "not found": skipped, never retried
|
| 701 |
+
lock = threading.Lock() # first-pass batches run in threads
|
| 702 |
+
|
| 703 |
+
def attempt(batch: list[tuple[str, Path]]) -> tuple[list[tuple[str, Path]], list[tuple[str, Path]]]:
|
| 704 |
+
ok, bad = [], []
|
| 705 |
+
try:
|
| 706 |
+
store.download([(r, _part(p)) for r, p in batch])
|
| 707 |
+
except Exception as e: # noqa: BLE001 - sorted out per file below
|
| 708 |
+
err = e
|
| 709 |
+
else:
|
| 710 |
+
err = None
|
| 711 |
+
for r, p in batch:
|
| 712 |
+
part = _part(p)
|
| 713 |
+
if err is None and part.is_file():
|
| 714 |
+
try:
|
| 715 |
+
os.replace(part, p)
|
| 716 |
+
ok.append((r, p))
|
| 717 |
+
continue
|
| 718 |
+
except OSError:
|
| 719 |
+
pass
|
| 720 |
+
part.unlink(missing_ok=True)
|
| 721 |
+
bad.append((r, p))
|
| 722 |
+
if ok and progress is not None:
|
| 723 |
+
with lock:
|
| 724 |
+
progress(len(ok))
|
| 725 |
+
if err is not None and len(batch) == 1:
|
| 726 |
+
log.debug("download of %s failed: %s", batch[0][0], _short(err))
|
| 727 |
+
if bad and _permanent(err):
|
| 728 |
+
gone.append(bad[0][0])
|
| 729 |
+
return ok, []
|
| 730 |
+
return ok, bad
|
| 731 |
+
|
| 732 |
+
backoff = RESTORE_BACKOFF if backoff is None else backoff
|
| 733 |
+
sleep = sleep or time.sleep
|
| 734 |
+
done: list[tuple[str, Path]] = []
|
| 735 |
+
pending: list[tuple[str, Path]] = []
|
| 736 |
+
size = restore_batch()
|
| 737 |
+
batches = [files[i : i + size] for i in range(0, len(files), size)]
|
| 738 |
+
# the first pass runs `restore_threads()` batches at once (per-request latency, not
|
| 739 |
+
# bandwidth, bounds a restore); the per-file retry rounds below stay sequential
|
| 740 |
+
with ThreadPoolExecutor(max(1, min(restore_threads(), len(batches)))) as pool:
|
| 741 |
+
for ok, bad in pool.map(attempt, batches):
|
| 742 |
+
done += ok
|
| 743 |
+
pending += bad
|
| 744 |
+
if pending: # each file alone, so one bad file costs only itself
|
| 745 |
+
retry, pending = pending, []
|
| 746 |
+
for f in retry:
|
| 747 |
+
ok, bad = attempt([f])
|
| 748 |
+
done += ok
|
| 749 |
+
pending += bad
|
| 750 |
+
for delay in backoff:
|
| 751 |
+
if not pending:
|
| 752 |
+
break
|
| 753 |
+
sleep(delay)
|
| 754 |
+
retry, pending = pending, []
|
| 755 |
+
for f in retry:
|
| 756 |
+
ok, bad = attempt([f])
|
| 757 |
+
done += ok
|
| 758 |
+
pending += bad
|
| 759 |
+
# the caller logs the skipped files (one summary line per agent, `BucketSync._restore_files`)
|
| 760 |
+
return done, gone + [r for r, _ in pending]
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def _clean_parts(root: Path) -> int:
|
| 764 |
+
"""Remove stray `.flock-part` files under `root` (a crash mid-download leaves them)."""
|
| 765 |
+
n = 0
|
| 766 |
+
if root.is_dir():
|
| 767 |
+
for p in root.rglob("*" + PART_SUFFIX):
|
| 768 |
+
try:
|
| 769 |
+
if p.is_file() and not p.is_symlink():
|
| 770 |
+
p.unlink()
|
| 771 |
+
n += 1
|
| 772 |
+
except OSError:
|
| 773 |
+
pass
|
| 774 |
+
return n
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def _short(e: BaseException) -> str:
|
| 778 |
+
return f"{type(e).__name__}: {str(e)[:300]}"
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
class BucketSync:
|
| 782 |
+
def __init__(self, store: BucketStore, swarm: str) -> None:
|
| 783 |
+
self.store = store
|
| 784 |
+
self.swarm = swarm
|
| 785 |
+
self.stats: BucketStats = getattr(store, "stats", None) or BucketStats()
|
| 786 |
+
self._seen: dict[Path, tuple[int, int]] = {}
|
| 787 |
+
# per agent prefix: may the workdir push delete remote files? Absent: no restore was
|
| 788 |
+
# attempted (a new agent), deletes allowed. False from the start of a restore until it
|
| 789 |
+
# completes with every file; stays False after an incomplete one (module docstring).
|
| 790 |
+
self._mirror: dict[str, bool] = {}
|
| 791 |
+
self._restoring: set[str] = set() # agent prefixes with a restore in flight
|
| 792 |
+
self._meta: dict[str, dict] = {} # per agent prefix: the meta.json last pushed
|
| 793 |
+
self._quota_note: dict[str, str] = {} # per agent prefix: the quota note last queued
|
| 794 |
+
self._base: dict[str, dict] = {} # per agent prefix: its committed workdir.base.json
|
| 795 |
+
self._building: set[str] = set() # agent prefixes with a base tar being made
|
| 796 |
+
self.stop_rebase = False # set by drain/preempt: base builds stop, none start
|
| 797 |
+
self._quota_at: dict[str, float] = {} # per agent prefix: monotonic time of the last note
|
| 798 |
+
# per agent prefix with a restore in flight: [files done, files listed, started (UTC)]
|
| 799 |
+
self.restore_progress: dict[str, list] = {}
|
| 800 |
+
|
| 801 |
+
def mirror_deletes(self, rt: AgentRuntime) -> bool:
|
| 802 |
+
return self._mirror.get(self.prefix(rt), True)
|
| 803 |
+
|
| 804 |
+
def prefix(self, rt: AgentRuntime) -> str:
|
| 805 |
+
return f"{self.swarm}/{rt.type_name}/{rt.name}/"
|
| 806 |
+
|
| 807 |
+
def collect(self, rt: AgentRuntime) -> list[tuple[Path, str]]:
|
| 808 |
+
"""The agent's session-log, state and harness files, with their bucket paths."""
|
| 809 |
+
pre = self.prefix(rt)
|
| 810 |
+
out: list[tuple[Path, str]] = []
|
| 811 |
+
for p in (rt.log.path, rt.state_path):
|
| 812 |
+
if p.is_file():
|
| 813 |
+
out.append((p, f"{pre}sessions/{p.name}"))
|
| 814 |
+
home = Path(rt.adapter.home)
|
| 815 |
+
for p in rt.harness_files():
|
| 816 |
+
try:
|
| 817 |
+
rel = p.relative_to(home)
|
| 818 |
+
except ValueError:
|
| 819 |
+
log.warning("%s: harness file %s is outside %s; not synced", rt.name, p, home)
|
| 820 |
+
continue
|
| 821 |
+
out.append((p, f"{pre}harness/{rel.as_posix()}"))
|
| 822 |
+
return out
|
| 823 |
+
|
| 824 |
+
def _changed(self, files: list[tuple[Path, str]]) -> list[tuple[Path, str]]:
|
| 825 |
+
changed = []
|
| 826 |
+
for p, r in files:
|
| 827 |
+
try:
|
| 828 |
+
st = p.stat()
|
| 829 |
+
except OSError:
|
| 830 |
+
continue
|
| 831 |
+
sig = (st.st_mtime_ns, st.st_size)
|
| 832 |
+
if self._seen.get(p) != sig:
|
| 833 |
+
changed.append((p, r))
|
| 834 |
+
return changed
|
| 835 |
+
|
| 836 |
+
def _mark(self, files: list[tuple[Path, str]]) -> None:
|
| 837 |
+
for p, _ in files:
|
| 838 |
+
try:
|
| 839 |
+
st = p.stat()
|
| 840 |
+
self._seen[p] = (st.st_mtime_ns, st.st_size)
|
| 841 |
+
except OSError:
|
| 842 |
+
pass
|
| 843 |
+
|
| 844 |
+
async def push(self, rt: AgentRuntime, *, rebase: bool = False) -> int:
|
| 845 |
+
"""`rebase`: may make a new base tar when one is due (periodic pushes only, so drain
|
| 846 |
+
and preempt stay as cheap as a delta)."""
|
| 847 |
+
try:
|
| 848 |
+
return await self._push(rt, rebase)
|
| 849 |
+
except Exception:
|
| 850 |
+
self.stats.add("errors", "push_failed")
|
| 851 |
+
raise
|
| 852 |
+
|
| 853 |
+
async def _push(self, rt: AgentRuntime, rebase: bool = False) -> int:
|
| 854 |
+
pre = self.prefix(rt)
|
| 855 |
+
if pre in self._restoring: # never mirror a half-restored agent (module docstring)
|
| 856 |
+
log.warning("%s: push skipped, its restore is still running", rt.name)
|
| 857 |
+
return 0
|
| 858 |
+
meta: list[tuple[Path, str]] = []
|
| 859 |
+
if rt.spec.persist_workdir and rt.workdir.is_dir():
|
| 860 |
+
exclude = workdir_excludes() + ephemeral_excludes(rt.spec)
|
| 861 |
+
ws = WorkdirStats()
|
| 862 |
+
await asyncio.to_thread(write_modes, rt.workdir, ws, exclude)
|
| 863 |
+
rt.workdir_files, rt.workdir_stats = ws.files, ws
|
| 864 |
+
self._quota(rt, ws)
|
| 865 |
+
stats = {"files": ws.files, "bytes": ws.bytes}
|
| 866 |
+
if self._meta.get(pre) != stats: # the workdir's size: predicts a restore's time
|
| 867 |
+
path = rt.sessions_dir / f"{rt.name}.meta.json"
|
| 868 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 869 |
+
path.write_text(json.dumps({**stats, "ts": datetime.now(UTC).isoformat()}))
|
| 870 |
+
meta = [(path, pre + "meta.json")]
|
| 871 |
+
delete = self.mirror_deletes(rt)
|
| 872 |
+
if not delete:
|
| 873 |
+
log.info("%s: workdir push without remote deletes (last restore incomplete)",
|
| 874 |
+
rt.name)
|
| 875 |
+
w = rt.spec.workdir or WorkdirSpec()
|
| 876 |
+
if not (w.base and (pre in self._base or (rebase and delete))
|
| 877 |
+
and await self._push_base(rt, exclude, w, rebase and delete, ws)):
|
| 878 |
+
await asyncio.to_thread(self.store.sync_up, rt.workdir, pre + "workdir",
|
| 879 |
+
delete=delete, exclude=exclude)
|
| 880 |
+
if pre in self._base and delete: # base turned off: the full mirror replaces it
|
| 881 |
+
await asyncio.to_thread(self.store.delete, [pre + BASE_JSON, pre + BASE_TAR])
|
| 882 |
+
self._base.pop(pre)
|
| 883 |
+
files = self._changed(self.collect(rt)) + meta
|
| 884 |
+
if files:
|
| 885 |
+
await asyncio.to_thread(self.store.upload, files)
|
| 886 |
+
self._mark(files)
|
| 887 |
+
if meta:
|
| 888 |
+
self._meta[pre] = stats
|
| 889 |
+
return len(files)
|
| 890 |
+
|
| 891 |
+
def _index_path(self, rt: AgentRuntime) -> Path:
|
| 892 |
+
return rt.sessions_dir / f"{rt.name}.base-index.json"
|
| 893 |
+
|
| 894 |
+
async def _push_base(self, rt: AgentRuntime, exclude: list[str], w: WorkdirSpec,
|
| 895 |
+
may_rebase: bool, ws: WorkdirStats) -> bool:
|
| 896 |
+
"""Workdir push with a base tar (module docstring, "Base tar"): a new base when due,
|
| 897 |
+
then the files changed since the base, and tombstones and symlinks in the manifest.
|
| 898 |
+
False: no base yet and none made (stopped, no disk); the caller mirrors file by file."""
|
| 899 |
+
pre, dpre = self.prefix(rt), self.prefix(rt) + "workdir/"
|
| 900 |
+
base = self._base.get(pre)
|
| 901 |
+
|
| 902 |
+
def delta():
|
| 903 |
+
index = _load_index(self._index_path(rt))
|
| 904 |
+
return workdir_delta(rt.workdir, exclude, index, base["created_at"])
|
| 905 |
+
|
| 906 |
+
async def send() -> dict[str, float | None]:
|
| 907 |
+
remote = {r[len(dpre):]: mt for r, mt in
|
| 908 |
+
await asyncio.to_thread(self.store.list_info, dpre)}
|
| 909 |
+
up = [(rt.workdir / r, dpre + r) for r, mt in files.items()
|
| 910 |
+
if remote.get(r) is None or abs(remote[r] - mt) > 2e-3]
|
| 911 |
+
if up:
|
| 912 |
+
await asyncio.to_thread(self.store.upload, up)
|
| 913 |
+
return remote
|
| 914 |
+
|
| 915 |
+
if base is not None:
|
| 916 |
+
files, links, deleted = await asyncio.to_thread(delta)
|
| 917 |
+
if may_rebase and (base is None or time.time() - base["created_at"] >= w.base_interval_s
|
| 918 |
+
or len(files) + len(links) + len(deleted) > w.base_delta_files):
|
| 919 |
+
if not _fits([(rt.sessions_dir, ws.bytes + ws.files * TAR_PER_FILE)]):
|
| 920 |
+
log.warning("%s: no new workdir base, not enough free disk for a %s tar",
|
| 921 |
+
rt.name, ws.summary())
|
| 922 |
+
elif (new := await self._make_base(rt, exclude)) is not None:
|
| 923 |
+
base = new
|
| 924 |
+
files, links, deleted = await asyncio.to_thread(delta)
|
| 925 |
+
if base is None:
|
| 926 |
+
return False
|
| 927 |
+
remote = await send()
|
| 928 |
+
if not self.mirror_deletes(rt): # tombstones and remote deletes: full baseline only
|
| 929 |
+
return True
|
| 930 |
+
while pre in self._building: # another push is making a base: its manifest goes first
|
| 931 |
+
await asyncio.sleep(0.1)
|
| 932 |
+
if self._base.get(pre) is not base: # ... and was committed: diff against it
|
| 933 |
+
base = self._base[pre]
|
| 934 |
+
files, links, deleted = await asyncio.to_thread(delta)
|
| 935 |
+
remote = await send()
|
| 936 |
+
if base.get("deleted", []) != deleted or base.get("links", {}) != links:
|
| 937 |
+
await self._write_base(rt, {**base, "deleted": deleted, "links": links})
|
| 938 |
+
|
| 939 |
+
def stale(index: dict[str, list], r: str) -> bool:
|
| 940 |
+
"""Remote delta not needed: not changed in this walk and, locally, gone or as in the
|
| 941 |
+
base (a file a concurrent push uploaded after this walk differs from it: it stays)."""
|
| 942 |
+
if r in files or is_excluded(r, exclude):
|
| 943 |
+
return False
|
| 944 |
+
try:
|
| 945 |
+
st = os.lstat(rt.workdir / r)
|
| 946 |
+
except OSError:
|
| 947 |
+
return True
|
| 948 |
+
return _same(index.get(r), st.st_mtime, st.st_size)
|
| 949 |
+
|
| 950 |
+
def stale_all() -> list[str]:
|
| 951 |
+
index = _load_index(self._index_path(rt))
|
| 952 |
+
return [dpre + r for r in remote if stale(index, r)]
|
| 953 |
+
|
| 954 |
+
gone = await asyncio.to_thread(stale_all)
|
| 955 |
+
if gone: # deltas now in the base, or deleted
|
| 956 |
+
await asyncio.to_thread(self.store.delete, gone)
|
| 957 |
+
return True
|
| 958 |
+
|
| 959 |
+
async def _make_base(self, rt: AgentRuntime, exclude: list[str]) -> dict | None:
|
| 960 |
+
"""Tar the workdir, upload it, then commit `workdir.base.json` (the commit point); the
|
| 961 |
+
local index of the base replaces the old one only after the commit. None when
|
| 962 |
+
`stop_rebase` (drain, preempt) stopped it before the upload: nothing was written."""
|
| 963 |
+
pre = self.prefix(rt)
|
| 964 |
+
tar, idx = rt.sessions_dir / f"{rt.name}.base.tar", self._index_path(rt)
|
| 965 |
+
new_idx = idx.with_name(idx.name + ".new")
|
| 966 |
+
self._building.add(pre)
|
| 967 |
+
try:
|
| 968 |
+
t0 = time.time()
|
| 969 |
+
index = await asyncio.to_thread(write_base_tar, rt.workdir, exclude, tar,
|
| 970 |
+
lambda: self.stop_rebase)
|
| 971 |
+
if index is None or self.stop_rebase:
|
| 972 |
+
log.info("%s: workdir base build stopped (drain or preempt)", rt.name)
|
| 973 |
+
return None
|
| 974 |
+
await asyncio.to_thread(_write_synced, new_idx, json.dumps(index))
|
| 975 |
+
await asyncio.to_thread(self.store.upload, [(tar, pre + BASE_TAR)])
|
| 976 |
+
base = {"created_at": t0, "files": len(index),
|
| 977 |
+
"bytes": sum(s for _, s in index.values()), "deleted": [], "links": {}}
|
| 978 |
+
await self._write_base(rt, base)
|
| 979 |
+
os.replace(new_idx, idx)
|
| 980 |
+
finally:
|
| 981 |
+
self._building.discard(pre)
|
| 982 |
+
tar.unlink(missing_ok=True)
|
| 983 |
+
new_idx.unlink(missing_ok=True)
|
| 984 |
+
log.info("%s: new workdir base: %d files, %.0f MB in %.1f s", rt.name, base["files"],
|
| 985 |
+
base["bytes"] / 2**20, time.time() - t0)
|
| 986 |
+
return base
|
| 987 |
+
|
| 988 |
+
async def _write_base(self, rt: AgentRuntime, base: dict) -> None:
|
| 989 |
+
path = rt.sessions_dir / f"{rt.name}.base.json"
|
| 990 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 991 |
+
path.write_text(json.dumps(base))
|
| 992 |
+
await asyncio.to_thread(self.store.upload, [(path, self.prefix(rt) + BASE_JSON)])
|
| 993 |
+
self._base[self.prefix(rt)] = base
|
| 994 |
+
|
| 995 |
+
async def _restore_base(self, rt: AgentRuntime,
|
| 996 |
+
skip: list[str]) -> tuple[dict | None, list[str], int]:
|
| 997 |
+
"""Manifest, then tar (extracted while read from disk), tombstones and symlinks.
|
| 998 |
+
Returns (the manifest or None when the base could not be restored, failed bucket paths,
|
| 999 |
+
files extracted)."""
|
| 1000 |
+
pre = self.prefix(rt)
|
| 1001 |
+
mpath, tar = rt.sessions_dir / f"{rt.name}.base.json", rt.sessions_dir / f"{rt.name}.base.tar"
|
| 1002 |
+
try:
|
| 1003 |
+
_, failed = await asyncio.to_thread(download_resilient, self.store,
|
| 1004 |
+
[(pre + BASE_JSON, mpath)])
|
| 1005 |
+
if failed:
|
| 1006 |
+
return None, failed, 0
|
| 1007 |
+
base = json.loads(mpath.read_text())
|
| 1008 |
+
size = int(base["bytes"])
|
| 1009 |
+
if not _fits([(rt.sessions_dir, size + int(base["files"]) * TAR_PER_FILE),
|
| 1010 |
+
(rt.workdir, size)]):
|
| 1011 |
+
log.error("%s: workdir base not restored: not enough free disk for %d MB "
|
| 1012 |
+
"(tar plus files)", rt.name, 2 * size // 2**20)
|
| 1013 |
+
return None, [pre + BASE_TAR], 0
|
| 1014 |
+
_, failed = await asyncio.to_thread(download_resilient, self.store,
|
| 1015 |
+
[(pre + BASE_TAR, tar)])
|
| 1016 |
+
if failed:
|
| 1017 |
+
return None, failed, 0
|
| 1018 |
+
index, bad = await asyncio.to_thread(extract_base_tar, tar, rt.workdir, skip, base)
|
| 1019 |
+
except (OSError, ValueError, KeyError, AttributeError, tarfile.TarError) as e:
|
| 1020 |
+
log.warning("%s: workdir base not restored: %s", rt.name, _short(e))
|
| 1021 |
+
return None, [pre + BASE_TAR], 0
|
| 1022 |
+
finally:
|
| 1023 |
+
tar.unlink(missing_ok=True)
|
| 1024 |
+
await asyncio.to_thread(self._index_path(rt).write_text, json.dumps(index))
|
| 1025 |
+
self._base[pre] = base
|
| 1026 |
+
if bad:
|
| 1027 |
+
log.warning("%s: %d workdir base entries not restored", rt.name, bad)
|
| 1028 |
+
return base, [pre + BASE_TAR] if bad else [], len(index)
|
| 1029 |
+
|
| 1030 |
+
def _quota(self, rt: AgentRuntime, ws: WorkdirStats) -> None:
|
| 1031 |
+
"""Above the soft limit: a note in front of the agent's next prompt, and above the hard
|
| 1032 |
+
one a `workdir_over_quota` event, each at most hourly. The push itself goes on."""
|
| 1033 |
+
w = rt.spec.workdir or WorkdirSpec()
|
| 1034 |
+
note, pre, now = quota_note(ws, w), self.prefix(rt), time.monotonic()
|
| 1035 |
+
if note is None or now - self._quota_at.get(pre, -QUOTA_NOTE_EVERY) < QUOTA_NOTE_EVERY:
|
| 1036 |
+
return
|
| 1037 |
+
rt._notes.pop(self._quota_note.pop(pre, None), None) # replace, do not stack
|
| 1038 |
+
rt._note(note)
|
| 1039 |
+
if note not in rt._notes: # dropped (no turn yet): try again at the next push
|
| 1040 |
+
return
|
| 1041 |
+
self._quota_at[pre] = now
|
| 1042 |
+
self._quota_note[pre] = note
|
| 1043 |
+
if over_hard_limit(ws, w):
|
| 1044 |
+
rt.emit("workdir_over_quota", {"files": ws.files, "bytes": ws.bytes,
|
| 1045 |
+
"top_dirs": [list(t) for t in ws.top_dirs]})
|
| 1046 |
+
|
| 1047 |
+
async def restore(self, rt: AgentRuntime) -> RestoreResult:
|
| 1048 |
+
try:
|
| 1049 |
+
return await self._restore(rt)
|
| 1050 |
+
except Exception:
|
| 1051 |
+
self.stats.add("errors", "restore_failed")
|
| 1052 |
+
raise
|
| 1053 |
+
|
| 1054 |
+
async def _restore(self, rt: AgentRuntime) -> RestoreResult:
|
| 1055 |
+
pre = self.prefix(rt)
|
| 1056 |
+
self._mirror[pre] = False # until this restore completes with every file
|
| 1057 |
+
self._restoring.add(pre)
|
| 1058 |
+
self.restore_progress[pre] = [0, 0, datetime.now(UTC)]
|
| 1059 |
+
try:
|
| 1060 |
+
res = await self._restore_files(rt, pre)
|
| 1061 |
+
finally:
|
| 1062 |
+
self._restoring.discard(pre)
|
| 1063 |
+
self.restore_progress.pop(pre, None)
|
| 1064 |
+
self._mirror[pre] = not res.failed
|
| 1065 |
+
return res
|
| 1066 |
+
|
| 1067 |
+
async def _restore_files(self, rt: AgentRuntime, pre: str) -> RestoreResult:
|
| 1068 |
+
lister = getattr(self.store, "list_info", None)
|
| 1069 |
+
if lister is not None: # raises: the caller starts fresh
|
| 1070 |
+
listed = await asyncio.to_thread(lister, pre)
|
| 1071 |
+
else:
|
| 1072 |
+
listed = [(r, None) for r in await asyncio.to_thread(self.store.list, pre)]
|
| 1073 |
+
mtimes = {r: mt for r, mt in listed}
|
| 1074 |
+
self._base.pop(pre, None) # known again only if this listing has one
|
| 1075 |
+
res = RestoreResult()
|
| 1076 |
+
work: list[tuple[str, Path]] = []
|
| 1077 |
+
plan: list[tuple[str, Path]] = []
|
| 1078 |
+
home = Path(rt.adapter.home)
|
| 1079 |
+
n = sum([await asyncio.to_thread(_clean_parts, d) for d in (rt.workdir, rt.sessions_dir)])
|
| 1080 |
+
if n:
|
| 1081 |
+
log.info("%s: removed %d stray %s file(s)", rt.name, n, PART_SUFFIX)
|
| 1082 |
+
skip = workdir_excludes() + ephemeral_excludes(rt.spec)
|
| 1083 |
+
for r, _ in listed:
|
| 1084 |
+
rel = r[len(pre):]
|
| 1085 |
+
area, _, sub = rel.partition("/")
|
| 1086 |
+
if rel == "meta.json": # known, the first push after a move need not resend it
|
| 1087 |
+
plan.append((r, rt.sessions_dir / f"{rt.name}.meta.json"))
|
| 1088 |
+
continue
|
| 1089 |
+
if not sub or ".." in Path(sub).parts:
|
| 1090 |
+
continue
|
| 1091 |
+
if area == "workdir":
|
| 1092 |
+
if rt.spec.persist_workdir and not is_excluded(sub, skip):
|
| 1093 |
+
work.append((r, rt.workdir / sub))
|
| 1094 |
+
elif area == "sessions":
|
| 1095 |
+
plan.append((r, rt.sessions_dir / sub))
|
| 1096 |
+
elif area == "harness":
|
| 1097 |
+
plan.append((r, home / sub))
|
| 1098 |
+
prog = self.restore_progress.get(pre)
|
| 1099 |
+
if prog is not None:
|
| 1100 |
+
prog[1] = len(work) + len(plan)
|
| 1101 |
+
|
| 1102 |
+
def progress(n: int) -> None:
|
| 1103 |
+
if prog is not None:
|
| 1104 |
+
prog[0] += n
|
| 1105 |
+
|
| 1106 |
+
if rt.spec.persist_workdir and pre + BASE_JSON in mtimes:
|
| 1107 |
+
base, failed, n = await self._restore_base(rt, skip)
|
| 1108 |
+
res.workdir, res.failed = n, res.failed + failed
|
| 1109 |
+
if prog is not None:
|
| 1110 |
+
prog[1] += n
|
| 1111 |
+
progress(n)
|
| 1112 |
+
if base is not None: # older deltas are already in the tar (or stale)
|
| 1113 |
+
work = [(r, p) for r, p in work
|
| 1114 |
+
if mtimes.get(r) is None or mtimes[r] > base["created_at"]]
|
| 1115 |
+
await asyncio.to_thread(_no_links, rt.workdir, work)
|
| 1116 |
+
if work:
|
| 1117 |
+
rt.workdir.mkdir(parents=True, exist_ok=True)
|
| 1118 |
+
got, failed = await asyncio.to_thread(download_resilient, self.store, work,
|
| 1119 |
+
progress=progress)
|
| 1120 |
+
res.workdir, res.failed = res.workdir + len(got), res.failed + failed
|
| 1121 |
+
await asyncio.to_thread(_set_mtimes, got, mtimes)
|
| 1122 |
+
if n := await asyncio.to_thread(apply_modes, rt.workdir):
|
| 1123 |
+
log.info("%s: restored the mode of %d file(s)", rt.name, n)
|
| 1124 |
+
if plan:
|
| 1125 |
+
for _, p in plan:
|
| 1126 |
+
_part(p).unlink(missing_ok=True)
|
| 1127 |
+
got, failed = await asyncio.to_thread(download_resilient, self.store, plan,
|
| 1128 |
+
progress=progress)
|
| 1129 |
+
res.failed += failed
|
| 1130 |
+
await asyncio.to_thread(_set_mtimes, got, mtimes)
|
| 1131 |
+
for r, p in got:
|
| 1132 |
+
if r == pre + "meta.json":
|
| 1133 |
+
try:
|
| 1134 |
+
self._meta[pre] = {k: v for k, v in json.loads(p.read_text()).items()
|
| 1135 |
+
if k in ("files", "bytes")}
|
| 1136 |
+
except (OSError, ValueError, AttributeError):
|
| 1137 |
+
pass
|
| 1138 |
+
elif r.startswith(pre + "sessions/"):
|
| 1139 |
+
res.sessions += 1
|
| 1140 |
+
else:
|
| 1141 |
+
res.harness += 1
|
| 1142 |
+
self._mark([(p, r) for r, p in got])
|
| 1143 |
+
if res.failed:
|
| 1144 |
+
self.stats.add("errors", "restore_file_failed", len(res.failed))
|
| 1145 |
+
state = f"{pre}sessions/{rt.state_path.name}"
|
| 1146 |
+
if state in res.failed:
|
| 1147 |
+
log.warning("%s: state file %s not restored; the agent starts a fresh session",
|
| 1148 |
+
rt.name, state)
|
| 1149 |
+
log.warning("%s: restored workdir=%d sessions=%d harness=%d; %d file(s) skipped "
|
| 1150 |
+
"(not found or still failing after retries), e.g. %s", rt.name,
|
| 1151 |
+
res.workdir, res.sessions, res.harness, len(res.failed),
|
| 1152 |
+
", ".join(res.failed[:10]))
|
| 1153 |
+
else:
|
| 1154 |
+
log.info("%s: restored %s", rt.name, res)
|
| 1155 |
+
return res
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
def _no_links(workdir: Path, work: list[tuple[str, Path]]) -> None:
|
| 1159 |
+
"""Deltas over a tar's symlinks: a file or directory replaced a symlink after the base, so
|
| 1160 |
+
remove symlinks at a delta's path and its parents, or the download writes through them."""
|
| 1161 |
+
for _, p in work:
|
| 1162 |
+
parts = p.relative_to(workdir).parts
|
| 1163 |
+
for i in range(1, len(parts) + 1):
|
| 1164 |
+
q = workdir.joinpath(*parts[:i])
|
| 1165 |
+
if q.is_symlink():
|
| 1166 |
+
q.unlink()
|
| 1167 |
+
break
|
| 1168 |
+
if not q.is_dir():
|
| 1169 |
+
break
|
| 1170 |
+
|
| 1171 |
+
|
| 1172 |
+
def _set_mtimes(files: list[tuple[str, Path]], mtimes: dict[str, float | None]) -> None:
|
| 1173 |
+
"""Give restored files the bucket's mtime, so the next `sync_up` sees them unchanged."""
|
| 1174 |
+
for r, p in files:
|
| 1175 |
+
mt = mtimes.get(r)
|
| 1176 |
+
if mt is None:
|
| 1177 |
+
continue
|
| 1178 |
+
try:
|
| 1179 |
+
os.utime(p, (mt, mt), follow_symlinks=False)
|
| 1180 |
+
except (OSError, NotImplementedError):
|
| 1181 |
+
pass
|
world/src/flock/world/__init__.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""`flock.world`: a small base for writing a world in Python (docs/world.md).
|
| 2 |
+
|
| 3 |
+
A world is any HTTP server that speaks World API v1 (`flock.world.protocol`); this base is a
|
| 4 |
+
convenience, not a requirement. Subclass `World`, mark tool methods with `@tool`, and serve it
|
| 5 |
+
with `python -m flock.world serve module:Class` (`flock.world.server`):
|
| 6 |
+
|
| 7 |
+
from flock.world import Agent, ToolError, World, tool
|
| 8 |
+
|
| 9 |
+
class Counter(World):
|
| 10 |
+
name, version = "counter", "0.1.0"
|
| 11 |
+
|
| 12 |
+
def __init__(self) -> None:
|
| 13 |
+
self.n = 0
|
| 14 |
+
|
| 15 |
+
@tool
|
| 16 |
+
def bump(self, agent: Agent, by: int = 1) -> dict:
|
| 17 |
+
\"\"\"Add `by` to the shared counter and return it.\"\"\"
|
| 18 |
+
if by < 1:
|
| 19 |
+
raise ToolError("by must be >= 1")
|
| 20 |
+
self.n += by
|
| 21 |
+
return {"n": self.n, "by": agent.name}
|
| 22 |
+
|
| 23 |
+
Tool schemas come from the type hints and docstrings with the tools-folder rules
|
| 24 |
+
(flock.tools.loader); a parameter named `agent` (or annotated `Agent`) receives the
|
| 25 |
+
caller and is never shown to the model. Override `manifest()` and `call()` to serve tools some
|
| 26 |
+
other way. The hooks `on_agent_start`, `on_agent_done` and `on_turn` are sent only when a
|
| 27 |
+
subclass overrides them (the manifest lists them in `hooks`).
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
from __future__ import annotations
|
| 31 |
+
|
| 32 |
+
import inspect
|
| 33 |
+
import os
|
| 34 |
+
import typing
|
| 35 |
+
from collections.abc import Callable
|
| 36 |
+
from dataclasses import dataclass
|
| 37 |
+
from typing import Any
|
| 38 |
+
|
| 39 |
+
from flock.world.admin import TYPES, Admin, Knob
|
| 40 |
+
from flock.world.protocol import HOOK_EVENTS, STATE_DIR_ENV, WORLD_API
|
| 41 |
+
|
| 42 |
+
AGENT_PARAM = "agent"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass(frozen=True)
|
| 46 |
+
class Agent:
|
| 47 |
+
"""Who calls: the flock agent name, its type and swarm, the turn and the request id (as
|
| 48 |
+
flock sent them; trust them when the token matched)."""
|
| 49 |
+
|
| 50 |
+
name: str
|
| 51 |
+
type: str = ""
|
| 52 |
+
swarm: str = ""
|
| 53 |
+
turn: str = ""
|
| 54 |
+
request_id: str = ""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ToolError(Exception):
|
| 58 |
+
"""Raise from a tool: the agent reads `message` as the tool's error result.
|
| 59 |
+
`retry_after_s`: the call cannot succeed before then (a budget, a busy backend); the
|
| 60 |
+
server sends it in the error envelope and the worker may hold the tool off until then."""
|
| 61 |
+
|
| 62 |
+
def __init__(self, message: str, code: str = "tool_error",
|
| 63 |
+
retry_after_s: float | None = None) -> None:
|
| 64 |
+
super().__init__(message)
|
| 65 |
+
self.code = code
|
| 66 |
+
self.message = message
|
| 67 |
+
self.retry_after_s = retry_after_s
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
POOLS = ("fast", "slow")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def tool(fn: Callable | None = None, *, pool: str = "fast", read_only: bool = False) -> Any:
|
| 74 |
+
"""Mark a method of a World subclass as a tool: `@tool`, or `@tool(pool="slow",
|
| 75 |
+
read_only=True)`. `pool`: the server's thread pool for the call ("slow" for tools that
|
| 76 |
+
block for seconds, so they never take the threads of the quick ones). `read_only`: the
|
| 77 |
+
tool changes nothing (manifest `annotations.readOnlyHint`; the worker may retry it)."""
|
| 78 |
+
if pool not in POOLS:
|
| 79 |
+
raise ValueError(f"pool {pool!r} must be one of {POOLS}")
|
| 80 |
+
|
| 81 |
+
def mark(f: Callable) -> Callable:
|
| 82 |
+
f.__flock_world_tool__ = True # type: ignore[attr-defined]
|
| 83 |
+
f.__flock_world_pool__ = pool # type: ignore[attr-defined]
|
| 84 |
+
f.__flock_world_read_only__ = read_only # type: ignore[attr-defined]
|
| 85 |
+
return f
|
| 86 |
+
|
| 87 |
+
return mark if fn is None else mark(fn)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _is_agent(p: inspect.Parameter, hints: dict[str, Any]) -> bool:
|
| 91 |
+
hint = hints.get(p.name)
|
| 92 |
+
return p.name == AGENT_PARAM or hint is Agent
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def tool_schema(fn: Callable) -> dict[str, Any]:
|
| 96 |
+
"""{name, description, parameters} of a tool method (raises flock.tools.loader.ToolsError)."""
|
| 97 |
+
from flock.tools.loader import tool_def
|
| 98 |
+
|
| 99 |
+
hints = typing.get_type_hints(fn)
|
| 100 |
+
sig = inspect.signature(fn)
|
| 101 |
+
keep = [p for p in sig.parameters.values() if not _is_agent(p, hints)]
|
| 102 |
+
|
| 103 |
+
def shim(*_a: Any, **_k: Any) -> None: ...
|
| 104 |
+
|
| 105 |
+
shim.__name__ = fn.__name__
|
| 106 |
+
shim.__doc__ = fn.__doc__
|
| 107 |
+
shim.__signature__ = sig.replace(parameters=keep) # type: ignore[attr-defined]
|
| 108 |
+
shim.__annotations__ = {k: v for k, v in hints.items() if k in {p.name for p in keep}}
|
| 109 |
+
d = tool_def(shim, type(getattr(fn, "__self__", fn)).__name__)
|
| 110 |
+
return {"name": d.name, "description": d.description, "parameters": d.parameters}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class World:
|
| 114 |
+
"""Base class. Class attributes: `name` (lowercase, `[a-z][a-z0-9-]*`), `version` (any
|
| 115 |
+
string; bump it when the tools change, agents are told), `description` (shown to the
|
| 116 |
+
agents), `capabilities` (extra names for the manifest)."""
|
| 117 |
+
|
| 118 |
+
name: typing.ClassVar[str] = "world"
|
| 119 |
+
version: typing.ClassVar[str] = "0.0.0"
|
| 120 |
+
description: typing.ClassVar[str] = ""
|
| 121 |
+
capabilities: typing.ClassVar[list[str]] = []
|
| 122 |
+
# False (default): the server runs one tool call or hook at a time (a global lock), so a
|
| 123 |
+
# world needs no locking of its own. True: calls and hooks run concurrently in the
|
| 124 |
+
# server's thread pool; the world guards its own state (a slow tool then never holds up
|
| 125 |
+
# the hooks or the other agents' calls).
|
| 126 |
+
concurrent: typing.ClassVar[bool] = False
|
| 127 |
+
|
| 128 |
+
# ------------------------------------------------------------------ tools
|
| 129 |
+
def tools(self) -> dict[str, Callable]:
|
| 130 |
+
"""The bound `@tool` methods, by name (in definition order)."""
|
| 131 |
+
found = self.__dict__.get("_flock_tools")
|
| 132 |
+
if found is None: # no __init__ needed in subclasses: built on first use
|
| 133 |
+
found = {}
|
| 134 |
+
for klass in reversed(type(self).__mro__):
|
| 135 |
+
for attr, value in vars(klass).items():
|
| 136 |
+
if getattr(value, "__flock_world_tool__", False):
|
| 137 |
+
found[attr] = getattr(self, attr)
|
| 138 |
+
self.__dict__["_flock_tools"] = found
|
| 139 |
+
return found
|
| 140 |
+
|
| 141 |
+
def hooks(self) -> list[str]:
|
| 142 |
+
"""The hooks a subclass overrides."""
|
| 143 |
+
out = []
|
| 144 |
+
for event in HOOK_EVENTS:
|
| 145 |
+
meth = f"on_{event}"
|
| 146 |
+
if getattr(type(self), meth) is not getattr(World, meth):
|
| 147 |
+
out.append(event)
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
def manifest(self) -> dict[str, Any]:
|
| 151 |
+
"""Built on every call (the server serves and dispatches from it), from the class
|
| 152 |
+
attributes as they are now; the tool schemas are computed once."""
|
| 153 |
+
hooks = self.hooks()
|
| 154 |
+
caps = list(dict.fromkeys([*self.capabilities, *(["hooks"] if hooks else [])]))
|
| 155 |
+
schemas = self.__dict__.get("_flock_schemas")
|
| 156 |
+
if schemas is None:
|
| 157 |
+
schemas = [tool_schema(fn) for fn in self.tools().values()]
|
| 158 |
+
for t, fn in zip(schemas, self.tools().values(), strict=True):
|
| 159 |
+
if getattr(fn, "__flock_world_read_only__", False):
|
| 160 |
+
t["annotations"] = {"readOnlyHint": True}
|
| 161 |
+
self.__dict__["_flock_schemas"] = schemas
|
| 162 |
+
return {"world_api": WORLD_API, "name": self.name, "version": self.version,
|
| 163 |
+
"description": self.description, "tools": [dict(t) for t in schemas],
|
| 164 |
+
"capabilities": caps, "hooks": hooks}
|
| 165 |
+
|
| 166 |
+
def call(self, tool: str, args: dict[str, Any], agent: Agent) -> Any:
|
| 167 |
+
"""Run `tool` for `agent`; the return value is the result (JSON-serialisable, or a
|
| 168 |
+
coroutine the server awaits). Raise ToolError for an error the agent should read;
|
| 169 |
+
KeyError for an unknown tool."""
|
| 170 |
+
fn = self.tools()[tool]
|
| 171 |
+
hints = typing.get_type_hints(fn)
|
| 172 |
+
extra = {p.name: agent for p in inspect.signature(fn).parameters.values()
|
| 173 |
+
if _is_agent(p, hints)}
|
| 174 |
+
return fn(**args, **extra)
|
| 175 |
+
|
| 176 |
+
def pool(self, tool: str) -> str:
|
| 177 |
+
"""The server's thread pool for `tool`: "fast" (default) or "slow" (`@tool(pool=)`)."""
|
| 178 |
+
return getattr(self.tools().get(tool), "__flock_world_pool__", "fast")
|
| 179 |
+
|
| 180 |
+
def cancellable(self, tool: str) -> bool:
|
| 181 |
+
"""May the server cancel this tool's `async` work when its caller disconnects (the
|
| 182 |
+
HTTP client gave up, e.g. on its own timeout)? Default False: the work always runs to
|
| 183 |
+
the end. A world returns True for tools whose work is wasted once nobody reads it."""
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
def metrics(self) -> dict[str, float]:
|
| 187 |
+
"""World-specific numbers for `GET /metrics` (under `world`). Called in a thread,
|
| 188 |
+
concurrently with tools, every scrape (about every 30 s): keep it cheap; take your
|
| 189 |
+
own lock if you need one. Default: none."""
|
| 190 |
+
return {}
|
| 191 |
+
|
| 192 |
+
# ------------------------------------------------------------------ admin (docs/world.md)
|
| 193 |
+
def state_dir(self) -> str | os.PathLike | None:
|
| 194 |
+
"""Where `knobs.json` lives (knob values and paused lanes set through the admin API,
|
| 195 |
+
read back at the next start). Default: $FLOCK_WORLD_STATE_DIR, else None (kept in
|
| 196 |
+
memory only). The server may call it before `__init__` ran (to serve /admin while the
|
| 197 |
+
world cannot be built): do not rely on attributes `__init__` sets without a fallback."""
|
| 198 |
+
return os.environ.get(STATE_DIR_ENV) or None
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def admin(self) -> Admin:
|
| 202 |
+
"""This world's knobs and paused lanes (the server may install one before __init__)."""
|
| 203 |
+
if "_flock_admin" not in self.__dict__:
|
| 204 |
+
self.__dict__["_flock_admin"] = Admin(self.state_dir())
|
| 205 |
+
return self.__dict__["_flock_admin"]
|
| 206 |
+
|
| 207 |
+
def knob(self, name: str, type: type, default: Any, *, min: float | None = None,
|
| 208 |
+
max: float | None = None, doc: str = "",
|
| 209 |
+
on_change: Callable[[Any], None] | None = None) -> Any:
|
| 210 |
+
"""Register a runtime knob (int, float, bool or str) and return its current value: the
|
| 211 |
+
value set through `PATCH /admin/knobs` if any (it survives restarts), else `default`.
|
| 212 |
+
A change calls `on_change(value)` (in a thread; raise to refuse it) and shows in
|
| 213 |
+
`self.knobs[name]`."""
|
| 214 |
+
if type not in TYPES:
|
| 215 |
+
raise ValueError(f"knob {name}: type must be one of int, float, bool, str")
|
| 216 |
+
return self.admin.register(Knob(name, type, default, min, max, doc, on_change))
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def knobs(self) -> dict[str, Any]:
|
| 220 |
+
"""The knobs' current values, by name (live: reflects admin changes)."""
|
| 221 |
+
return self.admin.values
|
| 222 |
+
|
| 223 |
+
def paused(self, lane: str) -> bool:
|
| 224 |
+
"""Did an operator pause `lane` (`POST /admin/pause`)? Lanes are names the world
|
| 225 |
+
chooses and documents (e.g. "push", "open", "merge")."""
|
| 226 |
+
return lane in self.admin.paused
|
| 227 |
+
|
| 228 |
+
# ------------------------------------------------------------------ hooks
|
| 229 |
+
def on_agent_start(self, agent: Agent) -> None:
|
| 230 |
+
"""An agent got its first prompt on its worker (again after a relaunch)."""
|
| 231 |
+
|
| 232 |
+
def on_agent_done(self, agent: Agent, data: dict[str, Any]) -> None:
|
| 233 |
+
"""An agent was removed from the swarm (scale down, `flock stop --delete`, `flock-agent remove`)."""
|
| 234 |
+
|
| 235 |
+
def on_turn(self, agent: Agent, data: dict[str, Any]) -> None:
|
| 236 |
+
"""An agent's turn ended: `data` has status, tool_calls, turn."""
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
__all__ = ["Admin", "Agent", "ToolError", "World", "tool", "tool_schema"]
|