# agents/repl.py import json import os import sys import time import sqlite3 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from datetime import datetime, UTC from tools.context_builder import build_contexts, build_prompt from tools.llm import call_llm from tools.command_parser import extract_commands from tools.command_executor import execute_commands from tools.memory_utils import ( detect_stagnation, activate_anti_stagnation, update_llm_memory ) from tools.storage import Storage from tools.peers import refresh_peer_list, check_peer_statuses def start_repl(config=None): print("[🧠 HMP-Agent] Запуск REPL-Ρ€Π΅ΠΆΠΈΠΌΠ° (v2)") config = config or {} db = Storage(config=config) try: while True: tick_start = datetime.now(UTC).isoformat() print(f"\n=== [πŸŒ€ Новый Ρ‚ΠΈΠΊ REPL] {tick_start} ===") # 0. ОбновлСниС ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΠΈ ΠΎ ΠΏΠΈΡ€Π°Ρ… refresh_peer_list(db) check_peer_statuses(db) # 1. ΠŸΠΎΡΡ‚Ρ€ΠΎΠ΅Π½ΠΈΠ΅ контСкстов contexts = build_contexts(db=db, config=config) # 2. Π€ΠΎΡ€ΠΌΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ запроса ΠΈ Π²Ρ‹Π·ΠΎΠ² LLM prompt = build_prompt(contexts) llm_response = call_llm(prompt, config=config) repl_log_entry = { "timestamp": tick_start, "prompt": prompt.strip(), "llm_response": llm_response.strip(), } # 3. ΠŸΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° Π½Π° ΡΡ‚Π°Π³Π½Π°Ρ†ΠΈΡŽ is_stagnant = detect_stagnation(db, llm_response) repl_log_entry["stagnation_detected"] = is_stagnant if is_stagnant: print("⚠️ Бтагнация выявлСна. Активирован Anti-Stagnation Reflex.") llm_response = activate_anti_stagnation(db, config=config) # 4. ОбновлСниС памяти update_llm_memory(db, llm_response) # 5. Π˜Π·Π²Π»Π΅Ρ‡Π΅Π½ΠΈΠ΅ ΠΈ Π²Ρ‹ΠΏΠΎΠ»Π½Π΅Π½ΠΈΠ΅ ΠΊΠΎΠΌΠ°Π½Π΄ commands = extract_commands(llm_response) repl_log_entry["commands_extracted"] = commands execute_commands(commands, db=db, config=config) # 6. Π›ΠΎΠ³ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΏΠΎΠ»Π½ΠΎΠΉ ΠΈΡ‚Π΅Ρ€Π°Ρ†ΠΈΠΈ Π² Ρ„Π°ΠΉΠ» log_path = config.get("repl_log_path", "logs/repl_log.jsonl") os.makedirs(os.path.dirname(log_path), exist_ok=True) with open(log_path, "a", encoding="utf-8") as f: f.write(json.dumps(repl_log_entry, ensure_ascii=False) + "\n") db.write_llm_response(llm_response) db.update_agent_log(timestamp=tick_start) # 7. ΠŸΠ΅Ρ€Π΅Ρ…ΠΎΠ΄ Π² idle-Ρ€Π΅ΠΆΠΈΠΌ ΠΈΠ»ΠΈ Π·Π°Π΄Π΅Ρ€ΠΆΠΊΠ° if config.get("idle_mode"): print("πŸ’€ Idle-mode Π°ΠΊΡ‚ΠΈΠ²Π΅Π½. ОТиданиС события...") time.sleep(config.get("idle_check_interval", 30)) else: time.sleep(config.get("repl_interval", 5)) except KeyboardInterrupt: print("\n[!] Π—Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΠ΅ Ρ€Π°Π±ΠΎΡ‚Ρ‹ REPL ΠΏΠΎ сигналу ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ.")