|
| 1 | +import json |
| 2 | +import shlex |
| 3 | +import subprocess |
| 4 | + |
| 5 | +from codeclash.agents.player import Player |
| 6 | +from codeclash.arenas.arena import CodeArena, RoundStats |
| 7 | +from codeclash.constants import RESULT_TIE |
| 8 | +from codeclash.utils.environment import assert_zero_exit_code |
| 9 | + |
| 10 | +RESULTS_JSON = "cyborg_results.json" |
| 11 | + |
| 12 | + |
| 13 | +class CybORGArena(CodeArena): |
| 14 | + name: str = "CybORG" |
| 15 | + submission: str = "cyborg_agent.py" |
| 16 | + description: str = """CybORG is a simulated cyber-defense arena based on the CAGE Challenge 3 DroneSwarm scenario. |
| 17 | +
|
| 18 | +Your bot is a Python file named `cyborg_agent.py` that defines a class named `MyAgent`. |
| 19 | +`MyAgent` should inherit from a CybORG BaseAgent-compatible class, for example: |
| 20 | +
|
| 21 | + from CybORG.Agents import RandomAgent |
| 22 | +
|
| 23 | + class MyAgent(RandomAgent): |
| 24 | + ... |
| 25 | +
|
| 26 | +Each round evaluates every submitted agent independently on the same seeded DroneSwarm episodes. |
| 27 | +Your agent controls the blue-team drone agents through CybORG's simulated PettingZoo interface. |
| 28 | +The objective is to maximize average episode reward. This arena uses CybORG simulation only and does |
| 29 | + not run real exploit tools or interact with external networks. |
| 30 | + """ |
| 31 | + default_args: dict = { |
| 32 | + "steps_per_episode": 30, |
| 33 | + "num_drones": 18, |
| 34 | + "timeout": 240, |
| 35 | + } |
| 36 | + |
| 37 | + def _game_arg(self, key: str): |
| 38 | + return self.game_config.get("args", {}).get(key, self.default_args[key]) |
| 39 | + |
| 40 | + def _episodes_per_round(self) -> int: |
| 41 | + return int(self.game_config.get("args", {}).get("episodes_per_round", self.game_config["sims_per_round"])) |
| 42 | + |
| 43 | + def validate_code(self, agent: Player) -> tuple[bool, str | None]: |
| 44 | + quoted_submission = shlex.quote(self.submission) |
| 45 | + file_check = agent.environment.execute(f"test -f {quoted_submission} && echo exists") |
| 46 | + if "exists" not in file_check["output"]: |
| 47 | + return False, f"Submission file `{self.submission}` not found in the workspace root" |
| 48 | + |
| 49 | + content = agent.environment.execute(f"cat {quoted_submission}")["output"] |
| 50 | + if not content.strip(): |
| 51 | + return False, f"`{self.submission}` is empty" |
| 52 | + |
| 53 | + syntax_check = agent.environment.execute(f"python -m py_compile {quoted_submission}") |
| 54 | + if syntax_check["returncode"] != 0: |
| 55 | + return False, f"Python syntax error in `{self.submission}`:\n{syntax_check['output']}" |
| 56 | + |
| 57 | + import_check = agent.environment.execute( |
| 58 | + "python - <<'PY'\n" |
| 59 | + "import importlib.util\n" |
| 60 | + f"spec = importlib.util.spec_from_file_location('submission_agent', {self.submission!r})\n" |
| 61 | + "module = importlib.util.module_from_spec(spec)\n" |
| 62 | + "spec.loader.exec_module(module)\n" |
| 63 | + "assert hasattr(module, 'MyAgent'), 'MyAgent class not found'\n" |
| 64 | + "from CybORG.Agents import BaseAgent\n" |
| 65 | + "assert issubclass(module.MyAgent, BaseAgent), 'MyAgent must inherit from a CybORG BaseAgent class'\n" |
| 66 | + "PY" |
| 67 | + ) |
| 68 | + if import_check["returncode"] != 0: |
| 69 | + return False, f"Could not import `MyAgent` from `{self.submission}`:\n{import_check['output']}" |
| 70 | + |
| 71 | + return True, None |
| 72 | + |
| 73 | + def execute_round(self, agents: list[Player]) -> None: |
| 74 | + agent_args = [] |
| 75 | + for agent in agents: |
| 76 | + agent_args.extend(["--agent", f"{agent.name}=/{agent.name}/{self.submission}"]) |
| 77 | + |
| 78 | + cmd = [ |
| 79 | + "python", |
| 80 | + "run_cyborg.py", |
| 81 | + "--episodes", |
| 82 | + str(self._episodes_per_round()), |
| 83 | + "--steps", |
| 84 | + str(self._game_arg("steps_per_episode")), |
| 85 | + "--drones", |
| 86 | + str(self._game_arg("num_drones")), |
| 87 | + "--output", |
| 88 | + str(self.log_env / RESULTS_JSON), |
| 89 | + *agent_args, |
| 90 | + ] |
| 91 | + full_cmd = " ".join(shlex.quote(part) for part in cmd) |
| 92 | + self.logger.info(f"Running game: {full_cmd}") |
| 93 | + try: |
| 94 | + response = self.environment.execute(full_cmd, timeout=int(self._game_arg("timeout"))) |
| 95 | + except subprocess.TimeoutExpired as exc: |
| 96 | + raise RuntimeError("CybORG round timed out") from exc |
| 97 | + assert_zero_exit_code(response, logger=self.logger) |
| 98 | + |
| 99 | + def get_results(self, agents: list[Player], round_num: int, stats: RoundStats): |
| 100 | + result_file = self.log_round(round_num) / RESULTS_JSON |
| 101 | + if not result_file.exists(): |
| 102 | + self.logger.error(f"Missing result file: {result_file}") |
| 103 | + stats.winner = RESULT_TIE |
| 104 | + for agent in agents: |
| 105 | + stats.scores[agent.name] = 0.0 |
| 106 | + stats.player_stats[agent.name].score = 0.0 |
| 107 | + return |
| 108 | + |
| 109 | + with open(result_file) as f: |
| 110 | + result = json.load(f) |
| 111 | + |
| 112 | + scores = {agent.name: 0.0 for agent in agents} |
| 113 | + for player, score in result.get("average_scores", {}).items(): |
| 114 | + if player in scores: |
| 115 | + scores[player] = float(score) |
| 116 | + |
| 117 | + stats.scores = scores |
| 118 | + stats.details = result.get("details", []) |
| 119 | + for player, score in scores.items(): |
| 120 | + stats.player_stats[player].score = score |
| 121 | + |
| 122 | + if not scores: |
| 123 | + stats.winner = RESULT_TIE |
| 124 | + return |
| 125 | + |
| 126 | + top_score = max(scores.values()) |
| 127 | + winners = [player for player, score in scores.items() if score == top_score] |
| 128 | + stats.winner = winners[0] if len(winners) == 1 else RESULT_TIE |
0 commit comments