Add TextCraft-Synth 1.0: 3,154 Harbor tasks (part 23)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/textcraft-synth-train-hard-01231/solution/solve.sh +104 -0
- tasks/textcraft-synth-train-hard-01231/task.toml +33 -0
- tasks/textcraft-synth-train-hard-01231/tests/Dockerfile +13 -0
- tasks/textcraft-synth-train-hard-01231/tests/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01231/tests/task.json +24 -0
- tasks/textcraft-synth-train-hard-01231/tests/test.sh +17 -0
- tasks/textcraft-synth-train-hard-01231/tests/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01235/environment/Dockerfile +17 -0
- tasks/textcraft-synth-train-hard-01235/environment/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01235/environment/task.json +23 -0
- tasks/textcraft-synth-train-hard-01235/environment/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01235/instruction.md +38 -0
- tasks/textcraft-synth-train-hard-01235/solution/solve.sh +106 -0
- tasks/textcraft-synth-train-hard-01235/task.toml +33 -0
- tasks/textcraft-synth-train-hard-01235/tests/Dockerfile +13 -0
- tasks/textcraft-synth-train-hard-01235/tests/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01235/tests/task.json +23 -0
- tasks/textcraft-synth-train-hard-01235/tests/test.sh +17 -0
- tasks/textcraft-synth-train-hard-01235/tests/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01244/environment/Dockerfile +17 -0
- tasks/textcraft-synth-train-hard-01244/environment/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01244/environment/task.json +24 -0
- tasks/textcraft-synth-train-hard-01244/environment/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01244/instruction.md +38 -0
- tasks/textcraft-synth-train-hard-01244/solution/solve.sh +77 -0
- tasks/textcraft-synth-train-hard-01244/task.toml +33 -0
- tasks/textcraft-synth-train-hard-01244/tests/Dockerfile +13 -0
- tasks/textcraft-synth-train-hard-01244/tests/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01244/tests/task.json +24 -0
- tasks/textcraft-synth-train-hard-01244/tests/test.sh +17 -0
- tasks/textcraft-synth-train-hard-01244/tests/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01257/environment/Dockerfile +17 -0
- tasks/textcraft-synth-train-hard-01257/environment/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01257/environment/task.json +22 -0
- tasks/textcraft-synth-train-hard-01257/environment/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01257/instruction.md +38 -0
- tasks/textcraft-synth-train-hard-01257/solution/solve.sh +121 -0
- tasks/textcraft-synth-train-hard-01257/task.toml +33 -0
- tasks/textcraft-synth-train-hard-01257/tests/Dockerfile +13 -0
- tasks/textcraft-synth-train-hard-01257/tests/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01257/tests/task.json +22 -0
- tasks/textcraft-synth-train-hard-01257/tests/test.sh +17 -0
- tasks/textcraft-synth-train-hard-01257/tests/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01267/environment/Dockerfile +17 -0
- tasks/textcraft-synth-train-hard-01267/environment/recipes.json +0 -0
- tasks/textcraft-synth-train-hard-01267/environment/task.json +22 -0
- tasks/textcraft-synth-train-hard-01267/environment/textcraft_game.py +756 -0
- tasks/textcraft-synth-train-hard-01267/instruction.md +38 -0
- tasks/textcraft-synth-train-hard-01267/solution/solve.sh +85 -0
- tasks/textcraft-synth-train-hard-01267/task.toml +33 -0
tasks/textcraft-synth-train-hard-01231/solution/solve.sh
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# The reference solution of textcraft-synth-train-hard-01231: the source task's gold trajectory (96 crafts), then finish.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
if ! command -v textcraft >/dev/null 2>&1; then
|
| 5 |
+
# platoon's process provider runs no image, so there is no textcraft command: run the game file itself.
|
| 6 |
+
textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }
|
| 7 |
+
fi
|
| 8 |
+
textcraft craft m7_i1_17 16 m9_ore=4
|
| 9 |
+
textcraft craft m2_i1_12 28 m9_ore=14
|
| 10 |
+
textcraft craft m2_i1_22 16 m3_ore=8
|
| 11 |
+
textcraft craft m8_i1 30 m1_ore=30
|
| 12 |
+
textcraft craft m1_i1 16 m3_ore=4
|
| 13 |
+
textcraft craft m5_i1 22 m4_ore=11
|
| 14 |
+
textcraft craft m1_i1_21 4 m9_ore=4
|
| 15 |
+
textcraft craft m2_i1 6 m4_ore=3
|
| 16 |
+
textcraft craft m3_i1 24 m5_ore=6
|
| 17 |
+
textcraft craft m0_i1_10 12 m0_ore=6
|
| 18 |
+
textcraft craft m3_i1_13 8 m9_ore=4
|
| 19 |
+
textcraft craft m6_i1 16 m8_ore=8
|
| 20 |
+
textcraft craft m4_i1 26 m7_ore=26
|
| 21 |
+
textcraft craft m0_i1 20 m0_ore=20
|
| 22 |
+
textcraft craft m9_i1_19 24 m0_ore=16
|
| 23 |
+
textcraft craft m1_i1_11 8 m7_ore=2
|
| 24 |
+
textcraft craft m4_i1_24 12 m4_ore=3
|
| 25 |
+
textcraft craft m4_i1_14 4 m4_ore=4
|
| 26 |
+
textcraft craft m5_i1_15 4 m7_ore=1
|
| 27 |
+
textcraft craft m8_i1_18 2 m1_ore=1
|
| 28 |
+
textcraft craft m1_i2_11 30 m1_ore=15 m8_i1=15
|
| 29 |
+
textcraft craft m0_i2_10 28 m1_i1=14 m5_i1=14
|
| 30 |
+
textcraft craft m9_i2_19 6 m1_i1_21=2 m7_i1_17=4
|
| 31 |
+
textcraft craft m1_i2 4 m8_i1=4 m3_ore=4
|
| 32 |
+
textcraft craft m8_i2 12 m8_ore=4 m3_i1=8
|
| 33 |
+
textcraft craft m5_i2_15 6 m0_i1_10=6 m1_ore=6
|
| 34 |
+
textcraft craft m6_i2_16 10 m3_ore=5 m3_i1_13=5
|
| 35 |
+
textcraft craft m3_i2_13 14 m4_i1=14 m6_ore=7
|
| 36 |
+
textcraft craft m0_i2_20 18 m3_ore=6 m0_i1=6
|
| 37 |
+
textcraft craft m2_i2 4 m1_i1_11=4 m5_i1=4
|
| 38 |
+
textcraft craft m2_i2_22 12 m9_ore=4
|
| 39 |
+
textcraft craft m1_i2_21 6 m4_i1_24=4 m6_ore=4
|
| 40 |
+
textcraft craft m4_i2_24 8 m4_ore=4 m5_ore=8
|
| 41 |
+
textcraft craft m9_i2 3 m2_i1_22=1 m4_i1_14=2
|
| 42 |
+
textcraft craft m8_i2_18 4 m9_i1_19=2 m4_ore=2
|
| 43 |
+
textcraft craft m6_i2 16 m6_ore=16 m3_ore=8
|
| 44 |
+
textcraft craft m2_i2_12 24 m2_i1_12=8 m3_ore=8
|
| 45 |
+
textcraft craft m7_i2_17 3 m5_i1=1 m8_ore=2
|
| 46 |
+
textcraft craft m4_i2 6 m8_i1_18=2 m3_i1=2
|
| 47 |
+
textcraft craft m7_i2 2 m9_i1_19=1 m2_i1_22=2
|
| 48 |
+
textcraft craft m6_i3 5 m7_i1_17=10 m2_i1_12=10 m2_i1_22=10
|
| 49 |
+
textcraft craft m1_i3_11 10 m1_i2_11=20 m0_i2_10=20
|
| 50 |
+
textcraft craft m0_i3_10 2 m1_i2=2 m2_i1=1
|
| 51 |
+
textcraft craft m4_i3_14 8 m6_i2_16=8 m6_i1=16
|
| 52 |
+
textcraft craft m9_i3_19 4 m3_i2_13=2 m9_i1_19=4 m8_i2=2
|
| 53 |
+
textcraft craft m2_i3 6 m2_i2_22=3 m1_i2_21=3 m0_i1=3
|
| 54 |
+
textcraft craft m7_i3_17 6 m0_i2_10=6 m4_i1_24=3 m4_i2_24=3
|
| 55 |
+
textcraft craft m7_i3 2 m9_i2=1 m8_i2_18=1
|
| 56 |
+
textcraft craft m2_i3_22 10 m1_i2_11=5 m9_i1_19=5 m2_i2_12=10
|
| 57 |
+
textcraft craft m9_i3 12 m4_i1=6 m0_i2_20=6
|
| 58 |
+
textcraft craft m0_i3_20 6 m2_i2_12=3 m0_i1=6
|
| 59 |
+
textcraft craft m1_i3 2 m2_i1_12=2 m3_i2_13=1 m5_i1_15=2
|
| 60 |
+
textcraft craft m5_i3 6 m2_i2_22=6 m8_i1=6
|
| 61 |
+
textcraft craft m5_i3_15 1 m7_i2_17=2 m2_i2=1
|
| 62 |
+
textcraft craft m0_i3 4 m7_i2=2 m2_i1=4
|
| 63 |
+
textcraft craft m3_i3 2 m2_i2_22=1 m9_i2_19=2
|
| 64 |
+
textcraft craft m2_i3_12 1 m9_i2_19=1 m4_i2_24=2
|
| 65 |
+
textcraft craft m1_i4_21 2 m6_i3=2 m1_i3_11=2 m9_i2_19=1
|
| 66 |
+
textcraft craft m7_i4 6 m8_i2=6 m5_i2_15=6
|
| 67 |
+
textcraft craft m2_i4_12 2 m3_i2_13=2 m0_i2_20=2 m4_i3_14=2
|
| 68 |
+
textcraft craft m2_i4_22 3 m0_i2_20=6 m9_i3_19=3 m1_i3_11=3
|
| 69 |
+
textcraft craft m0_i4_20 2 m2_i3=2 m7_i3_17=1 m7_i3=1
|
| 70 |
+
textcraft craft m9_i4_19 3 m6_i2=6 m2_i3_22=3 m9_i3=6
|
| 71 |
+
textcraft craft m9_i4 1 m8_i2_18=2 m4_i2_24=1 m0_i3_20=2
|
| 72 |
+
textcraft craft m3_i4 1 m9_i3_19=1 m7_i3_17=2
|
| 73 |
+
textcraft craft m0_i4 2 m2_i3=2 m1_i3=1 m2_i2_12=1
|
| 74 |
+
textcraft craft m6_i4_16 6 m2_i3_22=3 m6_i2=6
|
| 75 |
+
textcraft craft m5_i4 1 m7_i3_17=2 m5_i3=2 m0_i3_20=2
|
| 76 |
+
textcraft craft m0_i4_10 1 m1_i2=2 m1_i2_21=1 m1_i3_11=2
|
| 77 |
+
textcraft craft m5_i4_15 1 m6_i3=2 m3_i2_13=2
|
| 78 |
+
textcraft craft m1_i4 2 m1_i3_11=2 m3_i2_13=2
|
| 79 |
+
textcraft craft m6_i4 2 m9_i3=2 m6_i2_16=1 m4_i2=2
|
| 80 |
+
textcraft craft m8_i4 2 m5_i3=2 m0_i3=2 m2_i2_12=1
|
| 81 |
+
textcraft craft m3_i4_23 1 m3_i3=2 m4_i3_14=2 m1_i3_11=1
|
| 82 |
+
textcraft craft m4_i4_14 1 m2_i3_22=1 m1_i2_11=1
|
| 83 |
+
textcraft craft m5_i5_15 2 m1_i4_21=1 m0_i3_10=1 m7_i4=1
|
| 84 |
+
textcraft craft m0_i5_10 1 m4_i3_14=1 m2_i4_12=1
|
| 85 |
+
textcraft craft m0_i5_20 2 m2_i2=2 m0_i4_20=2
|
| 86 |
+
textcraft craft m8_i5_18 1 m9_i4=1 m3_i4=1 m0_i4=1
|
| 87 |
+
textcraft craft m2_i5_12 3 m6_i4_16=3 m7_i4=3
|
| 88 |
+
textcraft craft m6_i5 1 m9_i3=1 m6_i4_16=1
|
| 89 |
+
textcraft craft m7_i5_17 1 m5_i3_15=1 m6_i3=1 m5_i4_15=1
|
| 90 |
+
textcraft craft m1_i5_11 2 m1_i4=2 m6_i4=2
|
| 91 |
+
textcraft craft m5_i5 2 m0_i3_20=1 m3_i4_23=1 m4_i3_14=1
|
| 92 |
+
textcraft craft m7_i5 2 m8_i4=1 m6_i4_16=1 m2_i3_12=1
|
| 93 |
+
textcraft craft m2_i6_6_12 2 m2_i4_22=2 m7_i4=2 m0_i5_20=2 m9_i4_19=2
|
| 94 |
+
textcraft craft m4_i6_6_14 1 m8_i5_18=1 m2_i5_12=1
|
| 95 |
+
textcraft craft m5_i6_6 1 m2_i5_12=1 m5_i4=1 m0_i4_10=1 m9_i4_19=1
|
| 96 |
+
textcraft craft m1_i6_6 1 m2_i5_12=1 m7_i5_17=1 m2_i4_22=1
|
| 97 |
+
textcraft craft m9_i6_6_19 1 m1_i5_11=1 m2_i4_12=1
|
| 98 |
+
textcraft craft m6_i6_6 1 m8_i4=1 m5_i5=1 m7_i5=1
|
| 99 |
+
textcraft craft m4_i6_6 1 m4_i4_14=1 m1_i5_11=1
|
| 100 |
+
textcraft craft m0_i7_7_20 1 m5_i5_15=1 m0_i5_10=1
|
| 101 |
+
textcraft craft m1_i7_7_11 1 m2_i6_6_12=1 m4_i6_6_14=1 m5_i6_6=1
|
| 102 |
+
textcraft craft m3_i7_7 1 m6_i5=1 m2_i6_6_12=1 m1_i6_6=1 m9_i6_6_19=1
|
| 103 |
+
textcraft craft m9_i8_8 1 m0_i7_7_20=1 m1_i7_7_11=1 m3_i7_7=1 m6_i6_6=1 m4_i6_6=1
|
| 104 |
+
textcraft finish 'Crafted 1x m9_i8_8'
|
tasks/textcraft-synth-train-hard-01231/task.toml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.4"
|
| 2 |
+
# The game's action log: a separate verifier receives it at the same path.
|
| 3 |
+
artifacts = ["/app/textcraft/actions.jsonl"]
|
| 4 |
+
|
| 5 |
+
[task]
|
| 6 |
+
name = "textcraft-synth/train-hard-01231"
|
| 7 |
+
description = "TextCraft-Synth: craft the following items: 1x m9_i8_8 (hard, crafting depth 8)"
|
| 8 |
+
keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
|
| 9 |
+
|
| 10 |
+
[metadata]
|
| 11 |
+
environment = "textcraft-synth@1"
|
| 12 |
+
split = "train"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
max_depth = 8
|
| 15 |
+
num_craft_steps = 96
|
| 16 |
+
goal = "Craft the following items: 1x m9_i8_8"
|
| 17 |
+
source_task_id = "textcraft_synth.train.1231"
|
| 18 |
+
env_task_id = "train:1231"
|
| 19 |
+
env_split_task_id = "train-hard:269"
|
| 20 |
+
|
| 21 |
+
[verifier]
|
| 22 |
+
environment_mode = "separate"
|
| 23 |
+
timeout_sec = 180.0
|
| 24 |
+
|
| 25 |
+
[agent]
|
| 26 |
+
timeout_sec = 1560.0
|
| 27 |
+
|
| 28 |
+
[environment]
|
| 29 |
+
network_mode = "no-network"
|
| 30 |
+
cpus = 1
|
| 31 |
+
memory_mb = 2048
|
| 32 |
+
gpus = 0
|
| 33 |
+
build_timeout_sec = 900.0
|
tasks/textcraft-synth-train-hard-01231/tests/Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01231: task.json sha256:014bd90518af693825f772fa9152784b50aad1ce03637900fa49bc5ef7eee681
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The same image as the task's environment, so one image serves the agent and the verifier.
|
| 4 |
+
RUN set -eux; \
|
| 5 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 6 |
+
> /usr/local/bin/textcraft; \
|
| 7 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 8 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 10 |
+
rm -rf /var/lib/apt/lists/*
|
| 11 |
+
# The verifier's trusted copies of the grader, the game, the recipes and the task.
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
COPY test.sh textcraft_game.py recipes.json task.json /tests/
|
tasks/textcraft-synth-train-hard-01231/tests/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01231/tests/task.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01231",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 1x m9_i8_8",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"m9_i8_8": 1
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"m9_ore": 124,
|
| 11 |
+
"m3_ore": 229,
|
| 12 |
+
"m1_ore": 150,
|
| 13 |
+
"m4_ore": 110,
|
| 14 |
+
"m8_ore": 31,
|
| 15 |
+
"m5_ore": 57,
|
| 16 |
+
"m0_ore": 215,
|
| 17 |
+
"m7_ore": 99,
|
| 18 |
+
"m6_ore": 67,
|
| 19 |
+
"c3_ore": 3,
|
| 20 |
+
"raw_t9": 3,
|
| 21 |
+
"c2_ore": 2
|
| 22 |
+
},
|
| 23 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 24 |
+
}
|
tasks/textcraft-synth-train-hard-01231/tests/test.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting
|
| 3 |
+
# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The
|
| 4 |
+
# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target
|
| 5 |
+
# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a
|
| 6 |
+
# separate verifier that received the log as an artifact.
|
| 7 |
+
# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that
|
| 8 |
+
# directory; sandboxes leave it unset.
|
| 9 |
+
set -u
|
| 10 |
+
root="${PLATOON_SANDBOX_ROOT:-}"
|
| 11 |
+
tests="$root/tests"
|
| 12 |
+
out="$root/logs/verifier"
|
| 13 |
+
mkdir -p "$out"
|
| 14 |
+
# A fresh verdict: nothing the agent may have left in the verifier's directory counts.
|
| 15 |
+
rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"
|
| 16 |
+
exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01235/environment/Dockerfile
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01235: task.json sha256:f7c798ea978ae305ce70003427d9d063963370395f0d1feafee8088ed3b1bc84
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the
|
| 4 |
+
# `textcraft` command, which runs the game file below.
|
| 5 |
+
RUN set -eux; \
|
| 6 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 7 |
+
> /usr/local/bin/textcraft; \
|
| 8 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 10 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 11 |
+
rm -rf /var/lib/apt/lists/*
|
| 12 |
+
# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The
|
| 13 |
+
# game keeps its action log next to them.
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
ENV TEXTCRAFT_DIR=/app/textcraft
|
| 16 |
+
COPY textcraft_game.py recipes.json /app/textcraft/
|
| 17 |
+
COPY task.json /app/textcraft/
|
tasks/textcraft-synth-train-hard-01235/environment/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01235/environment/task.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01235",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 1x c0_i8_8",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"c0_i8_8": 1
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"c3_ore": 97,
|
| 11 |
+
"c2_ore": 41,
|
| 12 |
+
"c9_ore": 230,
|
| 13 |
+
"c0_ore": 30,
|
| 14 |
+
"c5_ore": 268,
|
| 15 |
+
"c8_ore": 111,
|
| 16 |
+
"c4_ore": 114,
|
| 17 |
+
"c6_ore": 155,
|
| 18 |
+
"c7_ore": 170,
|
| 19 |
+
"c1_ore": 48,
|
| 20 |
+
"m0_ore": 2
|
| 21 |
+
},
|
| 22 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 23 |
+
}
|
tasks/textcraft-synth-train-hard-01235/environment/textcraft_game.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01235/instruction.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an agent in a crafting game. Your goal is to craft items by combining ingredients.
|
| 2 |
+
You have access to an inventory of existing ingredients, which are sufficient to craft the target items; though, you may need to craft intermediate ingredients first.
|
| 3 |
+
|
| 4 |
+
Note: If you already have one of the target items in your inventory, you should craft the requested number of the target on top of what you already have.
|
| 5 |
+
For example, if you already have 2 wooden_pickaxes but your goal is to craft 3, your inventory should end up with 5 wooden_pickaxes.
|
| 6 |
+
|
| 7 |
+
## Task
|
| 8 |
+
|
| 9 |
+
Craft the following items: 1x c0_i8_8
|
| 10 |
+
|
| 11 |
+
## Actions
|
| 12 |
+
|
| 13 |
+
You act through the `textcraft` command in the shell:
|
| 14 |
+
|
| 15 |
+
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]`
|
| 16 |
+
Craft items using ingredients from your inventory.
|
| 17 |
+
- INGREDIENT=COUNT pairs: the items to consume and how many of each
|
| 18 |
+
- TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count
|
| 19 |
+
- Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
|
| 20 |
+
|
| 21 |
+
2. `textcraft info ITEM [ITEM ...]`
|
| 22 |
+
Get recipe information for items.
|
| 23 |
+
- Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]}
|
| 24 |
+
- crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps
|
| 25 |
+
- Each recipe shows {"ingredients": {...}, "result_count": int}
|
| 26 |
+
- Example: `textcraft info m2_i2 raw_m0`
|
| 27 |
+
|
| 28 |
+
3. `textcraft inventory`
|
| 29 |
+
View your current inventory.
|
| 30 |
+
- Prints JSON {item_name: count}
|
| 31 |
+
|
| 32 |
+
4. `textcraft finish MESSAGE`
|
| 33 |
+
Complete the task.
|
| 34 |
+
- Example: `textcraft finish "Successfully crafted all required items"`
|
| 35 |
+
- The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a
|
| 36 |
+
task that never finishes counts as failed.
|
| 37 |
+
|
| 38 |
+
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.
|
tasks/textcraft-synth-train-hard-01235/solution/solve.sh
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# The reference solution of textcraft-synth-train-hard-01235: the source task's gold trajectory (98 crafts), then finish.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
if ! command -v textcraft >/dev/null 2>&1; then
|
| 5 |
+
# platoon's process provider runs no image, so there is no textcraft command: run the game file itself.
|
| 6 |
+
textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }
|
| 7 |
+
fi
|
| 8 |
+
textcraft craft c4_i1_14 45 c3_ore=15
|
| 9 |
+
textcraft craft c0_i1_20 15 c2_ore=5
|
| 10 |
+
textcraft craft c2_i1 22 c9_ore=22
|
| 11 |
+
textcraft craft c7_i1_17 4 c0_ore=2
|
| 12 |
+
textcraft craft c1_i1_11 20 c5_ore=5
|
| 13 |
+
textcraft craft c3_i1_13 51 c9_ore=17
|
| 14 |
+
textcraft craft c1_i1 14 c8_ore=7
|
| 15 |
+
textcraft craft c3_i1_23 38 c8_ore=19
|
| 16 |
+
textcraft craft c6_i1_16 22 c9_ore=11
|
| 17 |
+
textcraft craft c1_i1_21 46 c7_ore=23
|
| 18 |
+
textcraft craft c9_i1_19 18 c5_ore=12
|
| 19 |
+
textcraft craft c5_i1 16 c1_ore=4
|
| 20 |
+
textcraft craft c6_i1 6 c2_ore=6
|
| 21 |
+
textcraft craft c8_i1 6 c8_ore=4
|
| 22 |
+
textcraft craft c0_i1 27 c1_ore=9
|
| 23 |
+
textcraft craft c0_i1_10 8 c9_ore=2
|
| 24 |
+
textcraft craft c3_i1 4 c9_ore=1
|
| 25 |
+
textcraft craft c8_i1_18 4 c3_ore=2
|
| 26 |
+
textcraft craft c9_i1 2 c6_ore=1
|
| 27 |
+
textcraft craft c2_i1_22 6 c9_ore=2
|
| 28 |
+
textcraft craft c2_i1_12 4 c7_ore=2
|
| 29 |
+
textcraft craft c1_i2_21 4 c2_i1=2 c9_ore=4
|
| 30 |
+
textcraft craft c3_i2_23 6 c7_i1_17=2 c1_i1_11=2
|
| 31 |
+
textcraft craft c2_i2_12 26 c4_i1_14=26 c4_ore=26
|
| 32 |
+
textcraft craft c5_i2 4 c5_ore=2 c6_ore=2
|
| 33 |
+
textcraft craft c2_i2_22 28 c9_ore=14 c6_ore=14
|
| 34 |
+
textcraft craft c3_i2 4 c6_i1_16=2 c6_ore=4
|
| 35 |
+
textcraft craft c6_i2_16 12 c5_ore=8 c1_i1_21=8
|
| 36 |
+
textcraft craft c8_i2 28 c5_ore=28 c1_i1_21=28
|
| 37 |
+
textcraft craft c4_i2_24 28 c5_ore=28 c6_ore=28
|
| 38 |
+
textcraft craft c5_i2_15 10 c5_i1=10 c4_ore=5
|
| 39 |
+
textcraft craft c0_i2_20 8 c4_ore=4 c3_ore=4
|
| 40 |
+
textcraft craft c9_i2 6 c7_ore=3 c1_i1_11=3
|
| 41 |
+
textcraft craft c0_i2_10 6 c3_i1_23=4 c4_ore=4
|
| 42 |
+
textcraft craft c6_i2 9 c9_i1_19=3 c0_ore=6
|
| 43 |
+
textcraft craft c2_i2 4 c7_ore=4 c6_i1_16=2
|
| 44 |
+
textcraft craft c3_i2_13 6 c9_ore=2 c2_i1_22=2
|
| 45 |
+
textcraft craft c1_i2_11 9 c5_ore=6 c2_i1=3
|
| 46 |
+
textcraft craft c1_i2 2 c2_i1_12=2 c9_ore=2
|
| 47 |
+
textcraft craft c4_i2 3 c2_i1=2 c1_ore=1
|
| 48 |
+
textcraft craft c4_i2_14 2 c2_i1_22=2 c0_ore=2
|
| 49 |
+
textcraft craft c2_i3_12 8 c4_i1_14=8 c0_i1_20=4
|
| 50 |
+
textcraft craft c1_i3_21 4 c1_i2_21=2 c3_i2_23=4 c3_i1_13=2
|
| 51 |
+
textcraft craft c5_i3 8 c1_i1=4 c2_i2_12=4 c1_i1_11=8
|
| 52 |
+
textcraft craft c7_i3_17 20 c3_i1_23=20 c2_i2_22=10
|
| 53 |
+
textcraft craft c8_i3 2 c3_i2=4 c6_i2_16=4 c0_i1_20=4
|
| 54 |
+
textcraft craft c0_i3 9 c6_i1_16=18 c4_i2_24=18 c1_i1=9
|
| 55 |
+
textcraft craft c9_i3 8 c9_i1_19=8 c3_i1_13=4
|
| 56 |
+
textcraft craft c1_i3_11 3 c5_i2_15=6 c2_i2_22=6
|
| 57 |
+
textcraft craft c0_i3_10 4 c5_i2_15=2 c4_i2_24=2 c2_i2_22=2
|
| 58 |
+
textcraft craft c6_i3 10 c0_i2_20=5 c2_i1=10 c8_i2=10
|
| 59 |
+
textcraft craft c1_i3 6 c6_i1=6 c6_i2_16=6 c8_i1=6
|
| 60 |
+
textcraft craft c3_i3_23 13 c0_i1=26 c3_i1_13=26 c2_i2_12=13
|
| 61 |
+
textcraft craft c2_i3 4 c3_i1_23=8 c9_i2=4 c0_i2_10=4
|
| 62 |
+
textcraft craft c9_i3_19 7 c3_i1_13=14 c8_i2=14 c0_i1_10=7
|
| 63 |
+
textcraft craft c2_i3_22 2 c4_i1_14=1 c4_i2_24=1
|
| 64 |
+
textcraft craft c7_i3 4 c3_i1=2 c8_i1_18=2 c9_i1=2
|
| 65 |
+
textcraft craft c4_i3 4 c2_i1=2 c2_i2=4
|
| 66 |
+
textcraft craft c3_i3_13 2 c6_i2=4 c1_i1_11=4
|
| 67 |
+
textcraft craft c8_i3_18 2 c0_i1_20=4 c4_i2_24=4 c3_i2_13=4
|
| 68 |
+
textcraft craft c3_i3 2 c0_i2_20=1 c1_i2=1
|
| 69 |
+
textcraft craft c5_i3_15 1 c6_i2_16=1 c0_i1_20=2
|
| 70 |
+
textcraft craft c5_i4_15 4 c1_i3_21=2 c5_i3=4
|
| 71 |
+
textcraft craft c6_i4 2 c5_i2=4 c7_i3_17=2 c8_i3=2
|
| 72 |
+
textcraft craft c3_i4_13 4 c2_i2_12=8 c7_i3_17=8 c8_i2=4
|
| 73 |
+
textcraft craft c3_i4 3 c2_i3_12=6 c0_i3=3 c9_i3=3
|
| 74 |
+
textcraft craft c6_i4_16 3 c0_i3_10=3 c6_i3=6 c1_i3=6
|
| 75 |
+
textcraft craft c7_i4 2 c3_i3_23=2 c2_i3=2 c6_i2=2
|
| 76 |
+
textcraft craft c0_i4_10 1 c3_i3_23=2 c7_i3=2 c5_i3=2
|
| 77 |
+
textcraft craft c0_i4_20 2 c7_i3_17=4 c4_i3=4 c9_i2=2
|
| 78 |
+
textcraft craft c0_i4 2 c3_i3_13=2 c3_i3_23=2 c8_i3_18=2
|
| 79 |
+
textcraft craft c8_i4 4 c1_i2_11=4 c9_i3_19=2 c2_i2_22=4
|
| 80 |
+
textcraft craft c2_i4_22 2 c7_i3_17=1 c3_i3=1 c9_i3=1
|
| 81 |
+
textcraft craft c4_i4 2 c0_i3=2 c6_i3=2
|
| 82 |
+
textcraft craft c2_i4_12 2 c3_i3_23=1 c5_i3_15=1
|
| 83 |
+
textcraft craft c2_i4 1 c4_i2=2 c1_i2_11=1
|
| 84 |
+
textcraft craft c1_i4_21 2 c7_i3_17=2 c4_i2_14=1
|
| 85 |
+
textcraft craft c9_i4_19 2 c6_i2_16=1 c0_i3=2 c0_i3_10=1
|
| 86 |
+
textcraft craft c3_i4_23 2 c0_i2_10=2 c9_i3_19=2 c7_i3=1
|
| 87 |
+
textcraft craft c4_i5_14 2 c2_i3_12=2 c5_i4_15=2 c6_i4=2
|
| 88 |
+
textcraft craft c1_i5_11 4 c3_i4=2 c1_i3_11=2
|
| 89 |
+
textcraft craft c0_i5 2 c3_i3_23=2 c9_i3=2
|
| 90 |
+
textcraft craft c8_i5_18 2 c3_i4_13=1 c7_i4=1 c9_i3_19=1
|
| 91 |
+
textcraft craft c0_i5_20 1 c2_i3_22=1 c0_i4_10=1
|
| 92 |
+
textcraft craft c3_i5_23 1 c7_i3_17=1 c5_i4_15=1
|
| 93 |
+
textcraft craft c7_i5_17 2 c3_i3_23=2 c8_i4=2
|
| 94 |
+
textcraft craft c2_i5 2 c8_i4=1 c2_i4_22=1 c2_i4_12=1
|
| 95 |
+
textcraft craft c1_i5 1 c4_i4=1 c9_i4_19=1 c3_i4_23=1
|
| 96 |
+
textcraft craft c4_i6_6_14 2 c4_i5_14=2 c3_i4_13=2
|
| 97 |
+
textcraft craft c5_i6_6 2 c6_i4_16=2 c0_i5=2 c8_i5_18=2
|
| 98 |
+
textcraft craft c1_i6_6 1 c0_i4_20=1 c0_i4=1 c1_i5_11=1
|
| 99 |
+
textcraft craft c1_i6_6_11 1 c2_i4_22=1 c7_i5_17=1 c4_i4=1 c2_i5=1
|
| 100 |
+
textcraft craft c8_i6_6 1 c2_i4=1 c6_i4_16=1 c0_i4_20=1
|
| 101 |
+
textcraft craft c3_i6_6 1 c1_i4_21=1 c1_i5_11=1 c1_i5=1
|
| 102 |
+
textcraft craft c1_i7_7 1 c4_i6_6_14=1 c1_i5_11=1 c5_i6_6=1 c0_i5_20=1
|
| 103 |
+
textcraft craft c4_i7_7_14 1 c1_i6_6=1 c3_i5_23=1 c7_i5_17=1
|
| 104 |
+
textcraft craft c3_i7_7 1 c1_i6_6_11=1 c8_i6_6=1 c4_i6_6_14=1 c3_i6_6=1
|
| 105 |
+
textcraft craft c0_i8_8 1 c1_i7_7=1 c4_i7_7_14=1 c3_i7_7=1 c5_i6_6=1
|
| 106 |
+
textcraft finish 'Crafted 1x c0_i8_8'
|
tasks/textcraft-synth-train-hard-01235/task.toml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.4"
|
| 2 |
+
# The game's action log: a separate verifier receives it at the same path.
|
| 3 |
+
artifacts = ["/app/textcraft/actions.jsonl"]
|
| 4 |
+
|
| 5 |
+
[task]
|
| 6 |
+
name = "textcraft-synth/train-hard-01235"
|
| 7 |
+
description = "TextCraft-Synth: craft the following items: 1x c0_i8_8 (hard, crafting depth 8)"
|
| 8 |
+
keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
|
| 9 |
+
|
| 10 |
+
[metadata]
|
| 11 |
+
environment = "textcraft-synth@1"
|
| 12 |
+
split = "train"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
max_depth = 8
|
| 15 |
+
num_craft_steps = 98
|
| 16 |
+
goal = "Craft the following items: 1x c0_i8_8"
|
| 17 |
+
source_task_id = "textcraft_synth.train.1235"
|
| 18 |
+
env_task_id = "train:1235"
|
| 19 |
+
env_split_task_id = "train-hard:270"
|
| 20 |
+
|
| 21 |
+
[verifier]
|
| 22 |
+
environment_mode = "separate"
|
| 23 |
+
timeout_sec = 180.0
|
| 24 |
+
|
| 25 |
+
[agent]
|
| 26 |
+
timeout_sec = 1620.0
|
| 27 |
+
|
| 28 |
+
[environment]
|
| 29 |
+
network_mode = "no-network"
|
| 30 |
+
cpus = 1
|
| 31 |
+
memory_mb = 2048
|
| 32 |
+
gpus = 0
|
| 33 |
+
build_timeout_sec = 900.0
|
tasks/textcraft-synth-train-hard-01235/tests/Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01235: task.json sha256:f7c798ea978ae305ce70003427d9d063963370395f0d1feafee8088ed3b1bc84
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The same image as the task's environment, so one image serves the agent and the verifier.
|
| 4 |
+
RUN set -eux; \
|
| 5 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 6 |
+
> /usr/local/bin/textcraft; \
|
| 7 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 8 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 10 |
+
rm -rf /var/lib/apt/lists/*
|
| 11 |
+
# The verifier's trusted copies of the grader, the game, the recipes and the task.
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
COPY test.sh textcraft_game.py recipes.json task.json /tests/
|
tasks/textcraft-synth-train-hard-01235/tests/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01235/tests/task.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01235",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 1x c0_i8_8",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"c0_i8_8": 1
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"c3_ore": 97,
|
| 11 |
+
"c2_ore": 41,
|
| 12 |
+
"c9_ore": 230,
|
| 13 |
+
"c0_ore": 30,
|
| 14 |
+
"c5_ore": 268,
|
| 15 |
+
"c8_ore": 111,
|
| 16 |
+
"c4_ore": 114,
|
| 17 |
+
"c6_ore": 155,
|
| 18 |
+
"c7_ore": 170,
|
| 19 |
+
"c1_ore": 48,
|
| 20 |
+
"m0_ore": 2
|
| 21 |
+
},
|
| 22 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 23 |
+
}
|
tasks/textcraft-synth-train-hard-01235/tests/test.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting
|
| 3 |
+
# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The
|
| 4 |
+
# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target
|
| 5 |
+
# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a
|
| 6 |
+
# separate verifier that received the log as an artifact.
|
| 7 |
+
# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that
|
| 8 |
+
# directory; sandboxes leave it unset.
|
| 9 |
+
set -u
|
| 10 |
+
root="${PLATOON_SANDBOX_ROOT:-}"
|
| 11 |
+
tests="$root/tests"
|
| 12 |
+
out="$root/logs/verifier"
|
| 13 |
+
mkdir -p "$out"
|
| 14 |
+
# A fresh verdict: nothing the agent may have left in the verifier's directory counts.
|
| 15 |
+
rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"
|
| 16 |
+
exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/task.json" --recipes "$tests/recipes.json" \
|
| 17 |
+
--root "$root/" --log app/textcraft/actions.jsonl --out "$out"
|
tasks/textcraft-synth-train-hard-01235/tests/textcraft_game.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01244/environment/Dockerfile
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01244: task.json sha256:1a827561edc15a77ef0890b004b466339519a7a9f8c8dc29279c366afc1cf3bf
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the
|
| 4 |
+
# `textcraft` command, which runs the game file below.
|
| 5 |
+
RUN set -eux; \
|
| 6 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 7 |
+
> /usr/local/bin/textcraft; \
|
| 8 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 10 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 11 |
+
rm -rf /var/lib/apt/lists/*
|
| 12 |
+
# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The
|
| 13 |
+
# game keeps its action log next to them.
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
ENV TEXTCRAFT_DIR=/app/textcraft
|
| 16 |
+
COPY textcraft_game.py recipes.json /app/textcraft/
|
| 17 |
+
COPY task.json /app/textcraft/
|
tasks/textcraft-synth-train-hard-01244/environment/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01244/environment/task.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01244",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 1x t6_i7_7",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"t6_i7_7": 1
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"raw_t6": 25,
|
| 11 |
+
"raw_t9": 89,
|
| 12 |
+
"raw_t3": 35,
|
| 13 |
+
"raw_t4": 39,
|
| 14 |
+
"raw_t0": 82,
|
| 15 |
+
"raw_t5": 93,
|
| 16 |
+
"raw_t1": 92,
|
| 17 |
+
"raw_t7": 28,
|
| 18 |
+
"raw_t8": 43,
|
| 19 |
+
"raw_o7": 4,
|
| 20 |
+
"c3_ore": 5,
|
| 21 |
+
"m8_ore": 3
|
| 22 |
+
},
|
| 23 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 24 |
+
}
|
tasks/textcraft-synth-train-hard-01244/environment/textcraft_game.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01244/instruction.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an agent in a crafting game. Your goal is to craft items by combining ingredients.
|
| 2 |
+
You have access to an inventory of existing ingredients, which are sufficient to craft the target items; though, you may need to craft intermediate ingredients first.
|
| 3 |
+
|
| 4 |
+
Note: If you already have one of the target items in your inventory, you should craft the requested number of the target on top of what you already have.
|
| 5 |
+
For example, if you already have 2 wooden_pickaxes but your goal is to craft 3, your inventory should end up with 5 wooden_pickaxes.
|
| 6 |
+
|
| 7 |
+
## Task
|
| 8 |
+
|
| 9 |
+
Craft the following items: 1x t6_i7_7
|
| 10 |
+
|
| 11 |
+
## Actions
|
| 12 |
+
|
| 13 |
+
You act through the `textcraft` command in the shell:
|
| 14 |
+
|
| 15 |
+
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]`
|
| 16 |
+
Craft items using ingredients from your inventory.
|
| 17 |
+
- INGREDIENT=COUNT pairs: the items to consume and how many of each
|
| 18 |
+
- TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count
|
| 19 |
+
- Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
|
| 20 |
+
|
| 21 |
+
2. `textcraft info ITEM [ITEM ...]`
|
| 22 |
+
Get recipe information for items.
|
| 23 |
+
- Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]}
|
| 24 |
+
- crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps
|
| 25 |
+
- Each recipe shows {"ingredients": {...}, "result_count": int}
|
| 26 |
+
- Example: `textcraft info m2_i2 raw_m0`
|
| 27 |
+
|
| 28 |
+
3. `textcraft inventory`
|
| 29 |
+
View your current inventory.
|
| 30 |
+
- Prints JSON {item_name: count}
|
| 31 |
+
|
| 32 |
+
4. `textcraft finish MESSAGE`
|
| 33 |
+
Complete the task.
|
| 34 |
+
- Example: `textcraft finish "Successfully crafted all required items"`
|
| 35 |
+
- The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a
|
| 36 |
+
task that never finishes counts as failed.
|
| 37 |
+
|
| 38 |
+
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.
|
tasks/textcraft-synth-train-hard-01244/solution/solve.sh
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# The reference solution of textcraft-synth-train-hard-01244: the source task's gold trajectory (69 crafts), then finish.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
if ! command -v textcraft >/dev/null 2>&1; then
|
| 5 |
+
# platoon's process provider runs no image, so there is no textcraft command: run the game file itself.
|
| 6 |
+
textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }
|
| 7 |
+
fi
|
| 8 |
+
textcraft craft t8_i1_18 9 raw_t9=6
|
| 9 |
+
textcraft craft t6_i1 12 raw_t3=6
|
| 10 |
+
textcraft craft t6_i1_16 21 raw_t0=7
|
| 11 |
+
textcraft craft t4_i1_24 12 raw_t5=12
|
| 12 |
+
textcraft craft t4_i1_14 3 raw_t1=1
|
| 13 |
+
textcraft craft t0_i1 9 raw_t1=6
|
| 14 |
+
textcraft craft t7_i1 8 raw_t0=8
|
| 15 |
+
textcraft craft t9_i1 6 raw_t7=6
|
| 16 |
+
textcraft craft t1_i1_21 8 raw_t4=2
|
| 17 |
+
textcraft craft t0_i1_10 9 raw_t9=6
|
| 18 |
+
textcraft craft t8_i1 18 raw_t1=9
|
| 19 |
+
textcraft craft t1_i1_11 6 raw_t0=4
|
| 20 |
+
textcraft craft t1_i1 6 raw_t5=6
|
| 21 |
+
textcraft craft t5_i1 4 raw_t1=2
|
| 22 |
+
textcraft craft t2_i1 2 raw_t3=2
|
| 23 |
+
textcraft craft t3_i1_23 4 raw_t6=2
|
| 24 |
+
textcraft craft t2_i1_12 4 raw_t6=2
|
| 25 |
+
textcraft craft t4_i1 12 raw_t8=6
|
| 26 |
+
textcraft craft t3_i1_13 3 raw_t4=2
|
| 27 |
+
textcraft craft t8_i2 9 raw_t6=6 t8_i1_18=3
|
| 28 |
+
textcraft craft t1_i2_11 4 t6_i1=4 raw_t4=4
|
| 29 |
+
textcraft craft t9_i2 9 t6_i1_16=3 t4_i1_24=6
|
| 30 |
+
textcraft craft t6_i2_16 2 t4_i1_14=1 raw_t7=2
|
| 31 |
+
textcraft craft t8_i2_18 6 t0_i1=4 t6_i1=2
|
| 32 |
+
textcraft craft t9_i2_19 3 t7_i1=1 t9_i1=1
|
| 33 |
+
textcraft craft t2_i2 3 raw_t8=2 raw_t1=2
|
| 34 |
+
textcraft craft t3_i2_13 12 t8_i1=12 t6_i1_16=12
|
| 35 |
+
textcraft craft t0_i2_20 3 t1_i1_21=2 t8_i1=2
|
| 36 |
+
textcraft craft t7_i2_17 3 t4_i1_24=2 raw_t8=2
|
| 37 |
+
textcraft craft t2_i2_22 4 t1_i1_11=4 t1_i1=4
|
| 38 |
+
textcraft craft t6_i2 10 t0_i1_10=5 raw_t9=5
|
| 39 |
+
textcraft craft t7_i2 3 t5_i1=1 raw_t7=2
|
| 40 |
+
textcraft craft t4_i2 2 raw_t8=1 raw_t9=1
|
| 41 |
+
textcraft craft t3_i2 3 t2_i1=1 t3_i1_23=1
|
| 42 |
+
textcraft craft t0_i2_10 2 t2_i1_12=2 t1_i1=2
|
| 43 |
+
textcraft craft t5_i2 6 t4_i1=4 t6_i1_16=2
|
| 44 |
+
textcraft craft t1_i2_21 2 t3_i1_13=1 t2_i1_12=1
|
| 45 |
+
textcraft craft t4_i2_14 2 t0_i1=1 t4_i1=2
|
| 46 |
+
textcraft craft t1_i2 3 t7_i1=2 t8_i1_18=1
|
| 47 |
+
textcraft craft t0_i2 2 t4_i1=1 raw_t6=1
|
| 48 |
+
textcraft craft t3_i3_13 3 t1_i2_11=3 t8_i2=6 t9_i2=6
|
| 49 |
+
textcraft craft t4_i3_14 2 t8_i2_18=2 t9_i2_19=2 t9_i2=2
|
| 50 |
+
textcraft craft t1_i3 4 t1_i1_21=4 t0_i1_10=4
|
| 51 |
+
textcraft craft t5_i3_15 2 t6_i1=2 t7_i1=2 t0_i2_20=2
|
| 52 |
+
textcraft craft t1_i3_11 2 t9_i1=4 t7_i2_17=2 t3_i2_13=2
|
| 53 |
+
textcraft craft t5_i3 4 t2_i2_22=4 t6_i2=8 t3_i2_13=8
|
| 54 |
+
textcraft craft t0_i3_10 2 t7_i2=1 t9_i2_19=1
|
| 55 |
+
textcraft craft t8_i3_18 2 t8_i1_18=2 t4_i2=1
|
| 56 |
+
textcraft craft t3_i3 2 t5_i1=2 t6_i2=2
|
| 57 |
+
textcraft craft t6_i3_16 1 t0_i2_10=2 t7_i1=2
|
| 58 |
+
textcraft craft t2_i3_12 1 t0_i1=1 t5_i1=1
|
| 59 |
+
textcraft craft t3_i3_23 2 t1_i2_21=2 t4_i2_14=2 t5_i2=4
|
| 60 |
+
textcraft craft t6_i3 1 t1_i2=2 t0_i2=1
|
| 61 |
+
textcraft craft t3_i4 2 t8_i2=1 t3_i3_13=1 t6_i2_16=1
|
| 62 |
+
textcraft craft t3_i4_13 2 t2_i2=2 t1_i3=4
|
| 63 |
+
textcraft craft t2_i4 1 t8_i2_18=1 t3_i2_13=1 t5_i3_15=2
|
| 64 |
+
textcraft craft t1_i4_11 1 t5_i3=2 t8_i2_18=2 t0_i3_10=2
|
| 65 |
+
textcraft craft t1_i4 2 t8_i3_18=1 t3_i3_13=2
|
| 66 |
+
textcraft craft t5_i4_15 2 t8_i2=1 t5_i3=2
|
| 67 |
+
textcraft craft t8_i4_18 1 t0_i2_20=1 t3_i2=1 t3_i3=2
|
| 68 |
+
textcraft craft t6_i4 2 t5_i2=2 t3_i3_23=2 t6_i3=1
|
| 69 |
+
textcraft craft t2_i5_22 2 t3_i4=1 t4_i3_14=1 t3_i4_13=1
|
| 70 |
+
textcraft craft t1_i5_21 2 t2_i4=1 t1_i3_11=1
|
| 71 |
+
textcraft craft t3_i5_23 1 t1_i4=1 t5_i4_15=1
|
| 72 |
+
textcraft craft t1_i5_11 1 t6_i3_16=1 t1_i3_11=1
|
| 73 |
+
textcraft craft t3_i5 1 t3_i4_13=1 t2_i3_12=1 t6_i4=1
|
| 74 |
+
textcraft craft t0_i6_6 1 t2_i5_22=1 t1_i5_21=1 t1_i4_11=1 t3_i5_23=1
|
| 75 |
+
textcraft craft t8_i6_6 1 t8_i4_18=1 t1_i5_11=1 t3_i5=1
|
| 76 |
+
textcraft craft t6_i7_7 1 t0_i6_6=1 t8_i6_6=1
|
| 77 |
+
textcraft finish 'Crafted 1x t6_i7_7'
|
tasks/textcraft-synth-train-hard-01244/task.toml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.4"
|
| 2 |
+
# The game's action log: a separate verifier receives it at the same path.
|
| 3 |
+
artifacts = ["/app/textcraft/actions.jsonl"]
|
| 4 |
+
|
| 5 |
+
[task]
|
| 6 |
+
name = "textcraft-synth/train-hard-01244"
|
| 7 |
+
description = "TextCraft-Synth: craft the following items: 1x t6_i7_7 (hard, crafting depth 7)"
|
| 8 |
+
keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
|
| 9 |
+
|
| 10 |
+
[metadata]
|
| 11 |
+
environment = "textcraft-synth@1"
|
| 12 |
+
split = "train"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
max_depth = 7
|
| 15 |
+
num_craft_steps = 69
|
| 16 |
+
goal = "Craft the following items: 1x t6_i7_7"
|
| 17 |
+
source_task_id = "textcraft_synth.train.1244"
|
| 18 |
+
env_task_id = "train:1244"
|
| 19 |
+
env_split_task_id = "train-hard:271"
|
| 20 |
+
|
| 21 |
+
[verifier]
|
| 22 |
+
environment_mode = "separate"
|
| 23 |
+
timeout_sec = 180.0
|
| 24 |
+
|
| 25 |
+
[agent]
|
| 26 |
+
timeout_sec = 1320.0
|
| 27 |
+
|
| 28 |
+
[environment]
|
| 29 |
+
network_mode = "no-network"
|
| 30 |
+
cpus = 1
|
| 31 |
+
memory_mb = 2048
|
| 32 |
+
gpus = 0
|
| 33 |
+
build_timeout_sec = 900.0
|
tasks/textcraft-synth-train-hard-01244/tests/Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01244: task.json sha256:1a827561edc15a77ef0890b004b466339519a7a9f8c8dc29279c366afc1cf3bf
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The same image as the task's environment, so one image serves the agent and the verifier.
|
| 4 |
+
RUN set -eux; \
|
| 5 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 6 |
+
> /usr/local/bin/textcraft; \
|
| 7 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 8 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 10 |
+
rm -rf /var/lib/apt/lists/*
|
| 11 |
+
# The verifier's trusted copies of the grader, the game, the recipes and the task.
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
COPY test.sh textcraft_game.py recipes.json task.json /tests/
|
tasks/textcraft-synth-train-hard-01244/tests/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01244/tests/task.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01244",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 1x t6_i7_7",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"t6_i7_7": 1
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"raw_t6": 25,
|
| 11 |
+
"raw_t9": 89,
|
| 12 |
+
"raw_t3": 35,
|
| 13 |
+
"raw_t4": 39,
|
| 14 |
+
"raw_t0": 82,
|
| 15 |
+
"raw_t5": 93,
|
| 16 |
+
"raw_t1": 92,
|
| 17 |
+
"raw_t7": 28,
|
| 18 |
+
"raw_t8": 43,
|
| 19 |
+
"raw_o7": 4,
|
| 20 |
+
"c3_ore": 5,
|
| 21 |
+
"m8_ore": 3
|
| 22 |
+
},
|
| 23 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 24 |
+
}
|
tasks/textcraft-synth-train-hard-01244/tests/test.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting
|
| 3 |
+
# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The
|
| 4 |
+
# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target
|
| 5 |
+
# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a
|
| 6 |
+
# separate verifier that received the log as an artifact.
|
| 7 |
+
# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that
|
| 8 |
+
# directory; sandboxes leave it unset.
|
| 9 |
+
set -u
|
| 10 |
+
root="${PLATOON_SANDBOX_ROOT:-}"
|
| 11 |
+
tests="$root/tests"
|
| 12 |
+
out="$root/logs/verifier"
|
| 13 |
+
mkdir -p "$out"
|
| 14 |
+
# A fresh verdict: nothing the agent may have left in the verifier's directory counts.
|
| 15 |
+
rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"
|
| 16 |
+
exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/task.json" --recipes "$tests/recipes.json" \
|
| 17 |
+
--root "$root/" --log app/textcraft/actions.jsonl --out "$out"
|
tasks/textcraft-synth-train-hard-01244/tests/textcraft_game.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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raft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01257/environment/Dockerfile
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01257: task.json sha256:a9e1c934faa4852940a3182f34993ad42c617eb951c0d3c9421985c714c4a28c
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the
|
| 4 |
+
# `textcraft` command, which runs the game file below.
|
| 5 |
+
RUN set -eux; \
|
| 6 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 7 |
+
> /usr/local/bin/textcraft; \
|
| 8 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 10 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 11 |
+
rm -rf /var/lib/apt/lists/*
|
| 12 |
+
# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The
|
| 13 |
+
# game keeps its action log next to them.
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
ENV TEXTCRAFT_DIR=/app/textcraft
|
| 16 |
+
COPY textcraft_game.py recipes.json /app/textcraft/
|
| 17 |
+
COPY task.json /app/textcraft/
|
tasks/textcraft-synth-train-hard-01257/environment/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01257/environment/task.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01257",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 2x t5_i9_9",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"t5_i9_9": 2
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"raw_t8": 1246,
|
| 11 |
+
"raw_t0": 1372,
|
| 12 |
+
"raw_t3": 654,
|
| 13 |
+
"raw_t9": 844,
|
| 14 |
+
"raw_t1": 1239,
|
| 15 |
+
"raw_t4": 642,
|
| 16 |
+
"raw_t5": 1289,
|
| 17 |
+
"raw_t6": 496,
|
| 18 |
+
"raw_t7": 292,
|
| 19 |
+
"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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01257/instruction.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an agent in a crafting game. Your goal is to craft items by combining ingredients.
|
| 2 |
+
You have access to an inventory of existing ingredients, which are sufficient to craft the target items; though, you may need to craft intermediate ingredients first.
|
| 3 |
+
|
| 4 |
+
Note: If you already have one of the target items in your inventory, you should craft the requested number of the target on top of what you already have.
|
| 5 |
+
For example, if you already have 2 wooden_pickaxes but your goal is to craft 3, your inventory should end up with 5 wooden_pickaxes.
|
| 6 |
+
|
| 7 |
+
## Task
|
| 8 |
+
|
| 9 |
+
Craft the following items: 2x t5_i9_9
|
| 10 |
+
|
| 11 |
+
## Actions
|
| 12 |
+
|
| 13 |
+
You act through the `textcraft` command in the shell:
|
| 14 |
+
|
| 15 |
+
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]`
|
| 16 |
+
Craft items using ingredients from your inventory.
|
| 17 |
+
- INGREDIENT=COUNT pairs: the items to consume and how many of each
|
| 18 |
+
- TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count
|
| 19 |
+
- Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
|
| 20 |
+
|
| 21 |
+
2. `textcraft info ITEM [ITEM ...]`
|
| 22 |
+
Get recipe information for items.
|
| 23 |
+
- Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]}
|
| 24 |
+
- crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps
|
| 25 |
+
- Each recipe shows {"ingredients": {...}, "result_count": int}
|
| 26 |
+
- Example: `textcraft info m2_i2 raw_m0`
|
| 27 |
+
|
| 28 |
+
3. `textcraft inventory`
|
| 29 |
+
View your current inventory.
|
| 30 |
+
- Prints JSON {item_name: count}
|
| 31 |
+
|
| 32 |
+
4. `textcraft finish MESSAGE`
|
| 33 |
+
Complete the task.
|
| 34 |
+
- Example: `textcraft finish "Successfully crafted all required items"`
|
| 35 |
+
- The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a
|
| 36 |
+
task that never finishes counts as failed.
|
| 37 |
+
|
| 38 |
+
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.
|
tasks/textcraft-synth-train-hard-01257/solution/solve.sh
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# The reference solution of textcraft-synth-train-hard-01257: the source task's gold trajectory (113 crafts), then finish.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
if ! command -v textcraft >/dev/null 2>&1; then
|
| 5 |
+
# platoon's process provider runs no image, so there is no textcraft command: run the game file itself.
|
| 6 |
+
textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }
|
| 7 |
+
fi
|
| 8 |
+
textcraft craft t4_i1 104 raw_t8=52
|
| 9 |
+
textcraft craft t6_i1_16 153 raw_t0=51
|
| 10 |
+
textcraft craft t9_i1_19 4 raw_t3=2
|
| 11 |
+
textcraft craft t0_i1_10 63 raw_t9=42
|
| 12 |
+
textcraft craft t8_i1 150 raw_t1=75
|
| 13 |
+
textcraft craft t0_i1 54 raw_t1=36
|
| 14 |
+
textcraft craft t6_i1 96 raw_t3=48
|
| 15 |
+
textcraft craft t3_i1_13 18 raw_t4=12
|
| 16 |
+
textcraft craft t1_i1_11 24 raw_t0=16
|
| 17 |
+
textcraft craft t1_i1 82 raw_t5=82
|
| 18 |
+
textcraft craft t2_i1_22 12 raw_t1=8
|
| 19 |
+
textcraft craft t8_i1_18 63 raw_t9=42
|
| 20 |
+
textcraft craft t4_i1_24 68 raw_t5=68
|
| 21 |
+
textcraft craft t4_i1_14 6 raw_t1=2
|
| 22 |
+
textcraft craft t1_i1_21 76 raw_t4=19
|
| 23 |
+
textcraft craft t2_i1 6 raw_t3=6
|
| 24 |
+
textcraft craft t3_i1_23 8 raw_t6=4
|
| 25 |
+
textcraft craft t5_i1 36 raw_t1=18
|
| 26 |
+
textcraft craft t2_i1_12 46 raw_t6=23
|
| 27 |
+
textcraft craft t7_i1 96 raw_t0=96
|
| 28 |
+
textcraft craft t9_i1 40 raw_t7=40
|
| 29 |
+
textcraft craft t5_i2 69 t4_i1=46 t6_i1_16=23
|
| 30 |
+
textcraft craft t8_i2_18 27 t0_i1=18 t6_i1=9
|
| 31 |
+
textcraft craft t2_i2_22 22 t1_i1_11=22 t1_i1=22
|
| 32 |
+
textcraft craft t8_i2 51 raw_t6=34 t8_i1_18=17
|
| 33 |
+
textcraft craft t1_i2_11 24 t6_i1=24 raw_t4=24
|
| 34 |
+
textcraft craft t9_i2 39 t6_i1_16=13 t4_i1_24=26
|
| 35 |
+
textcraft craft t6_i2_16 8 t4_i1_14=4 raw_t7=8
|
| 36 |
+
textcraft craft t0_i2_20 51 t1_i1_21=34 t8_i1=34
|
| 37 |
+
textcraft craft t3_i2 12 t2_i1=4 t3_i1_23=4
|
| 38 |
+
textcraft craft t6_i2 56 t0_i1_10=28 raw_t9=28
|
| 39 |
+
textcraft craft t0_i2_10 36 t2_i1_12=36 t1_i1=36
|
| 40 |
+
textcraft craft t7_i2_17 24 t4_i1_24=16 raw_t8=16
|
| 41 |
+
textcraft craft t3_i2_13 82 t8_i1=82 t6_i1_16=82
|
| 42 |
+
textcraft craft t2_i2 12 raw_t8=8 raw_t1=8
|
| 43 |
+
textcraft craft t1_i2_21 20 t3_i1_13=10 t2_i1_12=10
|
| 44 |
+
textcraft craft t4_i2_14 20 t0_i1=10 t4_i1=20
|
| 45 |
+
textcraft craft t1_i2 21 t7_i1=14 t8_i1_18=7
|
| 46 |
+
textcraft craft t0_i2 18 t4_i1=9 raw_t6=9
|
| 47 |
+
textcraft craft t7_i2 9 t5_i1=3 raw_t7=6
|
| 48 |
+
textcraft craft t9_i2_19 15 t7_i1=5 t9_i1=5
|
| 49 |
+
textcraft craft t4_i2 18 raw_t8=9 raw_t9=9
|
| 50 |
+
textcraft craft t2_i2_12 3 t6_i1_16=1 raw_t4=1
|
| 51 |
+
textcraft craft t3_i2_23 9 t2_i1_22=6 raw_t5=6
|
| 52 |
+
textcraft craft t0_i3 6 t9_i1_19=3 t0_i1_10=6 t8_i1=6
|
| 53 |
+
textcraft craft t2_i3 2 t3_i1_13=2 t0_i1_10=1 t2_i2_22=1
|
| 54 |
+
textcraft craft t3_i3_13 15 t1_i2_11=15 t8_i2=30 t9_i2=30
|
| 55 |
+
textcraft craft t3_i3 16 t5_i1=16 t6_i2=16
|
| 56 |
+
textcraft craft t6_i3_16 12 t0_i2_10=24 t7_i1=24
|
| 57 |
+
textcraft craft t1_i3_11 15 t9_i1=30 t7_i2_17=15 t3_i2_13=15
|
| 58 |
+
textcraft craft t1_i3 24 t1_i1_21=24 t0_i1_10=24
|
| 59 |
+
textcraft craft t2_i3_12 12 t0_i1=12 t5_i1=12
|
| 60 |
+
textcraft craft t3_i3_23 20 t1_i2_21=20 t4_i2_14=20 t5_i2=40
|
| 61 |
+
textcraft craft t6_i3 10 t1_i2=20 t0_i2=10
|
| 62 |
+
textcraft craft t5_i3_15 42 t6_i1=42 t7_i1=42 t0_i2_20=42
|
| 63 |
+
textcraft craft t9_i3_19 4 t1_i2_11=8 t0_i2=8 t7_i2_17=8
|
| 64 |
+
textcraft craft t5_i3 20 t2_i2_22=20 t6_i2=40 t3_i2_13=40
|
| 65 |
+
textcraft craft t0_i3_10 10 t7_i2=5 t9_i2_19=5
|
| 66 |
+
textcraft craft t8_i3_18 18 t8_i1_18=18 t4_i2=9
|
| 67 |
+
textcraft craft t2_i3_22 12 t8_i2=12 t1_i1=24
|
| 68 |
+
textcraft craft t7_i3 2 t3_i2_13=1 t7_i1=1 t2_i1_22=1
|
| 69 |
+
textcraft craft t9_i3 2 t6_i1=2 t2_i2_12=2 t4_i2=2
|
| 70 |
+
textcraft craft t4_i3_14 8 t8_i2_18=8 t9_i2_19=8 t9_i2=8
|
| 71 |
+
textcraft craft t1_i3_21 4 t7_i2=2 t0_i1_10=2
|
| 72 |
+
textcraft craft t8_i3 2 t4_i2=2 t6_i1_16=4
|
| 73 |
+
textcraft craft t0_i3_20 4 t3_i2=2 t3_i1_13=4 t0_i2_10=4
|
| 74 |
+
textcraft craft t9_i4 3 t5_i2=6 t0_i3=3
|
| 75 |
+
textcraft craft t5_i4 2 t8_i2_18=1 t2_i3=2
|
| 76 |
+
textcraft craft t3_i4 10 t8_i2=5 t3_i3_13=5 t6_i2_16=5
|
| 77 |
+
textcraft craft t8_i4_18 8 t0_i2_20=8 t3_i2=8 t3_i3=16
|
| 78 |
+
textcraft craft t3_i4_13 12 t2_i2=12 t1_i3=24
|
| 79 |
+
textcraft craft t6_i4 16 t5_i2=16 t3_i3_23=16 t6_i3=8
|
| 80 |
+
textcraft craft t2_i4 9 t8_i2_18=9 t3_i2_13=9 t5_i3_15=18
|
| 81 |
+
textcraft craft t1_i4_11 4 t5_i3=8 t8_i2_18=8 t0_i3_10=8
|
| 82 |
+
textcraft craft t0_i4 8 t8_i3_18=16 t3_i2_13=16 t5_i3_15=16
|
| 83 |
+
textcraft craft t0_i4_20 4 t4_i2=4 t0_i2_10=8
|
| 84 |
+
textcraft craft t7_i4 8 t2_i3_22=8 t3_i3_13=4 t1_i3_11=4
|
| 85 |
+
textcraft craft t4_i4 2 t5_i2=2 t7_i3=1
|
| 86 |
+
textcraft craft t2_i4_12 8 t3_i2_23=8 t4_i3_14=8
|
| 87 |
+
textcraft craft t9_i4_19 2 t1_i3_21=2 t6_i2_16=2
|
| 88 |
+
textcraft craft t1_i4 4 t8_i3_18=2 t3_i3_13=4
|
| 89 |
+
textcraft craft t5_i4_15 6 t8_i2=3 t5_i3=6
|
| 90 |
+
textcraft craft t1_i4_21 2 t7_i2=2 t5_i3=2
|
| 91 |
+
textcraft craft t6_i4_16 2 t1_i3_21=1 t0_i3_20=1
|
| 92 |
+
textcraft craft t6_i5 2 t2_i1_22=1 t9_i4=1 t3_i4=1
|
| 93 |
+
textcraft craft t1_i5_11 8 t6_i3_16=8 t1_i3_11=8
|
| 94 |
+
textcraft craft t3_i5 12 t3_i4_13=12 t2_i3_12=12 t6_i4=12
|
| 95 |
+
textcraft craft t9_i5_19 8 t2_i4=4 t9_i3_19=4
|
| 96 |
+
textcraft craft t2_i5 8 t1_i4_11=4 t6_i4=4 t0_i4=4
|
| 97 |
+
textcraft craft t9_i5 8 t0_i4_20=4 t7_i4=4
|
| 98 |
+
textcraft craft t7_i5_17 2 t9_i3=2 t7_i4=2 t8_i1_18=2
|
| 99 |
+
textcraft craft t6_i5_16 8 t2_i4_12=8 t5_i3_15=8 t3_i4=8
|
| 100 |
+
textcraft craft t0_i5_20 2 t9_i4_19=2 t0_i3=2 t0_i4=2
|
| 101 |
+
textcraft craft t3_i5_23 2 t1_i4=2 t5_i4_15=2
|
| 102 |
+
textcraft craft t8_i5_18 4 t5_i3=4 t5_i4_15=4 t6_i3_16=4
|
| 103 |
+
textcraft craft t5_i5_15 2 t0_i3_10=2 t8_i3=2 t0_i3_20=2
|
| 104 |
+
textcraft craft t1_i5_21 2 t2_i4=1 t1_i3_11=1
|
| 105 |
+
textcraft craft t3_i6_6 2 t9_i4=2 t5_i4=2 t6_i5=2
|
| 106 |
+
textcraft craft t8_i6_6 8 t8_i4_18=8 t1_i5_11=8 t3_i5=8
|
| 107 |
+
textcraft craft t3_i6_6_13 4 t2_i4=4 t9_i5_19=4 t2_i5=4
|
| 108 |
+
textcraft craft t2_i6_6_12 2 t9_i5_19=2 t4_i4=2 t0_i4=2
|
| 109 |
+
textcraft craft t1_i6_6_11 2 t7_i4=2 t6_i5_16=2 t0_i5_20=2 t3_i5=2
|
| 110 |
+
textcraft craft t8_i6_6_18 2 t3_i5_23=2 t9_i5=2 t8_i5_18=2 t1_i4_21=2
|
| 111 |
+
textcraft craft t2_i6_6_22 4 t2_i5=4 t6_i5_16=4 t9_i5=4
|
| 112 |
+
textcraft craft t4_i6_6_14 2 t5_i5_15=2 t1_i4=2 t6_i4_16=2
|
| 113 |
+
textcraft craft t0_i7_7 2 t8_i6_6=2 t3_i6_6_13=2
|
| 114 |
+
textcraft craft t0_i7_7_10 2 t9_i5=2 t8_i6_6=2
|
| 115 |
+
textcraft craft t0_i7_7_20 2 t2_i6_6_12=2 t7_i5_17=2 t1_i6_6_11=2
|
| 116 |
+
textcraft craft t8_i7_7_18 2 t3_i6_6_13=2 t4_i6_6_14=2 t9_i5_19=2
|
| 117 |
+
textcraft craft t3_i7_7 2 t2_i6_6_22=2 t1_i5_21=2 t6_i5_16=2 t8_i5_18=2
|
| 118 |
+
textcraft craft t3_i8_8_13 2 t3_i6_6=2 t0_i7_7=2 t0_i7_7_10=2 t8_i6_6=2
|
| 119 |
+
textcraft craft t0_i8_8 2 t8_i6_6_18=2 t2_i6_6_22=2 t8_i7_7_18=2 t3_i7_7=2 t8_i6_6=2
|
| 120 |
+
textcraft craft t5_i9_9 2 t3_i8_8_13=2 t0_i7_7_20=2 t3_i5=2 t0_i8_8=2
|
| 121 |
+
textcraft finish 'Crafted 2x t5_i9_9'
|
tasks/textcraft-synth-train-hard-01257/task.toml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.4"
|
| 2 |
+
# The game's action log: a separate verifier receives it at the same path.
|
| 3 |
+
artifacts = ["/app/textcraft/actions.jsonl"]
|
| 4 |
+
|
| 5 |
+
[task]
|
| 6 |
+
name = "textcraft-synth/train-hard-01257"
|
| 7 |
+
description = "TextCraft-Synth: craft the following items: 2x t5_i9_9 (hard, crafting depth 9)"
|
| 8 |
+
keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
|
| 9 |
+
|
| 10 |
+
[metadata]
|
| 11 |
+
environment = "textcraft-synth@1"
|
| 12 |
+
split = "train"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
max_depth = 9
|
| 15 |
+
num_craft_steps = 113
|
| 16 |
+
goal = "Craft the following items: 2x t5_i9_9"
|
| 17 |
+
source_task_id = "textcraft_synth.train.1257"
|
| 18 |
+
env_task_id = "train:1257"
|
| 19 |
+
env_split_task_id = "train-hard:272"
|
| 20 |
+
|
| 21 |
+
[verifier]
|
| 22 |
+
environment_mode = "separate"
|
| 23 |
+
timeout_sec = 180.0
|
| 24 |
+
|
| 25 |
+
[agent]
|
| 26 |
+
timeout_sec = 1740.0
|
| 27 |
+
|
| 28 |
+
[environment]
|
| 29 |
+
network_mode = "no-network"
|
| 30 |
+
cpus = 1
|
| 31 |
+
memory_mb = 2048
|
| 32 |
+
gpus = 0
|
| 33 |
+
build_timeout_sec = 900.0
|
tasks/textcraft-synth-train-hard-01257/tests/Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01257: task.json sha256:a9e1c934faa4852940a3182f34993ad42c617eb951c0d3c9421985c714c4a28c
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The same image as the task's environment, so one image serves the agent and the verifier.
|
| 4 |
+
RUN set -eux; \
|
| 5 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 6 |
+
> /usr/local/bin/textcraft; \
|
| 7 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 8 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 10 |
+
rm -rf /var/lib/apt/lists/*
|
| 11 |
+
# The verifier's trusted copies of the grader, the game, the recipes and the task.
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
COPY test.sh textcraft_game.py recipes.json task.json /tests/
|
tasks/textcraft-synth-train-hard-01257/tests/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01257/tests/task.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01257",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 2x t5_i9_9",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"t5_i9_9": 2
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"raw_t8": 1246,
|
| 11 |
+
"raw_t0": 1372,
|
| 12 |
+
"raw_t3": 654,
|
| 13 |
+
"raw_t9": 844,
|
| 14 |
+
"raw_t1": 1239,
|
| 15 |
+
"raw_t4": 642,
|
| 16 |
+
"raw_t5": 1289,
|
| 17 |
+
"raw_t6": 496,
|
| 18 |
+
"raw_t7": 292,
|
| 19 |
+
"raw_o5": 1
|
| 20 |
+
},
|
| 21 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 22 |
+
}
|
tasks/textcraft-synth-train-hard-01257/tests/test.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting
|
| 3 |
+
# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The
|
| 4 |
+
# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target
|
| 5 |
+
# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a
|
| 6 |
+
# separate verifier that received the log as an artifact.
|
| 7 |
+
# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that
|
| 8 |
+
# directory; sandboxes leave it unset.
|
| 9 |
+
set -u
|
| 10 |
+
root="${PLATOON_SANDBOX_ROOT:-}"
|
| 11 |
+
tests="$root/tests"
|
| 12 |
+
out="$root/logs/verifier"
|
| 13 |
+
mkdir -p "$out"
|
| 14 |
+
# A fresh verdict: nothing the agent may have left in the verifier's directory counts.
|
| 15 |
+
rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"
|
| 16 |
+
exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/task.json" --recipes "$tests/recipes.json" \
|
| 17 |
+
--root "$root/" --log app/textcraft/actions.jsonl --out "$out"
|
tasks/textcraft-synth-train-hard-01257/tests/textcraft_game.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01267/environment/Dockerfile
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# textcraft-synth-train-hard-01267: task.json sha256:c457dedf046fa498194c7812e5f1006adab42a7095262f3dd45a74eb157bff83
|
| 2 |
+
FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
|
| 3 |
+
# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the
|
| 4 |
+
# `textcraft` command, which runs the game file below.
|
| 5 |
+
RUN set -eux; \
|
| 6 |
+
printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \
|
| 7 |
+
> /usr/local/bin/textcraft; \
|
| 8 |
+
chmod 0755 /usr/local/bin/textcraft; \
|
| 9 |
+
apt-get -o APT::Sandbox::User=root update; \
|
| 10 |
+
apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \
|
| 11 |
+
rm -rf /var/lib/apt/lists/*
|
| 12 |
+
# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The
|
| 13 |
+
# game keeps its action log next to them.
|
| 14 |
+
WORKDIR /app
|
| 15 |
+
ENV TEXTCRAFT_DIR=/app/textcraft
|
| 16 |
+
COPY textcraft_game.py recipes.json /app/textcraft/
|
| 17 |
+
COPY task.json /app/textcraft/
|
tasks/textcraft-synth-train-hard-01267/environment/recipes.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/textcraft-synth-train-hard-01267/environment/task.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"format": "textcraft-task/1",
|
| 3 |
+
"name": "textcraft-synth-train-hard-01267",
|
| 4 |
+
"world": "textcraft-synth",
|
| 5 |
+
"goal": "Craft the following items: 1x a9_i8_8",
|
| 6 |
+
"target_items": {
|
| 7 |
+
"a9_i8_8": 1
|
| 8 |
+
},
|
| 9 |
+
"initial_inventory": {
|
| 10 |
+
"raw_a1": 182,
|
| 11 |
+
"raw_a4": 256,
|
| 12 |
+
"raw_a3": 69,
|
| 13 |
+
"raw_a2": 42,
|
| 14 |
+
"raw_a0": 148,
|
| 15 |
+
"raw_a7": 34,
|
| 16 |
+
"raw_a9": 13,
|
| 17 |
+
"raw_a6": 18,
|
| 18 |
+
"c0_ore": 4,
|
| 19 |
+
"c4_ore": 1
|
| 20 |
+
},
|
| 21 |
+
"recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"
|
| 22 |
+
}
|
tasks/textcraft-synth-train-hard-01267/environment/textcraft_game.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
|
| 2 |
+
|
| 3 |
+
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never imports
|
| 4 |
+
platoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as
|
| 5 |
+
``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, which
|
| 6 |
+
the image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraft
|
| 7 |
+
environments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation text
|
| 8 |
+
and the same success rule.
|
| 9 |
+
|
| 10 |
+
========================================= =================== ===============================================
|
| 11 |
+
command environment tool prints
|
| 12 |
+
========================================= =================== ===============================================
|
| 13 |
+
``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...``
|
| 14 |
+
``textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON
|
| 15 |
+
``textcraft inventory`` ``view_inventory`` the inventory, as JSON
|
| 16 |
+
``textcraft finish MESSAGE`` ``finish`` the message; the episode ends
|
| 17 |
+
========================================= =================== ===============================================
|
| 18 |
+
|
| 19 |
+
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool's
|
| 20 |
+
arguments as JSON values, the way a tool call passes them.
|
| 21 |
+
|
| 22 |
+
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds the
|
| 23 |
+
task (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or
|
| 24 |
+
``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,
|
| 25 |
+
every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool",
|
| 26 |
+
"args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
|
| 27 |
+
|
| 28 |
+
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trusted
|
| 29 |
+
copies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in
|
| 30 |
+
``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (the
|
| 31 |
+
environment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without a
|
| 32 |
+
symbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,
|
| 33 |
+
follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log the
|
| 34 |
+
command could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as in
|
| 35 |
+
the environment.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import argparse
|
| 41 |
+
import errno
|
| 42 |
+
import fcntl
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import os
|
| 46 |
+
import stat
|
| 47 |
+
import sys
|
| 48 |
+
|
| 49 |
+
VERSION = "1.0"
|
| 50 |
+
TASK_FORMAT = "textcraft-task/1"
|
| 51 |
+
RECIPES_FORMAT = "textcraft-recipes/1"
|
| 52 |
+
TASK_FILE = "task.json"
|
| 53 |
+
LOG_FILE = "actions.jsonl"
|
| 54 |
+
RECIPES_FILE = "recipes.json"
|
| 55 |
+
REWARD_FILE = "reward.json"
|
| 56 |
+
VERDICT_FILE = "textcraft-verdict.json"
|
| 57 |
+
LOG_CAP_BYTES = 32 * 1024 * 1024
|
| 58 |
+
CRAFTED = "Successfully crafted"
|
| 59 |
+
# The environment's tools and their arguments, as a log record names them.
|
| 60 |
+
ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}
|
| 61 |
+
READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothing
|
| 62 |
+
COMMANDS = {
|
| 63 |
+
"craft": "craft",
|
| 64 |
+
"info": "get_info",
|
| 65 |
+
"get_info": "get_info",
|
| 66 |
+
"inventory": "view_inventory",
|
| 67 |
+
"view_inventory": "view_inventory",
|
| 68 |
+
"finish": "finish",
|
| 69 |
+
}
|
| 70 |
+
_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
|
| 71 |
+
|
| 72 |
+
USAGE = """\
|
| 73 |
+
usage: textcraft COMMAND [ARGUMENTS]
|
| 74 |
+
|
| 75 |
+
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
|
| 76 |
+
|
| 77 |
+
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...]
|
| 78 |
+
Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's
|
| 79 |
+
result_count; each ingredient's N is its recipe count times COUNT / result_count.
|
| 80 |
+
Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1
|
| 81 |
+
textcraft info ITEM [ITEM ...]
|
| 82 |
+
Recipe information for the items, as a JSON list.
|
| 83 |
+
textcraft inventory
|
| 84 |
+
Your current inventory, as JSON {item_name: count}.
|
| 85 |
+
textcraft finish MESSAGE
|
| 86 |
+
Complete the task with a message saying what you achieved. The task is graded on what your
|
| 87 |
+
inventory gained; no command is accepted after it.
|
| 88 |
+
|
| 89 |
+
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take the
|
| 90 |
+
arguments as JSON. get_info and view_inventory are other names for info and inventory.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------------------------------------------------------------- the world
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Recipe:
|
| 98 |
+
__slots__ = ("result_count", "ingredients")
|
| 99 |
+
|
| 100 |
+
def __init__(self, result_count, ingredients):
|
| 101 |
+
self.result_count = result_count
|
| 102 |
+
self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class RecipeBook:
|
| 106 |
+
"""A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
|
| 107 |
+
|
| 108 |
+
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items,
|
| 109 |
+
every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, data, sha256=None):
|
| 113 |
+
if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT:
|
| 114 |
+
raise ValueError("not a %s file" % RECIPES_FORMAT)
|
| 115 |
+
self.name = data["name"]
|
| 116 |
+
self.sha256 = sha256
|
| 117 |
+
self.recipes = {
|
| 118 |
+
item: [
|
| 119 |
+
Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]})
|
| 120 |
+
for recipe in recipes
|
| 121 |
+
]
|
| 122 |
+
for item, recipes in data["recipes"].items()
|
| 123 |
+
}
|
| 124 |
+
self.base_items = frozenset(data["base_items"])
|
| 125 |
+
self.depths = dict(data["depths"])
|
| 126 |
+
self.tags = {tag: list(items) for tag, items in data["tags"].items()}
|
| 127 |
+
|
| 128 |
+
@classmethod
|
| 129 |
+
def load(cls, path):
|
| 130 |
+
with open(path, "rb") as handle:
|
| 131 |
+
raw = handle.read()
|
| 132 |
+
return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
|
| 133 |
+
|
| 134 |
+
def get_recipes_for_item(self, item):
|
| 135 |
+
return self.recipes.get(item, [])
|
| 136 |
+
|
| 137 |
+
def can_craft(self, item):
|
| 138 |
+
return item in self.recipes
|
| 139 |
+
|
| 140 |
+
def is_base_item(self, item):
|
| 141 |
+
return item in self.base_items
|
| 142 |
+
|
| 143 |
+
def get_crafting_depth(self, item):
|
| 144 |
+
return self.depths.get(item, 0)
|
| 145 |
+
|
| 146 |
+
def get_items_for_tag(self, tag):
|
| 147 |
+
return list(self.tags.get(tag, []))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def load_task(path):
|
| 151 |
+
"""A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
|
| 152 |
+
|
| 153 |
+
with open(path, "rb") as handle:
|
| 154 |
+
task = json.loads(handle.read().decode("utf-8"))
|
| 155 |
+
if not isinstance(task, dict) or task.get("format") != TASK_FORMAT:
|
| 156 |
+
raise ValueError("%s is not a %s file" % (path, TASK_FORMAT))
|
| 157 |
+
for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"):
|
| 158 |
+
if key not in task:
|
| 159 |
+
raise ValueError("%s has no %r" % (path, key))
|
| 160 |
+
return task
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ---------------------------------------------------------------------------------------------------- the game
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class Game:
|
| 167 |
+
"""One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, book, task):
|
| 170 |
+
self.book = book
|
| 171 |
+
self.goal = task["goal"]
|
| 172 |
+
self.target_items = dict(task["target_items"])
|
| 173 |
+
self.inventory = dict(task["initial_inventory"])
|
| 174 |
+
self.initial_inventory = dict(self.inventory)
|
| 175 |
+
self.finished = False
|
| 176 |
+
self.score = 0.0
|
| 177 |
+
self.reward_misc = {}
|
| 178 |
+
self.crafts = 0 # successful crafts
|
| 179 |
+
|
| 180 |
+
def call(self, tool, args):
|
| 181 |
+
"""Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
|
| 182 |
+
|
| 183 |
+
if tool == "craft":
|
| 184 |
+
text = self.craft(args["ingredients"], args["target"])
|
| 185 |
+
self.crafts += text.startswith(CRAFTED)
|
| 186 |
+
return text
|
| 187 |
+
if tool == "get_info":
|
| 188 |
+
return json.dumps(self.get_info(args["items"]))
|
| 189 |
+
if tool == "view_inventory":
|
| 190 |
+
return json.dumps(dict(self.inventory))
|
| 191 |
+
if tool == "finish":
|
| 192 |
+
self.score, self.reward_misc = self.evaluate(args["message"])
|
| 193 |
+
self.finished = True
|
| 194 |
+
return args["message"]
|
| 195 |
+
raise ValueError("unknown tool %r" % (tool,))
|
| 196 |
+
|
| 197 |
+
def craft(self, ingredients, target):
|
| 198 |
+
"""``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
|
| 199 |
+
|
| 200 |
+
if not isinstance(ingredients, dict):
|
| 201 |
+
return f"Error: ingredients must be a dict, got {type(ingredients).__name__}"
|
| 202 |
+
if not isinstance(target, (tuple, list)) or len(target) != 2:
|
| 203 |
+
return "Error: target must be a tuple of (item_name, count)"
|
| 204 |
+
target_item, target_count = target
|
| 205 |
+
if not isinstance(target_item, str):
|
| 206 |
+
return f"Error: target item must be a string, got {type(target_item).__name__}"
|
| 207 |
+
if not isinstance(target_count, int):
|
| 208 |
+
return f"Error: target count must be an int, got {type(target_count).__name__}"
|
| 209 |
+
if target_count <= 0:
|
| 210 |
+
return f"Error: target count must be positive, got {target_count}"
|
| 211 |
+
for ing_item, ing_count in ingredients.items():
|
| 212 |
+
if not isinstance(ing_item, str):
|
| 213 |
+
return f"Error: ingredient name must be a string, got {type(ing_item).__name__}"
|
| 214 |
+
if not isinstance(ing_count, int):
|
| 215 |
+
return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}"
|
| 216 |
+
if ing_count <= 0:
|
| 217 |
+
return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
|
| 218 |
+
|
| 219 |
+
book = self.book
|
| 220 |
+
recipes = book.get_recipes_for_item(target_item)
|
| 221 |
+
if not recipes:
|
| 222 |
+
return f"Error: No recipe found for {target_item}"
|
| 223 |
+
|
| 224 |
+
errors = []
|
| 225 |
+
for recipe_idx, recipe in enumerate(recipes):
|
| 226 |
+
if target_count % recipe.result_count != 0:
|
| 227 |
+
errors.append(
|
| 228 |
+
f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible "
|
| 229 |
+
f"by recipe result count {recipe.result_count}"
|
| 230 |
+
)
|
| 231 |
+
continue
|
| 232 |
+
num_crafts = target_count // recipe.result_count
|
| 233 |
+
|
| 234 |
+
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item
|
| 235 |
+
recipe_error = None
|
| 236 |
+
for recipe_ing, recipe_count in recipe.ingredients.items():
|
| 237 |
+
total_required = recipe_count * num_crafts
|
| 238 |
+
if recipe_ing.startswith("tag:"):
|
| 239 |
+
satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", ""))
|
| 240 |
+
provided = next(
|
| 241 |
+
(
|
| 242 |
+
item
|
| 243 |
+
for item, count in ingredients.items()
|
| 244 |
+
if item in satisfying_items and count == total_required
|
| 245 |
+
),
|
| 246 |
+
None,
|
| 247 |
+
)
|
| 248 |
+
if provided is None:
|
| 249 |
+
recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}"
|
| 250 |
+
break
|
| 251 |
+
ingredient_mapping[recipe_ing] = provided
|
| 252 |
+
else:
|
| 253 |
+
if recipe_ing not in ingredients:
|
| 254 |
+
recipe_error = f"Missing required ingredient {recipe_ing}"
|
| 255 |
+
break
|
| 256 |
+
if ingredients[recipe_ing] != total_required:
|
| 257 |
+
recipe_error = (
|
| 258 |
+
f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}"
|
| 259 |
+
)
|
| 260 |
+
break
|
| 261 |
+
ingredient_mapping[recipe_ing] = recipe_ing
|
| 262 |
+
if recipe_error:
|
| 263 |
+
errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}")
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()]
|
| 267 |
+
if extra_ingredients:
|
| 268 |
+
errors.append(
|
| 269 |
+
f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}"
|
| 270 |
+
)
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
missing = []
|
| 274 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 275 |
+
required = recipe.ingredients[recipe_ing] * num_crafts
|
| 276 |
+
available = self.inventory.get(provided_ing, 0)
|
| 277 |
+
if available < required:
|
| 278 |
+
missing.append(f"{provided_ing}: need {required}, have {available}")
|
| 279 |
+
if missing:
|
| 280 |
+
errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}")
|
| 281 |
+
continue
|
| 282 |
+
|
| 283 |
+
for recipe_ing, provided_ing in ingredient_mapping.items():
|
| 284 |
+
self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts
|
| 285 |
+
if self.inventory[provided_ing] <= 0:
|
| 286 |
+
del self.inventory[provided_ing]
|
| 287 |
+
crafted_count = recipe.result_count * num_crafts
|
| 288 |
+
self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count
|
| 289 |
+
return f"Successfully crafted {crafted_count} {target_item}(s)"
|
| 290 |
+
|
| 291 |
+
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
|
| 292 |
+
|
| 293 |
+
def get_info(self, items):
|
| 294 |
+
"""``TextCraftEnvironment._get_info``."""
|
| 295 |
+
|
| 296 |
+
book = self.book
|
| 297 |
+
results = []
|
| 298 |
+
for item in items:
|
| 299 |
+
info = {
|
| 300 |
+
"item": item,
|
| 301 |
+
"can_craft": book.can_craft(item),
|
| 302 |
+
"is_base": book.is_base_item(item),
|
| 303 |
+
"in_inventory": self.inventory.get(item, 0),
|
| 304 |
+
"crafting_depth": book.get_crafting_depth(item),
|
| 305 |
+
"recipes": [],
|
| 306 |
+
}
|
| 307 |
+
if info["can_craft"]:
|
| 308 |
+
for recipe in book.get_recipes_for_item(item):
|
| 309 |
+
expanded = {}
|
| 310 |
+
for ing, count in recipe.ingredients.items():
|
| 311 |
+
if ing.startswith("tag:"):
|
| 312 |
+
expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])}
|
| 313 |
+
else:
|
| 314 |
+
expanded[ing] = count
|
| 315 |
+
info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count})
|
| 316 |
+
results.append(info)
|
| 317 |
+
return results
|
| 318 |
+
|
| 319 |
+
def evaluate(self, finish_message):
|
| 320 |
+
"""``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish
|
| 321 |
+
message is not empty."""
|
| 322 |
+
|
| 323 |
+
reward_misc = {}
|
| 324 |
+
score = 0.0
|
| 325 |
+
if finish_message:
|
| 326 |
+
if not self.target_items:
|
| 327 |
+
return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0}
|
| 328 |
+
missing = {
|
| 329 |
+
item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0))
|
| 330 |
+
for item, required in self.target_items.items()
|
| 331 |
+
if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required
|
| 332 |
+
}
|
| 333 |
+
reward_misc["success"] = not missing
|
| 334 |
+
if missing:
|
| 335 |
+
reward_misc["missing_items"] = missing
|
| 336 |
+
else:
|
| 337 |
+
score = 1.0
|
| 338 |
+
reward_misc["target_items"] = dict(self.target_items)
|
| 339 |
+
reward_misc["initial_inventory"] = dict(self.initial_inventory)
|
| 340 |
+
reward_misc["final_inventory"] = dict(self.inventory)
|
| 341 |
+
else:
|
| 342 |
+
reward_misc["success"] = False
|
| 343 |
+
reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached"
|
| 344 |
+
reward_misc["reward/success"] = score
|
| 345 |
+
return score, reward_misc
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------------------------------- the log
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class LogError(ValueError):
|
| 352 |
+
"""An action log the game could not have written: its replay stops there."""
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _unique_pairs(pairs):
|
| 356 |
+
found = {}
|
| 357 |
+
for key, value in pairs:
|
| 358 |
+
if key in found:
|
| 359 |
+
raise ValueError("duplicate key %r" % (key,))
|
| 360 |
+
found[key] = value
|
| 361 |
+
return found
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _no_constant(name):
|
| 365 |
+
raise ValueError("%s is not a JSON number" % name)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _finite_float(text):
|
| 369 |
+
value = float(text)
|
| 370 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 371 |
+
raise ValueError("%s is out of range" % text)
|
| 372 |
+
return value
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def parse_json(text):
|
| 376 |
+
"""Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value
|
| 377 |
+
it returns can be written back to the log."""
|
| 378 |
+
|
| 379 |
+
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def encode_record(seq, tool, args, ok=None):
|
| 383 |
+
"""A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
|
| 384 |
+
|
| 385 |
+
record = {"seq": seq, "tool": tool, "args": args}
|
| 386 |
+
if tool == "craft":
|
| 387 |
+
record["ok"] = bool(ok)
|
| 388 |
+
return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def check_arguments(tool, args):
|
| 392 |
+
"""``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
|
| 393 |
+
|
| 394 |
+
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]):
|
| 395 |
+
raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none"))
|
| 396 |
+
if tool == "get_info" and (
|
| 397 |
+
not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"])
|
| 398 |
+
):
|
| 399 |
+
raise ValueError("get_info takes a list of item names")
|
| 400 |
+
if tool == "finish" and not isinstance(args["message"], str):
|
| 401 |
+
raise ValueError("finish takes a message string")
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _record(line, seq):
|
| 405 |
+
try:
|
| 406 |
+
record = parse_json(line.decode("utf-8"))
|
| 407 |
+
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
|
| 408 |
+
raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None
|
| 409 |
+
if not isinstance(record, dict):
|
| 410 |
+
raise LogError("record %d is not a JSON object" % seq)
|
| 411 |
+
tool = record.get("tool")
|
| 412 |
+
if not isinstance(tool, str) or tool not in ARGUMENTS:
|
| 413 |
+
raise LogError("record %d names no tool of the game: %r" % (seq, tool))
|
| 414 |
+
keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"}
|
| 415 |
+
if set(record) != keys:
|
| 416 |
+
raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys)))
|
| 417 |
+
if type(record["seq"]) is not int or record["seq"] != seq:
|
| 418 |
+
raise LogError("record %d is numbered %r" % (seq, record["seq"]))
|
| 419 |
+
try:
|
| 420 |
+
check_arguments(tool, record["args"])
|
| 421 |
+
except ValueError as exc:
|
| 422 |
+
raise LogError("record %d: %s" % (seq, exc)) from None
|
| 423 |
+
if tool == "craft" and not isinstance(record["ok"], bool):
|
| 424 |
+
raise LogError("record %d: ok must be true or false" % seq)
|
| 425 |
+
return tool, record["args"], record.get("ok")
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def replay(game, data):
|
| 429 |
+
"""Apply a log's records to ``game``; how many there were. LogError at the first record the game could not
|
| 430 |
+
have written: the replay stops there.
|
| 431 |
+
|
| 432 |
+
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have
|
| 433 |
+
their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds
|
| 434 |
+
and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
|
| 435 |
+
|
| 436 |
+
if not data:
|
| 437 |
+
return 0
|
| 438 |
+
if not data.endswith(b"\n"):
|
| 439 |
+
raise LogError("the last record does not end with a newline")
|
| 440 |
+
seq = start = 0
|
| 441 |
+
while start < len(data):
|
| 442 |
+
end = data.index(b"\n", start)
|
| 443 |
+
seq += 1
|
| 444 |
+
if game.finished:
|
| 445 |
+
raise LogError("record %d follows finish" % seq)
|
| 446 |
+
tool, args, ok = _record(data[start:end], seq)
|
| 447 |
+
start = end + 1
|
| 448 |
+
if tool in READ_ONLY:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
text = game.call(tool, args)
|
| 452 |
+
except Exception as exc: # arguments no command writes
|
| 453 |
+
raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None
|
| 454 |
+
if tool == "craft" and text.startswith(CRAFTED) != ok:
|
| 455 |
+
claim = "succeeded" if ok else "failed"
|
| 456 |
+
raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text))
|
| 457 |
+
return seq
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# ---------------------------------------------------------------------------------------------------- the command
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class UsageError(ValueError):
|
| 464 |
+
pass
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Result:
|
| 468 |
+
"""What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over),
|
| 469 |
+
2 a usage error (nothing was run or logged), 3 the task cannot be played."""
|
| 470 |
+
|
| 471 |
+
def __init__(self, code, out="", err=""):
|
| 472 |
+
self.code = code
|
| 473 |
+
self.out = out
|
| 474 |
+
self.err = err
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def parse_command(argv):
|
| 478 |
+
"""``(tool, args)`` of a command line; UsageError when it is not one."""
|
| 479 |
+
|
| 480 |
+
if not argv:
|
| 481 |
+
raise UsageError("no command")
|
| 482 |
+
tool = COMMANDS.get(argv[0])
|
| 483 |
+
if tool is None:
|
| 484 |
+
raise UsageError("unknown command %r" % argv[0])
|
| 485 |
+
rest = argv[1:]
|
| 486 |
+
if tool == "craft":
|
| 487 |
+
if rest[:1] == ["--json"]:
|
| 488 |
+
if len(rest) != 2:
|
| 489 |
+
raise UsageError("craft --json takes one JSON object")
|
| 490 |
+
args = _json_argument(rest[1])
|
| 491 |
+
if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]:
|
| 492 |
+
raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}')
|
| 493 |
+
return tool, args
|
| 494 |
+
if len(rest) < 2:
|
| 495 |
+
raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...")
|
| 496 |
+
ingredients = {}
|
| 497 |
+
for word in rest[2:]:
|
| 498 |
+
name, sep, count = word.rpartition("=")
|
| 499 |
+
if not sep or not name:
|
| 500 |
+
raise UsageError("ingredients are INGREDIENT=N, got %r" % word)
|
| 501 |
+
if name in ingredients:
|
| 502 |
+
raise UsageError("ingredient %r is given twice" % name)
|
| 503 |
+
ingredients[name] = _integer(count, "the count of %s" % name)
|
| 504 |
+
return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]}
|
| 505 |
+
if tool == "get_info":
|
| 506 |
+
if rest[:1] == ["--json"]:
|
| 507 |
+
if len(rest) != 2:
|
| 508 |
+
raise UsageError("info --json takes one JSON list")
|
| 509 |
+
items = _json_argument(rest[1])
|
| 510 |
+
else:
|
| 511 |
+
items = list(rest)
|
| 512 |
+
args = {"items": items}
|
| 513 |
+
elif tool == "view_inventory":
|
| 514 |
+
if rest:
|
| 515 |
+
raise UsageError("inventory takes no arguments")
|
| 516 |
+
args = {}
|
| 517 |
+
else:
|
| 518 |
+
if not rest:
|
| 519 |
+
raise UsageError("finish takes a MESSAGE saying what you achieved")
|
| 520 |
+
args = {"message": " ".join(rest)}
|
| 521 |
+
try:
|
| 522 |
+
check_arguments(tool, args)
|
| 523 |
+
except ValueError as exc:
|
| 524 |
+
raise UsageError(str(exc)) from None
|
| 525 |
+
return tool, args
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _json_argument(text):
|
| 529 |
+
try:
|
| 530 |
+
return parse_json(text)
|
| 531 |
+
except (ValueError, RecursionError) as exc:
|
| 532 |
+
raise UsageError("not valid JSON: %s" % exc) from None
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _integer(text, what):
|
| 536 |
+
try:
|
| 537 |
+
return int(text)
|
| 538 |
+
except ValueError:
|
| 539 |
+
raise UsageError("%s must be an integer, got %r" % (what, text)) from None
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def default_directory():
|
| 543 |
+
return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run(argv, directory=None, recipes=None):
|
| 547 |
+
"""Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's
|
| 548 |
+
directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's
|
| 549 |
+
``recipes.json``)."""
|
| 550 |
+
|
| 551 |
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
| 552 |
+
return Result(0 if argv else 2, USAGE)
|
| 553 |
+
if argv[0] == "--version":
|
| 554 |
+
return Result(0, "textcraft %s" % VERSION)
|
| 555 |
+
try:
|
| 556 |
+
tool, args = parse_command(argv)
|
| 557 |
+
except UsageError as exc:
|
| 558 |
+
return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE))
|
| 559 |
+
directory = directory or default_directory()
|
| 560 |
+
try:
|
| 561 |
+
task = load_task(os.path.join(directory, TASK_FILE))
|
| 562 |
+
book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE))
|
| 563 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 564 |
+
return Result(3, err="textcraft: cannot load the task: %s" % exc)
|
| 565 |
+
if task["recipes_sha256"] != book.sha256:
|
| 566 |
+
return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256)
|
| 567 |
+
path = os.path.join(directory, LOG_FILE)
|
| 568 |
+
try:
|
| 569 |
+
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 570 |
+
except OSError as exc:
|
| 571 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 572 |
+
return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why))
|
| 573 |
+
try:
|
| 574 |
+
try:
|
| 575 |
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
| 576 |
+
except OSError:
|
| 577 |
+
pass # a file system without locks: commands are not expected to overlap
|
| 578 |
+
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
| 579 |
+
return Result(3, err="textcraft: the action log %s is not a regular file" % path)
|
| 580 |
+
data = _read_all(fd)
|
| 581 |
+
game = Game(book, task)
|
| 582 |
+
try:
|
| 583 |
+
seq = replay(game, data) + 1
|
| 584 |
+
except LogError as exc:
|
| 585 |
+
return Result(
|
| 586 |
+
3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc)
|
| 587 |
+
)
|
| 588 |
+
if game.finished:
|
| 589 |
+
return Result(
|
| 590 |
+
1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it"
|
| 591 |
+
)
|
| 592 |
+
try:
|
| 593 |
+
text = game.call(tool, args)
|
| 594 |
+
except Exception as exc:
|
| 595 |
+
return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc))
|
| 596 |
+
ok = text.startswith(CRAFTED)
|
| 597 |
+
line = encode_record(seq, tool, args, ok)
|
| 598 |
+
if len(data) + len(line) > LOG_CAP_BYTES:
|
| 599 |
+
return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES)
|
| 600 |
+
_write_all(fd, line)
|
| 601 |
+
finally:
|
| 602 |
+
os.close(fd)
|
| 603 |
+
return Result(1 if tool == "craft" and not ok else 0, text)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _read_all(fd):
|
| 607 |
+
os.lseek(fd, 0, os.SEEK_SET)
|
| 608 |
+
chunks = []
|
| 609 |
+
while True:
|
| 610 |
+
chunk = os.read(fd, 1 << 20)
|
| 611 |
+
if not chunk:
|
| 612 |
+
return b"".join(chunks)
|
| 613 |
+
chunks.append(chunk)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _write_all(fd, data):
|
| 617 |
+
view = memoryview(data)
|
| 618 |
+
while view:
|
| 619 |
+
view = view[os.write(fd, view) :]
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# ---------------------------------------------------------------------------------------------------- the verifier
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def read_untrusted(root, relative, cap=LOG_CAP_BYTES):
|
| 626 |
+
"""The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does
|
| 627 |
+
not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
|
| 628 |
+
|
| 629 |
+
parts = [part for part in relative.split("/") if part not in ("", ".")]
|
| 630 |
+
if not parts or ".." in parts:
|
| 631 |
+
raise ValueError("%r is not a path below the root" % relative)
|
| 632 |
+
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC)
|
| 633 |
+
try:
|
| 634 |
+
for part in parts[:-1]:
|
| 635 |
+
try:
|
| 636 |
+
below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory)
|
| 637 |
+
except FileNotFoundError:
|
| 638 |
+
return None
|
| 639 |
+
except OSError as exc:
|
| 640 |
+
raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror))
|
| 641 |
+
os.close(directory)
|
| 642 |
+
directory = below
|
| 643 |
+
try:
|
| 644 |
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory)
|
| 645 |
+
except FileNotFoundError:
|
| 646 |
+
return None
|
| 647 |
+
except OSError as exc:
|
| 648 |
+
why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror
|
| 649 |
+
raise LogError("cannot open the action log: %s" % why)
|
| 650 |
+
finally:
|
| 651 |
+
os.close(directory)
|
| 652 |
+
try:
|
| 653 |
+
info = os.fstat(fd)
|
| 654 |
+
if not stat.S_ISREG(info.st_mode):
|
| 655 |
+
raise LogError("the action log is not a regular file")
|
| 656 |
+
if info.st_size > cap:
|
| 657 |
+
raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap))
|
| 658 |
+
chunks, total = [], 0
|
| 659 |
+
while total <= cap:
|
| 660 |
+
chunk = os.read(fd, min(1 << 20, cap + 1 - total))
|
| 661 |
+
if not chunk:
|
| 662 |
+
break
|
| 663 |
+
chunks.append(chunk)
|
| 664 |
+
total += len(chunk)
|
| 665 |
+
if total > cap:
|
| 666 |
+
raise LogError("the action log holds more than %d bytes" % cap)
|
| 667 |
+
return b"".join(chunks)
|
| 668 |
+
finally:
|
| 669 |
+
os.close(fd)
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
def verify(task_path, recipes_path, root, log, out=None):
|
| 673 |
+
"""Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why).
|
| 674 |
+
Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
|
| 675 |
+
|
| 676 |
+
task = load_task(task_path)
|
| 677 |
+
book = RecipeBook.load(recipes_path)
|
| 678 |
+
if task["recipes_sha256"] != book.sha256:
|
| 679 |
+
raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"]))
|
| 680 |
+
game = Game(book, task)
|
| 681 |
+
verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False}
|
| 682 |
+
try:
|
| 683 |
+
data = read_untrusted(root, log)
|
| 684 |
+
if data is None:
|
| 685 |
+
verdict["reason"] = "no action log: no textcraft command ran"
|
| 686 |
+
else:
|
| 687 |
+
verdict["log_bytes"] = len(data)
|
| 688 |
+
verdict["records"] = replay(game, data)
|
| 689 |
+
verdict["crafts"] = game.crafts
|
| 690 |
+
verdict["finished"] = game.finished
|
| 691 |
+
if not game.finished:
|
| 692 |
+
verdict["reason"] = "the episode did not end with textcraft finish"
|
| 693 |
+
elif game.score >= 1.0:
|
| 694 |
+
verdict["reward"] = 1.0
|
| 695 |
+
verdict["reason"] = "finished with every target crafted"
|
| 696 |
+
elif game.reward_misc.get("missing_items"):
|
| 697 |
+
verdict["reason"] = "finished without every target crafted"
|
| 698 |
+
verdict["missing_items"] = game.reward_misc["missing_items"]
|
| 699 |
+
else:
|
| 700 |
+
verdict["reason"] = "finished with an empty message"
|
| 701 |
+
except LogError as exc:
|
| 702 |
+
verdict["reason"] = "the action log is not one the game wrote: %s" % exc
|
| 703 |
+
if out is not None:
|
| 704 |
+
_write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n")
|
| 705 |
+
_write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n")
|
| 706 |
+
return verdict
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def _write_new(directory, name, text):
|
| 710 |
+
"""Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was
|
| 711 |
+
there."""
|
| 712 |
+
|
| 713 |
+
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid()))
|
| 714 |
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644)
|
| 715 |
+
try:
|
| 716 |
+
_write_all(fd, text.encode("utf-8"))
|
| 717 |
+
os.fsync(fd)
|
| 718 |
+
finally:
|
| 719 |
+
os.close(fd)
|
| 720 |
+
os.replace(temporary, os.path.join(directory, name))
|
| 721 |
+
|
| 722 |
+
|
| 723 |
+
def verify_main(argv):
|
| 724 |
+
parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.")
|
| 725 |
+
parser.add_argument("--task", required=True, help="the trusted task.json")
|
| 726 |
+
parser.add_argument("--recipes", required=True, help="the trusted recipes.json")
|
| 727 |
+
parser.add_argument("--root", required=True, help="the sandbox root the log path is below")
|
| 728 |
+
parser.add_argument("--log", required=True, help="the log's path below the root")
|
| 729 |
+
parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)")
|
| 730 |
+
options = parser.parse_args(argv)
|
| 731 |
+
try:
|
| 732 |
+
verdict = verify(options.task, options.recipes, options.root, options.log, options.out)
|
| 733 |
+
except (OSError, ValueError, KeyError) as exc:
|
| 734 |
+
print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr)
|
| 735 |
+
return 1
|
| 736 |
+
print(
|
| 737 |
+
"reward %g: %s (%d records, %d crafts)"
|
| 738 |
+
% (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"])
|
| 739 |
+
)
|
| 740 |
+
return 0
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def main(argv=None):
|
| 744 |
+
argv = list(sys.argv[1:] if argv is None else argv)
|
| 745 |
+
if argv[:1] == ["verify"]:
|
| 746 |
+
return verify_main(argv[1:])
|
| 747 |
+
result = run(argv)
|
| 748 |
+
if result.out:
|
| 749 |
+
print(result.out)
|
| 750 |
+
if result.err:
|
| 751 |
+
print(result.err, file=sys.stderr)
|
| 752 |
+
return result.code
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
if __name__ == "__main__":
|
| 756 |
+
sys.exit(main())
|
tasks/textcraft-synth-train-hard-01267/instruction.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are an agent in a crafting game. Your goal is to craft items by combining ingredients.
|
| 2 |
+
You have access to an inventory of existing ingredients, which are sufficient to craft the target items; though, you may need to craft intermediate ingredients first.
|
| 3 |
+
|
| 4 |
+
Note: If you already have one of the target items in your inventory, you should craft the requested number of the target on top of what you already have.
|
| 5 |
+
For example, if you already have 2 wooden_pickaxes but your goal is to craft 3, your inventory should end up with 5 wooden_pickaxes.
|
| 6 |
+
|
| 7 |
+
## Task
|
| 8 |
+
|
| 9 |
+
Craft the following items: 1x a9_i8_8
|
| 10 |
+
|
| 11 |
+
## Actions
|
| 12 |
+
|
| 13 |
+
You act through the `textcraft` command in the shell:
|
| 14 |
+
|
| 15 |
+
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]`
|
| 16 |
+
Craft items using ingredients from your inventory.
|
| 17 |
+
- INGREDIENT=COUNT pairs: the items to consume and how many of each
|
| 18 |
+
- TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count
|
| 19 |
+
- Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
|
| 20 |
+
|
| 21 |
+
2. `textcraft info ITEM [ITEM ...]`
|
| 22 |
+
Get recipe information for items.
|
| 23 |
+
- Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]}
|
| 24 |
+
- crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps
|
| 25 |
+
- Each recipe shows {"ingredients": {...}, "result_count": int}
|
| 26 |
+
- Example: `textcraft info m2_i2 raw_m0`
|
| 27 |
+
|
| 28 |
+
3. `textcraft inventory`
|
| 29 |
+
View your current inventory.
|
| 30 |
+
- Prints JSON {item_name: count}
|
| 31 |
+
|
| 32 |
+
4. `textcraft finish MESSAGE`
|
| 33 |
+
Complete the task.
|
| 34 |
+
- Example: `textcraft finish "Successfully crafted all required items"`
|
| 35 |
+
- The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a
|
| 36 |
+
task that never finishes counts as failed.
|
| 37 |
+
|
| 38 |
+
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.
|
tasks/textcraft-synth-train-hard-01267/solution/solve.sh
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# The reference solution of textcraft-synth-train-hard-01267: the source task's gold trajectory (77 crafts), then finish.
|
| 3 |
+
set -euo pipefail
|
| 4 |
+
if ! command -v textcraft >/dev/null 2>&1; then
|
| 5 |
+
# platoon's process provider runs no image, so there is no textcraft command: run the game file itself.
|
| 6 |
+
textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }
|
| 7 |
+
fi
|
| 8 |
+
textcraft craft a8_i1_18 18 raw_a4=6
|
| 9 |
+
textcraft craft a6_i1 18 raw_a4=12
|
| 10 |
+
textcraft craft a2_i1_12 15 raw_a3=5
|
| 11 |
+
textcraft craft a0_i1_10 8 raw_a4=2
|
| 12 |
+
textcraft craft a0_i1 32 raw_a4=16
|
| 13 |
+
textcraft craft a9_i1 24 raw_a1=16
|
| 14 |
+
textcraft craft a0_i1_20 16 raw_a0=4
|
| 15 |
+
textcraft craft a4_i1_24 18 raw_a7=6
|
| 16 |
+
textcraft craft a4_i1_14 6 raw_a4=4
|
| 17 |
+
textcraft craft a3_i1_13 2 raw_a0=2
|
| 18 |
+
textcraft craft a6_i1_16 4 raw_a0=1
|
| 19 |
+
textcraft craft a5_i1 22 raw_a0=22
|
| 20 |
+
textcraft craft a3_i1_23 12 raw_a6=6
|
| 21 |
+
textcraft craft a1_i1_21 4 raw_a1=1
|
| 22 |
+
textcraft craft a1_i1_11 6 raw_a1=2
|
| 23 |
+
textcraft craft a8_i1 4 raw_a9=2
|
| 24 |
+
textcraft craft a5_i1_15 3 raw_a0=1
|
| 25 |
+
textcraft craft a2_i1_22 4 raw_a9=2
|
| 26 |
+
textcraft craft a7_i1_17 3 raw_a2=2
|
| 27 |
+
textcraft craft a2_i2_12 34 raw_a1=17
|
| 28 |
+
textcraft craft a3_i2 20 a8_i1_18=10 raw_a4=20
|
| 29 |
+
textcraft craft a5_i2 15 a6_i1=10 raw_a4=5
|
| 30 |
+
textcraft craft a1_i2_21 8 raw_a3=4 a0_i1_10=4
|
| 31 |
+
textcraft craft a5_i2_15 9 raw_a3=3 raw_a2=3
|
| 32 |
+
textcraft craft a2_i2_22 21 a9_i1=14 a0_i1_20=7
|
| 33 |
+
textcraft craft a4_i2 2 raw_a0=2 a4_i1_14=2
|
| 34 |
+
textcraft craft a8_i2 2 raw_a9=1 raw_a3=1
|
| 35 |
+
textcraft craft a8_i2_18 2 a3_i1_13=1 a6_i1_16=2
|
| 36 |
+
textcraft craft a1_i2 12 a0_i1=4 raw_a0=4
|
| 37 |
+
textcraft craft a0_i2 6 a4_i1_24=6 a5_i1=3
|
| 38 |
+
textcraft craft a0_i2_10 2 raw_a3=2 raw_a0=1
|
| 39 |
+
textcraft craft a6_i2_16 3 raw_a0=1 raw_a4=1
|
| 40 |
+
textcraft craft a1_i2_11 6 a1_i1_21=3 raw_a2=6
|
| 41 |
+
textcraft craft a6_i2 2 a8_i1_18=1 raw_a0=1
|
| 42 |
+
textcraft craft a9_i2_19 4 a4_i1_24=2 a1_i1_11=4
|
| 43 |
+
textcraft craft a9_i2 3 a2_i1_12=1 a8_i1_18=2
|
| 44 |
+
textcraft craft a2_i2 6 raw_a4=4 a2_i1_12=4
|
| 45 |
+
textcraft craft a3_i2_23 3 a9_i1=2 raw_a3=2
|
| 46 |
+
textcraft craft a7_i2_17 3 raw_a2=2 a0_i1_20=2
|
| 47 |
+
textcraft craft a8_i3_18 6 a2_i2_12=12 a3_i2=12 a5_i2=12
|
| 48 |
+
textcraft craft a1_i3_11 4 a2_i1_12=4 a1_i2_21=4 a0_i1=4
|
| 49 |
+
textcraft craft a0_i3_20 9 a2_i2_22=18 a4_i1_24=9
|
| 50 |
+
textcraft craft a1_i3 2 a8_i2_18=2 a0_i1_20=2
|
| 51 |
+
textcraft craft a1_i3_21 8 a0_i1=16 a5_i1=16 a2_i2_12=16
|
| 52 |
+
textcraft craft a8_i3 3 a3_i1_23=6 a3_i2=3 a0_i2=6
|
| 53 |
+
textcraft craft a2_i3 6 a6_i2_16=3 a1_i2_11=6
|
| 54 |
+
textcraft craft a4_i3 2 a9_i2=2 a8_i1=2
|
| 55 |
+
textcraft craft a6_i3_16 1 a2_i2_22=1 a8_i1=1 a5_i1_15=1
|
| 56 |
+
textcraft craft a2_i3_22 3 a3_i1_23=3 a2_i2_12=6
|
| 57 |
+
textcraft craft a0_i3_10 1 a2_i2=2 a1_i2=1 a2_i1_22=2
|
| 58 |
+
textcraft craft a9_i3 4 a1_i2=4 a5_i1=2 a1_i2_21=2
|
| 59 |
+
textcraft craft a3_i3 1 a1_i2=2 a0_i1=1
|
| 60 |
+
textcraft craft a2_i3_12 1 a3_i2_23=1 a2_i1_22=2 a3_i2=1
|
| 61 |
+
textcraft craft a3_i3_23 1 a2_i2=1 a7_i2_17=1
|
| 62 |
+
textcraft craft a7_i3 2 a7_i1_17=2 a2_i2=2 a0_i2_10=1
|
| 63 |
+
textcraft craft a2_i4_22 3 a8_i3_18=6 a1_i3_11=3
|
| 64 |
+
textcraft craft a0_i4 4 a5_i2_15=8 a0_i3_20=8
|
| 65 |
+
textcraft craft a1_i4 2 a5_i2=1 a8_i2=1 a3_i2=2
|
| 66 |
+
textcraft craft a0_i4_10 2 raw_a3=4 a1_i2=4 a1_i3_21=4
|
| 67 |
+
textcraft craft a9_i4 1 a0_i2_10=1 a2_i3=1 a6_i2=1
|
| 68 |
+
textcraft craft a3_i4 2 a1_i3_21=2 a2_i3=2 a9_i2_19=2
|
| 69 |
+
textcraft craft a1_i4_11 1 a2_i3_22=2 a0_i3_10=1 a9_i3=2
|
| 70 |
+
textcraft craft a1_i5_21 1 a2_i4_22=1 a0_i4=1
|
| 71 |
+
textcraft craft a4_i5_14 2 a4_i2=2 a1_i4=2 a1_i3=2
|
| 72 |
+
textcraft craft a9_i5_19 2 a0_i4_10=1 a8_i3=1
|
| 73 |
+
textcraft craft a2_i5_12 1 a4_i3=1 a6_i3_16=1 a0_i4=1
|
| 74 |
+
textcraft craft a0_i5 1 a1_i4_11=1 a9_i3=1 a3_i3=1
|
| 75 |
+
textcraft craft a3_i5_13 1 a2_i4_22=1 a8_i3=1 a2_i3_12=1
|
| 76 |
+
textcraft craft a8_i5_18 2 a2_i4_22=1 a3_i3_23=1 a0_i3_20=1
|
| 77 |
+
textcraft craft a3_i5 2 a2_i3_22=1 a7_i3=1 a4_i3=1
|
| 78 |
+
textcraft craft a1_i6_6 1 a1_i5_21=1 a4_i5_14=1 a9_i5_19=1 a9_i4=1
|
| 79 |
+
textcraft craft a7_i6_6_17 1 a3_i4=1 a4_i5_14=1
|
| 80 |
+
textcraft craft a8_i6_6 1 a0_i4=1 a9_i5_19=1 a2_i5_12=1
|
| 81 |
+
textcraft craft a2_i6_6_22 1 a0_i5=1 a3_i5_13=1
|
| 82 |
+
textcraft craft a4_i6_6 1 a3_i4=1 a0_i4=1 a3_i5=1
|
| 83 |
+
textcraft craft a6_i7_7 1 a8_i6_6=1 a2_i6_6_22=1 a8_i5_18=1
|
| 84 |
+
textcraft craft a9_i8_8 1 a1_i6_6=1 a7_i6_6_17=1 a6_i7_7=1 a4_i6_6=1
|
| 85 |
+
textcraft finish 'Crafted 1x a9_i8_8'
|
tasks/textcraft-synth-train-hard-01267/task.toml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
schema_version = "1.4"
|
| 2 |
+
# The game's action log: a separate verifier receives it at the same path.
|
| 3 |
+
artifacts = ["/app/textcraft/actions.jsonl"]
|
| 4 |
+
|
| 5 |
+
[task]
|
| 6 |
+
name = "textcraft-synth/train-hard-01267"
|
| 7 |
+
description = "TextCraft-Synth: craft the following items: 1x a9_i8_8 (hard, crafting depth 8)"
|
| 8 |
+
keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
|
| 9 |
+
|
| 10 |
+
[metadata]
|
| 11 |
+
environment = "textcraft-synth@1"
|
| 12 |
+
split = "train"
|
| 13 |
+
difficulty = "hard"
|
| 14 |
+
max_depth = 8
|
| 15 |
+
num_craft_steps = 77
|
| 16 |
+
goal = "Craft the following items: 1x a9_i8_8"
|
| 17 |
+
source_task_id = "textcraft_synth.train.1267"
|
| 18 |
+
env_task_id = "train:1267"
|
| 19 |
+
env_split_task_id = "train-hard:273"
|
| 20 |
+
|
| 21 |
+
[verifier]
|
| 22 |
+
environment_mode = "separate"
|
| 23 |
+
timeout_sec = 180.0
|
| 24 |
+
|
| 25 |
+
[agent]
|
| 26 |
+
timeout_sec = 1380.0
|
| 27 |
+
|
| 28 |
+
[environment]
|
| 29 |
+
network_mode = "no-network"
|
| 30 |
+
cpus = 1
|
| 31 |
+
memory_mb = 2048
|
| 32 |
+
gpus = 0
|
| 33 |
+
build_timeout_sec = 900.0
|