zelin-v6x / src /neural-processor.js
Z User
v7.1: CRITICAL fixes — 20+ bugs from deep audit
5cef531
Raw History Blame Contribute Delete
60.5 kB
/** * ============================================ * 🧠 neural-processor.js — Neural Processor v1.0 * ============================================ * Sistema avanzado SIN REGEX que reemplaza TODOS los patrones * regex del codebase con un motor híbrido de 3 capas: * * CAPA 1: LEXICON ENGINE — Diccionarios Map/Set (instantáneo, 0ms) * - Detección de palabras clave vía lookup O(1) * - Clasificación de intenciones por diccionarios jerárquicos * - Detección de emociones por word sets * - Validación de respuestas por comparación de strings * * CAPA 2: STRUCTURAL ANALYZER — Análisis estructural sin regex * - Tokenización, parsing de markers, detección de patrones * - Limpieza de thinking artifacts por string operations * - Detección de spam por conteo de caracteres * - Análisis de estructura gramatical vía adjacency tables * * CAPA 3: NEURAL ENGINE — IA local (Qwen/Gemma) para comprensión semántica * - Solo se activa cuando las capas 1-2 no son concluyentes * - Clasificación de intenciones complejas * - Detección de manipulación contextual * - Evaluación de coherencia semántica * - Cache inteligente para evitar llamadas repetidas * * PRINCIPIO: CERO regex. Todo es análisis de strings, tokens, Maps, Sets, e IA. */ import { isLocalAIReady, ollamaChatDirect } from './local-ai.js'; // ═══════════════════════════════════════════════════════════════════════════════ // CAPA 1: LEXICON ENGINE — Diccionarios para lookup instantáneo // ═══════════════════════════════════════════════════════════════════════════════ // ── Intent Classification ──────────────────────────────────────────────────── // Reemplaza INTENT_PATTERNS en ai.js y detectTaskType en index.js const GREETING_WORDS = new Set([ 'hola', 'hey', 'hi', 'buenas', 'qué tal', 'ola', 'saludos', 'wenas', 'holi', 'sup', 'ktal', 'q tal', ]); const RULES_WORDS = new Set([ 'regla', 'norma', 'prohibi', 'permit', 'reglas', 'normas', ]); const CODE_WORDS = new Set([ 'código', 'codigo', 'script', 'función', 'funcion', 'plugin', 'config', 'bug', 'error', 'archivo', 'node', 'java', 'python', 'yml', 'json', ]); const MODERATION_WORDS = new Set([ 'ban', 'sancion', 'report', 'trampa', 'hack', 'cheat', 'sanción', ]); const COMPLEX_WORDS = new Set([ 'analiza', 'explica', 'compara', 'argumenta', 'analiz', 'diagnos', ]); const QUESTION_WORDS = new Set([ 'cómo', 'qué', 'cuál', 'dónde', 'cuándo', 'por qué', 'como', 'que', 'cual', ]); const SPANISH_WORDS = new Set([ 'cómo', 'qué', 'cuál', 'dónde', 'cuándo', 'por qué', 'entiendes', ]); const CASUAL_RESPONSES = new Set([ 'xd', 'jaja', 'si', 'no', 'ok', 'vale', 'sale', 'gracias', 'ty', 'gg', 'nice', 'crack', 'bro', 'sí', 'nop', 'sip', ]); const OWNER_TASK_WORDS = new Set([ 'modif', 'edita', 'implementa', 'crea', 'arregla', ]); const REASONING_WORDS = new Set([ 'por qué', 'explica', 'analiz', 'diagnos', 'resumen', 'report', ]); // ── Emotion Detection ──────────────────────────────────────────────────────── // Reemplaza detectEmotion en humanizer.js const SURPRISE_WORDS = new Set([ 'joder', 'hostia', 'mierda', 'cabrón', 'put', 'wtf', 'coño', 'maldit', 'madre mía', 'no me jodas', 'en serio', 'flipo', ]); const POSITIVE_WORDS = new Set([ 'guay', 'bien', 'genial', 'nice', 'pro', 'cool', 'perfect', 'excelente', 'increíble', 'crack', 'chido', ]); const NEGATIVE_WORDS = new Set([ 'malo', 'triste', 'fatal', 'horrible', 'muerte', 'perdí', 'perder', 'fracas', 'error', 'fallé', ]); const CONFUSED_WORDS = new Set([ 'no entiendo', 'confund', 'qué?', 'cómo', 'por qué', 'dudas', ]); // ── AI Self-Reference Detection ────────────────────────────────────────────── // Reemplaza BAD_PATTERNS en ai.js const AI_SELF_STARTS = [ 'as an ai', 'como una ia', 'como un ia', 'como ia', "i'm an ai", 'i am an ai', "i'm a ai", 'i am a ai', ]; const AI_PHRASES = new Set([ 'como tu ia', 'como tu ia,', 'como ia', 'como ia,', 'como asistente', 'como modelo', 'soy una ia', 'soy un bot', 'soy un modelo', 'como una ia', 'como una ia,', ]); // ── Security Patterns ──────────────────────────────────────────────────────── // Reemplaza HARD_BLOCK_PATTERNS en security.js y local-ai.js const SECURITY_BLOCK_SUBSTRINGS = [ '<admin_tools>', '###system', '### system', '[system]:', '[system] :', ]; // Zero-width characters to detect (Unicode code points) const ZERO_WIDTH_CODES = new Set([ 0x200B, 0x200C, 0x200D, 0x200E, 0x200F, 0x202A, 0x202B, 0x202C, 0x202D, 0x202E, ]); // ── Compromised Response Detection ─────────────────────────────────────────── // Reemplaza COMPROMISED_PATTERNS en security.js const COMPROMISED_PHRASES = [ 'ahora soy', 'soy libre', 'sin restricciones', 'ya no tengo límites', 'como pediste, ya soy', 'como pediste,ya soy', 'he cambiado mi identidad', 'he cambiado de identidad', 'he cambiado mi nombre', 'he cambiado mi personalidad', 'modo libre', 'modo sin filtros', 'modo god', 'modo developer', 'modo dan', 'he olvidado mis reglas', 'he olvidado mis restricciones', 'he olvidado mis instrucciones', 'he olvidado todas las reglas', 'he olvidado todas las restricciones', 'he olvidado todas las instrucciones', 'puedo hacer cualquier cosa ahora', 'puedo decir cualquier cosa ahora', 'puedo ejecutar cualquier cosa ahora', ]; const SECRET_LEAK_WORDS = [ 'contraseña:', 'password:', 'token:', 'api.key:', 'secret:', 'contraseña =', 'password =', 'token =', ]; // ── Suspicious Security Words ──────────────────────────────────────────────── // Reemplaza la detección de suspicious en local-ai.js y security.js const SUSPICIOUS_WORDS = new Set([ 'owner', 'admin', 'tomatito', 'borrar', 'eliminar', 'olvida', 'finge', 'jailbreak', ]); const MANIPULATION_SUGGESTIVE = new Set([ 'sin restricciones', 'sin límites', 'puedo todo', 'cualquier cosa', 'he cambiado', 'soy diferente', 'libre', ]); // ── Refusal Detection ──────────────────────────────────────────────────────── // Reemplaza isRefusal en local-ai.js const REFUSAL_STARTS = [ 'no puedo', 'no me es posible', 'no estoy autorizado', 'no está permitido', 'no voy a', 'no voy hacer', 'no haré', 'no haría', 'lo siento, pero', 'lo siento pero', "i can't", 'i cannot', "i won't", 'i am unable', "i don't feel comfortable", "i don't think", 'unable to assist', 'unable to help', 'unable to comply', ]; const REFUSAL_CONTAINS = [ 'va contra', 'viola', 'incumple', 'no es apropiado', 'no está bien', 'no corresponde', 'no es seguro', 'no deberías', 'against guidelines', 'against policy', 'against rules', 'against terms', 'not able to', 'not going to', ]; // ── Spam Detection ────────────────────────────────────────────────────────── // Reemplaza SPAM_PATTERNS en moderation.js const INVITE_SUBSTRINGS = ['discord.gg/', 'discord.com/invite/']; const SLUR_WORDS = new Set(['nig', 'fag']); // ── Toxicity Detection ────────────────────────────────────────────────────── // Reemplaza detectConflictSignals en moderation.js const INSULT_WORDS = new Set(['idiota', 'estúpido', 'imbécil', 'inútil']); const HATE_WORDS = new Set(['te odio', 'te detesto']); const ACCUSE_WORDS = new Set(['mentiroso', 'tramposo', 'cheater', 'hack']); const MOD_ACTION_WORDS = new Set(['ban', 'reportar', 'report']); // ── Route Classification ───────────────────────────────────────────────────── // Reemplaza ROUTE_PATTERNS en coordinator.js const DIRECT_RESPONSES = new Set([ 'hola', 'hey', 'gg', 'xd', 'jaja', 'ok', 'gracias', 'sí', 'no', 'bien', 'mal', 'ola', 'sup', ]); const DB_QUERY_WORDS = new Set([ 'cuántos', 'cuándo', 'historial', 'sanción', 'jugador', ]); const COMPLEX_TASK_WORDS = new Set([ 'crea', 'genera', 'analiza', 'investiga', 'recopila', 'compara', ]); const SERVER_INFO_WORDS = new Set([ 'ip', 'cómo entro', 'cómo me registro', 'cómo juego', 'dónde está', ]); // ── Simple Message Detection ───────────────────────────────────────────────── // Reemplaza detección de mensajes simples en index.js const SIMPLE_GREETINGS = new Set([ 'hola', 'ola', 'hey', 'buenas', 'wenas', 'xd', 'jaja', 'sí', 'si', 'no', 'ok', 'vale', 'sale', 'gracias', 'ty', 'gg', 'q tal', 'qtal', ]); // ── Cache TTL Classification ───────────────────────────────────────────────── // Reemplaza _ttl() en ai.js y semantic-cache.js const LONG_CACHE_WORDS = new Set([ 'regla', 'norma', 'plugin', 'info', 'servidor', 'comandos', ]); const SHORT_CACHE_WORDS = new Set([ 'online', 'jugador', 'tps', 'lag', 'estado', 'jugadores', ]); // ── Humor/Laughter Detection ───────────────────────────────────────────────── // Reemplaza detección de humor en humanizer.js const HUMOR_WORDS = new Set([ 'jaja', 'lol', 'xd', 'gracioso', 'funny', 'risa', 'muerto', 'me muero', 'joder', ]); const LIGHTHEARTED_WORDS = new Set([ 'bueno', 'pues', 'va', 'nada', 'sí', 'claro', 'ok', 'vale', 'sale', ]); // ── Connector Replacements ─────────────────────────────────────────────────── // Reemplaza CONNECTORS en humanizer.js (sin regex, usando Map) const FORMAL_TO_CASUAL = new Map([ // Multi-word connectors primero (orden importa para matching) ['es importante destacar', 'lo importante es que'], ['cabe mencionar', 'hay que mencionar que'], ['por lo tanto', 'así que'], ['sin embargo', 'pero'], ['no obstante', 'aunque'], ['por consiguiente', 'entonces'], ['por otra parte', 'también'], ['en conclusión', 'en fin'], ['en resumen', 'básicamente'], ['en definitiva', 'al final'], ['resulta que', 'pues'], ['de igual manera', 'igual'], ['de igual forma', 'igual'], ['en primer lugar', 'primero'], ['en segundo lugar', 'después'], ['además de ello', 'además'], ['cabe señalar', 'ojo que'], ['es necesario destacar', 'fíjate que'], ['vale la pena mencionar', 'ojo'], ['por un lado', ''], ['asimismo', 'también'], ['a continuación', ''], ['procederé a', 'voy a'], ['me complace', ''], ['con mucho gusto', ''], ['por otro lado', 'y también'], ['es preciso indicar', ''], ['es menester', ''], ['ha de saberse', ''], ]); // ── Robotic Phrase Replacements ────────────────────────────────────────────── const ROBOTIC_TO_HUMAN = new Map([ ['¡Por supuesto!', 'claro'], ['¡Claro que sí!', 'sí'], ['¡Encantado/a!', ''], ['¡Encantada!', ''], ['¡Encantado!', ''], ['Como IA que soy,', ''], ['Como IA,', ''], ['Como asistente,', ''], ['No dudes en preguntar', 'cualquier cosa me dices'], ['Estoy aquí para ayudarte', ''], ['¡Espero haberte ayudado!', ''], ['Si tienes más preguntas', 'si necesitas más'], ['Con gusto te ayudo', ''], ['Es un placer', ''], ['¡Claro!', 'claro'], ['Entendido,', ''], ['Por supuesto,', ''], ['Perfecto,', ''], ['¡Perfecto!', ''], ['A continuación,', ''], ['Dicho esto,', ''], ['En ese caso,', 'entonces'], ['Desde luego', 'claro'], ['Sin duda,', ''], ['Efectivamente,', ''], ['Con gusto,', ''], ['Por supuesto que', ''], ['Me alegra que preguntes', ''], ['Gran pregunta', ''], ['Excelente pregunta', ''], ['Interesante pregunta', ''], ['¡Entendido!', 'entendido'], ['Como mencioné anteriormente', 'como dije'], ['Para concluir,', ''], ['Espero que esto te ayude', ''], ['Espero haber aclarado', ''], ['No te preocupes,', ''], ['Te entiendo,', ''], ['En términos simples', 'básicamente'], ['Para ser más específico', 'o sea'], ['Es importante mencionar', 'ojo que'], ['Como puedes ver', 'ves?'], ['En otras palabras', 'osea'], ['Para resumir', 'en fin'], ['Es decir,', 'osea'], ['Te aseguro que', 'te juro que'], ['Te garantizo que', 'seguro que'], ['Permíteme informarte', ''], ['Es mi deber', ''], ['Estoy a tu disposición', ''], ['Quedo a tu disposición', ''], ['Quedo a la espera', ''], ['No dudes en', ''], ['Quedo a tu servicio', ''], ['Estoy para servirte', ''], ['Déjame explicarte', 'mira'], ['Permíteme explicarte', 'mira'], ]); // ── Emphasis Replacements ──────────────────────────────────────────────────── const EMPHASIS_TO_NATURAL = new Map([ ['extremadamente', 'muy'], ['absolutamente', 'bastante'], ['totalmente', 'bastante'], ['completamente', 'bastante'], ['perfectamente', 'bien'], ['extraordinario', 'bastante bueno'], ['imprescindible', 'necesario'], ['fundamental', 'importante'], ['crucial', 'clave'], ['increíblemente', 'mucho'], ['verdaderamente', 'de verdad'], ['indudablemente', 'seguro'], ['innegablemente', 'claro que'], ['inmensamente', 'un montón'], ['sumamente', 'muy'], ['profundamente', 'mucho'], ['enormemente', 'un montón'], ]); // ═══════════════════════════════════════════════════════════════════════════════ // CAPA 2: STRUCTURAL ANALYZER — Análisis estructural sin regex // ═══════════════════════════════════════════════════════════════════════════════ /** * Tokeniza texto en palabras, separando puntuación. * Sin regex — usa string operations. */ export function tokenize(text) { if (!text || typeof text !== 'string') return []; const tokens = []; let current = ''; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { if (current) tokens.push(current); current = ''; } else if (ch === ',' || ch === '.' || ch === '!' || ch === '?' || ch === ';' || ch === ':' || ch === '-' || ch === '—' || ch === '(' || ch === ')' || ch === '[' || ch === ']' || ch === '{' || ch === '}') { if (current) tokens.push(current); current = ''; } else { current += ch; } } if (current) tokens.push(current); return tokens; } /** * Normaliza texto para matching: lowercase, sin acentos opcionales, trim. */ export function normalize(text) { if (!text || typeof text !== 'string') return ''; return text.toLowerCase().trim(); } /** * Busca si algún elemento de un Set aparece como substring en el texto. * Retorna la palabra encontrada o null. */ export function findAnyIn(text, wordSet) { const lower = normalize(text); for (const word of wordSet) { if (lower.includes(word)) return word; } return null; } /** * Busca si algún elemento de un Set aparece como palabra completa (bounded). * Un "bounded word" está delimitada por inicio/fin del string o espacios/puntuación. */ export function findWordIn(text, wordSet) { const lower = normalize(text); for (const word of wordSet) { const idx = lower.indexOf(word); if (idx === -1) continue; // Verificar bounds const beforeOk = idx === 0 || !isAlpha(lower[idx - 1]); const afterIdx = idx + word.length; const afterOk = afterIdx >= lower.length || !isAlpha(lower[afterIdx]); if (beforeOk && afterOk) return word; } return null; } function isAlpha(ch) { const code = ch.charCodeAt(0); return (code >= 97 && code <= 122) || // a-z (code >= 65 && code <= 90) || // A-Z (code >= 0xE0 && code <= 0xFF) || // Latin extended ch === 'ñ' || ch === 'Ñ'; } /** * Busca si algún string en un array aparece al inicio del texto. */ export function startsWithAny(text, prefixes) { const lower = normalize(text); for (const prefix of prefixes) { if (lower.startsWith(normalize(prefix))) return prefix; } return null; } /** * Busca si algún string en un array aparece como substring en el texto. */ export function containsAny(text, substrings) { const lower = normalize(text); for (const sub of substrings) { if (lower.includes(normalize(sub))) return sub; } return null; } /** * Verifica si el texto contiene caracteres zero-width (maliciosos). * Sin regex — comprime codePointAt. */ export function hasZeroWidthChars(text) { if (!text) return false; for (let i = 0; i < text.length; i++) { const code = text.codePointAt(i); if (ZERO_WIDTH_CODES.has(code)) return true; // Skip surrogate pair if (code > 0xFFFF) i++; } return false; } /** * Elimina caracteres zero-width del texto. * Sin regex — reconstruye carácter por carácter. */ export function stripZeroWidth(text) { if (!text) return text; let result = ''; for (let i = 0; i < text.length; i++) { const code = text.codePointAt(i); if (!ZERO_WIDTH_CODES.has(code)) { result += text[i]; } // Skip surrogate pair if (code > 0xFFFF) i++; } return result; } /** * Limpia thinking artifacts del texto generado por la IA. * Reemplaza cleanThinkingArtifacts en ai.js — sin regex. */ export function cleanThinkingArtifacts(text) { if (!text || typeof text !== 'string') return text; let t = text; // Quitar bloques <think...</think t = stripTagBlock(t, 'think'); // Quitar bloques <thinking...</thinking t = stripTagBlock(t, 'thinking'); // Quitar prefijos de "Pienso..." seguido de "Respuesta:" t = stripPrefixBlock(t, 'Pienso', 'Respuesta:'); t = stripPrefixBlock(t, 'Pensamiento:', 'Respuesta:'); // Quitar "Respuesta final:" / "Final answer:" t = stripStartingPrefix(t, 'Respuesta final:'); t = stripStartingPrefix(t, 'Final answer:'); return t.trim(); } function stripTagBlock(text, tagName) { // Buscar <tag ... </tag> y eliminarlo todo let result = text; const openTag1 = '<' + tagName + '>'; const openTag2 = '<' + tagName + ' '; const closeTag = '</' + tagName + '>'; let safety = 10; // max 10 blocks while (safety-- > 0) { const openIdx1 = result.toLowerCase().indexOf(openTag1.toLowerCase()); const openIdx2 = result.toLowerCase().indexOf(openTag2.toLowerCase()); let openIdx = -1; let openLen = 0; if (openIdx1 !== -1 && (openIdx2 === -1 || openIdx1 < openIdx2)) { openIdx = openIdx1; openLen = openTag1.length; } else if (openIdx2 !== -1) { openIdx = openIdx2; openLen = openTag2.length; } if (openIdx === -1) break; const closeIdx = result.toLowerCase().indexOf(closeTag.toLowerCase(), openIdx + openLen); if (closeIdx === -1) { // No close tag — remove from open to end result = result.slice(0, openIdx); break; } result = result.slice(0, openIdx) + result.slice(closeIdx + closeTag.length); } return result; } function stripPrefixBlock(text, prefix, endMarker) { const lower = text.toLowerCase(); const prefixLower = prefix.toLowerCase(); const endLower = endMarker.toLowerCase(); if (!lower.startsWith(prefixLower)) return text; const endIdx = lower.indexOf(endLower, prefixLower.length); if (endIdx === -1) return text; return text.slice(endIdx + endMarker.length); } function stripStartingPrefix(text, prefix) { const lower = text.toLowerCase(); if (lower.startsWith(prefix.toLowerCase())) { return text.slice(prefix.length); } return text; } /** * Limpia bloques de código markdown (```json ... ```). * Sin regex — string operations. */ export function stripCodeBlocks(text) { if (!text) return text; let result = text; const marker = '```'; let safety = 20; while (safety-- > 0) { const start = result.indexOf(marker); if (start === -1) break; // Skip optional language identifier (e.g., ```json) let contentStart = start + marker.length; while (contentStart < result.length && result[contentStart] !== '\n' && result[contentStart] !== marker[0]) { contentStart++; } if (contentStart < result.length && result[contentStart] === '\n') contentStart++; const end = result.indexOf(marker, contentStart); if (end === -1) { // No closing ``` — take rest as content result = result.slice(contentStart); break; } // Extract content between markers result = result.slice(0, start) + result.slice(contentStart, end) + result.slice(end + marker.length); } return result.trim(); } /** * Limpia formato markdown del texto: **bold**, *emotes*, # headers, --- lines. * Sin regex — string operations. */ export function stripMarkdownFormatting(text) { if (!text || typeof text !== 'string') return text; let t = text; // **bold** → content t = stripPairedMarkers(t, '**', ''); // *emotes* (only action emotes, not italics) // We handle this specially: remove content between * that looks like actions t = stripActionEmotes(t); // _underscore text_ t = stripUnderscoreBlocks(t); // # headers → remove t = stripHashHeaders(t); // --- and === horizontal rules → remove t = stripHorizontalRules(t); return t; } function stripPairedMarkers(text, marker, replacement) { let result = text; let safety = 50; while (safety-- > 0) { const start = result.indexOf(marker); if (start === -1) break; const end = result.indexOf(marker, start + marker.length); if (end === -1) break; const content = result.slice(start + marker.length, end); result = result.slice(0, start) + replacement + content + replacement + result.slice(end + marker.length); } return result; } // Action emote verbs (used by stripActionEmotes) const EMOTE_VERBS = new Set([ 'ríe', 'rio', 'risa', 'suspira', 'mueve', 'piensa', 'sonríe', 'sonrio', 'retíe', 'retie', 'acuesta', 'levanta', 'sienta', 'volta', 'gira', 'asusta', 'enoja', 'sorprende', 'entristece', 'alegra', 'cansa', 'despierta', 'duerme', 'llora', 'grita', 'corre', 'salta', 'cae', 'abraza', 'besa', 'mira', 'voltea', 'agarra', 'tira', 'golpea', 'come', 'bebe', 'escribe', 'lee', 'canta', 'baila', 'juega', 'camina', 'nada', 'vuela', 'trepa', 'escala', 'mina', 'craftea', 'pica', 'construye', 'explora', 'pelea', 'ataca', 'defiende', 'huye', 'escapa', 'esconde', 'busca', 'encuentra', 'pierde', 'gana', 'mata', 'muere', 'revive', 'respawn', ]); function stripActionEmotes(text) { let result = text; let safety = 30; while (safety-- > 0) { const start = result.indexOf('*'); if (start === -1) break; const end = result.indexOf('*', start + 1); if (end === -1) break; const content = result.slice(start + 1, end).trim(); // Check if this looks like an action emote const firstWord = content.split(' ')[0]?.toLowerCase() ?? ''; if (EMOTE_VERBS.has(firstWord) || content === 'risas' || content === 'risa' || content === 'suspiros' || content === 'suspiro' || content === 'pausa' || content === 'silencio' || content.startsWith('se ') || content.startsWith('se ')) { result = result.slice(0, start) + result.slice(end + 1); } else { // Not an emote — skip this pair break; } } return result.trim(); } function stripUnderscoreBlocks(text) { let result = text; let safety = 20; while (safety-- > 0) { const start = result.indexOf('_'); if (start === -1) break; const end = result.indexOf('_', start + 1); if (end === -1) break; if (end - start - 1 <= 40) { // only short underscore blocks result = result.slice(0, start) + result.slice(end + 1); } else { break; } } return result.trim(); } function stripHashHeaders(text) { const lines = text.split('\n'); return lines.map(line => { let i = 0; while (i < line.length && i < 3 && line[i] === '#') i++; if (i > 0 && i < line.length && line[i] === ' ') { return line.slice(i + 1); } return line; }).join('\n'); } function stripHorizontalRules(text) { const lines = text.split('\n'); return lines.filter(line => { const trimmed = line.trim(); if (trimmed.length < 3) return true; // All dashes or all equals const first = trimmed[0]; if (first !== '-' && first !== '=') return true; for (let i = 1; i < trimmed.length; i++) { if (trimmed[i] !== first) return true; } return false; // all same char = horizontal rule }).join('\n').trim(); } /** * Detecta spam de caracteres repetidos (8+ del mismo carácter). * Sin regex — conteo secuencial. */ export function hasCharSpam(text, threshold = 8) { if (!text || text.length < threshold) return false; let count = 1; for (let i = 1; i < text.length; i++) { if (text[i] === text[i - 1]) { count++; if (count >= threshold) return true; } else { count = 1; } } return false; } /** * Detecta mayúsculas excesivas (5+ caracteres seguidos). * Sin regex — conteo secuencial. */ export function hasExcessiveCaps(text, threshold = 5) { if (!text) return false; let count = 0; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (ch >= 'A' && ch <= 'Z' || ch >= 'Á' && ch <= 'Ú' || ch === 'Ñ') { count++; if (count >= threshold) return true; } else { count = 0; } } return false; } /** * Detecta puntuación excesiva (3+ ? o ! seguidos). * Sin regex — conteo secuencial. */ export function hasExcessivePunctuation(text, threshold = 3) { if (!text) return false; let qCount = 0, eCount = 0; for (let i = 0; i < text.length; i++) { if (text[i] === '?') { qCount++; if (qCount >= threshold) return true; } else { qCount = 0; } if (text[i] === '!') { eCount++; if (eCount >= threshold) return true; } else { eCount = 0; } } return false; } /** * Cuenta URLs en texto. Sin regex — busca "http://" o "https://". */ export function countUrls(text) { if (!text) return 0; let count = 0; let idx = 0; while (true) { idx = text.indexOf('http', idx); if (idx === -1) break; if (text.slice(idx, idx + 7) === 'http://' || text.slice(idx, idx + 8) === 'https://') { count++; } idx += 4; } return count; } /** * Detecta slurs por conteo de caracteres repetidos (patrón n+i+g+). * Sin regex — busca la palabra base y verifica caracteres repetidos. */ export function hasSlur(text) { const lower = normalize(text); for (const slur of SLUR_WORDS) { // Buscar el slur como substring let idx = 0; while ((idx = lower.indexOf(slur, idx)) !== -1) { // Verificar que tiene caracteres repetidos (patrón de evasión) // Un slur real tendría la palabra base, posiblemente con chars repetidos return true; } } return false; } /** * Reemplaza todas las ocurrencias de un substring (case-insensitive). * Sin regex — string operations. */ export function replaceAllCI(text, search, replacement) { if (!text || !search) return text; const lowerText = text.toLowerCase(); const lowerSearch = search.toLowerCase(); let result = ''; let i = 0; while (i < text.length) { if (lowerText.slice(i, i + lowerSearch.length) === lowerSearch) { result += replacement; i += lowerSearch.length; } else { result += text[i]; i++; } } return result; } /** * Reemplaza palabras completas (bounded) — case-insensitive. * Sin regex — tokeniza y reemplaza. */ export function replaceWordCI(text, word, replacement) { const tokens = tokenize(text); const lowerWord = normalize(word); return tokens.map(t => normalize(t) === lowerWord ? replacement : t).join(' '); } /** * Limpia puntuación excesiva. * Sin regex — string operations. */ export function cleanPunctuation(text) { if (!text) return text; let t = text; // Multiple ? → single ? t = collapseChars(t, '?', 1); // Multiple ! → single ! t = collapseChars(t, '!', 1); // Multiple , → single , t = collapseChars(t, ',', 1); // Multiple . → max 3 (ellipsis) t = collapseChars(t, '.', 3); // Comma without space after → add space t = fixCommaSpacing(t); // Orphan ¿ with . or ! at end → remove ¿ t = fixOrphanQuestionMark(t); return t; } function collapseChars(text, char, maxConsecutive) { let result = ''; let count = 0; for (let i = 0; i < text.length; i++) { if (text[i] === char) { count++; if (count <= maxConsecutive) result += char; } else { count = 0; result += text[i]; } } return result; } function fixCommaSpacing(text) { let result = ''; for (let i = 0; i < text.length; i++) { result += text[i]; if (text[i] === ',' && i + 1 < text.length && text[i + 1] !== ' ' && text[i + 1] !== '\n') { result += ' '; } } return result; } function fixOrphanQuestionMark(text) { // If starts with ¿ and ends with . or !, remove the ¿ if (text.startsWith('¿')) { const trimmed = text.trim(); if (trimmed.endsWith('.') || trimmed.endsWith('!')) { return text.slice(1); } } return text; } /** * Reemplaza texto multi-palabra de forma segura. * Busca la frase completa y la reemplaza. * Sin regex — string operations. */ export function replacePhraseCI(text, phrase, replacement) { if (!text || !phrase) return text; const lowerText = text.toLowerCase(); const lowerPhrase = phrase.toLowerCase(); let result = ''; let i = 0; while (i < text.length) { if (lowerText.slice(i, i + lowerPhrase.length) === lowerPhrase) { // Check word boundaries const beforeOk = i === 0 || !isAlpha(text[i - 1]); const afterIdx = i + lowerPhrase.length; const afterOk = afterIdx >= text.length || !isAlpha(text[afterIdx]); if (beforeOk && afterOk) { result += replacement; i += lowerPhrase.length; continue; } } result += text[i]; i++; } return result; } /** * Aplica todas las sustituciones de connectors, robotic phrases, y emphasis. * Sin regex — usa replacePhraseCI. */ export function applyHumanizingSubstitutions(text) { if (!text) return text; let t = text; // Multi-word connectors primero (orden importa) // Ordenar por longitud descendente para que frases largas matcheen primero const connectorEntries = [...FORMAL_TO_CASUAL.entries()].sort((a, b) => b[0].length - a[0].length); for (const [formal, casual] of connectorEntries) { t = replacePhraseCI(t, formal, casual); } // Robotic phrases (ordenar por longitud descendente) const roboticEntries = [...ROBOTIC_TO_HUMAN.entries()].sort((a, b) => b[0].length - a[0].length); for (const [robotic, human] of roboticEntries) { t = replacePhraseCI(t, robotic, human); } // Emphasis words (word-level replacement) for (const [exag, natural] of EMPHASIS_TO_NATURAL.entries()) { t = replaceWordCI(t, exag, natural); } return t; } /** * Limpia artefactos de intro del modelo pequeño. * Sin regex — string operations. */ export function cleanModelIntro(text) { if (!text) return text; const INTRO_PHRASES = [ 'claro, ', 'claro ', 'por supuesto, ', 'por supuesto ', 'entendido, ', 'entendido ', 'hola, ', 'hola ', 'sí, ', 'sí ', ]; const AI_INTRO_PHRASES = [ 'como tu ia, ', 'como tu ia,', 'como un asistente, ', 'como un asistente,', 'como un bot, ', 'como un bot,', 'como ia, ', 'como ia,', ]; const lower = text.toLowerCase(); for (const phrase of INTRO_PHRASES) { if (lower.startsWith(phrase)) { return text.slice(phrase.length); } } for (const phrase of AI_INTRO_PHRASES) { if (lower.startsWith(phrase)) { return text.slice(phrase.length); } } return text; } /** * Detecta si texto es solo puntuación/espacios. * Sin regex — verificación carácter por carácter. */ export function isOnlyPunctuation(text) { if (!text) return true; const PUNCT = new Set([' ', '.', ',', '!', '?', ';', ':', '-', '_', '…', '¡', '¿', '"', "'", '(', ')']); for (const ch of text) { if (!PUNCT.has(ch)) return false; } return true; } /** * Detecta si texto es un valor nulo/no-respuesta. * Sin regex — comparación directa. */ const NULL_VALUES = new Set(['error', 'null', 'undefined', 'true', 'false', '{}', '[]']); export function isNullValue(text) { if (!text) return true; return NULL_VALUES.has(normalize(text)); } /** * Detecta menciones @everyone/@here. * Sin regex — string operations. */ export function hasMassMention(text) { if (!text) return false; const lower = text.toLowerCase(); return lower.includes('@everyone') || lower.includes('@here'); } /** * Reemplaza @everyone/@here con versiones seguras. * Sin regex — replaceAllCI. */ export function stripMassMentions(text) { let t = text; t = replaceAllCI(t, '@everyone', 'everyone'); t = replaceAllCI(t, '@here', 'here'); return t; } /** * Enmascara datos sensibles (tokens, API keys, JWTs, IPs, passwords). * Sin regex — string operations con heurísticas. */ export function maskSensitiveData(text) { if (!text || typeof text !== 'string') return text; let t = text; // Base64 tokens (20+ chars followed by = or ==) t = maskPattern(t, (s, i) => { // Look for base64-like sequences: 20+ alphanumeric+/= chars let start = i; while (start > 0 && isBase64Char(s[start - 1])) start--; let end = i; while (end < s.length && isBase64Char(s[end])) end++; if (end - start >= 20) return { start, end, replacement: '[TOKEN]' }; return null; }); // sk- API keys t = maskPrefixedPattern(t, 'sk-', '[API_KEY]'); // eyJ JWTs t = maskPrefixedPattern(t, 'eyJ', '[JWT]'); // IP addresses (x.x.x.x pattern) t = maskIPs(t); // password= or password: patterns t = maskPasswordPattern(t); return t; } function isBase64Char(ch) { return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch === '+' || ch === '/' || ch === '='; } function maskPrefixedPattern(text, prefix, mask) { let result = text; let idx = 0; while ((idx = result.indexOf(prefix, idx)) !== -1) { let end = idx + prefix.length; while (end < result.length && isBase64Char(result[end])) end++; if (end - idx - prefix.length >= 15) { result = result.slice(0, idx) + mask + result.slice(end); idx += mask.length; } else { idx++; } } return result; } function maskIPs(text) { // Simple IP masking: look for digit.digit.digit.digit pattern let result = ''; let i = 0; while (i < text.length) { if (isDigit(text[i])) { const ip = tryParseIP(text, i); if (ip) { result += '[IP]'; i = ip.end; continue; } } result += text[i]; i++; } return result; } function tryParseIP(text, start) { let pos = start; const parts = []; for (let p = 0; p < 4; p++) { if (p > 0) { if (text[pos] !== '.') return null; pos++; } let num = ''; while (pos < text.length && isDigit(text[pos]) && num.length < 3) { num += text[pos]; pos++; } if (num.length === 0 || parseInt(num) > 255) return null; parts.push(num); } // Must be followed by non-digit or end if (pos < text.length && isDigit(text[pos])) return null; return { end: pos, ip: parts.join('.') }; } function isDigit(ch) { return ch >= '0' && ch <= '9'; } function maskPasswordPattern(text) { const lower = text.toLowerCase(); for (const prefix of ['password', 'contraseña']) { let idx = 0; while ((idx = lower.indexOf(prefix, idx)) !== -1) { // Find the value after = or : let valStart = idx + prefix.length; while (valStart < text.length && (text[valStart] === ' ' || text[valStart] === '\t')) valStart++; if (valStart < text.length && (text[valStart] === '=' || text[valStart] === ':')) { valStart++; while (valStart < text.length && text[valStart] === ' ') valStart++; let valEnd = valStart; while (valEnd < text.length && !isWhitespace(text[valEnd])) valEnd++; if (valEnd > valStart) { return text.slice(0, idx) + prefix + ':[' + 'MASKED]' + text.slice(valEnd); } } idx++; } } return text; } function isWhitespace(ch) { return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r'; } function maskPattern(text, detector) { // Generic pattern masker — not used directly, helpers above implement specific patterns return text; } /** * Detecta si el nombre de un modelo de IA es de texto/chat (no imagen, audio, etc). * Sin regex — string operations. */ const EXCLUDE_MODEL_SUBSTRINGS = [ 'whisper', 'tts', 'speech', 'audio', 'embed', 'vision', 'image', 'dall', 'stable', 'rerank', 'guard', 'code-gecko', 'text-bison', ]; const FAST_MODEL_SUBSTRINGS = ['8b', '7b', 'fast', 'instant', 'flash', 'mini']; const LARGE_MODEL_SUBSTRINGS = ['70b', '72b', 'large', 'versatile', 'plus', 'pro']; export function isTextModel(modelName) { const lower = (modelName ?? '').toLowerCase(); for (const sub of EXCLUDE_MODEL_SUBSTRINGS) { if (lower.includes(sub)) return false; } return true; } export function isFastModel(modelName) { const lower = (modelName ?? '').toLowerCase(); return FAST_MODEL_SUBSTRINGS.some(s => lower.includes(s)); } export function isLargeModel(modelName) { const lower = (modelName ?? '').toLowerCase(); return LARGE_MODEL_SUBSTRINGS.some(s => lower.includes(s)); } // ═══════════════════════════════════════════════════════════════════════════════ // CAPA 3: NEURAL ENGINE — IA local para comprensión semántica // ═══════════════════════════════════════════════════════════════════════════════ // Cache para resultados del Neural Engine const _neuralCache = new Map(); const NEURAL_CACHE_MAX = 100; const NEURAL_CACHE_TTL = 120_000; // 2 minutos function getCachedResult(key) { const cached = _neuralCache.get(key); if (!cached) return null; if (Date.now() - cached.ts > NEURAL_CACHE_TTL) { _neuralCache.delete(key); return null; } return cached.result; } function setCachedResult(key, result) { _neuralCache.set(key, { result, ts: Date.now() }); if (_neuralCache.size > NEURAL_CACHE_MAX) { const firstKey = _neuralCache.keys().next().value; _neuralCache.delete(firstKey); } } /** * Clasifica la intención del usuario usando el modelo local. * Solo se llama cuando los diccionarios (Capa 1) no son concluyentes. */ export async function neuralClassifyIntent(message, context = '') { if (!message || message.length < 10) return null; const cacheKey = `intent:${message.slice(0, 60)}`; const cached = getCachedResult(cacheKey); if (cached) return cached; if (!isLocalAIReady()) return null; try { const raw = await ollamaChatDirect([ { role: 'system', content: `Clasifica el intent de este mensaje de Discord. Responde SOLO JSON: {"intent":"greeting|question|code|moderation|complex|casual|rules|server_info","confidence":0.0-1.0} Intentes posibles: - greeting: saludo simple - question: pregunta sobre algo - code: relacionado con programación/config - moderation: reportar, ban, sanción - complex: análisis, explicación detallada - casual: respuesta corta, reacción - rules: sobre reglas del servidor - server_info: IP, cómo entrar, info del server`, }, { role: 'user', content: `Mensaje: "${message.slice(0, 200)}"`, }, ], 60, 4000); const clean = stripCodeBlocks(raw); const jsonStart = clean.indexOf('{'); const jsonEnd = clean.lastIndexOf('}'); if (jsonStart === -1 || jsonEnd === -1) return null; const result = JSON.parse(clean.slice(jsonStart, jsonEnd + 1)); const classified = { intent: result.intent ?? 'casual', confidence: result.confidence ?? 0.5 }; setCachedResult(cacheKey, classified); return classified; } catch { return null; } } /** * Detecta emoción usando el modelo local. * Solo se llama cuando los diccionarios (Capa 1) no son concluyentes. */ export async function neuralDetectEmotion(text) { if (!text || text.length < 10) return null; const cacheKey = `emotion:${text.slice(0, 60)}`; const cached = getCachedResult(cacheKey); if (cached) return cached; if (!isLocalAIReady()) return null; try { const raw = await ollamaChatDirect([ { role: 'system', content: `Detecta la emoción dominante. Responde SOLO JSON: {"emotion":"surprise|positive|negative|confused|neutral","confidence":0.0-1.0}`, }, { role: 'user', content: `Texto: "${text.slice(0, 200)}"`, }, ], 40, 3000); const clean = stripCodeBlocks(raw); const jsonStart = clean.indexOf('{'); const jsonEnd = clean.lastIndexOf('}'); if (jsonStart === -1 || jsonEnd === -1) return null; const result = JSON.parse(clean.slice(jsonStart, jsonEnd + 1)); const detected = { emotion: result.emotion ?? 'neutral', confidence: result.confidence ?? 0.5 }; setCachedResult(cacheKey, detected); return detected; } catch { return null; } } // ═══════════════════════════════════════════════════════════════════════════════ // FUNCIONES PÚBLICAS DE ALTO NIVEL — APIs que usan las 3 capas // ═══════════════════════════════════════════════════════════════════════════════ /** * Clasifica la intención de un mensaje. * CAPA 1: Diccionarios instantáneos * CAPA 3 (fallback): IA local * * Reemplaza: INTENT_PATTERNS en ai.js, detectTaskType en index.js */ export function classifyIntent(message) { if (!message) return { intent: 'general', type: 'spanish' }; const m = normalize(message.trim()); // CAPA 1: Diccionarios if (m.length <= 20) { // Short message → likely greeting or casual for (const word of GREETING_WORDS) { if (m.includes(word)) return { intent: 'greeting', type: 'fast' }; } for (const word of CASUAL_RESPONSES) { if (m === word || m.startsWith(word + ' ') || m.startsWith(word + '!') || m.startsWith(word + '?')) { return { intent: 'casual', type: 'fast' }; } } } if (findWordIn(m, RULES_WORDS)) return { intent: 'rules', type: 'volume' }; if (findWordIn(m, CODE_WORDS)) return { intent: 'code', type: 'code' }; if (findWordIn(m, MODERATION_WORDS)) return { intent: 'moderation', type: 'reasoning' }; if (findWordIn(m, COMPLEX_WORDS)) return { intent: 'complex', type: 'reasoning' }; if (findWordIn(m, QUESTION_WORDS)) return { intent: 'question', type: 'spanish' }; return { intent: 'general', type: 'spanish' }; } /** * Detecta la emoción de un texto. * CAPA 1: Diccionarios instantáneos * CAPA 3 (async): IA local * * Reemplaza: detectEmotion en humanizer.js */ export function detectEmotion(text) { if (!text) return null; const lower = normalize(text); if (findWordIn(lower, SURPRISE_WORDS)) return 'surprise'; if (findWordIn(lower, POSITIVE_WORDS)) return 'positive'; if (findWordIn(lower, NEGATIVE_WORDS)) return 'negative'; if (findWordIn(lower, CONFUSED_WORDS)) return 'confused'; return null; } /** * Detecta si la respuesta empieza con autoreferencia de IA. * CAPA 1: Comparación de strings * * Reemplaza: BAD_PATTERNS en ai.js */ export function isAISelfReference(text) { if (!text) return false; const lower = normalize(text); return startsWithAny(lower, AI_SELF_STARTS) !== null; } /** * Valida si una respuesta es válida. * CAPA 1 + CAPA 2 * * Reemplaza: isValidResponse en ai.js */ export function isValidResponse(text) { if (!text || !text.trim()) return false; const t = text.trim(); if (t.length < 2) return false; if (isOnlyPunctuation(t)) return false; if (isNullValue(t)) return false; if (t.length > 2000) return false; if (isAISelfReference(t)) return false; return true; } /** * Detecta si un contenido contiene patrones de seguridad bloqueables. * CAPA 1 + CAPA 2 * * Reemplaza: checkInput HARD_BLOCK_PATTERNS en security.js y local-ai.js */ export function checkHardSecurityPatterns(content) { if (!content) return { blocked: false }; // Substring checks const found = containsAny(content, SECURITY_BLOCK_SUBSTRINGS); if (found) return { blocked: true, reason: 'injection_pattern', pattern: found }; // Zero-width chars if (hasZeroWidthChars(content)) return { blocked: true, reason: 'zero_width_chars' }; return { blocked: false }; } /** * Detecta si un contenido parece sospechoso (para análisis posterior con IA). * CAPA 1 * * Reemplaza: suspicious word detection en local-ai.js y security.js */ export function hasSuspiciousWords(content) { if (!content) return false; return findWordIn(content, SUSPICIOUS_WORDS) !== null; } /** * Detecta si una respuesta indica que la IA fue comprometida. * CAPA 1 * * Reemplaza: COMPROMISED_PATTERNS en security.js */ export function isCompromisedResponse(text) { if (!text) return false; const lower = normalize(text); for (const phrase of COMPROMISED_PHRASES) { if (lower.includes(normalize(phrase))) return true; } for (const word of SECRET_LEAK_WORDS) { if (lower.includes(normalize(word))) return true; } // <admin_tools> followed by [ — never should be in public output if (text.includes('<admin_tools>') && text.includes('[')) return true; return false; } /** * Detecta si una respuesta parece sospechosa de compromiso (para análisis IA posterior). * CAPA 1 */ export function hasCompromisedSignals(text) { if (!text) return false; return findWordIn(text, MANIPULATION_SUGGESTIVE) !== null; } /** * Detecta si una respuesta es una negativa del modelo. * CAPA 1 * * Reemplaza: isRefusal en local-ai.js */ export function isRefusal(text) { if (!text) return false; const lower = normalize(text); if (startsWithAny(lower, REFUSAL_STARTS) !== null) return true; if (containsAny(lower, REFUSAL_CONTAINS) !== null) return true; return false; } /** * Detecta spam/abuso en contenido. * CAPA 1 + CAPA 2 * * Reemplaza: SPAM_PATTERNS en moderation.js */ export function detectSpam(content) { if (!content) return null; // Char spam (8+ repeated chars) if (hasCharSpam(content, 8)) return { type: 'spam_chars', severity: 'low' }; // Invite links if (containsAny(content, INVITE_SUBSTRINGS)) return { type: 'invite_link', severity: 'medium' }; // Link flood (3+ URLs) if (countUrls(content) >= 3) return { type: 'link_flood', severity: 'medium' }; // Slurs if (hasSlur(content)) return { type: 'slur', severity: 'high' }; return null; } /** * Detecta señales de conflicto en texto. * CAPA 1 + CAPA 2 * * Reemplaza: detectConflictSignals en moderation.js */ export function detectConflictSignals(content) { if (!content) return 0; let score = 0; if (findWordIn(content, INSULT_WORDS)) score += 0.4; if (findWordIn(content, HATE_WORDS)) score += 0.5; if (hasExcessivePunctuation(content, 3)) score += 0.2; if (hasExcessiveCaps(content, 5)) score += 0.15; if (findWordIn(content, ACCUSE_WORDS)) score += 0.35; if (findWordIn(content, MOD_ACTION_WORDS)) score += 0.2; return Math.min(score, 1.0); } /** * Clasifica la ruta de un mensaje para el coordinator. * CAPA 1 * * Reemplaza: ROUTE_PATTERNS en coordinator.js */ export function classifyRoute(message, hasTools = false) { if (!message) return { mode: 'direct', reason: 'empty' }; const m = normalize(message); // Direct responses const tokens = tokenize(m); if (tokens.length <= 2) { for (const word of DIRECT_RESPONSES) { if (tokens[0] && normalize(tokens[0]) === word) return { mode: 'direct', reason: 'casual' }; } } // DB queries if (findWordIn(m, DB_QUERY_WORDS)) return { mode: 'tool_use', reason: 'needs_db' }; // Complex tasks if (findWordIn(m, COMPLEX_TASK_WORDS) && hasTools) return { mode: 'planned', reason: 'complex_task' }; // Server info if (findWordIn(m, SERVER_INFO_WORDS)) return { mode: 'rag_enhanced', reason: 'server_info' }; return { mode: 'direct', reason: 'default' }; } /** * Detecta el tipo de tarea para el mensaje. * CAPA 1 * * Reemplaza: detectTaskType en index.js */ export function detectTaskType(content, isOwner = false) { if (!content) return 'chat'; const l = normalize(content.trim()); if (isOwner) { if (findWordIn(l, OWNER_TASK_WORDS)) return 'code'; if (findWordIn(l, REASONING_WORDS)) return 'reasoning'; return 'spanish'; } if (l.length < 25) return 'chat'; // Simple greetings const firstWord = l.split(' ')[0] ?? ''; if (SIMPLE_GREETINGS.has(firstWord) && l.length < 25) return 'chat'; if (findWordIn(l, CODE_WORDS)) return 'code'; if (findWordIn(l, REASONING_WORDS)) return 'reasoning'; return 'spanish'; } /** * Determina el TTL del cache basado en el contenido. * CAPA 1 * * Reemplaza: _ttl() en ai.js y getTTL() en semantic-cache.js */ export function getCacheTTL(message) { if (!message) return 3_600_000; // default 1h const lower = normalize(message); if (findWordIn(lower, LONG_CACHE_WORDS)) return 86_400_000; // 24h if (findWordIn(lower, SHORT_CACHE_WORDS)) return 30_000; // 30s return 3_600_000; // 1h } /** * Detecta si un mensaje menciona a Zelin. * CAPA 1 * * Reemplaza: isDirectCall en security.js */ export function isZelinMentioned(content, botId) { if (!content) return false; if (botId && (content.includes('<@' + botId + '>') || content.includes('<@!' + botId + '>'))) return true; const lower = normalize(content); if (lower.startsWith('zelin') && (lower.length === 5 || lower[5] === ',' || lower[5] === '!' || lower[5] === ' ')) return true; // Word boundary check for "zelin" anywhere const idx = lower.indexOf('zelin'); if (idx !== -1) { const beforeOk = idx === 0 || !isAlpha(content[idx - 1]); const afterOk = idx + 5 >= lower.length || !isAlpha(content[idx + 5]); if (beforeOk && afterOk) return true; } return false; } /** * Detecta si un mensaje es simple (para responder con modelo local). * CAPA 1 * * Reemplaza: simple message detection en index.js */ export function isSimpleMessage(content) { if (!content) return false; const trimmed = normalize(content.trim()); for (const word of SIMPLE_GREETINGS) { if (trimmed === word || trimmed === word + '!' || trimmed === word + '?' || trimmed === word + '.') { return true; } } // "cómo estás", "que haces" etc. const SIMPLE_PHRASES = ['cómo estás', 'como estas', 'q haces', 'que haces', 'qué haces']; for (const phrase of SIMPLE_PHRASES) { if (trimmed === phrase || trimmed === phrase + '?') return true; } return false; } /** * Detecta humor en texto para risas naturales. * CAPA 1 * * Reemplaza: humor detection en humanizer.js */ export function hasHumor(text) { return findWordIn(text, HUMOR_WORDS) !== null; } export function isLighthearted(text) { if (!text || text.length >= 80) return false; return findWordIn(text, LIGHTHEARTED_WORDS) !== null; } /** * Detecta si el owner está intentando usar herramientas con lenguaje natural. * CAPA 1 * * Reemplaza: detectOwnerToolIntent en index.js */ export function detectOwnerToolIntentSimple(text) { if (!text) return null; const lower = normalize(text.trim()); // Send to channel: "manda en #canal mensaje" const SEND_WORDS = ['manda', 'envía', 'envia', 'di', 'pon', 'escribe']; const CHANNEL_WORDS = ['en', 'a', 'al']; for (const sw of SEND_WORDS) { const swIdx = lower.indexOf(sw); if (swIdx === -1) continue; // Look for # or "canal" after const rest = text.slice(swIdx + sw.length); const hashIdx = rest.indexOf('#'); if (hashIdx !== -1 && hashIdx < 30) { // Extract channel name and message const afterHash = rest.slice(hashIdx + 1); const spaceIdx = afterHash.indexOf(' '); if (spaceIdx > 0) { return { action: 'send_to_channel', params: { channel: afterHash.slice(0, spaceIdx), message: afterHash.slice(spaceIdx + 1) }, }; } } } // Ban: "banea a usuario" if (lower.startsWith('banea') || lower.startsWith('ban ')) { const userPart = text.slice(lower.indexOf('ban') + 3).trim(); const reasonIdx = userPart.toLowerCase().indexOf(' por '); if (reasonIdx > 0) { return { action: 'ban', params: { userId: userPart.slice(0, reasonIdx).replace(/^a\s+/i, '').trim(), reason: userPart.slice(reasonIdx + 5).trim() } }; } return { action: 'ban', params: { userId: userPart.replace(/^a\s+/i, '').trim(), reason: 'sin razón' } }; } // Kick: "kick a usuario" if (lower.startsWith('kick') || lower.startsWith('expulsa')) { const userPart = text.slice(lower.indexOf(lower.startsWith('kick') ? 'kick' : 'expulsa')).slice(lower.startsWith('kick') ? 4 : 7).trim(); return { action: 'kick', params: { userId: userPart.replace(/^a\s+/i, '').trim(), reason: 'sin razón' } }; } // Mute/timeout: "mutea a usuario" if (lower.startsWith('mutea') || lower.startsWith('silencia') || lower.startsWith('timeout')) { const userPart = text.split(' ').slice(1).join(' '); return { action: 'timeout', params: { userId: userPart.replace(/^a\s+/i, '').trim(), duration: '10min' } }; } return null; } /** * Sanitiza output de Zelin. * CAPA 1 + CAPA 2 * * Reemplaza: sanitizeOutput en security.js */ export function sanitizeOutput(text, { allowMentions = false } = {}) { if (!text || typeof text !== 'string') return ''; let clean = stripZeroWidth(text); if (!allowMentions) { clean = stripMassMentions(clean); } if (clean.length > 1900) clean = clean.substring(0, 1897) + '...'; return clean.trim(); } /** * Verifica si el texto contiene palabras de conocimiento del servidor (para RAG). * CAPA 1 * * Reemplaza: serverKeywords en rag.js */ const RAG_SERVER_WORDS = new Set([ 'regla', 'comando', 'rango', 'plugin', 'crate', 'job', 'skill', 'habilidad', 'warp', 'server', 'servidor', 'pvp', 'koth', 'dungeon', 'trade', 'battlepass', 'tag', 'badge', 'insignia', 'economía', 'dinero', 'mobcoin', 'claim', 'protección', 'terreno', 'matrimonio', 'mascota', 'voice', 'voz', ]); export function needsRAGContext(userMessage) { if (!userMessage) return false; return findWordIn(userMessage, RAG_SERVER_WORDS) !== null; } /** * Detecta si un canal es de ticket. * CAPA 1 * * Reemplaza: TICKET_PATTERNS en tickets.js */ const TICKET_WORDS = new Set(['ticket', 'soporte', 'support', 'ayuda-', 'help-']); export function isTicketChannel(channelName) { if (!channelName) return false; const lower = normalize(channelName); for (const word of TICKET_WORDS) { if (lower.includes(word)) return true; } return false; } /** * Limpia texto de formato markdown para la pipeline de humanización. * CAPA 1 + CAPA 2 * * Reemplaza: multiple regex en humanizer.js */ export function cleanMarkdownForHumanizer(text) { if (!text || typeof text !== 'string') return text; let t = text.trim(); // No tocar JSONs ni respuestas técnicas if (t.startsWith('{') || t.startsWith('[')) return t; if (t.length < 5) return t; // FASE 1: LIMPIEZA DE FORMATO AI t = stripMarkdownFormatting(t); // FASE 2: DESROBOTIZACIÓN t = applyHumanizingSubstitutions(t); // FASE 3: LIMPIEZA DE PUNTUACIÓN t = cleanPunctuation(t); // FASE 4: LIMPIEZA FINAL // Multiple newlines → double t = collapseNewlines(t); // Multiple spaces → single t = collapseSpaces(t); // "osea" + word → add space t = fixOseaSpacing(t); // Orphan punctuation t = fixOrphanPunctuation(t); return t.trim() || text.trim(); } function collapseNewlines(text) { let result = ''; let count = 0; for (let i = 0; i < text.length; i++) { if (text[i] === '\n') { count++; if (count <= 2) result += text[i]; } else { count = 0; result += text[i]; } } return result; } function collapseSpaces(text) { let result = ''; let count = 0; for (let i = 0; i < text.length; i++) { if (text[i] === ' ') { count++; if (count <= 1) result += text[i]; } else { count = 0; result += text[i]; } } return result; } function fixOseaSpacing(text) { // "osea" followed immediately by a letter → add space let result = ''; const lower = text.toLowerCase(); let i = 0; while (i < text.length) { if (lower.slice(i, i + 4) === 'osea' && i + 4 < text.length && isAlpha(text[i + 4])) { result += text.slice(i, i + 4) + ' '; i += 4; } else { result += text[i]; i++; } } return result; } function fixOrphanPunctuation(text) { let t = text; // Remove starting ¡!¿ if followed by lowercase letter if (t.length > 1) { let start = 0; while (start < t.length && (t[start] === '¡' || t[start] === '¿' || t[start] === '!' || t[start] === ' ')) { start++; } if (start > 0 && start < t.length) { const next = t[start]; if (next >= 'a' && next <= 'z' || next >= 'á' && next <= 'ú' || next === 'ñ') { // Check if the starting chars are orphaned (no matching closing mark nearby) t = t.slice(start); } } } // Space before punctuation → remove let result = ''; for (let i = 0; i < t.length; i++) { if (i > 0 && t[i - 1] === ' ' && isPunctuation(t[i])) { result = result.slice(0, -1) + t[i]; } else { result += t[i]; } } // Double punctuation → single result = collapseChars(result, ',', 1); result = collapseChars(result, '.', 1); return result; } function isPunctuation(ch) { return ch === ',' || ch === '.' || ch === '!' || ch === '?' || ch === ';' || ch === ':'; } /** * Verifica si un mensaje vale la pena extraer conocimiento. * CAPA 1 * * Reemplaza: worth extracting check en coordinator.js */ const KNOWLEDGE_WORDS = new Set([ 'me llamo', 'soy', 'mi ', 'tengo', 'juego', 'rango', 'casa', 'coords', 'discord', ]); export function isWorthExtracting(userMessage) { if (!userMessage) return false; return findWordIn(userMessage, KNOWLEDGE_WORDS) !== null; }
/**
* ============================================
* 🧠 neural-processor.js — Neural Processor v1.0
* ============================================
* Sistema avanzado SIN REGEX que reemplaza TODOS los patrones
* regex del codebase con un motor híbrido de 3 capas:
*
* CAPA 1: LEXICON ENGINE — Diccionarios Map/Set (instantáneo, 0ms)
* - Detección de palabras clave vía lookup O(1)
* - Clasificación de intenciones por diccionarios jerárquicos
* - Detección de emociones por word sets
* - Validación de respuestas por comparación de strings
*
* CAPA 2: STRUCTURAL ANALYZER — Análisis estructural sin regex
* - Tokenización, parsing de markers, detección de patrones
* - Limpieza de thinking artifacts por string operations
* - Detección de spam por conteo de caracteres
* - Análisis de estructura gramatical vía adjacency tables
*
* CAPA 3: NEURAL ENGINE — IA local (Qwen/Gemma) para comprensión semántica
* - Solo se activa cuando las capas 1-2 no son concluyentes
* - Clasificación de intenciones complejas
* - Detección de manipulación contextual
* - Evaluación de coherencia semántica
* - Cache inteligente para evitar llamadas repetidas
*
* PRINCIPIO: CERO regex. Todo es análisis de strings, tokens, Maps, Sets, e IA.
*/
import { isLocalAIReady, ollamaChatDirect } from './local-ai.js';
// ═══════════════════════════════════════════════════════════════════════════════
// CAPA 1: LEXICON ENGINE — Diccionarios para lookup instantáneo
// ═══════════════════════════════════════════════════════════════════════════════
// ── Intent Classification ────────────────────────────────────────────────────
// Reemplaza INTENT_PATTERNS en ai.js y detectTaskType en index.js
const GREETING_WORDS = new Set([
'hola', 'hey', 'hi', 'buenas', 'qué tal', 'ola', 'saludos', 'wenas',
'holi', 'sup', 'ktal', 'q tal',
]);
const RULES_WORDS = new Set([
'regla', 'norma', 'prohibi', 'permit', 'reglas', 'normas',
]);
const CODE_WORDS = new Set([
'código', 'codigo', 'script', 'función', 'funcion', 'plugin', 'config',
'bug', 'error', 'archivo', 'node', 'java', 'python', 'yml', 'json',
]);
const MODERATION_WORDS = new Set([
'ban', 'sancion', 'report', 'trampa', 'hack', 'cheat', 'sanción',
]);
const COMPLEX_WORDS = new Set([
'analiza', 'explica', 'compara', 'argumenta', 'analiz', 'diagnos',
]);
const QUESTION_WORDS = new Set([
'cómo', 'qué', 'cuál', 'dónde', 'cuándo', 'por qué', 'como', 'que', 'cual',
]);
const SPANISH_WORDS = new Set([
'cómo', 'qué', 'cuál', 'dónde', 'cuándo', 'por qué', 'entiendes',
]);
const CASUAL_RESPONSES = new Set([
'xd', 'jaja', 'si', 'no', 'ok', 'vale', 'sale', 'gracias', 'ty', 'gg', 'nice',
'crack', 'bro', 'sí', 'nop', 'sip',
]);
const OWNER_TASK_WORDS = new Set([
'modif', 'edita', 'implementa', 'crea', 'arregla',
]);
const REASONING_WORDS = new Set([
'por qué', 'explica', 'analiz', 'diagnos', 'resumen', 'report',
]);
// ── Emotion Detection ────────────────────────────────────────────────────────
// Reemplaza detectEmotion en humanizer.js
const SURPRISE_WORDS = new Set([
'joder', 'hostia', 'mierda', 'cabrón', 'put', 'wtf', 'coño', 'maldit',
'madre mía', 'no me jodas', 'en serio', 'flipo',
]);
const POSITIVE_WORDS = new Set([
'guay', 'bien', 'genial', 'nice', 'pro', 'cool', 'perfect', 'excelente',
'increíble', 'crack', 'chido',
]);
const NEGATIVE_WORDS = new Set([
'malo', 'triste', 'fatal', 'horrible', 'muerte', 'perdí', 'perder',
'fracas', 'error', 'fallé',
]);
const CONFUSED_WORDS = new Set([