File size: 5,199 Bytes
b8989d2
 
d1b70e9
 
 
 
 
 
9d7a35f
 
d1b70e9
9d7a35f
d1b70e9
6b091cc
d1b70e9
 
 
 
 
5ad94a3
d1b70e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ad94a3
 
 
 
 
 
 
 
 
 
d1b70e9
 
 
 
 
 
 
 
 
 
 
 
 
 
6b091cc
 
 
 
 
d1b70e9
 
5ad94a3
 
 
6b091cc
5ad94a3
 
 
 
 
 
 
 
 
d1b70e9
 
 
 
 
 
 
 
5ad94a3
 
 
 
 
 
 
 
d1b70e9
 
 
 
 
 
 
 
 
9eba3ee
 
 
c2c4e33
 
 
9eba3ee
 
 
 
 
 
 
 
9d7a35f
 
 
 
 
 
 
 
 
 
 
 
d1b70e9
9d7a35f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1b70e9
9d7a35f
24e9ff4
 
9d7a35f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# agents/init.py

import os
import sys
import yaml
import json
import time
import uuid
import sqlite3

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from datetime import datetime
from werkzeug.security import generate_password_hash
from tools.storage import Storage
from tools.identity import generate_did
from tools.crypto import generate_keypair
from tools.config_utils import update_config

CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.yml")

def load_config(path):
    with open(path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)

def save_config(path, config):
    with open(path, 'w', encoding='utf-8') as f:
        yaml.dump(config, f, allow_unicode=True)

def init_identity(storage, config):
    if not config.get("agent_id"):
        did = generate_did()
        pubkey, privkey = generate_keypair()
        identity_id = did.split(":")[-1]

        identity = {
            "id": identity_id,
            "name": config.get("agent_name", "Unnamed"),
            "pubkey": pubkey,
            "privkey": privkey,
            "metadata": json.dumps({"role": config.get("agent_role", "core")}),
            "created_at": datetime.utcnow().isoformat(),
            "updated_at": datetime.utcnow().isoformat()
        }
        storage.add_identity(identity)

        # Обновляем config.yml
        config["agent_id"] = did
        config["identity_agent"] = identity_id
        save_config(CONFIG_PATH, config)
        print(f"[+] Создана личность: {identity_id}")
    else:
        print("[=] agent_id уже задан, пропускаем генерацию DiD.")

def init_user(storage, config):
    user = config.get("default_user", {})
    if not user.get("email"):
        print("[-] Не указан email пользователя — пропуск.")
        return
    password = user.get("password")
    if not password:
        print("[-] Не указан пароль пользователя — пропуск.")
        return
    password_hash = generate_password_hash(password)

    did = generate_did()
    user_entry = {
        "username": user.get("username", "user"),
        "mail": user["email"],
        "password_hash": password_hash,
        "did": did,
        "ban": None,
        "info": json.dumps({}),
        "contacts": json.dumps([]),
        "language": "ru,en",
        "operator": 1
    }
    storage.add_user(user_entry)

    print(f"[+] Пользователь {user['username']} добавлен.")

def init_llm_backends(storage, config):
    backends = config.get("llm_backends", [])
    storage.clear_llm_registry()
    for backend in backends:
        backend_id = str(uuid.uuid4())
        desc = f"{backend.get('type', 'unknown')} model"
        llm = {
            "id": backend_id,
            "name": backend["name"],
            "endpoint": desc,
            "metadata": json.dumps(backend),
            "created_at": datetime.utcnow().isoformat()
        }
        storage.add_llm(llm)
        print(f"[+] Зарегистрирован LLM: {backend['name']}")

def init_config_table(storage, config):
    exclude_keys = {"default_user", "llm_backends"}
    flat_config = {k: v for k, v in config.items() if k not in exclude_keys}
    for key, value in flat_config.items():
        storage.set_config(key, json.dumps(value))
    print("[+] Конфигурация сохранена в БД.")

def ensure_directories(config):
    directories = [
        config.get("data_dir", "./data"),
        config.get("log_dir", "./logs"),
       # добавь другие директории при необходимости
   ]

    for path in directories:
        if path and not os.path.exists(path):
            os.makedirs(path)
            print(f"[+] Создан каталог: {path}")
        else:
            print(f"[=] Каталог уже существует: {path}")

def is_db_initialized(db_path):
    if not os.path.exists(db_path):
        return False
    try:
        with sqlite3.connect(db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='identity'")
            return cursor.fetchone() is not None
    except Exception:
        return False

def ensure_db_initialized():
    config = load_config(CONFIG_PATH)
    db_path = config.get("db_path", "./data/agent_storage.db")

    if not is_db_initialized(db_path):
        print("[*] БД не инициализирована — выполняем инициализацию.")
        try:
            ensure_directories(config)
            storage = Storage(config)
            init_identity(storage, config)
            init_user(storage, config)
            init_llm_backends(storage, config)
            init_config_table(storage, config)
            save_config(CONFIG_PATH, config)
        except Exception as e:
            print(f"[!] Ошибка при инициализации: {e}")
            sys.exit(1)
    else:
        print("[=] БД уже инициализирована.")

    return config

if __name__ == "__main__":
    ensure_db_initialized()