-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
422 lines (353 loc) · 16.1 KB
/
main.py
File metadata and controls
422 lines (353 loc) · 16.1 KB
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
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
"""
CyberDojo — Main CLI Entry Point
Usage:
python main.py train — Start co-evolutionary training
python main.py battle — Run a single battle with visualization
python main.py benchmark — Run agents against scripted baselines
python main.py dashboard — Start the visualization dashboard
"""
import argparse
import sys
import logging
from cyberdojo.config import CyberDojoConfig
from cyberdojo.trainer import CoEvolutionaryTrainer
from cyberdojo.agents import (
RedTeamAgent, BlueTeamAgent,
ScriptedRedAgent, ScriptedBlueAgent, RandomAgent,
)
from cyberdojo.llm_agents import LLMRedAgent, LLMBlueAgent, CyberCommanderAgent, CyberRedCommanderAgent, HAS_LANGCHAIN
from cyberdojo.apt_swarm import APTSwarmAgent
from cyberdojo.llm_scenario import generate_scenario
from cyberdojo.environment import CyberDojoEnv, RedAction, BlueAction
def setup_logging(verbose: bool = False) -> None:
"""Configure logging."""
level = logging.DEBUG if verbose else logging.INFO
logging.basicConfig(
level=level,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%H:%M:%S",
)
def cmd_train(args) -> None:
"""Run co-evolutionary training."""
config = CyberDojoConfig()
# Apply CLI overrides
if args.episodes:
config.training.total_episodes = args.episodes
if args.steps:
config.training.steps_per_episode = args.steps
if args.network_size:
sizes = {"small": config.network.small, "medium": config.network.medium,
"large": config.network.large}
config.network = sizes.get(args.network_size, config.network.small)()
if args.lr:
config.training.learning_rate = args.lr
trainer = CoEvolutionaryTrainer(config=config, verbose=1)
# Optionally connect to dashboard
if args.visualize:
try:
from dashboard.server import DashboardBridge
bridge = DashboardBridge(config.dashboard)
trainer.set_dashboard_callback(bridge.push_update)
bridge.start_async()
print(f"\n 🖥️ Dashboard: http://{config.dashboard.host}:{config.dashboard.port}\n")
except ImportError:
print(" ⚠️ Dashboard dependencies not available. Training without visualization.\n")
results = trainer.train(total_episodes=config.training.total_episodes)
# Save final agents
trainer.red_agent.save("./checkpoints/red_final")
trainer.blue_agent.save("./checkpoints/blue_final")
print("\n ✅ Agents saved to ./checkpoints/")
def cmd_battle(args) -> None:
"""Run a single battle."""
config = CyberDojoConfig()
if args.network_size:
sizes = {"small": config.network.small, "medium": config.network.medium,
"large": config.network.large}
config.network = sizes.get(args.network_size, config.network.small)()
if args.scenario:
print(f"\n 🧠 Generating Infinite Scenario: '{args.scenario}'...")
scenario = generate_scenario(args.scenario)
if scenario:
config.network.scenario_data = scenario
print(f" ✨ Generated scenario with {len(scenario['subnets'])} subnets and {len(scenario['nodes'])} nodes.")
else:
print(" ⚠️ Failed to generate scenario. Defaulting to random.")
if config.network.scenario_data:
n_nodes = len(config.network.scenario_data["nodes"])
else:
n_nodes = sum(config.network.nodes_per_subnet)
# Set up agents
if args.red == "scripted":
red = ScriptedRedAgent(n_nodes)
elif args.red == "random":
red = RandomAgent("red", RedAction.NUM_ACTIONS, n_nodes)
elif args.red == "llm":
red = LLMRedAgent(n_nodes)
elif args.red == "commander":
red = CyberRedCommanderAgent(n_nodes)
elif args.red == "swarm":
red = APTSwarmAgent(n_nodes)
else:
red = RedTeamAgent()
if args.red_checkpoint:
red.load(args.red_checkpoint)
if args.blue == "scripted":
blue = ScriptedBlueAgent(n_nodes)
elif args.blue == "random":
blue = RandomAgent("blue", BlueAction.NUM_ACTIONS, n_nodes)
elif args.blue == "llm":
blue = LLMBlueAgent(n_nodes)
elif args.blue == "commander":
blue = CyberCommanderAgent(n_nodes)
else:
blue = BlueTeamAgent()
if args.blue_checkpoint:
blue.load(args.blue_checkpoint)
trainer = CoEvolutionaryTrainer(
config=config, red_agent=red, blue_agent=blue, verbose=1
)
# Connect to dashboard if requested
if args.visualize:
try:
from dashboard.server import DashboardBridge
bridge = DashboardBridge(config.dashboard)
# Tell the dashboard which team the human commands
if args.red == "commander":
bridge.set_commander_mode("red")
elif args.blue == "commander":
bridge.set_commander_mode("blue")
trainer.set_dashboard_callback(bridge.push_update)
bridge.start_async()
print(f"\n 🖥️ Dashboard: http://{config.dashboard.host}:{config.dashboard.port}\n")
except ImportError:
pass
result = trainer.run_single_battle(visualize=not args.visualize)
print(f"\n {'🔴 RED WINS!' if result.winner == 'red' else '🔵 BLUE WINS!' if result.winner == 'blue' else '🤝 DRAW'}")
print(f" Score — Red: {result.red_score:.1f} | Blue: {result.blue_score:.1f}")
print(f" Compromised: {result.compromised_nodes}/{result.total_nodes}")
print(f" Data Stolen: {result.data_stolen:.1f}")
print(f" Detections: {result.detections}")
print(f" Steps: {result.steps}\n")
if getattr(args, "sim2real", False):
try:
from cyberdojo.sim2real import export_campaign
export_campaign(result.events)
except ImportError as e:
print(f" [!] Failed to export sim2real campaign: {e}")
if args.visualize:
import time
print(" Dashboard will remain open for 15 seconds so you can view the final state...")
time.sleep(15)
def cmd_benchmark(args) -> None:
"""Benchmark trained agents against baselines."""
config = CyberDojoConfig()
trainer = CoEvolutionaryTrainer(config=config, verbose=1)
# Load trained agents if checkpoints provided
if args.red_checkpoint:
trainer.red_agent.load(args.red_checkpoint)
if args.blue_checkpoint:
trainer.blue_agent.load(args.blue_checkpoint)
print("\n 📊 Running benchmarks...\n")
results = trainer.benchmark()
for matchup, data in results.items():
print(f" {matchup}:")
for k, v in data.items():
print(f" {k}: {v}")
print()
def cmd_demo(args) -> None:
"""Run continuous demo battles with dashboard visualization."""
import time
import threading
config = CyberDojoConfig()
if args.network_size:
sizes = {"small": config.network.small, "medium": config.network.medium,
"large": config.network.large}
config.network = sizes.get(args.network_size, config.network.small)()
n_nodes = sum(config.network.nodes_per_subnet)
# Start the dashboard server in background
try:
from dashboard.server import DashboardBridge, start_dashboard
bridge = DashboardBridge(config.dashboard)
bridge.start_async()
except ImportError as e:
print(f" ❌ Error: {e}")
print(" Run: pip install flask flask-socketio")
return
port = args.port or config.dashboard.port
print(f"\n ⚔️ CYBERDOJO — Live Demo Mode")
print(f" 🖥️ Dashboard: http://{config.dashboard.host}:{port}")
print(f" 📡 Open the link above in your browser!")
print(f" ⏹️ Press Ctrl+C to stop\n")
# Give server a moment to start
time.sleep(1.0)
red_elo = 1000.0
blue_elo = 1000.0
battle_num = 0
try:
while True:
battle_num += 1
import os
# Alternate agent types for variety
if battle_num % 4 == 0:
red = RandomAgent("red", RedAction.NUM_ACTIONS, n_nodes)
blue = ScriptedBlueAgent(n_nodes)
matchup = "Random Red vs Scripted Blue"
elif battle_num % 4 == 1:
red = ScriptedRedAgent(n_nodes)
blue = ScriptedBlueAgent(n_nodes)
matchup = "Scripted Red vs Scripted Blue"
elif battle_num % 4 == 2:
red = ScriptedRedAgent(n_nodes)
blue = RandomAgent("blue", BlueAction.NUM_ACTIONS, n_nodes)
matchup = "Scripted Red vs Random Blue"
else:
if HAS_LANGCHAIN and os.environ.get("OPENAI_API_KEY"):
red = LLMRedAgent(n_nodes)
blue = ScriptedBlueAgent(n_nodes)
matchup = "🤖 LLM Red vs Scripted Blue"
else:
red = ScriptedRedAgent(n_nodes)
blue = ScriptedBlueAgent(n_nodes)
matchup = "Scripted Red vs Scripted Blue"
print(f" ⚔️ Battle #{battle_num}: {matchup}")
# Create environment
env = CyberDojoEnv(config=config, mode="red")
env.set_opponent_policy(lambda obs, b=blue: b.act(obs))
obs, info = env.reset()
# Push initial network topology
bridge.push_update({
"step": 0,
"network_state": env.network.get_topology_data(),
"red": {"action": "preparing", "target": None, "events": {}},
"blue": {"action": "preparing", "target": None, "events": {}},
})
time.sleep(1.5)
for step in range(config.training.steps_per_episode):
action = red.act(obs)
obs, reward, terminated, truncated, info = env.step(action)
# Push the step data directly — it already has red/blue actions,
# targets, events, and full network state from _log_event()
bridge.push_update(env.step_data)
time.sleep(0.8) # Pace for visual observation
if terminated or truncated:
break
# Determine winner
compromised_ratio = info.get("compromised_ratio", 0)
data_stolen_ratio = info.get("data_stolen_ratio", 0)
red_score = compromised_ratio * 50 + data_stolen_ratio * 50
blue_score = (1 - compromised_ratio) * 30 + (1 - data_stolen_ratio) * 30
if red_score > blue_score + 10:
winner = "🔴 RED WINS"
winner_key = "red"
elif blue_score > red_score + 10:
winner = "🔵 BLUE WINS"
winner_key = "blue"
else:
winner = "🤝 DRAW"
winner_key = "draw"
# Update Elo-style ratings
e_red = 1.0 / (1.0 + 10 ** ((blue_elo - red_elo) / 400.0))
if winner_key == "red":
red_elo += 32 * (1.0 - e_red)
blue_elo += 32 * (0.0 - (1.0 - e_red))
elif winner_key == "blue":
red_elo += 32 * (0.0 - e_red)
blue_elo += 32 * (1.0 - (1.0 - e_red))
else:
red_elo += 32 * (0.5 - e_red)
blue_elo += 32 * (0.5 - (1.0 - e_red))
# Push training progress to dashboard charts
bridge.push_training_progress({
"red_elo": red_elo,
"blue_elo": blue_elo,
"battle": {
"episode": battle_num,
"red_score": red_score,
"blue_score": blue_score,
"winner": winner_key,
},
})
comp_nodes = info.get("compromised_nodes", 0)
total_nodes = info.get("total_nodes", n_nodes)
print(f" {winner} | Compromised: {comp_nodes}/{total_nodes} | "
f"Red: {red_score:.0f} Blue: {blue_score:.0f} | "
f"Elo R:{red_elo:.0f} B:{blue_elo:.0f}")
time.sleep(3.0) # Pause between battles
except KeyboardInterrupt:
print("\n\n ⏹️ Demo stopped. Thanks for watching!")
def cmd_dashboard(args) -> None:
"""Start the visualization dashboard."""
config = CyberDojoConfig()
if args.port:
config.dashboard.port = args.port
try:
from dashboard.server import start_dashboard
print(f"\n 🖥️ Starting CyberDojo Dashboard...")
print(f" 📡 Open http://{config.dashboard.host}:{config.dashboard.port}\n")
start_dashboard(config.dashboard)
except ImportError as e:
print(f" ❌ Error: {e}")
print(" Run: pip install flask flask-socketio eventlet")
def main():
parser = argparse.ArgumentParser(
description="⚔️ CyberDojo — Adversarial AI War Games Engine",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python main.py demo — Live demo with dashboard
python main.py train --episodes 500 — Co-evolutionary RL training
python main.py battle --red scripted --blue scripted
python main.py dashboard --port 5000
""",
)
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Demo command (recommended starting point)
demo_parser = subparsers.add_parser("demo", help="Run live demo with dashboard visualization")
demo_parser.add_argument("--network-size", choices=["small", "medium", "large"],
default="small")
demo_parser.add_argument("--port", type=int, default=5000)
demo_parser.set_defaults(func=cmd_demo)
# Train command
train_parser = subparsers.add_parser("train", help="Start co-evolutionary training")
train_parser.add_argument("--episodes", type=int, help="Number of training episodes")
train_parser.add_argument("--steps", type=int, help="Steps per episode")
train_parser.add_argument("--network-size", choices=["small", "medium", "large"],
default="small")
train_parser.add_argument("--lr", type=float, help="Learning rate")
train_parser.add_argument("--visualize", action="store_true",
help="Enable dashboard visualization")
train_parser.set_defaults(func=cmd_train)
# Battle command
battle_parser = subparsers.add_parser("battle", help="Run a single battle")
battle_parser.add_argument("--red", choices=["rl", "scripted", "random", "llm", "commander", "swarm"],
default="scripted")
battle_parser.add_argument("--blue", choices=["rl", "scripted", "random", "llm", "commander"],
default="scripted")
battle_parser.add_argument("--red-checkpoint", type=str)
battle_parser.add_argument("--blue-checkpoint", type=str)
battle_parser.add_argument("--network-size", choices=["small", "medium", "large"],
default="small")
battle_parser.add_argument("--scenario", type=str,
help="Generate a dynamic LLM scenario (e.g., 'Hospital', 'Bank')")
battle_parser.add_argument("--sim2real", action="store_true",
help="Export battle events as real-world CLI bash playbooks")
battle_parser.add_argument("--visualize", action="store_true",
help="Enable dashboard visualization")
battle_parser.set_defaults(func=cmd_battle)
# Benchmark command
bench_parser = subparsers.add_parser("benchmark", help="Benchmark against baselines")
bench_parser.add_argument("--red-checkpoint", type=str)
bench_parser.add_argument("--blue-checkpoint", type=str)
bench_parser.set_defaults(func=cmd_benchmark)
# Dashboard command
dash_parser = subparsers.add_parser("dashboard", help="Start visualization dashboard")
dash_parser.add_argument("--port", type=int, default=5000)
dash_parser.set_defaults(func=cmd_dashboard)
args = parser.parse_args()
if args.command is None:
parser.print_help()
sys.exit(1)
setup_logging(verbose=getattr(args, "verbose", False))
args.func(args)
if __name__ == "__main__":
main()