Add TextCraft-Synth 1.0: 3,154 Harbor tasks
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- LICENSEAdded+21
- README.mdAdded+239
- registry.jsonAdded
- splits.jsonAdded
- task-index.jsonAdded
- tasks/textcraft-synth-train-easy-00006/environment/DockerfileAdded+17
- tasks/textcraft-synth-train-easy-00006/environment/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00006/environment/task.jsonAdded+17
- tasks/textcraft-synth-train-easy-00006/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00006/instruction.mdAdded+38
- tasks/textcraft-synth-train-easy-00006/solution/solve.shAdded+12
- tasks/textcraft-synth-train-easy-00006/task.tomlAdded+33
- tasks/textcraft-synth-train-easy-00006/tests/DockerfileAdded+13
- tasks/textcraft-synth-train-easy-00006/tests/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00006/tests/task.jsonAdded+17
- tasks/textcraft-synth-train-easy-00006/tests/test.shAdded+17
- tasks/textcraft-synth-train-easy-00006/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00008/environment/DockerfileAdded+17
- tasks/textcraft-synth-train-easy-00008/environment/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00008/environment/task.jsonAdded+17
- tasks/textcraft-synth-train-easy-00008/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00008/instruction.mdAdded+38
- tasks/textcraft-synth-train-easy-00008/solution/solve.shAdded+12
- tasks/textcraft-synth-train-easy-00008/task.tomlAdded+33
- tasks/textcraft-synth-train-easy-00008/tests/DockerfileAdded+13
- tasks/textcraft-synth-train-easy-00008/tests/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00008/tests/task.jsonAdded+17
- tasks/textcraft-synth-train-easy-00008/tests/test.shAdded+17
- tasks/textcraft-synth-train-easy-00008/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00009/environment/DockerfileAdded+17
- tasks/textcraft-synth-train-easy-00009/environment/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00009/environment/task.jsonAdded+16
- tasks/textcraft-synth-train-easy-00009/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00009/instruction.mdAdded+38
- tasks/textcraft-synth-train-easy-00009/solution/solve.shAdded+13
- tasks/textcraft-synth-train-easy-00009/task.tomlAdded+33
- tasks/textcraft-synth-train-easy-00009/tests/DockerfileAdded+13
- tasks/textcraft-synth-train-easy-00009/tests/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00009/tests/task.jsonAdded+16
- tasks/textcraft-synth-train-easy-00009/tests/test.shAdded+17
- tasks/textcraft-synth-train-easy-00009/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00012/environment/DockerfileAdded+17
- tasks/textcraft-synth-train-easy-00012/environment/recipes.jsonAdded
- tasks/textcraft-synth-train-easy-00012/environment/task.jsonAdded+19
- tasks/textcraft-synth-train-easy-00012/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-train-easy-00012/instruction.mdAdded+38
- tasks/textcraft-synth-train-easy-00012/solution/solve.shAdded+13
- tasks/textcraft-synth-train-easy-00012/task.tomlAdded+33
- tasks/textcraft-synth-train-easy-00012/tests/DockerfileAdded+13
- tasks/textcraft-synth-train-easy-00012/tests/recipes.jsonAdded
123456789101112131415161718192021MIT License
Copyright (c) 2025 Apurva Gandhi
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239---pretty_name: TextCraft-Synthlicense: mitlanguage:- entags:- rl-environment- harbor- textcraft- crafting- planningsize_categories:- 1K<n<10Kviewer: false---
# TextCraft-Synth
TextCraft-Synth is a text crafting game for training and evaluating LLM agents on long-horizon planning: craft thetarget items from a starting inventory of base materials, through recipes up to 12 levels deep. Thisrepository holds it as an RL environment in the [Harbor][harbor] task format: 3,154 tasks, in each of which theagent plays through a `textcraft` command in a container, and a verifier replays the agent's moves to grade them.
The tasks, rules, observations and success rule are those of `textcraft-synth@1`, the TextCraft-Synth environment of theTextCraft plugin of [platoon][platoon], exported task for task.[ADaPT][adapt] (Prasad et al., Findings of NAACL 2024) introduced TextCraft, a text game of crafting Minecraft items;TextCraft-Synth is platoon's synthetic-recipe variant of it.
## Use it
### With Harbor
[Harbor](https://pypi.org/project/harbor/) (0.21.0 or later) loads the tasks from this repository by thedatasets in `registry.json`, one per split:
```bashharbor run --repo https://huggingface.co/datasets/apurvaga/textcraft-synth --dataset textcraft-synth-val@1.0 --agent oracleharbor run --repo https://huggingface.co/datasets/apurvaga/textcraft-synth --dataset textcraft-synth-train@1.0 \ --include-task-name 'textcraft-synth-train-medium-*' --agent terminus-2 --model <model> \ --ak record_terminal_session=false```
The oracle runs each task's reference solution and scores 1 on every task; the `nop` agent scores 0. Task namescarry the split and the difficulty, so `--include-task-name` picks difficulties: `textcraft-synth-train-medium-*` isthe 852-task medium training set that platoon's RAO configurations train on.
The tasks have no network (`network_mode = "no-network"`): this repository holds every reference solution, whichan agent with internet access could fetch. Harbor's Docker environment enforces it. Terminal agents that drivethe container from outside, such as terminus-2, need nothing more: the image has tmux, and`--ak record_terminal_session=false` (above) stops terminus-2 from spending up to four minutes trying to installits session recorder. An agent installed in the container needs its hosts allowed with `--allow-environment-host`(or `--allow-agent-host` for its run alone). Harbor's Singularity environment cannot enforce `no-network` andrefuses the tasks. To run them there, edit `network_mode` to `"public"` in a copy: its in-container serverinstalls its own Python packages over the network when a container starts.
With Harbor, run untrusted agents, and train, only on an environment whose verifier runs as root, such as Docker.Under Singularity the agent and the verifier run as the same unprivileged user and share `/logs/verifier`: an agentthat leaves a reward file there and makes the directory read-only stops Harbor from clearing it and from runningthe tests, and Harbor then reads the agent's reward (seen with Harbor 0.21.0 and harbor-singularity-hpc 0.1.0).
### With platoon
platoon's Harbor support fetches the dataset at a commit, selecting tasks on the fields of `task-index.json`:
```yamlenvironments: - name: textcraft-synth service: harbor service_kwargs: dataset: hf://apurvaga/textcraft-synth@<commit> select: {split: train, difficulty: medium} # the RAO training set image_map: images/site.json # `platoon harbor images build` builds the one image every task uses provider: singularity provider_options: {allow_network_none: true} # the tasks run without a network harness: <harness>```
platoon stops the agent's processes and grades each task in a verifier sandbox of its own, which gets the action logbut not the agent's `/logs/verifier`, so the Singularity caveat above does not apply to it: a planted reward scores 0.
To train on one split and evaluate on another from one entry, fetch every task (no `select`) and pass a local copyof this repository's `splits.json` as `splits`:
```bashhf download apurvaga/textcraft-synth splits.json --repo-type dataset --revision <commit> --local-dir .```
It maps the environment's split names (`train`, `val`, `train-medium`, `val-hard`, ...) to task names,for `dataset_kwargs: {split_name: train-medium}` and `eval_dataset_kwargs: {split_name: val}`.
platoon also runs the same game in process (`env: textcraft-synth@1`), which is what its recursive agents need:subagents that share the parent's inventory and are graded on their own targets. This dataset serves runnersthat take Harbor tasks.
## The game
The goal names the targets, for example `Craft the following items: 3x a1_i5`. The starting inventory holds thebase materials they need, with some to spare and a few unrelated ones. Item names carry no meaning, so the agentlooks recipes up.
| Command | platoon tool | Prints ||---|---|---|| `textcraft craft TARGET COUNT INGREDIENT=N ...` | `craft` | `Successfully crafted N TARGET(s)`, or `Error: ...` and nothing changes || `textcraft info ITEM ...` | `get_info` | each item's recipes, crafting depth, whether it is a base item, and how many the inventory holds, as JSON || `textcraft inventory` | `view_inventory` | the inventory, as JSON || `textcraft finish MESSAGE` | `finish` | the message; the episode ends |
A craft must name exactly the recipe's ingredients, each in the recipe's amount times `COUNT / result_count`,and `COUNT` must be divisible by the recipe's `result_count`. The episode succeeds when it ends with `finish` anda non-empty message, and the inventory then holds every target count on top of what it started with; there isno partial credit. The commands print what platoon's tools return, character for character; `craft --json` and`info --json` take the tools' JSON arguments.
## Task format
```registry.json Harbor datasets: textcraft-synth-<split>@1.0task-index.json every task's split, difficulty, crafting depth, reference crafts, source ids and content hashsplits.json the environment's split names to task namesLICENSE MIT, platoon's license, which covers the game file every task carriestasks/<name>/ instruction.md the game description of platoon's TextCraft agents, the goal, and the commands task.toml timeouts, metadata, no network, a separate verifier, the action log as an artifact environment/ Dockerfile, textcraft_game.py, recipes.json, task.json tests/ test.sh, Dockerfile, and the verifier's copies of the game, the recipes and the task solution/solve.sh the task's gold trajectory as textcraft commands, then finish```
- **One image.** Every Dockerfile, the environment's and the verifier's, starts with the same two steps: `FROM python:3.12-slim`, pinned by digest, and one `RUN` that adds tmux and the `textcraft` command. The rest only copies files: the game and the recipes, which are the same in every task, then the task's `task.json`. Docker reuses the cached layers across tasks, and platoon builds the image once and copies the files when a session starts. A comment on each Dockerfile's first line names its task, so that builders that cache by a Dockerfile's text (harbor-singularity-hpc) never reuse one task's image for another.- **State.** `/app/textcraft` holds the game, the recipes, `task.json` and the action log `actions.jsonl`. Every command replays the log under a lock, runs, and appends one record, so the log is the state.- **Resources.** 1 CPU, 2 GiB of memory, no GPU, no network. The agent's timeout is 600 s plus 10 s per craft of the reference solution, rounded up to a minute; the verifier's is 180 s.
| Difficulty | Crafting depth | Reference crafts (min / median / max) | Agent timeout (s) ||---|---|---|---|| easy | 2-3 | 1 / 3 / 10 | 660-720 || medium | 4-6 | 4 / 18 / 65 | 660-1,260 || hard | 7-9 | 26 / 87 / 141 | 900-2,040 || extreme | 10-12 | 92 / 173 / 549 | 1,560-6,120 |
## The verifier
`tests/test.sh` replays `/app/textcraft/actions.jsonl` from the task's starting inventory with its own copies ofthe game, the recipes and the task, and writes `reward.json` (`{"reward": 1.0}` or `{"reward": 0.0}`) and itsreasons (`textcraft-verdict.json`) to `/logs/verifier`:
- The reward is 1 only when the log is an episode the rules allow that ends with `finish` with every target crafted. A log without `finish`, or with an empty finish message, scores 0, as in platoon.- The log must be a regular file of at most 32 MiB, reached without symbolic links. A record that does not parse, breaks the record format or the numbering, follows `finish`, or claims a craft outcome the rules do not give ends the replay with reward 0: a hand-written log scores only if the moves it records are legal and reach the goal. A craft the rules reject, recorded as rejected, changes nothing, as in the environment.- The log is the agent's to edit, so an agent can take back a move by deleting its record. The reward still needs every move the final log records to be legal from the task's starting inventory, and the goal reached: editing the log never earns a reward that its moves do not.- The verifier runs in a container of its own (`environment_mode = "separate"`) that receives the log as an artifact; reward files already in `/logs/verifier` are removed first, where the runner can clear that directory (not under Singularity: see [With Harbor](#with-harbor)). The same `test.sh` also runs in the agent's container when a runner uses a shared verifier, but there the agent, which is root in that container, could have replaced Python or the grader itself: use a shared verifier only for agents you trust.
## Splits
| Split | Harbor dataset | Tasks | easy | medium | hard | extreme ||---|---|---:|---:|---:|---:|---:|| `train` | `textcraft-synth-train@1.0` | 2,522 | 588 | 852 | 544 | 538 || `val` | `textcraft-synth-val@1.0` | 632 | 147 | 213 | 136 | 136 |
Difficulties are crafting depths: easy 2-3, medium 4-6, hard 7-9 and extreme 10-12. Train and validation targetsare disjoint: the generator held out a fifth of each tier's craftable items as validation targets, and each splitholds every pair of one of its items and a count, one task each.
## Provenance
The tasks are platoon's TextCraft-Synth task files, exported by `python -m platoon.textcraft.harbor export--variant synth --version 1.0` (the TextCraft plugin, `plugins/textcraft`) at platooncommit `a92480114ec24fd5182cce75615a749832ff10b7`. The export writes the same bytes from the same inputs.
| Split | platoon task file | Tasks | SHA-256 ||---|---|---:|---|| `train` | `plugins/textcraft/platoon/textcraft/textcraft_synth_train.jsonl` | 2,522 | `685823fbca90aa89e061e61fef58d0122def4221eed14cf2c8c730341363a00f` || `val` | `plugins/textcraft/platoon/textcraft/textcraft_synth_val.jsonl` | 632 | `84a123ee46e29e65f4d7b95f4943aa56907fc3fd5992268faa749602579dfc0c` |
platoon generated the task files with `platoon.textcraft.synth_tasks` (seed 42) on the world that `platoon.textcraft.synth_recipe_generator` builds with seed 42 and 25 items per domain and tier: 1,452 items, 50 of them base materials, and recipes up to depth 12. The environment builds this world in process when it loads. The world's recipes are`recipes.json`, `sha256:a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10`; the export checks that it answers everyrecipe lookup as the environment's database does. The generator draws each task's unrelated base materials froma Python set, so running it again gives the same goals, but in another order and with other starting inventories,unless it runs under the same string-hash seed: the task files above are the source. Each reference solution isthe task's gold trajectory from the same files, which the export plays with the game, failing unless it reachesthe goal.
## License
MIT, the license of platoon, whose code generated the recipes and the tasks and whose game file every taskcarries (`LICENSE`). The images are built from the `python:3.12-slim` base image at run time; it is not part of thisrepository.
## Citation
platoon was built for [Recursive Agent Optimization](https://arxiv.org/abs/2605.06639) (RAO), whose experimentstrain on TextCraft-Synth. Please cite RAO, platoon, which generated and exported the tasks, and ADaPT, whichintroduced TextCraft:
```bibtex@article{gandhi2026rao, title = {Recursive Agent Optimization}, author = {Gandhi, Apurva and Chakraborty, Satyaki and Wang, Xiangjun and Kumar, Aviral and Neubig, Graham}, journal = {arXiv preprint arXiv:2605.06639}, year = {2026}}
@misc{gandhi2025platoon, author = {Gandhi, Apurva}, title = {{Platoon}: Build and Train Systems of Agents}, howpublished = {\url{https://github.com/ApGa/platoon}}, year = {2025}}
@inproceedings{prasad2024adapt, title = {{ADaPT}: As-Needed Decomposition and Planning with Language Models}, author = {Prasad, Archiki and Koller, Alexander and Hartmann, Mareike and Clark, Peter and Sabharwal, Ashish and Bansal, Mohit and Khot, Tushar}, booktitle = {Findings of the Association for Computational Linguistics: NAACL 2024}, pages = {4226--4252}, year = {2024}, url = {https://aclanthology.org/2024.findings-naacl.264/}}```
[adapt]: https://arxiv.org/abs/2311.05772[harbor]: https://github.com/harbor-framework/harbor[platoon]: https://github.com/ApGa/platoon1234567891011121314151617# textcraft-synth-train-easy-00006: task.json sha256:f6fc314f717f9778cc89c52059964eb42e1bc445f8c415601d21b6a0d7ba5ed8FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the# `textcraft` command, which runs the game file below.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The# game keeps its action log next to them.WORKDIR /appENV TEXTCRAFT_DIR=/app/textcraftCOPY textcraft_game.py recipes.json /app/textcraft/COPY task.json /app/textcraft/1234567891011121314151617{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00006", "world": "textcraft-synth", "goal": "Craft the following items: 1x c3_i3_13", "target_items": { "c3_i3_13": 1 }, "initial_inventory": { "c5_ore": 6, "c0_ore": 6, "c1_ore": 5, "raw_t4": 5, "raw_t2": 3 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738You are an agent in a crafting game. Your goal is to craft items by combining ingredients.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.
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.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.
## Task
Craft the following items: 1x c3_i3_13
## Actions
You act through the `textcraft` command in the shell:
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]` Craft items using ingredients from your inventory. - INGREDIENT=COUNT pairs: the items to consume and how many of each - TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count - Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
2. `textcraft info ITEM [ITEM ...]` Get recipe information for items. - Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]} - crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps - Each recipe shows {"ingredients": {...}, "result_count": int} - Example: `textcraft info m2_i2 raw_m0`
3. `textcraft inventory` View your current inventory. - Prints JSON {item_name: count}
4. `textcraft finish MESSAGE` Complete the task. - Example: `textcraft finish "Successfully crafted all required items"` - The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a task that never finishes counts as failed.
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.123456789101112#!/bin/bash# The reference solution of textcraft-synth-train-easy-00006: the source task's gold trajectory (4 crafts), then finish.set -euo pipefailif ! command -v textcraft >/dev/null 2>&1; then # platoon's process provider runs no image, so there is no textcraft command: run the game file itself. textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }fitextcraft craft c9_i1_19 3 c5_ore=2textcraft craft c1_i1_11 4 c5_ore=1textcraft craft c6_i2 3 c9_i1_19=1 c0_ore=2textcraft craft c3_i3_13 1 c6_i2=2 c1_i1_11=2textcraft finish 'Crafted 1x c3_i3_13'123456789101112131415161718192021222324252627282930313233schema_version = "1.4"# The game's action log: a separate verifier receives it at the same path.artifacts = ["/app/textcraft/actions.jsonl"]
[task]name = "textcraft-synth/train-easy-00006"description = "TextCraft-Synth: craft the following items: 1x c3_i3_13 (easy, crafting depth 3)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "train"difficulty = "easy"max_depth = 3num_craft_steps = 4goal = "Craft the following items: 1x c3_i3_13"source_task_id = "textcraft_synth.train.6"env_task_id = "train:6"env_split_task_id = "train-easy:0"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 660.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-train-easy-00006: task.json sha256:f6fc314f717f9778cc89c52059964eb42e1bc445f8c415601d21b6a0d7ba5ed8FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The same image as the task's environment, so one image serves the agent and the verifier.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The verifier's trusted copies of the grader, the game, the recipes and the task.WORKDIR /appCOPY test.sh textcraft_game.py recipes.json task.json /tests/1234567891011121314151617{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00006", "world": "textcraft-synth", "goal": "Craft the following items: 1x c3_i3_13", "target_items": { "c3_i3_13": 1 }, "initial_inventory": { "c5_ore": 6, "c0_ore": 6, "c1_ore": 5, "raw_t4": 5, "raw_t2": 3 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}1234567891011121314151617#!/bin/bash# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a# separate verifier that received the log as an artifact.# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that# directory; sandboxes leave it unset.set -uroot="${PLATOON_SANDBOX_ROOT:-}"tests="$root/tests"out="$root/logs/verifier"mkdir -p "$out"# A fresh verdict: nothing the agent may have left in the verifier's directory counts.rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/task.json" --recipes "$tests/recipes.json" \ --root "$root/" --log app/textcraft/actions.jsonl --out "$out"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617# textcraft-synth-train-easy-00008: task.json sha256:950e4519f1eb7213650544dcf71f0090f743779d03b073c00addae4cb4f44d09FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the# `textcraft` command, which runs the game file below.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The# game keeps its action log next to them.WORKDIR /appENV TEXTCRAFT_DIR=/app/textcraftCOPY textcraft_game.py recipes.json /app/textcraft/COPY task.json /app/textcraft/1234567891011121314151617{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00008", "world": "textcraft-synth", "goal": "Craft the following items: 2x c1_i3_11", "target_items": { "c1_i3_11": 2 }, "initial_inventory": { "c1_ore": 12, "c4_ore": 5, "c9_ore": 4, "c6_ore": 6, "raw_t6": 3 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738You are an agent in a crafting game. Your goal is to craft items by combining ingredients.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.
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.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.
## Task
Craft the following items: 2x c1_i3_11
## Actions
You act through the `textcraft` command in the shell:
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]` Craft items using ingredients from your inventory. - INGREDIENT=COUNT pairs: the items to consume and how many of each - TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count - Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
2. `textcraft info ITEM [ITEM ...]` Get recipe information for items. - Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]} - crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps - Each recipe shows {"ingredients": {...}, "result_count": int} - Example: `textcraft info m2_i2 raw_m0`
3. `textcraft inventory` View your current inventory. - Prints JSON {item_name: count}
4. `textcraft finish MESSAGE` Complete the task. - Example: `textcraft finish "Successfully crafted all required items"` - The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a task that never finishes counts as failed.
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.123456789101112#!/bin/bash# The reference solution of textcraft-synth-train-easy-00008: the source task's gold trajectory (4 crafts), then finish.set -euo pipefailif ! command -v textcraft >/dev/null 2>&1; then # platoon's process provider runs no image, so there is no textcraft command: run the game file itself. textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }fitextcraft craft c5_i1 4 c1_ore=1textcraft craft c5_i2_15 4 c5_i1=4 c4_ore=2textcraft craft c2_i2_22 4 c9_ore=2 c6_ore=2textcraft craft c1_i3_11 2 c5_i2_15=4 c2_i2_22=4textcraft finish 'Crafted 2x c1_i3_11'123456789101112131415161718192021222324252627282930313233schema_version = "1.4"# The game's action log: a separate verifier receives it at the same path.artifacts = ["/app/textcraft/actions.jsonl"]
[task]name = "textcraft-synth/train-easy-00008"description = "TextCraft-Synth: craft the following items: 2x c1_i3_11 (easy, crafting depth 3)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "train"difficulty = "easy"max_depth = 3num_craft_steps = 4goal = "Craft the following items: 2x c1_i3_11"source_task_id = "textcraft_synth.train.8"env_task_id = "train:8"env_split_task_id = "train-easy:1"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 660.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-train-easy-00008: task.json sha256:950e4519f1eb7213650544dcf71f0090f743779d03b073c00addae4cb4f44d09FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The same image as the task's environment, so one image serves the agent and the verifier.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The verifier's trusted copies of the grader, the game, the recipes and the task.WORKDIR /appCOPY test.sh textcraft_game.py recipes.json task.json /tests/1234567891011121314151617{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00008", "world": "textcraft-synth", "goal": "Craft the following items: 2x c1_i3_11", "target_items": { "c1_i3_11": 2 }, "initial_inventory": { "c1_ore": 12, "c4_ore": 5, "c9_ore": 4, "c6_ore": 6, "raw_t6": 3 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}1234567891011121314151617#!/bin/bash# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a# separate verifier that received the log as an artifact.# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that# directory; sandboxes leave it unset.set -uroot="${PLATOON_SANDBOX_ROOT:-}"tests="$root/tests"out="$root/logs/verifier"mkdir -p "$out"# A fresh verdict: nothing the agent may have left in the verifier's directory counts.rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/task.json" --recipes "$tests/recipes.json" \ --root "$root/" --log app/textcraft/actions.jsonl --out "$out"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617# textcraft-synth-train-easy-00009: task.json sha256:0e13707b49b25104d2f1fa8a84407c36798c1b4bd86af37830cc8e7c12f8351cFROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the# `textcraft` command, which runs the game file below.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The# game keeps its action log next to them.WORKDIR /appENV TEXTCRAFT_DIR=/app/textcraftCOPY textcraft_game.py recipes.json /app/textcraft/COPY task.json /app/textcraft/12345678910111213141516{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00009", "world": "textcraft-synth", "goal": "Craft the following items: 1x o2_i3_12", "target_items": { "o2_i3_12": 1 }, "initial_inventory": { "raw_o7": 6, "raw_o1": 4, "raw_o2": 2, "m3_ore": 5 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738You are an agent in a crafting game. Your goal is to craft items by combining ingredients.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.
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.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.
## Task
Craft the following items: 1x o2_i3_12
## Actions
You act through the `textcraft` command in the shell:
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]` Craft items using ingredients from your inventory. - INGREDIENT=COUNT pairs: the items to consume and how many of each - TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count - Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
2. `textcraft info ITEM [ITEM ...]` Get recipe information for items. - Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]} - crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps - Each recipe shows {"ingredients": {...}, "result_count": int} - Example: `textcraft info m2_i2 raw_m0`
3. `textcraft inventory` View your current inventory. - Prints JSON {item_name: count}
4. `textcraft finish MESSAGE` Complete the task. - Example: `textcraft finish "Successfully crafted all required items"` - The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a task that never finishes counts as failed.
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.12345678910111213#!/bin/bash# The reference solution of textcraft-synth-train-easy-00009: the source task's gold trajectory (5 crafts), then finish.set -euo pipefailif ! command -v textcraft >/dev/null 2>&1; then # platoon's process provider runs no image, so there is no textcraft command: run the game file itself. textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }fitextcraft craft o0_i1_10 3 raw_o7=2textcraft craft o4_i1 3 raw_o1=1textcraft craft o5_i1 2 raw_o2=1textcraft craft o6_i2_16 3 o4_i1=1 o5_i1=1textcraft craft o2_i3_12 1 o0_i1_10=2 o4_i1=2 o6_i2_16=2textcraft finish 'Crafted 1x o2_i3_12'123456789101112131415161718192021222324252627282930313233schema_version = "1.4"# The game's action log: a separate verifier receives it at the same path.artifacts = ["/app/textcraft/actions.jsonl"]
[task]name = "textcraft-synth/train-easy-00009"description = "TextCraft-Synth: craft the following items: 1x o2_i3_12 (easy, crafting depth 3)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "train"difficulty = "easy"max_depth = 3num_craft_steps = 5goal = "Craft the following items: 1x o2_i3_12"source_task_id = "textcraft_synth.train.9"env_task_id = "train:9"env_split_task_id = "train-easy:2"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 660.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-train-easy-00009: task.json sha256:0e13707b49b25104d2f1fa8a84407c36798c1b4bd86af37830cc8e7c12f8351cFROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The same image as the task's environment, so one image serves the agent and the verifier.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The verifier's trusted copies of the grader, the game, the recipes and the task.WORKDIR /appCOPY test.sh textcraft_game.py recipes.json task.json /tests/12345678910111213141516{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00009", "world": "textcraft-synth", "goal": "Craft the following items: 1x o2_i3_12", "target_items": { "o2_i3_12": 1 }, "initial_inventory": { "raw_o7": 6, "raw_o1": 4, "raw_o2": 2, "m3_ore": 5 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}1234567891011121314151617#!/bin/bash# Grade a TextCraft episode: replay the agent's action log (/app/textcraft/actions.jsonl) from the task's starting# inventory with the game's rules, using this directory's own copies of the game, the recipes and the task. The# reward is 1 only when the log is an episode the rules allow that ends in `textcraft finish` with every target# crafted (the verdict goes to textcraft-verdict.json). It runs in the agent's container (a shared verifier) or in a# separate verifier that received the log as an artifact.# PLATOON_SANDBOX_ROOT: platoon's process provider runs this on the host, with the sandbox's files below that# directory; sandboxes leave it unset.set -uroot="${PLATOON_SANDBOX_ROOT:-}"tests="$root/tests"out="$root/logs/verifier"mkdir -p "$out"# A fresh verdict: nothing the agent may have left in the verifier's directory counts.rm -rf -- "$out/reward.json" "$out/reward.txt" "$out/textcraft-verdict.json"exec python3 -I "$tests/textcraft_game.py" verify --task "$tests/task.json" --recipes "$tests/recipes.json" \ --root "$root/" --log app/textcraft/actions.jsonl --out "$out"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617# textcraft-synth-train-easy-00012: task.json sha256:af9325480cb46dc4c5f34942c321f7cd3f15a9c79c3b187a3810c147d2d64926FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The image is the same for every task (and for the verifier): Python, tmux for terminal agents, and the# `textcraft` command, which runs the game file below.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The game and the world's recipes (the same in every task), then this task's goal and starting inventory. The# game keeps its action log next to them.WORKDIR /appENV TEXTCRAFT_DIR=/app/textcraftCOPY textcraft_game.py recipes.json /app/textcraft/COPY task.json /app/textcraft/12345678910111213141516171819{ "format": "textcraft-task/1", "name": "textcraft-synth-train-easy-00012", "world": "textcraft-synth", "goal": "Craft the following items: 3x c0_i3_10", "target_items": { "c0_i3_10": 3 }, "initial_inventory": { "c1_ore": 8, "c4_ore": 3, "c5_ore": 8, "c6_ore": 10, "c9_ore": 3, "raw_t8": 3, "raw_o3": 5 }, "recipes_sha256": "a020eec273337c66b35c0fc487664e35c44da65ad18e9afffe6a4c25af949f10"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756"""TextCraft in a container: the ``textcraft`` command of a Harbor task, and the verifier that grades it.
This one file is the whole game. It needs Python 3.8 or later and its standard library only, and it never importsplatoon: the exporter (``python -m platoon.textcraft.harbor export``) copies it into every task as``textcraft_game.py``, into ``environment/`` (the container gets it at ``/app/textcraft/textcraft_game.py``, whichthe image's ``textcraft`` command runs) and into ``tests/`` for the verifier. It reproduces platoon's TextCraftenvironments (``platoon.textcraft.env``): the same four tools with the same arguments, the same observation textand the same success rule.
========================================= =================== ===============================================command environment tool prints========================================= =================== ===============================================``textcraft craft TARGET COUNT ING=N ...`` ``craft`` ``Successfully crafted ...`` or ``Error: ...````textcraft info ITEM ...`` ``get_info`` the recipe information, as JSON``textcraft inventory`` ``view_inventory`` the inventory, as JSON``textcraft finish MESSAGE`` ``finish`` the message; the episode ends========================================= =================== ===============================================
``craft --json '{"ingredients": {...}, "target": [item, count]}'`` and ``info --json '[item, ...]'`` take a tool'sarguments as JSON values, the way a tool call passes them.
**State.** ``$TEXTCRAFT_DIR`` (default: this file's directory, ``/app/textcraft`` in a task's container) holds thetask (``task.json``: goal, targets, starting inventory), the world's recipes (``recipes.json``, or``$TEXTCRAFT_RECIPES``) and the action log (``actions.jsonl``). The log is the state: under an exclusive lock,every command replays the log from the starting inventory, runs, and appends its own record (``{"seq", "tool","args"}``, plus ``"ok"`` for a craft). Nothing is accepted after ``finish``, or once the log no longer replays.
**Grading** (``python3 textcraft_game.py verify``, from the task's ``tests/test.sh``) replays the log with trustedcopies of the task and the recipes. The reward is 1 when the log is an episode the rules allow that ends in``finish`` with a message, and the inventory then holds every target count on top of the starting inventory (theenvironment's rule); otherwise it is 0. The log must be a regular file of at most 32 MiB, reached without asymbolic link below the sandbox root. A record that does not parse, breaks the record format or the numbering,follows ``finish``, or claims a craft outcome the rules do not give ends the replay with reward 0: only a log thecommand could have written earns a reward. A craft the rules reject, recorded as rejected, changes nothing, as inthe environment."""
from __future__ import annotations
import argparseimport errnoimport fcntlimport hashlibimport jsonimport osimport statimport sys
VERSION = "1.0"TASK_FORMAT = "textcraft-task/1"RECIPES_FORMAT = "textcraft-recipes/1"TASK_FILE = "task.json"LOG_FILE = "actions.jsonl"RECIPES_FILE = "recipes.json"REWARD_FILE = "reward.json"VERDICT_FILE = "textcraft-verdict.json"LOG_CAP_BYTES = 32 * 1024 * 1024CRAFTED = "Successfully crafted"# The environment's tools and their arguments, as a log record names them.ARGUMENTS = {"craft": ("ingredients", "target"), "get_info": ("items",), "view_inventory": (), "finish": ("message",)}READ_ONLY = frozenset({"get_info", "view_inventory"}) # tools that change nothingCOMMANDS = { "craft": "craft", "info": "get_info", "get_info": "get_info", "inventory": "view_inventory", "view_inventory": "view_inventory", "finish": "finish",}_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
USAGE = """\usage: textcraft COMMAND [ARGUMENTS]
Play the TextCraft task in $TEXTCRAFT_DIR (default /app/textcraft, the game's directory).
textcraft craft TARGET COUNT INGREDIENT=N [INGREDIENT=N ...] Craft COUNT of TARGET from exactly these ingredients. COUNT must be divisible by the recipe's result_count; each ingredient's N is its recipe count times COUNT / result_count. Example: textcraft craft m2_i2 2 m0_i1=2 m1_i1=1 textcraft info ITEM [ITEM ...] Recipe information for the items, as a JSON list. textcraft inventory Your current inventory, as JSON {item_name: count}. textcraft finish MESSAGE Complete the task with a message saying what you achieved. The task is graded on what your inventory gained; no command is accepted after it.
craft --json '{"ingredients": {...}, "target": [item, count]}' and info --json '[item, ...]' take thearguments as JSON. get_info and view_inventory are other names for info and inventory."""
# ---------------------------------------------------------------------------------------------------- the world
class Recipe: __slots__ = ("result_count", "ingredients")
def __init__(self, result_count, ingredients): self.result_count = result_count self.ingredients = ingredients # {item or "tag:<name>": count}, in the recipe's order
class RecipeBook: """A world's recipes (``recipes.json``), with the lookups of platoon's recipe databases.
The file lists each craftable item's recipes (ingredients as ``[name, count]`` pairs, in order), the base items, every item's crafting depth (0 for items it does not list) and the items each ``tag:<name>`` ingredient accepts. """
def __init__(self, data, sha256=None): if not isinstance(data, dict) or data.get("format") != RECIPES_FORMAT: raise ValueError("not a %s file" % RECIPES_FORMAT) self.name = data["name"] self.sha256 = sha256 self.recipes = { item: [ Recipe(recipe["result_count"], {name: count for name, count in recipe["ingredients"]}) for recipe in recipes ] for item, recipes in data["recipes"].items() } self.base_items = frozenset(data["base_items"]) self.depths = dict(data["depths"]) self.tags = {tag: list(items) for tag, items in data["tags"].items()}
@classmethod def load(cls, path): with open(path, "rb") as handle: raw = handle.read() return cls(json.loads(raw.decode("utf-8")), sha256=hashlib.sha256(raw).hexdigest())
def get_recipes_for_item(self, item): return self.recipes.get(item, [])
def can_craft(self, item): return item in self.recipes
def is_base_item(self, item): return item in self.base_items
def get_crafting_depth(self, item): return self.depths.get(item, 0)
def get_items_for_tag(self, tag): return list(self.tags.get(tag, []))
def load_task(path): """A task file (``task.json``): its goal, targets and starting inventory, and its recipes' SHA-256."""
with open(path, "rb") as handle: task = json.loads(handle.read().decode("utf-8")) if not isinstance(task, dict) or task.get("format") != TASK_FORMAT: raise ValueError("%s is not a %s file" % (path, TASK_FORMAT)) for key in ("name", "goal", "target_items", "initial_inventory", "recipes_sha256"): if key not in task: raise ValueError("%s has no %r" % (path, key)) return task
# ---------------------------------------------------------------------------------------------------- the game
class Game: """One episode: platoon's ``TextCraftEnvironment`` tools over an inventory, its rules and messages unchanged."""
def __init__(self, book, task): self.book = book self.goal = task["goal"] self.target_items = dict(task["target_items"]) self.inventory = dict(task["initial_inventory"]) self.initial_inventory = dict(self.inventory) self.finished = False self.score = 0.0 self.reward_misc = {} self.crafts = 0 # successful crafts
def call(self, tool, args): """Run a tool with its arguments (the JSON values a tool call carries); the observation text it returns."""
if tool == "craft": text = self.craft(args["ingredients"], args["target"]) self.crafts += text.startswith(CRAFTED) return text if tool == "get_info": return json.dumps(self.get_info(args["items"])) if tool == "view_inventory": return json.dumps(dict(self.inventory)) if tool == "finish": self.score, self.reward_misc = self.evaluate(args["message"]) self.finished = True return args["message"] raise ValueError("unknown tool %r" % (tool,))
def craft(self, ingredients, target): """``TextCraftEnvironment._craft``: the same checks in the same order, with the same messages."""
if not isinstance(ingredients, dict): return f"Error: ingredients must be a dict, got {type(ingredients).__name__}" if not isinstance(target, (tuple, list)) or len(target) != 2: return "Error: target must be a tuple of (item_name, count)" target_item, target_count = target if not isinstance(target_item, str): return f"Error: target item must be a string, got {type(target_item).__name__}" if not isinstance(target_count, int): return f"Error: target count must be an int, got {type(target_count).__name__}" if target_count <= 0: return f"Error: target count must be positive, got {target_count}" for ing_item, ing_count in ingredients.items(): if not isinstance(ing_item, str): return f"Error: ingredient name must be a string, got {type(ing_item).__name__}" if not isinstance(ing_count, int): return f"Error: ingredient count for {ing_item} must be an int, got {type(ing_count).__name__}" if ing_count <= 0: return f"Error: ingredient count for {ing_item} must be positive, got {ing_count}"
book = self.book recipes = book.get_recipes_for_item(target_item) if not recipes: return f"Error: No recipe found for {target_item}"
errors = [] for recipe_idx, recipe in enumerate(recipes): if target_count % recipe.result_count != 0: errors.append( f"Recipe {recipe_idx + 1}: Target count {target_count} is not divisible " f"by recipe result count {recipe.result_count}" ) continue num_crafts = target_count // recipe.result_count
ingredient_mapping = {} # recipe ingredient (or tag) -> provided item recipe_error = None for recipe_ing, recipe_count in recipe.ingredients.items(): total_required = recipe_count * num_crafts if recipe_ing.startswith("tag:"): satisfying_items = book.get_items_for_tag(recipe_ing.replace("tag:", "")) provided = next( ( item for item, count in ingredients.items() if item in satisfying_items and count == total_required ), None, ) if provided is None: recipe_error = f"No ingredient provided for {recipe_ing}. Expected one of: {satisfying_items}" break ingredient_mapping[recipe_ing] = provided else: if recipe_ing not in ingredients: recipe_error = f"Missing required ingredient {recipe_ing}" break if ingredients[recipe_ing] != total_required: recipe_error = ( f"Wrong amount of {recipe_ing}. Need {total_required}, provided {ingredients[recipe_ing]}" ) break ingredient_mapping[recipe_ing] = recipe_ing if recipe_error: errors.append(f"Recipe {recipe_idx + 1}: {recipe_error}") continue
extra_ingredients = [item for item in ingredients if item not in ingredient_mapping.values()] if extra_ingredients: errors.append( f"Recipe {recipe_idx + 1}: Extra ingredients not required: {', '.join(extra_ingredients)}" ) continue
missing = [] for recipe_ing, provided_ing in ingredient_mapping.items(): required = recipe.ingredients[recipe_ing] * num_crafts available = self.inventory.get(provided_ing, 0) if available < required: missing.append(f"{provided_ing}: need {required}, have {available}") if missing: errors.append(f"Recipe {recipe_idx + 1}: Insufficient ingredients in inventory: {', '.join(missing)}") continue
for recipe_ing, provided_ing in ingredient_mapping.items(): self.inventory[provided_ing] -= recipe.ingredients[recipe_ing] * num_crafts if self.inventory[provided_ing] <= 0: del self.inventory[provided_ing] crafted_count = recipe.result_count * num_crafts self.inventory[target_item] = self.inventory.get(target_item, 0) + crafted_count return f"Successfully crafted {crafted_count} {target_item}(s)"
return f"Error: All {len(recipes)} recipe(s) failed for {target_item}. Errors:\n" + "\n".join(errors)
def get_info(self, items): """``TextCraftEnvironment._get_info``."""
book = self.book results = [] for item in items: info = { "item": item, "can_craft": book.can_craft(item), "is_base": book.is_base_item(item), "in_inventory": self.inventory.get(item, 0), "crafting_depth": book.get_crafting_depth(item), "recipes": [], } if info["can_craft"]: for recipe in book.get_recipes_for_item(item): expanded = {} for ing, count in recipe.ingredients.items(): if ing.startswith("tag:"): expanded[ing] = {"count": count, "use_one_of": book.get_items_for_tag(ing[4:])} else: expanded[ing] = count info["recipes"].append({"ingredients": expanded, "result_count": recipe.result_count}) results.append(info) return results
def evaluate(self, finish_message): """``TextCraftEnvironment.evaluate``: success when the inventory gained every target count and the finish message is not empty."""
reward_misc = {} score = 0.0 if finish_message: if not self.target_items: return 0.0, {"success": False, "error": "No target items defined in task", "reward/success": 0.0} missing = { item: required - (self.inventory.get(item, 0) - self.initial_inventory.get(item, 0)) for item, required in self.target_items.items() if self.inventory.get(item, 0) - self.initial_inventory.get(item, 0) < required } reward_misc["success"] = not missing if missing: reward_misc["missing_items"] = missing else: score = 1.0 reward_misc["target_items"] = dict(self.target_items) reward_misc["initial_inventory"] = dict(self.initial_inventory) reward_misc["final_inventory"] = dict(self.inventory) else: reward_misc["success"] = False reward_misc["error"] = "Episode ended without calling finish() - likely timeout or max steps reached" reward_misc["reward/success"] = score return score, reward_misc
# ---------------------------------------------------------------------------------------------------- the log
class LogError(ValueError): """An action log the game could not have written: its replay stops there."""
def _unique_pairs(pairs): found = {} for key, value in pairs: if key in found: raise ValueError("duplicate key %r" % (key,)) found[key] = value return found
def _no_constant(name): raise ValueError("%s is not a JSON number" % name)
def _finite_float(text): value = float(text) if value != value or value in (float("inf"), float("-inf")): raise ValueError("%s is out of range" % text) return value
def parse_json(text): """Strict JSON: no duplicate keys, no NaN or Infinity (also none that overflows, such as 1e999), so every value it returns can be written back to the log."""
return json.loads(text, object_pairs_hook=_unique_pairs, parse_constant=_no_constant, parse_float=_finite_float)
def encode_record(seq, tool, args, ok=None): """A log line: ``{"seq", "tool", "args"}``, plus ``"ok"`` (the craft succeeded) for a craft."""
record = {"seq": seq, "tool": tool, "args": args} if tool == "craft": record["ok"] = bool(ok) return (json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False) + "\n").encode("ascii")
def check_arguments(tool, args): """``args`` as a log record or a command may give them to ``tool``; ValueError says what is wrong."""
if not isinstance(args, dict) or sorted(args) != sorted(ARGUMENTS[tool]): raise ValueError("%s takes the arguments %s" % (tool, ", ".join(ARGUMENTS[tool]) or "none")) if tool == "get_info" and ( not isinstance(args["items"], list) or not all(isinstance(item, str) for item in args["items"]) ): raise ValueError("get_info takes a list of item names") if tool == "finish" and not isinstance(args["message"], str): raise ValueError("finish takes a message string")
def _record(line, seq): try: record = parse_json(line.decode("utf-8")) except (UnicodeDecodeError, ValueError, RecursionError) as exc: raise LogError("record %d is not a JSON object: %s" % (seq, exc)) from None if not isinstance(record, dict): raise LogError("record %d is not a JSON object" % seq) tool = record.get("tool") if not isinstance(tool, str) or tool not in ARGUMENTS: raise LogError("record %d names no tool of the game: %r" % (seq, tool)) keys = {"seq", "tool", "args", "ok"} if tool == "craft" else {"seq", "tool", "args"} if set(record) != keys: raise LogError("record %d must have exactly the keys %s" % (seq, sorted(keys))) if type(record["seq"]) is not int or record["seq"] != seq: raise LogError("record %d is numbered %r" % (seq, record["seq"])) try: check_arguments(tool, record["args"]) except ValueError as exc: raise LogError("record %d: %s" % (seq, exc)) from None if tool == "craft" and not isinstance(record["ok"], bool): raise LogError("record %d: ok must be true or false" % seq) return tool, record["args"], record.get("ok")
def replay(game, data): """Apply a log's records to ``game``; how many there were. LogError at the first record the game could not have written: the replay stops there.
The records are read one at a time, and those of ``get_info`` and ``view_inventory``, which change nothing, have their arguments checked but their output never rebuilt, so replaying any log within the size cap takes seconds and a bounded amount of memory (a ``get_info`` record can name millions of items)."""
if not data: return 0 if not data.endswith(b"\n"): raise LogError("the last record does not end with a newline") seq = start = 0 while start < len(data): end = data.index(b"\n", start) seq += 1 if game.finished: raise LogError("record %d follows finish" % seq) tool, args, ok = _record(data[start:end], seq) start = end + 1 if tool in READ_ONLY: continue try: text = game.call(tool, args) except Exception as exc: # arguments no command writes raise LogError("record %d cannot be applied: %s: %s" % (seq, type(exc).__name__, exc)) from None if tool == "craft" and text.startswith(CRAFTED) != ok: claim = "succeeded" if ok else "failed" raise LogError("record %d says the craft %s, but the rules give: %s" % (seq, claim, text)) return seq
# ---------------------------------------------------------------------------------------------------- the command
class UsageError(ValueError): pass
class Result: """What a command printed and its exit status: 0 done, 1 a game error (a rejected craft, the episode is over), 2 a usage error (nothing was run or logged), 3 the task cannot be played."""
def __init__(self, code, out="", err=""): self.code = code self.out = out self.err = err
def parse_command(argv): """``(tool, args)`` of a command line; UsageError when it is not one."""
if not argv: raise UsageError("no command") tool = COMMANDS.get(argv[0]) if tool is None: raise UsageError("unknown command %r" % argv[0]) rest = argv[1:] if tool == "craft": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("craft --json takes one JSON object") args = _json_argument(rest[1]) if not isinstance(args, dict) or sorted(args) != ["ingredients", "target"]: raise UsageError('craft --json takes {"ingredients": {...}, "target": [item, count]}') return tool, args if len(rest) < 2: raise UsageError("craft takes TARGET COUNT INGREDIENT=N ...") ingredients = {} for word in rest[2:]: name, sep, count = word.rpartition("=") if not sep or not name: raise UsageError("ingredients are INGREDIENT=N, got %r" % word) if name in ingredients: raise UsageError("ingredient %r is given twice" % name) ingredients[name] = _integer(count, "the count of %s" % name) return tool, {"ingredients": ingredients, "target": [rest[0], _integer(rest[1], "COUNT")]} if tool == "get_info": if rest[:1] == ["--json"]: if len(rest) != 2: raise UsageError("info --json takes one JSON list") items = _json_argument(rest[1]) else: items = list(rest) args = {"items": items} elif tool == "view_inventory": if rest: raise UsageError("inventory takes no arguments") args = {} else: if not rest: raise UsageError("finish takes a MESSAGE saying what you achieved") args = {"message": " ".join(rest)} try: check_arguments(tool, args) except ValueError as exc: raise UsageError(str(exc)) from None return tool, args
def _json_argument(text): try: return parse_json(text) except (ValueError, RecursionError) as exc: raise UsageError("not valid JSON: %s" % exc) from None
def _integer(text, what): try: return int(text) except ValueError: raise UsageError("%s must be an integer, got %r" % (what, text)) from None
def default_directory(): return os.environ.get("TEXTCRAFT_DIR") or os.path.dirname(os.path.abspath(__file__))
def run(argv, directory=None, recipes=None): """Run a command line against the task in ``directory`` (default ``$TEXTCRAFT_DIR``, else this file's directory), with the recipes ``recipes`` (default ``$TEXTCRAFT_RECIPES``, else the directory's ``recipes.json``)."""
if not argv or argv[0] in ("-h", "--help", "help"): return Result(0 if argv else 2, USAGE) if argv[0] == "--version": return Result(0, "textcraft %s" % VERSION) try: tool, args = parse_command(argv) except UsageError as exc: return Result(2, err="textcraft: %s\n\n%s" % (exc, USAGE)) directory = directory or default_directory() try: task = load_task(os.path.join(directory, TASK_FILE)) book = RecipeBook.load(recipes or os.environ.get("TEXTCRAFT_RECIPES") or os.path.join(directory, RECIPES_FILE)) except (OSError, ValueError, KeyError) as exc: return Result(3, err="textcraft: cannot load the task: %s" % exc) if task["recipes_sha256"] != book.sha256: return Result(3, err="textcraft: the recipes (%s) are not the ones of this task" % book.sha256) path = os.path.join(directory, LOG_FILE) try: fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | _CLOEXEC, 0o644) except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror return Result(3, err="textcraft: cannot open the action log %s: %s" % (path, why)) try: try: fcntl.flock(fd, fcntl.LOCK_EX) except OSError: pass # a file system without locks: commands are not expected to overlap if not stat.S_ISREG(os.fstat(fd).st_mode): return Result(3, err="textcraft: the action log %s is not a regular file" % path) data = _read_all(fd) game = Game(book, task) try: seq = replay(game, data) + 1 except LogError as exc: return Result( 3, err="textcraft: the action log %s does not replay (%s); the episode cannot continue" % (path, exc) ) if game.finished: return Result( 1, "Error: the episode is finished (textcraft finish was called); no command is accepted after it" ) try: text = game.call(tool, args) except Exception as exc: return Result(2, err="textcraft: cannot run %s: %s: %s" % (tool, type(exc).__name__, exc)) ok = text.startswith(CRAFTED) line = encode_record(seq, tool, args, ok) if len(data) + len(line) > LOG_CAP_BYTES: return Result(1, "Error: the action log is full (%d bytes); no command is accepted" % LOG_CAP_BYTES) _write_all(fd, line) finally: os.close(fd) return Result(1 if tool == "craft" and not ok else 0, text)
def _read_all(fd): os.lseek(fd, 0, os.SEEK_SET) chunks = [] while True: chunk = os.read(fd, 1 << 20) if not chunk: return b"".join(chunks) chunks.append(chunk)
def _write_all(fd, data): view = memoryview(data) while view: view = view[os.write(fd, view) :]
# ---------------------------------------------------------------------------------------------------- the verifier
def read_untrusted(root, relative, cap=LOG_CAP_BYTES): """The bytes of ``root/relative``, reached without following a symbolic link below ``root``; None when it does not exist. LogError when it is not a regular file, or holds more than ``cap`` bytes."""
parts = [part for part in relative.split("/") if part not in ("", ".")] if not parts or ".." in parts: raise ValueError("%r is not a path below the root" % relative) directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | _CLOEXEC) try: for part in parts[:-1]: try: below = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: raise LogError("%s on the way to the action log is not a directory (%s)" % (part, exc.strerror)) os.close(directory) directory = below try: fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | _CLOEXEC, dir_fd=directory) except FileNotFoundError: return None except OSError as exc: why = "it is a symbolic link" if exc.errno == errno.ELOOP else exc.strerror raise LogError("cannot open the action log: %s" % why) finally: os.close(directory) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode): raise LogError("the action log is not a regular file") if info.st_size > cap: raise LogError("the action log holds %d bytes; the limit is %d" % (info.st_size, cap)) chunks, total = [], 0 while total <= cap: chunk = os.read(fd, min(1 << 20, cap + 1 - total)) if not chunk: break chunks.append(chunk) total += len(chunk) if total > cap: raise LogError("the action log holds more than %d bytes" % cap) return b"".join(chunks) finally: os.close(fd)
def verify(task_path, recipes_path, root, log, out=None): """Grade the log at ``root/log`` against the trusted task and recipes; the verdict (``reward`` and why). Writes ``reward.json`` and ``textcraft-verdict.json`` into ``out`` when given."""
task = load_task(task_path) book = RecipeBook.load(recipes_path) if task["recipes_sha256"] != book.sha256: raise ValueError("the verifier's recipes %s are not the task's %s" % (book.sha256, task["recipes_sha256"])) game = Game(book, task) verdict = {"reward": 0.0, "task": task["name"], "version": VERSION, "records": 0, "crafts": 0, "finished": False} try: data = read_untrusted(root, log) if data is None: verdict["reason"] = "no action log: no textcraft command ran" else: verdict["log_bytes"] = len(data) verdict["records"] = replay(game, data) verdict["crafts"] = game.crafts verdict["finished"] = game.finished if not game.finished: verdict["reason"] = "the episode did not end with textcraft finish" elif game.score >= 1.0: verdict["reward"] = 1.0 verdict["reason"] = "finished with every target crafted" elif game.reward_misc.get("missing_items"): verdict["reason"] = "finished without every target crafted" verdict["missing_items"] = game.reward_misc["missing_items"] else: verdict["reason"] = "finished with an empty message" except LogError as exc: verdict["reason"] = "the action log is not one the game wrote: %s" % exc if out is not None: _write_new(out, VERDICT_FILE, json.dumps(verdict, indent=1, sort_keys=True) + "\n") _write_new(out, REWARD_FILE, json.dumps({"reward": verdict["reward"]}) + "\n") return verdict
def _write_new(directory, name, text): """Write ``directory/name`` through a new file and a rename, so the name ends up a regular file whatever was there."""
temporary = os.path.join(directory, ".%s.%d.tmp" % (name, os.getpid())) fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | _CLOEXEC, 0o644) try: _write_all(fd, text.encode("utf-8")) os.fsync(fd) finally: os.close(fd) os.replace(temporary, os.path.join(directory, name))
def verify_main(argv): parser = argparse.ArgumentParser(prog="textcraft_game.py verify", description="Grade a TextCraft action log.") parser.add_argument("--task", required=True, help="the trusted task.json") parser.add_argument("--recipes", required=True, help="the trusted recipes.json") parser.add_argument("--root", required=True, help="the sandbox root the log path is below") parser.add_argument("--log", required=True, help="the log's path below the root") parser.add_argument("--out", required=True, help="the verifier's output directory (reward.json)") options = parser.parse_args(argv) try: verdict = verify(options.task, options.recipes, options.root, options.log, options.out) except (OSError, ValueError, KeyError) as exc: print("textcraft verify: cannot grade: %s" % exc, file=sys.stderr) return 1 print( "reward %g: %s (%d records, %d crafts)" % (verdict["reward"], verdict["reason"], verdict["records"], verdict["crafts"]) ) return 0
def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) if argv[:1] == ["verify"]: return verify_main(argv[1:]) result = run(argv) if result.out: print(result.out) if result.err: print(result.err, file=sys.stderr) return result.code
if __name__ == "__main__": sys.exit(main())1234567891011121314151617181920212223242526272829303132333435363738You are an agent in a crafting game. Your goal is to craft items by combining ingredients.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.
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.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.
## Task
Craft the following items: 3x c0_i3_10
## Actions
You act through the `textcraft` command in the shell:
1. `textcraft craft TARGET TOTAL_COUNT INGREDIENT=COUNT [INGREDIENT=COUNT ...]` Craft items using ingredients from your inventory. - INGREDIENT=COUNT pairs: the items to consume and how many of each - TARGET TOTAL_COUNT: the item to craft and its total count, which must be divisible by the recipe's result_count - Example: `textcraft craft m2_i2 2 m0_i1=2 m1_i1=1`
2. `textcraft info ITEM [ITEM ...]` Get recipe information for items. - Prints a JSON list with {"item": str, "can_craft": bool, "is_base": bool, "in_inventory": int, "crafting_depth": int, "recipes": [...]} - crafting_depth indicates complexity: 0=base item, 1=direct craft, 2+=needs intermediate steps - Each recipe shows {"ingredients": {...}, "result_count": int} - Example: `textcraft info m2_i2 raw_m0`
3. `textcraft inventory` View your current inventory. - Prints JSON {item_name: count}
4. `textcraft finish MESSAGE` Complete the task. - Example: `textcraft finish "Successfully crafted all required items"` - The task is graded when you finish, on what your inventory gained; no command is accepted after it, and a task that never finishes counts as failed.
The game keeps its state in `/app/textcraft`; change it only through the `textcraft` command.12345678910111213#!/bin/bash# The reference solution of textcraft-synth-train-easy-00012: the source task's gold trajectory (5 crafts), then finish.set -euo pipefailif ! command -v textcraft >/dev/null 2>&1; then # platoon's process provider runs no image, so there is no textcraft command: run the game file itself. textcraft() { python3 -I "${PLATOON_SANDBOX_ROOT:-}/app/textcraft/textcraft_game.py" "$@"; }fitextcraft craft c5_i1 4 c1_ore=1textcraft craft c5_i2_15 2 c5_i1=2 c4_ore=1textcraft craft c4_i2_24 2 c5_ore=2 c6_ore=2textcraft craft c2_i2_22 2 c9_ore=1 c6_ore=1textcraft craft c0_i3_10 4 c5_i2_15=2 c4_i2_24=2 c2_i2_22=2textcraft finish 'Crafted 3x c0_i3_10'123456789101112131415161718192021222324252627282930313233schema_version = "1.4"# The game's action log: a separate verifier receives it at the same path.artifacts = ["/app/textcraft/actions.jsonl"]
[task]name = "textcraft-synth/train-easy-00012"description = "TextCraft-Synth: craft the following items: 3x c0_i3_10 (easy, crafting depth 3)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "train"difficulty = "easy"max_depth = 3num_craft_steps = 5goal = "Craft the following items: 3x c0_i3_10"source_task_id = "textcraft_synth.train.12"env_task_id = "train:12"env_split_task_id = "train-easy:3"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 660.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-train-easy-00012: task.json sha256:af9325480cb46dc4c5f34942c321f7cd3f15a9c79c3b187a3810c147d2d64926FROM docker.io/library/python:3.12-slim@sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1# The same image as the task's environment, so one image serves the agent and the verifier.RUN set -eux; \ printf '#!/bin/sh\nexec python3 -I /app/textcraft/textcraft_game.py "$@"\n' \ > /usr/local/bin/textcraft; \ chmod 0755 /usr/local/bin/textcraft; \ apt-get -o APT::Sandbox::User=root update; \ apt-get -o APT::Sandbox::User=root install -y --no-install-recommends tmux; \ rm -rf /var/lib/apt/lists/*# The verifier's trusted copies of the grader, the game, the recipes and the task.WORKDIR /appCOPY test.sh textcraft_game.py recipes.json task.json /tests/LICENSEAdded+21
README.mdAdded+239
registry.jsonAdded
splits.jsonAdded
task-index.jsonAdded
tasks/textcraft-synth-train-easy-00006/environment/DockerfileAdded+17
tasks/textcraft-synth-train-easy-00006/environment/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00006/environment/task.jsonAdded+17
tasks/textcraft-synth-train-easy-00006/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00006/instruction.mdAdded+38
tasks/textcraft-synth-train-easy-00006/solution/solve.shAdded+12
tasks/textcraft-synth-train-easy-00006/task.tomlAdded+33
tasks/textcraft-synth-train-easy-00006/tests/DockerfileAdded+13
tasks/textcraft-synth-train-easy-00006/tests/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00006/tests/task.jsonAdded+17
tasks/textcraft-synth-train-easy-00006/tests/test.shAdded+17
tasks/textcraft-synth-train-easy-00006/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00008/environment/DockerfileAdded+17
tasks/textcraft-synth-train-easy-00008/environment/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00008/environment/task.jsonAdded+17
tasks/textcraft-synth-train-easy-00008/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00008/instruction.mdAdded+38
tasks/textcraft-synth-train-easy-00008/solution/solve.shAdded+12
tasks/textcraft-synth-train-easy-00008/task.tomlAdded+33
tasks/textcraft-synth-train-easy-00008/tests/DockerfileAdded+13
tasks/textcraft-synth-train-easy-00008/tests/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00008/tests/task.jsonAdded+17
tasks/textcraft-synth-train-easy-00008/tests/test.shAdded+17
tasks/textcraft-synth-train-easy-00008/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00009/environment/DockerfileAdded+17
tasks/textcraft-synth-train-easy-00009/environment/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00009/environment/task.jsonAdded+16
tasks/textcraft-synth-train-easy-00009/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00009/instruction.mdAdded+38
tasks/textcraft-synth-train-easy-00009/solution/solve.shAdded+13
tasks/textcraft-synth-train-easy-00009/task.tomlAdded+33
tasks/textcraft-synth-train-easy-00009/tests/DockerfileAdded+13
tasks/textcraft-synth-train-easy-00009/tests/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00009/tests/task.jsonAdded+16
tasks/textcraft-synth-train-easy-00009/tests/test.shAdded+17
tasks/textcraft-synth-train-easy-00009/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00012/environment/DockerfileAdded+17
tasks/textcraft-synth-train-easy-00012/environment/recipes.jsonAdded
tasks/textcraft-synth-train-easy-00012/environment/task.jsonAdded+19
tasks/textcraft-synth-train-easy-00012/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-train-easy-00012/instruction.mdAdded+38
tasks/textcraft-synth-train-easy-00012/solution/solve.shAdded+13
tasks/textcraft-synth-train-easy-00012/task.tomlAdded+33
tasks/textcraft-synth-train-easy-00012/tests/DockerfileAdded+13
tasks/textcraft-synth-train-easy-00012/tests/recipes.jsonAdded