diff --git a/Universal_AI_Agent/.gitignore b/Universal_AI_Agent/.gitignore new file mode 100644 index 0000000..dc8e533 --- /dev/null +++ b/Universal_AI_Agent/.gitignore @@ -0,0 +1,55 @@ +# Dependencies +node_modules/ +npm-debug.log* +.npm/ +.yarn/ +.yarn-integrity + +# Production +/build +/dist + +# Logs +logs +*.log + +# Environment variables +.env +.env.local +.env.development.local +.env.test.local +.env.production.local + +# IDE and editor files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS generated files +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# Temporary files +tmp/ +temp/ +*.tmp + +# Cache +.cache/ +*.cache + +# Coverage +coverage/ +*.lcov + +# Build artifacts +*.min.js +*.min.css +*.map diff --git a/Universal_AI_Agent/docs/API_REFERENCE.md b/Universal_AI_Agent/docs/API_REFERENCE.md new file mode 100644 index 0000000..53a0295 --- /dev/null +++ b/Universal_AI_Agent/docs/API_REFERENCE.md @@ -0,0 +1,1003 @@ +# Universal AI Agent - API Reference + +## Table of Contents + +1. [Authentication](#authentication) +2. [Core Endpoints](#core-endpoints) +3. [AI Chat & Streaming](#ai-chat--streaming) +4. [RAG (Retrieval-Augmented Generation)](#rag-retrieval-augmented-generation) +5. [Multi-Agent Orchestration](#multi-agent-orchestration) +6. [Voice Integration](#voice-integration) +7. [Plugin System](#plugin-system) +8. [Analytics & Monitoring](#analytics--monitoring) +9. [WebSocket API](#websocket-api) +10. [Error Handling](#error-handling) +11. [Rate Limiting](#rate-limiting) +12. [SDK Examples](#sdk-examples) + +## Authentication + +### Bearer Token Authentication + +All API endpoints (except `/` and `/health`) require authentication when `AUTH_TOKEN` is configured. + +```http +Authorization: Bearer your_auth_token_here +``` + +### JWT Authentication + +For advanced authentication, use JWT tokens: + +```http +POST /auth/login +Content-Type: application/json + +{ + "email": "user@example.com", + "password": "secure_password", + "mfaCode": "123456" // Optional, if MFA is enabled +} +``` + +**Response:** + +```json +{ + "success": true, + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + "sessionId": "session_id_here", + "user": { + "id": "user_id", + "email": "user@example.com", + "roles": ["user"], + "mfaEnabled": false + } +} +``` + +## Core Endpoints + +### Health Check + +```http +GET /health +``` + +**Response:** + +```json +{ + "status": "healthy", + "uptime": 3600, + "memory": "512MB", + "connections": { + "redis": "connected", + "postgres": "connected" + }, + "features": { + "rag": true, + "voice": true, + "plugins": true, + "multiAgent": true + } +} +``` + +### System Information + +```http +GET /system/info +Authorization: Bearer your_token +``` + +**Response:** + +```json +{ + "version": "1.0.0", + "nodeVersion": "18.17.0", + "platform": "linux", + "architecture": "x64", + "environment": "production", + "features": ["rag", "voice", "plugins", "multi-agent"], + "limits": { + "maxRequestSize": "50MB", + "rateLimit": { + "window": 60000, + "max": 100 + } + } +} +``` + +## AI Chat & Streaming + +### Standard Chat + +```http +POST /chat +Authorization: Bearer your_token +Content-Type: application/json + +{ + "message": "Hello, how can you help me?", + "optimizePrompt": true, + "context": "optional context", + "userId": "user123" +} +``` + +**Response:** + +```json +{ + "response": "Hello! I'm your Universal AI Agent...", + "metadata": { + "model": "gpt-4", + "tokens": 150, + "responseTime": 1200, + "optimized": true + }, + "conversationId": "conv_123" +} +``` + +### Streaming Chat + +```http +GET /stream?message=Hello&optimizePrompt=true +Authorization: Bearer your_token +Accept: text/event-stream +``` + +**Server-Sent Events Response:** + + + +data: {"type": "start", "conversationId": "conv_123"} + +data: {"type": "chunk", "content": "Hello! I'm", "index": 0} + +data: {"type": "chunk", "content": " your Universal", "index": 1} + +data: {"type": "end", "metadata": {"tokens": 150, "model": "gpt-4"}} +``` + +### Conversation History + +```http +GET /conversations +Authorization: Bearer your_token +``` + +**Query Parameters:** + +- `limit`: Number of conversations (default: 50) +- `offset`: Pagination offset (default: 0) +- `userId`: Filter by user ID + +**Response:** + +```json +{ + "conversations": [ + { + "id": "conv_123", + "userId": "user123", + "messages": [ + { + "role": "user", + "content": "Hello", + "timestamp": "2024-01-01T12:00:00Z" + }, + { + "role": "assistant", + "content": "Hello! How can I help?", + "timestamp": "2024-01-01T12:00:01Z" + } + ], + "createdAt": "2024-01-01T12:00:00Z", + "updatedAt": "2024-01-01T12:00:01Z" + } + ], + "total": 1, + "hasMore": false +} +``` + +## RAG (Retrieval-Augmented Generation) + +### Ingest Documents + +```http +POST /rag/ingest +Authorization: Bearer your_token +Content-Type: application/json + +{ + "documents": [ + { + "id": "doc1", + "content": "This is a sample document content...", + "metadata": { + "title": "Sample Document", + "author": "John Doe", + "category": "technical" + } + } + ], + "collection": "knowledge_base" +} +``` + +**Response:** + +```json +{ + "success": true, + "ingested": 1, + "failed": 0, + "collection": "knowledge_base", + "processingTime": 1500 +} +``` + +### Search Documents + +```http +POST /rag/search +Authorization: Bearer your_token +Content-Type: application/json + +{ + "query": "machine learning algorithms", + "collection": "knowledge_base", + "limit": 5, + "threshold": 0.7 +} +``` + +**Response:** + +```json +{ + "results": [ + { + "id": "doc1", + "content": "Machine learning algorithms are...", + "score": 0.95, + "metadata": { + "title": "ML Guide", + "category": "technical" + } + } + ], + "query": "machine learning algorithms", + "totalResults": 1, + "searchTime": 50 +} +``` + +### RAG-Enhanced Answer + +```http +POST /rag/answer +Authorization: Bearer your_token +Content-Type: application/json + +{ + "question": "What are the best machine learning algorithms?", + "collection": "knowledge_base", + "maxContext": 3, + "includeContext": true +} +``` + +**Response:** + +```json +{ + "answer": "Based on the knowledge base, the best machine learning algorithms include...", + "sources": [ + { + "id": "doc1", + "title": "ML Guide", + "relevanceScore": 0.95 + } + ], + "context": [ + { + "content": "Machine learning algorithms are...", + "source": "doc1" + } + ], + "confidence": 0.92 +} +``` + +## Multi-Agent Orchestration + +### Execute Multi-Agent Task + +```http +POST /agents/execute +Authorization: Bearer your_token +Content-Type: application/json + +{ + "task": "Analyze the performance of our web application and suggest optimizations", + "agents": ["planner", "critic", "executor"], + "parallel": false, + "maxIterations": 3 +} +``` + +**Response:** + +```json +{ + "success": true, + "taskId": "task_123", + "results": [ + { + "agent": "planner", + "role": "Task Planner", + "response": "I'll break down the web app performance analysis into...", + "executionTime": 2000 + }, + { + "agent": "critic", + "role": "Critical Reviewer", + "response": "The analysis approach looks comprehensive, but consider...", + "executionTime": 1800 + }, + { + "agent": "executor", + "role": "Solution Executor", + "response": "Based on the plan and critique, here are the optimizations...", + "executionTime": 2200 + } + ], + "finalSynthesis": "Comprehensive analysis complete. Key recommendations: ...", + "totalExecutionTime": 6000, + "confidence": 0.89 +} +``` + +### Get Task Status + +```http +GET /agents/task/{taskId} +Authorization: Bearer your_token +``` + +**Response:** + +```json +{ + "taskId": "task_123", + "status": "completed", + "progress": 100, + "currentAgent": null, + "results": [...], + "startTime": "2024-01-01T12:00:00Z", + "endTime": "2024-01-01T12:00:06Z" +} +``` + +## Voice Integration + +### Text-to-Speech + +```http +POST /voice/tts +Authorization: Bearer your_token +Content-Type: application/json + +{ + "text": "Hello, this is your AI assistant speaking.", + "voice": "neural", + "language": "en-US", + "speed": 1.0, + "format": "mp3" +} +``` + +**Response:** + +```json +{ + "success": true, + "audioUrl": "/audio/tts_123.mp3", + "duration": 3.5, + "format": "mp3", + "size": 56789 +} +``` + +### Voice Command Processing + +```http +POST /voice/command +Authorization: Bearer your_token +Content-Type: application/json + +{ + "command": "analyze the latest sales data", + "context": "dashboard", + "userId": "user123" +} +``` + +**Response:** + +```json +{ + "success": true, + "command": "analyze the latest sales data", + "intent": "data_analysis", + "entities": ["sales data"], + "action": "execute_analysis", + "response": "I'll analyze the latest sales data for you...", + "audioResponse": "/audio/response_123.mp3" +} +``` + +### Autopilot Mode + +```http +POST /voice/autopilot +Authorization: Bearer your_token +Content-Type: application/json + +{ + "mode": "start", // "start", "stop", "status" + "context": "development", + "preferences": { + "verbosity": "medium", + "autoExecute": false + } +} +``` + +**Response:** + +```json +{ + "success": true, + "mode": "active", + "sessionId": "autopilot_123", + "status": "Autopilot mode activated. I'm ready to assist you.", + "capabilities": ["voice_commands", "proactive_suggestions", "context_awareness"] +} +``` + +## Plugin System + +### List Available Plugins + +```http +GET /plugins +Authorization: Bearer your_token +``` + +**Response:** + +```json +{ + "plugins": [ + { + "name": "web-scraper", + "version": "1.0.0", + "description": "Advanced web scraping and content extraction", + "category": "utility", + "status": "active", + "permissions": ["web_access"] + }, + { + "name": "database-analyzer", + "version": "1.0.0", + "description": "Database schema and performance analysis", + "category": "analysis", + "status": "active", + "permissions": ["database_access"] + } + ], + "total": 2 +} +``` + +### Execute Plugin + +```http +POST /plugins/{pluginName}/execute +Authorization: Bearer your_token +Content-Type: application/json + +{ + "action": "scrape", + "parameters": { + "url": "https://example.com", + "selector": ".content", + "format": "text" + } +} +``` + +**Response:** + +```json +{ + "success": true, + "plugin": "web-scraper", + "action": "scrape", + "result": { + "content": "Scraped content here...", + "metadata": { + "title": "Example Page", + "url": "https://example.com", + "scrapedAt": "2024-01-01T12:00:00Z" + } + }, + "executionTime": 2500 +} +``` + +### Install Plugin + +```http +POST /plugins/install +Authorization: Bearer your_token +Content-Type: application/json + +{ + "source": "npm", + "package": "@universal-ai/plugin-example", + "version": "1.0.0" +} +``` + +**Response:** + +```json +{ + "success": true, + "plugin": "example-plugin", + "version": "1.0.0", + "status": "installed", + "message": "Plugin installed successfully" +} +``` + +## Analytics & Monitoring + +### Get Dashboard Data + +```http +GET /analytics/dashboard +Authorization: Bearer your_token +``` + +**Response:** + +```json +{ + "overview": { + "uptime": 86400, + "totalRequests": 1500, + "successRate": "98.5", + "averageResponseTime": 850, + "activeUsers": 25, + "healthScore": 95 + }, + "requests": { + "total": 1500, + "successful": 1478, + "failed": 22, + "byHour": [10, 15, 20, ...], + "topEndpoints": [ + { + "endpoint": "POST /chat", + "requests": 800, + "averageTime": 1200, + "errorRate": 1.2 + } + ] + }, + "ai": { + "totalTokens": 150000, + "totalCost": 25.50, + "averageResponseTime": 1100, + "topModels": [ + { + "model": "gpt-4", + "requests": 600, + "tokens": 90000, + "cost": 18.00 + } + ] + } +} +``` + +### Get System Metrics + +```http +GET /analytics/metrics +Authorization: Bearer your_token +``` + +**Query Parameters:** + +- `timeRange`: `1h`, `24h`, `7d`, `30d` (default: `24h`) +- `metric`: `requests`, `performance`, `errors`, `users` + +**Response:** + +```json +{ + "timeRange": "24h", + "metrics": { + "requests": { + "timestamps": ["2024-01-01T00:00:00Z", ...], + "values": [10, 15, 20, ...] + }, + "responseTime": { + "timestamps": ["2024-01-01T00:00:00Z", ...], + "values": [850, 920, 780, ...] + } + } +} +``` + +### Export Analytics Data + +```http +GET /analytics/export +Authorization: Bearer your_token +``` + +**Query Parameters:** + +- `format`: `json`, `csv` (default: `json`) +- `timeRange`: `1h`, `24h`, `7d`, `30d` (default: `24h`) + +**Response:** File download with analytics data + +## WebSocket API + +### Connection + +```javascript +const ws = new WebSocket('wss://your-domain.com'); + +// Authenticate after connection +ws.onopen = () => { + ws.send(JSON.stringify({ + type: 'auth', + token: 'your_bearer_token' + })); +}; +``` + +### Message Types + +#### Authentication + +```json +{ + "type": "auth", + "token": "your_bearer_token" +} +``` + +#### Chat Streaming + +```json +{ + "type": "stream_chat", + "text": "Hello, how are you?", + "optimizePrompt": true, + "userId": "user123" +} +``` + +#### Voice Command + +```json +{ + "type": "voice_command", + "command": "analyze the data", + "context": "dashboard" +} +``` + +#### Plugin Execution + +```json +{ + "type": "plugin_execute", + "plugin": "web-scraper", + "action": "scrape", + "parameters": { + "url": "https://example.com" + } +} +``` + +### Server Messages + +#### Authentication Success + +```json +{ + "type": "auth_success", + "userId": "user123", + "sessionId": "session_456" +} +``` + +#### Chat Response + +```json +{ + "type": "chat_response", + "message": "Hello! How can I help you?", + "conversationId": "conv_123" +} +``` + +#### Stream Chunk + +```json +{ + "type": "stream_chunk", + "chunk": "Hello! I'm", + "index": 0, + "total": 10 +} +``` + +#### Error + +```json +{ + "type": "error", + "message": "Authentication failed", + "code": "AUTH_ERROR" +} +``` + +## Error Handling + +### Standard Error Response + +```json +{ + "error": true, + "message": "Detailed error message", + "code": "ERROR_CODE", + "timestamp": "2024-01-01T12:00:00Z", + "requestId": "req_123" +} +``` + +### Error Codes + +| Code | Description | HTTP Status | +|------|-------------|-------------| +| `AUTH_REQUIRED` | Authentication required | 401 | +| `AUTH_INVALID` | Invalid authentication token | 401 | +| `FORBIDDEN` | Insufficient permissions | 403 | +| `NOT_FOUND` | Resource not found | 404 | +| `RATE_LIMITED` | Rate limit exceeded | 429 | +| `VALIDATION_ERROR` | Request validation failed | 400 | +| `INTERNAL_ERROR` | Internal server error | 500 | +| `SERVICE_UNAVAILABLE` | External service unavailable | 503 | + +## Rate Limiting + +### Default Limits + +- **Window**: 60 seconds +- **Max Requests**: 100 per window per IP +- **Burst**: 10 requests per second + +### Rate Limit Headers + +```http +X-RateLimit-Limit: 100 +X-RateLimit-Remaining: 95 +X-RateLimit-Reset: 1704110400 +X-RateLimit-Window: 60 +``` + +### Rate Limit Exceeded Response + +```json +{ + "error": true, + "message": "Rate limit exceeded", + "code": "RATE_LIMITED", + "retryAfter": 45, + "limit": 100, + "window": 60 +} +``` + +## SDK Examples + +### JavaScript/Node.js + +```javascript +class UniversalAIClient { + constructor(baseUrl, token) { + this.baseUrl = baseUrl; + this.token = token; + } + + async chat(message, options = {}) { + const response = await fetch(`${this.baseUrl}/chat`, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.token}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + message, + ...options + }) + }); + + return response.json(); + } + + async streamChat(message, onChunk) { + const response = await fetch( + `${this.baseUrl}/stream?message=${encodeURIComponent(message)}`, + { + headers: { + 'Authorization': `Bearer ${this.token}`, + 'Accept': 'text/event-stream' + } + } + ); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = JSON.parse(line.slice(6)); + onChunk(data); + } + } + } + } +} + +// Usage +const client = new UniversalAIClient('https://your-domain.com', 'your_token'); + +// Standard chat +const response = await client.chat('Hello, how are you?'); +console.log(response.response); + +// Streaming chat +await client.streamChat('Tell me a story', (chunk) => { + if (chunk.type === 'chunk') { + process.stdout.write(chunk.content); + } +}); +``` + +### Python + +```python +import requests +import json +from typing import Optional, Dict, Any + +class UniversalAIClient: + def __init__(self, base_url: str, token: str): + self.base_url = base_url.rstrip('/') + self.token = token + self.session = requests.Session() + self.session.headers.update({ + 'Authorization': f'Bearer {token}', + 'Content-Type': 'application/json' + }) + + def chat(self, message: str, **kwargs) -> Dict[str, Any]: + """Send a chat message and get response""" + response = self.session.post( + f'{self.base_url}/chat', + json={'message': message, **kwargs} + ) + response.raise_for_status() + return response.json() + + def rag_ingest(self, documents: list, collection: str = 'default') -> Dict[str, Any]: + """Ingest documents into RAG system""" + response = self.session.post( + f'{self.base_url}/rag/ingest', + json={'documents': documents, 'collection': collection} + ) + response.raise_for_status() + return response.json() + + def rag_search(self, query: str, collection: str = 'default', limit: int = 5) -> Dict[str, Any]: + """Search documents in RAG system""" + response = self.session.post( + f'{self.base_url}/rag/search', + json={'query': query, 'collection': collection, 'limit': limit} + ) + response.raise_for_status() + return response.json() + + def execute_plugin(self, plugin_name: str, action: str, parameters: Dict[str, Any]) -> Dict[str, Any]: + """Execute a plugin action""" + response = self.session.post( + f'{self.base_url}/plugins/{plugin_name}/execute', + json={'action': action, 'parameters': parameters} + ) + response.raise_for_status() + return response.json() + +# Usage +client = UniversalAIClient('https://your-domain.com', 'your_token') + +# Chat +response = client.chat('Hello, how are you?') +print(response['response']) + +# RAG +documents = [ + { + 'id': 'doc1', + 'content': 'This is a sample document...', + 'metadata': {'title': 'Sample Doc'} + } +] +client.rag_ingest(documents) + +search_results = client.rag_search('sample document') +print(search_results['results']) +``` + +### cURL Examples + +```bash +# Chat +curl -X POST https://your-domain.com/chat \ + -H "Authorization: Bearer your_token" \ + -H "Content-Type: application/json" \ + -d '{"message": "Hello, how are you?"}' + +# RAG Search +curl -X POST https://your-domain.com/rag/search \ + -H "Authorization: Bearer your_token" \ + -H "Content-Type: application/json" \ + -d '{"query": "machine learning", "limit": 5}' + +# Plugin Execution +curl -X POST https://your-domain.com/plugins/web-scraper/execute \ + -H "Authorization: Bearer your_token" \ + -H "Content-Type: application/json" \ + -d '{"action": "scrape", "parameters": {"url": "https://example.com"}}' + +# Analytics +curl -X GET https://your-domain.com/analytics/dashboard \ + -H "Authorization: Bearer your_token" +``` + +For more examples and detailed integration guides, see the [Deployment Guide](DEPLOYMENT_GUIDE.md) and [Plugin Development Guide](PLUGIN_DEVELOPMENT.md). diff --git a/Universal_AI_Agent/docs/DEPLOYMENT_GUIDE.md b/Universal_AI_Agent/docs/DEPLOYMENT_GUIDE.md new file mode 100644 index 0000000..8a522ef --- /dev/null +++ b/Universal_AI_Agent/docs/DEPLOYMENT_GUIDE.md @@ -0,0 +1,644 @@ +# Universal AI Agent - Complete Deployment Guide + +## Table of Contents + +1. [Quick Start](#quick-start) +2. [Local Development](#local-development) +3. [Docker Deployment](#docker-deployment) +4. [Kubernetes Production Deployment](#kubernetes-production-deployment) +5. [Cloud Platform Deployment](#cloud-platform-deployment) +6. [Mobile App Setup](#mobile-app-setup) +7. [Monitoring and Analytics](#monitoring-and-analytics) +8. [Security Configuration](#security-configuration) +9. [Troubleshooting](#troubleshooting) + +## Quick Start + +### Prerequisites + +- Node.js 18+ +- Docker and Docker Compose +- Redis (optional, for caching) +- PostgreSQL (optional, for persistence) + +### 1-Minute Setup + +```bash +# Clone and setup +git clone +cd Universal_AI_Agent + +# Configure environment +cp .env.example .env +# Edit .env with your API keys + +# Start with Docker +docker-compose up -d + +# Access the application +open http://localhost:8787 +``` + +## Local Development + +### Environment Setup + +1. **Install Dependencies** + + ```bash + npm install + ``` + +2. **Configure Environment Variables** + + ```bash + # Copy example environment file + cp .env.example .env + + # Edit .env file with your configuration + nano .env + ``` + +3. **Required Environment Variables** + + ```env + # Core Configuration + PORT=8787 + NODE_ENV=development + + # AI Provider Keys + OPENAI_API_KEY=your_openai_key_here + ANTHROPIC_API_KEY=your_anthropic_key_here + + # Azure Speech (for voice features) + AZURE_SPEECH_KEY=your_azure_speech_key + AZURE_SPEECH_REGION=your_azure_region + + # Database URLs (optional) + REDIS_URL=redis://localhost:6379 + POSTGRES_URL=postgres://user:password@localhost:5432/agent + + # Security + AUTH_TOKEN=your_secure_bearer_token + JWT_SECRET=your_jwt_secret_key + + # Rate Limiting + RATE_LIMIT_WINDOW_MS=60000 + RATE_LIMIT_MAX=100 + + # Feature Flags + ALLOW_WEB_FETCH=true + ALLOW_GIT_INFO=true + ALLOW_FS_READ=true + ALLOW_POWERSHELL=false + LOG_JSON=true + ``` + +4. **Start Development Server** + + ```bash + npm run dev + ``` + +### Development Features + +- **Hot Reload**: Server automatically restarts on file changes +- **Debug Mode**: Detailed logging and error traces +- **Memory Persistence**: File-based memory for development +- **Plugin Development**: Hot-reload plugins without restart + +## Docker Deployment + +### Single Container + +```bash +# Build the image +docker build -t universal-ai-agent . + +# Run with environment file +docker run -d \ + --name ai-agent \ + --env-file .env \ + -p 8787:8787 \ + -v $(pwd)/memory:/app/memory \ + universal-ai-agent +``` + +### Full Stack with Docker Compose + +```bash +# Start all services +docker-compose up -d + +# View logs +docker-compose logs -f + +# Scale the application +docker-compose up -d --scale app=3 + +# Stop all services +docker-compose down +``` + +### Docker Compose Configuration + +```yaml +version: '3.8' +services: + app: + build: . + ports: + - "8787:8787" + environment: + - REDIS_URL=redis://redis:6379 + - POSTGRES_URL=postgres://postgres:postgres@postgres:5432/agent + depends_on: + - redis + - postgres + volumes: + - ./memory:/app/memory + - ./logs:/app/logs + + redis: + image: redis:7-alpine + ports: + - "6379:6379" + volumes: + - redis_data:/data + + postgres: + image: postgres:15-alpine + environment: + POSTGRES_DB: agent + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + +volumes: + redis_data: + postgres_data: +``` + +## Kubernetes Production Deployment + +### Prerequisites + +- Kubernetes cluster (1.20+) +- kubectl configured +- Ingress controller (nginx recommended) +- cert-manager for SSL certificates + +### 1. Create Namespace + +```bash +kubectl create namespace ai-agent +``` + +### 2. Create Secrets + +```bash +# AI API Keys +kubectl create secret generic ai-keys \ + --from-literal=openai-key=your_openai_key \ + --from-literal=anthropic-key=your_anthropic_key \ + --from-literal=azure-speech-key=your_azure_key \ + --from-literal=azure-speech-region=your_region \ + -n ai-agent + +# Database Connection +kubectl create secret generic postgres-secret \ + --from-literal=connection-string=postgres://user:pass@postgres:5432/agent \ + -n ai-agent + +# Authentication +kubectl create secret generic auth-secret \ + --from-literal=bearer-token=your_secure_token \ + --from-literal=jwt-secret=your_jwt_secret \ + -n ai-agent +``` + +### 3. Deploy Infrastructure + +```bash +# Deploy Redis +kubectl apply -f k8s/redis.yaml -n ai-agent + +# Deploy PostgreSQL +kubectl apply -f k8s/postgres.yaml -n ai-agent + +# Wait for databases to be ready +kubectl wait --for=condition=ready pod -l app=redis -n ai-agent --timeout=300s +kubectl wait --for=condition=ready pod -l app=postgres -n ai-agent --timeout=300s +``` + +### 4. Deploy Application + +```bash +# Deploy the main application +kubectl apply -f k8s/deployment.yaml -n ai-agent + +# Check deployment status +kubectl get pods -n ai-agent +kubectl logs -f deployment/universal-ai-agent -n ai-agent +``` + +### 5. Configure Ingress + +```bash +# Update the ingress with your domain +sed -i 's/ai-agent.yourdomain.com/your-actual-domain.com/g' k8s/deployment.yaml + +# Apply ingress configuration +kubectl apply -f k8s/deployment.yaml -n ai-agent + +# Check ingress status +kubectl get ingress -n ai-agent +``` + +### 6. Monitor Deployment + +```bash +# Check all resources +kubectl get all -n ai-agent + +# View application logs +kubectl logs -f deployment/universal-ai-agent -n ai-agent + +# Check horizontal pod autoscaler +kubectl get hpa -n ai-agent +``` + +## Cloud Platform Deployment + +### AWS EKS + +```bash +# Create EKS cluster +eksctl create cluster --name ai-agent-cluster --region us-west-2 + +# Configure kubectl +aws eks update-kubeconfig --region us-west-2 --name ai-agent-cluster + +# Deploy application +kubectl apply -f k8s/ -n ai-agent +``` + +### Google GKE + +```bash +# Create GKE cluster +gcloud container clusters create ai-agent-cluster \ + --zone us-central1-a \ + --num-nodes 3 + +# Get credentials +gcloud container clusters get-credentials ai-agent-cluster --zone us-central1-a + +# Deploy application +kubectl apply -f k8s/ -n ai-agent +``` + +### Azure AKS + +```bash +# Create resource group +az group create --name ai-agent-rg --location eastus + +# Create AKS cluster +az aks create \ + --resource-group ai-agent-rg \ + --name ai-agent-cluster \ + --node-count 3 \ + --enable-addons monitoring \ + --generate-ssh-keys + +# Get credentials +az aks get-credentials --resource-group ai-agent-rg --name ai-agent-cluster + +# Deploy application +kubectl apply -f k8s/ -n ai-agent +``` + +### Serverless Deployment + +#### Vercel + +```bash +# Install Vercel CLI +npm i -g vercel + +# Deploy +vercel --prod + +# Configure environment variables in Vercel dashboard +``` + +#### Netlify + +```bash +# Install Netlify CLI +npm i -g netlify-cli + +# Deploy +netlify deploy --prod --dir=. + +# Configure environment variables in Netlify dashboard +``` + +## Mobile App Setup + +### React Native Setup + +1. **Prerequisites** + + ```bash + # Install React Native CLI + npm install -g react-native-cli + + # For iOS development (macOS only) + sudo gem install cocoapods + + # For Android development + # Install Android Studio and configure SDK + ``` + +2. **Initialize Project** + + ```bash + # Create new React Native project + npx react-native init UniversalAIAgent + cd UniversalAIAgent + + # Copy the mobile app code + cp ../mobile/react-native-app.js App.js + + # Install dependencies + npm install @react-native-async-storage/async-storage + npm install @react-native-netinfo/netinfo + npm install @react-native-voice/voice + npm install expo-av + ``` + +3. **Configure API Endpoints** + + ```javascript + // Update API_BASE_URL in App.js + const API_BASE_URL = 'https://your-deployed-domain.com'; + const WS_URL = 'wss://your-deployed-domain.com'; + ``` + +4. **Build and Run** + + ```bash + # For iOS + npx react-native run-ios + + # For Android + npx react-native run-android + ``` + +### Flutter Alternative + +```bash +# Create Flutter project +flutter create universal_ai_agent +cd universal_ai_agent + +# Add dependencies to pubspec.yaml +flutter pub add http +flutter pub add web_socket_channel +flutter pub add shared_preferences +flutter pub add speech_to_text + +# Run the app +flutter run +``` + +## Monitoring and Analytics + +### Built-in Analytics Dashboard + +Access the analytics dashboard at: `https://your-domain.com/analytics` + +Features: + +- Real-time metrics +- Performance monitoring +- User analytics +- Cost tracking +- System health + +### External Monitoring + +#### Prometheus + Grafana + +```bash +# Deploy monitoring stack +kubectl apply -f monitoring/prometheus.yaml +kubectl apply -f monitoring/grafana.yaml + +# Access Grafana dashboard +kubectl port-forward svc/grafana 3000:3000 +``` + +#### DataDog Integration + +```javascript +// Add to server.js +import { StatsD } from 'node-statsd'; +const statsd = new StatsD(); + +// Track metrics +statsd.increment('requests.total'); +statsd.timing('response.time', responseTime); +``` + +## Security Configuration + +### SSL/TLS Setup + +#### Let's Encrypt with cert-manager + +```bash +# Install cert-manager +kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml + +# Create ClusterIssuer +kubectl apply -f k8s/cert-issuer.yaml +``` + +### Authentication Options + +#### JWT Authentication + +```env +AUTH_TOKEN=your_bearer_token +JWT_SECRET=your_jwt_secret_256_bit +``` + +#### OAuth Integration + +```env +GOOGLE_CLIENT_ID=your_google_client_id +GOOGLE_CLIENT_SECRET=your_google_client_secret +GITHUB_CLIENT_ID=your_github_client_id +GITHUB_CLIENT_SECRET=your_github_client_secret +``` + +### Security Best Practices + +1. **Environment Variables**: Never commit secrets to version control +2. **Rate Limiting**: Configure appropriate limits for your use case +3. **CORS**: Configure CORS for your domain +4. **Input Validation**: Enable strict input validation +5. **Monitoring**: Set up security monitoring and alerts + +## Troubleshooting + +### Common Issues + +#### 1. Application Won't Start + +```bash +# Check logs +docker-compose logs app + +# Common causes: +# - Missing environment variables +# - Database connection issues +# - Port conflicts +``` + +#### 2. Database Connection Errors + +```bash +# Test Redis connection +redis-cli -h localhost -p 6379 ping + +# Test PostgreSQL connection +psql -h localhost -p 5432 -U postgres -d agent +``` + +#### 3. High Memory Usage + +```bash +# Monitor memory usage +docker stats + +# Restart if needed +docker-compose restart app +``` + +#### 4. SSL Certificate Issues + +```bash +# Check certificate status +kubectl describe certificate ai-agent-tls -n ai-agent + +# Force certificate renewal +kubectl delete certificate ai-agent-tls -n ai-agent +kubectl apply -f k8s/deployment.yaml -n ai-agent +``` + +### Performance Optimization + +#### 1. Database Optimization + +```sql +-- Create indexes for better performance +CREATE INDEX idx_conversations_user_id ON conversations(user_id); +CREATE INDEX idx_conversations_timestamp ON conversations(timestamp); +CREATE INDEX idx_vector_embeddings ON documents USING ivfflat (embedding vector_cosine_ops); +``` + +#### 2. Caching Strategy + +```javascript +// Configure Redis caching +const cacheConfig = { + conversations: 3600, // 1 hour + embeddings: 86400, // 24 hours + responses: 1800 // 30 minutes +}; +``` + +#### 3. Load Balancing + +```yaml +# Update deployment for multiple replicas +spec: + replicas: 5 + strategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 2 + maxUnavailable: 1 +``` + +### Health Checks + +#### Application Health + +```bash +# Health check endpoint +curl https://your-domain.com/health + +# Expected response: +{ + "status": "healthy", + "uptime": 3600, + "memory": "512MB", + "connections": { + "redis": "connected", + "postgres": "connected" + } +} +``` + +#### Kubernetes Health + +```bash +# Check pod health +kubectl get pods -n ai-agent + +# Check service endpoints +kubectl get endpoints -n ai-agent + +# Check ingress status +kubectl describe ingress ai-agent-ingress -n ai-agent +``` + +## Support and Maintenance + +### Backup Strategy + +```bash +# Database backups +kubectl exec -it postgres-pod -- pg_dump -U postgres agent > backup.sql + +# Redis backup +kubectl exec -it redis-pod -- redis-cli BGSAVE +``` + +### Updates and Upgrades + +```bash +# Update application +docker build -t universal-ai-agent:v2.0.0 . +kubectl set image deployment/universal-ai-agent ai-agent=universal-ai-agent:v2.0.0 -n ai-agent + +# Monitor rollout +kubectl rollout status deployment/universal-ai-agent -n ai-agent +``` + +### Scaling Guidelines + +- **CPU**: Scale up when CPU usage > 70% +- **Memory**: Scale up when memory usage > 80% +- **Response Time**: Scale up when avg response time > 2 seconds +- **Queue Length**: Scale up when request queue > 100 + +For additional support, please refer to the [API Documentation](API_REFERENCE.md) and [Plugin Development Guide](PLUGIN_DEVELOPMENT.md). diff --git a/Universal_AI_Agent/netlify.toml b/Universal_AI_Agent/netlify.toml new file mode 100644 index 0000000..1103ea3 --- /dev/null +++ b/Universal_AI_Agent/netlify.toml @@ -0,0 +1,16 @@ +[build] + command = "npm run build" + publish = "/" + functions = "functions" + +[[redirects]] + from = "/*" + to = "/server.js" + status = 200 + +[dev] + command = "node server.js" + port = 3000 + targetPort = 3001 + publish = "/" + autoLaunch = true diff --git a/Universal_AI_Agent/server.js b/Universal_AI_Agent/server.js new file mode 100644 index 0000000..1dff4fe --- /dev/null +++ b/Universal_AI_Agent/server.js @@ -0,0 +1,915 @@ +// Universal AI Agent - zero-dependency Node server (Node 18+) +// Features: +// - POST /chat { message, role?, optimizePrompt?: boolean } +// - Lightweight prompt optimizer (heuristics) +// - File-backed memory (memory.json) +// - Optional LLM call via OPENAI_API_KEY or ANTHROPIC_API_KEY using global fetch +// - CORS for local use + +import { createServer } from 'node:http'; +import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import { ENV } from './config/env.js'; +import { optimizePrompt, respond } from './core/pipeline.js'; +import { exec } from 'node:child_process'; +import { initRedis, pushConversation } from './memory/redisStore.js'; +import { initPg, logConversation } from './storage/pgLogger.js'; +import { ingest as ragIngest, search as ragSearch, answer as ragAnswer } from './core/rag.js'; +import { runAgents } from './core/agents.js'; +import { continuousImprovement } from './core/continuous_improvement.js'; +import { voiceIntegration } from './core/voice_integration.js'; +import { pluginManager } from './core/plugin_system.js'; +import { websocketServer } from './core/websocket.js'; +import { advancedAuth } from './core/advanced_auth.js'; +import { analytics } from './core/analytics.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const PORT = Number(process.env.PORT || ENV.PORT || 8787); +const MEMORY_PATH = join(__dirname, 'memory.json'); + +function ensureMemory() { + try { + if (!existsSync(MEMORY_PATH)) { + writeFileSync(MEMORY_PATH, JSON.stringify({ conversations: [] }, null, 2)); + } + } catch (e) { + console.error('Failed to init memory:', e); + } +} + +function readMemory() { + try { + return JSON.parse(readFileSync(MEMORY_PATH, 'utf-8')); + } catch { + return { conversations: [] }; + } +} + +function writeMemory(data) { + try { + writeFileSync(MEMORY_PATH, JSON.stringify(data, null, 2)); + } catch (e) { + console.error('Failed to write memory:', e); + } +} + +function cors(res) { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); + res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); +} + +function sendJson(res, status, obj) { + const body = JSON.stringify(obj); + res.statusCode = status; + res.setHeader('content-type', 'application/json; charset=utf-8'); + res.setHeader('content-length', Buffer.byteLength(body)); + res.end(body); +} + +// --- Auth, Rate limiting, Logging helpers --- +function getIp(req) { + const xf = req.headers['x-forwarded-for']; + if (typeof xf === 'string' && xf.length) return xf.split(',')[0].trim(); + return req.socket?.remoteAddress || 'unknown'; +} + +function needsAuth(req) { + const url = req.url || ''; + if (req.method === 'GET' && (url === '/' || url.startsWith('/health'))) return false; + return !!ENV.AUTH_TOKEN; +} + +function checkAuth(req) { + if (!ENV.AUTH_TOKEN) return true; + try { + const h = req.headers['authorization'] || ''; + if (typeof h === 'string' && h.startsWith('Bearer ')) { + const token = h.slice('Bearer '.length).trim(); + if (token === ENV.AUTH_TOKEN) return true; + } + const u = new URL(req.url, `http://localhost:${PORT}`); + const qtok = u.searchParams.get('token'); + return qtok === ENV.AUTH_TOKEN; + } catch { + return false; + } +} + +const rlStore = new Map(); // ip -> { count, windowStart } +function rateLimited(ip) { + const now = Date.now(); + const winMs = ENV.RATE_LIMIT_WINDOW_MS; + const max = ENV.RATE_LIMIT_MAX; + const cur = rlStore.get(ip) || { count: 0, windowStart: now }; + if (now - cur.windowStart >= winMs) { + cur.windowStart = now; + cur.count = 0; + } + cur.count += 1; + rlStore.set(ip, cur); + return cur.count > max; +} + +function logReq(obj) { + try { + if (ENV.LOG_JSON) console.log(JSON.stringify(obj)); + else console.log(`[${obj.time}] ${obj.ip} ${obj.method} ${obj.url} -> ${obj.status} ${obj.ms}ms`); + } catch {} +} + +ensureMemory(); +// Initialize optional backends +initRedis().then(() => console.log('Redis: initialized (if REDIS_URL set)')).catch(()=>{}); +initPg().then(() => console.log('Postgres: initialized (if POSTGRES_URL set)')).catch(()=>{}); +// Initialize plugin system +pluginManager.loadAllPlugins().then(() => console.log('Plugins: initialized')).catch(()=>{}); +websocketServer.initialize(); + +// Initialize analytics tracking +analytics.on('alert', (alert) => { + console.log(`🚨 Analytics Alert [${alert.severity}]: ${alert.message}`); +}); + +// Initialize advanced authentication +console.log('🔐 Advanced authentication system initialized'); + +/** + * Handles incoming HTTP requests to the server. + * Applies CORS headers, middleware for continuous learning, and logs request details. + * Enforces authentication and rate limiting. + * Routes requests to various endpoints for chat, RAG, multi-agent, voice processing, plugin management, and system health. + * Responds with appropriate JSON or HTML content based on the endpoint. + */ +const server = createServer(async (req, res) => { + cors(res); + if (req.method === 'OPTIONS') return res.end(); + const start = Date.now(); + const ip = getIp(req); + + // Apply learning middleware for continuous improvement + continuousImprovement.learningMiddleware(req, res, () => {}); + + res.on('finish', () => { + logReq({ time: new Date().toISOString(), ip, method: req.method, url: req.url, status: res.statusCode, ms: Date.now() - start }); + }); + if (needsAuth(req) && !checkAuth(req)) { + return sendJson(res, 401, { error: 'unauthorized' }); + } + if (rateLimited(ip)) { + return sendJson(res, 429, { error: 'rate_limited' }); + } + + if (req.method === 'GET' && req.url === '/') { + res.setHeader('content-type', 'text/html; charset=utf-8'); + return res.end(` +Universal AI Agent + + +

🤖 Universal AI Agent

+
Auth Token (if configured):
+ +
+

System Health

+
Loading...
+ + +
+ +
+
+

💬 Chat

+
+ +
+ + +
+

+  
+
+

🧠 RAG

+
+
+
+
+
+
+

+  
+
+

🤝 Multi-agent

+
+
+

+  
+
+ +
+

🔧 Advanced Features

+
+
+

🛠️ Tools

+ + + +

+    
+
+

🎙️ Voice

+
+
+
+
+
+ + +
+
+
+
+
+

🔌 Plugins

+ + + + +

+  
+
+

📊 Advanced Analytics

+
+ + + +
+
+
+
+

🔐 Authentication

+
+ + + + +
+
+
+
+ + +`); + } + + if (req.method === 'GET' && req.url === '/health') { + return sendJson(res, 200, { status: 'ok', time: new Date().toISOString(), version: '0.1.1' }); + } + + if (req.method === 'GET' && req.url === '/memory') { + return sendJson(res, 200, readMemory()); + } + + // Safe web fetch tool: GET /tools/web?url=https://... + if (req.method === 'GET' && req.url?.startsWith('/tools/web')) { + try { + if (!ENV.ALLOW_WEB_FETCH) return sendJson(res, 403, { error: 'web_fetch_disabled' }); + const u = new URL(req.url, `http://localhost:${PORT}`); + const target = u.searchParams.get('url') || ''; + if (!/^https?:\/\//i.test(target)) return sendJson(res, 400, { error: 'invalid_url' }); + const r = await fetch(target, { method: 'GET' }); + const text = await r.text(); + const limited = text.slice(0, 10000); // 10KB cap + return sendJson(res, 200, { status: r.status, content: limited }); + } catch (e) { + console.error('tools/web error:', e.message); + return sendJson(res, 500, { error: 'fetch_failed' }); + } + } + + if (req.method === 'POST' && req.url === '/chat') { + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', async () => { + try { + const { message = '', role = 'user', optimizePrompt: doOpt = true } = JSON.parse(body || '{}'); + if (!message || typeof message !== 'string') return sendJson(res, 400, { error: 'message required' }); + + // Prompt optimization + const optimization = doOpt ? optimizePrompt(message) : null; + + // Compose messages with a system directive inspired by repo patterns + const messages = [ + { role: 'system', content: 'You are a rigorous, concise, planning-first coding agent. Provide short, high-quality answers with runnable snippets when requested. Always propose next actions.' }, + { role, content: message } + ]; + + // Respond via pipeline (OpenAI, Anthropic, or offline fallback) + const reply = await respond(messages); + + // Persist to memory + const mem = readMemory(); + mem.conversations.push({ + id: Date.now(), + ts: new Date().toISOString(), + role, + message, + reply, + optimization, + }); + writeMemory(mem); + + // Push to Redis (recent list) and log to Postgres (if configured) + try { await pushConversation({ ts: new Date().toISOString(), role, message, reply, optimization }); } catch {} + try { await logConversation({ ts: new Date().toISOString(), role, message, reply, optimization }); } catch {} + + return sendJson(res, 200, { reply, optimization }); + } catch (e) { + console.error('Chat error:', e); + return sendJson(res, 500, { error: 'internal_error' }); + } + }); + return; + } + + // SSE stream endpoint: GET /stream?message=... + if (req.method === 'GET' && req.url?.startsWith('/stream')) { + try { + const u = new URL(req.url, `http://localhost:${PORT}`); + const message = u.searchParams.get('message') || ''; + const role = 'user'; + if (!message) { + res.statusCode = 400; + return res.end('message required'); + } + const messages = [ + { role: 'system', content: 'You are a rigorous, concise, planning-first coding agent. Provide short, high-quality answers with runnable snippets when requested. Always propose next actions.' }, + { role, content: message } + ]; + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }); + (async () => { + const reply = await respond(messages); + // naive sentence chunking + const chunks = String(reply).split(/(?<=[.!?])\s+/); + for (const c of chunks) { + res.write(`data: ${c}\n\n`); + await new Promise(r => setTimeout(r, 80)); + } + res.write('event: done\n'); + res.write('data: end\n\n'); + res.end(); + })(); + return; + } catch (e) { + console.error('stream error:', e); + res.statusCode = 500; + return res.end('stream_error'); + } + } + + // Git info (read-only): GET /tools/git-info + if (req.method === 'GET' && req.url === '/tools/git-info') { + if (!ENV.ALLOW_GIT_INFO) return sendJson(res, 403, { error: 'git_info_disabled' }); + const run = (cmd) => new Promise((resolve) => { + const p = exec(cmd, { cwd: __dirname, timeout: 4000 }, (err, stdout, stderr) => { + resolve({ ok: !err, out: String(stdout||'').trim(), err: String(stderr||'').trim() }); + }); + p.on('error', () => resolve({ ok: false, out: '', err: 'spawn_error' })); + }); + const rev = await run('git rev-parse --short HEAD'); + const status = await run('git status --porcelain -uno'); + return sendJson(res, 200, { rev, status }); + } + + // Sandboxed FS read: GET /tools/fs-read?path=relative/path + if (req.method === 'GET' && req.url?.startsWith('/tools/fs-read')) { + if (!ENV.ALLOW_FS_READ) return sendJson(res, 403, { error: 'fs_read_disabled' }); + try { + const u = new URL(req.url, `http://localhost:${PORT}`); + const rel = u.searchParams.get('path') || ''; + if (!rel || rel.includes('..')) return sendJson(res, 400, { error: 'invalid_path' }); + const target = join(__dirname, rel); + if (!existsSync(target)) return sendJson(res, 404, { error: 'not_found' }); + const buf = readFileSync(target); + if (buf.length > 64 * 1024) return sendJson(res, 413, { error: 'file_too_large' }); + const content = buf.toString('utf-8'); + return sendJson(res, 200, { path: rel, size: buf.length, content }); + } catch (e) { + console.error('fs-read error:', e.message); + return sendJson(res, 500, { error: 'fs_read_failed' }); + } + } + + // Azure TTS: POST /voice/tts { text } + if (req.method === 'POST' && req.url === '/voice/tts') { + try { + if (!ENV.AZURE_SPEECH_KEY || !ENV.AZURE_SPEECH_REGION) { + res.statusCode = 501; return res.end('tts_not_configured'); + } + let body = ''; + req.on('data', c => body += c); + req.on('end', async () => { + const { text = '' } = JSON.parse(body || '{}'); + if (!text) { res.statusCode = 400; return res.end('text_required'); } + const ssml = `\n\n ${text}\n`; + const url = `https://${ENV.AZURE_SPEECH_REGION}.tts.speech.microsoft.com/cognitiveservices/v1`; + const r = await fetch(url, { + method: 'POST', + headers: { + 'Ocp-Apim-Subscription-Key': ENV.AZURE_SPEECH_KEY, + 'Content-Type': 'application/ssml+xml', + 'X-Microsoft-OutputFormat': 'audio-16khz-32kbitrate-mono-mp3', + }, + body: ssml, + }); + if (!r.ok) { res.statusCode = 502; return res.end('tts_failed'); } + const audio = Buffer.from(await r.arrayBuffer()); + res.writeHead(200, { 'Content-Type': 'audio/mpeg', 'Content-Length': audio.length }); + return res.end(audio); + }); + return; + } catch (e) { + console.error('tts error:', e.message); + res.statusCode = 500; return res.end('tts_error'); + } + } + + // System health endpoint + if (req.method === 'GET' && req.url === '/system/health') { + try { + const health = selfImprovement.getSystemHealth(); + return sendJson(res, 200, health); + } catch (e) { + console.error('Health check error:', e); + return sendJson(res, 500, { error: 'health_check_failed' }); + } + } + + // System optimization endpoint + if (req.method === 'POST' && req.url === '/system/optimize') { + try { + const optimization = await selfImprovement.autoOptimize(); + if (optimization) { + return sendJson(res, 200, optimization); + } else { + return sendJson(res, 200, { message: 'no_optimizations_needed', optimizations_applied: 0 }); + } + } catch (e) { + console.error('Optimization error:', e); + return sendJson(res, 500, { error: 'optimization_failed' }); + } + } + + // User feedback endpoint for continuous learning + if (req.method === 'POST' && req.url === '/system/feedback') { + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', () => { + try { + const { endpoint, rating, comment } = JSON.parse(body || '{}'); + if (!endpoint || !rating) return sendJson(res, 400, { error: 'endpoint and rating required' }); + + const context = { endpoint, timestamp: Date.now() }; + const outcome = { user_rating: rating }; + const userFeedback = { rating, comment }; + + selfImprovement.recordInteraction(context, 'user_feedback', outcome, userFeedback); + return sendJson(res, 200, { message: 'feedback_recorded' }); + } catch (e) { + console.error('Feedback error:', e); + return sendJson(res, 500, { error: 'feedback_failed' }); + } + }); + return; + } + + // Performance metrics endpoint + if (req.method === 'GET' && req.url === '/system/metrics') { + try { + const report = selfImprovement.metrics.getPerformanceReport(); + return sendJson(res, 200, report); + } catch (e) { + console.error('Metrics error:', e); + return sendJson(res, 500, { error: 'metrics_failed' }); + } + } + + // Optimization suggestions endpoint + if (req.method === 'GET' && req.url === '/system/suggestions') { + try { + const suggestions = await selfImprovement.getOptimizationSuggestions(); + return sendJson(res, 200, { suggestions }); + } catch (e) { + console.error('Suggestions error:', e); + return sendJson(res, 500, { error: 'suggestions_failed' }); + } + } + + // Voice command processing endpoint + if (req.method === 'POST' && req.url === '/voice/process') { + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', async () => { + try { + const { text, autopilot = false, responseMode = 'detailed' } = JSON.parse(body || '{}'); + if (!text) return sendJson(res, 400, { error: 'text required' }); + + // Set voice processor mode + voiceProcessor.autopilotMode = autopilot; + voiceProcessor.responseMode = responseMode; + + const result = await voiceProcessor.processVoiceInput(text); + return sendJson(res, 200, result); + } catch (e) { + console.error('Voice processing error:', e); + return sendJson(res, 500, { error: 'voice_processing_failed' }); + } + }); + return; + } + + // Plugin list endpoint + if (req.method === 'GET' && req.url === '/plugins/list') { + try { + const pluginList = pluginManager.getPluginList(); + return sendJson(res, 200, pluginList); + } catch (e) { + console.error('Plugin list error:', e); + return sendJson(res, 500, { error: 'plugin_list_failed' }); + } + } + + // Plugin execution endpoint + if (req.method === 'POST' && req.url === '/plugins/execute') { + let body = ''; + req.on('data', chunk => body += chunk); + req.on('end', async () => { + try { + const { plugin, context } = JSON.parse(body || '{}'); + if (!plugin) return sendJson(res, 400, { error: 'plugin name required' }); + + const result = await pluginManager.executePlugin(plugin, context || {}); + return sendJson(res, 200, result); + } catch (e) { + console.error('Plugin execution error:', e); + return sendJson(res, 500, { error: 'plugin_execution_failed', message: e.message }); + } + }); + return; + } + + // Plugin management endpoints + if (req.method === 'POST' && req.url?.startsWith('/plugins/')) { + const action = req.url.split('/')[2]; + const pluginName = req.url.split('/')[3]; + + try { + switch (action) { + case 'enable': + await pluginManager.enablePlugin(pluginName); + return sendJson(res, 200, { message: `Plugin ${pluginName} enabled` }); + case 'disable': + await pluginManager.disablePlugin(pluginName); + return sendJson(res, 200, { message: `Plugin ${pluginName} disabled` }); + default: + return sendJson(res, 400, { error: 'invalid_action' }); + } + } catch (e) { + console.error('Plugin management error:', e); + return sendJson(res, 500, { error: 'plugin_management_failed', message: e.message }); + } + } + + res.statusCode = 404; + res.end('Not found'); +}); + +server.listen(PORT, () => { + console.log(`Universal AI Agent listening on http://localhost:${PORT}`); +}); diff --git a/Universal_AI_Agent/windsurf_deployment.yaml b/Universal_AI_Agent/windsurf_deployment.yaml new file mode 100644 index 0000000..2eaebf9 --- /dev/null +++ b/Universal_AI_Agent/windsurf_deployment.yaml @@ -0,0 +1,6 @@ +# Windsurf Deploys Configuration (Beta) +# This is an auto-generated file used to store your app deployment configuration. Do not modify. +# The ID of the project (different from project name) on the provider's system. This is populated as a way to update existing deployments. +project_id: db2de7a8-0d70-4caf-a469-b9979278290d +# The framework of the web application (examples: nextjs, react, vue, etc.) +framework: node