Platform Architecture
HedgeAI is built as a modern, scalable web application using cutting-edge technologies to deliver AI-powered security automation. This document outlines the comprehensive system architecture, data flow, and integration patterns.
High-Level Architecture
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend │ │ Backend │ │ External │
│ (Next.js) │◄──►│ (API Routes) │◄──►│ Services │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ • React UI │ │ • OpenRouter │ │ • AI Models │
│ • TypeScript │ │ • API Handlers │ │ • Blockchain │
│ • Tailwind CSS │ │ • State Mgmt │ │ • File Storage │
│ • Framer Motion │ │ • Validation │ │ • CDN │
└─────────────────┘ └─────────────────┘ └─────────────────┘Technology Stack
Frontend Layer
Backend Layer
External Services
Core Components
1. AI Agent Workspace (AgentWorkspace.tsx)
The centerpiece of the platform, providing an integrated development environment for AI-powered security script generation.
Key Features:
- Responsive Layout: Adapts to different screen sizes
- Language Selection: Support for Python, JavaScript, Rust, YAML, Bash
- Real-time Chat: Direct communication with AI models
- Code Editor: Syntax highlighting and intelligent editing
interface AgentWorkspaceProps {
// Collapsible sidebar with chat interface
sidebarCollapsed: boolean;
// Active development environment
activeTab: "code" | "preview";
// Code state management
code: string;
language: SupportedLanguage;
// AI integration
chatHistory: ConversationMessage[];
}2. Chat Interface (ChatInterface.tsx)
Real-time communication system between users and AI models with streaming technology.
Message Flow:
User Input → Validation → AI Processing → Response → UI Update
↓ ↓ ↓ ↓ ↓
┌────────┐ ┌──────────┐ ┌─────────────┐ ┌─────────┐ ┌──────────┐
│ Input │ │ Zod │ │ OpenRouter │ │ Code │ │ React │
│ Field │ │ Schema │ │ API Call │ │ Extract │ │ Update │
└────────┘ └──────────┘ └─────────────┘ └─────────┘ └──────────┘Implementation Features:
- • Streaming Responses: Real-time AI output using Server-Sent Events
- • Context Preservation: Maintains conversation history
- • Error Handling: Graceful degradation on API failures
- • Rate Limiting: Built-in protection against API abuse
3. Code Editor (CodeEditor.tsx)
Advanced code editing environment powered by CodeMirror 6 with AI enhancements.
CodeMirror Configuration:
const editorConfig = {
extensions: [
javascript(), // Language support
python(),
rust(),
yaml(),
oneDark, // Theme
EditorView.theme({
'&': { height: '100%' },
'.cm-editor': { fontSize: '14px' },
'.cm-focused': { outline: 'none' }
})
],
value: code,
onChange: (value) => setCode(value)
}Editor Features:
- • Multi-Language Support
- • AI Integration
- • Auto-Completion
- • Error Detection
Language Support:
- • Python (Security automation)
- • JavaScript (Web security)
- • Rust (High-performance tools)
- • YAML (Configuration)
- • Bash (System administration)
Data Flow Architecture
AI Code Generation Flow
User Request → Chat Interface → API Route → OpenRouter → AI Model
↓
Response Processing ← Code Extraction ← JSON Response ← AI Response
↓
State Update → Editor Update → User InterfaceDetailed Steps:
1. Request Processing (/api/openrouter/vibe-coder/route.ts):
export async function POST(req: NextRequest) {
const { message, currentCode, conversationHistory } = await req.json()
// Build context with current code and history
const userMessage = currentCode
? `Current code:\n\n${currentCode}\n\nUser request: ${message}`
: message
// Send to AI model
const completion = await client.chat.completions.create({
model: 'qwen/qwen3-coder',
messages: [...conversationHistory, { role: 'user', content: userMessage }],
temperature: 0.3,
max_tokens: 8000,
})
}2. Code Extraction (/lib/utils/codeExtractor.ts):
export function extractCodeFromJson(response: string) {
try {
const parsed = JSON.parse(response)
return {
code: parsed.code || '',
message: parsed.message || 'Code generated successfully'
}
} catch (error) {
// Fallback extraction logic
return extractCodeFromMarkdown(response)
}
}State Management
Global State (Zustand)
Agent Store (/lib/store/agent.ts):
interface AgentState {
// Code editor state
code: string;
language: 'python' | 'javascript' | 'rust' | 'yaml' | 'bash';
// Chat state
messages: ConversationMessage[];
isLoading: boolean;
// Actions
setCode: (code: string) => void;
setLanguage: (language: SupportedLanguage) => void;
addMessage: (message: ConversationMessage) => void;
clearMessages: () => void;
}
export const useAgentStore = create<AgentState>((set) => ({
code: '',
language: 'python',
messages: [],
isLoading: false,
setCode: (code) => set({ code }),
setLanguage: (language) => set({ language }),
addMessage: (message) => set((state) => ({
messages: [...state.messages, message]
})),
clearMessages: () => set({ messages: [] })
}))Benefits:
- • Minimal Boilerplate: Simple store creation
- • TypeScript Native: Full type safety
- • DevTools Support: Browser extension integration
- • Middleware Support: Persistence, logging, etc.
Performance Optimizations
Frontend Performance
Code Splitting:
// Dynamic imports for heavy components
const CodeEditor = dynamic(() => import('./CodeEditor'), {
ssr: false,
loading: () => <LoadingSpinner />
})Image Optimization:
import Image from 'next/image'
<Image
src="/images/dashboard-preview.png"
alt="Platform Dashboard"
width={800}
height={600}
loading="lazy"
placeholder="blur"
/>API Performance
Response Streaming:
- • Real-time AI response chunks
- • Better user experience
- • Reduced perceived latency
Caching Strategy:
- • Static Assets: CDN caching with long TTL
- • API Responses: Short-term caching
- • Component State: localStorage backup
Security Architecture
API Security
- • Environment Variables: Secure API key management
- • Request Validation: Zod schemas
- • Rate Limiting: API abuse protection
- • Error Handling: Secure error messages
Content Security
- • Security-Focused Prompting
- • Input sanitization
- • Output validation
- • Secure code generation
Data Protection
- • No Sensitive Data Storage
- • HTTPS-only communication
- • Environment isolation
- • Session-based state only
Scalability Considerations
Horizontal Scaling
Stateless Architecture: All API routes are stateless, enabling easy horizontal scaling.
Database Preparation:
Architecture supports future database integration for:
- • User accounts and authentication
- • Conversation history persistence
- • Usage analytics and billing
- • Community features (ratings, reviews)
Vertical Scaling
Resource Optimization:
- • Efficient bundle splitting reduces initial load time
- • Lazy loading for non-critical components
- • Optimized API calls with request batching
- • Memory-efficient state management
Future Architecture Enhancements
1. Microservices Migration
Monolithic Next.js App → Microservices Architecture
↓
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Frontend │ │ AI Service │ │ Marketplace │
│ Service │ │ │ │ Service │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└───────────────┼───────────────┘
│
┌─────────────┐
│ API Gateway │
└─────────────┘2. Blockchain Integration
Smart Contract Architecture:
// HEDGE Token Contract (planned)
contract HEDGEToken is ERC20, Ownable {
uint256 public buybackPercentage = 90;
uint256 public burnPercentage = 80;
function buybackAndBurn() external {
// Revenue → Buyback → Burn mechanism
}
function distributeRevenue() external {
// Revenue sharing with token holders
}
}3. Enterprise Features
- Multi-tenant Architecture: Isolated environments for enterprise clients
- Advanced Authentication: SSO, SAML, LDAP integration
- Audit Logging: Comprehensive activity tracking
- Custom Deployment: On-premises and private cloud options
Architecture Summary
This architecture provides a solid foundation for HedgeAI's current capabilities while being designed to scale with future growth and feature expansion.