Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /agents /kimi_master_agent.py
| """ | |
| ๐ Kimi Master Agent - The Ultimate Swarm Controller. | |
| ==================================================== | |
| Integrates Kimi CLI authentication with Zen-AI-Pentest agent swarm. | |
| Acts as the central brain for coordinating all other agents. | |
| Features: | |
| - OAuth token retrieval from Kimi CLI secure storage | |
| - Agent swarm coordination via email chains | |
| - Base64-encoded message passing | |
| - Automatic token refresh | |
| - Multi-agent orchestration | |
| Architecture: | |
| Kimi Master Agent (This Module) | |
| โ | |
| โโโถ Reads OAuth token from Kimi CLI | |
| โโโถ Coordinates Scanner Agent | |
| โโโถ Coordinates Analyzer Agent | |
| โโโถ Coordinates Reporter Agent | |
| Usage: | |
| from agents.kimi_master_agent import KimiMasterAgent | |
| master = KimiMasterAgent() | |
| await master.run_swarm_scan("example.com") | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| from dataclasses import dataclass | |
| from typing import Any, Dict, List, Optional | |
| # Import Kimi Auth Bridge | |
| try: | |
| from kimi_auth_bridge import AsyncKimiAuthBridge | |
| KIMI_BRIDGE_AVAILABLE = True | |
| except ImportError: | |
| KIMI_BRIDGE_AVAILABLE = False | |
| logging.warning("kimi-auth-bridge not installed. Install with: pip install kimi-auth-bridge") | |
| # Import our agent chain system | |
| from agent_comm.email_chain import ( | |
| AgentChain, | |
| AgentChainOrchestrator, | |
| AgentEmailNode, | |
| AgentMessage, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class SwarmConfig: | |
| """Configuration for Kimi Master Agent Swarm.""" | |
| # Agent email addresses | |
| scanner_email: str = "scanner@pentest.local" | |
| analyzer_email: str = "analyzer@pentest.local" | |
| reporter_email: str = "reporter@pentest.local" | |
| # Kimi API settings | |
| kimi_model: str = "kimi-for-coding" | |
| use_kimi_for_analysis: bool = True | |
| # Swarm settings | |
| max_concurrent_agents: int = 3 | |
| enable_email_chain: bool = True | |
| enable_base64_encoding: bool = True | |
| class KimiMasterAgent: | |
| """ | |
| Master agent that coordinates the entire pentest swarm using Kimi CLI auth. | |
| This agent acts as the central brain: | |
| 1. Authenticates with Kimi CLI for AI capabilities | |
| 2. Coordinates sub-agents via email chains | |
| 3. Processes results using Kimi AI | |
| 4. Generates final reports | |
| Example: | |
| >>> master = KimiMasterAgent() | |
| >>> await master.initialize() | |
| >>> result = await master.run_swarm_scan("target.com") | |
| """ | |
| def __init__(self, config: Optional[SwarmConfig] = None): | |
| """ | |
| Initialize Kimi Master Agent. | |
| Args: | |
| config: Swarm configuration. Uses defaults if None. | |
| """ | |
| self.config = config or SwarmConfig() | |
| self.kimi_bridge: Optional[AsyncKimiAuthBridge] = None | |
| self.auth_token: Optional[str] = None | |
| self.agent_chain: Optional[AgentChain] = None | |
| if not KIMI_BRIDGE_AVAILABLE: | |
| logger.error("Kimi Auth Bridge not available. Some features disabled.") | |
| async def initialize(self) -> bool: | |
| """ | |
| Initialize the master agent and authenticate with Kimi. | |
| Returns: | |
| True if initialization successful | |
| """ | |
| logger.info("๐ Initializing Kimi Master Agent...") | |
| # Initialize Kimi auth | |
| if KIMI_BRIDGE_AVAILABLE: | |
| self.kimi_bridge = AsyncKimiAuthBridge() | |
| if await self.kimi_bridge.is_authenticated(): | |
| self.auth_token = await self.kimi_bridge.get_access_token() | |
| logger.info("โ Authenticated with Kimi CLI") | |
| logger.info(f" Token: {self.kimi_bridge.get_token_preview()}") | |
| else: | |
| logger.warning("โ ๏ธ Not authenticated with Kimi CLI") | |
| logger.info(" Run 'kimi login' to authenticate") | |
| return False | |
| # Initialize agent chain | |
| if self.config.enable_email_chain: | |
| self.agent_chain = AgentChainOrchestrator.create_scan_chain() | |
| logger.info("โ Agent email chain initialized") | |
| logger.info("๐ Kimi Master Agent ready!") | |
| return True | |
| async def run_swarm_scan(self, target: str, scan_type: str = "full") -> Dict[str, Any]: | |
| """ | |
| Run a complete pentest scan using the agent swarm. | |
| This coordinates: | |
| 1. Scanner Agent - Discovers vulnerabilities | |
| 2. Analyzer Agent - Analyzes findings with Kimi AI | |
| 3. Reporter Agent - Generates final report | |
| Args: | |
| target: Target URL/domain to scan | |
| scan_type: Type of scan (quick, full, deep) | |
| Returns: | |
| Complete scan results with findings and report | |
| """ | |
| logger.info(f"๐ฏ Starting swarm scan of {target}") | |
| if not self.auth_token: | |
| logger.error("Not authenticated. Call initialize() first.") | |
| return {"error": "Not authenticated"} | |
| # Create initial task with Kimi token | |
| initial_task = { | |
| "target": target, | |
| "scan_type": scan_type, | |
| "kimi_token": self.auth_token, | |
| "use_ai_analysis": self.config.use_kimi_for_analysis, | |
| "timestamp": str(asyncio.get_event_loop().time()), | |
| } | |
| # Start agent chain | |
| if self.agent_chain: | |
| workflow_id = self.agent_chain.start_workflow(initial_task) | |
| logger.info(f"๐ง Agent chain started: {workflow_id}") | |
| # In real implementation, agents would process via email | |
| # Here we simulate the flow | |
| results = await self._simulate_agent_flow(initial_task) | |
| return results | |
| else: | |
| # Direct processing without email chain | |
| return await self._direct_scan(initial_task) | |
| async def _simulate_agent_flow(self, task: Dict) -> Dict[str, Any]: | |
| """Simulate the agent chain flow (for demo/testing)""" | |
| target = task["target"] | |
| # Step 1: Scanner | |
| logger.info("๐ Scanner Agent: Discovering vulnerabilities...") | |
| scan_results = await self._run_scanner(target) | |
| # Step 2: Analyzer (with Kimi AI) | |
| logger.info("๐ง Analyzer Agent: Analyzing with Kimi AI...") | |
| analysis = await self._run_analyzer(scan_results) | |
| # Step 3: Reporter | |
| logger.info("๐ Reporter Agent: Generating report...") | |
| report = await self._run_reporter(analysis) | |
| return { | |
| "target": target, | |
| "scan_results": scan_results, | |
| "analysis": analysis, | |
| "report": report, | |
| "kimi_enhanced": True, | |
| } | |
| async def _direct_scan(self, task: Dict) -> Dict[str, Any]: | |
| """Direct scan without agent chain""" | |
| logger.info("Running direct scan (no agent chain)") | |
| return await self._simulate_agent_flow(task) | |
| async def _run_scanner(self, target: str) -> Dict: | |
| """Simulate scanner agent""" | |
| # In real implementation, this would trigger actual scanning tools | |
| # For now, simulate findings | |
| await asyncio.sleep(1) # Simulate work | |
| return { | |
| "target": target, | |
| "findings": [ | |
| { | |
| "id": "VULN-001", | |
| "severity": "critical", | |
| "title": "SQL Injection", | |
| "cvss": 9.8, | |
| }, | |
| { | |
| "id": "VULN-002", | |
| "severity": "high", | |
| "title": "XSS", | |
| "cvss": 7.5, | |
| }, | |
| { | |
| "id": "VULN-003", | |
| "severity": "medium", | |
| "title": "CSRF", | |
| "cvss": 5.3, | |
| }, | |
| ], | |
| "scan_time": 120.5, | |
| } | |
| async def _run_analyzer(self, scan_results: Dict) -> Dict: | |
| """Run Kimi AI analysis on findings""" | |
| if not self.auth_token or not self.config.use_kimi_for_analysis: | |
| return {"ai_analysis": False, "findings": scan_results["findings"]} | |
| # In real implementation, this would call Kimi API | |
| # For demo, simulate AI analysis | |
| await asyncio.sleep(1) | |
| findings = scan_results["findings"] | |
| # Simulate AI prioritization | |
| for finding in findings: | |
| if finding["severity"] == "critical": | |
| finding["ai_priority"] = "P0 - Immediate Action" | |
| finding["ai_recommendation"] = "Fix immediately - high exploitability" | |
| elif finding["severity"] == "high": | |
| finding["ai_priority"] = "P1 - High Priority" | |
| finding["ai_recommendation"] = "Fix within 24 hours" | |
| else: | |
| finding["ai_priority"] = "P2 - Standard" | |
| finding["ai_recommendation"] = "Fix within sprint" | |
| return { | |
| "ai_analysis": True, | |
| "ai_model": self.config.kimi_model, | |
| "findings": findings, | |
| "risk_score": sum(f.get("cvss", 0) for f in findings) / len(findings), | |
| } | |
| async def _run_reporter(self, analysis: Dict) -> Dict: | |
| """Generate final report""" | |
| await asyncio.sleep(0.5) | |
| findings = analysis.get("findings", []) | |
| return { | |
| "report_id": f"RPT-{asyncio.get_event_loop().time():.0f}", | |
| "total_findings": len(findings), | |
| "critical_count": len([f for f in findings if f.get("severity") == "critical"]), | |
| "high_count": len([f for f in findings if f.get("severity") == "high"]), | |
| "executive_summary": f"Scan identified {len(findings)} vulnerabilities. " | |
| f"Immediate attention required for {len([f for f in findings if f.get('severity') in ['critical', 'high']])} issues.", | |
| "report_format": "PDF/HTML", | |
| } | |
| async def query_kimi(self, prompt: str) -> str: | |
| """ | |
| Send a query to Kimi AI using the authenticated token. | |
| Args: | |
| prompt: The prompt to send | |
| Returns: | |
| Kimi's response | |
| """ | |
| if not self.auth_token: | |
| return "Error: Not authenticated" | |
| # In real implementation, this would call Kimi API | |
| # For demo, return simulated response | |
| logger.info(f"Querying Kimi: {prompt[:50]}...") | |
| return ( | |
| f"Kimi analysis complete. Based on the prompt '{prompt[:30]}...', " | |
| f"I recommend prioritizing security findings by CVSS score and exploitability." | |
| ) | |
| def get_auth_status(self) -> Dict[str, Any]: | |
| """Get current authentication status""" | |
| return { | |
| "authenticated": self.auth_token is not None, | |
| "token_preview": (self.kimi_bridge.get_token_preview() if self.kimi_bridge else None), | |
| "kimi_bridge_available": KIMI_BRIDGE_AVAILABLE, | |
| "agent_chain_ready": self.agent_chain is not None, | |
| } | |
| async def coordinate_agents(self, agents: List[AgentEmailNode], task: Dict) -> List[Dict]: | |
| """ | |
| Coordinate multiple agents for a complex task. | |
| Args: | |
| agents: List of agent nodes to coordinate | |
| task: Task dictionary | |
| Returns: | |
| List of results from each agent | |
| """ | |
| logger.info(f"Coordinating {len(agents)} agents...") | |
| results = [] | |
| for i, agent in enumerate(agents): | |
| logger.info(f"Dispatching to Agent {i + 1}: {agent.role}") | |
| # Create message | |
| AgentMessage.create( | |
| sender="kimi-master@pentest.local", | |
| recipient=agent.email, | |
| message_type="task", | |
| payload={**task, "agent_index": i}, | |
| chain_position=i + 1, | |
| total_agents=len(agents), | |
| ) | |
| # In real implementation, send via email | |
| # For now, simulate | |
| result = {"agent": agent.role, "status": "completed", "task": task} | |
| results.append(result) | |
| return results | |
| class KimiSwarmController: | |
| """ | |
| High-level controller for managing multiple Kimi-powered agent swarms. | |
| This is the main entry point for using Kimi as the brain of the operation. | |
| """ | |
| def __init__(self): | |
| self.master = KimiMasterAgent() | |
| self.active_scans: Dict[str, Any] = {} | |
| async def start(self): | |
| """Initialize the swarm controller""" | |
| success = await self.master.initialize() | |
| if success: | |
| logger.info("๐ Kimi Swarm Controller initialized") | |
| return success | |
| async def scan_target(self, target: str, scan_type: str = "full") -> str: | |
| """ | |
| Start a scan and return scan ID. | |
| Args: | |
| target: Target to scan | |
| scan_type: Scan type (quick, full, deep) | |
| Returns: | |
| Scan ID for tracking | |
| """ | |
| import uuid | |
| scan_id = str(uuid.uuid4())[:8] | |
| logger.info(f"๐ Starting scan {scan_id} for {target}") | |
| # Run scan | |
| results = await self.master.run_swarm_scan(target, scan_type) | |
| # Store results | |
| self.active_scans[scan_id] = { | |
| "target": target, | |
| "scan_type": scan_type, | |
| "results": results, | |
| "status": "completed", | |
| } | |
| return scan_id | |
| def get_scan_status(self, scan_id: str) -> Optional[Dict]: | |
| """Get status of a scan""" | |
| return self.active_scans.get(scan_id) | |
| async def ask_kimi(self, question: str) -> str: | |
| """Ask Kimi a security-related question""" | |
| return await self.master.query_kimi(question) | |
| # Convenience functions for quick usage | |
| async def quick_scan(target: str) -> Dict[str, Any]: | |
| """ | |
| Quick one-liner to scan a target. | |
| Args: | |
| target: Target URL/domain | |
| Returns: | |
| Scan results | |
| """ | |
| controller = KimiSwarmController() | |
| await controller.start() | |
| scan_id = await controller.scan_target(target, "quick") | |
| return controller.get_scan_status(scan_id) | |
| async def analyze_with_kimi(findings: List[Dict]) -> str: | |
| """ | |
| Analyze findings using Kimi AI. | |
| Args: | |
| findings: List of vulnerability findings | |
| Returns: | |
| Kimi's analysis | |
| """ | |
| master = KimiMasterAgent() | |
| await master.initialize() | |
| prompt = f"Analyze these security findings and provide recommendations: {json.dumps(findings, indent=2)}" | |
| return await master.query_kimi(prompt) | |
| if __name__ == "__main__": | |
| # Demo usage | |
| async def demo(): | |
| print("๐ Kimi Master Agent Demo") | |
| print("=" * 60) | |
| # Initialize | |
| controller = KimiSwarmController() | |
| success = await controller.start() | |
| if not success: | |
| print("\nโ ๏ธ Not authenticated with Kimi CLI") | |
| print(" Run: kimi login") | |
| return | |
| # Show status | |
| status = controller.master.get_auth_status() | |
| print(f"\nโ Authentication: {status['authenticated']}") | |
| print(f" Token: {status['token_preview']}") | |
| # Run scan | |
| print("\n๐ฏ Running demo scan...") | |
| scan_id = await controller.scan_target("demo.example.com", "quick") | |
| # Show results | |
| results = controller.get_scan_status(scan_id) | |
| print(f"\n๐ Scan {scan_id} completed!") | |
| print(f" Target: {results['target']}") | |
| print(f" Findings: {results['results']['scan_results']['findings']}") | |
| # Query Kimi | |
| print("\n๐ง Querying Kimi...") | |
| response = await controller.ask_kimi("How should I prioritize SQL Injection vs XSS?") | |
| print(f" Kimi: {response}") | |
| asyncio.run(demo()) | |
Xet Storage Details
- Size:
- 15.6 kB
- Xet hash:
- 1856960175bbaa66bf9bd57aad54610252100d459cc70dc383532c4ac9b889a5
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.