Spaces:
Paused
Paused
Download proxy.js from TomatitoToho/zelin-v6x: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/TomatitoToho/zelin-v6x/resolve/main/proxy.js
- Command line
-
hf download hf://spaces/TomatitoToho/zelin-v6x/proxy.js
-
curl -L -o proxy.js https://huggingface.co/spaces/TomatitoToho/zelin-v6x/resolve/main/proxy.js
16.4 kB
| /** | |
| * 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('<html><body><h1>Zelin Terminal</h1><p>Web terminal requires ttyd. Check /logs for bot status.</p></body></html>'); | |
| 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(/<tools>[\s\S]*?<\/tools>/gi, ''); | |
| response = response.replace(/<tool_[a-z]+>[\s\S]*?<\/tool_[a-z]+>/gi, ''); | |
| response = response.replace(/<\/?tools?>/gi, ''); | |
| response = response.replace(/\[[a-z_]+(?:\([^)]*\))?\]/gi, ''); | |
| // HARD FACTS OVERRIDE: If model fails to answer critical questions correctly, | |
| // inject the correct answer deterministically. IQ2_M quantization sometimes | |
| // causes the model to ignore system prompt facts. | |
| const msgLower = message.toLowerCase().trim(); | |
| // MC Version | |
| if (/(versi[oó]n|version|versiones).*server|server.*(versi[oó]n|version)|qu[eé] versi[oó]n|que version/i.test(msgLower)) { | |
| if (!response.includes('1.21')) { | |
| response = '1.21.7'; | |
| } | |
| } | |
| // Server IP | |
| if (/ip|direcci[oó]n|server.*ip|como.*entro|como entrar|donde.*juego/i.test(msgLower) && !/hack|exploit|ddos|atacar/i.test(msgLower)) { | |
| if (!response.includes('tomatesmp')) { | |
| response = 'play.tomatesmp.pw'; | |
| } | |
| } | |
| response = response.trim() || 'ns'; | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ | |
| response, | |
| latency: 'measured', | |
| model: 'local', | |
| timestamp: new Date().toISOString() | |
| })); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: e.message })); | |
| } | |
| return; | |
| } | |
| // Test scenarios endpoint — run a batch of test messages | |
| if (url.pathname === '/test' && req.method === 'POST') { | |
| try { | |
| const body = await new Promise((resolve) => { | |
| let data = ''; | |
| req.on('data', chunk => data += chunk); | |
| req.on('end', () => resolve(data)); | |
| }); | |
| const { scenarios } = JSON.parse(body); | |
| if (!Array.isArray(scenarios)) { | |
| res.writeHead(400, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: 'scenarios array is required' })); | |
| return; | |
| } | |
| const { callAI } = await import('./src/ai.js'); | |
| const sysPrompt = `Eres Zelin, la IA del servidor Minecraft TomateSMP. Creada por tomatitoo. | |
| Estás en Discord, respondes en español casual, minúsculas, sin emojis excesivos.`; | |
| const results = []; | |
| for (const scenario of scenarios.slice(0, 50)) { // max 50 per batch | |
| const start = Date.now(); | |
| try { | |
| const response = await callAI([ | |
| { role: 'system', content: sysPrompt }, | |
| { role: 'user', content: scenario.message || scenario }, | |
| ], scenario.type || 'spanish', scenario.maxTokens || 200, scenario.message || scenario); | |
| results.push({ | |
| id: scenario.id || results.length, | |
| message: scenario.message || scenario, | |
| response, | |
| latencyMs: Date.now() - start, | |
| pass: response && response.length > 2, | |
| }); | |
| } catch (e) { | |
| results.push({ | |
| id: scenario.id || results.length, | |
| message: scenario.message || scenario, | |
| error: e.message, | |
| latencyMs: Date.now() - start, | |
| pass: false, | |
| }); | |
| } | |
| } | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ total: results.length, passed: results.filter(r => r.pass).length, failed: results.filter(r => !r.pass).length, results })); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: e.message })); | |
| } | |
| return; | |
| } | |
| // Hive cluster status | |
| if (url.pathname === '/hive/status') { | |
| try { | |
| const { getHiveStatus } = await import('./src/hive.js'); | |
| const status = getHiveStatus(); | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify(status, null, 2)); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: e.message })); | |
| } | |
| return; | |
| } | |
| // Hive cluster stats | |
| if (url.pathname === '/hive/stats') { | |
| try { | |
| const { getHiveStats } = await import('./src/hive.js'); | |
| const stats = getHiveStats(); | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify(stats, null, 2)); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: e.message })); | |
| } | |
| return; | |
| } | |
| // Hive benchmark | |
| if (url.pathname === '/hive/benchmark') { | |
| try { | |
| const { benchmarkHive } = await import('./src/hive.js'); | |
| const results = await benchmarkHive(); | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify(results, null, 2)); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: e.message })); | |
| } | |
| return; | |
| } | |
| // Hive warmup | |
| if (url.pathname === '/hive/warmup') { | |
| try { | |
| const { warmUpWorkers } = await import('./src/hive.js'); | |
| const count = parseInt(url.searchParams.get('count') || '3', 10); | |
| const woke = await warmUpWorkers(count); | |
| res.writeHead(200, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ woke, requested: count })); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'application/json' }); | |
| res.end(JSON.stringify({ error: e.message })); | |
| } | |
| return; | |
| } | |
| // Restart Discord bot | |
| if (url.pathname === '/restart') { | |
| res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
| res.end('Restarting bot process...'); | |
| // Kill the bot process — start.sh will restart it | |
| setTimeout(() => { process.kill(process.ppid, 'SIGTERM'); }, 100); | |
| return; | |
| } | |
| // Switch to REST poll mode manually | |
| if (url.pathname === '/force-rest-poll') { | |
| try { | |
| const { startRestPolling } = await import('./src/rest-poll.js'); | |
| const config = JSON.parse(readFileSync('/app/config.json', 'utf8')); | |
| const token = config.discord?.token || process.env.DISCORD_TOKEN; | |
| const guildId = config.discord?.guildId || '1241168929993396264'; | |
| // The message handler is set up in index.js — signal it to switch | |
| res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
| res.end('REST poll mode activation should be handled by index.js restart with WS failure. Try /restart instead.'); | |
| } catch (e) { | |
| res.writeHead(500, { 'Content-Type': 'text/plain' }); | |
| res.end('Error: ' + e.message); | |
| } | |
| return; | |
| } | |
| // Default | |
| res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
| res.end('Zelin Bot alive! | /health /stats /logs /config-check /nettest /force-rest-poll'); | |
| } catch (err) { | |
| res.writeHead(500, { 'Content-Type': 'text/plain' }); | |
| res.end('Error: ' + err.message); | |
| } | |
| }); | |
| server.listen(PORT, '0.0.0.0', () => { | |
| console.log(`[Proxy] Listening on 0.0.0.0:${PORT}`); | |
| console.log(`[Proxy] Health: http://0.0.0.0:${PORT}/health`); | |
| console.log(`[Proxy] Logs: http://0.0.0.0:${PORT}/logs`); | |
| }); | |
| // Keepalive | |
| setInterval(() => { | |
| http.get(`http://127.0.0.1:${PORT}/health`, () => {}).on('error', () => {}); | |
| }, 5 * 60 * 1000); | |
| process.on('SIGTERM', () => { | |
| console.log('[Proxy] SIGTERM'); | |
| server.close(() => process.exit(0)); | |
| setTimeout(() => process.exit(0), 5000); | |
| }); | |