Buckets:

download
raw
9.17 kB
#!/usr/bin/env python3
"""
Agent Email Chain Examples
==========================
Shows how to use the agent-to-agent email communication system.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from agent_comm.email_chain import (
AgentChain,
AgentChainOrchestrator,
AgentEmailNode,
AgentHandlers,
AgentMessage,
)
def example_basic_chain():
"""Basic 3-agent chain: Scanner -> Analyzer -> Reporter"""
print("=" * 60)
print("Example 1: Basic Agent Chain")
print("=" * 60)
# Create chain
chain = AgentChainOrchestrator.create_scan_chain()
print("\nChain Configuration:")
for i, agent in enumerate(chain.agents, 1):
print(f" {i}. {agent.role} ({agent.email})")
# Start workflow
print("\nStarting workflow...")
workflow_id = chain.start_workflow(
{
"target": "example.com",
"scan_type": "full",
}
)
print(f"Workflow started: {workflow_id}")
print("\nNext steps (normally automated via email):")
print(" 1. Scanner receives email, processes, sends to Analyzer")
print(" 2. Analyzer receives email, processes, sends to Reporter")
print(" 3. Reporter receives email, generates final report")
def example_custom_handlers():
"""Custom agent handlers"""
print("\n" + "=" * 60)
print("Example 2: Custom Agent Handlers")
print("=" * 60)
# Custom handler for data processor
def data_processor_handler(message: AgentMessage):
"""Process and enrich data"""
data = message.payload
print(f" Processing data: {data}")
# Enrich data
data["processed"] = True
data["enriched_fields"] = ["field1", "field2"]
data["processed_at"] = "2024-01-15T10:00:00Z"
return data
# Create agents with custom handlers
collector = AgentEmailNode(
email="collector@pentest.local",
role="data_collector",
handler=AgentHandlers.subdomain_handler,
)
processor = AgentEmailNode(
email="processor@pentest.local",
role="data_processor",
handler=data_processor_handler,
)
# Create chain
chain = AgentChain([collector, processor])
print("\nCustom chain with 2 agents:")
print(f" 1. {collector.role}: {collector.email}")
print(f" 2. {processor.role}: {processor.email}")
# Start
workflow_id = chain.start_workflow(
{
"target": "example.com",
"data_source": "subdomain_enumeration",
}
)
print(f"\nWorkflow started: {workflow_id}")
def example_manual_processing():
"""Manual chain processing (simulating email reception)"""
print("\n" + "=" * 60)
print("Example 3: Manual Chain Processing")
print("=" * 60)
# Create a message manually
message = AgentMessage.create(
sender="orchestrator@pentest.local",
recipient="scanner@pentest.local",
message_type="task",
payload={"target": "test.com", "scan_type": "quick"},
workflow_id="test-workflow-001",
chain_position=1,
total_agents=2,
)
print(f"\nCreated message: {message.message_id}")
print(f"Workflow: {message.workflow_id}")
print(f"Payload: {message.payload}")
# Encode to Base64 (as would be in email)
encoded = message.encode()
print(f"\nBase64 encoded ({len(encoded)} chars):")
print(f" {encoded[:60]}...")
# Create agent
scanner = AgentEmailNode(
email="scanner@pentest.local",
role="scanner",
handler=AgentHandlers.scan_handler,
)
# Process (as if agent received email)
print("\nProcessing message...")
result = scanner.process_message(encoded)
if result:
print("✅ Processing complete")
print(f" New payload: {result.payload}")
print(f" History: {result.history}")
else:
print("❌ Processing failed")
def example_message_encoding():
"""Demonstrate Base64 encoding/decoding"""
print("\n" + "=" * 60)
print("Example 4: Base64 Encoding/Decoding")
print("=" * 60)
# Create message
original = AgentMessage.create(
sender="agent1@pentest.local",
recipient="agent2@pentest.local",
message_type="result",
payload={
"findings": [
{"id": "VULN-001", "severity": "critical"},
{"id": "VULN-002", "severity": "high"},
],
"scan_id": "scan-123",
},
)
print("\nOriginal Message:")
print(f" ID: {original.message_id}")
print(f" From: {original.sender}")
print(f" To: {original.recipient}")
print(f" Payload: {original.payload}")
# Encode
encoded = original.encode()
print("\nBase64 Encoded:")
print(f" Length: {len(encoded)} characters")
print(f" Content: {encoded[:80]}...")
# Decode
decoded = AgentMessage.decode(encoded)
print("\nDecoded Message:")
print(f" ID: {decoded.message_id}")
print(f" From: {decoded.sender}")
print(f" To: {decoded.recipient}")
print(f" Payload matches: {decoded.payload == original.payload}")
def example_recon_chain():
"""Reconnaissance chain: Subfinder -> DNS -> PortScanner"""
print("\n" + "=" * 60)
print("Example 5: Reconnaissance Chain")
print("=" * 60)
chain = AgentChainOrchestrator.create_recon_chain()
print("\nRecon Chain Configuration:")
for i, agent in enumerate(chain.agents, 1):
print(f" {i}. {agent.role}")
print(f" Email: {agent.email}")
print("\nStarting reconnaissance workflow...")
workflow_id = chain.start_workflow(
{
"target": "example.com",
"wordlist": "subdomains-top-1000.txt",
}
)
print(f"Workflow ID: {workflow_id}")
print("\nExpected flow:")
print(" 1. Subfinder finds subdomains")
print(" 2. DNS Resolver resolves IPs")
print(" 3. Port Scanner scans open ports")
def example_workflow_with_history():
"""Show audit trail / history feature"""
print("\n" + "=" * 60)
print("Example 6: Workflow with History/Audit Trail")
print("=" * 60)
# Create message with history tracking
message = AgentMessage.create(
sender="orchestrator@pentest.local",
recipient="scanner@pentest.local",
message_type="task",
payload={"target": "example.com"},
)
print(f"\nInitial message: {message.message_id}")
print(f"Initial history: {message.history}")
# Simulate agent processing
message.add_history_entry("scanner@pentest.local", "scan_started")
print(f"After start: {message.history}")
message.add_history_entry("scanner@pentest.local", "scan_completed", "success")
print(f"After completion: {message.history}")
# Simulate next agent
message.sender = "scanner@pentest.local"
message.recipient = "analyzer@pentest.local"
message.chain_position = 2
message.add_history_entry("analyzer@pentest.local", "analysis_started")
print(f"After analysis start: {message.history}")
print("\nFull audit trail:")
for entry in message.history:
print(f" [{entry['timestamp']}] {entry['agent']}: {entry['action']} ({entry['status']})")
def example_environment_setup():
"""Show environment configuration"""
print("\n" + "=" * 60)
print("Example 7: Environment Configuration")
print("=" * 60)
print("\nRequired environment variables:")
print(" SMTP_HOST=smtp.gmail.com")
print(" SMTP_PORT=587")
print(" SMTP_USER=your-agent@gmail.com")
print(" SMTP_PASS=your-app-password")
print(" FROM_NAME=Zen-AI-Agent")
print("\nAgent email addresses (example):")
print(" scanner@pentest.local")
print(" analyzer@pentest.local")
print(" reporter@pentest.local")
print(" collector@pentest.local")
print(" subfinder@pentest.local")
print(" dns@pentest.local")
print(" portscanner@pentest.local")
print("\nNote: These can be:")
print(" - Real email accounts")
print(" - Aliases of one account")
print(" - Distribution lists")
print(" - Different providers (Gmail, Outlook, etc.)")
if __name__ == "__main__":
print("\n" + "=" * 60)
print("Agent Email Chain - Examples")
print("=" * 60)
examples = [
("Basic Chain", example_basic_chain),
("Custom Handlers", example_custom_handlers),
("Manual Processing", example_manual_processing),
("Base64 Encoding", example_message_encoding),
("Recon Chain", example_recon_chain),
("History/Audit", example_workflow_with_history),
("Environment Setup", example_environment_setup),
]
print("\nAvailable examples:")
for i, (name, _) in enumerate(examples, 1):
print(f" {i}. {name}")
print("\n" + "=" * 60)
print("Running all examples...")
print("=" * 60)
for name, func in examples:
try:
func()
except Exception as e:
print(f"\nError in {name}: {e}")
print("\n" + "=" * 60)
print("All examples completed!")
print("=" * 60)

Xet Storage Details

Size:
9.17 kB
·
Xet hash:
3025d183128f0d24f4bf81e7ff61f12ae9bcfa15ea4f91f9a5b74829392dfd34

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