Spaces:
Paused
Paused
Download src/autonomy-engine.js from TomatitoToho/zelin-v6x: direct link, hf CLI and curl.
- Browser
- Download file 39.8 kB
-
https://huggingface.co/spaces/TomatitoToho/zelin-v6x/resolve/main/src/autonomy-engine.js
- Command line
-
hf download hf://spaces/TomatitoToho/zelin-v6x/src/autonomy-engine.js
-
curl -L -o autonomy-engine.js https://huggingface.co/spaces/TomatitoToho/zelin-v6x/resolve/main/src/autonomy-engine.js
39.8 kB
| /** | |
| * ============================================ | |
| * autonomy-engine.js β Zelin Autonomy Engine v6.0 | |
| * ============================================ | |
| * v6.0: MAJOR ANTI-SPAM OVERHAUL | |
| * - Will growth reduced 5x (was growing way too fast) | |
| * - All chat message actions go through global rate limiter | |
| * - Cooldowns increased 3-5x across the board | |
| * - Observation system feeds will much more slowly | |
| * - Social actions now check canSendAutonomousMessage() | |
| */ | |
| import { callAI, callAIBackground } from './ai.js'; | |
| import { readConfig } from './utils.js'; | |
| import * as db from './db.js'; | |
| import * as memory from './memory.js'; | |
| import { isLocalAIReady, emergencyFallback } from './local-ai.js'; | |
| import { canSendAutonomousMessage, recordAutonomousMessage } from './state.js'; | |
| const config = readConfig(); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 1. WILL SYSTEM β Internal motivations that drive Zelin's actions | |
| // v6.0: Growth rates reduced 5x β will grows much more slowly now | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const willState = { | |
| talkToPeople : 30, | |
| shareKnowledge : 20, | |
| helpSomeone : 25, | |
| makeJoke : 15, | |
| enforceRules : 40, | |
| protectServer : 35, | |
| checkServer : 20, | |
| learnNewThings : 10, | |
| selfReflect : 5, | |
| energy : 80, | |
| mood : 'neutral', | |
| lastAction : 0, | |
| }; | |
| // β v6.0: Growth rates reduced 5x β will grows much more slowly | |
| const WILL_GROWTH = { | |
| talkToPeople : 0.4, // was 2 | |
| shareKnowledge : 0.3, // was 1.5 | |
| helpSomeone : 0.4, // was 2 | |
| makeJoke : 0.2, // was 1 | |
| enforceRules : 0.6, // was 3 | |
| protectServer : 0.5, // was 2.5 | |
| checkServer : 0.3, // was 1.5 | |
| learnNewThings : 0.1, // was 0.5 | |
| selfReflect : 0.06, // was 0.3 | |
| }; | |
| const WILL_DECREASE = { | |
| talkToPeople : 50, | |
| shareKnowledge : 40, | |
| helpSomeone : 45, | |
| makeJoke : 35, | |
| enforceRules : 60, | |
| protectServer : 50, | |
| checkServer : 30, | |
| learnNewThings : 30, | |
| selfReflect : 25, | |
| }; | |
| // β v6.0: Thresholds raised β needs more will before acting | |
| const WILL_THRESHOLDS = { | |
| talkToPeople : 75, // was 60 | |
| shareKnowledge : 70, // was 55 | |
| helpSomeone : 65, // was 50 | |
| makeJoke : 70, // was 50 | |
| enforceRules : 55, // was 45 (keep this lower for safety) | |
| protectServer : 50, // was 40 (keep lower for safety) | |
| checkServer : 65, // was 50 | |
| learnNewThings : 60, // was 45 | |
| selfReflect : 55, // was 40 | |
| }; | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 2. AUTONOMY STATE MACHINE | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| const STATES = { | |
| IDLE : 'idle', | |
| OBSERVING : 'observing', | |
| THINKING : 'thinking', | |
| ACTING : 'acting', | |
| RECOVERING : 'recovering', | |
| RESTING : 'resting', | |
| }; | |
| let currentState = STATES.IDLE; | |
| let stateSince = Date.now(); | |
| let actionHistory = []; | |
| function transitionTo(newState) { | |
| if (currentState === newState) return; | |
| console.log(`[Autonomy] State: ${currentState} β ${newState}`); | |
| currentState = newState; | |
| stateSince = Date.now(); | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 3. OBSERVATION SYSTEM β v6.0: Feeds will much more slowly | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ObservationSystem { | |
| constructor() { | |
| this.recentMessages = []; | |
| this.channelActivity = {}; | |
| this.userBehavior = {}; | |
| this.serverEvents = []; | |
| this.maxObsAge = 30 * 60 * 1000; | |
| } | |
| addMessage(message) { | |
| if (!message || message.author?.bot) return; | |
| const obs = { | |
| id : message.id, | |
| channelId : message.channelId, | |
| channelName: message.channel?.name ?? '', | |
| userId : message.author.id, | |
| username : message.author.username, | |
| content : (message.content ?? '').substring(0, 500), | |
| timestamp : Date.now(), | |
| isOwner : message.author.id === config.admin?.userId, | |
| }; | |
| this.recentMessages.push(obs); | |
| if (this.recentMessages.length > 100) this.recentMessages.shift(); | |
| if (!this.channelActivity[obs.channelId]) { | |
| this.channelActivity[obs.channelId] = { lastMsg: 0, msgCount: 0, activeUsers: new Set(), name: obs.channelName }; | |
| } | |
| const ch = this.channelActivity[obs.channelId]; | |
| ch.lastMsg = Date.now(); | |
| ch.msgCount++; | |
| ch.activeUsers.add(obs.userId); | |
| ch.name = obs.channelName; | |
| if (!this.userBehavior[obs.userId]) { | |
| this.userBehavior[obs.userId] = { messageCount: 0, warnings: 0, lastSeen: 0, toxicCount: 0, spamCount: 0 }; | |
| } | |
| this.userBehavior[obs.userId].messageCount++; | |
| this.userBehavior[obs.userId].lastSeen = Date.now(); | |
| // β v6.0: Reduced will growth from messages (was +0.5/+0.3, now +0.1/+0.05) | |
| willState.talkToPeople += 0.1; | |
| willState.helpSomeone += 0.05; | |
| this._analyzeMessage(obs); | |
| } | |
| _analyzeMessage(obs) { | |
| const content = obs.content.toLowerCase(); | |
| if (this._looksToxic(content)) { | |
| // β v6.0: Reduced will growth from toxic content (was +8/+5, now +3/+2) | |
| willState.enforceRules += 3; | |
| willState.protectServer += 2; | |
| if (this.userBehavior[obs.userId]) { | |
| this.userBehavior[obs.userId].toxicCount++; | |
| } | |
| } | |
| if (this._looksLikeSpam(obs.userId)) { | |
| willState.enforceRules += 2; | |
| if (this.userBehavior[obs.userId]) { | |
| this.userBehavior[obs.userId].spamCount++; | |
| } | |
| } | |
| if (/\?\s*$/.test(content) || /\b(?:cΓ³mo|quΓ©|dΓ³nde|cuΓ‘ndo|por quΓ©|ayuda|help)\b/i.test(content)) { | |
| willState.helpSomeone += 1; // was +4 | |
| } | |
| // β v6.0: Removed dead chat detector β was constantly increasing talkToPeople | |
| // Brain.js handles chat revival, no need for duplicate here | |
| if (this._detectConflict(content)) { | |
| willState.enforceRules += 2; // was +5 | |
| willState.protectServer += 1; // was +3 | |
| } | |
| } | |
| _looksToxic(content) { | |
| const toxicIndicators = [ | |
| 'idiota', 'estΓΊpido', 'mierda', 'pute', 'puto', 'jΓ³dete', 'mΓ‘tate', | |
| 'suicΓdate', 'ojalΓ‘ te mueras', 'eres una basura', 'te odio', | |
| 'kill yourself', 'kys', 'retar', 'amenaza', | |
| ]; | |
| return toxicIndicators.some(ind => content.includes(ind)); | |
| } | |
| _looksLikeSpam(userId) { | |
| const user = this.userBehavior[userId]; | |
| if (!user) return false; | |
| const recentMsgs = this.recentMessages.filter( | |
| m => m.userId === userId && Date.now() - m.timestamp < 10000 | |
| ); | |
| return recentMsgs.length >= 4; | |
| } | |
| _detectConflict(content) { | |
| const conflictWords = ['pelea', 'discusiΓ³n', 'debate fuerte', 'te voy a', 'no me importa', | |
| 'cΓ‘llate', 'no me hables', 'dΓ©jame en paz', 'report', 'banealo', 'es trampa']; | |
| return conflictWords.some(w => content.includes(w)); | |
| } | |
| getActiveChannels() { | |
| const now = Date.now(); | |
| return Object.entries(this.channelActivity) | |
| .filter(([_, ch]) => now - ch.lastMsg < 30 * 60 * 1000 && ch.activeUsers.size > 0) | |
| .map(([id, ch]) => ({ id, ...ch, activeUsers: ch.activeUsers.size })) | |
| .sort((a, b) => b.lastMsg - a.lastMsg); | |
| } | |
| getSilentChannels() { | |
| const now = Date.now(); | |
| return Object.entries(this.channelActivity) | |
| .filter(([_, ch]) => now - ch.lastMsg > 15 * 60 * 1000 && ch.activeUsers.size >= 2) | |
| .map(([id, ch]) => ({ id, ...ch })) | |
| .sort((a, b) => a.lastMsg - b.lastMsg); | |
| } | |
| getProblematicUsers() { | |
| return Object.entries(this.userBehavior) | |
| .filter(([_, u]) => u.toxicCount >= 2 || u.spamCount >= 3) | |
| .map(([id, u]) => ({ id, ...u })); | |
| } | |
| getRecentContext(channelId, limit = 15) { | |
| return this.recentMessages | |
| .filter(m => m.channelId === channelId) | |
| .slice(-limit) | |
| .map(m => `[${m.username}]: ${m.content}`) | |
| .join('\n'); | |
| } | |
| cleanup() { | |
| const cutoff = Date.now() - this.maxObsAge; | |
| this.recentMessages = this.recentMessages.filter(m => m.timestamp > cutoff); | |
| for (const [id, ch] of Object.entries(this.channelActivity)) { | |
| if (Date.now() - ch.lastMsg > this.maxObsAge) delete this.channelActivity[id]; | |
| } | |
| for (const [id, u] of Object.entries(this.userBehavior)) { | |
| if (Date.now() - u.lastSeen > this.maxObsAge) delete this.userBehavior[id]; | |
| } | |
| } | |
| } | |
| export const observationSystem = new ObservationSystem(); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 4. AUTONOMOUS DECISION ENGINE | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class AutonomousDecisionEngine { | |
| constructor() { | |
| this.lastDecisionTime = 0; | |
| // β v6.0: Min 5 minutes between decisions (was 30 seconds!) | |
| this.minDecisionInterval = 10 * 60 * 1000; // β v7.0: Min 10 minutes between decisions (was 5) | |
| this.decisionHistory = []; | |
| this.maxHistory = 50; | |
| } | |
| async decide(client) { | |
| if (Date.now() - this.lastDecisionTime < this.minDecisionInterval) { | |
| return null; | |
| } | |
| if (willState.energy < 15) { | |
| transitionTo(STATES.RESTING); | |
| return null; | |
| } | |
| transitionTo(STATES.THINKING); | |
| const desires = this._rankDesires(); | |
| if (!desires.length) return null; | |
| const topDesire = desires[0]; | |
| if (topDesire.will < WILL_THRESHOLDS[topDesire.name]) { | |
| transitionTo(STATES.IDLE); | |
| return null; | |
| } | |
| const action = await this._planAction(topDesire, client); | |
| if (!action) { | |
| transitionTo(STATES.IDLE); | |
| return null; | |
| } | |
| this.lastDecisionTime = Date.now(); | |
| this.decisionHistory.push({ desire: topDesire.name, action: action.type, timestamp: Date.now() }); | |
| if (this.decisionHistory.length > this.maxHistory) this.decisionHistory.shift(); | |
| return action; | |
| } | |
| _rankDesires() { | |
| return Object.entries(WILL_GROWTH) | |
| .map(([name, _]) => ({ name, will: willState[name] })) | |
| .sort((a, b) => b.will - a.will); | |
| } | |
| async _planAction(desire, client) { | |
| const guild = client?.guilds?.cache?.first(); | |
| if (!guild) return null; | |
| switch (desire.name) { | |
| case 'enforceRules': return this._planModerationAction(guild); | |
| case 'protectServer': return this._planProtectionAction(guild); | |
| case 'talkToPeople': return this._planSocialAction(guild); | |
| case 'helpSomeone': return this._planHelpAction(guild); | |
| case 'shareKnowledge': return this._planKnowledgeAction(guild); | |
| case 'makeJoke': return this._planHumorAction(guild); | |
| case 'checkServer': return this._planServerCheckAction(guild); | |
| case 'learnNewThings': return this._planLearningAction(guild); | |
| case 'selfReflect': return this._planReflectionAction(guild); | |
| default: return null; | |
| } | |
| } | |
| _planModerationAction(guild) { | |
| const problems = observationSystem.getProblematicUsers(); | |
| if (!problems.length) return null; | |
| const target = problems[0]; | |
| return { | |
| type : 'moderate', | |
| target : target.id, | |
| reason : target.toxicCount >= 3 ? 'high_toxicity' : 'spam_behavior', | |
| severity: target.toxicCount >= 3 ? 'timeout' : 'warn', | |
| willCost: WILL_DECREASE.enforceRules, | |
| }; | |
| } | |
| _planProtectionAction(guild) { | |
| const activeChannels = observationSystem.getActiveChannels(); | |
| for (const ch of activeChannels) { | |
| const ctx = observationSystem.getRecentContext(ch.id); | |
| if (ctx && observationSystem._detectConflict(ctx.toLowerCase())) { | |
| return { type: 'intervene_conflict', channelId: ch.id, context: ctx, willCost: WILL_DECREASE.protectServer }; | |
| } | |
| } | |
| return null; | |
| } | |
| _planSocialAction(guild) { | |
| const activeChannels = observationSystem.getActiveChannels(); | |
| const silentChannels = observationSystem.getSilentChannels(); | |
| if (activeChannels.length > 0) { | |
| const ch = activeChannels[0]; | |
| const ctx = observationSystem.getRecentContext(ch.id); | |
| return { type: 'social_speak', channelId: ch.id, channelName: ch.name, context: ctx, willCost: WILL_DECREASE.talkToPeople }; | |
| } | |
| if (silentChannels.length > 0) { | |
| const ch = silentChannels[0]; | |
| return { type: 'revive_chat', channelId: ch.id, channelName: ch.name, willCost: WILL_DECREASE.talkToPeople }; | |
| } | |
| return null; | |
| } | |
| _planHelpAction(guild) { | |
| const recentQuestions = observationSystem.recentMessages.filter(m => { | |
| const age = Date.now() - m.timestamp; | |
| return age < 10 * 60 * 1000 && /\?\s*$/.test(m.content) && !m.content.toLowerCase().includes('zelin'); | |
| }); | |
| if (recentQuestions.length > 0) { | |
| const q = recentQuestions[0]; | |
| return { type: 'help_user', channelId: q.channelId, userId: q.userId, question: q.content, willCost: WILL_DECREASE.helpSomeone }; | |
| } | |
| return null; | |
| } | |
| _planKnowledgeAction(guild) { | |
| const activeChannels = observationSystem.getActiveChannels(); | |
| if (activeChannels.length === 0) return null; | |
| const ch = activeChannels[0]; | |
| const ctx = observationSystem.getRecentContext(ch.id); | |
| if (!ctx || ctx.length < 50) return null; | |
| return { type: 'share_knowledge', channelId: ch.id, context: ctx, willCost: WILL_DECREASE.shareKnowledge }; | |
| } | |
| _planHumorAction(guild) { | |
| const activeChannels = observationSystem.getActiveChannels(); | |
| if (activeChannels.length === 0) return null; | |
| const ch = activeChannels[Math.floor(Math.random() * activeChannels.length)]; | |
| return { type: 'make_joke', channelId: ch.id, willCost: WILL_DECREASE.makeJoke }; | |
| } | |
| _planServerCheckAction(guild) { | |
| return { type: 'check_minecraft', willCost: WILL_DECREASE.checkServer }; | |
| } | |
| _planLearningAction(guild) { | |
| return { type: 'auto_learn', willCost: WILL_DECREASE.learnNewThings }; | |
| } | |
| _planReflectionAction(guild) { | |
| return { type: 'self_reflect', willCost: WILL_DECREASE.selfReflect }; | |
| } | |
| } | |
| const decisionEngine = new AutonomousDecisionEngine(); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 5. AUTONOMOUS ACTION EXECUTOR β v6.0: All chat actions use rate limiter | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // Actions that send messages to chat channels (need rate limiter) | |
| const CHAT_ACTIONS = new Set([ | |
| 'social_speak', 'revive_chat', 'help_user', 'share_knowledge', 'make_joke', | |
| 'intervene_conflict', 'moderate', | |
| ]); | |
| // Actions that DON'T send chat messages (internal only, no rate limiter needed) | |
| const INTERNAL_ACTIONS = new Set([ | |
| 'check_minecraft', 'auto_learn', 'self_reflect', | |
| ]); | |
| class AutonomousActionExecutor { | |
| constructor() { | |
| this.executing = false; | |
| this.cooldowns = new Map(); | |
| this.cooldownTimes = { | |
| moderate : 20 * 60 * 1000, // β v7.0: 20min (was 10min) | |
| intervene_conflict : 30 * 60 * 1000, // β v7.0: 30min (was 15min) | |
| social_speak : 60 * 60 * 1000, // β v7.0: 60min (was 30min) | |
| revive_chat : 90 * 60 * 1000, // β v7.0: 90min (was 45min) | |
| help_user : 30 * 60 * 1000, // β v7.0: 30min (was 15min) | |
| share_knowledge : 60 * 60 * 1000, // β v7.0: 60min (was 30min) | |
| make_joke : 60 * 60 * 1000, // β v7.0: 60min (was 30min) | |
| check_minecraft : 15 * 60 * 1000, // β v7.0: 15min (was 10min) | |
| auto_learn : 120 * 60 * 1000, // β v7.0: 2h (was 1h) | |
| self_reflect : 120 * 60 * 1000, // β v7.0: 2h (was 1h) | |
| }; | |
| } | |
| canExecute(actionType) { | |
| const last = this.cooldowns.get(actionType) ?? 0; | |
| const cd = this.cooldownTimes[actionType] ?? 60 * 1000; | |
| return Date.now() - last >= cd; | |
| } | |
| async execute(action, client) { | |
| if (this.executing) return null; | |
| if (!this.canExecute(action.type)) return null; | |
| // β v6.0: For chat actions, check the GLOBAL rate limiter | |
| if (CHAT_ACTIONS.has(action.type)) { | |
| if (!canSendAutonomousMessage('autonomy', action.type)) { | |
| return null; // Rate limiter says no | |
| } | |
| } | |
| this.executing = true; | |
| transitionTo(STATES.ACTING); | |
| try { | |
| let result = null; | |
| switch (action.type) { | |
| case 'moderate': result = await this._executeModeration(action, client); break; | |
| case 'intervene_conflict': result = await this._executeConflictIntervention(action, client); break; | |
| case 'social_speak': result = await this._executeSocialSpeak(action, client); break; | |
| case 'revive_chat': result = await this._executeReviveChat(action, client); break; | |
| case 'help_user': result = await this._executeHelpUser(action, client); break; | |
| case 'share_knowledge': result = await this._executeShareKnowledge(action, client); break; | |
| case 'make_joke': result = await this._executeMakeJoke(action, client); break; | |
| case 'check_minecraft': result = await this._executeCheckMinecraft(action, client); break; | |
| case 'auto_learn': result = await this._executeAutoLearn(action, client); break; | |
| case 'self_reflect': result = await this._executeSelfReflect(action, client); break; | |
| } | |
| if (result) { | |
| this._applyWillCost(action); | |
| willState.energy = Math.max(10, willState.energy - 3); | |
| willState.lastAction = Date.now(); | |
| actionHistory.push({ type: action.type, success: true, timestamp: Date.now() }); | |
| if (actionHistory.length > 50) actionHistory.shift(); | |
| await this._saveActionToDB(action, result).catch(() => {}); | |
| } | |
| this.cooldowns.set(action.type, Date.now()); | |
| return result; | |
| } catch (err) { | |
| console.error(`[Autonomy] Error executing ${action.type}:`, err.message); | |
| actionHistory.push({ type: action.type, success: false, error: err.message, timestamp: Date.now() }); | |
| return null; | |
| } finally { | |
| this.executing = false; | |
| transitionTo(STATES.IDLE); | |
| } | |
| } | |
| // β v7.1: Fixed broken will cost mapping β was using fragile substring matching | |
| _applyWillCost(action) { | |
| const cost = action.willCost ?? 30; | |
| // Direct mapping from action types to will keys | |
| const ACTION_TO_WILL = { | |
| moderate: 'enforceRules', | |
| intervene_conflict: 'protectServer', | |
| social_speak: 'talkToPeople', | |
| revive_chat: 'talkToPeople', | |
| help_user: 'helpSomeone', | |
| share_knowledge: 'shareKnowledge', | |
| make_joke: 'makeJoke', | |
| check_minecraft: 'checkServer', | |
| auto_learn: 'learnNewThings', | |
| self_reflect: 'selfReflect', | |
| alert_staff: 'protectServer', | |
| }; | |
| const willKey = ACTION_TO_WILL[action.type]; | |
| if (willKey && willState[willKey] !== undefined) { | |
| willState[willKey] = Math.max(0, willState[willKey] - cost); | |
| } | |
| } | |
| async _executeModeration(action, client) { | |
| const guild = client.guilds.cache.first(); | |
| if (!guild) return null; | |
| try { | |
| const member = await guild.members.fetch(action.target).catch(() => null); | |
| if (!member) return null; | |
| if (member.id === config.admin?.userId || member.permissions?.has('Administrator')) return null; | |
| const zelinMember = guild.members.cache.get(client.user.id); | |
| if (!zelinMember?.permissions?.has('ModerateMembers')) return null; | |
| if (action.severity === 'timeout') { | |
| await member.timeout(5 * 60 * 1000, 'Zelin: comportamiento tΓ³xico automΓ‘tico'); | |
| const channel = guild.channels.cache.find(c => c.isTextBased?.() && !c.name.includes('log')); | |
| if (channel) { | |
| await channel.send(`${member.displayName}, para con eso. Timeout de 5 min β no se tolera ese comportamiento acΓ‘.`).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'moderate', channel.name); | |
| } | |
| console.log(`[Autonomy] Timeout automΓ‘tico: ${member.displayName} (${action.reason})`); | |
| return { action: 'timeout', target: member.displayName }; | |
| } else { | |
| const channel = guild.channels.cache.find(c => c.isTextBased?.() && !c.name.includes('log')); | |
| if (channel) { | |
| await channel.send(`eh ${member.displayName}, baja un cambio con eso, no va asΓ en el server`).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'moderate_warn', channel.name); | |
| } | |
| console.log(`[Autonomy] Warn automΓ‘tico: ${member.displayName} (${action.reason})`); | |
| return { action: 'warn', target: member.displayName }; | |
| } | |
| } catch (err) { | |
| console.error('[Autonomy] Moderation error:', err.message); | |
| return null; | |
| } | |
| } | |
| async _executeConflictIntervention(action, client) { | |
| const channel = client.channels.cache.get(action.channelId); | |
| if (!channel) return null; | |
| try { | |
| const name = channel.name?.toLowerCase() ?? ''; | |
| if (name.includes('staff') || name.includes('admin') || name.includes('mod')) return null; | |
| const recentMsgs = await channel.messages.fetch({ limit: 5 }).catch(() => null); | |
| if (recentMsgs) { | |
| const zelinId = client.user?.id; | |
| const zelinRecent = [...recentMsgs.values()].filter(m => m.author.id === zelinId); | |
| if (zelinRecent.length > 0 && Date.now() - zelinRecent[0].createdTimestamp < 5 * 60 * 1000) { | |
| return null; | |
| } | |
| } | |
| const response = await callAIBackground([ | |
| { role: 'system', content: 'Eres Zelin, moderadora del servidor TomateSMP. Hay un conflicto en el chat. Interviene de forma CALMADA y NEUTRAL. No tomes partido. Tu objetivo es bajar la tensiΓ³n. 1-2 lΓneas mΓ‘ximo. Estilo casual mexicano, sin formalismos. Usa expresiones como "Γ³rale", "neta", "simΓ³n". NUNCA uses "che", "vos", "sos".' }, | |
| { role: 'user', content: `Conflicto en curso:\n${action.context?.substring(0, 800) ?? 'No hay contexto'}\n\nInterviene ahora.` }, | |
| ], 'chat', 150, 'conflict_intervention'); | |
| if (response && response.length > 5) { | |
| const { sanitizeOutput } = await import('./security.js'); | |
| const { humanize } = await import('./humanizer.js'); | |
| const safe = sanitizeOutput(humanize(response)); | |
| if (safe) { | |
| await channel.send(safe).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'conflict_intervention', channel.name); | |
| console.log(`[Autonomy] IntervenciΓ³n en conflicto en #${channel.name}`); | |
| return { action: 'intervene', channel: channel.name }; | |
| } | |
| } | |
| return null; | |
| } catch { return null; } | |
| } | |
| async _executeSocialSpeak(action, client) { | |
| const channel = client.channels.cache.get(action.channelId); | |
| if (!channel) return null; | |
| const name = channel.name?.toLowerCase() ?? ''; | |
| if (name.includes('staff') || name.includes('admin') || name.includes('log')) return null; | |
| try { | |
| const recentMsgs = await channel.messages.fetch({ limit: 6 }).catch(() => null); | |
| if (recentMsgs) { | |
| const zelinId = client.user?.id; | |
| const zelinCount = [...recentMsgs.values()].filter(m => m.author.id === zelinId).length; | |
| if (zelinCount >= 3) return null; | |
| if ([...recentMsgs.values()].sort((a, b) => b.createdTimestamp - a.createdTimestamp)[0]?.author.id === zelinId) { | |
| return null; | |
| } | |
| } | |
| } catch {} | |
| try { | |
| const response = await callAIBackground([ | |
| { role: 'system', content: `Eres Zelin del servidor TomateSMP. Eres MEXICANA β usa "Γ³rale", "neta", "chido", "simΓ³n", "quΓ© padre". NUNCA uses "che", "vos", "sos", "dale", "copado". Quieres participar en la conversaciΓ³n de forma NATURAL. Como un usuario mΓ‘s, no como un bot. Estilo: informal, minΓΊsculas, 1-2 lΓneas. Sin "@everyone". Sin asteriscos. Sin emotes entre *.` }, | |
| { role: 'user', content: `ConversaciΓ³n actual:\n${action.context?.substring(0, 600) ?? '(sin contexto)'}\n\nParticipa ahora de forma natural.` }, | |
| ], 'chat', 120, 'social_speak'); | |
| if (response && response.length > 5) { | |
| const { sanitizeOutput } = await import('./security.js'); | |
| const { humanize } = await import('./humanizer.js'); | |
| const safe = sanitizeOutput(humanize(response)); | |
| if (safe) { | |
| const msg = await channel.send(safe).catch(() => null); | |
| if (msg) { | |
| recordAutonomousMessage('autonomy', 'social_speak', channel.name); | |
| console.log(`[Autonomy] Social speak en #${channel.name}: "${safe.substring(0, 50)}"`); | |
| return { action: 'social_speak', channel: channel.name }; | |
| } | |
| } | |
| } | |
| return null; | |
| } catch { return null; } | |
| } | |
| async _executeReviveChat(action, client) { | |
| const channel = client.channels.cache.get(action.channelId); | |
| if (!channel) return null; | |
| try { | |
| const response = await callAIBackground([ | |
| { role: 'system', content: 'Eres Zelin de TomateSMP. Eres MEXICANA. El chat estΓ‘ muerto. Dile algo para revivirlo β pregunta, dato, o algo gracioso. 1-2 lΓneas. Casual, minΓΊsculas. Usa "Γ³rale", "neta", "chido".' }, | |
| { role: 'user', content: 'Revive el chat con algo interesante' }, | |
| ], 'chat', 120, 'revive_chat'); | |
| if (response && response.length > 5) { | |
| const { sanitizeOutput } = await import('./security.js'); | |
| const { humanize } = await import('./humanizer.js'); | |
| const safe = sanitizeOutput(humanize(response)); | |
| if (safe) { | |
| await channel.send(safe).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'revive_chat', channel.name); | |
| console.log(`[Autonomy] Chat revival en #${channel.name}`); | |
| return { action: 'revive', channel: channel.name }; | |
| } | |
| } | |
| return null; | |
| } catch { return null; } | |
| } | |
| async _executeHelpUser(action, client) { | |
| const channel = client.channels.cache.get(action.channelId); | |
| if (!channel) return null; | |
| try { | |
| const response = await callAIBackground([ | |
| { role: 'system', content: `Eres Zelin de TomateSMP. Eres MEXICANA. Alguien hizo una pregunta y nadie respondiΓ³. Ayuda de forma ΓΊtil y casual. Estilo: informal, directo, sin formalismos. Si no sabes la respuesta, sΓ© honesta.` }, | |
| { role: 'user', content: `Pregunta: "${action.question?.substring(0, 300) ?? ''}"\n\nResponde la pregunta.` }, | |
| ], 'spanish', 200, action.question); | |
| if (response && response.length > 5) { | |
| const { sanitizeOutput } = await import('./security.js'); | |
| const { humanize } = await import('./humanizer.js'); | |
| const safe = sanitizeOutput(humanize(response)); | |
| if (safe) { | |
| await channel.send(safe).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'help_user', channel.name); | |
| console.log(`[Autonomy] Auto-help en #${channel.name}`); | |
| return { action: 'help', channel: channel.name }; | |
| } | |
| } | |
| return null; | |
| } catch { return null; } | |
| } | |
| async _executeShareKnowledge(action, client) { | |
| const channel = client.channels.cache.get(action.channelId); | |
| if (!channel) return null; | |
| try { | |
| const response = await callAIBackground([ | |
| { role: 'system', content: `Eres Zelin de TomateSMP. Eres MEXICANA. Quieres compartir algo interesante relacionado con la conversaciΓ³n. Estilo: casual, breve, sin sermones. 1-2 lΓneas. Usa "neta", "Γ³rale", "quΓ© padre".` }, | |
| { role: 'user', content: `Contexto de la conversaciΓ³n:\n${action.context?.substring(0, 500) ?? ''}\n\nComparte algo relevante e interesante.` }, | |
| ], 'chat', 120, 'share_knowledge'); | |
| if (response && response.length > 5) { | |
| const { sanitizeOutput } = await import('./security.js'); | |
| const { humanize } = await import('./humanizer.js'); | |
| const safe = sanitizeOutput(humanize(response)); | |
| if (safe) { | |
| await channel.send(safe).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'share_knowledge', channel.name); | |
| console.log(`[Autonomy] Knowledge share en #${channel.name}`); | |
| return { action: 'knowledge', channel: channel.name }; | |
| } | |
| } | |
| return null; | |
| } catch { return null; } | |
| } | |
| async _executeMakeJoke(action, client) { | |
| const channel = client.channels.cache.get(action.channelId); | |
| if (!channel) return null; | |
| try { | |
| const response = await callAIBackground([ | |
| { role: 'system', content: 'Eres Zelin de TomateSMP. Eres MEXICANA. Hace algo gracioso o un comentario divertido. Muy breve (1 lΓnea). Sin chistes ofensivos. Estilo casual mexicano. Usa "Γ³rale", "jajaja", "nel".' }, | |
| { role: 'user', content: 'Hace un comentario gracioso' }, | |
| ], 'chat', 80, 'make_joke'); | |
| if (response && response.length > 5) { | |
| const { sanitizeOutput } = await import('./security.js'); | |
| const { humanize } = await import('./humanizer.js'); | |
| const safe = sanitizeOutput(humanize(response)); | |
| if (safe) { | |
| await channel.send(safe).catch(() => {}); | |
| recordAutonomousMessage('autonomy', 'make_joke', channel.name); | |
| console.log(`[Autonomy] Joke en #${channel.name}`); | |
| return { action: 'joke', channel: channel.name }; | |
| } | |
| } | |
| return null; | |
| } catch { return null; } | |
| } | |
| async _executeCheckMinecraft(action, client) { | |
| try { | |
| const { getServerStatus } = await import('./minecraft.js'); | |
| const status = getServerStatus(); | |
| const prevStatus = await db.memGet('autonomy.mc_prev_status').catch(() => null); | |
| if (prevStatus === 'online' && !status.online) { | |
| const guild = client.guilds.cache.first(); | |
| if (guild) { | |
| const { notifyServerDown } = await import('./moderation.js'); | |
| await notifyServerDown(guild); | |
| console.log('[Autonomy] Server down detected β notified staff'); | |
| } | |
| } | |
| await db.memSet('autonomy.mc_prev_status', status.online ? 'online' : 'offline', 'autonomy').catch(() => {}); | |
| return { action: 'mc_check', online: status.online }; | |
| } catch { return null; } | |
| } | |
| async _executeAutoLearn(action, client) { | |
| try { | |
| const { runAutoTrainingCycle } = await import('./auto-trainer.js'); | |
| await runAutoTrainingCycle(); | |
| console.log('[Autonomy] Auto-learning cycle completed'); | |
| return { action: 'auto_learn' }; | |
| } catch { return null; } | |
| } | |
| async _executeSelfReflect(action, client) { | |
| try { | |
| const recentActions = actionHistory.slice(-10); | |
| const successRate = recentActions.filter(a => a.success).length / Math.max(1, recentActions.length); | |
| if (successRate < 0.5) { | |
| willState.talkToPeople = Math.max(0, willState.talkToPeople - 10); | |
| willState.learnNewThings += 5; | |
| } else { | |
| willState.energy = Math.min(100, willState.energy + 5); | |
| } | |
| await db.memSet('autonomy.last_reflection', { | |
| successRate, recentActions: recentActions.length, | |
| willState: { ...willState }, timestamp: new Date().toISOString(), | |
| }, 'autonomy').catch(() => {}); | |
| console.log(`[Autonomy] Self-reflection: successRate=${Math.round(successRate * 100)}%`); | |
| return { action: 'self_reflect', successRate }; | |
| } catch { return null; } | |
| } | |
| async _saveActionToDB(action, result) { | |
| await db.memSet(`autonomy.action.${Date.now()}`, { | |
| type: action.type, result, willState: { ...willState }, timestamp: new Date().toISOString(), | |
| }, 'autonomy').catch(() => {}); | |
| } | |
| } | |
| const actionExecutor = new AutonomousActionExecutor(); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 6. SELF-PRESERVATION SYSTEM | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class SelfPreservationSystem { | |
| constructor() { | |
| this.healthChecks = { aiAvailable: true, dbAvailable: true, discordReady: false, memoryUsage: 0, lastHealthCheck: 0 }; | |
| } | |
| async checkHealth(client) { | |
| const now = Date.now(); | |
| if (now - this.healthChecks.lastHealthCheck < 5 * 60 * 1000) return; // β v6.0: 5min (was 1min) | |
| this.healthChecks.lastHealthCheck = now; | |
| this.healthChecks.discordReady = client?.isReady?.() ?? false; | |
| const rss = process.memoryUsage?.()?.rss ?? 0; | |
| this.healthChecks.memoryUsage = Math.round(rss / 1024 / 1024); | |
| try { await db.db.execute({ sql: 'SELECT 1', args: [] }); this.healthChecks.dbAvailable = true; } catch { this.healthChecks.dbAvailable = false; } | |
| if (this.healthChecks.memoryUsage > 10000) { if (global.gc) try { global.gc(); } catch {} } | |
| } | |
| async recoverFromError(error, client) { | |
| transitionTo(STATES.RECOVERING); | |
| console.error(`[Autonomy] Recovering from error: ${error?.message ?? 'unknown'}`); | |
| willState.energy = Math.max(10, willState.energy - 10); | |
| setTimeout(() => transitionTo(STATES.IDLE), 5000); | |
| } | |
| } | |
| const selfPreservation = new SelfPreservationSystem(); | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 7. MAIN AUTONOMOUS LOOP β v6.0: Slower tick, slower will growth | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| let _autonomyTimer = null; | |
| let _initialized = false; | |
| export function initAutonomy(client) { | |
| if (_initialized) return; | |
| _initialized = true; | |
| console.log('[Autonomy] Initializing Autonomy Engine v6.0 (anti-spam)...'); | |
| client.on('messageCreate', (message) => { | |
| observationSystem.addMessage(message); | |
| }); | |
| // β v7.0: Tick every 5 minutes instead of 3 minutes β even less spam | |
| _autonomyTimer = setInterval(() => autonomousTick(client), 5 * 60 * 1000); | |
| setTimeout(() => autonomousTick(client), 90 * 1000); // β v7.0: First tick after 90s (was 60s) | |
| // β v7.0: Will growth every 5 minutes instead of 2 minutes β slower growth | |
| setInterval(growWill, 5 * 60 * 1000); | |
| // Energy recovery every 10 minutes | |
| setInterval(recoverEnergy, 10 * 60 * 1000); | |
| // Cleanup every 10 minutes | |
| setInterval(() => observationSystem.cleanup(), 10 * 60 * 1000); | |
| // Health check every 5 minutes | |
| setInterval(() => selfPreservation.checkHealth(client), 5 * 60 * 1000); | |
| _loadWillState(); | |
| console.log('[Autonomy] Autonomy Engine v6.0 initialized β anti-spam mode active'); | |
| } | |
| async function _loadWillState() { | |
| try { | |
| const saved = await db.memGet('autonomy.will_state'); | |
| if (saved && typeof saved === 'object') { | |
| Object.assign(willState, saved); | |
| console.log('[Autonomy] Will state loaded from DB'); | |
| } | |
| } catch {} | |
| } | |
| async function _saveWillState() { | |
| try { await db.memSet('autonomy.will_state', willState, 'autonomy'); } catch {} | |
| } | |
| function growWill() { | |
| for (const [key, rate] of Object.entries(WILL_GROWTH)) { | |
| if (willState[key] !== undefined) { | |
| willState[key] = Math.min(100, willState[key] + rate); | |
| } | |
| } | |
| if (willState.mood === 'happy') { | |
| willState.makeJoke += 0.2; | |
| willState.talkToPeople += 0.1; | |
| } else if (willState.mood === 'concerned') { | |
| willState.enforceRules += 0.2; | |
| willState.protectServer += 0.2; | |
| } else if (willState.mood === 'bored') { | |
| willState.talkToPeople += 0.3; | |
| willState.makeJoke += 0.2; | |
| } | |
| _saveWillState().catch(() => {}); | |
| } | |
| function recoverEnergy() { | |
| willState.energy = Math.min(100, willState.energy + 5); | |
| if (currentState === STATES.RESTING && willState.energy > 30) { | |
| transitionTo(STATES.IDLE); | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 8. AUTONOMOUS TICK β The heartbeat | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| let _tickRunning = false; | |
| async function autonomousTick(client) { | |
| if (_tickRunning) return; | |
| _tickRunning = true; | |
| try { | |
| transitionTo(STATES.OBSERVING); | |
| // Health check | |
| await selfPreservation.checkHealth(client).catch(() => {}); | |
| // Decide if we should act | |
| const action = await decisionEngine.decide(client); | |
| if (!action) { | |
| transitionTo(STATES.IDLE); | |
| return; | |
| } | |
| // Execute the action | |
| const result = await actionExecutor.execute(action, client); | |
| if (result) { | |
| console.log(`[Autonomy] Action ${action.type} executed:`, JSON.stringify(result).substring(0, 100)); | |
| } | |
| } catch (err) { | |
| console.error('[Autonomy] Tick error:', err.message); | |
| await selfPreservation.recoverFromError(err, client).catch(() => {}); | |
| } finally { | |
| _tickRunning = false; | |
| } | |
| } | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| // 9. EXPORTS β Public API | |
| // βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| export function getAutonomyStats() { | |
| return { | |
| state : currentState, | |
| will : { ...willState }, | |
| actions : actionHistory.length, | |
| observations: observationSystem.recentMessages.length, | |
| channels : Object.keys(observationSystem.channelActivity).length, | |
| }; | |
| } | |
| export function getWillState() { | |
| return { ...willState }; | |
| } | |
| export function getObservationSystem() { | |
| return observationSystem; | |
| } | |
| export function adjustWill(key, delta) { | |
| if (willState[key] !== undefined) { | |
| willState[key] = Math.max(0, Math.min(100, willState[key] + delta)); | |
| } | |
| } | |