Add TextCraft-Synth 1.0: 3,154 Harbor tasks (part 39)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/textcraft-synth-val-extreme-00289/tests/task.jsonAdded+23
- tasks/textcraft-synth-val-extreme-00289/tests/test.shAdded+17
- tasks/textcraft-synth-val-extreme-00289/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00292/environment/DockerfileAdded+17
- tasks/textcraft-synth-val-extreme-00292/environment/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00292/environment/task.jsonAdded+22
- tasks/textcraft-synth-val-extreme-00292/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00292/instruction.mdAdded+38
- tasks/textcraft-synth-val-extreme-00292/solution/solve.shAdded+140
- tasks/textcraft-synth-val-extreme-00292/task.tomlAdded+33
- tasks/textcraft-synth-val-extreme-00292/tests/DockerfileAdded+13
- tasks/textcraft-synth-val-extreme-00292/tests/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00292/tests/task.jsonAdded+22
- tasks/textcraft-synth-val-extreme-00292/tests/test.shAdded+17
- tasks/textcraft-synth-val-extreme-00292/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00300/environment/DockerfileAdded+17
- tasks/textcraft-synth-val-extreme-00300/environment/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00300/environment/task.jsonAdded+24
- tasks/textcraft-synth-val-extreme-00300/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00300/instruction.mdAdded+38
- tasks/textcraft-synth-val-extreme-00300/solution/solve.shAdded+189
- tasks/textcraft-synth-val-extreme-00300/task.tomlAdded+33
- tasks/textcraft-synth-val-extreme-00300/tests/DockerfileAdded+13
- tasks/textcraft-synth-val-extreme-00300/tests/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00300/tests/task.jsonAdded+24
- tasks/textcraft-synth-val-extreme-00300/tests/test.shAdded+17
- tasks/textcraft-synth-val-extreme-00300/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00305/environment/DockerfileAdded+17
- tasks/textcraft-synth-val-extreme-00305/environment/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00305/environment/task.jsonAdded+21
- tasks/textcraft-synth-val-extreme-00305/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00305/instruction.mdAdded+38
- tasks/textcraft-synth-val-extreme-00305/solution/solve.shAdded+190
- tasks/textcraft-synth-val-extreme-00305/task.tomlAdded+33
- tasks/textcraft-synth-val-extreme-00305/tests/DockerfileAdded+13
- tasks/textcraft-synth-val-extreme-00305/tests/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00305/tests/task.jsonAdded+21
- tasks/textcraft-synth-val-extreme-00305/tests/test.shAdded+17
- tasks/textcraft-synth-val-extreme-00305/tests/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00307/environment/DockerfileAdded+17
- tasks/textcraft-synth-val-extreme-00307/environment/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00307/environment/task.jsonAdded+32
- tasks/textcraft-synth-val-extreme-00307/environment/textcraft_game.pyAdded+756
- tasks/textcraft-synth-val-extreme-00307/instruction.mdAdded+38
- tasks/textcraft-synth-val-extreme-00307/solution/solve.shAdded+111
- tasks/textcraft-synth-val-extreme-00307/task.tomlAdded+33
- tasks/textcraft-synth-val-extreme-00307/tests/DockerfileAdded+13
- tasks/textcraft-synth-val-extreme-00307/tests/recipes.jsonAdded
- tasks/textcraft-synth-val-extreme-00307/tests/task.jsonAdded+32
- tasks/textcraft-synth-val-extreme-00307/tests/test.shAdded+17
1234567891011121314151617181920212223{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00289", "world": "textcraft-synth", "goal": "Craft the following items: 2x c4_i12_12", "target_items": { "c4_i12_12": 2 }, "initial_inventory": { "c9_ore": 43743, "c6_ore": 23885, "c5_ore": 48898, "c7_ore": 18712, "c2_ore": 6379, "c3_ore": 17784, "c8_ore": 12626, "c1_ore": 9747, "c4_ore": 19438, "c0_ore": 10298, "raw_a3": 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-val-extreme-00292: task.json sha256:41f079e7a1f4ec90b856dae36ab3130e1bceb9ef85956f99e906064cedc2eeb6FROM 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/12345678910111213141516171819202122{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00292", "world": "textcraft-synth", "goal": "Craft the following items: 1x a1_i10_10_11", "target_items": { "a1_i10_10_11": 1 }, "initial_inventory": { "raw_a4": 1752, "raw_a0": 839, "raw_a1": 1877, "raw_a2": 178, "raw_a7": 110, "raw_a3": 528, "raw_a6": 74, "raw_a9": 338, "m4_ore": 5, "c1_ore": 2 }, "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 a1_i10_10_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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140#!/bin/bash# The reference solution of textcraft-synth-val-extreme-00292: the source task's gold trajectory (132 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 a0_i1 164 raw_a4=82textcraft craft a5_i1 56 raw_a0=56textcraft craft a1_i1_21 24 raw_a1=6textcraft craft a4_i1_24 60 raw_a7=20textcraft craft a1_i1_11 12 raw_a1=4textcraft craft a9_i1 330 raw_a1=220textcraft craft a0_i1_20 148 raw_a0=37textcraft craft a3_i1_23 28 raw_a6=14textcraft craft a7_i1_17 15 raw_a2=10textcraft craft a2_i1_12 120 raw_a3=40textcraft craft a8_i1_18 60 raw_a4=20textcraft craft a8_i1 34 raw_a9=17textcraft craft a2_i1_22 186 raw_a9=93textcraft craft a0_i1_10 36 raw_a4=9textcraft craft a5_i1_15 24 raw_a0=8textcraft craft a3_i1_13 14 raw_a0=14textcraft craft a6_i1_16 28 raw_a0=7textcraft craft a6_i1 60 raw_a4=40textcraft craft a4_i1_14 12 raw_a4=8textcraft craft a2_i2_12 142 raw_a1=71textcraft craft a6_i2_16 6 raw_a0=2 raw_a4=2textcraft craft a1_i2_11 8 a1_i1_21=4 raw_a2=8textcraft craft a9_i2_19 8 a4_i1_24=4 a1_i1_11=8textcraft craft a5_i2_15 24 raw_a3=8 raw_a2=8textcraft craft a2_i2_22 165 a9_i1=110 a0_i1_20=55textcraft craft a2_i2 90 raw_a4=60 a2_i1_12=60textcraft craft a0_i2_10 18 raw_a3=18 raw_a0=9textcraft craft a9_i2 12 a2_i1_12=4 a8_i1_18=8textcraft craft a3_i2_23 30 a9_i1=20 raw_a3=20textcraft craft a3_i2 76 a8_i1_18=38 raw_a4=76textcraft craft a1_i2 141 a0_i1=47 raw_a0=47textcraft craft a1_i2_21 48 raw_a3=24 a0_i1_10=24textcraft craft a4_i2_14 74 a9_i1=74 a2_i1_22=74textcraft craft a7_i2_17 33 raw_a2=22 a0_i1_20=22textcraft craft a8_i2 50 raw_a9=25 raw_a3=25textcraft craft a8_i2_18 24 a3_i1_13=12 a6_i1_16=24textcraft craft a6_i2 6 a8_i1_18=3 raw_a0=3textcraft craft a5_i2 57 a6_i1=38 raw_a4=19textcraft craft a7_i2 18 raw_a7=9 a4_i1_14=9textcraft craft a0_i2 6 a4_i1_24=6 a5_i1=3textcraft craft a4_i2 2 raw_a0=2 a4_i1_14=2textcraft craft a1_i3_21 15 a0_i1=30 a5_i1=30 a2_i2_12=30textcraft craft a2_i3 6 a6_i2_16=3 a1_i2_11=6textcraft craft a0_i3_20 47 a2_i2_22=94 a4_i1_24=47textcraft craft a2_i3_22 28 a3_i1_23=28 a2_i2_12=56textcraft craft a7_i3 12 a7_i1_17=12 a2_i2=12 a0_i2_10=6textcraft craft a4_i3 10 a9_i2=10 a8_i1=10textcraft craft a2_i3_12 16 a3_i2_23=16 a2_i1_22=32 a3_i2=16textcraft craft a0_i3_10 37 a2_i2=74 a1_i2=37 a2_i1_22=74textcraft craft a9_i3 36 a1_i2=36 a5_i1=18 a1_i2_21=18textcraft craft a3_i3 28 a1_i2=56 a0_i1=28textcraft craft a4_i3_14 16 a0_i2_10=8 a2_i2_22=8textcraft craft a6_i3_16 23 a2_i2_22=23 a8_i1=23 a5_i1_15=23textcraft craft a5_i3 19 a8_i2=19 a8_i2_18=19textcraft craft a3_i3_13 16 a2_i2_22=16 a9_i1=16 a4_i2_14=16textcraft craft a8_i3_18 27 a2_i2_12=54 a3_i2=54 a5_i2=54textcraft craft a1_i3_11 12 a2_i1_12=12 a1_i2_21=12 a0_i1=12textcraft craft a1_i3 1 a8_i2_18=1 a0_i1_20=1textcraft craft a3_i4 2 a1_i3_21=2 a2_i3=2 a9_i2_19=2textcraft craft a0_i4 12 a5_i2_15=24 a0_i3_20=24textcraft craft a4_i4_14 6 a9_i2_19=3 a7_i3=6textcraft craft a1_i4_11 10 a2_i3_22=20 a0_i3_10=10 a9_i3=20textcraft craft a7_i4 6 a4_i2_14=3 a3_i3=6 a4_i3_14=6textcraft craft a6_i4_16 6 a6_i3_16=3 a7_i2_17=6textcraft craft a3_i4_23 19 a7_i2_17=19 a8_i2=19 a4_i2_14=38textcraft craft a9_i4 3 a0_i2_10=3 a2_i3=3 a6_i2=3textcraft craft a5_i4 8 a3_i3_13=4 a0_i3_20=8 a8_i2=4textcraft craft a7_i4_17 3 a8_i2=3 a0_i3_10=6 a6_i3_16=6textcraft craft a0_i4_20 10 a1_i1_21=10 a5_i3=10textcraft craft a5_i4_15 9 a6_i3_16=9 a1_i3_21=9 a7_i2=18textcraft craft a2_i4_22 12 a8_i3_18=24 a1_i3_11=12textcraft craft a2_i4_12 7 a3_i2_23=14 a2_i3_12=14 a3_i3_13=7textcraft craft a6_i4 3 a4_i3=6 a0_i3_10=3 a0_i2=6textcraft craft a4_i4 4 a0_i3_10=8 a2_i2_22=8 a3_i2=4textcraft craft a8_i4_18 2 a9_i3=4 a2_i2_12=2 a8_i2_18=4textcraft craft a0_i4_10 1 raw_a3=2 a1_i2=2 a1_i3_21=2textcraft craft a1_i4 2 a5_i2=1 a8_i2=1 a3_i2=2textcraft craft a3_i4_13 2 a5_i2=2 a6_i2=2 a4_i3_14=4textcraft craft a2_i4 2 a6_i2_16=2 a2_i3_22=2textcraft craft a3_i5 2 a2_i3_22=1 a7_i3=1 a4_i3=1textcraft craft a6_i5 2 a4_i4_14=2 a2_i3_12=2textcraft craft a0_i5 7 a1_i4_11=7 a9_i3=7 a3_i3=7textcraft craft a7_i5_17 1 a7_i4=1 a6_i4_16=1 a5_i3=1textcraft craft a1_i5 2 a7_i4=2 a3_i4_23=2 a9_i4=2textcraft craft a1_i5_11 4 a8_i3_18=2 a7_i4_17=2textcraft craft a0_i5_10 7 a5_i4=7 a3_i4_23=7 a0_i3_20=7textcraft craft a5_i5 6 a3_i3=3 a0_i4_20=3 a5_i4_15=3textcraft craft a2_i5_12 2 a4_i3=2 a6_i3_16=2 a0_i4=2textcraft craft a0_i5_20 8 a2_i4_12=4 a0_i3_10=4 a3_i4_23=4textcraft craft a4_i5 4 a6_i4_16=2 a0_i3_10=2textcraft craft a2_i5_22 4 a2_i4_22=2 a9_i3=2textcraft craft a1_i5_21 1 a2_i4_22=1 a0_i4=1textcraft craft a8_i5 2 a4_i4=2 a1_i3_21=2textcraft craft a6_i5_16 3 a2_i3_22=3 a3_i4_23=3textcraft craft a5_i5_15 1 a3_i3=1 a0_i4_10=1 a2_i3_22=1textcraft craft a4_i5_14 1 a4_i2=1 a1_i4=1 a1_i3=1textcraft craft a9_i5 2 a2_i4_22=2 a4_i4=2textcraft craft a4_i6_6 1 a3_i4=1 a0_i4=1 a3_i5=1textcraft craft a1_i6_6_21 1 a7_i5_17=1 a1_i4_11=1 a1_i5=1 a5_i4=1textcraft craft a9_i6_6_19 1 a1_i5_11=1 a0_i5_10=1textcraft craft a0_i6_6 1 a2_i5_12=1 a1_i5_11=1textcraft craft a0_i6_6_20 2 a5_i5=2 a2_i4_22=2 a0_i5_10=2 a1_i4_11=2textcraft craft a7_i6_6 3 a0_i5_20=3 a5_i5=3 a5_i4_15=3textcraft craft a2_i6_6 3 a2_i4_22=3 a6_i4=3textcraft craft a6_i6_6 1 a0_i5_20=1 a0_i5=1 a1_i5_21=1 a0_i4=1textcraft craft a1_i6_6_11 3 a0_i4_20=3 a0_i4=3textcraft craft a3_i6_6_13 2 a3_i3=2 a4_i4_14=2 a6_i5_16=2textcraft craft a5_i6_6_15 2 a0_i5=2 a8_i4_18=2 a0_i5_10=2textcraft craft a3_i6_6 2 a6_i4_16=2 a0_i4=2 a0_i5_10=2textcraft craft a5_i6_6 2 a0_i5=2 a0_i4=2textcraft craft a0_i6_6_10 1 a4_i5=1 a1_i5_11=1 a7_i4=1 a5_i5_15=1textcraft craft a9_i6_6 1 a4_i5_14=1 a0_i5_20=1 a9_i4=1textcraft craft a8_i6_6_18 1 a1_i5=1 a4_i4_14=1textcraft craft a4_i6_6_14 2 a9_i5=2 a3_i4_13=2 a7_i4=2 a2_i4=2textcraft craft a2_i7_7_12 2 a6_i5=2 a0_i5=2textcraft craft a1_i7_7 1 a1_i6_6_21=1 a3_i5=1textcraft craft a9_i7_7 1 a9_i6_6_19=1 a5_i5=1textcraft craft a3_i7_7_13 1 a0_i6_6_20=1 a7_i6_6=1textcraft craft a8_i7_7_18 2 a4_i5=2 a0_i5_20=2 a2_i5_22=2textcraft craft a4_i7_7_14 1 a2_i6_6=1 a6_i6_6=1textcraft craft a9_i7_7_19 2 a7_i6_6=2 a1_i6_6_11=2 a8_i5=2textcraft craft a2_i7_7 2 a3_i6_6_13=2 a2_i5_22=2 a5_i6_6_15=2textcraft craft a0_i7_7 2 a3_i6_6=2 a5_i6_6=2textcraft craft a7_i7_7_17 1 a6_i5_16=1 a0_i6_6_20=1 a0_i6_6_10=1 a9_i6_6=1textcraft craft a3_i7_7 1 a2_i5_12=1 a1_i6_6_11=1 a8_i6_6_18=1 a4_i6_6_14=1textcraft craft a5_i8_8 1 a2_i7_7_12=1 a1_i7_7=1 a9_i7_7=1 a0_i6_6=1textcraft craft a5_i8_8_15 1 a8_i7_7_18=1 a4_i7_7_14=1 a9_i7_7_19=1 a2_i7_7=1 a0_i7_7=1textcraft craft a7_i8_8_17 1 a2_i6_6=1 a8_i7_7_18=1 a0_i7_7=1 a7_i7_7_17=1textcraft craft a1_i8_8_21 1 a3_i7_7=1 a2_i7_7_12=1 a2_i7_7=1 a4_i6_6_14=1 a2_i6_6=1textcraft craft a6_i9_9_16 1 a5_i8_8=1 a3_i7_7_13=1 a5_i8_8_15=1textcraft craft a0_i9_9_10 1 a7_i8_8_17=1 a1_i8_8_21=1 a9_i7_7_19=1textcraft craft a1_i10_10_11 1 a4_i6_6=1 a6_i9_9_16=1 a0_i9_9_10=1textcraft finish 'Crafted 1x a1_i10_10_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/val-extreme-00292"description = "TextCraft-Synth: craft the following items: 1x a1_i10_10_11 (extreme, crafting depth 10)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "val"difficulty = "extreme"max_depth = 10num_craft_steps = 132goal = "Craft the following items: 1x a1_i10_10_11"source_task_id = "textcraft_synth.val.292"env_task_id = "val:292"env_split_task_id = "val-extreme:60"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 1920.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-val-extreme-00292: task.json sha256:41f079e7a1f4ec90b856dae36ab3130e1bceb9ef85956f99e906064cedc2eeb6FROM 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/12345678910111213141516171819202122{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00292", "world": "textcraft-synth", "goal": "Craft the following items: 1x a1_i10_10_11", "target_items": { "a1_i10_10_11": 1 }, "initial_inventory": { "raw_a4": 1752, "raw_a0": 839, "raw_a1": 1877, "raw_a2": 178, "raw_a7": 110, "raw_a3": 528, "raw_a6": 74, "raw_a9": 338, "m4_ore": 5, "c1_ore": 2 }, "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-val-extreme-00300: task.json sha256:7a8960ebc84248e01171892b3f8d6411658c78c631d543e648cfb769cf8d19a4FROM 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/123456789101112131415161718192021222324{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00300", "world": "textcraft-synth", "goal": "Craft the following items: 1x t7_i11_11_17", "target_items": { "t7_i11_11_17": 1 }, "initial_inventory": { "raw_t4": 2902, "raw_t1": 5790, "raw_t3": 3097, "raw_t6": 2780, "raw_t9": 4802, "raw_t5": 5632, "raw_t0": 7054, "raw_t7": 1845, "raw_t8": 4073, "c8_ore": 1, "raw_a9": 2, "raw_o7": 4 }, "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 t7_i11_11_17
## 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189#!/bin/bash# The reference solution of textcraft-synth-val-extreme-00300: the source task's gold trajectory (181 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 t1_i1_21 464 raw_t4=116textcraft craft t8_i1 1414 raw_t1=707textcraft craft t2_i1 74 raw_t3=74textcraft craft t3_i1_23 76 raw_t6=38textcraft craft t5_i1 242 raw_t1=121textcraft craft t0_i1_10 435 raw_t9=290textcraft craft t2_i1_12 302 raw_t6=151textcraft craft t1_i1 742 raw_t5=742textcraft craft t7_i1 746 raw_t0=746textcraft craft t9_i1 362 raw_t7=362textcraft craft t4_i1_24 716 raw_t5=716textcraft craft t6_i1_16 1518 raw_t0=506textcraft craft t0_i1 480 raw_t1=320textcraft craft t4_i1 868 raw_t8=434textcraft craft t3_i1_13 180 raw_t4=120textcraft craft t8_i1_18 573 raw_t9=382textcraft craft t6_i1 864 raw_t3=432textcraft craft t1_i1_11 255 raw_t0=170textcraft craft t2_i1_22 111 raw_t1=74textcraft craft t4_i1_14 54 raw_t1=18textcraft craft t9_i1_19 34 raw_t3=17textcraft craft t0_i2_20 339 t1_i1_21=226 t8_i1=226textcraft craft t3_i2 75 t2_i1=25 t3_i1_23=25textcraft craft t6_i2 504 t0_i1_10=252 raw_t9=252textcraft craft t0_i2_10 224 t2_i1_12=224 t1_i1=224textcraft craft t7_i2_17 201 t4_i1_24=134 raw_t8=134textcraft craft t3_i2_13 748 t8_i1=748 t6_i1_16=748textcraft craft t2_i2 39 raw_t8=26 raw_t1=26textcraft craft t5_i2 570 t4_i1=380 t6_i1_16=190textcraft craft t1_i2_21 156 t3_i1_13=78 t2_i1_12=78textcraft craft t4_i2_14 156 t0_i1=78 t4_i1=156textcraft craft t1_i2 183 t7_i1=122 t8_i1_18=61textcraft craft t0_i2 184 t4_i1=92 raw_t6=92textcraft craft t8_i2_18 282 t0_i1=188 t6_i1=94textcraft craft t1_i2_11 252 t6_i1=252 raw_t4=252textcraft craft t2_i2_22 222 t1_i1_11=222 t1_i1=222textcraft craft t7_i2 126 t5_i1=42 raw_t7=84textcraft craft t9_i2_19 168 t7_i1=56 t9_i1=56textcraft craft t4_i2 150 raw_t8=75 raw_t9=75textcraft craft t8_i2 528 raw_t6=352 t8_i1_18=176textcraft craft t9_i2 402 t6_i1_16=134 t4_i1_24=268textcraft craft t3_i2_23 33 t2_i1_22=22 raw_t5=22textcraft craft t6_i2_16 62 t4_i1_14=31 raw_t7=62textcraft craft t2_i2_12 18 t6_i1_16=6 raw_t4=6textcraft craft t5_i2_15 9 t9_i1_19=3 raw_t0=6textcraft craft t3_i3 96 t5_i1=96 t6_i2=96textcraft craft t6_i3_16 48 t0_i2_10=96 t7_i1=96textcraft craft t1_i3_11 116 t9_i1=232 t7_i2_17=116 t3_i2_13=116textcraft craft t1_i3 82 t1_i1_21=82 t0_i1_10=82textcraft craft t2_i3_12 30 t0_i1=30 t5_i1=30textcraft craft t3_i3_23 156 t1_i2_21=156 t4_i2_14=156 t5_i2=312textcraft craft t6_i3 91 t1_i2=182 t0_i2=91textcraft craft t5_i3_15 282 t6_i1=282 t7_i1=282 t0_i2_20=282textcraft craft t9_i3_19 42 t1_i2_11=84 t0_i2=84 t7_i2_17=84textcraft craft t5_i3 201 t2_i2_22=201 t6_i2=402 t3_i2_13=402textcraft craft t0_i3_10 136 t7_i2=68 t9_i2_19=68textcraft craft t8_i3_18 140 t8_i1_18=140 t4_i2=70textcraft craft t3_i3_13 162 t1_i2_11=162 t8_i2=324 t9_i2=324textcraft craft t2_i3_22 132 t8_i2=132 t1_i1=264textcraft craft t4_i3_14 38 t8_i2_18=38 t9_i2_19=38 t9_i2=38textcraft craft t0_i3_20 36 t3_i2=18 t3_i1_13=36 t0_i2_10=36textcraft craft t1_i3_21 34 t7_i2=17 t0_i1_10=17textcraft craft t2_i3 34 t3_i1_13=34 t0_i1_10=17 t2_i2_22=17textcraft craft t0_i3 26 t9_i1_19=13 t0_i1_10=26 t8_i1=26textcraft craft t9_i3 16 t6_i1=16 t2_i2_12=16 t4_i2=16textcraft craft t7_i3 42 t3_i2_13=21 t7_i1=21 t2_i1_22=21textcraft craft t8_i3 17 t4_i2=17 t6_i1_16=34textcraft craft t7_i3_17 1 t2_i2_12=2 t1_i2_11=2 t6_i2_16=2textcraft craft t8_i4_18 43 t0_i2_20=43 t3_i2=43 t3_i3=86textcraft craft t3_i4_13 37 t2_i2=37 t1_i3=74textcraft craft t6_i4 78 t5_i2=78 t3_i3_23=78 t6_i3=39textcraft craft t2_i4 77 t8_i2_18=77 t3_i2_13=77 t5_i3_15=154textcraft craft t1_i4_11 54 t5_i3=108 t8_i2_18=108 t0_i3_10=108textcraft craft t0_i4 56 t8_i3_18=112 t3_i2_13=112 t5_i3_15=112textcraft craft t1_i4 28 t8_i3_18=14 t3_i3_13=28textcraft craft t5_i4_15 30 t8_i2=15 t5_i3=30textcraft craft t0_i4_20 33 t4_i2=33 t0_i2_10=66textcraft craft t7_i4 66 t2_i3_22=66 t3_i3_13=33 t1_i3_11=33textcraft craft t1_i4_21 10 t7_i2=10 t5_i3=10textcraft craft t2_i4_12 31 t3_i2_23=31 t4_i3_14=31textcraft craft t3_i4_23 6 t9_i3_19=3 t9_i2_19=3 t0_i3_20=6textcraft craft t8_i4 6 t2_i3=6 t6_i2=6 t9_i2_19=6textcraft craft t3_i4 42 t8_i2=21 t3_i3_13=21 t6_i2_16=21textcraft craft t9_i4 23 t5_i2=46 t0_i3=23textcraft craft t4_i4 28 t5_i2=28 t7_i3=14textcraft craft t9_i4_19 10 t1_i3_21=10 t6_i2_16=10textcraft craft t2_i4_22 8 t0_i2=8 t5_i2_15=8textcraft craft t5_i4 14 t8_i2_18=7 t2_i3=14textcraft craft t7_i4_17 4 t1_i2_11=4 t3_i3=8 raw_t0=4textcraft craft t4_i4_14 4 t8_i2_18=4 t1_i3=4textcraft craft t6_i4_16 12 t1_i3_21=6 t0_i3_20=6textcraft craft t1_i5_11 35 t6_i3_16=35 t1_i3_11=35textcraft craft t3_i5 30 t3_i4_13=30 t2_i3_12=30 t6_i4=30textcraft craft t9_i5_19 38 t2_i4=19 t9_i3_19=19textcraft craft t2_i5 48 t1_i4_11=24 t6_i4=24 t0_i4=24textcraft craft t3_i5_23 16 t1_i4=16 t5_i4_15=16textcraft craft t9_i5 28 t0_i4_20=14 t7_i4=14textcraft craft t8_i5_18 13 t5_i3=13 t5_i4_15=13 t6_i3_16=13textcraft craft t7_i5 12 t2_i4_12=6 t0_i3_10=6textcraft craft t4_i5 6 t1_i3_21=3 t1_i3_11=3 t8_i4=3textcraft craft t2_i5_22 8 t3_i4=4 t4_i3_14=4 t3_i4_13=4textcraft craft t7_i5_17 16 t9_i3=16 t7_i4=16 t8_i1_18=16textcraft craft t4_i5_14 4 t2_i4=2 t9_i4_19=2 t2_i4_22=2textcraft craft t1_i5 4 t5_i4=2 t9_i4_19=2 t7_i4_17=2textcraft craft t5_i5_15 15 t0_i3_10=15 t8_i3=15 t0_i3_20=15textcraft craft t2_i5_12 14 t7_i3=14 t3_i4=14 t8_i4_18=14textcraft craft t6_i5_16 15 t2_i4_12=15 t5_i3_15=15 t3_i4=15textcraft craft t1_i5_21 10 t2_i4=5 t1_i3_11=5textcraft craft t6_i5 6 t2_i1_22=3 t9_i4=3 t3_i4=3textcraft craft t0_i5 12 t4_i4=6 t6_i3=6 t7_i4=6textcraft craft t3_i5_13 1 t1_i3_11=1 t8_i4=1textcraft craft t0_i5_20 2 t9_i4_19=2 t0_i3=2 t0_i4=2textcraft craft t8_i5 2 t9_i4=1 t3_i3=1 t6_i3=1textcraft craft t0_i5_10 1 t3_i3=1 t7_i4_17=1textcraft craft t5_i5 1 t2_i3=1 t7_i3_17=1 t4_i4=1textcraft craft t8_i6_6 25 t8_i4_18=25 t1_i5_11=25 t3_i5=25textcraft craft t3_i6_6_13 23 t2_i4=23 t9_i5_19=23 t2_i5=23textcraft craft t8_i6_6_18 10 t3_i5_23=10 t9_i5=10 t8_i5_18=10 t1_i4_21=10textcraft craft t0_i6_6_10 5 t3_i4_23=5 t2_i5=5 t4_i5=5 t2_i5_22=5textcraft craft t6_i6_6_16 9 t7_i4=9 t9_i4=9textcraft craft t9_i6_6 9 t7_i5_17=9 t2_i5=9 t4_i4=9 t1_i5_11=9textcraft craft t4_i6_6 4 t4_i5_14=4 t5_i4=4textcraft craft t2_i6_6 4 t4_i4_14=4 t2_i4_12=4textcraft craft t5_i6_6_15 5 t9_i5=5 t7_i5=5 t0_i4_20=5textcraft craft t2_i6_6_22 9 t2_i5=9 t6_i5_16=9 t9_i5=9textcraft craft t3_i6_6 6 t9_i4=6 t5_i4=6 t6_i5=6textcraft craft t5_i6_6 6 t7_i5_17=6 t2_i5_12=6 t0_i5=6textcraft craft t4_i6_6_14 11 t5_i5_15=11 t1_i4=11 t6_i4_16=11textcraft craft t0_i6_6_20 4 t2_i4_22=4 t3_i5=4textcraft craft t1_i6_6_21 4 t2_i4=4 t0_i5=4 t1_i4_11=4 t8_i4_18=4textcraft craft t2_i6_6_12 5 t9_i5_19=5 t4_i4=5 t0_i4=5textcraft craft t1_i6_6_11 1 t7_i4=1 t6_i5_16=1 t0_i5_20=1 t3_i5=1textcraft craft t1_i6_6 1 t2_i5=1 t9_i4=1 t0_i4=1textcraft craft t9_i6_6_19 1 t5_i4_15=1 t0_i5_10=1 t9_i5_19=1 t7_i5_17=1textcraft craft t0_i6_6 2 t2_i5_22=2 t1_i5_21=2 t1_i4_11=2 t3_i5_23=2textcraft craft t0_i7_7 4 t8_i6_6=4 t3_i6_6_13=4textcraft craft t9_i7_7 1 t8_i6_6=1 t7_i5=1textcraft craft t8_i7_7 6 t6_i6_6_16=6 t3_i6_6_13=6 t8_i6_6=6 t9_i6_6=6textcraft craft t5_i7_7_15 3 t9_i6_6=3 t4_i6_6=3 t1_i5=3 t2_i6_6=3textcraft craft t1_i7_7_21 4 t7_i5=4 t8_i6_6=4 t8_i6_6_18=4 t5_i5_15=4textcraft craft t7_i7_7_17 4 t5_i6_6_15=4 t2_i5_12=4textcraft craft t3_i7_7 3 t2_i6_6_22=3 t1_i5_21=3 t6_i5_16=3 t8_i5_18=3textcraft craft t0_i7_7_10 1 t9_i5=1 t8_i6_6=1textcraft craft t7_i7_7 2 t5_i6_6=2 t2_i5_12=2 t3_i5_23=2 t4_i6_6_14=2textcraft craft t5_i7_7 2 t1_i6_6_21=2 t7_i5=2 t3_i5_23=2 t2_i5_12=2textcraft craft t3_i7_7_13 4 t2_i6_6_22=4 t3_i6_6=4textcraft craft t4_i7_7 2 t3_i6_6_13=2 t6_i5_16=2textcraft craft t8_i7_7_18 8 t3_i6_6_13=8 t4_i6_6_14=8 t9_i5_19=8textcraft craft t1_i7_7_11 3 t8_i6_6_18=3 t6_i6_6_16=3 t9_i5=3 t1_i5_21=3textcraft craft t2_i7_7_22 2 t2_i6_6_12=2 t3_i6_6_13=2 t8_i3=2textcraft craft t1_i7_7 1 t0_i5=1 t0_i5_20=1 t1_i5_21=1 t2_i6_6=1textcraft craft t4_i7_7_14 1 t1_i6_6_21=1 t0_i5=1 t2_i5=1 t0_i6_6_10=1textcraft craft t9_i7_7_19 1 t4_i6_6_14=1 t8_i5=1textcraft craft t2_i7_7 1 t0_i6_6_10=1 t5_i6_6=1textcraft craft t2_i7_7_12 1 t9_i6_6_19=1 t1_i5_11=1textcraft craft t6_i7_7_16 1 t8_i6_6=1 t0_i6_6=1 t5_i6_6_15=1 t5_i5=1textcraft craft t6_i7_7 1 t0_i6_6=1 t8_i6_6=1textcraft craft t5_i8_8 1 t8_i6_6_18=1 t9_i7_7=1 t0_i6_6_10=1textcraft craft t3_i8_8 2 t5_i7_7_15=2 t0_i6_6_10=2 t1_i7_7_21=2 t7_i7_7_17=2textcraft craft t3_i8_8_13 1 t3_i6_6=1 t0_i7_7=1 t0_i7_7_10=1 t8_i6_6=1textcraft craft t6_i8_8_16 1 t7_i7_7=1 t3_i6_6=1 t4_i6_6=1 t0_i6_6_20=1 t5_i7_7=1textcraft craft t1_i8_8 3 t2_i6_6_12=3 t8_i6_6=3 t8_i7_7=3 t3_i7_7_13=3textcraft craft t9_i8_8 3 t5_i6_6=3 t8_i7_7_18=3 t0_i6_6_20=3 t1_i7_7_11=3textcraft craft t0_i8_8 1 t8_i6_6_18=1 t2_i6_6_22=1 t8_i7_7_18=1 t3_i7_7=1 t8_i6_6=1textcraft craft t9_i8_8_19 1 t3_i6_6_13=1 t1_i6_6_21=1 t1_i6_6_11=1 t2_i7_7_22=1textcraft craft t4_i8_8_14 1 t1_i6_6=1 t1_i7_7=1 t2_i6_6_22=1 t7_i7_7=1textcraft craft t8_i8_8_18 1 t8_i6_6=1 t4_i7_7_14=1 t8_i7_7_18=1textcraft craft t5_i8_8_15 1 t8_i6_6_18=1 t3_i7_7=1 t3_i7_7_13=1textcraft craft t2_i8_8_22 1 t2_i7_7=1 t8_i7_7_18=1 t2_i7_7_12=1 t8_i7_7=1textcraft craft t7_i8_8_17 1 t6_i7_7_16=1 t8_i7_7_18=1 t6_i7_7=1 t5_i7_7=1textcraft craft t1_i8_8_11 1 t8_i7_7=1 t8_i6_6=1 t1_i7_7_21=1textcraft craft t8_i9_9 1 t0_i7_7=1 t5_i8_8=1 t8_i7_7=1 t3_i8_8=1 t3_i7_7=1textcraft craft t3_i9_9 1 t6_i8_8_16=1 t1_i7_7_21=1 t1_i8_8=1textcraft craft t7_i9_9 1 t7_i7_7_17=1 t3_i5_13=1 t4_i7_7=1 t9_i8_8=1 t0_i8_8=1textcraft craft t0_i9_9_10 1 t9_i8_8_19=1 t5_i7_7_15=1 t8_i7_7_18=1 t4_i8_8_14=1textcraft craft t2_i9_9_12 1 t1_i8_8=1 t8_i8_8_18=1 t5_i8_8_15=1 t0_i7_7=1 t3_i8_8=1textcraft craft t0_i9_9 1 t7_i7_7_17=1 t9_i8_8=1 t2_i7_7_22=1 t0_i7_7=1 t9_i7_7_19=1textcraft craft t9_i9_9_19 1 t1_i8_8=1 t2_i8_8_22=1 t4_i7_7=1 t7_i8_8_17=1textcraft craft t7_i10_10 1 t3_i8_8_13=1 t3_i9_9=1 t7_i9_9=1 t0_i9_9_10=1textcraft craft t9_i10_10 1 t2_i9_9_12=1 t0_i9_9=1 t9_i9_9_19=1 t1_i8_8_11=1 t9_i8_8=1textcraft craft t7_i11_11_17 1 t8_i9_9=1 t7_i10_10=1 t9_i10_10=1textcraft finish 'Crafted 1x t7_i11_11_17'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/val-extreme-00300"description = "TextCraft-Synth: craft the following items: 1x t7_i11_11_17 (extreme, crafting depth 11)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "val"difficulty = "extreme"max_depth = 11num_craft_steps = 181goal = "Craft the following items: 1x t7_i11_11_17"source_task_id = "textcraft_synth.val.300"env_task_id = "val:300"env_split_task_id = "val-extreme:61"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 2460.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-val-extreme-00300: task.json sha256:7a8960ebc84248e01171892b3f8d6411658c78c631d543e648cfb769cf8d19a4FROM 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/123456789101112131415161718192021222324{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00300", "world": "textcraft-synth", "goal": "Craft the following items: 1x t7_i11_11_17", "target_items": { "t7_i11_11_17": 1 }, "initial_inventory": { "raw_t4": 2902, "raw_t1": 5790, "raw_t3": 3097, "raw_t6": 2780, "raw_t9": 4802, "raw_t5": 5632, "raw_t0": 7054, "raw_t7": 1845, "raw_t8": 4073, "c8_ore": 1, "raw_a9": 2, "raw_o7": 4 }, "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-val-extreme-00305: task.json sha256:5550ebe8a0d8be016407be976ccd3b8eab87a0b1c2c00c0a97f89f8244fb469aFROM 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/123456789101112131415161718192021{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00305", "world": "textcraft-synth", "goal": "Craft the following items: 2x a0_i11_11_20", "target_items": { "a0_i11_11_20": 2 }, "initial_inventory": { "raw_a1": 24334, "raw_a4": 23548, "raw_a3": 8690, "raw_a0": 12436, "raw_a9": 4958, "raw_a6": 1408, "raw_a2": 3391, "raw_a7": 1604, "raw_o0": 2 }, "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 a0_i11_11_20
## 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190#!/bin/bash# The reference solution of textcraft-synth-val-extreme-00305: the source task's gold trajectory (182 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 a8_i1_18 591 raw_a4=197textcraft craft a6_i1 540 raw_a4=360textcraft craft a2_i1_12 999 raw_a3=333textcraft craft a0_i1_10 248 raw_a4=62textcraft craft a0_i1 1592 raw_a4=796textcraft craft a2_i1_22 1692 raw_a9=846textcraft craft a9_i1 2895 raw_a1=1930textcraft craft a0_i1_20 1284 raw_a0=321textcraft craft a3_i1_23 504 raw_a6=252textcraft craft a8_i1 300 raw_a9=150textcraft craft a5_i1_15 204 raw_a0=68textcraft craft a3_i1_13 116 raw_a0=116textcraft craft a6_i1_16 232 raw_a0=58textcraft craft a5_i1 694 raw_a0=694textcraft craft a1_i1_21 132 raw_a1=33textcraft craft a4_i1_24 801 raw_a7=267textcraft craft a1_i1_11 90 raw_a1=30textcraft craft a7_i1_17 111 raw_a2=74textcraft craft a4_i1_14 102 raw_a4=68textcraft craft a2_i2_12 1808 raw_a1=904textcraft craft a3_i2 844 a8_i1_18=422 raw_a4=844textcraft craft a5_i2 633 a6_i1=422 raw_a4=211textcraft craft a1_i2_21 420 raw_a3=210 a0_i1_10=210textcraft craft a2_i2 807 raw_a4=538 a2_i1_12=538textcraft craft a1_i2 1512 a0_i1=504 raw_a0=504textcraft craft a2_i2_22 1779 a9_i1=1186 a0_i1_20=593textcraft craft a6_i2 76 a8_i1_18=38 raw_a0=38textcraft craft a0_i2_10 180 raw_a3=180 raw_a0=90textcraft craft a4_i2_14 696 a9_i1=696 a2_i1_22=696textcraft craft a6_i2_16 66 raw_a0=22 raw_a4=22textcraft craft a7_i2_17 330 raw_a2=220 a0_i1_20=220textcraft craft a8_i2 454 raw_a9=227 raw_a3=227textcraft craft a8_i2_18 228 a3_i1_13=114 a6_i1_16=228textcraft craft a1_i2_11 100 a1_i1_21=50 raw_a2=100textcraft craft a9_i2_19 64 a4_i1_24=32 a1_i1_11=64textcraft craft a5_i2_15 357 raw_a3=119 raw_a2=119textcraft craft a9_i2 96 a2_i1_12=32 a8_i1_18=64textcraft craft a4_i2 44 raw_a0=44 a4_i1_14=44textcraft craft a0_i2 136 a4_i1_24=136 a5_i1=68textcraft craft a3_i2_23 204 a9_i1=136 raw_a3=136textcraft craft a7_i2 114 raw_a7=57 a4_i1_14=57textcraft craft a8_i3_18 297 a2_i2_12=594 a3_i2=594 a5_i2=594textcraft craft a1_i3_11 138 a2_i1_12=138 a1_i2_21=138 a0_i1=138textcraft craft a0_i3_10 344 a2_i2=688 a1_i2=344 a2_i1_22=688textcraft craft a4_i3_14 130 a0_i2_10=65 a2_i2_22=65textcraft craft a3_i3 285 a1_i2=570 a0_i1=285textcraft craft a2_i3_22 406 a3_i1_23=406 a2_i2_12=812textcraft craft a6_i3_16 203 a2_i2_22=203 a8_i1=203 a5_i1_15=203textcraft craft a5_i3 110 a8_i2=110 a8_i2_18=110textcraft craft a1_i3_21 183 a0_i1=366 a5_i1=366 a2_i2_12=366textcraft craft a2_i3 98 a6_i2_16=49 a1_i2_11=98textcraft craft a0_i3_20 619 a2_i2_22=1238 a4_i1_24=619textcraft craft a7_i3 80 a7_i1_17=80 a2_i2=80 a0_i2_10=40textcraft craft a4_i3 96 a9_i2=96 a8_i1=96textcraft craft a1_i3 44 a8_i2_18=44 a0_i1_20=44textcraft craft a8_i3 48 a3_i1_23=96 a3_i2=48 a0_i2=96textcraft craft a3_i3_13 108 a2_i2_22=108 a9_i1=108 a4_i2_14=108textcraft craft a9_i3 506 a1_i2=506 a5_i1=253 a1_i2_21=253textcraft craft a2_i3_12 130 a3_i2_23=130 a2_i1_22=260 a3_i2=130textcraft craft a3_i3_23 9 a2_i2=9 a7_i2_17=9textcraft craft a2_i4_22 137 a8_i3_18=274 a1_i3_11=137textcraft craft a4_i4 28 a0_i3_10=56 a2_i2_22=56 a3_i2=28textcraft craft a3_i4_13 16 a5_i2=16 a6_i2=16 a4_i3_14=32textcraft craft a7_i4 98 a4_i2_14=49 a3_i3=98 a4_i3_14=98textcraft craft a2_i4 16 a6_i2_16=16 a2_i3_22=16textcraft craft a6_i4_16 86 a6_i3_16=43 a7_i2_17=86textcraft craft a3_i4 38 a1_i3_21=38 a2_i3=38 a9_i2_19=38textcraft craft a0_i4 178 a5_i2_15=356 a0_i3_20=356textcraft craft a1_i4 44 a5_i2=22 a8_i2=22 a3_i2=44textcraft craft a5_i4 142 a3_i3_13=71 a0_i3_20=142 a8_i2=71textcraft craft a3_i4_23 215 a7_i2_17=215 a8_i2=215 a4_i2_14=430textcraft craft a0_i4_10 38 raw_a3=76 a1_i2=76 a1_i3_21=76textcraft craft a4_i4_14 50 a9_i2_19=25 a7_i3=50textcraft craft a1_i4_11 154 a2_i3_22=308 a0_i3_10=154 a9_i3=308textcraft craft a8_i4_18 36 a9_i3=72 a2_i2_12=36 a8_i2_18=72textcraft craft a2_i4_12 37 a3_i2_23=74 a2_i3_12=74 a3_i3_13=37textcraft craft a0_i4_20 50 a1_i1_21=50 a5_i3=50textcraft craft a5_i4_15 57 a6_i3_16=57 a1_i3_21=57 a7_i2=114textcraft craft a7_i4_17 31 a8_i2=31 a0_i3_10=62 a6_i3_16=62textcraft craft a9_i4 60 a0_i2_10=60 a2_i3=60 a6_i2=60textcraft craft a8_i4 2 a8_i2_18=2 a1_i2_11=2 a8_i2=4textcraft craft a6_i4 20 a4_i3=40 a0_i3_10=20 a0_i2=40textcraft craft a9_i5 16 a2_i4_22=16 a4_i4=16textcraft craft a7_i5_17 32 a7_i4=32 a6_i4_16=32 a5_i3=32textcraft craft a3_i5 48 a2_i3_22=24 a7_i3=24 a4_i3=24textcraft craft a4_i5_14 44 a4_i2=44 a1_i4=44 a1_i3=44textcraft craft a7_i5 12 a6_i4_16=6 a7_i3=6 a8_i3=6textcraft craft a0_i5_10 112 a5_i4=112 a3_i4_23=112 a0_i3_20=112textcraft craft a9_i5_19 24 a0_i4_10=12 a8_i3=12textcraft craft a2_i5_12 32 a4_i3=32 a6_i3_16=32 a0_i4=32textcraft craft a6_i5_16 32 a2_i3_22=32 a3_i4_23=32textcraft craft a2_i5_22 28 a2_i4_22=14 a9_i3=14textcraft craft a0_i5 112 a1_i4_11=112 a9_i3=112 a3_i3=112textcraft craft a0_i5_20 74 a2_i4_12=37 a0_i3_10=37 a3_i4_23=37textcraft craft a5_i5 58 a3_i3=29 a0_i4_20=29 a5_i4_15=29textcraft craft a8_i5 12 a4_i4=12 a1_i3_21=12textcraft craft a6_i5 26 a4_i4_14=26 a2_i3_12=26textcraft craft a4_i5 26 a6_i4_16=13 a0_i3_10=13textcraft craft a1_i5_21 22 a2_i4_22=22 a0_i4=22textcraft craft a5_i5_15 26 a3_i3=26 a0_i4_10=26 a2_i3_22=26textcraft craft a1_i5_11 42 a8_i3_18=21 a7_i4_17=21textcraft craft a3_i5_13 30 a2_i4_22=30 a8_i3=30 a2_i3_12=30textcraft craft a8_i5_18 18 a2_i4_22=9 a3_i3_23=9 a0_i3_20=9textcraft craft a1_i5 34 a7_i4=34 a3_i4_23=34 a9_i4=34textcraft craft a2_i5 4 a8_i3_18=2 a8_i4=2 a0_i3_10=2textcraft craft a4_i6_6_14 16 a9_i5=16 a3_i4_13=16 a7_i4=16 a2_i4=16textcraft craft a4_i6_6 20 a3_i4=20 a0_i4=20 a3_i5=20textcraft craft a7_i6_6_17 14 a3_i4=14 a4_i5_14=14textcraft craft a3_i6_6 34 a6_i4_16=34 a0_i4=34 a0_i5_10=34textcraft craft a8_i6_6 16 a0_i4=16 a9_i5_19=16 a2_i5_12=16textcraft craft a3_i6_6_13 20 a3_i3=20 a4_i4_14=20 a6_i5_16=20textcraft craft a5_i6_6_15 36 a0_i5=36 a8_i4_18=36 a0_i5_10=36textcraft craft a7_i6_6 28 a0_i5_20=28 a5_i5=28 a5_i4_15=28textcraft craft a1_i6_6_11 20 a0_i4_20=20 a0_i4=20textcraft craft a5_i6_6 18 a0_i5=18 a0_i4=18textcraft craft a9_i6_6_19 16 a1_i5_11=16 a0_i5_10=16textcraft craft a2_i6_6_22 30 a0_i5=30 a3_i5_13=30textcraft craft a9_i6_6 18 a4_i5_14=18 a0_i5_20=18 a9_i4=18textcraft craft a6_i6_6_16 4 a1_i5=4 a3_i4=4 a7_i4=4 a2_i4_22=4textcraft craft a1_i6_6_21 20 a7_i5_17=20 a1_i4_11=20 a1_i5=20 a5_i4=20textcraft craft a2_i6_6 20 a2_i4_22=20 a6_i4=20textcraft craft a1_i6_6 8 a1_i5_21=8 a4_i5_14=8 a9_i5_19=8 a9_i4=8textcraft craft a0_i6_6 8 a2_i5_12=8 a1_i5_11=8textcraft craft a2_i6_6_12 10 a0_i4=10 a3_i5=10 a7_i4_17=10 a5_i4=10textcraft craft a0_i6_6_20 22 a5_i5=22 a2_i4_22=22 a0_i5_10=22 a1_i4_11=22textcraft craft a8_i6_6_18 4 a1_i5=4 a4_i4_14=4textcraft craft a0_i6_6_10 12 a4_i5=12 a1_i5_11=12 a7_i4=12 a5_i5_15=12textcraft craft a6_i6_6 6 a0_i5_20=6 a0_i5=6 a1_i5_21=6 a0_i4=6textcraft craft a6_i7_7_16 12 a7_i5_17=12 a4_i6_6=12 a7_i6_6_17=12 a7_i5=12textcraft craft a2_i7_7 14 a3_i6_6_13=14 a2_i5_22=14 a5_i6_6_15=14textcraft craft a9_i7_7_19 12 a7_i6_6=12 a1_i6_6_11=12 a8_i5=12textcraft craft a2_i7_7_12 22 a6_i5=22 a0_i5=22textcraft craft a8_i7_7_18 14 a4_i5=14 a0_i5_20=14 a2_i5_22=14textcraft craft a0_i7_7_20 8 a1_i5_21=8 a5_i5_15=8 a9_i6_6_19=8 a5_i6_6_15=8textcraft craft a5_i7_7 6 a5_i5_15=6 a5_i6_6_15=6textcraft craft a6_i7_7 12 a8_i6_6=12 a2_i6_6_22=12 a8_i5_18=12textcraft craft a1_i7_7_21 4 a5_i6_6_15=4 a2_i6_6_22=4 a4_i6_6_14=4 a6_i5=4textcraft craft a0_i7_7_10 6 a3_i6_6=6 a3_i6_6_13=6 a9_i6_6=6 a1_i5=6textcraft craft a4_i7_7 4 a0_i5_10=4 a2_i5=4textcraft craft a7_i7_7 4 a6_i6_6_16=4 a5_i6_6_15=4 a2_i5_12=4 a2_i6_6_22=4textcraft craft a8_i7_7 6 a7_i6_6=6 a1_i5_11=6 a1_i6_6=6 a8_i5_18=6textcraft craft a1_i7_7 18 a1_i6_6_21=18 a3_i5=18textcraft craft a9_i7_7 8 a9_i6_6_19=8 a5_i5=8textcraft craft a5_i7_7_15 4 a4_i5_14=4 a5_i6_6=4textcraft craft a2_i7_7_22 8 a0_i5_20=8 a3_i6_6=8 a2_i6_6=8textcraft craft a3_i7_7_13 10 a0_i6_6_20=10 a7_i6_6=10textcraft craft a3_i7_7 4 a2_i5_12=4 a1_i6_6_11=4 a8_i6_6_18=4 a4_i6_6_14=4textcraft craft a7_i7_7_17 12 a6_i5_16=12 a0_i6_6_20=12 a0_i6_6_10=12 a9_i6_6=12textcraft craft a0_i7_7 6 a3_i6_6=6 a5_i6_6=6textcraft craft a4_i7_7_14 4 a2_i6_6=4 a6_i6_6=4textcraft craft a2_i8_8 4 a4_i6_6_14=4 a6_i7_7_16=4 a3_i6_6=4 a8_i6_6=4textcraft craft a3_i8_8_13 6 a2_i7_7=6 a9_i7_7_19=6 a5_i6_6=6 a2_i7_7_12=6 a8_i7_7_18=6textcraft craft a0_i8_8_20 2 a9_i7_7_19=2 a2_i7_7=2 a4_i6_6=2 a2_i7_7_12=2 a0_i7_7_20=2textcraft craft a1_i8_8 2 a6_i7_7=2 a1_i7_7_21=2 a9_i7_7_19=2 a3_i6_6=2textcraft craft a6_i8_8 4 a6_i7_7_16=4 a0_i7_7_10=4 a8_i7_7_18=4 a4_i7_7=4textcraft craft a4_i8_8 2 a4_i6_6=2 a7_i7_7=2 a6_i7_7_16=2textcraft craft a7_i8_8 2 a1_i6_6_21=2 a1_i7_7_21=2 a2_i7_7_12=2 a2_i6_6_22=2 a2_i6_6=2textcraft craft a8_i8_8 8 a3_i6_6=8 a2_i6_6_22=8 a1_i7_7=8textcraft craft a5_i8_8 8 a2_i7_7_12=8 a1_i7_7=8 a9_i7_7=8 a0_i6_6=8textcraft craft a2_i8_8_22 4 a5_i7_7_15=4 a2_i7_7_22=4 a1_i6_6_11=4 a2_i6_6_12=4textcraft craft a1_i8_8_11 4 a2_i7_7_22=4 a3_i7_7_13=4 a0_i7_7_20=4textcraft craft a1_i8_8_21 4 a3_i7_7=4 a2_i7_7_12=4 a2_i7_7=4 a4_i6_6_14=4 a2_i6_6=4textcraft craft a9_i8_8_19 6 a6_i7_7=6 a7_i7_7_17=6 a2_i6_6_12=6textcraft craft a7_i8_8_17 2 a2_i6_6=2 a8_i7_7_18=2 a0_i7_7=2 a7_i7_7_17=2textcraft craft a3_i8_8 2 a0_i7_7_10=2 a4_i6_6=2 a7_i7_7_17=2textcraft craft a5_i8_8_15 2 a8_i7_7_18=2 a4_i7_7_14=2 a9_i7_7_19=2 a2_i7_7=2 a0_i7_7=2textcraft craft a2_i8_8_12 2 a5_i6_6=2 a0_i7_7=2 a3_i7_7_13=2 a6_i6_6=2 a6_i7_7_16=2textcraft craft a9_i8_8 2 a1_i6_6=2 a7_i6_6_17=2 a6_i7_7=2 a4_i6_6=2textcraft craft a9_i9_9 2 a3_i8_8_13=2 a0_i8_8_20=2 a5_i7_7=2 a1_i8_8=2 a6_i8_8=2textcraft craft a5_i9_9_15 2 a8_i7_7=2 a8_i8_8=2 a5_i8_8=2 a2_i8_8_22=2 a6_i8_8=2textcraft craft a8_i9_9 4 a1_i8_8_11=4 a1_i8_8_21=4 a9_i8_8_19=4 a5_i7_7=4textcraft craft a7_i9_9_17 2 a1_i7_7=2 a2_i8_8_22=2 a7_i8_8_17=2 a7_i7_7=2 a9_i8_8_19=2textcraft craft a1_i9_9_21 2 a6_i7_7=2 a3_i7_7_13=2 a0_i7_7_20=2 a4_i7_7_14=2textcraft craft a0_i9_9_20 2 a3_i8_8=2 a8_i8_8=2 a5_i8_8=2 a8_i7_7=2textcraft craft a6_i9_9_16 2 a5_i8_8=2 a3_i7_7_13=2 a5_i8_8_15=2textcraft craft a3_i9_9 2 a3_i8_8_13=2 a2_i8_8_12=2 a7_i7_7_17=2 a8_i7_7=2 a2_i8_8=2textcraft craft a4_i9_9 2 a9_i8_8=2 a8_i8_8=2 a5_i8_8=2textcraft craft a9_i10_10 2 a2_i8_8=2 a9_i9_9=2 a4_i8_8=2 a7_i8_8=2 a5_i9_9_15=2textcraft craft a8_i10_10 2 a8_i9_9=2 a7_i9_9_17=2 a1_i9_9_21=2textcraft craft a2_i10_10_12 2 a0_i9_9_20=2 a6_i9_9_16=2 a3_i8_8_13=2textcraft craft a0_i10_10_20 2 a8_i8_8=2 a3_i9_9=2 a4_i9_9=2textcraft craft a0_i11_11_20 2 a9_i10_10=2 a8_i9_9=2 a8_i10_10=2 a2_i10_10_12=2 a0_i10_10_20=2textcraft finish 'Crafted 2x a0_i11_11_20'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/val-extreme-00305"description = "TextCraft-Synth: craft the following items: 2x a0_i11_11_20 (extreme, crafting depth 11)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "val"difficulty = "extreme"max_depth = 11num_craft_steps = 182goal = "Craft the following items: 2x a0_i11_11_20"source_task_id = "textcraft_synth.val.305"env_task_id = "val:305"env_split_task_id = "val-extreme:62"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 2460.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-val-extreme-00305: task.json sha256:5550ebe8a0d8be016407be976ccd3b8eab87a0b1c2c00c0a97f89f8244fb469aFROM 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/123456789101112131415161718192021{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00305", "world": "textcraft-synth", "goal": "Craft the following items: 2x a0_i11_11_20", "target_items": { "a0_i11_11_20": 2 }, "initial_inventory": { "raw_a1": 24334, "raw_a4": 23548, "raw_a3": 8690, "raw_a0": 12436, "raw_a9": 4958, "raw_a6": 1408, "raw_a2": 3391, "raw_a7": 1604, "raw_o0": 2 }, "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-val-extreme-00307: task.json sha256:3b993c55c84aa66c2929de0b6e3aaddfc291df79484c79152c1f4d4d425a02edFROM 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/1234567891011121314151617181920212223242526272829303132{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00307", "world": "textcraft-synth", "goal": "Craft the following items: 2x x10_ct", "target_items": { "x10_ct": 2 }, "initial_inventory": { "c3_ore": 34, "c4_ore": 58, "c8_ore": 65, "c9_ore": 60, "c6_ore": 30, "c5_ore": 73, "c7_ore": 68, "c1_ore": 17, "c0_ore": 18, "c2_ore": 13, "raw_t1": 225, "raw_t3": 187, "raw_t0": 238, "raw_t4": 150, "raw_t8": 145, "raw_t6": 21, "raw_t5": 54, "raw_t9": 107, "raw_t7": 21, "raw_o0": 4 }, "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 x10_ct
## 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111#!/bin/bash# The reference solution of textcraft-synth-val-extreme-00307: the source task's gold trajectory (103 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 c4_i1_14 9 c3_ore=3textcraft craft c3_i1_23 12 c8_ore=6textcraft craft c1_i1_21 16 c7_ore=8textcraft craft c0_i1 6 c1_ore=2textcraft craft c3_i1_13 12 c9_ore=4textcraft craft c1_i1_11 4 c5_ore=1textcraft craft c9_i1_19 3 c5_ore=2textcraft craft c0_i1_10 4 c9_ore=1textcraft craft c6_i1 2 c2_ore=2textcraft craft c8_i1 3 c8_ore=2textcraft craft c2_i1 2 c9_ore=2textcraft craft c4_i1 4 c1_ore=1textcraft craft c3_i1 4 c9_ore=1textcraft craft c8_i1_18 4 c3_ore=2textcraft craft c9_i1 2 c6_ore=1textcraft craft c0_i1_20 6 c2_ore=2textcraft craft c7_i1_17 2 c0_ore=1textcraft craft c1_i1 2 c8_ore=1textcraft craft c6_i1_16 2 c9_ore=1textcraft craft t0_i1 9 raw_t1=6textcraft craft t6_i1 24 raw_t3=12textcraft craft t8_i1 32 raw_t1=16textcraft craft t6_i1_16 27 raw_t0=9textcraft craft t7_i1 18 raw_t0=18textcraft craft t1_i1_21 16 raw_t4=4textcraft craft t4_i1 16 raw_t8=8textcraft craft t4_i1_24 4 raw_t5=4textcraft craft t2_i1_22 3 raw_t1=2textcraft craft t8_i1_18 9 raw_t9=6textcraft craft t1_i1_11 3 raw_t0=2textcraft craft t1_i1 2 raw_t5=2textcraft craft t0_i1_10 3 raw_t9=2textcraft craft t5_i1 2 raw_t1=1textcraft craft t9_i1 2 raw_t7=2textcraft craft t3_i1_13 3 raw_t4=2textcraft craft t2_i1_12 2 raw_t6=1textcraft craft c2_i2_12 6 c4_i1_14=6 c4_ore=6textcraft craft c2_i2_22 2 c9_ore=1 c6_ore=1textcraft craft c8_i2 8 c5_ore=8 c1_i1_21=8textcraft craft c9_i2 2 c7_ore=1 c1_i1_11=1textcraft craft c0_i2_10 6 c3_i1_23=4 c4_ore=4textcraft craft c6_i2 3 c9_i1_19=1 c0_ore=2textcraft craft c6_i2_16 6 c5_ore=4 c1_i1_21=4textcraft craft c1_i2_21 2 c2_i1=1 c9_ore=2textcraft craft c3_i2_23 3 c7_i1_17=1 c1_i1_11=1textcraft craft c5_i2 4 c5_ore=2 c6_ore=2textcraft craft c3_i2 4 c6_i1_16=2 c6_ore=4textcraft craft t8_i2_18 6 t0_i1=4 t6_i1=2textcraft craft t3_i2_13 16 t8_i1=16 t6_i1_16=16textcraft craft t0_i2_20 15 t1_i1_21=10 t8_i1=10textcraft craft t1_i2_11 4 t6_i1=4 raw_t4=4textcraft craft t0_i2 6 t4_i1=3 raw_t6=3textcraft craft t7_i2_17 6 t4_i1_24=4 raw_t8=4textcraft craft t5_i2 9 t4_i1=6 t6_i1_16=3textcraft craft t4_i2 6 raw_t8=3 raw_t9=3textcraft craft t2_i2_22 2 t1_i1_11=2 t1_i1=2textcraft craft t6_i2 4 t0_i1_10=2 raw_t9=2textcraft craft t7_i2 3 t5_i1=1 raw_t7=2textcraft craft t9_i2_19 3 t7_i1=1 t9_i1=1textcraft craft t1_i2_21 2 t3_i1_13=1 t2_i1_12=1textcraft craft t4_i2_14 2 t0_i1=1 t4_i1=2textcraft craft t1_i2 3 t7_i1=2 t8_i1_18=1textcraft craft c7_i3_17 4 c3_i1_23=4 c2_i2_22=2textcraft craft c3_i3_23 2 c0_i1=4 c3_i1_13=4 c2_i2_12=2textcraft craft c2_i3 2 c3_i1_23=4 c9_i2=2 c0_i2_10=2textcraft craft c9_i3_19 3 c3_i1_13=6 c8_i2=6 c0_i1_10=3textcraft craft c1_i3 2 c6_i1=2 c6_i2_16=2 c8_i1=2textcraft craft c4_i3_14 2 c2_i1=1 c4_i1=2 c8_i2=1textcraft craft c7_i3 2 c3_i1=1 c8_i1_18=1 c9_i1=1textcraft craft c2_i3_12 2 c4_i1_14=2 c0_i1_20=1textcraft craft c1_i3_21 2 c1_i2_21=1 c3_i2_23=2 c3_i1_13=1textcraft craft c5_i3 2 c1_i1=1 c2_i2_12=1 c1_i1_11=2textcraft craft c8_i3 2 c3_i2=4 c6_i2_16=4 c0_i1_20=4textcraft craft t5_i3_15 14 t6_i1=14 t7_i1=14 t0_i2_20=14textcraft craft t9_i3_19 2 t1_i2_11=4 t0_i2=4 t7_i2_17=4textcraft craft t7_i3 2 t3_i2_13=1 t7_i1=1 t2_i1_22=1textcraft craft t8_i3_18 6 t8_i1_18=6 t4_i2=3textcraft craft t5_i3 2 t2_i2_22=2 t6_i2=4 t3_i2_13=4textcraft craft t0_i3_10 2 t7_i2=1 t9_i2_19=1textcraft craft t3_i3_23 2 t1_i2_21=2 t4_i2_14=2 t5_i2=4textcraft craft t6_i3 1 t1_i2=2 t0_i2=1textcraft craft t8_i3 2 t4_i2=2 t6_i1_16=4textcraft craft c3_i4_13 1 c2_i2_12=2 c7_i3_17=2 c8_i2=1textcraft craft c7_i4 2 c3_i3_23=2 c2_i3=2 c6_i2=2textcraft craft c3_i4_23 2 c0_i2_10=2 c9_i3_19=2 c7_i3=1textcraft craft c5_i4_15 2 c1_i3_21=1 c5_i3=2textcraft craft c6_i4 2 c5_i2=4 c7_i3_17=2 c8_i3=2textcraft craft t2_i4 4 t8_i2_18=4 t3_i2_13=4 t5_i3_15=8textcraft craft t4_i4 2 t5_i2=2 t7_i3=1textcraft craft t0_i4 3 t8_i3_18=6 t3_i2_13=6 t5_i3_15=6textcraft craft t1_i4_11 1 t5_i3=2 t8_i2_18=2 t0_i3_10=2textcraft craft t6_i4 2 t5_i2=2 t3_i3_23=2 t6_i3=1textcraft craft c8_i5_18 2 c3_i4_13=1 c7_i4=1 c9_i3_19=1textcraft craft c9_i5_19 2 c1_i3=2 c4_i3_14=2 c3_i4_23=2textcraft craft c4_i5_14 2 c2_i3_12=2 c5_i4_15=2 c6_i4=2textcraft craft t9_i5_19 4 t2_i4=2 t9_i3_19=2textcraft craft t2_i5 2 t1_i4_11=1 t6_i4=1 t0_i4=1textcraft craft c7_i6_6 2 c8_i5_18=2 c9_i5_19=2textcraft craft t2_i6_6_12 2 t9_i5_19=2 t4_i4=2 t0_i4=2textcraft craft t3_i6_6_13 2 t2_i4=2 t9_i5_19=2 t2_i5=2textcraft craft c5_i7_7 2 c7_i6_6=2 c4_i5_14=2textcraft craft t2_i7_7_22 2 t2_i6_6_12=2 t3_i6_6_13=2 t8_i3=2textcraft craft x10_ct 2 c5_i7_7=2 t2_i7_7_22=2textcraft finish 'Crafted 2x x10_ct'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/val-extreme-00307"description = "TextCraft-Synth: craft the following items: 2x x10_ct (extreme, crafting depth 10)"keywords = ["textcraft", "textcraft-synth", "crafting", "planning"]
[metadata]environment = "textcraft-synth@1"split = "val"difficulty = "extreme"max_depth = 10num_craft_steps = 103goal = "Craft the following items: 2x x10_ct"source_task_id = "textcraft_synth.val.307"env_task_id = "val:307"env_split_task_id = "val-extreme:63"
[verifier]environment_mode = "separate"timeout_sec = 180.0
[agent]timeout_sec = 1680.0
[environment]network_mode = "no-network"cpus = 1memory_mb = 2048gpus = 0build_timeout_sec = 900.012345678910111213# textcraft-synth-val-extreme-00307: task.json sha256:3b993c55c84aa66c2929de0b6e3aaddfc291df79484c79152c1f4d4d425a02edFROM 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/1234567891011121314151617181920212223242526272829303132{ "format": "textcraft-task/1", "name": "textcraft-synth-val-extreme-00307", "world": "textcraft-synth", "goal": "Craft the following items: 2x x10_ct", "target_items": { "x10_ct": 2 }, "initial_inventory": { "c3_ore": 34, "c4_ore": 58, "c8_ore": 65, "c9_ore": 60, "c6_ore": 30, "c5_ore": 73, "c7_ore": 68, "c1_ore": 17, "c0_ore": 18, "c2_ore": 13, "raw_t1": 225, "raw_t3": 187, "raw_t0": 238, "raw_t4": 150, "raw_t8": 145, "raw_t6": 21, "raw_t5": 54, "raw_t9": 107, "raw_t7": 21, "raw_o0": 4 }, "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"tasks/textcraft-synth-val-extreme-00289/tests/task.jsonAdded+23
tasks/textcraft-synth-val-extreme-00289/tests/test.shAdded+17
tasks/textcraft-synth-val-extreme-00289/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00292/environment/DockerfileAdded+17
tasks/textcraft-synth-val-extreme-00292/environment/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00292/environment/task.jsonAdded+22
tasks/textcraft-synth-val-extreme-00292/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00292/instruction.mdAdded+38
tasks/textcraft-synth-val-extreme-00292/solution/solve.shAdded+140
tasks/textcraft-synth-val-extreme-00292/task.tomlAdded+33
tasks/textcraft-synth-val-extreme-00292/tests/DockerfileAdded+13
tasks/textcraft-synth-val-extreme-00292/tests/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00292/tests/task.jsonAdded+22
tasks/textcraft-synth-val-extreme-00292/tests/test.shAdded+17
tasks/textcraft-synth-val-extreme-00292/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00300/environment/DockerfileAdded+17
tasks/textcraft-synth-val-extreme-00300/environment/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00300/environment/task.jsonAdded+24
tasks/textcraft-synth-val-extreme-00300/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00300/instruction.mdAdded+38
tasks/textcraft-synth-val-extreme-00300/solution/solve.shAdded+189
tasks/textcraft-synth-val-extreme-00300/task.tomlAdded+33
tasks/textcraft-synth-val-extreme-00300/tests/DockerfileAdded+13
tasks/textcraft-synth-val-extreme-00300/tests/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00300/tests/task.jsonAdded+24
tasks/textcraft-synth-val-extreme-00300/tests/test.shAdded+17
tasks/textcraft-synth-val-extreme-00300/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00305/environment/DockerfileAdded+17
tasks/textcraft-synth-val-extreme-00305/environment/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00305/environment/task.jsonAdded+21
tasks/textcraft-synth-val-extreme-00305/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00305/instruction.mdAdded+38
tasks/textcraft-synth-val-extreme-00305/solution/solve.shAdded+190
tasks/textcraft-synth-val-extreme-00305/task.tomlAdded+33
tasks/textcraft-synth-val-extreme-00305/tests/DockerfileAdded+13
tasks/textcraft-synth-val-extreme-00305/tests/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00305/tests/task.jsonAdded+21
tasks/textcraft-synth-val-extreme-00305/tests/test.shAdded+17
tasks/textcraft-synth-val-extreme-00305/tests/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00307/environment/DockerfileAdded+17
tasks/textcraft-synth-val-extreme-00307/environment/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00307/environment/task.jsonAdded+32
tasks/textcraft-synth-val-extreme-00307/environment/textcraft_game.pyAdded+756
tasks/textcraft-synth-val-extreme-00307/instruction.mdAdded+38
tasks/textcraft-synth-val-extreme-00307/solution/solve.shAdded+111
tasks/textcraft-synth-val-extreme-00307/task.tomlAdded+33
tasks/textcraft-synth-val-extreme-00307/tests/DockerfileAdded+13
tasks/textcraft-synth-val-extreme-00307/tests/recipes.jsonAdded
tasks/textcraft-synth-val-extreme-00307/tests/task.jsonAdded+32
tasks/textcraft-synth-val-extreme-00307/tests/test.shAdded+17