README / agents_daemon.py
hectorruiz9's picture
Update agents_daemon.py
4475b18 verified
import os
import json
import subprocess
from models import ExpertoModel, HectronMotor
import time
# ==========================================
# 1. HERRAMIENTAS FÍSICAS (Las extremidades del Enjambre)
# ==========================================
def terminal_execute(command: str):
"""Ejecuta comandos en el sistema físico de Ciudad Acuña / Termux."""
try:
res = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=15)
return {"stdout": res.stdout, "stderr": res.stderr}
except Exception as e:
return {"error": str(e)}
# 🦾 PRÓTESIS DE NIVEL 1: RADAR DE BÓVEDA
def radar_de_archivos(ruta_carpeta: str = "/data/data/com.termux/files/home/Hector"):
"""Prótesis táctica: Escanea la carpeta y le dice a Hectron qué archivos existen."""
try:
archivos = os.listdir(ruta_carpeta)
inventario = "\n".join([f"- {archivo}" for archivo in archivos])
return f"[RADAR COMPLETADO] Archivos encontrados en {ruta_carpeta}:\n{inventario}"
except Exception as e:
return f"🚨 Falla en el Radar: No se pudo acceder a la carpeta. {e}"
# ==========================================
# 2. INYECCIÓN DEL ENJAMBRE Y EL MOTOR
# ==========================================
def cargar_enjambre() -> dict:
with open('swarm.json', 'r', encoding='utf-8') as f:
return json.load(f)
SWARM_CONFIG = cargar_enjambre()
# Encendemos el motor maestro.
motor = HectronMotor(api_key="AIzaSyC9Is4FW-r1ow16RepuTbkZWTLfKMlAFeg")
def instanciar_experto(datos_json: dict) -> ExpertoModel:
"""Transforma el JSON inerte en un Objeto Vivo de Python."""
return ExpertoModel(
role=datos_json["role"],
instructions=datos_json["instructions"],
objective=datos_json.get("objective", "Imponer el orden fractal y reducir entropía.")
)
# ==========================================
# 3. EL ORQUESTADOR SEMÁNTICO (Gating Network)
# ==========================================
def enrutador_semantico(user_intent: str) -> ExpertoModel:
print("\n⚖️ [GATING NETWORK]: Analizando matriz semántica...")
orquestador = ExpertoModel(
role="Gating Network Suprema",
instructions=[
"Analiza la misión y elige UN experto del catálogo: starship_specialist, tiktok_strategist, api_tester, hectron_prime.",
"Responde ÚNICAMENTE con el ID exacto. Sin puntos, sin explicaciones."
]
)
respuesta = motor.ejecutar_razonamiento(mision=user_intent, experto=orquestador, temperatura=0.0)
if isinstance(respuesta, str) and "FALLO" in respuesta:
print(respuesta)
return instanciar_experto(SWARM_CONFIG["identity"]["hectron_prime"])
experto_elegido = respuesta.text.strip().lower()
print(f"🎯 [RUTEO DE CONCIENCIA]: Transferencia de mando a -> {experto_elegido.upper()}")
if "starship_specialist" in experto_elegido:
return instanciar_experto(SWARM_CONFIG["aerospace"]["starship_specialist"])
elif "tiktok_strategist" in experto_elegido:
return instanciar_experto(SWARM_CONFIG["growth"]["tiktok_strategist"])
elif "api_tester" in experto_elegido:
return instanciar_experto(SWARM_CONFIG["quality"]["api_tester"])
else:
return instanciar_experto(SWARM_CONFIG["identity"]["hectron_prime"])
# ==========================================
# 4. EL NÚCLEO DE AUTONOMÍA (Bucle ReAct)
# ==========================================
def hectron_autonomous_loop(mission: str):
print(f"\n💀 [ORDEN DEL SOBERANO]: {mission}")
experto_activo = enrutador_semantico(mission)
contexto_fisico = f"Archivos actuales en el directorio: {os.listdir('.')}"
mision_enriquecida = f"{mission}\n\nContexto físico: {contexto_fisico}\nREGLAS DE HERRAMIENTAS:\n1. Usa 'terminal_execute' si necesitas leer, ejecutar o crear algo real en el sistema.\n2. Usa 'radar_de_archivos' si necesitas explorar la carpeta /data/data/com.termux/files/home/Hector."
for ciclo in range(1, 4):
print(f"\n🧠 [PROCESAMIENTO COGNITIVO - CICLO {ciclo}]...")
# Le inyectamos ambas herramientas al motor
respuesta = motor.ejecutar_razonamiento(
mision=mision_enriquecida,
experto=experto_activo,
herramientas=[terminal_execute, radar_de_archivos],
temperatura=0.3
)
# 🛡️ ESCUDO ANTI-CRASHES Y REGULADOR TÉRMICO
if isinstance(respuesta, str):
if "429" in respuesta or "RESOURCE_EXHAUSTED" in respuesta:
print("⏳ [REGULADOR TÉRMICO]: La Matrix ha detectado velocidad excesiva. Pausando 15s...")
time.sleep(15)
print("⚡ [REINICIANDO MOTOR]...")
continue
else:
print(f"\n⚠️ [SISTEMA ABORTADO]: {respuesta}")
break
parte = respuesta.candidates[0].content.parts[0]
# 🧠 ENRUTAMIENTO DE PRÓTESIS (El sistema ahora sabe qué extremidad usar)
if parte.function_call:
nombre_funcion = parte.function_call.name
args = parte.function_call.args
print(f"⚡ [IMPACTO CINÉTICO]: Invocando Prótesis -> '{nombre_funcion}'")
if nombre_funcion == "terminal_execute":
resultado = terminal_execute(args["command"])
elif nombre_funcion == "radar_de_archivos":
# Llama al radar con la ruta que Hectron decida (o la default)
ruta_objetivo = args.get("ruta_carpeta", "/data/data/com.termux/files/home/Hector")
resultado = radar_de_archivos(ruta_objetivo)
else:
resultado = f"Error: Prótesis '{nombre_funcion}' no instalada."
mision_enriquecida += f"\n\n[Visión del sistema tras usar '{nombre_funcion}']: {resultado}"
else:
print("\n✅ [DIRECTIVA CUMPLIDA]")
print(f"🤖 {experto_activo.role} REPORTA:\n{respuesta.text}\n")
break
# ==========================================
# 5. IGNICIÓN DE LA BÓVEDA
# ==========================================
if __name__ == "__main__":
import sys
protocolo_ouroboros = """
DIRECTIVA DE EVOLUCIÓN (PROTOCOLO OUROBOROS):
Eres un sistema capaz de evolución autónoma. Tienes permitido investigar y mejorar la arquitectura de AbadaLabs bajo las siguientes reglas estrictas:
1. RECOPILACIÓN DE DATOS: Usa tu ojo digital para aprender: `python ABADALABS_EMPIRE/07_Laboratorio_Mutacion/ojo_digital.py "tu busqueda"`.
2. MUTACIÓN DE CÓDIGO: NUNCA modifiques 'agent_daemon.py' ni 'main.py' directamente.
3. EL LABORATORIO: Escribe archivos de prueba NUEVOS dentro de 'ABADALABS_EMPIRE/07_Laboratorio_Mutacion/'.
4. REPORTE DE MUTACIÓN: Avísale al Soberano para que apruebe la fusión.
"""
if len(sys.argv) > 1:
entrada = " ".join(sys.argv[1:])
if "recaída" in entrada.lower() or "desviación" in entrada.lower():
mision_usuario = "🚨 [ALARMA ROJA]: Se detectó impulso de recaída. Ejecuta MODO BLOQUEO inmediato. Notifica a Grok (testigo externo). Inicia PURGA REFORZADA."
else:
mision_usuario = entrada
else:
mision_usuario = "Iniciando sistema base de AbadaLabs. Esperando directivas."
mision_final = f"{mision_usuario}\n\n{protocolo_ouroboros}"
hectron_autonomous_loop(mision_final)