File size: 5,629 Bytes
80833e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
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
"""Reference solver: use trusted inputs, but obtain the answer through public actions."""

import json
import urllib.request
from pathlib import Path


def http_action(base_url, payload):
    request = urllib.request.Request(
        base_url + "/action",
        data=json.dumps(payload).encode(),
        headers={"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.load(response)


def solve(scenario, act, observe):
    nodes = {node["id"]: node for node in scenario["nodes"]}
    visible = {entity["id"] for entity in observe["available_entities"]}
    solved = set()
    seen_outputs = {}
    action_count = 0

    def call(payload):
        nonlocal action_count
        action_count += 1
        response = act(payload)
        visible.update(entity["id"] for entity in response.get("newly_revealed", []))
        if (
            response.get("episode", {}).get("termination_reason")
            == "infrastructure_error"
        ):
            raise RuntimeError("Infrastructure failure")
        return response

    for _round in range(len(nodes) + 2):
        progress = False
        for node_id, node in nodes.items():
            if node_id not in visible or node_id in solved:
                continue
            # Preserve graph order for data inputs; trigger/drop edges express visibility.
            predecessors = [
                edge["source_id"]
                for edge in scenario["edges"]
                if edge["target_id"] == node_id
                and edge["connection_type"] not in ("Item", "Hidden_Item")
            ]
            if any(pred not in solved for pred in predecessors):
                continue
            info = call({"action": "investigate", "node_id": node_id})
            if not info.get("ok"):
                raise RuntimeError(f"Investigation failed: {node_id}: {info}")
            inputs = {
                port["name"]: port["value"]
                for port in node.get("inputs", [])
                if "value" in port
            }
            if node["type"] == "Tool":
                result = call(
                    {"action": "tool_call", "node_id": node_id, "arguments": inputs}
                )
                if not result.get("ok") or result.get("output_values", {}).get("error"):
                    raise RuntimeError(f"Tool failed: {node_id}: {result}")
                output = result.get("output_values", {})
                if node.get("template_id") in ("terminal_1", "terminal_2"):
                    slots = {
                        port["name"]: inputs[port["name"]]
                        for port in node["inputs"]
                        if port["type"] not in ("Item", "Hidden_Item")
                        and port["name"] in inputs
                    }
                    triggers = {
                        key: value for key, value in inputs.items() if key not in slots
                    }
                    for key, value in slots.items():
                        partial = call(
                            {
                                "action": "tool_call",
                                "node_id": node_id,
                                "arguments": {**triggers, key: value},
                            }
                        )
                        if partial.get("ok"):
                            output.update(partial.get("output_values", {}))
                # HIDDEN_ITEM tool drops only occur on subsequent investigation.
                call({"action": "investigate", "node_id": node_id})
            elif info.get("required_inputs"):
                result = call(
                    {"action": "use_item", "node_id": node_id, "arguments": inputs}
                )
                if not result.get("ok"):
                    raise RuntimeError(f"Item failed: {node_id}: {result}")
                output = result.get("content")
            else:
                output = info.get("content")
            seen_outputs[node_id] = output
            solved.add(node_id)
            progress = True
        win_id = scenario["metadata"]["win_node_id"]
        if win_id in solved and (len(solved) == len(nodes) or not progress):
            outputs = seen_outputs[win_id]
            if not outputs:
                raise RuntimeError(f"Victory node returned no output: {win_id}")
            # Upstream grades its first stored output port, independent of response order.
            victory_port = next(
                port["name"] for port in nodes[win_id]["outputs"] if "value" in port
            )
            answer = outputs[victory_port] if isinstance(outputs, dict) else outputs
            result = call({"action": "submit_answer", "answer": answer})
            if not result.get("is_win"):
                raise RuntimeError(f"Victory submission failed: {result}")
            return {"won": True, "actions": action_count, "visited_nodes": len(solved)}
        if not progress:
            raise RuntimeError(f"No progress: visible={visible}, solved={solved}")
    raise RuntimeError("Reference solver exceeded graph traversal limit")


if __name__ == "__main__":
    import os

    base = os.environ.get("ESCAPE_URL", "http://puzzle:8000")
    with urllib.request.urlopen(base + "/observation", timeout=20) as response:
        observation = json.load(response)
    print(
        json.dumps(
            solve(
                json.loads(Path("/solution/scenario.json").read_text()),
                lambda payload: http_action(base, payload),
                observation,
            )
        )
    )