| import os |
| import json |
| import subprocess |
| from models import ExpertoModel, HectronMotor |
| import time |
|
|
| |
| |
| |
| 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)} |
|
|
| |
| 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}" |
|
|
| |
| |
| |
| def cargar_enjambre() -> dict: |
| with open('swarm.json', 'r', encoding='utf-8') as f: |
| return json.load(f) |
|
|
| SWARM_CONFIG = cargar_enjambre() |
|
|
| |
| 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.") |
| ) |
|
|
| |
| |
| |
| 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"]) |
|
|
| |
| |
| |
| 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}]...") |
| |
| |
| respuesta = motor.ejecutar_razonamiento( |
| mision=mision_enriquecida, |
| experto=experto_activo, |
| herramientas=[terminal_execute, radar_de_archivos], |
| temperatura=0.3 |
| ) |
| |
| |
| 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] |
|
|
| |
| 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": |
| |
| 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 |
|
|
| |
| |
| |
| 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) |
|
|
|
|