"""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, ) ) )