/** * proxy.js — Simple HTTP proxy + health check para HuggingFace Spaces * v9.5 — Hard facts override + tool leak fix * ============================================================ * NO uses http-proxy package (CJS/ESM issues) * Uses raw Node.js http for everything */ import http from 'node:http'; import { readFileSync, existsSync } from 'node:fs'; import { execSync } from 'node:child_process'; const PORT = parseInt(process.env.PORT || '7860', 10); const TTYD_PORT = 8081; let botStartTime = Date.now(); let requestCount = 0; const server = http.createServer(async (req, res) => { requestCount++; const url = new URL(req.url, `http://${req.headers.host}`); try { // Health check — verifies Discord bot is ACTUALLY alive (not just process) if (url.pathname === '/' || url.pathname === '/health') { const uptime = Math.floor((Date.now() - botStartTime) / 1000); const hours = Math.floor(uptime / 3600); const mins = Math.floor((uptime % 3600) / 60); const mem = process.memoryUsage(); // Check if Discord bot is actually connected let discordStatus = 'unknown'; let botTag = 'unknown'; let guildCount = 0; let lastHeartbeat = null; try { // Read watchdog health file const healthData = existsSync('/tmp/zelin-health.json') ? JSON.parse(readFileSync('/tmp/zelin-health.json', 'utf8')) : null; if (healthData) { lastHeartbeat = healthData.lastHeartbeat; const timeSinceHB = Date.now() - healthData.lastHeartbeat; if (timeSinceHB < 60_000) { discordStatus = 'connected'; } else if (timeSinceHB < 120_000) { discordStatus = 'degraded'; } else { discordStatus = 'disconnected'; } } } catch {} const isHealthy = discordStatus === 'connected'; res.writeHead(isHealthy ? 200 : 503, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: isHealthy ? 'alive' : 'unhealthy', discord: discordStatus, bot: 'Zelin v5.8', uptime: `${hours}h ${mins}m`, memory: `${(mem.rss/1024/1024).toFixed(0)}MB`, lastDiscordHeartbeat: lastHeartbeat ? new Date(lastHeartbeat).toISOString() : null, requests: requestCount, endpoints: '/health /stats /logs /config-check /nettest', })); return; } // Stats if (url.pathname === '/stats') { const mem = process.memoryUsage(); let pollStats = null; try { const { getRestPollStats } = await import('./src/rest-poll.js'); pollStats = getRestPollStats(); } catch {} res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'running', uptime: Math.floor((Date.now() - botStartTime) / 1000), memory: { rss: `${(mem.rss / 1024 / 1024).toFixed(1)}MB`, heapUsed: `${(mem.heapUsed / 1024 / 1024).toFixed(1)}MB`, }, requests: requestCount, restPoll: pollStats, })); return; } // Logs endpoint if (url.pathname === '/logs') { try { const logs = execSync('tail -200 /tmp/zelin-bot.log 2>/dev/null || echo "No logs yet"').toString(); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(logs); } catch (e) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Logs not available: ' + e.message); } return; } // Config check (masks secrets) if (url.pathname === '/config-check') { try { const config = JSON.parse(readFileSync('/app/config.json', 'utf8')); const mask = (obj) => { for (const key in obj) { if (typeof obj[key] === 'string' && obj[key].length > 8 && /key|token|secret|password|apiKey|sk/i.test(key)) { obj[key] = obj[key].substring(0, 4) + '...' + obj[key].substring(obj[key].length - 4); } else if (typeof obj[key] === 'object' && obj[key] !== null) { mask(obj[key]); } } }; const masked = JSON.parse(JSON.stringify(config)); mask(masked); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(masked, null, 2)); } catch (e) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Config error: ' + e.message); } return; } // Terminal path - simple redirect info if (url.pathname === '/terminal') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('
Web terminal requires ttyd. Check /logs for bot status.
'); return; } // Network diagnostic if (url.pathname === '/nettest') { const targets = [ { name: 'Discord Gateway (discord.com)', url: 'https://discord.com/api/v10/gateway' }, { name: 'Discord API v10 (discordapp.com)', url: 'https://discordapp.com/api/v10/gateway' }, { name: 'Discord API no version (discordapp.com)', url: 'https://discordapp.com/api/gateway' }, { name: 'Discord API v9 (discordapp.com)', url: 'https://discordapp.com/api/v9/gateway' }, { name: 'Gateway.discord.gg', url: 'https://gateway.discord.gg' }, { name: 'Groq', url: 'https://api.groq.com/openai/v1/models' }, { name: 'HuggingFace', url: 'https://router.huggingface.co/v1/models' }, { name: 'Google', url: 'https://www.google.com' }, ]; const results = {}; for (const t of targets) { const start = Date.now(); try { const r = await fetch(t.url, { signal: AbortSignal.timeout(10000) }); const body = await r.text().catch(() => ''); results[t.name] = { status: r.status, ms: Date.now() - start, ok: true, body: body.substring(0, 200) }; } catch (e) { results[t.name] = { error: e.message?.substring(0, 100), ms: Date.now() - start, ok: false }; } } // Test Discord API with bot token try { const config = JSON.parse(readFileSync('/app/config.json', 'utf8')); const token = config.discord?.token || process.env.DISCORD_TOKEN; if (token) { // Test with discordapp.com const r1 = await fetch('https://discordapp.com/api/v10/gateway/bot', { headers: { 'Authorization': `Bot ${token}` }, signal: AbortSignal.timeout(10000), }); const b1 = await r1.text().catch(() => ''); results['Discordapp Bot Gateway v10'] = { status: r1.status, ok: r1.ok, body: b1.substring(0, 300) }; } } catch (e) { results['Discordapp Bot Gateway v10'] = { error: e.message?.substring(0, 150), ok: false }; } res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(results, null, 2)); return; } // Test chat endpoint — send a message to Zelin and get response if (url.pathname === '/chat' && req.method === 'POST') { try { const body = await new Promise((resolve) => { let data = ''; req.on('data', chunk => data += chunk); req.on('end', () => resolve(data)); }); const { message, userId } = JSON.parse(body); if (!message) { res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'message is required' })); return; } // Use the AI router + proper prompt + humanizer const { callAI } = await import('./src/ai.js'); const { humanize } = await import('./src/humanizer.js'); const { buildSystemPrompt } = await import('./src/prompt.js'); const { readConfig: readCfg } = await import('./src/utils.js'); const cfg = readCfg(); // Build proper system prompt with all the style rules and few-shot examples const sysPrompt = buildSystemPrompt({ currentTime: new Date().toLocaleTimeString('es-MX'), isOwnerMessage: userId === cfg.admin?.userId, }); const rawResponse = await callAI([ { role: 'system', content: sysPrompt }, { role: 'user', content: message }, ], 'spanish', 200, message, userId === cfg.admin?.userId); // Apply humanizer to strip AI patterns let response = humanize(rawResponse); // Safety net: strip any remaining tool call XML that escaped post-processing response = response.replace(/