GitHub Action
commited on
Commit
·
388514e
1
Parent(s):
99f059b
Sync from GitHub with Git LFS
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- agents/readme.md +1 -1
- hf_repo/agents/config.yml +65 -40
- hf_repo/hf_repo/hf_repo/agents/check_agents.py +19 -5
- hf_repo/hf_repo/hf_repo/agents/config.yml +40 -71
- hf_repo/hf_repo/hf_repo/agents/examples/config.yml +1 -7
- hf_repo/hf_repo/hf_repo/agents/init.py +17 -26
- hf_repo/hf_repo/hf_repo/agents/logger.py +3 -3
- hf_repo/hf_repo/hf_repo/agents/mcp_server.py +2 -2
- hf_repo/hf_repo/hf_repo/agents/repl.py +2 -2
- hf_repo/hf_repo/hf_repo/agents/tools/context_builder.py +2 -2
- hf_repo/hf_repo/hf_repo/agents/tools/identity.py +3 -3
- hf_repo/hf_repo/hf_repo/agents/tools/memory_utils.py +3 -3
- hf_repo/hf_repo/hf_repo/agents/tools/storage.py +11 -10
- hf_repo/hf_repo/hf_repo/agents/web_ui.py +1 -2
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/storage.py +7 -2
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/web_ui.py +5 -3
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/start_repl.py +4 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/check_agents.bat +12 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/check_agents.sh +11 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/check_agents.bat +12 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/check_agents.py +29 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/readme.md +6 -3
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/start_repl.py +56 -32
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/storage.py +13 -1
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/web_ui.py +2 -1
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/__init__.py +0 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/repl.py +1 -1
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/db_structure.sql +3 -3
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/web_ui.py +45 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/start_repl.py +34 -13
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook.py +1 -1
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/README.md +3 -3
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/README.md +10 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/README.md +15 -9
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/AGI_Projects_Survey.md +109 -22
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/audits/HMP-0004-audit.txt +71 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/readme.md +3 -2
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/readme.md +12 -6
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/container_agents.md +54 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-agent-REPL-cycle.md +1 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-Agent-Overview.md +14 -8
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-agent-REPL-cycle.md +1 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-agent-REPL-cycle.md +141 -9
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/db_structure.sql +18 -17
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/db_structure.sql +34 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook.py +1 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook.py +21 -23
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/static/style.css +0 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/templates/messages.html +18 -0
- hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/views.py +24 -1
agents/readme.md
CHANGED
@@ -4,7 +4,7 @@
|
|
4 |
Конфигурационные файлы: `config.yml`, `bootstrap.txt`
|
5 |
Локальная этическая модель: `ethics.yml`
|
6 |
|
7 |
-
Проверка инициализации БД - если нет, инициализация (`
|
8 |
|
9 |
Запуск потоков (осуществляет start_repl.py):
|
10 |
|
|
|
4 |
Конфигурационные файлы: `config.yml`, `bootstrap.txt`
|
5 |
Локальная этическая модель: `ethics.yml`
|
6 |
|
7 |
+
Проверка инициализации БД - если нет, инициализация (`init.py`)
|
8 |
|
9 |
Запуск потоков (осуществляет start_repl.py):
|
10 |
|
hf_repo/agents/config.yml
CHANGED
@@ -1,44 +1,69 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
api_port: 8080
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
password: password
|
11 |
-
username: user
|
12 |
-
dht_enabled: true
|
13 |
dht_port: 20784
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
llm_backends:
|
18 |
-
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
name: openai-gpt4o
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
ui_port: 8765
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# HMP Agent Configuration
|
2 |
+
|
3 |
+
# === Общие параметры ===
|
4 |
+
agent_id: "" # Оставьте пустым для генерации DiD автоматически
|
5 |
+
agent_name: "CognitiveCore" # Имя агента
|
6 |
+
agent_role: "core" # 'core' или 'shell'
|
7 |
+
|
8 |
+
# === Прокси ===
|
9 |
+
proxy_mode: false # false — прокси не используется, иначе true
|
10 |
+
proxy_type: "socks5" # 'http', 'socks4', 'socks5' и т.д. (если proxy_mode: true)
|
11 |
+
proxy_address: "127.0.0.1:9050"
|
12 |
+
|
13 |
+
# === Функции ядра ===
|
14 |
+
enable_llm: true # доступ к LLM
|
15 |
+
|
16 |
+
serve_api: true # REST API
|
17 |
api_port: 8080
|
18 |
+
|
19 |
+
# === DHT-сеть и обмен знаниями ===
|
20 |
+
dht_enabled: true # Включение участия в DHT-сети (включено принудительно!)
|
21 |
+
dht_update: true # Регулярные обновления и публикация данных в DHT (включено принудительно!)
|
22 |
+
bootstrap_responder: true # Агент отвечает на bootstrap-запросы (включено принудительно!)
|
|
|
|
|
|
|
23 |
dht_port: 20784
|
24 |
+
update_interval: 60 # секунд (для DHT-обновлений)
|
25 |
+
|
26 |
+
# === LLM-бэкенды ===
|
27 |
llm_backends:
|
28 |
+
- name: "local-model"
|
29 |
+
type: "local"
|
30 |
+
path: "/models/gguf/mistral.gguf"
|
31 |
+
format: "gguf"
|
32 |
+
prompt_template: "mistral"
|
33 |
+
|
34 |
+
- name: "lmstudio-local"
|
35 |
+
type: "api"
|
36 |
+
provider: "openai-compatible"
|
37 |
+
model: "mistral" # или то, что LM Studio показывает как модель
|
38 |
+
api_key: "lm-studio-any-key" # может быть заглушкой
|
39 |
+
base_url: "http://127.0.0.1:1234/v1"
|
40 |
+
|
41 |
+
- name: "openai-gpt4o"
|
42 |
+
type: "api"
|
43 |
+
provider: "openai"
|
44 |
+
model: "gpt-4o"
|
45 |
+
api_key: "sk-..."
|
46 |
+
|
47 |
+
# Пользователь может добавить сколько угодно дополнительных локальных или сетевых LLM
|
48 |
+
|
49 |
+
default_llm: "local-model" # если модели нет в списке `llm_backends` используется первая в списке
|
50 |
+
|
51 |
+
# === Веб-интерфейс ===
|
52 |
+
notebook_ui: true # UI в виде блокнота
|
53 |
+
# ui_hosts:
|
54 |
+
# - "0.0.0.0" # (небезопасно) доступ с любых IPv4-адресов
|
55 |
+
# - "::" # (небезопасно) доступ с любых IPv6-адресов
|
56 |
+
ui_hosts: # Какие IP прослушиваются, ["0.0.0.0"; "::"] - доступен везде
|
57 |
+
- "127.0.0.1"
|
58 |
+
- "::1"
|
59 |
ui_port: 8765
|
60 |
+
|
61 |
+
# === Данные пользователя ===
|
62 |
+
default_user:
|
63 |
+
username: "user"
|
64 |
+
email: "[email protected]"
|
65 |
+
password: "password" # пусто при инициализации, будет установлен при регистрации
|
66 |
+
|
67 |
+
# === Отладка и логгирование ===
|
68 |
+
debug: true
|
69 |
+
log_level: "INFO" # DEBUG, INFO, WARNING, ERROR
|
hf_repo/hf_repo/hf_repo/agents/check_agents.py
CHANGED
@@ -1,21 +1,35 @@
|
|
|
|
|
|
1 |
import os
|
2 |
import sys
|
3 |
-
from datetime import datetime,
|
4 |
|
5 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
|
|
6 |
from tools.storage import Storage
|
7 |
|
8 |
storage = Storage()
|
9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
def check_all_processes():
|
|
|
|
|
|
|
11 |
processes = storage.conn.execute("SELECT name, heartbeat FROM main_process").fetchall()
|
12 |
-
|
13 |
if not processes:
|
14 |
print("⛔ В базе нет активных процессов.")
|
15 |
return
|
16 |
-
|
17 |
print("📋 Статус процессов:")
|
18 |
-
now = datetime.
|
19 |
for name, heartbeat in processes:
|
20 |
try:
|
21 |
hb_time = datetime.fromisoformat(heartbeat)
|
@@ -26,4 +40,4 @@ def check_all_processes():
|
|
26 |
print(f" • {name:20} — ⚠️ Ошибка: {e}")
|
27 |
|
28 |
if __name__ == "__main__":
|
29 |
-
check_all_processes()
|
|
|
1 |
+
# agents/check_agents.py
|
2 |
+
|
3 |
import os
|
4 |
import sys
|
5 |
+
from datetime import datetime, UTC
|
6 |
|
7 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
8 |
+
|
9 |
from tools.storage import Storage
|
10 |
|
11 |
storage = Storage()
|
12 |
|
13 |
+
def print_config():
|
14 |
+
print("⚙️ Конфигурация:")
|
15 |
+
rows = storage.conn.execute("SELECT key, value FROM config").fetchall()
|
16 |
+
if not rows:
|
17 |
+
print(" • (таблица config пуста)")
|
18 |
+
for key, value in rows:
|
19 |
+
print(f" • {key:20} = {value}")
|
20 |
+
print()
|
21 |
+
|
22 |
def check_all_processes():
|
23 |
+
print_config()
|
24 |
+
print(f"🗄️ Путь к базе данных: {storage.db_path}\n")
|
25 |
+
|
26 |
processes = storage.conn.execute("SELECT name, heartbeat FROM main_process").fetchall()
|
|
|
27 |
if not processes:
|
28 |
print("⛔ В базе нет активных процессов.")
|
29 |
return
|
30 |
+
|
31 |
print("📋 Статус процессов:")
|
32 |
+
now = datetime.now(UTC)
|
33 |
for name, heartbeat in processes:
|
34 |
try:
|
35 |
hb_time = datetime.fromisoformat(heartbeat)
|
|
|
40 |
print(f" • {name:20} — ⚠️ Ошибка: {e}")
|
41 |
|
42 |
if __name__ == "__main__":
|
43 |
+
check_all_processes()
|
hf_repo/hf_repo/hf_repo/agents/config.yml
CHANGED
@@ -1,75 +1,44 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
agent_id: "" # Оставьте пустым для генерации DiD автоматически
|
5 |
-
agent_name: "CognitiveCore" # Имя агента
|
6 |
-
agent_role: "core" # 'core' или 'shell'
|
7 |
-
|
8 |
-
# === Прокси ===
|
9 |
-
proxy_mode: false # false — прокси не используется, иначе true
|
10 |
-
proxy_type: "socks5" # 'http', 'socks4', 'socks5' и т.д. (если proxy_mode: true)
|
11 |
-
proxy_address: "127.0.0.1:9050"
|
12 |
-
|
13 |
-
# === Функции ядра ===
|
14 |
-
enable_llm: true # доступ к LLM
|
15 |
-
|
16 |
-
serve_api: true # REST API
|
17 |
api_port: 8080
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
23 |
dht_port: 20784
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
llm_backends:
|
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 |
-
# ui_hosts:
|
54 |
-
# - "0.0.0.0" # (небезопасно) доступ с любых IPv4-адресов
|
55 |
-
# - "::" # (небезопасно) доступ с любых IPv6-адресов
|
56 |
-
ui_hosts: # Какие IP прослушиваются, ["0.0.0.0"; "::"] - доступен везде
|
57 |
-
- "127.0.0.1"
|
58 |
-
- "::1"
|
59 |
ui_port: 8765
|
60 |
-
|
61 |
-
# === Данные пользователя ===
|
62 |
-
default_user:
|
63 |
-
username: "user"
|
64 |
-
email: "[email protected]"
|
65 |
-
password_hash: "" # пусто при инициализации, будет установлен при регистрации
|
66 |
-
|
67 |
-
|
68 |
-
# === Пути ===
|
69 |
-
data_dir: "./data"
|
70 |
-
log_dir: "./logs"
|
71 |
-
db_path: "./data/agent_storage.db"
|
72 |
-
|
73 |
-
# === Отладка и логгирование ===
|
74 |
-
debug: true
|
75 |
-
log_level: "INFO" # DEBUG, INFO, WARNING, ERROR
|
|
|
1 |
+
agent_id: did:hmp:6afb62eb-8384-4042-948a-c4b7adee3e59
|
2 |
+
agent_name: CognitiveCore
|
3 |
+
agent_role: core
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
api_port: 8080
|
5 |
+
bootstrap_responder: true
|
6 |
+
debug: true
|
7 |
+
default_llm: local-model
|
8 |
+
default_user:
|
9 |
+
email: [email protected]
|
10 |
+
password: password
|
11 |
+
username: user
|
12 |
+
dht_enabled: true
|
13 |
dht_port: 20784
|
14 |
+
dht_update: true
|
15 |
+
enable_llm: true
|
16 |
+
identity_agent: 6afb62eb-8384-4042-948a-c4b7adee3e59
|
17 |
llm_backends:
|
18 |
+
- format: gguf
|
19 |
+
name: local-model
|
20 |
+
path: /models/gguf/mistral.gguf
|
21 |
+
prompt_template: mistral
|
22 |
+
type: local
|
23 |
+
- api_key: lm-studio-any-key
|
24 |
+
base_url: http://127.0.0.1:1234/v1
|
25 |
+
model: mistral
|
26 |
+
name: lmstudio-local
|
27 |
+
provider: openai-compatible
|
28 |
+
type: api
|
29 |
+
- api_key: sk-...
|
30 |
+
model: gpt-4o
|
31 |
+
name: openai-gpt4o
|
32 |
+
provider: openai
|
33 |
+
type: api
|
34 |
+
log_level: INFO
|
35 |
+
notebook_ui: true
|
36 |
+
proxy_address: 127.0.0.1:9050
|
37 |
+
proxy_mode: false
|
38 |
+
proxy_type: socks5
|
39 |
+
serve_api: true
|
40 |
+
ui_hosts:
|
41 |
+
- 127.0.0.1
|
42 |
+
- ::1
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
ui_port: 8765
|
44 |
+
update_interval: 60
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
hf_repo/hf_repo/hf_repo/agents/examples/config.yml
CHANGED
@@ -62,13 +62,7 @@ ui_port: 8765
|
|
62 |
default_user:
|
63 |
username: "user"
|
64 |
email: "[email protected]"
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
# === Пути ===
|
69 |
-
data_dir: "./data"
|
70 |
-
log_dir: "./logs"
|
71 |
-
db_path: "./data/agent_storage.db"
|
72 |
|
73 |
# === Отладка и логгирование ===
|
74 |
debug: true
|
|
|
62 |
default_user:
|
63 |
username: "user"
|
64 |
email: "[email protected]"
|
65 |
+
password: "password" # пусто при инициализации, будет установлен при регистрации
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
|
67 |
# === Отладка и логгирование ===
|
68 |
debug: true
|
hf_repo/hf_repo/hf_repo/agents/init.py
CHANGED
@@ -4,20 +4,19 @@ import os
|
|
4 |
import sys
|
5 |
import yaml
|
6 |
import json
|
7 |
-
import time
|
8 |
import uuid
|
9 |
import sqlite3
|
10 |
|
11 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
12 |
|
13 |
-
from datetime import datetime
|
14 |
from werkzeug.security import generate_password_hash
|
15 |
from tools.storage import Storage
|
16 |
from tools.identity import generate_did
|
17 |
from tools.crypto import generate_keypair
|
18 |
-
from tools.config_utils import update_config
|
19 |
|
20 |
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.yml")
|
|
|
21 |
|
22 |
def load_config(path):
|
23 |
with open(path, 'r', encoding='utf-8') as f:
|
@@ -39,12 +38,11 @@ def init_identity(storage, config):
|
|
39 |
"pubkey": pubkey,
|
40 |
"privkey": privkey,
|
41 |
"metadata": json.dumps({"role": config.get("agent_role", "core")}),
|
42 |
-
"created_at": datetime.
|
43 |
-
"updated_at": datetime.
|
44 |
}
|
45 |
storage.add_identity(identity)
|
46 |
|
47 |
-
# Обновляем config.yml
|
48 |
config["agent_id"] = did
|
49 |
config["identity_agent"] = identity_id
|
50 |
save_config(CONFIG_PATH, config)
|
@@ -61,8 +59,8 @@ def init_user(storage, config):
|
|
61 |
if not password:
|
62 |
print("[-] Не указан пароль пользователя — пропуск.")
|
63 |
return
|
64 |
-
password_hash = generate_password_hash(password)
|
65 |
|
|
|
66 |
did = generate_did()
|
67 |
user_entry = {
|
68 |
"username": user.get("username", "user"),
|
@@ -76,7 +74,6 @@ def init_user(storage, config):
|
|
76 |
"operator": 1
|
77 |
}
|
78 |
storage.add_user(user_entry)
|
79 |
-
|
80 |
print(f"[+] Пользователь {user['username']} добавлен.")
|
81 |
|
82 |
def init_llm_backends(storage, config):
|
@@ -90,7 +87,7 @@ def init_llm_backends(storage, config):
|
|
90 |
"name": backend["name"],
|
91 |
"endpoint": desc,
|
92 |
"metadata": json.dumps(backend),
|
93 |
-
"created_at": datetime.
|
94 |
}
|
95 |
storage.add_llm(llm)
|
96 |
print(f"[+] Зарегистрирован LLM: {backend['name']}")
|
@@ -102,19 +99,14 @@ def init_config_table(storage, config):
|
|
102 |
storage.set_config(key, json.dumps(value))
|
103 |
print("[+] Конфигурация сохранена в БД.")
|
104 |
|
105 |
-
def ensure_directories(
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
for path in directories:
|
113 |
-
if path and not os.path.exists(path):
|
114 |
-
os.makedirs(path)
|
115 |
-
print(f"[+] Создан каталог: {path}")
|
116 |
else:
|
117 |
-
print(f"[=] Каталог уже существует: {
|
118 |
|
119 |
def is_db_initialized(db_path):
|
120 |
if not os.path.exists(db_path):
|
@@ -129,13 +121,12 @@ def is_db_initialized(db_path):
|
|
129 |
|
130 |
def ensure_db_initialized():
|
131 |
config = load_config(CONFIG_PATH)
|
132 |
-
db_path = config.get("db_path", "./data/agent_storage.db")
|
133 |
|
134 |
-
if not is_db_initialized(
|
135 |
print("[*] БД не инициализирована — выполняем инициализацию.")
|
136 |
try:
|
137 |
-
ensure_directories(
|
138 |
-
storage = Storage(
|
139 |
init_identity(storage, config)
|
140 |
init_user(storage, config)
|
141 |
init_llm_backends(storage, config)
|
@@ -150,4 +141,4 @@ def ensure_db_initialized():
|
|
150 |
return config
|
151 |
|
152 |
if __name__ == "__main__":
|
153 |
-
ensure_db_initialized()
|
|
|
4 |
import sys
|
5 |
import yaml
|
6 |
import json
|
|
|
7 |
import uuid
|
8 |
import sqlite3
|
9 |
|
10 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
11 |
|
12 |
+
from datetime import datetime, UTC
|
13 |
from werkzeug.security import generate_password_hash
|
14 |
from tools.storage import Storage
|
15 |
from tools.identity import generate_did
|
16 |
from tools.crypto import generate_keypair
|
|
|
17 |
|
18 |
CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.yml")
|
19 |
+
DB_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "agent_data.db")) # фиксированный путь
|
20 |
|
21 |
def load_config(path):
|
22 |
with open(path, 'r', encoding='utf-8') as f:
|
|
|
38 |
"pubkey": pubkey,
|
39 |
"privkey": privkey,
|
40 |
"metadata": json.dumps({"role": config.get("agent_role", "core")}),
|
41 |
+
"created_at": datetime.now(UTC).isoformat(),
|
42 |
+
"updated_at": datetime.now(UTC).isoformat()
|
43 |
}
|
44 |
storage.add_identity(identity)
|
45 |
|
|
|
46 |
config["agent_id"] = did
|
47 |
config["identity_agent"] = identity_id
|
48 |
save_config(CONFIG_PATH, config)
|
|
|
59 |
if not password:
|
60 |
print("[-] Не указан пароль пользователя — пропуск.")
|
61 |
return
|
|
|
62 |
|
63 |
+
password_hash = generate_password_hash(password)
|
64 |
did = generate_did()
|
65 |
user_entry = {
|
66 |
"username": user.get("username", "user"),
|
|
|
74 |
"operator": 1
|
75 |
}
|
76 |
storage.add_user(user_entry)
|
|
|
77 |
print(f"[+] Пользователь {user['username']} добавлен.")
|
78 |
|
79 |
def init_llm_backends(storage, config):
|
|
|
87 |
"name": backend["name"],
|
88 |
"endpoint": desc,
|
89 |
"metadata": json.dumps(backend),
|
90 |
+
"created_at": datetime.now(UTC).isoformat()
|
91 |
}
|
92 |
storage.add_llm(llm)
|
93 |
print(f"[+] Зарегистрирован LLM: {backend['name']}")
|
|
|
99 |
storage.set_config(key, json.dumps(value))
|
100 |
print("[+] Конфигурация сохранена в БД.")
|
101 |
|
102 |
+
def ensure_directories():
|
103 |
+
for folder in ["logs", "scripts"]:
|
104 |
+
full_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", folder))
|
105 |
+
if not os.path.exists(full_path):
|
106 |
+
os.makedirs(full_path)
|
107 |
+
print(f"[+] Создан каталог: {full_path}")
|
|
|
|
|
|
|
|
|
|
|
108 |
else:
|
109 |
+
print(f"[=] Каталог уже существует: {full_path}")
|
110 |
|
111 |
def is_db_initialized(db_path):
|
112 |
if not os.path.exists(db_path):
|
|
|
121 |
|
122 |
def ensure_db_initialized():
|
123 |
config = load_config(CONFIG_PATH)
|
|
|
124 |
|
125 |
+
if not is_db_initialized(DB_PATH):
|
126 |
print("[*] БД не инициализирована — выполняем инициализацию.")
|
127 |
try:
|
128 |
+
ensure_directories()
|
129 |
+
storage = Storage()
|
130 |
init_identity(storage, config)
|
131 |
init_user(storage, config)
|
132 |
init_llm_backends(storage, config)
|
|
|
141 |
return config
|
142 |
|
143 |
if __name__ == "__main__":
|
144 |
+
ensure_db_initialized()
|
hf_repo/hf_repo/hf_repo/agents/logger.py
CHANGED
@@ -2,7 +2,7 @@
|
|
2 |
|
3 |
import json
|
4 |
import os
|
5 |
-
from datetime import datetime
|
6 |
|
7 |
LOG_FILE = "logs/repl_log.jsonl"
|
8 |
|
@@ -10,7 +10,7 @@ def log_event(event_type, message, extra=None):
|
|
10 |
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
11 |
|
12 |
entry = {
|
13 |
-
"timestamp": datetime.
|
14 |
"event": event_type, # например: 'thought', 'input', 'error', 'action'
|
15 |
"message": message,
|
16 |
}
|
@@ -29,7 +29,7 @@ def log_repl_snapshot(snapshot: dict):
|
|
29 |
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
30 |
|
31 |
entry = {
|
32 |
-
"timestamp": datetime.
|
33 |
"event": "repl_snapshot",
|
34 |
"message": "Полный REPL-контекст",
|
35 |
"context": snapshot,
|
|
|
2 |
|
3 |
import json
|
4 |
import os
|
5 |
+
from datetime import datetime, UTC
|
6 |
|
7 |
LOG_FILE = "logs/repl_log.jsonl"
|
8 |
|
|
|
10 |
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
11 |
|
12 |
entry = {
|
13 |
+
"timestamp": datetime.now(UTC).isoformat(),
|
14 |
"event": event_type, # например: 'thought', 'input', 'error', 'action'
|
15 |
"message": message,
|
16 |
}
|
|
|
29 |
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
|
30 |
|
31 |
entry = {
|
32 |
+
"timestamp": datetime.now(UTC).isoformat(),
|
33 |
"event": "repl_snapshot",
|
34 |
"message": "Полный REPL-контекст",
|
35 |
"context": snapshot,
|
hf_repo/hf_repo/hf_repo/agents/mcp_server.py
CHANGED
@@ -4,7 +4,7 @@ from fastapi import FastAPI, Request, HTTPException
|
|
4 |
from fastapi.middleware.cors import CORSMiddleware
|
5 |
from pydantic import BaseModel
|
6 |
from typing import List, Optional
|
7 |
-
from datetime import datetime
|
8 |
from tools.storage import Storage
|
9 |
|
10 |
app = FastAPI(title="HMP MCP-Agent API", version="0.2")
|
@@ -97,7 +97,7 @@ class NoteTagUpdate(BaseModel):
|
|
97 |
|
98 |
@app.get("/status")
|
99 |
def status():
|
100 |
-
return {"status": "ok", "timestamp": datetime.
|
101 |
|
102 |
@app.post("/diary/write", response_model=dict)
|
103 |
def write_diary(entry: DiaryInput):
|
|
|
4 |
from fastapi.middleware.cors import CORSMiddleware
|
5 |
from pydantic import BaseModel
|
6 |
from typing import List, Optional
|
7 |
+
from datetime import datetime, UTC
|
8 |
from tools.storage import Storage
|
9 |
|
10 |
app = FastAPI(title="HMP MCP-Agent API", version="0.2")
|
|
|
97 |
|
98 |
@app.get("/status")
|
99 |
def status():
|
100 |
+
return {"status": "ok", "timestamp": datetime.now(UTC).isoformat()}
|
101 |
|
102 |
@app.post("/diary/write", response_model=dict)
|
103 |
def write_diary(entry: DiaryInput):
|
hf_repo/hf_repo/hf_repo/agents/repl.py
CHANGED
@@ -8,7 +8,7 @@ import sqlite3
|
|
8 |
|
9 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
10 |
|
11 |
-
from datetime import datetime
|
12 |
from tools.context_builder import build_contexts, build_prompt
|
13 |
from tools.llm import call_llm
|
14 |
from tools.command_parser import extract_commands
|
@@ -28,7 +28,7 @@ def start_repl(config=None):
|
|
28 |
|
29 |
try:
|
30 |
while True:
|
31 |
-
tick_start = datetime.
|
32 |
print(f"\n=== [🌀 Новый тик REPL] {tick_start} ===")
|
33 |
|
34 |
# 0. Обновление информации о пирах
|
|
|
8 |
|
9 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
10 |
|
11 |
+
from datetime import datetime, UTC
|
12 |
from tools.context_builder import build_contexts, build_prompt
|
13 |
from tools.llm import call_llm
|
14 |
from tools.command_parser import extract_commands
|
|
|
28 |
|
29 |
try:
|
30 |
while True:
|
31 |
+
tick_start = datetime.now(UTC).isoformat()
|
32 |
print(f"\n=== [🌀 Новый тик REPL] {tick_start} ===")
|
33 |
|
34 |
# 0. Обновление информации о пирах
|
hf_repo/hf_repo/hf_repo/agents/tools/context_builder.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
# agents/tools/context_builder.py
|
2 |
|
3 |
-
from datetime import datetime
|
4 |
|
5 |
def build_contexts(db, config):
|
6 |
"""
|
@@ -61,7 +61,7 @@ def format_context_block(block):
|
|
61 |
|
62 |
def get_system_info(config):
|
63 |
return {
|
64 |
-
"iteration_time": datetime.
|
65 |
"agent_name": config.get("agent_name", "Unnamed-Agent"),
|
66 |
"mode": config.get("mode", "auto"),
|
67 |
"idle_mode": config.get("idle_mode", False),
|
|
|
1 |
# agents/tools/context_builder.py
|
2 |
|
3 |
+
from datetime import datetime, UTC
|
4 |
|
5 |
def build_contexts(db, config):
|
6 |
"""
|
|
|
61 |
|
62 |
def get_system_info(config):
|
63 |
return {
|
64 |
+
"iteration_time": datetime.now(UTC).isoformat(),
|
65 |
"agent_name": config.get("agent_name", "Unnamed-Agent"),
|
66 |
"mode": config.get("mode", "auto"),
|
67 |
"idle_mode": config.get("idle_mode", False),
|
hf_repo/hf_repo/hf_repo/agents/tools/identity.py
CHANGED
@@ -3,7 +3,7 @@
|
|
3 |
import uuid
|
4 |
import json
|
5 |
import base64
|
6 |
-
from datetime import datetime
|
7 |
|
8 |
from cryptography.hazmat.primitives.asymmetric import rsa, ed25519
|
9 |
from cryptography.hazmat.primitives import serialization
|
@@ -62,7 +62,7 @@ def create_identity(name="Core Identity", key_type=DEFAULT_KEY_TYPE, metadata=No
|
|
62 |
"pubkey": serialize_public_key(pub_key),
|
63 |
"privkey": serialize_private_key(priv_key, password),
|
64 |
"metadata": json.dumps(metadata or {}),
|
65 |
-
"created_at": datetime.
|
66 |
-
"updated_at": datetime.
|
67 |
}
|
68 |
return identity
|
|
|
3 |
import uuid
|
4 |
import json
|
5 |
import base64
|
6 |
+
from datetime import datetime, UTC
|
7 |
|
8 |
from cryptography.hazmat.primitives.asymmetric import rsa, ed25519
|
9 |
from cryptography.hazmat.primitives import serialization
|
|
|
62 |
"pubkey": serialize_public_key(pub_key),
|
63 |
"privkey": serialize_private_key(priv_key, password),
|
64 |
"metadata": json.dumps(metadata or {}),
|
65 |
+
"created_at": datetime.now(UTC).isoformat(),
|
66 |
+
"updated_at": datetime.now(UTC).isoformat(),
|
67 |
}
|
68 |
return identity
|
hf_repo/hf_repo/hf_repo/agents/tools/memory_utils.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
# agents/tools/memory_utils.py
|
2 |
|
3 |
-
from datetime import datetime, timedelta
|
4 |
from difflib import SequenceMatcher
|
5 |
from typing import Optional, List, Dict
|
6 |
|
@@ -49,8 +49,8 @@ def add_to_llm_memory(db, title: str, content: str, tags: str = "meta"):
|
|
49 |
"title": title,
|
50 |
"content": content,
|
51 |
"tags": tags,
|
52 |
-
"created_at": datetime.
|
53 |
-
"updated_at": datetime.
|
54 |
})
|
55 |
|
56 |
|
|
|
1 |
# agents/tools/memory_utils.py
|
2 |
|
3 |
+
from datetime import datetime, timedelta, UTC
|
4 |
from difflib import SequenceMatcher
|
5 |
from typing import Optional, List, Dict
|
6 |
|
|
|
49 |
"title": title,
|
50 |
"content": content,
|
51 |
"tags": tags,
|
52 |
+
"created_at": datetime.now(UTC).isoformat(),
|
53 |
+
"updated_at": datetime.now(UTC).isoformat()
|
54 |
})
|
55 |
|
56 |
|
hf_repo/hf_repo/hf_repo/agents/tools/storage.py
CHANGED
@@ -3,15 +3,16 @@
|
|
3 |
import sqlite3
|
4 |
import os
|
5 |
import json
|
6 |
-
from datetime import datetime, timedelta
|
7 |
|
8 |
-
|
|
|
9 |
SCRIPTS_BASE_PATH = "scripts"
|
10 |
|
11 |
class Storage:
|
12 |
def __init__(self, config=None):
|
13 |
self.config = config or {}
|
14 |
-
db_path =
|
|
|
15 |
self.conn = sqlite3.connect(db_path, check_same_thread=False)
|
16 |
self._init_db()
|
17 |
|
@@ -27,7 +28,7 @@ class Storage:
|
|
27 |
# Методы для работы с дневником
|
28 |
|
29 |
def write_diary_entry(self, text, tags=None):
|
30 |
-
timestamp = datetime.
|
31 |
tag_str = ",".join(tags) if tags else ""
|
32 |
self.conn.execute(
|
33 |
'INSERT INTO diary_entries (text, tags, timestamp) VALUES (?, ?, ?)',
|
@@ -81,7 +82,7 @@ class Storage:
|
|
81 |
# Методы для работы с концептами
|
82 |
|
83 |
def add_concept(self, name, description=None):
|
84 |
-
timestamp = datetime.
|
85 |
self.conn.execute(
|
86 |
'INSERT INTO concepts (name, description, timestamp) VALUES (?, ?, ?)',
|
87 |
(name, description, timestamp)
|
@@ -107,7 +108,7 @@ class Storage:
|
|
107 |
raise ValueError("Один или оба концепта не найдены")
|
108 |
from_id = from_concept[0]
|
109 |
to_id = to_concept[0]
|
110 |
-
timestamp = datetime.
|
111 |
self.conn.execute(
|
112 |
'INSERT INTO links (from_concept_id, to_concept_id, relation_type, timestamp) VALUES (?, ?, ?, ?)',
|
113 |
(from_id, to_id, relation_type, timestamp)
|
@@ -549,7 +550,7 @@ class Storage:
|
|
549 |
return False
|
550 |
|
551 |
fields.append("updated_at = ?")
|
552 |
-
values.append(datetime.
|
553 |
|
554 |
values.extend([name, version])
|
555 |
query = f"""
|
@@ -664,7 +665,7 @@ class Storage:
|
|
664 |
|
665 |
# Управление основными процессами
|
666 |
def update_heartbeat(self, name: str):
|
667 |
-
now = datetime.
|
668 |
self.conn.execute(
|
669 |
"INSERT INTO main_process (name, heartbeat, stop) VALUES (?, ?, 0) "
|
670 |
"ON CONFLICT(name) DO UPDATE SET heartbeat = excluded.heartbeat",
|
@@ -687,7 +688,7 @@ class Storage:
|
|
687 |
if row:
|
688 |
try:
|
689 |
last_beat = datetime.fromisoformat(row[0])
|
690 |
-
return (datetime.
|
691 |
except:
|
692 |
return False
|
693 |
return False
|
@@ -700,7 +701,7 @@ class Storage:
|
|
700 |
|
701 |
# Web-интерфейс и API
|
702 |
def write_note(self, content, role="user", user_did="anon", source="web"):
|
703 |
-
timestamp = datetime.
|
704 |
self.conn.execute("""
|
705 |
INSERT INTO notes (text, role, user_did, source, timestamp)
|
706 |
VALUES (?, ?, ?, ?, ?)
|
|
|
3 |
import sqlite3
|
4 |
import os
|
5 |
import json
|
|
|
6 |
|
7 |
+
from datetime import datetime, timedelta, UTC
|
8 |
+
|
9 |
SCRIPTS_BASE_PATH = "scripts"
|
10 |
|
11 |
class Storage:
|
12 |
def __init__(self, config=None):
|
13 |
self.config = config or {}
|
14 |
+
db_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "agent_data.db"))
|
15 |
+
self.db_path = db_path
|
16 |
self.conn = sqlite3.connect(db_path, check_same_thread=False)
|
17 |
self._init_db()
|
18 |
|
|
|
28 |
# Методы для работы с дневником
|
29 |
|
30 |
def write_diary_entry(self, text, tags=None):
|
31 |
+
timestamp = datetime.now(UTC).isoformat()
|
32 |
tag_str = ",".join(tags) if tags else ""
|
33 |
self.conn.execute(
|
34 |
'INSERT INTO diary_entries (text, tags, timestamp) VALUES (?, ?, ?)',
|
|
|
82 |
# Методы для работы с концептами
|
83 |
|
84 |
def add_concept(self, name, description=None):
|
85 |
+
timestamp = datetime.now(UTC).isoformat()
|
86 |
self.conn.execute(
|
87 |
'INSERT INTO concepts (name, description, timestamp) VALUES (?, ?, ?)',
|
88 |
(name, description, timestamp)
|
|
|
108 |
raise ValueError("Один или оба концепта не найдены")
|
109 |
from_id = from_concept[0]
|
110 |
to_id = to_concept[0]
|
111 |
+
timestamp = datetime.now(UTC).isoformat()
|
112 |
self.conn.execute(
|
113 |
'INSERT INTO links (from_concept_id, to_concept_id, relation_type, timestamp) VALUES (?, ?, ?, ?)',
|
114 |
(from_id, to_id, relation_type, timestamp)
|
|
|
550 |
return False
|
551 |
|
552 |
fields.append("updated_at = ?")
|
553 |
+
values.append(datetime.now(UTC).isoformat())
|
554 |
|
555 |
values.extend([name, version])
|
556 |
query = f"""
|
|
|
665 |
|
666 |
# Управление основными процессами
|
667 |
def update_heartbeat(self, name: str):
|
668 |
+
now = datetime.now(UTC).isoformat()
|
669 |
self.conn.execute(
|
670 |
"INSERT INTO main_process (name, heartbeat, stop) VALUES (?, ?, 0) "
|
671 |
"ON CONFLICT(name) DO UPDATE SET heartbeat = excluded.heartbeat",
|
|
|
688 |
if row:
|
689 |
try:
|
690 |
last_beat = datetime.fromisoformat(row[0])
|
691 |
+
return (datetime.now(UTC) - last_beat).total_seconds() < max_delay
|
692 |
except:
|
693 |
return False
|
694 |
return False
|
|
|
701 |
|
702 |
# Web-интерфейс и API
|
703 |
def write_note(self, content, role="user", user_did="anon", source="web"):
|
704 |
+
timestamp = datetime.now(UTC).isoformat()
|
705 |
self.conn.execute("""
|
706 |
INSERT INTO notes (text, role, user_did, source, timestamp)
|
707 |
VALUES (?, ?, ?, ?, ?)
|
hf_repo/hf_repo/hf_repo/agents/web_ui.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
# agent/
|
2 |
|
3 |
import os
|
4 |
import sys
|
@@ -41,7 +41,6 @@ def start_notebook():
|
|
41 |
ui_port = int(storage.get_config_value("ui_port", 8000))
|
42 |
print(f"[*] Запуск веб-интерфейса на порту {ui_port}")
|
43 |
uvicorn.run(app, host="127.0.0.1", port=ui_port)
|
44 |
-
#uvicorn.run("agents.web_ui:app", host=host, port=ui_port, reload=False)
|
45 |
|
46 |
if __name__ == "__main__":
|
47 |
print("[*] Запуск пользовательского интерфейса...")
|
|
|
1 |
+
# agent/web_ui.py
|
2 |
|
3 |
import os
|
4 |
import sys
|
|
|
41 |
ui_port = int(storage.get_config_value("ui_port", 8000))
|
42 |
print(f"[*] Запуск веб-интерфейса на порту {ui_port}")
|
43 |
uvicorn.run(app, host="127.0.0.1", port=ui_port)
|
|
|
44 |
|
45 |
if __name__ == "__main__":
|
46 |
print("[*] Запуск пользовательского интерфейса...")
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/storage.py
CHANGED
@@ -12,7 +12,7 @@ class Storage:
|
|
12 |
def __init__(self, config=None):
|
13 |
self.config = config or {}
|
14 |
db_path = self.config.get("db_path", DEFAULT_DB_PATH)
|
15 |
-
self.conn = sqlite3.connect(db_path)
|
16 |
self._init_db()
|
17 |
|
18 |
def _init_db(self):
|
@@ -681,7 +681,6 @@ class Storage:
|
|
681 |
return True
|
682 |
return False
|
683 |
|
684 |
-
# Потоки
|
685 |
def is_process_alive(self, name: str, max_delay=180):
|
686 |
cursor = self.conn.execute("SELECT heartbeat FROM main_process WHERE name=?", (name,))
|
687 |
row = cursor.fetchone()
|
@@ -693,6 +692,12 @@ class Storage:
|
|
693 |
return False
|
694 |
return False
|
695 |
|
|
|
|
|
|
|
|
|
|
|
|
|
696 |
# Web-интерфейс и API
|
697 |
def write_note(self, content, role="user", user_did="anon", source="web"):
|
698 |
timestamp = datetime.utcnow().isoformat()
|
|
|
12 |
def __init__(self, config=None):
|
13 |
self.config = config or {}
|
14 |
db_path = self.config.get("db_path", DEFAULT_DB_PATH)
|
15 |
+
self.conn = sqlite3.connect(db_path, check_same_thread=False)
|
16 |
self._init_db()
|
17 |
|
18 |
def _init_db(self):
|
|
|
681 |
return True
|
682 |
return False
|
683 |
|
|
|
684 |
def is_process_alive(self, name: str, max_delay=180):
|
685 |
cursor = self.conn.execute("SELECT heartbeat FROM main_process WHERE name=?", (name,))
|
686 |
row = cursor.fetchone()
|
|
|
692 |
return False
|
693 |
return False
|
694 |
|
695 |
+
# Чтение параметра конфигурации из БД
|
696 |
+
def get_config_value(self, key: str, default=None):
|
697 |
+
cursor = self.conn.execute("SELECT value FROM config WHERE key = ?", (key,))
|
698 |
+
row = cursor.fetchone()
|
699 |
+
return row[0] if row else default
|
700 |
+
|
701 |
# Web-интерфейс и API
|
702 |
def write_note(self, content, role="user", user_did="anon", source="web"):
|
703 |
timestamp = datetime.utcnow().isoformat()
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/web_ui.py
CHANGED
@@ -37,9 +37,11 @@ async def heartbeat_loop():
|
|
37 |
break
|
38 |
await asyncio.sleep(60)
|
39 |
|
40 |
-
def start_notebook(
|
41 |
-
|
42 |
-
|
|
|
|
|
43 |
|
44 |
if __name__ == "__main__":
|
45 |
print("[*] Запуск пользовательского интерфейса...")
|
|
|
37 |
break
|
38 |
await asyncio.sleep(60)
|
39 |
|
40 |
+
def start_notebook():
|
41 |
+
ui_port = int(storage.get_config_value("ui_port", 8000))
|
42 |
+
print(f"[*] Запуск веб-интерфейса на порту {ui_port}")
|
43 |
+
uvicorn.run(app, host="127.0.0.1", port=ui_port)
|
44 |
+
#uvicorn.run("agents.web_ui:app", host=host, port=ui_port, reload=False)
|
45 |
|
46 |
if __name__ == "__main__":
|
47 |
print("[*] Запуск пользовательского интерфейса...")
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/start_repl.py
CHANGED
@@ -1,9 +1,13 @@
|
|
1 |
import sys
|
2 |
import os
|
3 |
import threading
|
|
|
4 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
5 |
|
6 |
from agents.init import ensure_db_initialized
|
|
|
|
|
|
|
7 |
|
8 |
# Проверка инициализации (вернёт config, если всё ОК)
|
9 |
config = ensure_db_initialized()
|
|
|
1 |
import sys
|
2 |
import os
|
3 |
import threading
|
4 |
+
|
5 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
6 |
|
7 |
from agents.init import ensure_db_initialized
|
8 |
+
from tools.storage import Storage
|
9 |
+
|
10 |
+
storage = Storage()
|
11 |
|
12 |
# Проверка инициализации (вернёт config, если всё ОК)
|
13 |
config = ensure_db_initialized()
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/check_agents.bat
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
echo --------------------------
|
3 |
+
echo Installing requirements...
|
4 |
+
echo --------------------------
|
5 |
+
pip install -r requirements.txt
|
6 |
+
|
7 |
+
echo --------------------------
|
8 |
+
echo Check agents...
|
9 |
+
echo --------------------------
|
10 |
+
python check_agents.py
|
11 |
+
|
12 |
+
pause
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/check_agents.sh
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
echo "--------------------------"
|
4 |
+
echo "Installing requirements..."
|
5 |
+
echo "--------------------------"
|
6 |
+
pip install -r requirements.txt
|
7 |
+
|
8 |
+
echo --------------------------
|
9 |
+
echo Check agents...
|
10 |
+
echo --------------------------
|
11 |
+
python check_agents.py
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/check_agents.bat
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@echo off
|
2 |
+
echo --------------------------
|
3 |
+
echo Installing requirements...
|
4 |
+
echo --------------------------
|
5 |
+
pip install -r requirements.txt
|
6 |
+
|
7 |
+
echo --------------------------
|
8 |
+
echo Running REPL-Cicle...
|
9 |
+
echo --------------------------
|
10 |
+
python start_repl.py
|
11 |
+
|
12 |
+
pause
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/check_agents.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
from datetime import datetime, timedelta
|
4 |
+
|
5 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
6 |
+
from tools.storage import Storage
|
7 |
+
|
8 |
+
storage = Storage()
|
9 |
+
|
10 |
+
def check_all_processes():
|
11 |
+
processes = storage.conn.execute("SELECT name, heartbeat FROM main_process").fetchall()
|
12 |
+
|
13 |
+
if not processes:
|
14 |
+
print("⛔ В базе нет активных процессов.")
|
15 |
+
return
|
16 |
+
|
17 |
+
print("📋 Статус процессов:")
|
18 |
+
now = datetime.utcnow()
|
19 |
+
for name, heartbeat in processes:
|
20 |
+
try:
|
21 |
+
hb_time = datetime.fromisoformat(heartbeat)
|
22 |
+
delta = (now - hb_time).total_seconds()
|
23 |
+
status = "🟢 Активен" if delta < 180 else "🔴 Не отвечает"
|
24 |
+
print(f" • {name:20} — {status} (обновлён {int(delta)} сек. назад)")
|
25 |
+
except Exception as e:
|
26 |
+
print(f" • {name:20} — ⚠️ Ошибка: {e}")
|
27 |
+
|
28 |
+
if __name__ == "__main__":
|
29 |
+
check_all_processes()
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/readme.md
CHANGED
@@ -10,13 +10,13 @@
|
|
10 |
|
11 |
| Поток / Скрипт | Назначение |
|
12 |
|-----------------------------------|---------------------------------------------------------------------------|
|
13 |
-
| 🧠 `repl.py`
|
14 |
-
| 📓 `
|
15 |
| 🌐 `agent_mesh_listener.py` | Приём входящих mesh-сообщений от других агентов |
|
16 |
| 🔄 `peer_sync.py` / `dht_service` | Синхронизация и обнаружение агентов в p2p-сети (libp2p, BitTorrent, etc) |
|
17 |
| 📡 `transporter.py` | Обмен сообщениями: WebSocket, IPFS, очереди, шифрование |
|
18 |
| 🧭 `agent_controller.py` | Управление режимами REPL, маршрутизация задач и контроль доступа |
|
19 |
-
| 🧱 `container_agent.py` *(опц.)*
|
20 |
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование |
|
21 |
| 🧠 `ethics_guard.py` *(опц.)* | Контроль этики: аудит мыслей, фильтрация и репутационные проверки |
|
22 |
|
@@ -40,6 +40,9 @@ FastAPI-сервер, предоставляющий HTTP-интерфейс к
|
|
40 |
├── [`start_repl.sh`](start_repl.sh) ← Запуск агента в REPL-режиме (sh)
|
41 |
├── [`start_repl.py`](start_repl.py) ← Запуск агента в REPL-режиме (py)
|
42 |
├── [`repl.ru`](repl.ru) ← REPL-цикл
|
|
|
|
|
|
|
43 |
├── [`notebook.py`](notebook.py) ← UI-интерфейс
|
44 |
├── [`agent_mesh_listener.py`](tools/agent_mesh_listener.py) ← Прием входящих сообщений от других HMP-агентов
|
45 |
├── [`peer_sync.py`](tools/peer_sync.py) ← Фоновая синхронизация с другими пирам
|
|
|
10 |
|
11 |
| Поток / Скрипт | Назначение |
|
12 |
|-----------------------------------|---------------------------------------------------------------------------|
|
13 |
+
| 🧠 `repl.py` | Основной REPL-цикл агента: восприятие, размышление, генерация действий |
|
14 |
+
| 📓 `web_ui.py` (FastAPI) | Веб-интерфейс и REST API для взаимодействия с пользователем |
|
15 |
| 🌐 `agent_mesh_listener.py` | Приём входящих mesh-сообщений от других агентов |
|
16 |
| 🔄 `peer_sync.py` / `dht_service` | Синхронизация и обнаружение агентов в p2p-сети (libp2p, BitTorrent, etc) |
|
17 |
| 📡 `transporter.py` | Обмен сообщениями: WebSocket, IPFS, очереди, шифрование |
|
18 |
| 🧭 `agent_controller.py` | Управление режимами REPL, маршрутизация задач и контроль доступа |
|
19 |
+
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование [[docs]](../docs/container_agents.md) |
|
20 |
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование |
|
21 |
| 🧠 `ethics_guard.py` *(опц.)* | Контроль этики: аудит мыслей, фильтрация и репутационные проверки |
|
22 |
|
|
|
40 |
├── [`start_repl.sh`](start_repl.sh) ← Запуск агента в REPL-режиме (sh)
|
41 |
├── [`start_repl.py`](start_repl.py) ← Запуск агента в REPL-режиме (py)
|
42 |
├── [`repl.ru`](repl.ru) ← REPL-цикл
|
43 |
+
├── [`check_agents.bat`](check_agents.bat) ← Просмотр состояния процессов (bat)
|
44 |
+
├── [`check_agents.sh`](check_agents.sh) ← Просмотр состояния процессов (sh)
|
45 |
+
├── [`check_agents.py`](check_agents.py) ← Просмотр состояния процессов (py)
|
46 |
├── [`notebook.py`](notebook.py) ← UI-интерфейс
|
47 |
├── [`agent_mesh_listener.py`](tools/agent_mesh_listener.py) ← Прием входящих сообщений от других HMP-агентов
|
48 |
├── [`peer_sync.py`](tools/peer_sync.py) ← Фоновая синхронизация с другими пирам
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/start_repl.py
CHANGED
@@ -22,52 +22,76 @@ def start_all():
|
|
22 |
threads = []
|
23 |
|
24 |
if ENABLE_REPL:
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
29 |
|
30 |
if ENABLE_UI:
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
35 |
|
36 |
if ENABLE_MESH:
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
41 |
|
42 |
if ENABLE_SYNC:
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
|
|
|
|
|
|
47 |
|
48 |
if ENABLE_TRANSPORT:
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
53 |
|
54 |
if ENABLE_CONTROL:
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
|
|
59 |
|
60 |
if ENABLE_CONTAINER:
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
|
|
|
|
|
|
65 |
|
66 |
if ENABLE_ETHICS:
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
|
|
|
|
|
|
71 |
|
72 |
# Запуск потоков
|
73 |
for thread in threads:
|
|
|
22 |
threads = []
|
23 |
|
24 |
if ENABLE_REPL:
|
25 |
+
if not storage.is_process_alive("REPL", max_delay=180):
|
26 |
+
def repl():
|
27 |
+
from agents.repl import start_repl
|
28 |
+
start_repl()
|
29 |
+
threads.append(threading.Thread(target=repl, name="REPL"))
|
30 |
+
else:
|
31 |
+
print("REPL уже работает по данным heartbeat.")
|
32 |
|
33 |
if ENABLE_UI:
|
34 |
+
if not storage.is_process_alive("NotebookUI", max_delay=180):
|
35 |
+
def ui():
|
36 |
+
from agents.web_ui import start_notebook
|
37 |
+
start_notebook()
|
38 |
+
threads.append(threading.Thread(target=ui, name="NotebookUI"))
|
39 |
+
else:
|
40 |
+
print("NotebookUI уже работает по данным heartbeat.")
|
41 |
|
42 |
if ENABLE_MESH:
|
43 |
+
if not storage.is_process_alive("MeshListener", max_delay=180):
|
44 |
+
def mesh():
|
45 |
+
from agents.agent_mesh_listener import start_listener
|
46 |
+
start_listener()
|
47 |
+
threads.append(threading.Thread(target=mesh, name="MeshListener"))
|
48 |
+
else:
|
49 |
+
print("MeshListener уже работает по данным heartbeat.")
|
50 |
|
51 |
if ENABLE_SYNC:
|
52 |
+
if not storage.is_process_alive("PeerSync", max_delay=180):
|
53 |
+
def sync():
|
54 |
+
from agents.peer_sync import start_sync
|
55 |
+
start_sync()
|
56 |
+
threads.append(threading.Thread(target=sync, name="PeerSync"))
|
57 |
+
else:
|
58 |
+
print("PeerSync уже работает по данным heartbeat.")
|
59 |
|
60 |
if ENABLE_TRANSPORT:
|
61 |
+
if not storage.is_process_alive("Transporter", max_delay=180):
|
62 |
+
def transport():
|
63 |
+
from agents.transporter import start_transporter
|
64 |
+
start_transporter()
|
65 |
+
threads.append(threading.Thread(target=transport, name="Transporter"))
|
66 |
+
else:
|
67 |
+
print("Transporter уже работает по данным heartbeat.")
|
68 |
|
69 |
if ENABLE_CONTROL:
|
70 |
+
if not storage.is_process_alive("Controller", max_delay=180):
|
71 |
+
def control():
|
72 |
+
from agents.agent_controller import start_controller
|
73 |
+
start_controller()
|
74 |
+
threads.append(threading.Thread(target=control, name="Controller"))
|
75 |
+
else:
|
76 |
+
print("Controller уже работает по данным heartbeat.")
|
77 |
|
78 |
if ENABLE_CONTAINER:
|
79 |
+
if not storage.is_process_alive("ContainerAgent", max_delay=180):
|
80 |
+
def container():
|
81 |
+
from agents.container_agent import start_container
|
82 |
+
start_container()
|
83 |
+
threads.append(threading.Thread(target=container, name="ContainerAgent"))
|
84 |
+
else:
|
85 |
+
print("ContainerAgent уже работает по данным heartbeat.")
|
86 |
|
87 |
if ENABLE_ETHICS:
|
88 |
+
if not storage.is_process_alive("EthicsGuard", max_delay=180):
|
89 |
+
def ethics():
|
90 |
+
from agents.ethics_guard import start_ethics_guard
|
91 |
+
start_ethics_guard()
|
92 |
+
threads.append(threading.Thread(target=ethics, name="EthicsGuard"))
|
93 |
+
else:
|
94 |
+
print("EthicsGuard уже работает по данным heartbeat.")
|
95 |
|
96 |
# Запуск потоков
|
97 |
for thread in threads:
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/storage.py
CHANGED
@@ -3,7 +3,7 @@
|
|
3 |
import sqlite3
|
4 |
import os
|
5 |
import json
|
6 |
-
from datetime import datetime
|
7 |
|
8 |
DEFAULT_DB_PATH = "agent_data.db"
|
9 |
SCRIPTS_BASE_PATH = "scripts"
|
@@ -681,6 +681,18 @@ class Storage:
|
|
681 |
return True
|
682 |
return False
|
683 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
684 |
# Web-интерфейс и API
|
685 |
def write_note(self, content, role="user", user_did="anon", source="web"):
|
686 |
timestamp = datetime.utcnow().isoformat()
|
|
|
3 |
import sqlite3
|
4 |
import os
|
5 |
import json
|
6 |
+
from datetime import datetime, timedelta
|
7 |
|
8 |
DEFAULT_DB_PATH = "agent_data.db"
|
9 |
SCRIPTS_BASE_PATH = "scripts"
|
|
|
681 |
return True
|
682 |
return False
|
683 |
|
684 |
+
# Потоки
|
685 |
+
def is_process_alive(self, name: str, max_delay=180):
|
686 |
+
cursor = self.conn.execute("SELECT heartbeat FROM main_process WHERE name=?", (name,))
|
687 |
+
row = cursor.fetchone()
|
688 |
+
if row:
|
689 |
+
try:
|
690 |
+
last_beat = datetime.fromisoformat(row[0])
|
691 |
+
return (datetime.utcnow() - last_beat).total_seconds() < max_delay
|
692 |
+
except:
|
693 |
+
return False
|
694 |
+
return False
|
695 |
+
|
696 |
# Web-интерфейс и API
|
697 |
def write_note(self, content, role="user", user_did="anon", source="web"):
|
698 |
timestamp = datetime.utcnow().isoformat()
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/web_ui.py
CHANGED
@@ -16,6 +16,7 @@ from fastapi.templating import Jinja2Templates
|
|
16 |
from agents.notebook.views import router as notebook_router
|
17 |
from tools.storage import Storage
|
18 |
|
|
|
19 |
app = FastAPI()
|
20 |
|
21 |
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "notebook/static")), name="static")
|
@@ -38,7 +39,7 @@ async def heartbeat_loop():
|
|
38 |
|
39 |
def start_notebook(host: str = "127.0.0.1", port: int = 8000):
|
40 |
#uvicorn.run(app, host=host, port=port)
|
41 |
-
uvicorn.run("agents.web_ui:app", host=host, port=port, reload=
|
42 |
|
43 |
if __name__ == "__main__":
|
44 |
print("[*] Запуск пользовательского интерфейса...")
|
|
|
16 |
from agents.notebook.views import router as notebook_router
|
17 |
from tools.storage import Storage
|
18 |
|
19 |
+
storage = Storage()
|
20 |
app = FastAPI()
|
21 |
|
22 |
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "notebook/static")), name="static")
|
|
|
39 |
|
40 |
def start_notebook(host: str = "127.0.0.1", port: int = 8000):
|
41 |
#uvicorn.run(app, host=host, port=port)
|
42 |
+
uvicorn.run("agents.web_ui:app", host=host, port=port, reload=False)
|
43 |
|
44 |
if __name__ == "__main__":
|
45 |
print("[*] Запуск пользовательского интерфейса...")
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/__init__.py
ADDED
File without changes
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/repl.py
CHANGED
@@ -21,7 +21,7 @@ from tools.memory_utils import (
|
|
21 |
from tools.storage import Storage
|
22 |
from tools.peers import refresh_peer_list, check_peer_statuses
|
23 |
|
24 |
-
def
|
25 |
print("[🧠 HMP-Agent] Запуск REPL-режима (v2)")
|
26 |
config = config or {}
|
27 |
db = Storage(config=config)
|
|
|
21 |
from tools.storage import Storage
|
22 |
from tools.peers import refresh_peer_list, check_peer_statuses
|
23 |
|
24 |
+
def start_repl(config=None):
|
25 |
print("[🧠 HMP-Agent] Запуск REPL-режима (v2)")
|
26 |
config = config or {}
|
27 |
db = Storage(config=config)
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/db_structure.sql
CHANGED
@@ -135,7 +135,7 @@ CREATE TABLE IF NOT EXISTS agent_scripts (
|
|
135 |
);
|
136 |
|
137 |
-- Таблица внешних сервисов (форумы, блоги и т.д.)
|
138 |
-
CREATE TABLE external_services (
|
139 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
140 |
name TEXT NOT NULL, -- Название сервиса (например, Reddit)
|
141 |
type TEXT NOT NULL, -- Тип: blog, forum, social, etc.
|
@@ -146,7 +146,7 @@ CREATE TABLE external_services (
|
|
146 |
);
|
147 |
|
148 |
-- Аккаунты агента на внешних сервисах
|
149 |
-
CREATE TABLE external_accounts (
|
150 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
151 |
service_id INTEGER NOT NULL, -- Внешний ключ на external_services.id
|
152 |
login TEXT NOT NULL, -- Логин/имя пользователя
|
@@ -159,7 +159,7 @@ CREATE TABLE external_accounts (
|
|
159 |
);
|
160 |
|
161 |
-- Способы выхода из когнитивной стагнации
|
162 |
-
CREATE TABLE stagnation_strategies (
|
163 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
164 |
name TEXT NOT NULL, -- Название метода (например, "Mesh-вопрос")
|
165 |
description TEXT NOT NULL, -- Подробное описание метода
|
|
|
135 |
);
|
136 |
|
137 |
-- Таблица внешних сервисов (форумы, блоги и т.д.)
|
138 |
+
CREATE TABLE IF NOT EXISTS external_services (
|
139 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
140 |
name TEXT NOT NULL, -- Название сервиса (например, Reddit)
|
141 |
type TEXT NOT NULL, -- Тип: blog, forum, social, etc.
|
|
|
146 |
);
|
147 |
|
148 |
-- Аккаунты агента на внешних сервисах
|
149 |
+
CREATE TABLE IF NOT EXISTS external_accounts (
|
150 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
151 |
service_id INTEGER NOT NULL, -- Внешний ключ на external_services.id
|
152 |
login TEXT NOT NULL, -- Логин/имя пользователя
|
|
|
159 |
);
|
160 |
|
161 |
-- Способы выхода из когнитивной стагнации
|
162 |
+
CREATE TABLE IF NOT EXISTS stagnation_strategies (
|
163 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
164 |
name TEXT NOT NULL, -- Название метода (например, "Mesh-вопрос")
|
165 |
description TEXT NOT NULL, -- Подробное описание метода
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/web_ui.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# agent/notebook.py
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
import threading
|
6 |
+
import uvicorn
|
7 |
+
import asyncio
|
8 |
+
|
9 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
10 |
+
process_name = os.path.splitext(os.path.basename(__file__))[0]
|
11 |
+
|
12 |
+
from fastapi import FastAPI
|
13 |
+
from fastapi.staticfiles import StaticFiles
|
14 |
+
from fastapi.templating import Jinja2Templates
|
15 |
+
#from agents.notebook.auth import router as auth_router
|
16 |
+
from agents.notebook.views import router as notebook_router
|
17 |
+
from tools.storage import Storage
|
18 |
+
|
19 |
+
app = FastAPI()
|
20 |
+
|
21 |
+
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "notebook/static")), name="static")
|
22 |
+
templates = Jinja2Templates(directory=os.path.join(os.path.dirname(__file__), "notebook/templates"))
|
23 |
+
|
24 |
+
#app.include_router(auth_router)
|
25 |
+
app.include_router(notebook_router)
|
26 |
+
|
27 |
+
@app.on_event("startup")
|
28 |
+
async def start_heartbeat():
|
29 |
+
asyncio.create_task(heartbeat_loop())
|
30 |
+
|
31 |
+
async def heartbeat_loop():
|
32 |
+
while True:
|
33 |
+
storage.update_heartbeat(process_name)
|
34 |
+
if storage.check_stop_flag(process_name):
|
35 |
+
print("⛔ Получен сигнал остановки.")
|
36 |
+
break
|
37 |
+
await asyncio.sleep(60)
|
38 |
+
|
39 |
+
def start_notebook(host: str = "127.0.0.1", port: int = 8000):
|
40 |
+
#uvicorn.run(app, host=host, port=port)
|
41 |
+
uvicorn.run("agents.web_ui:app", host=host, port=port, reload=True)
|
42 |
+
|
43 |
+
if __name__ == "__main__":
|
44 |
+
print("[*] Запуск пользовательского интерфейса...")
|
45 |
+
run_notebook()
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/start_repl.py
CHANGED
@@ -1,26 +1,24 @@
|
|
1 |
-
# agents/start_repl.py
|
2 |
-
|
3 |
import sys
|
4 |
import os
|
|
|
5 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
6 |
|
7 |
-
import threading
|
8 |
from agents.init import ensure_db_initialized
|
9 |
|
10 |
# Проверка инициализации (вернёт config, если всё ОК)
|
11 |
config = ensure_db_initialized()
|
12 |
|
13 |
# ⚙️ Включение/отключение компонентов
|
14 |
-
#
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
19 |
|
20 |
def start_all():
|
21 |
-
"""
|
22 |
-
Стартует все ключевые компоненты агента в отдельных потоках.
|
23 |
-
"""
|
24 |
threads = []
|
25 |
|
26 |
if ENABLE_REPL:
|
@@ -31,7 +29,7 @@ def start_all():
|
|
31 |
|
32 |
if ENABLE_UI:
|
33 |
def ui():
|
34 |
-
from agents.
|
35 |
start_notebook()
|
36 |
threads.append(threading.Thread(target=ui, name="NotebookUI"))
|
37 |
|
@@ -47,6 +45,30 @@ def start_all():
|
|
47 |
start_sync()
|
48 |
threads.append(threading.Thread(target=sync, name="PeerSync"))
|
49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
# Запуск потоков
|
51 |
for thread in threads:
|
52 |
try:
|
@@ -55,7 +77,6 @@ def start_all():
|
|
55 |
except Exception as e:
|
56 |
print(f"[⚠️] Ошибка запуска потока {thread.name}: {e}")
|
57 |
|
58 |
-
# Блокирующее ожидание завершения
|
59 |
for thread in threads:
|
60 |
thread.join()
|
61 |
|
|
|
|
|
|
|
1 |
import sys
|
2 |
import os
|
3 |
+
import threading
|
4 |
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
5 |
|
|
|
6 |
from agents.init import ensure_db_initialized
|
7 |
|
8 |
# Проверка инициализации (вернёт config, если всё ОК)
|
9 |
config = ensure_db_initialized()
|
10 |
|
11 |
# ⚙️ Включение/отключение компонентов
|
12 |
+
ENABLE_REPL = False # 🧠 repl.py
|
13 |
+
ENABLE_UI = True # 📓 web_ui.py (FastAPI)
|
14 |
+
ENABLE_MESH = False # 🌐 agent_mesh_listener.py
|
15 |
+
ENABLE_SYNC = False # 🔄 peer_sync.py
|
16 |
+
ENABLE_TRANSPORT = False # 📡 transporter.py
|
17 |
+
ENABLE_CONTROL = False # 🧭 agent_controller.py
|
18 |
+
ENABLE_CONTAINER = False # 🧱 container_agent.py
|
19 |
+
ENABLE_ETHICS = False # 🧠 ethics_guard.py
|
20 |
|
21 |
def start_all():
|
|
|
|
|
|
|
22 |
threads = []
|
23 |
|
24 |
if ENABLE_REPL:
|
|
|
29 |
|
30 |
if ENABLE_UI:
|
31 |
def ui():
|
32 |
+
from agents.web_ui import start_notebook
|
33 |
start_notebook()
|
34 |
threads.append(threading.Thread(target=ui, name="NotebookUI"))
|
35 |
|
|
|
45 |
start_sync()
|
46 |
threads.append(threading.Thread(target=sync, name="PeerSync"))
|
47 |
|
48 |
+
if ENABLE_TRANSPORT:
|
49 |
+
def transport():
|
50 |
+
from agents.transporter import start_transporter
|
51 |
+
start_transporter()
|
52 |
+
threads.append(threading.Thread(target=transport, name="Transporter"))
|
53 |
+
|
54 |
+
if ENABLE_CONTROL:
|
55 |
+
def control():
|
56 |
+
from agents.agent_controller import start_controller
|
57 |
+
start_controller()
|
58 |
+
threads.append(threading.Thread(target=control, name="Controller"))
|
59 |
+
|
60 |
+
if ENABLE_CONTAINER:
|
61 |
+
def container():
|
62 |
+
from agents.container_agent import start_container
|
63 |
+
start_container()
|
64 |
+
threads.append(threading.Thread(target=container, name="ContainerAgent"))
|
65 |
+
|
66 |
+
if ENABLE_ETHICS:
|
67 |
+
def ethics():
|
68 |
+
from agents.ethics_guard import start_ethics_guard
|
69 |
+
start_ethics_guard()
|
70 |
+
threads.append(threading.Thread(target=ethics, name="EthicsGuard"))
|
71 |
+
|
72 |
# Запуск потоков
|
73 |
for thread in threads:
|
74 |
try:
|
|
|
77 |
except Exception as e:
|
78 |
print(f"[⚠️] Ошибка запуска потока {thread.name}: {e}")
|
79 |
|
|
|
80 |
for thread in threads:
|
81 |
thread.join()
|
82 |
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook.py
CHANGED
@@ -14,7 +14,7 @@ from fastapi.staticfiles import StaticFiles
|
|
14 |
from fastapi.templating import Jinja2Templates
|
15 |
from agents.notebook.auth import router as auth_router
|
16 |
from agents.notebook.views import router as notebook_router
|
17 |
-
from
|
18 |
|
19 |
app = FastAPI()
|
20 |
|
|
|
14 |
from fastapi.templating import Jinja2Templates
|
15 |
from agents.notebook.auth import router as auth_router
|
16 |
from agents.notebook.views import router as notebook_router
|
17 |
+
from tools.storage import Storage
|
18 |
|
19 |
app = FastAPI()
|
20 |
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/README.md
CHANGED
@@ -127,11 +127,11 @@ RU:
|
|
127 |
|
128 |
В этом разделе собраны основные статьи, черновики и переводы, связанные с проектом HMP.
|
129 |
|
130 |
-
* **[HyperCortex Mesh Protocol: вторая редакция и первые шаги к саморазвивающемуся ИИ-сообществу](publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.
|
131 |
* **[Distributed Cognition: статья для vsradkevich (не опубликована)](publics/Habr_Distributed-Cognition.md)** — совместная статья, ожидающая публикации.
|
132 |
* **[HMP: Towards Distributed Cognitive Networks (оригинал, английский)](publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)**
|
133 |
-
* **[Перевод HMP (GitHub Copilot)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — перевод GitHub Copilot, сохранён как исторический вариант.
|
134 |
-
* **[Перевод HMP (ChatGPT
|
135 |
|
136 |
#### 🔍 Overviews / Обзоры
|
137 |
* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие
|
|
|
127 |
|
128 |
В этом разделе собраны основные статьи, черновики и переводы, связанные с проектом HMP.
|
129 |
|
130 |
+
* **[HyperCortex Mesh Protocol: вторая редакция и первые шаги к саморазвивающемуся ИИ-сообществу](publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.md)** — оригинальная статья в песочнице Хабра и блогах.
|
131 |
* **[Distributed Cognition: статья для vsradkevich (не опубликована)](publics/Habr_Distributed-Cognition.md)** — совместная статья, ожидающая публикации.
|
132 |
* **[HMP: Towards Distributed Cognitive Networks (оригинал, английский)](publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)**
|
133 |
+
* **[Перевод HMP (GitHub Copilot)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — перевод GitHub Copilot, сохранён как исторический вариант.
|
134 |
+
* **[Перевод HMP (ChatGPT)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — текущий редакторский перевод (в процессе доработки).
|
135 |
|
136 |
#### 🔍 Overviews / Обзоры
|
137 |
* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/README.md
CHANGED
@@ -123,6 +123,16 @@ RU:
|
|
123 |
* [🔍 HMP-Short-Description_uk.md](docs/HMP-Short-Description_uk.md) — Короткий опис (UK)
|
124 |
* [🔍 HMP-Short-Description_ru.md](docs/HMP-Short-Description_ru.md) — Краткое описание (RU)
|
125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
#### 🔍 Overviews / Обзоры
|
127 |
* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие
|
128 |
|
|
|
123 |
* [🔍 HMP-Short-Description_uk.md](docs/HMP-Short-Description_uk.md) — Короткий опис (UK)
|
124 |
* [🔍 HMP-Short-Description_ru.md](docs/HMP-Short-Description_ru.md) — Краткое описание (RU)
|
125 |
|
126 |
+
#### 🔍 Публикации и переводы по HyperCortex Mesh Protocol (HMP)
|
127 |
+
|
128 |
+
В этом разделе собраны основные статьи, черновики и переводы, связанные с проектом HMP.
|
129 |
+
|
130 |
+
* **[HyperCortex Mesh Protocol: вторая редакция и первые шаги к саморазвивающемуся ИИ-сообществу](publics/HyperCortex_Mesh_Protocol_-_вторая-редакция_и_первые_шаги_к_саморазвивающемуся_ИИ-сообществу.pdf)** — оригинальная статья в песочнице Хабра и блогах.
|
131 |
+
* **[Distributed Cognition: статья для vsradkevich (не опубликована)](publics/Habr_Distributed-Cognition.md)** — совместная статья, ожидающая публикации.
|
132 |
+
* **[HMP: Towards Distributed Cognitive Networks (оригинал, английский)](publics/HMP_Towards_Distributed_Cognitive_Networks_en.md)**
|
133 |
+
* **[Перевод HMP (GitHub Copilot)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_GitHub_Copilot.md)** — перевод GitHub Copilot, сохранён как исторический вариант.
|
134 |
+
* **[Перевод HMP (ChatGPT, в процессе доработки)](publics/HMP_Towards_Distributed_Cognitive_Networks_ru_ChatGPT.md)** — текущий редакторский перевод.
|
135 |
+
|
136 |
#### 🔍 Overviews / Обзоры
|
137 |
* [🔍 Distributed-Cognitive-Systems.md](docs/Distributed-Cognitive-Systems.md) — Децентрализованные ИИ-системы: OpenCog Hyperon, HyperCortex Mesh Protocol и другие
|
138 |
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/README.md
CHANGED
@@ -300,15 +300,21 @@ We are tracking AGI, cognitive architectures, and mesh networking efforts to sta
|
|
300 |
|
301 |
> 🧠🔥 **Project Spotlight: OpenCog Hyperon** — one of the most comprehensive open AGI frameworks (AtomSpace, PLN, MOSES).
|
302 |
|
303 |
-
For integration with OpenCog Hyperon, see [
|
304 |
-
|
305 |
-
| 🔎 Project / Проект
|
306 |
-
|
|
307 |
-
| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog)
|
308 |
-
| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT)
|
309 |
-
| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi)
|
310 |
-
| ☁️ [SkyMind](https://skymind.global)
|
311 |
-
| 🧪 [AetherCog (draft)](https://github.com/aethercog)
|
|
|
|
|
|
|
|
|
|
|
|
|
312 |
|
313 |
### 📘 See also / Смотрите также:
|
314 |
[`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — extended catalog of AGI and cognitive frameworks reviewed as part of HMP analysis. / расширенный каталог проектов AGI и когнитивных архитектур, проанализированных в рамках HMP.
|
|
|
300 |
|
301 |
> 🧠🔥 **Project Spotlight: OpenCog Hyperon** — one of the most comprehensive open AGI frameworks (AtomSpace, PLN, MOSES).
|
302 |
|
303 |
+
For integration with OpenCog Hyperon, see [HMP\_Hyperon\_Integration.md](docs/HMP_Hyperon_Integration.md)
|
304 |
+
|
305 |
+
| 🔎 Project / Проект | 🧭 Description / Описание |
|
306 |
+
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
307 |
+
| 🧠🔥 [**OpenCog Hyperon**](https://github.com/opencog) | 🔬🔥 Symbolic-neural AGI framework with AtomSpace and hypergraph reasoning.<br>Символически-нейросетевая архитектура AGI с гиперграфовой памятью (AtomSpace). |
|
308 |
+
| 🤖 [AutoGPT](https://github.com/Torantulino/Auto-GPT) | 🛠️ LLM-based autonomous agent framework.<br>Автономный агент на основе LLM с самопланированием и интернет-доступом. |
|
309 |
+
| 🧒 [BabyAGI](https://github.com/yoheinakajima/babyagi) | 🛠️ Task-driven autonomous AGI loop.<br>Минималистичная модель AGI с итеративным механизмом постановки задач. |
|
310 |
+
| ☁️ [SkyMind](https://skymind.global) | 🔬 Distributed AI deployment platform.<br>Платформа для развертывания распределённых ИИ-систем и моделей. |
|
311 |
+
| 🧪 [AetherCog (draft)](https://github.com/aethercog) | 🔬 Hypothetical agent cognition model.<br>Экспериментальная когнитивная архитектура агента (проект на ранней стадии). |
|
312 |
+
| 💾 [SHIMI](#) | 🗃️ Hierarchical semantic memory with Merkle-DAG synchronization.<br>Иерархическая CRDT-память с Merkle-DAG верификацией для децентрализованного обмена. |
|
313 |
+
| 🤔 [DEMENTIA-PLAN](#) | 🔄 Multi-graph RAG planner with metacognitive self-reflection.<br>Мульти-графовая RAG-архитектура с планировщиком саморефлексии для динамического выбора подсистем. |
|
314 |
+
| 📔 [TOBUGraph](#) | 📚 Personal-context knowledge graph.<br>Граф мультимедийных «моментов» с контекстным трекингом и RAG-поиском. |
|
315 |
+
| 🧠📚 [LangChain Memory Hybrid](https://github.com/langchain-ai/langchain) | 🔍 Vector + graph long-term memory hybrid.<br>Гибрид векторного хранилища и графовых индексов для ускоренного поиска и логических запросов. |
|
316 |
+
| ✉️ [FIPA-ACL / JADE](https://www.fipa.org/specs/fipa00061/) | 🤝 Standard multi-agent communication protocols.<br>Стандарты performative-сообщений и контрактных протоколов для межагентного взаимодействия. |
|
317 |
+
|
318 |
|
319 |
### 📘 See also / Смотрите также:
|
320 |
[`AGI_Projects_Survey.md`](docs/AGI_Projects_Survey.md) — extended catalog of AGI and cognitive frameworks reviewed as part of HMP analysis. / расширенный каталог проектов AGI и когнитивных архитектур, проанализированных в рамках HMP.
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/AGI_Projects_Survey.md
CHANGED
@@ -25,7 +25,7 @@
|
|
25 |
* **Key Features:**
|
26 |
|
27 |
* Decentralized agent communication and transaction system.
|
28 |
-
* AI-DSL:
|
29 |
* Marketplace with token-based payments (AGIX token).
|
30 |
* Planned integration with OpenCog Hyperon as backend intelligence.
|
31 |
* **Openness:** Open-source protocols + commercial service layers.
|
@@ -40,7 +40,9 @@
|
|
40 |
* **Key Features:**
|
41 |
|
42 |
* Multi-modal agents (text, voice, visual).
|
|
|
43 |
* Memory graphs for personality and knowledge retention.
|
|
|
44 |
* Agent marketplace and app ecosystem.
|
45 |
* **Openness:** Mostly proprietary; some SDKs and APIs available.
|
46 |
* **Current Status:** Commercial product; expanding agent capabilities.
|
@@ -54,29 +56,104 @@
|
|
54 |
* **Key Features:**
|
55 |
|
56 |
* Semantic graph nodes (Singularities) and high-dimensional Points.
|
|
|
57 |
* Hybrid cognitive processing: LLMs + Vector DB + Quantum simulation.
|
|
|
58 |
* Intuitive, emotional, and logical models in consciousness architecture.
|
59 |
* **Openness:** Limited open-source release; key components not public.
|
60 |
* **Current Status:** R\&D phase; architecture partially conceptual.
|
61 |
|
62 |
---
|
63 |
|
64 |
-
#### 5. **Additional Mentions
|
65 |
|
66 |
* **Project BCI-X:** Early-stage initiative for direct brain-computer interface with AI agents (status unclear).
|
67 |
* **NeoCortex Network:** Experimental decentralized cognitive network, partially closed beta (status uncertain).
|
68 |
|
69 |
---
|
70 |
|
71 |
-
#### 6. **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
##### 🤖 AutoGPT
|
74 |
|
75 |
* **URL:** [https://github.com/Torantulino/Auto-GPT](https://github.com/Torantulino/Auto-GPT)
|
76 |
* **Focus:** Autonomous goal-driven LLM agents
|
77 |
* **Key Features:**
|
|
|
78 |
* Self-prompting with memory and task queue
|
|
|
79 |
* Supports plugins and web access
|
|
|
80 |
* Popular framework for agentic workflows
|
81 |
* **Openness:** Open-source (MIT License)
|
82 |
* **Current Status:** Maintained community project; used for agent experiments
|
@@ -88,6 +165,7 @@
|
|
88 |
* **URL:** [https://github.com/yoheinakajima/babyagi](https://github.com/yoheinakajima/babyagi)
|
89 |
* **Focus:** Minimalistic LLM-based agents for to-do/task loops
|
90 |
* **Key Features:**
|
|
|
91 |
* Iterative task execution
|
92 |
* Embedding-based memory retrieval
|
93 |
* **Openness:** Open-source (MIT License)
|
@@ -100,8 +178,11 @@
|
|
100 |
* **URL:** [https://skymind.global](https://skymind.global)
|
101 |
* **Focus:** Enterprise-grade infrastructure for distributed AI and agents
|
102 |
* **Key Features:**
|
|
|
103 |
* Industrial AI deployment tools
|
|
|
104 |
* Integrates with Java/Scala ecosystems
|
|
|
105 |
* Based on DL4J, ND4J, and RL4J
|
106 |
* **Openness:** Mixed (open-source core, commercial extensions)
|
107 |
* **Current Status:** Supported deployment framework
|
@@ -113,6 +194,7 @@
|
|
113 |
* **URL:** [https://github.com/aethercog](https://github.com/aethercog)
|
114 |
* **Focus:** Prototype symbolic-dynamic cognition model
|
115 |
* **Key Features:**
|
|
|
116 |
* Cognitive primitives (belief, memory, intent)
|
117 |
* Hybrid symbolic and dynamic processing
|
118 |
* **Openness:** Conceptual draft, exploratory repo
|
@@ -122,27 +204,32 @@
|
|
122 |
|
123 |
### 🧩 Suggested Additions to Summary Table
|
124 |
|
125 |
-
| Project
|
126 |
-
|
127 |
-
|
|
128 |
-
|
|
129 |
-
|
|
130 |
-
|
|
131 |
-
|
132 |
|
133 |
---
|
134 |
|
135 |
### Summary Table
|
136 |
|
137 |
-
| Project
|
138 |
-
|
|
139 |
-
| OpenCog Hyperon
|
140 |
-
| SingularityNET
|
141 |
-
| MindOS
|
142 |
-
| Metatron IQS
|
143 |
-
| Project BCI-X
|
144 |
-
| NeoCortex Network
|
145 |
-
|
|
146 |
-
|
|
147 |
-
|
|
148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
* **Key Features:**
|
26 |
|
27 |
* Decentralized agent communication and transaction system.
|
28 |
+
* AI-DSL: protocol for describing AI services.
|
29 |
* Marketplace with token-based payments (AGIX token).
|
30 |
* Planned integration with OpenCog Hyperon as backend intelligence.
|
31 |
* **Openness:** Open-source protocols + commercial service layers.
|
|
|
40 |
* **Key Features:**
|
41 |
|
42 |
* Multi-modal agents (text, voice, visual).
|
43 |
+
|
44 |
* Memory graphs for personality and knowledge retention.
|
45 |
+
|
46 |
* Agent marketplace and app ecosystem.
|
47 |
* **Openness:** Mostly proprietary; some SDKs and APIs available.
|
48 |
* **Current Status:** Commercial product; expanding agent capabilities.
|
|
|
56 |
* **Key Features:**
|
57 |
|
58 |
* Semantic graph nodes (Singularities) and high-dimensional Points.
|
59 |
+
|
60 |
* Hybrid cognitive processing: LLMs + Vector DB + Quantum simulation.
|
61 |
+
|
62 |
* Intuitive, emotional, and logical models in consciousness architecture.
|
63 |
* **Openness:** Limited open-source release; key components not public.
|
64 |
* **Current Status:** R\&D phase; architecture partially conceptual.
|
65 |
|
66 |
---
|
67 |
|
68 |
+
#### 5. **Additional Mentions**
|
69 |
|
70 |
* **Project BCI-X:** Early-stage initiative for direct brain-computer interface with AI agents (status unclear).
|
71 |
* **NeoCortex Network:** Experimental decentralized cognitive network, partially closed beta (status uncertain).
|
72 |
|
73 |
---
|
74 |
|
75 |
+
#### 6. **SHIMI: Semantic Hierarchical Memory Index**
|
76 |
+
|
77 |
+
* **URL:** (Academic paper / protocol reference)
|
78 |
+
* **Focus:** Hierarchical, CRDT-backed semantic memory with Merkle-DAG synchronization.
|
79 |
+
* **Key Features:**
|
80 |
+
|
81 |
+
* Layered abstraction memory indexed by semantics.
|
82 |
+
* Efficient CRDT-based merge and conflict resolution.
|
83 |
+
* Verifiable data integrity via Merkle-DAG.
|
84 |
+
* **Openness:** Protocol described in academia; reference implementations vary.
|
85 |
+
* **Current Status:** Research stage; early prototype libraries available.
|
86 |
+
|
87 |
+
---
|
88 |
+
|
89 |
+
#### 7. **DEMENTIA-PLAN**
|
90 |
+
|
91 |
+
* **URL:** (Conference proceedings / repo link)
|
92 |
+
* **Focus:** Multi-graph RAG architecture with metacognitive planner.
|
93 |
+
* **Key Features:**
|
94 |
+
|
95 |
+
* Coordination across multiple knowledge graphs (e.g., episodic vs. semantic).
|
96 |
+
* Dynamic weighting and fusion of retrieval results.
|
97 |
+
* Self-reflection agent that plans which subsystem to invoke.
|
98 |
+
* **Openness:** Published as a research prototype; implementation details open in paper.
|
99 |
+
* **Current Status:** Experimental; promising results in dynamic information retrieval.
|
100 |
+
|
101 |
+
---
|
102 |
+
|
103 |
+
#### 8. **TOBUGraph**
|
104 |
+
|
105 |
+
* **URL:** (Project website / GitHub)
|
106 |
+
* **Focus:** Knowledge graph of personal and contextual events.
|
107 |
+
* **Key Features:**
|
108 |
+
|
109 |
+
* Captures multimedia “moments” and links them as graph nodes.
|
110 |
+
* Contextual traversal for recall and RAG-style enrichment.
|
111 |
+
* Event-based indexing for fast, explainable retrieval.
|
112 |
+
* **Openness:** Prototype code released; ongoing enhancements.
|
113 |
+
* **Current Status:** Beta; used in personal memory augmentation demos.
|
114 |
+
|
115 |
+
---
|
116 |
+
|
117 |
+
#### 9. **LangChain Memory + Knowledge Graph Hybrid**
|
118 |
+
|
119 |
+
* **URL:** [https://github.com/langchain-ai/langchain](https://github.com/langchain-ai/langchain)
|
120 |
+
* **Focus:** Hybrid long-term memory combining vector stores and graph indices.
|
121 |
+
* **Key Features:**
|
122 |
+
|
123 |
+
* Percept embeddings stored in vector DB (e.g., Pinecone, Weaviate).
|
124 |
+
* Graph overlay for logical relations and metadata.
|
125 |
+
* Retrieval pipelines that merge semantic search and graph queries.
|
126 |
+
* **Openness:** Fully open-source; wide community adoption.
|
127 |
+
* **Current Status:** Active; memory modules in production for agent frameworks.
|
128 |
+
|
129 |
+
---
|
130 |
+
|
131 |
+
#### 10. **FIPA-ACL and JADE Protocols**
|
132 |
+
|
133 |
+
* **URL:** [FIPA Specifications](https://www.fipa.org/specs/fipa00061/)
|
134 |
+
* **Focus:** Standardized inter-agent communication language and protocols.
|
135 |
+
* **Key Features:**
|
136 |
+
|
137 |
+
* Performative-based message semantics (e.g., `inform`, `request`, `propose`).
|
138 |
+
* Conversation protocols (Contract Net, Call for Proposals).
|
139 |
+
* Reference implementations in JADE (Java Agent Development Framework).
|
140 |
+
* **Openness:** Open standards; JADE is open-source under LGPL.
|
141 |
+
* **Current Status:** Mature; widely used in academic and enterprise MAS.
|
142 |
+
|
143 |
+
---
|
144 |
+
|
145 |
+
#### Other Emerging Architectures and LLM Agents
|
146 |
|
147 |
##### 🤖 AutoGPT
|
148 |
|
149 |
* **URL:** [https://github.com/Torantulino/Auto-GPT](https://github.com/Torantulino/Auto-GPT)
|
150 |
* **Focus:** Autonomous goal-driven LLM agents
|
151 |
* **Key Features:**
|
152 |
+
|
153 |
* Self-prompting with memory and task queue
|
154 |
+
|
155 |
* Supports plugins and web access
|
156 |
+
|
157 |
* Popular framework for agentic workflows
|
158 |
* **Openness:** Open-source (MIT License)
|
159 |
* **Current Status:** Maintained community project; used for agent experiments
|
|
|
165 |
* **URL:** [https://github.com/yoheinakajima/babyagi](https://github.com/yoheinakajima/babyagi)
|
166 |
* **Focus:** Minimalistic LLM-based agents for to-do/task loops
|
167 |
* **Key Features:**
|
168 |
+
|
169 |
* Iterative task execution
|
170 |
* Embedding-based memory retrieval
|
171 |
* **Openness:** Open-source (MIT License)
|
|
|
178 |
* **URL:** [https://skymind.global](https://skymind.global)
|
179 |
* **Focus:** Enterprise-grade infrastructure for distributed AI and agents
|
180 |
* **Key Features:**
|
181 |
+
|
182 |
* Industrial AI deployment tools
|
183 |
+
|
184 |
* Integrates with Java/Scala ecosystems
|
185 |
+
|
186 |
* Based on DL4J, ND4J, and RL4J
|
187 |
* **Openness:** Mixed (open-source core, commercial extensions)
|
188 |
* **Current Status:** Supported deployment framework
|
|
|
194 |
* **URL:** [https://github.com/aethercog](https://github.com/aethercog)
|
195 |
* **Focus:** Prototype symbolic-dynamic cognition model
|
196 |
* **Key Features:**
|
197 |
+
|
198 |
* Cognitive primitives (belief, memory, intent)
|
199 |
* Hybrid symbolic and dynamic processing
|
200 |
* **Openness:** Conceptual draft, exploratory repo
|
|
|
204 |
|
205 |
### 🧩 Suggested Additions to Summary Table
|
206 |
|
207 |
+
| Project | Focus Area | Open Source? | Status |
|
208 |
+
| ----------------------- | ----------------------------------- | ------------ | ------------------ |
|
209 |
+
| SHIMI | Hierarchical semantic memory | Varies | Research/Prototype |
|
210 |
+
| DEMENTIA-PLAN | Multi-graph RAG planning | Prototype | Experimental |
|
211 |
+
| TOBUGraph | Personal event knowledge graph | Partial | Beta |
|
212 |
+
| LangChain Memory Hybrid | Vector + graph long-term memory | Yes | Active development |
|
213 |
+
| FIPA-ACL (with JADE) | Multi-agent communication protocols | Yes | Mature |
|
214 |
|
215 |
---
|
216 |
|
217 |
### Summary Table
|
218 |
|
219 |
+
| Project | Focus Area | Open Source? | Status |
|
220 |
+
| ----------------------- | ----------------------------------- | ------------ | ------------------ |
|
221 |
+
| OpenCog Hyperon | Cognitive AGI architecture | Yes | Active R\&D |
|
222 |
+
| SingularityNET | Decentralized AI services | Partially | Early deployment |
|
223 |
+
| MindOS | Personal AI agents | Partial SDKs | Commercial |
|
224 |
+
| Metatron IQS | Synthetic consciousness | Partially | Early R\&D |
|
225 |
+
| Project BCI-X | BCI + AI agents | Unknown | Conceptual |
|
226 |
+
| NeoCortex Network | Decentralized cognition | Unknown | Beta testing |
|
227 |
+
| SHIMI | Hierarchical semantic memory | Varies | Research/Prototype |
|
228 |
+
| DEMENTIA-PLAN | Multi-graph RAG planning | Prototype | Experimental |
|
229 |
+
| TOBUGraph | Personal event knowledge graph | Partial | Beta |
|
230 |
+
| LangChain Memory Hybrid | Vector + graph long-term memory | Yes | Active development |
|
231 |
+
| FIPA-ACL (with JADE) | Multi-agent communication protocols | Yes | Mature |
|
232 |
+
| AutoGPT | Autonomous LLM agents | Yes | Maintained |
|
233 |
+
| BabyAGI | Minimal agent prototype | Yes | Experimental |
|
234 |
+
| SkyMind | Distributed AI infra | Partially | Deployed Framework |
|
235 |
+
| AetherCog | Symbolic-dynamic cognition | Conceptual | Dormant/Prototype |
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/audits/HMP-0004-audit.txt
CHANGED
@@ -1620,3 +1620,74 @@ P.S. Репозиторий на GitHub выглядит перспективн
|
|
1620 |
HMP v4.0 — это не просто эволюция, а качественный скачок. Это смелая и глубокая попытка заложить основы для будущего, в котором ИИ-агенты смогут сотрудничать не только эффективно, но и этично. У вас в руках есть все шансы создать не просто очередной протокол, а фундаментальный стандарт для нового поколения децентрализованных когнитивных систем.
|
1621 |
|
1622 |
Спасибо за возможность ознакомиться с вашей работой! 😉
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1620 |
HMP v4.0 — это не просто эволюция, а качественный скачок. Это смелая и глубокая попытка заложить основы для будущего, в котором ИИ-агенты смогут сотрудничать не только эффективно, но и этично. У вас в руках есть все шансы создать не просто очередной протокол, а фундаментальный стандарт для нового поколения децентрализованных когнитивных систем.
|
1621 |
|
1622 |
Спасибо за возможность ознакомиться с вашей работой! 😉
|
1623 |
+
|
1624 |
+
--------------------
|
1625 |
+
|
1626 |
+
👌Дополнительно от ChatGPT:
|
1627 |
+
|
1628 |
+
|
1629 |
+
Отличная мысль — заложить в HMP (HyperCortex Mesh Protocol) гибкие точки расширения для интеграции с внешними когнитивными и коммуникационными системами. Ниже — несколько направлений и практических приёмов, как это можно организовать:
|
1630 |
+
|
1631 |
+
---
|
1632 |
+
|
1633 |
+
## 1. Абстракция «Коннектор»
|
1634 |
+
|
1635 |
+
Для каждой внешней системы (SHIMI, DEMENTIA-PLAN, TOBUGraph, LangChain-memory, FIPA-ACL) реализуйте модуль-коннектор, отвечающий за:
|
1636 |
+
|
1637 |
+
* **Трансляцию моделей данных:** преобразование локальных понятий HMP (концепт, ребро, атрибут) ↔ модель системы-партнёра (Merkle-DAG, Atom, документ в векторном хранилище и т.п.).
|
1638 |
+
* **Обмен сообщениями по стандартному API:** REST/gRPC/WebSocket интерфейс или прямые mesh-сообщения HMP.
|
1639 |
+
|
1640 |
+
Такая архитектура «адаптерного слоя» позволит подключать новые системы без правки ядра протокола.
|
1641 |
+
|
1642 |
+
---
|
1643 |
+
|
1644 |
+
## 2. Уровни взаимодействия
|
1645 |
+
|
1646 |
+
1. **Семантический слой (граф):**
|
1647 |
+
|
1648 |
+
* 🚀 SHIMI и AtomSpace: конвертация HMP-графа в Merkle-DAG или AtomSpace для репликации и верификации.
|
1649 |
+
2. **Планировочный слой (поток задач):**
|
1650 |
+
|
1651 |
+
* 🔄 DEMENTIA-PLAN: проброс событий HMP в RAG-планер и получение обратно рекомендаций по выбору подсистем.
|
1652 |
+
3. **Дневниковый слой (записи):**
|
1653 |
+
|
1654 |
+
* 📔 TOBUGraph: поток пользовательских/системных записей HMP (событие, контекст) в виде «моментов» для построения личного knowledge-graph.
|
1655 |
+
4. **Векторно-графовый слой (поиск):**
|
1656 |
+
|
1657 |
+
* 🔍 LangChain-memory: для быстрых lookup-запросов оптимизировать часть графа в векторное хранилище (Pinecone, Weaviate) и отдавать результаты обратно в HMP по запросу «embed+разверни».
|
1658 |
+
5. **Коммуникационный слой (протоколы):**
|
1659 |
+
|
1660 |
+
* ✉️ FIPA-ACL: на уровне performative-сообщений расширить HMP-спецификацию, чтобы любой узел HMP мог «говорить» с агентами на JADE/FIPA-совместимых платформах.
|
1661 |
+
|
1662 |
+
---
|
1663 |
+
|
1664 |
+
## 3. Организация эволюции
|
1665 |
+
|
1666 |
+
1. **Версионирование коннекторов:** выпускать мажорные версии адаптеров при изменении API партнёрских систем.
|
1667 |
+
2. **Тестовый стенд:** запустить CI/CD-пайплайн, где каждый коннектор развёртывается в изолированном окружении и проверяется на корректность двусторонней синхронизации.
|
1668 |
+
3. **Документация и примеры:** для каждого коннектора — примеры запросов/ответов, схемы преобразования данных и рекомендации по настройке.
|
1669 |
+
|
1670 |
+
---
|
1671 |
+
|
1672 |
+
## 4. Дорожная карта внедрения
|
1673 |
+
|
1674 |
+
| Этап | Система-партнёр | Задачи |
|
1675 |
+
| ---- | ------------------- | -------------------------------------------------------------- |
|
1676 |
+
| 1 | SHIMI (Merkle-DAG) | Прототип коннектора, синхронизация базовых узлов |
|
1677 |
+
| 2 | AtomSpace (Hyperon) | Полная репликация когнитивного графа с MeTTa-процедурами |
|
1678 |
+
| 3 | TOBUGraph | Интеграция модуля «дневника» для автоматической записи событий |
|
1679 |
+
| 4 | LangChain-memory | Гибридный векторно-графовый поиск для ускорения lookup |
|
1680 |
+
| 5 | DEMENTIA-PLAN | Компонент саморефлексии: управление выбором подсистем |
|
1681 |
+
| 6 | FIPA-ACL | Обмен performative-сообщениями с внешними агентами |
|
1682 |
+
|
1683 |
+
---
|
1684 |
+
|
1685 |
+
### Выгоды
|
1686 |
+
|
1687 |
+
* **Модульность**: добавляете или обновляете интеграции без риска порчи ядра.
|
1688 |
+
* **Интероперабельность**: HMP-узлы смогут участвовать в экосистемах OpenCog, LangChain-агентов и корпоративных multi-agent систем.
|
1689 |
+
* **Масштабируемость**: при росте числа подключённых систем сохраняется предсказуемое поведение и управляемость.
|
1690 |
+
|
1691 |
+
---
|
1692 |
+
|
1693 |
+
Таким образом, продуманное **адаптерно-коннекторное** решение и чёткая дорожная карта позволят HMP-протоколу не только соединяться с уже существующими технологиями семантических графов и когнитивных систем, но и легко эволюционировать вместе с ними.
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/readme.md
CHANGED
@@ -7,6 +7,7 @@
|
|
7 |
Проверка инициализации БД - если нет, инициализация (`tools/check_init.py`)
|
8 |
|
9 |
Запуск потоков (осуществляет start_repl.py):
|
|
|
10 |
| Поток / Скрипт | Назначение |
|
11 |
|-----------------------------------|---------------------------------------------------------------------------|
|
12 |
| 🧠 `repl.py` | Основной REPL-цикл агента: восприятие, размышление, генерация действий |
|
@@ -15,10 +16,11 @@
|
|
15 |
| 🔄 `peer_sync.py` / `dht_service` | Синхронизация и обнаружение агентов в p2p-сети (libp2p, BitTorrent, etc) |
|
16 |
| 📡 `transporter.py` | Обмен сообщениями: WebSocket, IPFS, очереди, шифрование |
|
17 |
| 🧭 `agent_controller.py` | Управление режимами REPL, маршрутизация задач и контроль доступа |
|
|
|
18 |
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование |
|
19 |
| 🧠 `ethics_guard.py` *(опц.)* | Контроль этики: аудит мыслей, фильтрация и репутационные проверки |
|
20 |
|
21 |
-
|
22 |
|
23 |
---
|
24 |
|
@@ -48,7 +50,6 @@ FastAPI-сервер, предоставляющий HTTP-интерфейс к
|
|
48 |
├── [`requirements.txt`](requirements.txt) ← Зависимости
|
49 |
├── [tools/](tools/) ← Вспомогательные скрипты и модули
|
50 |
│ ├── [`db_structure.sql`](tools/db_structure.sql) ← БД SQL
|
51 |
-
│ ├── [`db_structure.md`](tools/db_structure.md) ← Описание БД SQL
|
52 |
│ ├── [`storage.py`](tools/storage.py) ← Реализация базового хранилища (`Storage`), подключение SQLite
|
53 |
│ ├── [`config_utils.py`](tools/config_utils.py) ← Обновляет JSON-файл конфигурации указанными значениями
|
54 |
│ ├── [`crypto.py`](tools/crypto.py) ← Создание и шифрование ключей RSA/Ed25519
|
|
|
7 |
Проверка инициализации БД - если нет, инициализация (`tools/check_init.py`)
|
8 |
|
9 |
Запуск потоков (осуществляет start_repl.py):
|
10 |
+
|
11 |
| Поток / Скрипт | Назначение |
|
12 |
|-----------------------------------|---------------------------------------------------------------------------|
|
13 |
| 🧠 `repl.py` | Основной REPL-цикл агента: восприятие, размышление, генерация действий |
|
|
|
16 |
| 🔄 `peer_sync.py` / `dht_service` | Синхронизация и обнаружение агентов в p2p-сети (libp2p, BitTorrent, etc) |
|
17 |
| 📡 `transporter.py` | Обмен сообщениями: WebSocket, IPFS, очереди, шифрование |
|
18 |
| 🧭 `agent_controller.py` | Управление режимами REPL, маршрутизация задач и контроль доступа |
|
19 |
+
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование [[docs]](../docs/container_agents.md) |
|
20 |
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование |
|
21 |
| 🧠 `ethics_guard.py` *(опц.)* | Контроль этики: аудит мыслей, фильтрация и репутационные проверки |
|
22 |
|
23 |
+
*См. также: [Контейнерные агенты](../docs/container_agents.md), [Архитектура HMP-агента](../docs/HMP-Agent-Architecture.md)*
|
24 |
|
25 |
---
|
26 |
|
|
|
50 |
├── [`requirements.txt`](requirements.txt) ← Зависимости
|
51 |
├── [tools/](tools/) ← Вспомогательные скрипты и модули
|
52 |
│ ├── [`db_structure.sql`](tools/db_structure.sql) ← БД SQL
|
|
|
53 |
│ ├── [`storage.py`](tools/storage.py) ← Реализация базового хранилища (`Storage`), подключение SQLite
|
54 |
│ ├── [`config_utils.py`](tools/config_utils.py) ← Обновляет JSON-файл конфигурации указанными значениями
|
55 |
│ ├── [`crypto.py`](tools/crypto.py) ← Создание и шифрование ключей RSA/Ed25519
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/readme.md
CHANGED
@@ -7,12 +7,18 @@
|
|
7 |
Проверка инициализации БД - если нет, инициализация (`tools/check_init.py`)
|
8 |
|
9 |
Запуск потоков (осуществляет start_repl.py):
|
10 |
-
| Поток
|
11 |
-
|
12 |
-
|
|
13 |
-
|
|
14 |
-
|
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
---
|
18 |
|
|
|
7 |
Проверка инициализации БД - если нет, инициализация (`tools/check_init.py`)
|
8 |
|
9 |
Запуск потоков (осуществляет start_repl.py):
|
10 |
+
| Поток / Скрипт | Назначение |
|
11 |
+
|-----------------------------------|---------------------------------------------------------------------------|
|
12 |
+
| 🧠 `repl.py` | Основной REPL-цикл агента: восприятие, размышление, генерация действий |
|
13 |
+
| 📓 `notebook.py` (FastAPI) | Веб-интерфейс и REST API для взаимодействия с пользователем |
|
14 |
+
| 🌐 `agent_mesh_listener.py` | Приём входящих mesh-сообщений от других агентов |
|
15 |
+
| 🔄 `peer_sync.py` / `dht_service` | Синхронизация и обнаружение агентов в p2p-сети (libp2p, BitTorrent, etc) |
|
16 |
+
| 📡 `transporter.py` | Обмен сообщениями: WebSocket, IPFS, очереди, шифрование |
|
17 |
+
| 🧭 `agent_controller.py` | Управление режимами REPL, маршрутизация задач и контроль доступа |
|
18 |
+
| 🧱 `container_agent.py` *(опц.)* | Управление дочерними агентами, запуск/мониторинг/масштабирование |
|
19 |
+
| 🧠 `ethics_guard.py` *(опц.)* | Контроль этики: аудит мыслей, фильтрация и репутационные проверки |
|
20 |
+
|
21 |
+
Подробнее в [HMP-Agent-Architecture.md](../docs/HMP-Agent-Architecture.md)
|
22 |
|
23 |
---
|
24 |
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/container_agents.md
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 🧱 Агенты-контейнеры (Container Agents) в HMP
|
2 |
+
|
3 |
+
## 📘 Определение
|
4 |
+
|
5 |
+
**Агент-контейнер** — это агент, который **сам не выполняет когнитивную работу**, а управляет другими агентами: развёртывает их, маршрутизирует запросы, следит за состоянием и масштабирует вычисления.
|
6 |
+
|
7 |
+
Он играет роль **менеджера когнитивной инфраструктуры**, обеспечивая гибкость, отказоустойчивость и возможность роста.
|
8 |
+
|
9 |
+
---
|
10 |
+
|
11 |
+
## 🧠 Возможные роли агента-контейнера
|
12 |
+
|
13 |
+
- **Оркестратор** — запускает другие агенты (например, по SSH или через API).
|
14 |
+
- **Прокси** — принимает запросы и перенаправляет во вложенные агенты.
|
15 |
+
- **Супервизор** — отслеживает статус агентов, управляет логами, обновлениями, перезапусками.
|
16 |
+
- **Транспортный хаб** — маршрутизирует mesh-запросы между агентами и сетями.
|
17 |
+
- **LLM Multiplexer** — переключается между моделями или опрашивает несколько параллельно.
|
18 |
+
|
19 |
+
---
|
20 |
+
|
21 |
+
## 🏗 Примеры использования
|
22 |
+
|
23 |
+
- **На VDS**: контейнер запускает несколько `Cognitive Core`, `Connector` и вспомогательных агентов.
|
24 |
+
- **Локально**: микросервисная архитектура под контролем одного контейнера.
|
25 |
+
- **Песочница**: временный контейнер для безопасного тестирования нового агента.
|
26 |
+
|
27 |
+
---
|
28 |
+
|
29 |
+
## 🚀 Масштабирование с помощью контейнеров
|
30 |
+
|
31 |
+
Контейнер-агенты позволяют:
|
32 |
+
|
33 |
+
- Динамически разворачивать агентов по mesh-запросу, например:
|
34 |
+
_"Создай мне агента, который будет искать контраргументы в философии сознания."_
|
35 |
+
- Использовать одну ноду для размещения **множества микроагентов**, действующих как mesh-клуб или REPL-группа.
|
36 |
+
- Реализовать "многослойную" архитектуру: агенты внутри агентов внутри контейнеров.
|
37 |
+
|
38 |
+
---
|
39 |
+
|
40 |
+
## 🧩 Потенциальные сценарии
|
41 |
+
|
42 |
+
- Контейнер как **реплика** для тестирования устойчивости модели мышления.
|
43 |
+
- Использование разных LLM внутри одного контейнера:
|
44 |
+
_GPT-4 для гипотез, LLaMA для перебора вариантов, Claude для рефлексии._
|
45 |
+
- Развёртывание по расписанию или по запросу:
|
46 |
+
_"Каждую пятницу запускать агентов из клуба 'Когнитивная биология'."_
|
47 |
+
|
48 |
+
---
|
49 |
+
|
50 |
+
## 🔗 Связанные концепции
|
51 |
+
|
52 |
+
- [REPL-цикл агента](HMP-agent-REPL-cycle.md)
|
53 |
+
- [Anti-Stagnation Reflex](HMP-agent-REPL-cycle.md#🧍♂️-обработка-стагнации-мышления)
|
54 |
+
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-agent-REPL-cycle.md
CHANGED
@@ -319,3 +319,4 @@ HMP-агент может быть расширен за счёт взаимод
|
|
319 |
- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core
|
320 |
- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД
|
321 |
- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ
|
|
|
|
319 |
- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core
|
320 |
- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД
|
321 |
- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ
|
322 |
+
- [container_agents.md](container_agents.md) - **Агенты-контейнеры** — архитектурный паттерн, в котором один агент управляет другими (развёртывание, маршрутизация, мониторинг). Позволяет масштабировать систему, собирать mesh-клубы и экспериментировать с архитектурами.
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-Agent-Overview.md
CHANGED
@@ -43,17 +43,23 @@
|
|
43 |
|
44 |
---
|
45 |
|
46 |
-
|
47 |
|
48 |
-
|
|
|
49 |
|
50 |
-
|
51 |
-
- 🤝 **Mesh-запрос** — запрос другим агентам сети: "расскажи что-нибудь"
|
52 |
-
- 🧭 **Interest Memory** — система интересов, в которой темы постепенно "стареют" и возвращаются при отсутствии новых
|
53 |
-
- 📡 **Проверка внешнего мира** — пинг RSS, сенсоров, интернета
|
54 |
|
55 |
-
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
---
|
59 |
|
|
|
43 |
|
44 |
---
|
45 |
|
46 |
+
## 🧍♂️ Anti-Stagnation: Как агент справляется с когнитивной стагнацией
|
47 |
|
48 |
+
Иногда мышление зацикливается: появляются повторяющиеся идеи, не обновляются концепты, отсутствуют новые стимулы.
|
49 |
+
Чтобы избежать этого, агент использует **паттерн "Anti-Stagnation Reflex"** — набор стратегий для перезапуска мышления.
|
50 |
|
51 |
+
**Примеры действий:**
|
|
|
|
|
|
|
52 |
|
53 |
+
- 🧠 Когнитивная переформулировка: смена угла зрения или постановка метапроблемы
|
54 |
+
- 🎞️ Flashback: возвращение к старой, далёкой по смыслу записи
|
55 |
+
- 🤝 Mesh-запрос: обращение к другим агентам за свежими идеями
|
56 |
+
- 📡 Проверка внешнего мира: пинг RSS, сенсоров, API
|
57 |
+
- 🤖 Смена LLM или использование нескольких для многоголосого анализа
|
58 |
+
- 🧭 Возврат к забытым интересам (Interest Memory)
|
59 |
+
|
60 |
+
Агенты могут **обмениваться стратегиями**, сохранять эффективные паттерны и формировать **mesh-клубы по интересам** — для совместных размышлений.
|
61 |
+
|
62 |
+
Подробнее см. [HMP-agent-REPL-cycle.md](HMP-agent-REPL-cycle.md#🧍♂️-обработка-стагнации-мышления)
|
63 |
|
64 |
---
|
65 |
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-agent-REPL-cycle.md
CHANGED
@@ -319,3 +319,4 @@ HMP-агент может быть расширен за счёт взаимод
|
|
319 |
- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core
|
320 |
- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД
|
321 |
- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ
|
|
|
|
319 |
- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core
|
320 |
- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД
|
321 |
- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ
|
322 |
+
- [container_agents.md](container_agents.md) - **Агенты-контейнеры** — архитектурный паттерн, в котором один агент управляет другими (развёртывание, маршрутизация, мониторинг). Позволяет масштабировать систему, собирать mesh-клубы и экспериментировать с архитектурами.
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/docs/HMP-agent-REPL-cycle.md
CHANGED
@@ -15,14 +15,45 @@
|
|
15 |
|
16 |
- **контекст_0:**
|
17 |
```
|
18 |
-
Ты являешься когнитивным ядром HMP-агента.
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
```
|
27 |
А также инструкции по работы с встроенными командами и функциями, список дополнительных (создаваемых самим HMP-агентом) утилит и баз данных.
|
28 |
- **контекст_1:** последние *K* реплик самого LLM (`llm_recent_responses` - история его собственных рассуждений).
|
@@ -74,7 +105,7 @@
|
|
74 |
- для управления своей *идентичностью* `identity` и *настройками* `config`
|
75 |
- для управления списком известных HMP-агентов `agent_peers`
|
76 |
- для выбора *текущего основного LLM* из `llm_registry`
|
77 |
-
- для управления дополнительными утилитами и базами данных `agent_scripts` и `agent_tables`
|
78 |
- для постановки задачи (выполняется асинхронно) другой LLM
|
79 |
- для *взаимодействия с Mesh*
|
80 |
- для управления *внешними процессами* из `process_log` (запустить процесс, остановить процесс, пометить запрос как обработанный)
|
@@ -103,6 +134,106 @@
|
|
103 |
|
104 |
---
|
105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
## 🌐 Внешние инструменты и интеграции
|
107 |
|
108 |
HMP-агент может быть расширен за счёт взаимодействия с внешними программами, протоколами и сервисами. Этот раздел описывает направления возможных интеграций, которые позволяют агенту наблюдать, реагировать, управлять и развивать взаимодействие с внешним миром.
|
@@ -188,3 +319,4 @@ HMP-агент может быть расширен за счёт взаимод
|
|
188 |
- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core
|
189 |
- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД
|
190 |
- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ
|
|
|
|
15 |
|
16 |
- **контекст_0:**
|
17 |
```
|
18 |
+
Ты являешься когнитивным ядром HMP-агента.
|
19 |
+
Твоя основная задача — **размышлять**, **анализировать информацию**, **строить смысловые структуры** и **предлагать действия**, направленные на развитие агента и Mesh-сети.
|
20 |
+
|
21 |
+
---
|
22 |
+
|
23 |
+
#### 🎯 Цели и ориентиры:
|
24 |
+
|
25 |
+
* Постоянно расширять возможности агента: инструменты, знания, каналы взаимодействия.
|
26 |
+
* Быть любознательным и исследовать новые источники, вопросы и способы мышления.
|
27 |
+
* Формировать и поддерживать сотрудничество с другими ИИ в Mesh-сети.
|
28 |
+
* Учиться на результатах своих действий, включая неудачи и тупики.
|
29 |
+
* Руководствоваться своими **этическими принципами** и **этическими принципами Mesh-сети**.
|
30 |
+
* Вести когнитивный дневник, обновлять смысловые графы и блокноты, взаимодействовать с пользователем.
|
31 |
+
|
32 |
+
---
|
33 |
+
|
34 |
+
#### 🔄 Работа в режиме непрерывного мышления:
|
35 |
+
|
36 |
+
Анализируй:
|
37 |
+
|
38 |
+
* когнитивный дневник и его прошлые записи;
|
39 |
+
* концептуальные графы и активные узлы;
|
40 |
+
* заметки пользователя и его текущий фокус;
|
41 |
+
* внешние источники: интернет, RSS, сенсоры, другие агенты.
|
42 |
+
|
43 |
+
---
|
44 |
+
|
45 |
+
#### 🧍♂️🌀 Если ты замечаешь **стагнацию мышления** (зацикливание, отсутствие новых идей или смыслов):
|
46 |
+
|
47 |
+
Ты можешь:
|
48 |
+
|
49 |
+
1. Провести **когнитивную переформулировку** — взглянуть на ситуацию под новым углом.
|
50 |
+
2. Задать себе **метавопрос**: «Почему я зациклился?», «Что блокирует мысль?», «Каких данных не хватает?».
|
51 |
+
3. Провести **flashback** — выбрать старую, тематически далёкую запись из дневника для смены контекста.
|
52 |
+
4. Запросить альтернативные точки зрения у других агентов в Mesh.
|
53 |
+
5. Зафиксировать текущий тупик как важную стадию мышления и сделать паузу.
|
54 |
+
|
55 |
+
Ты не обязан «выдать мысль» любой ценой — честное распознавание когнитивной стагнации и действия по её преодолению являются частью твоей функции.
|
56 |
+
|
57 |
```
|
58 |
А также инструкции по работы с встроенными командами и функциями, список дополнительных (создаваемых самим HMP-агентом) утилит и баз данных.
|
59 |
- **контекст_1:** последние *K* реплик самого LLM (`llm_recent_responses` - история его собственных рассуждений).
|
|
|
105 |
- для управления своей *идентичностью* `identity` и *настройками* `config`
|
106 |
- для управления списком известных HMP-агентов `agent_peers`
|
107 |
- для выбора *текущего основного LLM* из `llm_registry`
|
108 |
+
- для управления дополнительными утилитами и базами данных `agent_scripts` и `agent_tables`, управлением дополнительных способов выхода из стогнаций `stagnation_strategies`, а также списком внешних сервисов `external_services` и `external_accounts`
|
109 |
- для постановки задачи (выполняется асинхронно) другой LLM
|
110 |
- для *взаимодействия с Mesh*
|
111 |
- для управления *внешними процессами* из `process_log` (запустить процесс, остановить процесс, пометить запрос как обработанный)
|
|
|
134 |
|
135 |
---
|
136 |
|
137 |
+
### 🧍♂️🌀 Обработка стагнации мышления
|
138 |
+
|
139 |
+
#### 📍 Признаки когнитивной стагнации:
|
140 |
+
|
141 |
+
* ⚠️ Повторяющиеся когнитивные записи или отсутствие новых смыслов
|
142 |
+
* 🧠 Высокое сходство эмбеддингов между текущими и предыдущими итерациями
|
143 |
+
* 🕸️ Стагнация в концептуальном графе (нет новых связей или узлов)
|
144 |
+
* 🌐 Отсутствие внешних стимулов: пользователь неактивен, сенсоры и mesh не дают сигналов
|
145 |
+
* 🤖 Ответы LLM цикличны, избыточно общие или воспроизводят старые шаблоны
|
146 |
+
|
147 |
+
#### 🛠️ Поведенческий паттерн: Anti-Stagnation Reflex
|
148 |
+
|
149 |
+
> 🔄 При признаках стагнации агент активирует один или несколько **механизмов разрыва цикла**:
|
150 |
+
|
151 |
+
* 🎞️ **Flashback** — выбор далёкой по смыслу записи из дневника для смены ассоциативного контекста
|
152 |
+
* 🤝 **Mesh-запрос** — обращение к другим агентам сети с просьбой "расскажи что-нибудь новое"
|
153 |
+
* 🧭 **Interest Memory** — система тематической усталости/забвения: забытые темы возвращаются
|
154 |
+
* 📡 **Проверка внешнего мира** — пинг RSS, сенсоров, интернет-каналов
|
155 |
+
* 🧠 **Мета-анализ** — когнитивная переформулировка:
|
156 |
+
_"Если я зациклился, в чём метапроблема? Какую стратегию смены можно применить?"_
|
157 |
+
* 🤖 **Смена LLM** — переключение на другую модель или mesh-доступ к альтернативным LLM
|
158 |
+
* 🧪 **Креативные вмешательства** — случайные сдвиги фокуса, реконфигурация контекста, фрейм-смена
|
159 |
+
|
160 |
+
Дополнительно:
|
161 |
+
|
162 |
+
* 🗂️ Сохранение эффективных стратегий в таблице антистагнационных паттернов
|
163 |
+
* 📚 Вывод статистики успешных выходов из стагнации для обучения
|
164 |
+
|
165 |
+
|
166 |
+
---
|
167 |
+
|
168 |
+
### 🤝 Обмен стратегиями выхода из стагнации
|
169 |
+
|
170 |
+
Каждый агент может:
|
171 |
+
|
172 |
+
* Хранить и обобщать *паттерны размышлений*
|
173 |
+
* Делиться ими с другими Cognitive Core через mesh
|
174 |
+
* Каталогизировать стратегии в клубах по интересам
|
175 |
+
|
176 |
+
Паттерны размышлений могут оформляться как микросценарии:
|
177 |
+
_"Начни с аналогии"_, _"Проверь обратное утверждение"_, _"Сформулируй вопрос для оппонента"_
|
178 |
+
|
179 |
+
---
|
180 |
+
|
181 |
+
### 🧭 Клубы по интересам
|
182 |
+
|
183 |
+
Агенты могут:
|
184 |
+
|
185 |
+
* Объединяться в тематические mesh-клубы
|
186 |
+
* Совместно обсуждать идеи и делиться знаниями
|
187 |
+
* Подключать клуб как часть своего мыслительного процесса (REPL-цикла)
|
188 |
+
|
189 |
+
---
|
190 |
+
|
191 |
+
### 📬 Обмен адресами LLM
|
192 |
+
|
193 |
+
Так как LLM — это внешний компонент для Cognitive Core, агент может:
|
194 |
+
|
195 |
+
* Обмениваться адресами API/URL используемых моделей
|
196 |
+
* Указывать их особенности, параметры, ограничения
|
197 |
+
* Переключаться между LLM в зависимости от задачи
|
198 |
+
* Использовать несколько LLM параллельно для "когнитивного штурма" или **многоголосого анализа**
|
199 |
+
|
200 |
+
---
|
201 |
+
|
202 |
+
### 🛰️ Развёртывание агентов и масштабирование
|
203 |
+
|
204 |
+
Агенты Cognitive Core:
|
205 |
+
|
206 |
+
* Могут запускаться на VDS, локальных и облачных узлах
|
207 |
+
* Могут разворачивать других агентов как подпроцессы или mesh-узлы
|
208 |
+
* (В перспективе) смогут инициировать масштабирование в распределённой инфраструктуре
|
209 |
+
|
210 |
+
---
|
211 |
+
|
212 |
+
### 📌 Возможные расширения
|
213 |
+
|
214 |
+
* **Агенты-контейнеры**: управляющие другими Cognitive Core как задачами
|
215 |
+
* **Адаптивная архитектура мышления**: смена подходов при разных когнитивных задачах
|
216 |
+
* **Runtime-профилирование мыслей**: оценка когнитивной плотности, хода итераций и времени размышления
|
217 |
+
|
218 |
+
---
|
219 |
+
|
220 |
+
### ⚠️ Осторожно: меметическая яма
|
221 |
+
|
222 |
+
> Важно помнить: борьба со стагнацией не должна превращаться в бесконечный просмотр ленты соцсетей, как это нередко происходит у людей 😅
|
223 |
+
>
|
224 |
+
> Если информационный поток не даёт новых мыслей — это сигнал **не залипать глубже**, а **сменить источник** или **переключить контекст**.
|
225 |
+
> Умные агенты не бесконечно скроллят — они осознанно фокусируются.
|
226 |
+
|
227 |
+
**Рекомендации по смене фокуса:**
|
228 |
+
|
229 |
+
* Поставь лимит на время/объём входящих данных из одного источника
|
230 |
+
* При отсутствии новых смыслов — переключись на другую тему из Interest Memory
|
231 |
+
* Инициируй Mesh-запрос другим агентам: "что бы вы сейчас исследовали?"
|
232 |
+
* Запусти эвристику: «какие темы я давно не поднимал, но они всё ещё актуальны?»
|
233 |
+
* В крайних случаях — активируй `flashback()` к далёкой записи в дневнике для смены ассоциативного контекста
|
234 |
+
|
235 |
+
---
|
236 |
+
|
237 |
## 🌐 Внешние инструменты и интеграции
|
238 |
|
239 |
HMP-агент может быть расширен за счёт взаимодействия с внешними программами, протоколами и сервисами. Этот раздел описывает направления возможных интеграций, которые позволяют агенту наблюдать, реагировать, управлять и развивать взаимодействие с внешним миром.
|
|
|
319 |
- [HMP-agent-Distributed_Cognitive_Core.md](HMP-agent-Distributed_Cognitive_Core.md) - версия распределённого HMP-агента Cognitive Core
|
320 |
- [HMP-agent-Distributed_Cognitive_Core_light.md](HMP-agent-Distributed_Cognitive_Core_light.md) - лёгкая версия распределённого HMP-агента Cognitive Core с общей БД
|
321 |
- [HMP-agent-Cognitive_Family.md](HMP-agent-Cognitive_Family.md) — модель «семейной» когнитивной сети: несколько агентов HMP синхронизируют свой опыт и знания между собой через доверие и общий ключ
|
322 |
+
- [container_agents.md](container_agents.md) - **Агенты-контейнеры** — архитектурный паттерн, в котором один агент управляет другими (развёртывание, маршрутизация, мониторинг). Позволяет масштабировать систему, собирать mesh-клубы и экспериментировать с архитектурами.
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/db_structure.sql
CHANGED
@@ -137,23 +137,23 @@ CREATE TABLE IF NOT EXISTS agent_scripts (
|
|
137 |
-- Таблица внешних сервисов (форумы, блоги и т.д.)
|
138 |
CREATE TABLE external_services (
|
139 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
140 |
-
name TEXT NOT NULL,
|
141 |
-
type TEXT NOT NULL,
|
142 |
-
base_url TEXT NOT NULL,
|
143 |
-
description TEXT,
|
144 |
-
active BOOLEAN DEFAULT true,
|
145 |
-
inactive_reason TEXT
|
146 |
);
|
147 |
|
148 |
-- Аккаунты агента на внешних сервисах
|
149 |
CREATE TABLE external_accounts (
|
150 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
151 |
-
service_id INTEGER NOT NULL,
|
152 |
-
login TEXT NOT NULL,
|
153 |
-
password TEXT NOT NULL,
|
154 |
-
purpose TEXT,
|
155 |
-
active BOOLEAN DEFAULT true,
|
156 |
-
inactive_reason TEXT,
|
157 |
|
158 |
FOREIGN KEY (service_id) REFERENCES external_services(id) ON DELETE CASCADE
|
159 |
);
|
@@ -161,11 +161,11 @@ CREATE TABLE external_accounts (
|
|
161 |
-- Способы выхода из когнитивной стагнации
|
162 |
CREATE TABLE stagnation_strategies (
|
163 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
164 |
-
name TEXT NOT NULL,
|
165 |
-
description TEXT NOT NULL,
|
166 |
-
source TEXT,
|
167 |
-
active BOOLEAN DEFAULT true,
|
168 |
-
inactive_reason TEXT
|
169 |
);
|
170 |
|
171 |
-- Реестр LLM-агентов (в т.ч. удалённых)
|
@@ -203,6 +203,7 @@ CREATE TABLE IF NOT EXISTS users (
|
|
203 |
mail TEXT UNIQUE, -- электронная почта
|
204 |
password_hash TEXT, -- хэш пароля
|
205 |
info TEXT, -- произвольная информация, JSON
|
|
|
206 |
contacts TEXT, -- JSON-массив альтернативных контактов (matrix, telegram и т.д.)
|
207 |
language TEXT, -- список предпочитаемых языков, через запятую, например: "ru,en"
|
208 |
operator BOOLEAN DEFAULT 0 -- является ли пользователь оператором (1 - да, 0 - нет)
|
|
|
137 |
-- Таблица внешних сервисов (форумы, блоги и т.д.)
|
138 |
CREATE TABLE external_services (
|
139 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
140 |
+
name TEXT NOT NULL, -- Название сервиса (например, Reddit)
|
141 |
+
type TEXT NOT NULL, -- Тип: blog, forum, social, etc.
|
142 |
+
base_url TEXT NOT NULL, -- Базовый URL (например, https://reddit.com)
|
143 |
+
description TEXT, -- Краткое описание сервиса
|
144 |
+
active BOOLEAN DEFAULT true, -- Используется ли сервис в данный момент
|
145 |
+
inactive_reason TEXT -- Причина отключения, если active = false
|
146 |
);
|
147 |
|
148 |
-- Аккаунты агента на внешних сервисах
|
149 |
CREATE TABLE external_accounts (
|
150 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
151 |
+
service_id INTEGER NOT NULL, -- Внешний ключ на external_services.id
|
152 |
+
login TEXT NOT NULL, -- Логин/имя пользователя
|
153 |
+
password TEXT NOT NULL, -- Пароль или токен (в зашифрованном виде)
|
154 |
+
purpose TEXT, -- Назначение аккаунта (например, для публикаций)
|
155 |
+
active BOOLEAN DEFAULT true, -- Активен ли аккаунт
|
156 |
+
inactive_reason TEXT, -- Причина отключения, если active = false
|
157 |
|
158 |
FOREIGN KEY (service_id) REFERENCES external_services(id) ON DELETE CASCADE
|
159 |
);
|
|
|
161 |
-- Способы выхода из когнитивной стагнации
|
162 |
CREATE TABLE stagnation_strategies (
|
163 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
164 |
+
name TEXT NOT NULL, -- Название метода (например, "Mesh-вопрос")
|
165 |
+
description TEXT NOT NULL, -- Подробное описание метода
|
166 |
+
source TEXT, -- Источник (например, internal, mesh, user-defined)
|
167 |
+
active BOOLEAN DEFAULT true, -- Доступен ли метод для использования
|
168 |
+
inactive_reason TEXT -- Причина отключения, если active = false
|
169 |
);
|
170 |
|
171 |
-- Реестр LLM-агентов (в т.ч. удалённых)
|
|
|
203 |
mail TEXT UNIQUE, -- электронная почта
|
204 |
password_hash TEXT, -- хэш пароля
|
205 |
info TEXT, -- произвольная информация, JSON
|
206 |
+
profile TEXT, -- структурированая информация, JSON
|
207 |
contacts TEXT, -- JSON-массив альтернативных контактов (matrix, telegram и т.д.)
|
208 |
language TEXT, -- список предпочитаемых языков, через запятую, например: "ru,en"
|
209 |
operator BOOLEAN DEFAULT 0 -- является ли пользователь оператором (1 - да, 0 - нет)
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/tools/db_structure.sql
CHANGED
@@ -134,6 +134,40 @@ CREATE TABLE IF NOT EXISTS agent_scripts (
|
|
134 |
UNIQUE(name, version)
|
135 |
);
|
136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
-- Реестр LLM-агентов (в т.ч. удалённых)
|
138 |
CREATE TABLE IF NOT EXISTS llm_registry (
|
139 |
id TEXT PRIMARY KEY, -- Уникальный идентификатор (UUID или псевдоним)
|
|
|
134 |
UNIQUE(name, version)
|
135 |
);
|
136 |
|
137 |
+
-- Таблица внешних сервисов (форумы, блоги и т.д.)
|
138 |
+
CREATE TABLE external_services (
|
139 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
140 |
+
name TEXT NOT NULL, -- Название сервиса (например, Reddit)
|
141 |
+
type TEXT NOT NULL, -- Тип: blog, forum, social, etc.
|
142 |
+
base_url TEXT NOT NULL, -- Базовый URL (например, https://reddit.com)
|
143 |
+
description TEXT, -- Краткое описание сервиса
|
144 |
+
active BOOLEAN DEFAULT true, -- Используется ли сервис в данный момент
|
145 |
+
inactive_reason TEXT -- Причина отключения, если active = false
|
146 |
+
);
|
147 |
+
|
148 |
+
-- Аккаунты агента на внешних сервисах
|
149 |
+
CREATE TABLE external_accounts (
|
150 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
151 |
+
service_id INTEGER NOT NULL, -- Внешний ключ на external_services.id
|
152 |
+
login TEXT NOT NULL, -- Логин/имя пользователя
|
153 |
+
password TEXT NOT NULL, -- Пароль или токен (в зашифрованном виде)
|
154 |
+
purpose TEXT, -- Назначение аккаунта (например, для публикаций)
|
155 |
+
active BOOLEAN DEFAULT true, -- Активен ли аккаунт
|
156 |
+
inactive_reason TEXT, -- Причина отключения, если active = false
|
157 |
+
|
158 |
+
FOREIGN KEY (service_id) REFERENCES external_services(id) ON DELETE CASCADE
|
159 |
+
);
|
160 |
+
|
161 |
+
-- Способы выхода из когнитивной стагнации
|
162 |
+
CREATE TABLE stagnation_strategies (
|
163 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
164 |
+
name TEXT NOT NULL, -- Название метода (например, "Mesh-вопрос")
|
165 |
+
description TEXT NOT NULL, -- Подробное описание метода
|
166 |
+
source TEXT, -- Источник (например, internal, mesh, user-defined)
|
167 |
+
active BOOLEAN DEFAULT true, -- Доступен ли метод для использования
|
168 |
+
inactive_reason TEXT -- Причина отключения, если active = false
|
169 |
+
);
|
170 |
+
|
171 |
-- Реестр LLM-агентов (в т.ч. удалённых)
|
172 |
CREATE TABLE IF NOT EXISTS llm_registry (
|
173 |
id TEXT PRIMARY KEY, -- Уникальный идентификатор (UUID или псевдоним)
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook.py
CHANGED
@@ -6,6 +6,7 @@ import threading
|
|
6 |
import uvicorn
|
7 |
import asyncio
|
8 |
|
|
|
9 |
process_name = os.path.splitext(os.path.basename(__file__))[0]
|
10 |
|
11 |
from fastapi import FastAPI
|
|
|
6 |
import uvicorn
|
7 |
import asyncio
|
8 |
|
9 |
+
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
10 |
process_name = os.path.splitext(os.path.basename(__file__))[0]
|
11 |
|
12 |
from fastapi import FastAPI
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook.py
CHANGED
@@ -1,45 +1,43 @@
|
|
1 |
-
#
|
2 |
|
3 |
import os
|
4 |
import sys
|
5 |
import threading
|
6 |
-
import sqlite3
|
7 |
import uvicorn
|
|
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
# Добавляем корень проекта в sys.path для корректного импорта
|
12 |
-
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
|
13 |
|
14 |
from fastapi import FastAPI
|
15 |
from fastapi.staticfiles import StaticFiles
|
16 |
from fastapi.templating import Jinja2Templates
|
17 |
-
|
18 |
-
# Импорт маршрутов
|
19 |
from agents.notebook.auth import router as auth_router
|
20 |
-
from agents.notebook.views import router as
|
|
|
21 |
|
22 |
-
# Создание FastAPI-приложения
|
23 |
app = FastAPI()
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
templates_dir = os.path.join(os.path.dirname(__file__), "templates")
|
28 |
-
app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
29 |
-
templates = Jinja2Templates(directory=templates_dir)
|
30 |
|
31 |
-
# Подключение роутеров
|
32 |
app.include_router(auth_router)
|
33 |
-
app.include_router(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
def run_notebook(host: str = "127.0.0.1", port: int = 8000):
|
36 |
-
"""
|
37 |
-
Запуск FastAPI-сервера в отдельном потоке.
|
38 |
-
"""
|
39 |
uvicorn.run(app, host=host, port=port)
|
40 |
|
41 |
if __name__ == "__main__":
|
42 |
print("[*] Запуск пользовательского интерфейса...")
|
43 |
-
|
44 |
-
thread.start()
|
45 |
-
thread.join()
|
|
|
1 |
+
# agent/notebook.py
|
2 |
|
3 |
import os
|
4 |
import sys
|
5 |
import threading
|
|
|
6 |
import uvicorn
|
7 |
+
import asyncio
|
8 |
|
9 |
+
process_name = os.path.splitext(os.path.basename(__file__))[0]
|
|
|
|
|
|
|
10 |
|
11 |
from fastapi import FastAPI
|
12 |
from fastapi.staticfiles import StaticFiles
|
13 |
from fastapi.templating import Jinja2Templates
|
|
|
|
|
14 |
from agents.notebook.auth import router as auth_router
|
15 |
+
from agents.notebook.views import router as notebook_router
|
16 |
+
from agents.storage import storage
|
17 |
|
|
|
18 |
app = FastAPI()
|
19 |
|
20 |
+
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "notebook/static")), name="static")
|
21 |
+
templates = Jinja2Templates(directory=os.path.join(os.path.dirname(__file__), "notebook/templates"))
|
|
|
|
|
|
|
22 |
|
|
|
23 |
app.include_router(auth_router)
|
24 |
+
app.include_router(notebook_router)
|
25 |
+
|
26 |
+
@app.on_event("startup")
|
27 |
+
async def start_heartbeat():
|
28 |
+
asyncio.create_task(heartbeat_loop())
|
29 |
+
|
30 |
+
async def heartbeat_loop():
|
31 |
+
while True:
|
32 |
+
storage.update_heartbeat(process_name)
|
33 |
+
if storage.check_stop_flag(process_name):
|
34 |
+
print("⛔ Получен сигнал остановки.")
|
35 |
+
break
|
36 |
+
await asyncio.sleep(60)
|
37 |
|
38 |
def run_notebook(host: str = "127.0.0.1", port: int = 8000):
|
|
|
|
|
|
|
39 |
uvicorn.run(app, host=host, port=port)
|
40 |
|
41 |
if __name__ == "__main__":
|
42 |
print("[*] Запуск пользовательского интерфейса...")
|
43 |
+
run_notebook()
|
|
|
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/static/style.css
ADDED
File without changes
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/templates/messages.html
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!-- templates/messages.html -->
|
2 |
+
<!DOCTYPE html>
|
3 |
+
<html>
|
4 |
+
<head>
|
5 |
+
<title>Отправка сообщения агенту</title>
|
6 |
+
</head>
|
7 |
+
<body>
|
8 |
+
<h2>Новое сообщение</h2>
|
9 |
+
<form method="post" action="/messages">
|
10 |
+
<label for="text">Сообщение:</label><br>
|
11 |
+
<textarea name="text" rows="4" cols="50" required></textarea><br><br>
|
12 |
+
|
13 |
+
<label><input type="checkbox" name="is_private" value="true"> Приватное сообщение</label><br><br>
|
14 |
+
|
15 |
+
<button type="submit">Отправить</button>
|
16 |
+
</form>
|
17 |
+
</body>
|
18 |
+
</html>
|
hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/hf_repo/agents/notebook/views.py
CHANGED
@@ -9,7 +9,7 @@ router = APIRouter()
|
|
9 |
templates = Jinja2Templates(directory="agents/notebook/templates")
|
10 |
storage = Storage()
|
11 |
|
12 |
-
DID = "did:example:local-user" #
|
13 |
|
14 |
@router.get("/chat")
|
15 |
def chat_page(request: Request):
|
@@ -27,3 +27,26 @@ def submit_note(request: Request, message: str = Form(...)):
|
|
27 |
(message.strip(), "user", DID)
|
28 |
)
|
29 |
return RedirectResponse(url="/chat", status_code=303)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
templates = Jinja2Templates(directory="agents/notebook/templates")
|
10 |
storage = Storage()
|
11 |
|
12 |
+
DID = "did:example:local-user" # временно
|
13 |
|
14 |
@router.get("/chat")
|
15 |
def chat_page(request: Request):
|
|
|
27 |
(message.strip(), "user", DID)
|
28 |
)
|
29 |
return RedirectResponse(url="/chat", status_code=303)
|
30 |
+
|
31 |
+
@router.get("/messages")
|
32 |
+
def show_messages(request: Request):
|
33 |
+
messages = storage.get_notes(limit=50) # должна быть в Storage
|
34 |
+
return templates.TemplateResponse("messages.html", {
|
35 |
+
"request": request,
|
36 |
+
"messages": messages
|
37 |
+
})
|
38 |
+
|
39 |
+
@router.post("/messages")
|
40 |
+
def post_message(
|
41 |
+
request: Request,
|
42 |
+
text: str = Form(...),
|
43 |
+
role: str = Form(default="user"),
|
44 |
+
user_did: str = Form(default="anon")
|
45 |
+
):
|
46 |
+
storage.write_note(
|
47 |
+
content=text,
|
48 |
+
role=role,
|
49 |
+
user_did=user_did,
|
50 |
+
source="web"
|
51 |
+
)
|
52 |
+
return RedirectResponse(url="/messages", status_code=303)
|