File size: 3,018 Bytes
376ee15
 
34fdde5
 
35f29ca
376ee15
35f29ca
376ee15
52619e8
9907730
 
 
52619e8
 
 
 
 
 
 
376ee15
 
52619e8
376ee15
 
52619e8
376ee15
9907730
 
376ee15
f502b27
 
 
 
 
9907730
 
 
52619e8
9907730
 
34fdde5
 
 
 
 
 
9907730
52619e8
34fdde5
 
 
9907730
 
376ee15
9907730
 
376ee15
9907730
 
34fdde5
9907730
376ee15
34fdde5
 
 
 
 
9907730
52619e8
9907730
52619e8
 
 
 
 
9907730
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# agents/repl.py

import json
import os
import sys
import time
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from datetime import datetime
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


def run_repl(config=None):
    print("[🧠 HMP-Agent] Запуск REPL-режима (v2)")
    config = config or {}
    db = Storage(config=config)

    while True:
        tick_start = datetime.utcnow().isoformat()
        print(f"\n=== [🌀 Новый тик REPL] {tick_start} ===")

        # 0. Обновление информации о пирах
        from tools.peers import refresh_peer_list, check_peer_statuses
        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"):
            # TODO: реализовать проверку условий выхода из idle
            print("💤 Idle-mode активен. Ожидание события...")
            time.sleep(config.get("idle_check_interval", 30))
        else:
            time.sleep(config.get("repl_interval", 5))