"""Shared protocol for SPAgent Sokoban and FifteenPuzzle training. This module has no ms-swift or Beyond-MMEnv dependency. Dataset generation, GRPO rollout stepping, answer replay, rendering, and future evaluation adapters can therefore use the same deterministic transition rules. """ from __future__ import annotations import json import os import re from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, Iterable, List, Mapping, MutableMapping, Tuple from PIL import Image, ImageDraw, ImageFont from spagent.frozenlake_v3_protocol import create_tool_response SOKOBAN_TASK = "Games/Sokoban-v0" FIFTEEN_TASK = "Games/FifteenPuzzle-v0" SUPPORTED_TASKS = (SOKOBAN_TASK, FIFTEEN_TASK) DIRECTIONS: Dict[str, Tuple[int, int]] = { "Left": (0, -1), "Down": (1, 0), "Right": (0, 1), "Up": (-1, 0), } ANSWER_TOKEN_RE = re.compile(r"[\s,;]+") SOKOBAN_CELL_PX = 64 FIFTEEN_CELL_PX = 80 MARGIN = 20 SOKOBAN_COLORS = { "#": (54, 59, 68), "_": (232, 235, 239), "O": (250, 208, 91), "X": (164, 105, 57), "*": (104, 176, 93), "P": (70, 135, 210), "+": (92, 183, 211), } _font_cache: Dict[Tuple[str, int], ImageFont.ImageFont] = {} @dataclass(frozen=True) class StepOutcome: changed: bool done: bool success: bool body_text: str tool_result: Dict[str, Any] def _font(size: int, *, bold: bool = False) -> ImageFont.ImageFont: key = ("bold" if bold else "regular", size) if key not in _font_cache: filename = "DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf" try: _font_cache[key] = ImageFont.truetype(filename, size) except OSError: _font_cache[key] = ImageFont.load_default() return _font_cache[key] def parse_action_tokens(answer_text: str) -> List[str]: """Parse a lenient, space/comma/semicolon-separated direction sequence.""" if not answer_text: return [] actions: List[str] = [] for token in ANSWER_TOKEN_RE.split(answer_text.strip()): normalized = re.sub(r"[^A-Za-z]", "", token).capitalize() if normalized in DIRECTIONS: actions.append(normalized) return actions def encode_initial_state(state: Mapping[str, Any]) -> str: """Return a stable JSON representation suitable for a JSONL column.""" return json.dumps(state, sort_keys=True, separators=(",", ":")) def decode_initial_state(value: str | Mapping[str, Any]) -> Dict[str, Any]: if isinstance(value, str): state = json.loads(value) elif isinstance(value, Mapping): state = dict(value) else: raise TypeError( "initial_state must be JSON text or a mapping, " f"got {type(value)}" ) if not isinstance(state, dict): raise ValueError("initial_state must decode to an object") return state def canonical_sokoban_state( *, rows: int, cols: int, walls: Iterable[Tuple[int, int]], goals: Iterable[Tuple[int, int]], boxes: Iterable[Tuple[int, int]], player: Tuple[int, int], ) -> Dict[str, Any]: return { "rows": int(rows), "cols": int(cols), "walls": [list(pos) for pos in sorted(set(walls))], "goals": [list(pos) for pos in sorted(set(goals))], "boxes": [list(pos) for pos in sorted(set(boxes))], "player": list(player), } def canonical_fifteen_state(board: Iterable[int], *, size: int = 4) -> Dict[str, Any]: values = [int(value) for value in board] expected = set(range(size * size)) if len(values) != size * size or set(values) != expected: raise ValueError( f"FifteenPuzzle board must contain each value 0..{size * size - 1} once" ) return {"size": int(size), "board": values} def clone_state(state: Mapping[str, Any]) -> Dict[str, Any]: return json.loads(json.dumps(state)) def _pairs(values: Iterable[Iterable[int]]) -> set[Tuple[int, int]]: return {tuple(int(x) for x in value) for value in values} def sokoban_grid_lines(state: Mapping[str, Any]) -> List[str]: rows = int(state["rows"]) cols = int(state["cols"]) walls = _pairs(state["walls"]) goals = _pairs(state["goals"]) boxes = _pairs(state["boxes"]) player = tuple(int(x) for x in state["player"]) lines: List[str] = [] for r in range(rows): chars: List[str] = [] for c in range(cols): pos = (r, c) if pos in walls: char = "#" elif pos == player and pos in goals: char = "+" elif pos in boxes and pos in goals: char = "*" elif pos == player: char = "P" elif pos in boxes: char = "X" elif pos in goals: char = "O" else: char = "_" chars.append(char) lines.append("".join(chars)) return lines def fifteen_grid_lines(state: Mapping[str, Any]) -> List[str]: size = int(state.get("size", 4)) board = [int(value) for value in state["board"]] return [ " ".join( "__" if value == 0 else f"{value:02d}" for value in board[row * size : (row + 1) * size] ) for row in range(size) ] def state_text(task_id: str, state: Mapping[str, Any]) -> str: if task_id == SOKOBAN_TASK: return "\n".join(sokoban_grid_lines(state)) if task_id == FIFTEEN_TASK: return "\n".join(fifteen_grid_lines(state)) raise ValueError(f"Unsupported task_id: {task_id}") def is_solved(task_id: str, state: Mapping[str, Any]) -> bool: if task_id == SOKOBAN_TASK: return _pairs(state["boxes"]).issubset(_pairs(state["goals"])) if task_id == FIFTEEN_TASK: size = int(state.get("size", 4)) solved = list(range(1, size * size)) + [0] return [int(value) for value in state["board"]] == solved raise ValueError(f"Unsupported task_id: {task_id}") def _step_sokoban(state: MutableMapping[str, Any], direction: str) -> StepOutcome: rows = int(state["rows"]) cols = int(state["cols"]) walls = _pairs(state["walls"]) goals = _pairs(state["goals"]) boxes = _pairs(state["boxes"]) player = tuple(int(x) for x in state["player"]) dr, dc = DIRECTIONS[direction] dest = (player[0] + dr, player[1] + dc) if not (0 <= dest[0] < rows and 0 <= dest[1] < cols) or dest in walls: return StepOutcome( changed=False, done=False, success=False, body_text=( f"Blocked: cannot move {direction} from {player}. " "Position unchanged." ), tool_result={ "success": False, "error": "wall", "from": list(player), "direction": direction, }, ) pushed = False if dest in boxes: beyond = (dest[0] + dr, dest[1] + dc) if ( not (0 <= beyond[0] < rows and 0 <= beyond[1] < cols) or beyond in walls or beyond in boxes ): return StepOutcome( changed=False, done=False, success=False, body_text=( f"Blocked: the box at {dest} cannot be pushed {direction}. " "Position unchanged." ), tool_result={ "success": False, "error": "blocked_box", "box": list(dest), "direction": direction, }, ) boxes.remove(dest) boxes.add(beyond) pushed = True state["player"] = list(dest) state["boxes"] = [list(pos) for pos in sorted(boxes)] success = boxes.issubset(goals) verb = "Pushed a box and moved" if pushed else "Moved" body = f"{verb} {direction} to ({dest[0]},{dest[1]})." if success: body += " **All boxes are on targets - success!**" return StepOutcome( changed=True, done=success, success=success, body_text=body, tool_result={ "success": True, "to": list(dest), "pushed_box": pushed, "boxes_on_targets": len(boxes & goals), "total_boxes": len(boxes), "done": success, "succeeded": success, }, ) def _step_fifteen(state: MutableMapping[str, Any], direction: str) -> StepOutcome: size = int(state.get("size", 4)) board = [int(value) for value in state["board"]] blank_index = board.index(0) blank_r, blank_c = divmod(blank_index, size) # Directions describe the numbered tile's motion into the blank, matching # Games/FifteenPuzzle-v0. Therefore the blank moves in the opposite visual # direction. source_delta = { "Up": (1, 0), "Down": (-1, 0), "Left": (0, 1), "Right": (0, -1), } dr, dc = source_delta[direction] source_r, source_c = blank_r + dr, blank_c + dc if not (0 <= source_r < size and 0 <= source_c < size): return StepOutcome( changed=False, done=False, success=False, body_text=( f"Blocked: no tile can move {direction} into the blank at " f"({blank_r},{blank_c}). Board unchanged." ), tool_result={ "success": False, "error": "invalid_slide", "blank": [blank_r, blank_c], "direction": direction, }, ) source_index = source_r * size + source_c tile = board[source_index] board[blank_index], board[source_index] = board[source_index], board[blank_index] state["board"] = board success = board == list(range(1, size * size)) + [0] body = ( f"Slid tile {tile} {direction} into the blank. " f"Blank is now at ({source_r},{source_c})." ) if success: body += " **Puzzle solved - success!**" return StepOutcome( changed=True, done=success, success=success, body_text=body, tool_result={ "success": True, "moved_tile": tile, "direction": direction, "blank": [source_r, source_c], "done": success, "succeeded": success, }, ) def step_state( task_id: str, state: MutableMapping[str, Any], direction: Any, ) -> StepOutcome: if not isinstance(direction, str) or direction not in DIRECTIONS: return StepOutcome( changed=False, done=False, success=False, body_text=( f"Invalid direction {direction!r}. " "Use one of: Left, Down, Right, Up." ), tool_result={ "success": False, "error": "invalid_direction", "direction": direction, }, ) if task_id == SOKOBAN_TASK: return _step_sokoban(state, direction) if task_id == FIFTEEN_TASK: return _step_fifteen(state, direction) raise ValueError(f"Unsupported task_id: {task_id}") def replay_actions( task_id: str, initial_state: str | Mapping[str, Any], actions: Iterable[Any], ) -> bool: state = clone_state(decode_initial_state(initial_state)) if is_solved(task_id, state): return True for direction in actions: if not isinstance(direction, str) or direction not in DIRECTIONS: return False outcome = step_state(task_id, state, direction) if not outcome.changed: return False if outcome.success: return True return is_solved(task_id, state) def _apply_image_mode(image: Image.Image) -> Image.Image: mode = os.environ.get("TOOL_IMAGE_MODE", "real").lower().strip() if mode == "black": return Image.new("RGB", image.size, "black") if mode == "white": return Image.new("RGB", image.size, "white") return image def _render_sokoban(state: Mapping[str, Any]) -> Image.Image: lines = sokoban_grid_lines(state) rows = len(lines) cols = len(lines[0]) width = cols * SOKOBAN_CELL_PX + 2 * MARGIN height = rows * SOKOBAN_CELL_PX + 2 * MARGIN image = Image.new("RGB", (width, height), "white") draw = ImageDraw.Draw(image) label_font = _font(24, bold=True) for r, line in enumerate(lines): for c, char in enumerate(line): x0 = MARGIN + c * SOKOBAN_CELL_PX y0 = MARGIN + r * SOKOBAN_CELL_PX draw.rectangle( [x0, y0, x0 + SOKOBAN_CELL_PX, y0 + SOKOBAN_CELL_PX], fill=SOKOBAN_COLORS[char], outline=(65, 65, 65), width=2, ) if char != "_": bbox = draw.textbbox((0, 0), char, font=label_font) text_w = bbox[2] - bbox[0] text_h = bbox[3] - bbox[1] draw.text( ( x0 + (SOKOBAN_CELL_PX - text_w) // 2, y0 + (SOKOBAN_CELL_PX - text_h) // 2 - bbox[1], ), char, fill="white" if char in {"#", "X", "*", "P", "+"} else "black", font=label_font, ) return image def _render_fifteen(state: Mapping[str, Any]) -> Image.Image: size = int(state.get("size", 4)) board = [int(value) for value in state["board"]] width = size * FIFTEEN_CELL_PX + 2 * MARGIN image = Image.new("RGB", (width, width), (242, 244, 247)) draw = ImageDraw.Draw(image) number_font = _font(30, bold=True) for index, value in enumerate(board): r, c = divmod(index, size) x0 = MARGIN + c * FIFTEEN_CELL_PX y0 = MARGIN + r * FIFTEEN_CELL_PX fill = (90, 98, 110) if value == 0 else (250, 250, 250) draw.rectangle( [x0, y0, x0 + FIFTEEN_CELL_PX, y0 + FIFTEEN_CELL_PX], fill=fill, outline=(100, 106, 115), width=2, ) if value: text = str(value) bbox = draw.textbbox((0, 0), text, font=number_font) text_w = bbox[2] - bbox[0] text_h = bbox[3] - bbox[1] draw.text( ( x0 + (FIFTEEN_CELL_PX - text_w) // 2, y0 + (FIFTEEN_CELL_PX - text_h) // 2 - bbox[1], ), text, fill=(25, 28, 32), font=number_font, ) return image def render_state( task_id: str, state: Mapping[str, Any], output_path: str | Path, ) -> None: if task_id == SOKOBAN_TASK: image = _render_sokoban(state) elif task_id == FIFTEEN_TASK: image = _render_fifteen(state) else: raise ValueError(f"Unsupported task_id: {task_id}") image = _apply_image_mode(image) output_path = Path(output_path) output_path.parent.mkdir(parents=True, exist_ok=True) image.save(output_path, format="PNG") def move_tool_spec(task_id: str) -> Dict[str, Any]: if task_id == SOKOBAN_TASK: description = ( "Move the player one cell in the given direction. If a box is in " "that cell and the next cell is free, the box is pushed. Returns " "the updated complete board as a new image." ) elif task_id == FIFTEEN_TASK: description = ( "Slide one numbered tile into the blank. Direction names describe " "the tile's motion: Up moves the tile below the blank upward, Down " "moves the tile above downward, Left moves the tile to the right " "leftward, and Right moves the tile to the left rightward. Returns " "the updated complete board as a new image." ) else: raise ValueError(f"Unsupported task_id: {task_id}") return { "type": "function", "function": { "name": "move", "description": description, "parameters": { "type": "object", "properties": { "direction": { "type": "string", "enum": ["Left", "Down", "Right", "Up"], } }, "required": ["direction"], }, }, } def build_system_prompt(task_id: str) -> str: if task_id == SOKOBAN_TASK: intro = ( "You are an agent solving a deterministic Sokoban board.\n\n" "Cells: # = wall, _ = floor, O = target, X = box, * = box on " "target, P = player, + = player on target.\n" "Goal: push every box onto a target. Boxes can be pushed but never " "pulled. The full board is always visible." ) elif task_id == FIFTEEN_TASK: intro = ( "You are an agent solving a deterministic 4x4 Fifteen Puzzle.\n\n" "The board contains tiles 1 through 15 and one blank shown as __.\n" "Goal: arrange tiles in row-major order 1..15 with the blank in the " "bottom-right corner. The full board is always visible." ) else: raise ValueError(f"Unsupported task_id: {task_id}") tool_json = json.dumps(move_tool_spec(task_id), ensure_ascii=False) return ( f"{intro}\n\n" "# Tools\n\n" "You may call one or more functions to assist with the user query.\n\n" "You are provided with function signatures within XML tags:\n" "\n" f"{tool_json}\n" "\n\n" "For each function call, return a JSON object with function name and " "arguments within XML tags:\n" "\n" '{"name": , "arguments": }\n' "\n\n" "Reason step-by-step in . When the puzzle is solved, " "output the full executed direction sequence in , " "space-separated." ) def build_user_prompt( task_id: str, state: Mapping[str, Any], image_path: str | Path, ) -> str: lines = state_text(task_id, state) if task_id == SOKOBAN_TASK: rows = int(state["rows"]) cols = int(state["cols"]) label = "initial Sokoban board" task_instruction = ( "Push every X box onto an O target. Call the `move` tool one step " "at a time. After each valid move you will see the updated board." ) elif task_id == FIFTEEN_TASK: rows = cols = int(state.get("size", 4)) label = "initial Fifteen Puzzle board" task_instruction = ( "Arrange the tiles as 01 02 03 04 / 05 06 07 08 / " "09 10 11 12 / 13 14 15 __. Call the `move` tool one slide at a " "time. Direction names describe the numbered tile's motion into " "the blank." ) else: raise ValueError(f"Unsupported task_id: {task_id}") return ( f"# Initial Grid (text view, {rows}x{cols})\n" f"{lines}\n\n" "# Images\n" f"- Image_1 ({label}) — img_idx=0\n" f"[image: {Path(image_path).resolve()}]\n\n" f"{task_instruction}\n\n" "Output step-by-step reasoning in . When solved, output " "the full executed action sequence in ." ) __all__ = [ "DIRECTIONS", "FIFTEEN_TASK", "SOKOBAN_TASK", "SUPPORTED_TASKS", "StepOutcome", "build_system_prompt", "build_user_prompt", "canonical_fifteen_state", "canonical_sokoban_state", "clone_state", "create_tool_response", "decode_initial_state", "encode_initial_state", "fifteen_grid_lines", "is_solved", "move_tool_spec", "parse_action_tokens", "render_state", "replay_actions", "sokoban_grid_lines", "state_text", "step_state", ]