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4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
"""Shared SPAgent protocol for deterministic VRBench navigation tasks.

Dataset generation samples official Beyond-MMEnv states. Training rollouts,
answer replay, rendering, and tests use the pure deterministic state machine
defined here, so distributed workers do not need Beyond-MMEnv installed.
"""

from __future__ import annotations

import json
import os
from collections import deque
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 (
    DIRS,
    create_tool_response,
    parse_action_tokens,
)


PATHFINDER_TASK = "VRBench/Pathfinder-v0"
MAZE_TASK = "VRBench/Maze-v0"
TRAPFIELD_TASK = "VRBench/TrapField-v0"
SUPPORTED_TASKS = (PATHFINDER_TASK, MAZE_TASK, TRAPFIELD_TASK)

EMPTY = 0
WALL = 1
PLAYER = 2
GOAL = 3
TRAP = 4

TASK_LABELS = {
    PATHFINDER_TASK: "Pathfinder",
    MAZE_TASK: "Maze",
    TRAPFIELD_TASK: "TrapField",
}
TASK_TITLES = {
    PATHFINDER_TASK: "VRBench Pathfinder",
    MAZE_TASK: "VRBench Maze",
    TRAPFIELD_TASK: "VRBench TrapField",
}

# The current upstream TrapField generator usually disconnects start and goal.
# These seeds are verified solvable and are also used by the evaluation suite.
TRAPFIELD_SOLVABLE_SEEDS = (
    173,
    1126,
    1553,
    1701,
    2596,
    3860,
    3962,
    4296,
    4736,
    5098,
    5206,
    5805,
    5839,
    7126,
    7856,
    10060,
    10741,
    10748,
    10751,
    10995,
    11073,
    11089,
    11155,
    11194,
    11918,
    12206,
    13519,
    14715,
    15212,
    15265,
)

CELL_PX = 40
MARGIN = 20
PALETTE = {
    "F": (210, 235, 255),
    "S": (170, 225, 150),
    "G": (245, 205, 70),
    "#": (45, 55, 70),
    "X": (190, 65, 65),
    "AGENT": (220, 70, 70),
    "GRID": (60, 60, 60),
}
_font: ImageFont.ImageFont | None = None


@dataclass(frozen=True)
class StepOutcome:
    changed: bool
    done: bool
    success: bool
    body_text: str
    tool_result: Dict[str, Any]


def encode_initial_state(state: Mapping[str, Any]) -> str:
    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 clone_state(state: Mapping[str, Any]) -> Dict[str, Any]:
    return json.loads(json.dumps(state))


def canonical_state(
    *,
    grid: Iterable[Iterable[int]],
    start: Tuple[int, int],
    goal: Tuple[int, int],
) -> Dict[str, Any]:
    rows = [[int(cell) for cell in row] for row in grid]
    if not rows or not rows[0] or any(len(row) != len(rows[0]) for row in rows):
        raise ValueError("grid must be a non-empty rectangle")
    allowed = {EMPTY, WALL, PLAYER, GOAL, TRAP}
    if any(cell not in allowed for row in rows for cell in row):
        raise ValueError("grid contains an unsupported cell value")
    sr, sc = (int(start[0]), int(start[1]))
    gr, gc = (int(goal[0]), int(goal[1]))
    if not (0 <= sr < len(rows) and 0 <= sc < len(rows[0])):
        raise ValueError(f"start is outside the grid: {(sr, sc)}")
    if not (0 <= gr < len(rows) and 0 <= gc < len(rows[0])):
        raise ValueError(f"goal is outside the grid: {(gr, gc)}")
    rows[sr][sc] = EMPTY
    rows[gr][gc] = GOAL
    return {
        "grid": rows,
        "start": [sr, sc],
        "goal": [gr, gc],
        "position": [sr, sc],
    }


def symbolic_grid_lines(
    state: Mapping[str, Any],
    *,
    initial: bool = False,
) -> List[str]:
    grid = state["grid"]
    position = tuple(int(value) for value in state["position"])
    start = tuple(int(value) for value in state["start"])
    goal = tuple(int(value) for value in state["goal"])
    mapping = {EMPTY: "F", WALL: "#", GOAL: "G", TRAP: "X"}
    rows: List[str] = []
    for r, row in enumerate(grid):
        chars: List[str] = []
        for c, value in enumerate(row):
            pos = (r, c)
            if initial and pos == start:
                chars.append("S")
            elif not initial and pos == position:
                chars.append("P")
            elif pos == goal:
                chars.append("G")
            else:
                chars.append(mapping[int(value)])
        rows.append("".join(chars))
    return rows


def state_text(state: Mapping[str, Any], *, initial: bool = False) -> str:
    return "\n".join(symbolic_grid_lines(state, initial=initial))


def is_solved(state: Mapping[str, Any]) -> bool:
    position = tuple(int(value) for value in state["position"])
    goal = tuple(int(value) for value in state["goal"])
    return position == goal


def step_state(
    task_id: str,
    state: MutableMapping[str, Any],
    direction: Any,
) -> StepOutcome:
    if task_id not in SUPPORTED_TASKS:
        raise ValueError(f"Unsupported task_id: {task_id}")
    if not isinstance(direction, str) or direction not in DIRS:
        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,
            },
        )

    grid = state["grid"]
    r, c = (int(value) for value in state["position"])
    dr, dc = DIRS[direction]
    nr, nc = r + dr, c + dc
    if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0])):
        obstacle = "wall"
    else:
        destination = int(grid[nr][nc])
        obstacle = (
            "wall"
            if destination == WALL
            else "trap"
            if destination == TRAP
            else ""
        )
    if obstacle:
        return StepOutcome(
            changed=False,
            done=False,
            success=False,
            body_text=(
                f"Blocked by {obstacle}: cannot move {direction} from "
                f"({r},{c}). Position unchanged."
            ),
            tool_result={
                "success": False,
                "error": obstacle,
                "from": [r, c],
                "direction": direction,
            },
        )

    state["position"] = [nr, nc]
    success = (nr, nc) == tuple(int(value) for value in state["goal"])
    cell = "G" if success else "F"
    body = f"Moved {direction} to ({nr},{nc}). Cell: {cell}."
    if success:
        body += " **Reached goal - success!**"
    return StepOutcome(
        changed=True,
        done=success,
        success=success,
        body_text=body,
        tool_result={
            "success": True,
            "to": [nr, nc],
            "cell": cell,
            "done": success,
            "succeeded": success,
        },
    )


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(state):
        return True
    for direction in actions:
        outcome = step_state(task_id, state, direction)
        if not outcome.changed:
            return False
        if outcome.success:
            return True
    return is_solved(state)


def shortest_path(state: Mapping[str, Any]) -> List[str] | None:
    grid = state["grid"]
    start = tuple(int(value) for value in state["start"])
    goal = tuple(int(value) for value in state["goal"])
    queue = deque([(start, [])])
    seen = {start}
    while queue:
        (r, c), path = queue.popleft()
        if (r, c) == goal:
            return path
        for direction, (dr, dc) in DIRS.items():
            nr, nc = r + dr, c + dc
            if not (0 <= nr < len(grid) and 0 <= nc < len(grid[0])):
                continue
            if (nr, nc) in seen or int(grid[nr][nc]) in (WALL, TRAP):
                continue
            seen.add((nr, nc))
            queue.append(((nr, nc), path + [direction]))
    return None


def _font_fn() -> ImageFont.ImageFont:
    global _font
    if _font is None:
        try:
            _font = ImageFont.truetype("DejaVuSans-Bold.ttf", 18)
        except OSError:
            _font = ImageFont.load_default()
    return _font


def render_state(
    task_id: str,
    state: Mapping[str, Any],
    output_path: str | Path,
) -> None:
    if task_id not in SUPPORTED_TASKS:
        raise ValueError(f"Unsupported task_id: {task_id}")
    lines = symbolic_grid_lines(state, initial=True)
    rows, cols = len(lines), len(lines[0])
    width = cols * CELL_PX + 2 * MARGIN
    height = rows * CELL_PX + 2 * MARGIN
    image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(image)
    font = _font_fn()
    for row_index, row in enumerate(lines):
        for col_index, value in enumerate(row):
            x0 = MARGIN + col_index * CELL_PX
            y0 = MARGIN + row_index * CELL_PX
            draw.rectangle(
                [x0, y0, x0 + CELL_PX, y0 + CELL_PX],
                fill=PALETTE[value],
                outline=PALETTE["GRID"],
                width=2,
            )
            bbox = draw.textbbox((0, 0), value, font=font)
            text_width = bbox[2] - bbox[0]
            draw.text(
                (
                    x0 + (CELL_PX - text_width) // 2,
                    y0 + 2,
                ),
                value,
                fill="white" if value in {"#", "X"} else "black",
                font=font,
            )
    r, c = (int(value) for value in state["position"])
    center_x = MARGIN + c * CELL_PX + CELL_PX // 2
    center_y = MARGIN + r * CELL_PX + CELL_PX // 2 + 5
    radius = max(6, CELL_PX // 4)
    draw.ellipse(
        [
            center_x - radius,
            center_y - radius,
            center_x + radius,
            center_y + radius,
        ],
        fill=PALETTE["AGENT"],
        outline="black",
        width=2,
    )
    mode = os.environ.get("TOOL_IMAGE_MODE", "real").lower().strip()
    if mode == "black":
        image = Image.new("RGB", image.size, "black")
    elif mode == "white":
        image = Image.new("RGB", image.size, "white")
    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]:
    label = TASK_LABELS[task_id]
    blocked = "walls and blocked traps" if task_id == TRAPFIELD_TASK else "walls"
    return {
        "type": "function",
        "function": {
            "name": "move",
            "description": (
                f"Move the agent one cell on the {label} grid. Moves into "
                f"{blocked} are no-ops. Returns the updated complete grid "
                "as a new image."
            ),
            "parameters": {
                "type": "object",
                "properties": {
                    "direction": {
                        "type": "string",
                        "enum": ["Left", "Down", "Right", "Up"],
                    }
                },
                "required": ["direction"],
            },
        },
    }


def build_system_prompt(task_id: str, state: Mapping[str, Any]) -> str:
    if task_id not in SUPPORTED_TASKS:
        raise ValueError(f"Unsupported task_id: {task_id}")
    size = len(state["grid"])
    label = TASK_LABELS[task_id]
    cells = (
        "S = start, G = goal, F = free cell, # = wall, X = blocked trap."
        if task_id == TRAPFIELD_TASK
        else "S = start, G = goal, F = free cell, # = wall."
    )
    objective = (
        "Reach G while avoiding walls and every blocked trap X."
        if task_id == TRAPFIELD_TASK
        else "Reach G while avoiding walls."
    )
    schema = json.dumps(move_tool_spec(task_id), ensure_ascii=False)
    return (
        f"You are an agent navigating a {size}x{size} {label} grid.\n\n"
        f"Cells: {cells}\n"
        "The environment is deterministic and fully observed. A move succeeds "
        "when its destination is traversable; blocked moves are no-ops and the "
        "grid does not wrap.\n"
        f"Goal: {objective}\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 <tools></tools> XML "
        "tags:\n"
        "<tools>\n"
        f"{schema}\n"
        "</tools>\n\n"
        "For each function call, return a JSON object with function name and "
        "arguments within <tool_call></tool_call> XML tags:\n"
        "<tool_call>\n"
        '{"name": <function-name>, "arguments": <args-json-object>}\n'
        "</tool_call>\n\n"
        "Reason step-by-step in <think></think>. When you reach G, output the "
        "full executed direction sequence in <answer></answer>, space-separated."
    )


def build_user_prompt(
    task_id: str,
    state: Mapping[str, Any],
    image_path: str | Path,
) -> str:
    label = TASK_LABELS[task_id]
    lines = symbolic_grid_lines(state, initial=True)
    start = state["start"]
    goal = state["goal"]
    objective = (
        "Avoid walls and every blocked trap X."
        if task_id == TRAPFIELD_TASK
        else "Avoid every wall #."
    )
    return (
        f"# Initial Grid (text view, {len(lines)}x{len(lines[0])})\n"
        + "\n".join(lines)
        + "\n\n# Images\n"
        f"- Image_1 (initial {label} grid) — img_idx=0\n"
        f"<image>[image: {Path(image_path).resolve()}]\n\n"
        f"You are at S (row {start[0]}, col {start[1]}). Reach G at "
        f"(row {goal[0]}, col {goal[1]}). {objective} Call the `move` tool "
        "one step at a time. After each valid move you will see the updated "
        "complete grid.\n\n"
        "Output step-by-step reasoning in <think></think>. When you reach G, "
        "output the full executed action sequence in <answer></answer>."
    )


__all__ = [
    "DIRS",
    "EMPTY",
    "GOAL",
    "MAZE_TASK",
    "PATHFINDER_TASK",
    "PLAYER",
    "SUPPORTED_TASKS",
    "StepOutcome",
    "TRAP",
    "TRAPFIELD_SOLVABLE_SEEDS",
    "TRAPFIELD_TASK",
    "WALL",
    "build_system_prompt",
    "build_user_prompt",
    "canonical_state",
    "clone_state",
    "create_tool_response",
    "decode_initial_state",
    "encode_initial_state",
    "is_solved",
    "parse_action_tokens",
    "render_state",
    "replay_actions",
    "shortest_path",
    "state_text",
    "step_state",
    "symbolic_grid_lines",
]