Buckets:

download
raw
17.8 kB
"""
Agent-to-Agent Email Communication Chain
========================================
Distributed agent workflow using email as message bus.
Each agent has its own email address.
Messages encoded in Base64 for data integrity.
Flow:
Agent A ──▶ [Base64 Encode] ──▶ Email ──▶ Agent B ──▶ [Base64 Decode] ──▶ Process ──▶ Next Agent
Usage:
from agent_comm.email_chain import AgentEmailNode, AgentChain
# Create agent nodes
scanner = AgentEmailNode("scanner@pentest.local", role="scanner")
analyzer = AgentEmailNode("analyzer@pentest.local", role="analyzer")
reporter = AgentEmailNode("reporter@pentest.local", role="reporter")
# Create chain
chain = AgentChain([scanner, analyzer, reporter])
# Start workflow
chain.start_workflow({"target": "example.com"})
"""
import base64
import json
import logging
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from typing import Any, Callable, Dict, List, Optional
from notifications.email_sender import EmailConfig, EmailReporter
logger = logging.getLogger(__name__)
@dataclass
class AgentMessage:
"""
Standard message format for agent communication.
All data is JSON-serializable and then Base64 encoded for email transport.
"""
message_id: str
workflow_id: str
sender: str # agent email
recipient: str # agent email
message_type: str # "task", "result", "handoff", "status"
payload: Dict[str, Any] # Actual data
timestamp: str
chain_position: int # Position in supply chain
total_agents: int
history: List[Dict] # Audit trail
@classmethod
def create(
cls,
sender: str,
recipient: str,
message_type: str,
payload: Dict[str, Any],
workflow_id: Optional[str] = None,
chain_position: int = 0,
total_agents: int = 1,
history: Optional[List[Dict]] = None,
) -> "AgentMessage":
"""Factory method to create a new message."""
return cls(
message_id=str(uuid.uuid4())[:8],
workflow_id=workflow_id or str(uuid.uuid4())[:12],
sender=sender,
recipient=recipient,
message_type=message_type,
payload=payload,
timestamp=datetime.now(timezone.utc).isoformat(),
chain_position=chain_position,
total_agents=total_agents,
history=history or [],
)
def to_dict(self) -> Dict:
"""Convert to dictionary."""
return asdict(self)
@classmethod
def from_dict(cls, data: Dict) -> "AgentMessage":
"""Create from dictionary."""
return cls(**data)
def encode(self) -> str:
"""
Encode message to Base64 for email transport.
Returns:
Base64 encoded JSON string
"""
json_str = json.dumps(self.to_dict(), default=str)
base64_bytes = base64.b64encode(json_str.encode("utf-8"))
return base64_bytes.decode("utf-8")
@classmethod
def decode(cls, base64_str: str) -> "AgentMessage":
"""
Decode Base64 message back to AgentMessage.
Args:
base64_str: Base64 encoded message
Returns:
Decoded AgentMessage
"""
try:
base64_bytes = base64_str.encode("utf-8")
json_str = base64.b64decode(base64_bytes).decode("utf-8")
data = json.loads(json_str)
return cls.from_dict(data)
except Exception as e:
logger.error(f"Failed to decode message: {e}")
raise
def add_history_entry(self, agent: str, action: str, status: str = "completed"):
"""Add entry to audit trail."""
self.history.append(
{
"agent": agent,
"action": action,
"timestamp": datetime.now(timezone.utc).isoformat(),
"status": status,
}
)
class AgentEmailNode:
"""
Represents an agent in the email chain.
Each agent has:
- Unique email address
- Specific role/function
- Handler for processing messages
"""
def __init__(
self,
email: str,
role: str,
handler: Optional[Callable[[AgentMessage], Dict[str, Any]]] = None,
email_config: Optional[EmailConfig] = None,
):
"""
Initialize agent node.
Args:
email: Agent's unique email address (e.g., "scanner@pentest.local")
role: Agent role (e.g., "scanner", "analyzer", "reporter")
handler: Function to process incoming messages
email_config: Email configuration for sending
"""
self.email = email
self.role = role
self.handler = handler or self._default_handler
self.email_reporter = EmailReporter(email_config)
logger.info(f"Agent node initialized: {email} (role: {role})")
def _default_handler(self, message: AgentMessage) -> Dict[str, Any]:
"""Default handler - just passes through payload."""
logger.info(f"Agent {self.email} processing message {message.message_id}")
return message.payload
def process_message(self, base64_content: str) -> Optional[AgentMessage]:
"""
Process incoming Base64 encoded message.
Args:
base64_content: Base64 encoded message from email body
Returns:
Response message to send to next agent, or None if chain ends
"""
try:
# Decode message
message = AgentMessage.decode(base64_content)
logger.info(f"Agent {self.email} received message: {message.message_id}")
# Verify this message is for us
if message.recipient != self.email:
logger.warning(f"Message not for this agent. To: {message.recipient}, Us: {self.email}")
return None
# Add history entry
message.add_history_entry(self.email, f"{self.role}_started")
# Process with handler
result_payload = self.handler(message)
# Update history
message.add_history_entry(self.email, f"{self.role}_completed", "success")
# Update message for next agent
message.payload = result_payload
message.chain_position += 1
message.sender = self.email
logger.info(f"Agent {self.email} completed processing")
return message
except Exception as e:
logger.error(f"Agent {self.email} failed to process message: {e}")
return None
def send_to_next(self, message: AgentMessage, next_agent_email: str) -> bool:
"""
Send processed message to next agent in chain.
Args:
message: Processed message
next_agent_email: Email of next agent
Returns:
True if sent successfully
"""
message.recipient = next_agent_email
# Encode to Base64
encoded_payload = message.encode()
# Send email
subject = f"[AGENT-CHAIN] Workflow {message.workflow_id} - Step {message.chain_position}/{message.total_agents}"
# Create simple text body with Base64 payload
email_body = f"""
AGENT-CHAIN MESSAGE
===================
Workflow ID: {message.workflow_id}
Message ID: {message.message_id}
From: {message.sender}
To: {next_agent_email}
Type: {message.message_type}
Position: {message.chain_position}/{message.total_agents}
BASE64 PAYLOAD:
{encoded_payload}
---
This is an automated message from the Zen-AI-Pentest Agent Chain.
Do not reply to this email.
"""
try:
success = self.email_reporter.send_simple_notification(
to_email=next_agent_email,
subject=subject,
message=email_body,
)
if success:
logger.info(f"Message sent to {next_agent_email}")
else:
logger.error(f"Failed to send message to {next_agent_email}")
return success
except Exception as e:
logger.error(f"Error sending message: {e}")
return False
def __repr__(self):
return f"AgentEmailNode(email={self.email}, role={self.role})"
class AgentChain:
"""
Manages a chain of agents working together.
Example chain:
Scanner ──▶ Analyzer ──▶ Reporter
"""
def __init__(self, agents: List[AgentEmailNode]):
"""
Initialize agent chain.
Args:
agents: Ordered list of agent nodes
"""
self.agents = agents
self.total_agents = len(agents)
if self.total_agents < 2:
raise ValueError("Chain must have at least 2 agents")
logger.info(f"Agent chain created with {self.total_agents} agents")
def start_workflow(self, initial_data: Dict[str, Any]) -> str:
"""
Start workflow by sending initial message to first agent.
Args:
initial_data: Initial payload for first agent
Returns:
Workflow ID
"""
first_agent = self.agents[0]
second_agent = self.agents[1] if len(self.agents) > 1 else None
# Create initial message
message = AgentMessage.create(
sender="orchestrator@pentest.local",
recipient=first_agent.email,
message_type="task",
payload=initial_data,
chain_position=1,
total_agents=self.total_agents,
)
# Send to first agent
if second_agent:
success = first_agent.send_to_next(message, second_agent.email)
else:
# Single agent chain - just send to first
success = first_agent.send_to_next(message, first_agent.email)
if success:
logger.info(f"Workflow {message.workflow_id} started")
return message.workflow_id
else:
raise RuntimeError("Failed to start workflow")
def get_next_agent(self, current_email: str) -> Optional[AgentEmailNode]:
"""Get next agent in chain."""
for i, agent in enumerate(self.agents):
if agent.email == current_email and i + 1 < len(self.agents):
return self.agents[i + 1]
return None
def is_last_agent(self, email: str) -> bool:
"""Check if agent is last in chain."""
return self.agents[-1].email == email
class AgentChainOrchestrator:
"""
High-level orchestrator for agent chains.
Predefined chains for common workflows.
"""
@staticmethod
def create_scan_chain(
email_config: Optional[EmailConfig] = None,
) -> AgentChain:
"""
Create standard pentest scan chain:
Scanner ──▶ Analyzer ──▶ Reporter
"""
scanner = AgentEmailNode(
email="scanner@pentest.local",
role="scanner",
handler=AgentHandlers.scan_handler,
email_config=email_config,
)
analyzer = AgentEmailNode(
email="analyzer@pentest.local",
role="analyzer",
handler=AgentHandlers.analyze_handler,
email_config=email_config,
)
reporter = AgentEmailNode(
email="reporter@pentest.local",
role="reporter",
handler=AgentHandlers.report_handler,
email_config=email_config,
)
return AgentChain([scanner, analyzer, reporter])
@staticmethod
def create_recon_chain(
email_config: Optional[EmailConfig] = None,
) -> AgentChain:
"""
Create reconnaissance chain:
Subfinder ──▶ DNSResolver ──▶ PortScanner
"""
subfinder = AgentEmailNode(
email="subfinder@pentest.local",
role="subfinder",
handler=AgentHandlers.subdomain_handler,
email_config=email_config,
)
dns = AgentEmailNode(
email="dns@pentest.local",
role="dns_resolver",
handler=AgentHandlers.dns_handler,
email_config=email_config,
)
ports = AgentEmailNode(
email="portscanner@pentest.local",
role="port_scanner",
handler=AgentHandlers.port_handler,
email_config=email_config,
)
return AgentChain([subfinder, dns, ports])
class AgentHandlers:
"""
Predefined handler functions for common agent roles.
"""
@staticmethod
def scan_handler(message: AgentMessage) -> Dict[str, Any]:
"""Scanner agent handler."""
target = message.payload.get("target")
logger.info(f"Scanner: Scanning {target}")
# Simulate scan
import random
findings = []
for i in range(random.randint(1, 5)):
findings.append(
{
"id": f"VULN-{i + 1}",
"severity": random.choice(["critical", "high", "medium", "low"]),
"title": f"Vulnerability {i + 1} on {target}",
}
)
return {
"target": target,
"scan_id": str(uuid.uuid4())[:8],
"findings": findings,
"scan_time": datetime.now(timezone.utc).isoformat(),
}
@staticmethod
def analyze_handler(message: AgentMessage) -> Dict[str, Any]:
"""Analyzer agent handler."""
findings = message.payload.get("findings", [])
logger.info(f"Analyzer: Analyzing {len(findings)} findings")
# Analyze and prioritize
prioritized = sorted(findings, key=lambda x: x.get("severity", "low"))
return {
**message.payload,
"analyzed": True,
"prioritized_findings": prioritized,
"risk_score": len([f for f in findings if f.get("severity") in ["critical", "high"]]),
}
@staticmethod
def report_handler(message: AgentMessage) -> Dict[str, Any]:
"""Reporter agent handler."""
logger.info("Reporter: Generating final report")
return {
**message.payload,
"report_generated": True,
"report_id": str(uuid.uuid4())[:8],
"final_status": "completed",
}
@staticmethod
def subdomain_handler(message: AgentMessage) -> Dict[str, Any]:
"""Subdomain finder handler."""
target = message.payload.get("target")
logger.info(f"Subfinder: Finding subdomains for {target}")
return {
**message.payload,
"subdomains": [
f"www.{target}",
f"api.{target}",
f"admin.{target}",
],
}
@staticmethod
def dns_handler(message: AgentMessage) -> Dict[str, Any]:
"""DNS resolver handler."""
subdomains = message.payload.get("subdomains", [])
logger.info(f"DNS: Resolving {len(subdomains)} subdomains")
return {
**message.payload,
"resolved": {sd: f"192.168.1.{i + 1}" for i, sd in enumerate(subdomains)},
}
@staticmethod
def port_handler(message: AgentMessage) -> Dict[str, Any]:
"""Port scanner handler."""
resolved = message.payload.get("resolved", {})
logger.info(f"PortScanner: Scanning {len(resolved)} hosts")
return {
**message.payload,
"open_ports": {ip: [80, 443, 22] for ip in resolved.values()},
}
def parse_email_content(email_body: str) -> Optional[str]:
"""
Parse Base64 payload from email body.
Args:
email_body: Raw email body text
Returns:
Base64 payload string or None
"""
lines = email_body.split("\n")
in_payload = False
payload_lines = []
for line in lines:
if "BASE64 PAYLOAD:" in line:
in_payload = True
continue
if in_payload:
if line.strip() == "" or line.startswith("---"):
break
payload_lines.append(line.strip())
if payload_lines:
return "".join(payload_lines)
return None
# Convenience function for manual chain processing
def process_chain_step(
agent: AgentEmailNode,
email_body: str,
next_agent_email: Optional[str] = None,
) -> bool:
"""
Process one step in the chain from received email.
Args:
agent: This agent node
email_body: Received email body
next_agent_email: Next agent's email (None if last)
Returns:
True if successful
"""
# Parse Base64 payload
base64_payload = parse_email_content(email_body)
if not base64_payload:
logger.error("No Base64 payload found in email")
return False
# Process message
result_message = agent.process_message(base64_payload)
if not result_message:
return False
# Send to next if not last
if next_agent_email:
return agent.send_to_next(result_message, next_agent_email)
else:
logger.info(f"Chain complete. Final result: {result_message.payload}")
return True
if __name__ == "__main__":
# Example usage
print("Agent Email Chain System")
print("=" * 50)
# Create a simple 3-agent chain
chain = AgentChainOrchestrator.create_scan_chain()
# Start workflow
workflow_id = chain.start_workflow(
{
"target": "example.com",
"scan_type": "full",
}
)
print(f"Workflow started: {workflow_id}")
print("\nChain configuration:")
for i, agent in enumerate(chain.agents):
print(f" {i + 1}. {agent.role} ({agent.email})")

Xet Storage Details

Size:
17.8 kB
·
Xet hash:
041a989f857fa0d6a559669d688b2ed15ecc8a1719b0b1f6717f719312a65f19

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.