ki-brain / src /main.cpp
Arian8888's picture
Fallback auf Llama wenn Web-Suche nichts findet (DuckDuckGo blockt manchmal HF)
aa7d3d8
Raw History Blame Contribute Delete
42.5 kB
// Brian Server - HTTP API + Web Dashboard.
// Built on cpp-httplib (single header, fetched by CMake).
#include "httplib.h"
#include "bot.h"
#include "tinylm.h"
#include "github.h"
#include "hfhub.h"
#include "llm_backend.h"
#include "web.h"
#include <curl/curl.h>
#include <atomic>
#include <thread>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <mutex>
#include <random>
#include <sstream>
#include <map>
#include <ctime>
#include <unordered_set>
// ---------- JSON Helpers (hand-rolled, einfache Daten) ----------
static std::string json_escape(const std::string& s) {
std::string o; o.reserve(s.size() + 8);
for (unsigned char c : s) {
switch (c) {
case '"': o += "\\\""; break;
case '\\': o += "\\\\"; break;
case '\n': o += "\\n"; break;
case '\r': o += "\\r"; break;
case '\t': o += "\\t"; break;
case '\b': o += "\\b"; break;
case '\f': o += "\\f"; break;
default:
if (c < 0x20) { char buf[8]; std::snprintf(buf, sizeof(buf), "\\u%04x", c); o += buf; }
else o += (char)c;
}
}
return o;
}
static std::string parse_json_string(const std::string& body, const std::string& key) {
// Sehr einfacher Parser fuer {"key":"value"} -- ausreichend fuer unseren Fall
std::string needle = "\"" + key + "\"";
size_t p = body.find(needle);
if (p == std::string::npos) return "";
p = body.find(":", p);
if (p == std::string::npos) return "";
p = body.find("\"", p);
if (p == std::string::npos) return "";
++p;
std::string out;
while (p < body.size()) {
char c = body[p];
if (c == '\\' && p + 1 < body.size()) {
char n = body[p+1];
switch (n) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
default: out += n; break;
}
p += 2;
} else if (c == '"') break;
else { out += c; ++p; }
}
return out;
}
// ---------- Agent-Tracking ----------
struct AgentInfo { std::string ip; std::string user_agent; long long last_seen; int polls; };
static std::map<std::string, AgentInfo> g_agents;
static std::mutex g_agents_mtx;
static void track_agent(const httplib::Request& req) {
auto ua_it = req.headers.find("User-Agent");
std::string ua = ua_it != req.headers.end() ? ua_it->second : "";
std::string ip = req.remote_addr;
auto xff = req.headers.find("X-Forwarded-For");
if (xff != req.headers.end()) ip = xff->second;
std::string key = ip + "|" + ua;
std::lock_guard<std::mutex> lk(g_agents_mtx);
auto& a = g_agents[key];
a.ip = ip; a.user_agent = ua;
a.last_seen = (long long)std::time(nullptr);
a.polls++;
}
// ---------- Auth ----------
static std::string g_password;
static std::unordered_set<std::string> g_sessions;
static std::mutex g_sess_mtx;
static std::string gen_token() {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<uint64_t> dis;
char buf[33];
std::snprintf(buf, sizeof(buf), "%016llx%016llx",
(unsigned long long)dis(gen), (unsigned long long)dis(gen));
return std::string(buf);
}
static std::string get_cookie(const httplib::Request& req, const std::string& name) {
auto it = req.headers.find("Cookie");
if (it == req.headers.end()) return "";
const std::string& c = it->second;
size_t p = c.find(name + "=");
if (p == std::string::npos) return "";
p += name.size() + 1;
size_t e = c.find(";", p);
return c.substr(p, e == std::string::npos ? std::string::npos : e - p);
}
static bool is_authed(const httplib::Request& req) {
std::string t = get_cookie(req, "brian_session");
if (t.empty()) return false;
std::lock_guard<std::mutex> lk(g_sess_mtx);
return g_sessions.count(t) > 0;
}
static void require_auth_or_401(const httplib::Request& req, httplib::Response& res, std::function<void()> fn) {
if (!is_authed(req)) { res.status = 401; res.set_content("{\"error\":\"unauth\"}", "application/json"); return; }
fn();
}
// ---------- Static Files ----------
static std::string read_file(const std::string& path) {
std::ifstream f(path, std::ios::binary);
if (!f) return "";
std::ostringstream ss; ss << f.rdbuf();
return ss.str();
}
int main() {
const char* pw = std::getenv("BRIAN_PASSWORD");
g_password = pw ? pw : "brian"; // Standard nur fuer lokales Testen!
const char* port_s = std::getenv("PORT");
int port = port_s ? std::atoi(port_s) : 8080;
const char* db_s = std::getenv("BRIAN_DB");
std::string db_path = db_s ? db_s : "/data/brain.db";
const char* web_s = std::getenv("BRIAN_WEB");
std::string web_dir = web_s ? web_s : "web";
curl_global_init(CURL_GLOBAL_DEFAULT);
gh::init(); // GitHub Sync (Topics)
hf::init(); // HF Hub Dataset Sync (Brain-Code, Konversationen, Modell)
llm::init_async(); // Llama 8B GGUF im Hintergrund laden
Brian brian(db_path);
// TinyLM - eigenes kleines Sprachmodell, persistiert in /data/tinylm.bin
TinyLM lm;
std::string lm_path = (db_s ? std::string(db_s) : "/data/brain.db") + ".tinylm";
lm.load(lm_path); // ignoriert wenn Datei fehlt
std::atomic<bool> lm_training{false};
httplib::Server svr;
svr.set_payload_max_length(8 * 1024 * 1024);
// Static
svr.set_mount_point("/static", web_dir);
svr.Get("/", [&](const httplib::Request&, httplib::Response& res) {
std::string html = read_file(web_dir + "/index.html");
if (html.empty()) { res.status = 500; res.set_content("index.html nicht gefunden", "text/plain"); return; }
res.set_content(html, "text/html; charset=utf-8");
});
// ----- Auth -----
svr.Post("/api/login", [&](const httplib::Request& req, httplib::Response& res) {
std::string pw = parse_json_string(req.body, "password");
if (pw == g_password) {
std::string t = gen_token();
{ std::lock_guard<std::mutex> lk(g_sess_mtx); g_sessions.insert(t); }
res.set_header("Set-Cookie", "brian_session=" + t + "; HttpOnly; Path=/; SameSite=Lax; Max-Age=2592000");
res.set_content("{\"ok\":true}", "application/json");
} else {
res.status = 401;
res.set_content("{\"error\":\"falsches passwort\"}", "application/json");
}
});
svr.Post("/api/logout", [&](const httplib::Request& req, httplib::Response& res) {
std::string t = get_cookie(req, "brian_session");
if (!t.empty()) { std::lock_guard<std::mutex> lk(g_sess_mtx); g_sessions.erase(t); }
res.set_header("Set-Cookie", "brian_session=; Max-Age=0; Path=/");
res.set_content("{\"ok\":true}", "application/json");
});
svr.Get("/api/me", [&](const httplib::Request& req, httplib::Response& res) {
res.set_content(std::string("{\"auth\":") + (is_authed(req) ? "true" : "false") + "}", "application/json");
});
// ----- Topics -----
svr.Get("/api/topics", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto ts = brian.db().all_topics();
std::ostringstream out;
out << "[";
for (size_t i = 0; i < ts.size(); ++i) {
if (i) out << ",";
out << "{\"name\":\"" << json_escape(ts[i].name)
<< "\",\"updated_at\":" << ts[i].updated_at
<< ",\"preview\":\"" << json_escape(ts[i].content.substr(0, 120)) << "\"}";
}
out << "]";
res.set_content(out.str(), "application/json; charset=utf-8");
});
});
svr.Get("/api/topic", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string name = req.get_param_value("name");
auto t = brian.db().get_topic(name);
std::ostringstream out;
out << "{\"name\":\"" << json_escape(t.name)
<< "\",\"content\":\"" << json_escape(t.content)
<< "\",\"sources\":\"" << json_escape(t.sources)
<< "\",\"updated_at\":" << t.updated_at << "}";
res.set_content(out.str(), "application/json; charset=utf-8");
});
});
svr.Post("/api/topic", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string name = parse_json_string(req.body, "name");
std::string content = parse_json_string(req.body, "content");
std::string sources = parse_json_string(req.body, "sources");
if (name.empty()) { res.status = 400; res.set_content("{\"error\":\"name fehlt\"}", "application/json"); return; }
brian.db().save_topic(name, content, sources);
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- Rules -----
svr.Get("/api/rules", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string r = brian.db().get_rules();
res.set_content("{\"content\":\"" + json_escape(r) + "\"}", "application/json; charset=utf-8");
});
});
svr.Post("/api/rules", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string c = parse_json_string(req.body, "content");
// Schutz: Sektion "## Regeln" muss vorhanden bleiben
if (c.find("## Regeln") == std::string::npos) {
res.status = 400;
res.set_content("{\"error\":\"Sektion '## Regeln' darf nicht entfernt werden\"}", "application/json");
return;
}
brian.db().set_rules(c);
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- Brain-Files (Datei-Browser) -----
svr.Get("/api/brain/tree", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto files = brian.db().list_brain_files();
std::ostringstream o; o << "[";
for (size_t i = 0; i < files.size(); ++i) {
if (i) o << ",";
o << "{\"path\":\"" << json_escape(files[i].path)
<< "\",\"is_dir\":" << files[i].is_dir
<< ",\"updated_at\":" << files[i].updated_at << "}";
}
o << "]";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
svr.Get("/api/brain/file", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string path = req.get_param_value("path");
auto f = brian.db().get_brain_file(path);
std::ostringstream o;
o << "{\"path\":\"" << json_escape(f.path)
<< "\",\"content\":\"" << json_escape(f.content)
<< "\",\"is_dir\":" << f.is_dir << "}";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
svr.Post("/api/brain/file", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string path = parse_json_string(req.body, "path");
std::string content = parse_json_string(req.body, "content");
std::string is_dir_s = parse_json_string(req.body, "is_dir");
if (path.empty()) { res.status = 400; res.set_content("{\"error\":\"path\"}", "application/json"); return; }
int is_dir = (is_dir_s == "1" || is_dir_s == "true") ? 1 : 0;
brian.db().save_brain_file(path, content, is_dir);
// GitHub-Sync
if (hf::enabled() && !is_dir) {
hf::put_file("brain/" + path, content, "update " + path);
}
res.set_content("{\"ok\":true}", "application/json");
});
});
svr.Post("/api/brain/delete", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string path = parse_json_string(req.body, "path");
brian.db().delete_brain_file(path);
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- Code-History (fuer Rollback) -----
svr.Get("/api/code/history", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto v = brian.db().list_code_versions();
std::ostringstream o; o << "[";
for (size_t i = 0; i < v.size(); ++i) {
if (i) o << ",";
o << "{\"id\":" << v[i].first << ",\"note\":\"" << json_escape(v[i].second) << "\"}";
}
o << "]";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
svr.Get("/api/code/version", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string id = req.get_param_value("id");
std::string c = brian.db().get_code_version(std::stoll(id));
res.set_content("{\"content\":\"" + json_escape(c) + "\"}", "application/json; charset=utf-8");
});
});
svr.Post("/api/code/revert", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string id_s = parse_json_string(req.body, "id");
std::string c = brian.db().get_code_version(std::stoll(id_s));
if (c.empty()) { res.status = 404; res.set_content("{\"error\":\"version not found\"}", "application/json"); return; }
brian.db().set_rules(c);
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- Chat -----
svr.Post("/api/chat", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string msg = parse_json_string(req.body, "msg");
if (msg.empty()) { res.status = 400; res.set_content("{\"error\":\"msg fehlt\"}", "application/json"); return; }
auto r = brian.chat(msg);
std::ostringstream out;
out << "{\"reply\":\"" << json_escape(r.reply)
<< "\",\"topic_learned\":\"" << json_escape(r.topic_learned)
<< "\",\"sources\":[";
for (size_t i = 0; i < r.sources.size(); ++i) {
if (i) out << ",";
out << "\"" << json_escape(r.sources[i]) << "\"";
}
out << "]}";
res.set_content(out.str(), "application/json; charset=utf-8");
});
});
svr.Post("/api/reset", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{ brian.reset_history(); res.set_content("{\"ok\":true}", "application/json"); });
});
// ----- Approval-Queue: Aktionen die der Bot ausfuehren will -----
svr.Get("/api/actions", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto list = brian.db().list_pending_actions();
std::ostringstream out; out << "[";
for (size_t i = 0; i < list.size(); ++i) {
if (i) out << ",";
out << "{\"id\":" << list[i].id
<< ",\"kind\":\"" << json_escape(list[i].kind) << "\""
<< ",\"title\":\"" << json_escape(list[i].title) << "\""
<< ",\"payload\":\"" << json_escape(list[i].payload) << "\""
<< ",\"created_at\":" << list[i].created_at << "}";
}
out << "]";
res.set_content(out.str(), "application/json; charset=utf-8");
});
});
svr.Post("/api/actions/approve", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string id_s = parse_json_string(req.body, "id");
if (id_s.empty()) { res.status = 400; res.set_content("{\"error\":\"id\"}", "application/json"); return; }
long long id = std::stoll(id_s);
auto a = brian.db().get_pending_action(id);
if (!a.id) { res.status = 404; res.set_content("{\"error\":\"not found\"}", "application/json"); return; }
// Aktion ausfuehren je nach kind
if (a.kind == "rule_change") {
brian.db().set_rules(a.payload);
} else if (a.kind == "shell_cmd" || a.kind == "file_write" || a.kind == "read_file" || a.kind == "list_dir") {
// Befehl in die Agent-Queue legen, damit lokale .exe ihn ausfuehrt
brian.db().queue_agent_task(a.kind, a.payload);
}
// andere Typen koennen hier ergaenzt werden
brian.db().set_action_status(id, "approved");
res.set_content("{\"ok\":true}", "application/json");
});
});
svr.Post("/api/actions/reject", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string id_s = parse_json_string(req.body, "id");
long long id = std::stoll(id_s);
brian.db().set_action_status(id, "rejected");
res.set_content("{\"ok\":true}", "application/json");
});
});
// Test-Endpunkt: User legt selbst Aktion in Queue (z.B. "fuehre Befehl X aus")
svr.Post("/api/actions/propose", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string kind = parse_json_string(req.body, "kind");
std::string title = parse_json_string(req.body, "title");
std::string payload = parse_json_string(req.body, "payload");
long long id = brian.db().add_pending_action(kind, title, payload);
std::ostringstream o; o << "{\"id\":" << id << "}";
res.set_content(o.str(), "application/json");
});
});
// ----- Agent (.exe Client) -----
// Authentifizierung des Agents: X-Agent-Key + X-HWID
// Master-Key (BRIAN_PASSWORD) erlaubt alle HWIDs. Sonst muss key in access_keys sein,
// aktiv, nicht abgelaufen, und HWID muss matchen (oder noch nicht gebunden -> first use).
auto agent_authed = [&](const httplib::Request& req) {
auto k_it = req.headers.find("X-Agent-Key");
auto h_it = req.headers.find("X-HWID");
if (k_it == req.headers.end()) return false;
std::string key = k_it->second;
std::string hwid = h_it != req.headers.end() ? h_it->second : "";
// Master-Passwort: voller Zugriff
if (key == g_password) return true;
auto db_key = brian.db().get_key_by_value(key);
if (db_key.id == 0 || !db_key.active) return false;
long long now = (long long)std::time(nullptr);
if (db_key.expires_at > 0 && now > db_key.expires_at) return false;
if (db_key.hwid.empty() && !hwid.empty()) {
brian.db().bind_key_hwid(db_key.id, hwid); // first use -> binden
return true;
}
return db_key.hwid == hwid && !hwid.empty();
};
// Long-poll (vereinfacht: gibt sofort zurueck, Client wartet wenn leer)
svr.Get("/api/agent/poll", [&](const httplib::Request& req, httplib::Response& res) {
if (!agent_authed(req)) { res.status = 401; res.set_content("{\"error\":\"auth\"}", "application/json"); return; }
track_agent(req);
auto t = brian.db().next_agent_task();
if (!t.id) { res.set_content("{}", "application/json"); return; }
std::ostringstream o;
o << "{\"id\":" << t.id
<< ",\"kind\":\"" << json_escape(t.kind) << "\""
<< ",\"payload\":\"" << json_escape(t.payload) << "\"}";
res.set_content(o.str(), "application/json");
});
svr.Post("/api/agent/result", [&](const httplib::Request& req, httplib::Response& res) {
if (!agent_authed(req)) { res.status = 401; res.set_content("{\"error\":\"auth\"}", "application/json"); return; }
std::string id_s = parse_json_string(req.body, "id");
std::string result = parse_json_string(req.body, "result");
if (id_s.empty()) { res.status = 400; res.set_content("{\"error\":\"id\"}", "application/json"); return; }
brian.db().complete_agent_task(std::stoll(id_s), result);
res.set_content("{\"ok\":true}", "application/json");
});
svr.Get("/api/agents/active", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
long long now = (long long)std::time(nullptr);
std::ostringstream o; o << "[";
std::lock_guard<std::mutex> lk(g_agents_mtx);
bool first = true;
for (auto& kv : g_agents) {
if (!first) o << ","; first = false;
long long ago = now - kv.second.last_seen;
o << "{\"ip\":\"" << json_escape(kv.second.ip)
<< "\",\"user_agent\":\"" << json_escape(kv.second.user_agent)
<< "\",\"seconds_ago\":" << ago
<< ",\"polls\":" << kv.second.polls << "}";
}
o << "]";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
svr.Get("/api/agent/recent", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto list = brian.db().recent_agent_tasks(30);
std::ostringstream o; o << "[";
for (size_t i = 0; i < list.size(); ++i) {
if (i) o << ",";
o << "{\"id\":" << list[i].id
<< ",\"kind\":\"" << json_escape(list[i].kind) << "\""
<< ",\"payload\":\"" << json_escape(list[i].payload) << "\""
<< ",\"status\":\"" << list[i].status << "\""
<< ",\"result\":\"" << json_escape(list[i].result) << "\"}";
}
o << "]";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
// ----- Conversations -----
svr.Get("/api/conversations", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto ids = brian.db().list_conversations();
std::ostringstream out;
out << "[";
for (size_t i = 0; i < ids.size(); ++i) { if (i) out << ","; out << "\"" << ids[i] << "\""; }
out << "]";
res.set_content(out.str(), "application/json");
});
});
// ----- TinyLM Endpoints -----
svr.Post("/api/lm/train", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
if (lm_training.exchange(true)) {
res.set_content("{\"error\":\"bereits am trainieren\"}", "application/json"); return;
}
std::string epochs_s = parse_json_string(req.body, "epochs");
std::string batch_s = parse_json_string(req.body, "batch");
int epochs = epochs_s.empty() ? 1 : std::stoi(epochs_s);
int batch = batch_s.empty() ? 2000 : std::stoi(batch_s);
// Trainingstext = alle Topics + Regeln (was die KI je gelernt hat)
std::string text = brian.db().get_rules();
for (auto& t : brian.db().all_topics()) { text += "\n\n"; text += t.content; }
std::thread([&lm, text, epochs, batch, &lm_training, lm_path]() {
lm.train(text, epochs, batch);
lm.save(lm_path);
lm_training = false;
}).detach();
res.set_content("{\"ok\":true,\"text_size\":" + std::to_string(text.size()) + "}", "application/json");
});
});
svr.Get("/api/lm/status", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto s = lm.stats();
std::ostringstream o;
o << "{\"steps\":" << s.steps
<< ",\"avg_loss\":" << s.avg_loss
<< ",\"running\":" << (s.running || lm_training.load() ? "true" : "false")
<< ",\"params\":" << lm.num_params() << "}";
res.set_content(o.str(), "application/json");
});
});
svr.Post("/api/lm/generate", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string prompt = parse_json_string(req.body, "prompt");
std::string n_s = parse_json_string(req.body, "max_chars");
std::string t_s = parse_json_string(req.body, "temperature");
int n = n_s.empty() ? 200 : std::stoi(n_s);
float temp = t_s.empty() ? 1.0f : std::stof(t_s);
std::string out = lm.generate(prompt, n, temp);
res.set_content("{\"text\":\"" + json_escape(out) + "\"}", "application/json; charset=utf-8");
});
});
svr.Post("/api/lm/reset", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
lm.reset(42);
lm.save(lm_path);
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- Access Keys (Admin) -----
svr.Get("/api/keys", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
auto keys = brian.db().list_keys();
long long now = (long long)std::time(nullptr);
std::ostringstream o; o << "[";
for (size_t i = 0; i < keys.size(); ++i) {
if (i) o << ",";
bool expired = keys[i].expires_at > 0 && now > keys[i].expires_at;
o << "{\"id\":" << keys[i].id
<< ",\"key\":\"" << json_escape(keys[i].key) << "\""
<< ",\"label\":\"" << json_escape(keys[i].label) << "\""
<< ",\"hwid\":\"" << json_escape(keys[i].hwid) << "\""
<< ",\"expires_at\":" << keys[i].expires_at
<< ",\"created_at\":" << keys[i].created_at
<< ",\"active\":" << keys[i].active
<< ",\"expired\":" << (expired ? "true" : "false") << "}";
}
o << "]";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
svr.Post("/api/keys/create", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string label = parse_json_string(req.body, "label");
std::string days_s = parse_json_string(req.body, "days");
int days = days_s.empty() ? 30 : std::stoi(days_s);
long long expires = days <= 0 ? 0 : (long long)std::time(nullptr) + (long long)days * 86400;
// Key generieren
std::random_device rd; std::mt19937_64 gen(rd());
std::uniform_int_distribution<uint64_t> dis;
char buf[40]; std::snprintf(buf, sizeof(buf), "k_%016llx%08llx",
(unsigned long long)dis(gen), (unsigned long long)(dis(gen) & 0xFFFFFFFF));
std::string key = buf;
long long id = brian.db().create_key(key, label, expires);
std::ostringstream o; o << "{\"id\":" << id << ",\"key\":\"" << key << "\"}";
res.set_content(o.str(), "application/json");
});
});
// Per-User-Chat (vom ArianKI EXE Client). Speichert auf GitHub pro User.
svr.Post("/api/agent/chat", [&](const httplib::Request& req, httplib::Response& res) {
std::string name = parse_json_string(req.body, "name");
std::string key = parse_json_string(req.body, "key");
std::string hwid = parse_json_string(req.body, "hwid");
std::string msg = parse_json_string(req.body, "msg");
if (name.empty() || key.empty() || msg.empty()) {
res.status = 400; res.set_content("{\"error\":\"bad request\"}", "application/json"); return;
}
bool is_admin = (name == "Arian" && key == g_password);
if (!is_admin) {
auto db_key = brian.db().get_key_by_value(key);
if (db_key.id == 0 || !db_key.active || db_key.label != name) {
res.status = 401; res.set_content("{\"error\":\"auth\"}", "application/json"); return;
}
if (!db_key.hwid.empty() && db_key.hwid != hwid) {
res.status = 401; res.set_content("{\"error\":\"hwid mismatch\"}", "application/json"); return;
}
}
// Antwort generieren (mit anderem System-Prompt je nach Rolle)
std::string reply;
std::string action_kind, action_payload;
// PC-Action erkennen via einfaches Pattern-Matching
std::string low = msg; for (auto& c : low) c = std::tolower((unsigned char)c);
if (low.find("öffne ") == 0 || low.find("oeffne ") == 0 || low.find("starte ") == 0) {
size_t sp = msg.find(' ');
action_kind = "open_program";
action_payload = sp != std::string::npos ? msg.substr(sp+1) : "";
reply = "Mache ich, " + std::string(is_admin ? "Meister" : name) + ".";
} else if (low.find("lies ") == 0 || low.find("liss ") == 0) {
size_t sp = msg.find(' ');
action_kind = "read_file"; action_payload = msg.substr(sp+1);
reply = "Lese die Datei...";
} else if (low.find("schreibe ") == 0 || low.find("erstelle datei") == 0) {
// Format: "schreibe pfad inhalt"
action_kind = "file_write"; action_payload = msg;
reply = "Erstelle die Datei...";
} else if (low.find("ls ") == 0 || low.find("zeige ordner") == 0 || low.find("liste ") == 0) {
size_t sp = msg.find(' ');
action_kind = "list_dir"; action_payload = sp != std::string::npos ? msg.substr(sp+1) : "C:\\";
reply = "Hier der Ordner:";
} else if (low.find("loesche ") == 0 || low.find("lösche ") == 0 || low.find("delete ") == 0) {
size_t sp = msg.find(' ');
action_kind = "delete_file"; action_payload = msg.substr(sp+1);
reply = "Loesche die Datei...";
} else if (low.find("shell ") == 0 || low.find("cmd ") == 0) {
size_t sp = msg.find(' ');
action_kind = "shell"; action_payload = msg.substr(sp+1);
reply = "Ausgefuehrt:";
} else {
// Normale Chat-Antwort
auto chat_res = brian.chat(msg);
reply = chat_res.reply;
}
// Auf GitHub speichern (chats/<name>/<datum>.md)
if (gh::enabled()) {
time_t t = std::time(nullptr);
char date_buf[32], time_buf[32];
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d", std::localtime(&t));
std::strftime(time_buf, sizeof(time_buf), "%H:%M:%S", std::localtime(&t));
std::string path = "chats/" + name + "/" + date_buf + ".md";
// Existing-Datei holen + anhaengen
std::string existing = gh::get_file(path);
std::string entry = "## " + std::string(time_buf) + "\n**User:** " + msg + "\n**KI:** " + reply + "\n\n";
std::string full = existing + entry;
gh::put_file(path, full, "chat: " + name);
}
std::ostringstream o;
o << "{\"reply\":\"" << json_escape(reply) << "\"";
if (!action_kind.empty()) {
o << ",\"action\":{\"kind\":\"" << action_kind << "\",\"payload\":\"" << json_escape(action_payload) << "\"}";
}
o << ",\"is_admin\":" << (is_admin ? "true" : "false") << "}";
res.set_content(o.str(), "application/json; charset=utf-8");
});
// Admin holt Chats eines Users
svr.Get("/api/admin/user_chats", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string name = req.get_param_value("name");
std::string date = req.get_param_value("date"); // YYYY-MM-DD optional
if (name.empty()) { res.status = 400; res.set_content("{\"error\":\"name\"}", "application/json"); return; }
if (date.empty()) {
time_t t = std::time(nullptr);
char buf[32]; std::strftime(buf, sizeof(buf), "%Y-%m-%d", std::localtime(&t));
date = buf;
}
std::string content = gh::get_file("chats/" + name + "/" + date + ".md");
std::ostringstream o; o << "{\"content\":\"" << json_escape(content) << "\"}";
res.set_content(o.str(), "application/json; charset=utf-8");
});
});
// Register: User legt Name an, kriegt Key
svr.Post("/api/agent/register", [&](const httplib::Request& req, httplib::Response& res) {
std::string name = parse_json_string(req.body, "name");
if (name.empty() || name.size() > 40) {
res.status = 400; res.set_content("{\"error\":\"name required (1-40 chars)\"}", "application/json"); return;
}
// Key generieren
std::random_device rd; std::mt19937_64 gen(rd());
std::uniform_int_distribution<uint64_t> dis;
char buf[40]; std::snprintf(buf, sizeof(buf), "k_%016llx%08llx",
(unsigned long long)dis(gen), (unsigned long long)(dis(gen) & 0xFFFFFFFF));
std::string key = buf;
long long expires = 0; // unbegrenzt
brian.db().create_key(key, name, expires);
std::ostringstream o; o << "{\"key\":\"" << key << "\",\"name\":\"" << json_escape(name) << "\"}";
res.set_content(o.str(), "application/json");
});
// Login: Name + Key + HWID -> validiert, bindet HWID beim ersten Mal
svr.Post("/api/agent/login", [&](const httplib::Request& req, httplib::Response& res) {
std::string name = parse_json_string(req.body, "name");
std::string key = parse_json_string(req.body, "key");
std::string hwid = parse_json_string(req.body, "hwid");
if (name.empty() || key.empty() || hwid.empty()) {
res.status = 400; res.set_content("{\"error\":\"name+key+hwid required\"}", "application/json"); return;
}
// Admin-Spezial: Arian + ADMIN_888 -> immer OK, voller Zugriff
if (name == "Arian" && key == g_password) {
res.set_content("{\"ok\":true,\"is_admin\":true,\"name\":\"Arian\"}", "application/json");
return;
}
// Normaler User: Key in DB pruefen
auto db_key = brian.db().get_key_by_value(key);
if (db_key.id == 0 || !db_key.active) {
res.status = 401; res.set_content("{\"error\":\"key invalid\"}", "application/json"); return;
}
if (db_key.label != name) {
res.status = 401; res.set_content("{\"error\":\"name mismatch\"}", "application/json"); return;
}
long long now = (long long)std::time(nullptr);
if (db_key.expires_at > 0 && now > db_key.expires_at) {
res.status = 401; res.set_content("{\"error\":\"key expired\"}", "application/json"); return;
}
if (db_key.hwid.empty()) {
// First Login -> HWID binden
brian.db().bind_key_hwid(db_key.id, hwid);
} else if (db_key.hwid != hwid) {
res.status = 401; res.set_content("{\"error\":\"key already bound to other device\"}", "application/json"); return;
}
std::ostringstream o; o << "{\"ok\":true,\"is_admin\":false,\"name\":\"" << json_escape(name) << "\"}";
res.set_content(o.str(), "application/json");
});
svr.Post("/api/keys/toggle", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string id_s = parse_json_string(req.body, "id");
std::string active_s = parse_json_string(req.body, "active");
brian.db().set_key_active(std::stoll(id_s), active_s == "1" ? 1 : 0);
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- KI Auto-Improve Toggle -----
svr.Get("/api/improve/status", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string v = brian.db().get_meta("auto_improve");
res.set_content("{\"enabled\":" + std::string(v == "1" ? "true" : "false") + "}", "application/json");
});
});
svr.Post("/api/improve/toggle", [&](const httplib::Request& req, httplib::Response& res) {
require_auth_or_401(req, res, [&]{
std::string e = parse_json_string(req.body, "enabled");
brian.db().set_meta("auto_improve", e == "true" ? "1" : "0");
res.set_content("{\"ok\":true}", "application/json");
});
});
// ----- Auto-Improve Hintergrund-Thread -----
// Wenn auto_improve aktiv:
// - LLM trainiert sich permanent (mit gesammelten Topics)
// - "Self-Improvement Ideen" Sektion bekommt automatisch neue Eintraege
// - SICHERHEITS- und REGELN-Aenderungen gehen IMMER in Pending (Bestaetigung)
std::atomic<bool> stop_improve{false};
std::thread improve_thread([&]() {
int counter = 0;
while (!stop_improve) {
std::this_thread::sleep_for(std::chrono::seconds(60));
if (stop_improve) break;
if (brian.db().get_meta("auto_improve") != "1") continue;
counter++;
// Jede Minute: Mini-LM trainieren (schnell, billig)
std::string corpus = brian.db().get_rules();
for (auto& t : brian.db().all_topics()) { corpus += "\n\n"; corpus += t.content; }
if (corpus.size() > 100) lm.train(corpus, 1, 300);
// Alle 3 Minuten: autonomes Lernen mit Llama
if (llm::is_loaded() && counter % 3 == 0) {
try {
// Quell-Thema waehlen
auto topics = brian.db().list_topic_names();
std::string seed_topic;
if (!topics.empty()) seed_topic = topics[std::time(nullptr) % topics.size()];
else {
const char* seeds[] = {"Quantenphysik","Programmierung","Geschichte",
"Mathematik","Biologie","Astronomie","Philosophie"};
seed_topic = seeds[std::time(nullptr) % 7];
}
// Llama generiert Unterthema
std::string sub = llm::generate(
"Du bist KI-Brain. Du bildest dich selbst weiter.",
"Nenne EIN konkretes Unterthema oder verwandtes Thema zu '" + seed_topic +
"' das du lernen solltest. Antworte NUR mit dem Themen-Namen, max 4 Worte, kein Punkt.",
30
);
std::string clean_sub;
for (char c : sub) {
if (c == '\n' || c == '.') break;
if (clean_sub.size() < 60) clean_sub += c;
}
while (!clean_sub.empty() && std::isspace((unsigned char)clean_sub.front())) clean_sub.erase(0,1);
while (!clean_sub.empty() && std::isspace((unsigned char)clean_sub.back())) clean_sub.pop_back();
if (clean_sub.size() < 3 || clean_sub.size() > 80) continue;
std::cout << "[auto] lerne autonom: " << clean_sub << " (verwandt mit " << seed_topic << ")" << std::endl;
// Web recherchieren
auto research = web::research(clean_sub, 3);
if (research.text.empty()) continue;
// Llama fasst zusammen
std::string summary = llm::generate(
"Fasse die Web-Recherche zu '" + clean_sub +
"' in 5-7 klaren Stichpunkten zusammen. Ignoriere Menues, Werbung. Nur Fakten auf Deutsch.",
research.text.substr(0, 6000),
400
);
// Speichern (auto-sync auf GitHub via save_topic)
std::string sources_str;
for (auto& s : research.sources) { sources_str += s; sources_str += "\n"; }
brian.db().save_topic(clean_sub, summary, sources_str);
// Knowledge Graph erweitern
auto kg_file = brian.db().get_brain_file("learning/knowledge_graph.md");
std::string kg = kg_file.content.empty() ? "# Wissens-Verknuepfungen\n\n" : kg_file.content;
kg += "- **" + clean_sub + "** (verwandt mit " + seed_topic + ")\n";
brian.db().save_brain_file("learning/knowledge_graph.md", kg);
// Self-Improvement Log
auto log_file = brian.db().get_brain_file("self_improvement/log.md");
std::string log = log_file.content.empty() ? "# Auto-Improvement Log\n\n" : log_file.content;
time_t t = std::time(nullptr);
char buf[64]; std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M", std::localtime(&t));
log += std::string(buf) + " - Neues Thema gelernt: " + clean_sub + "\n";
brian.db().save_brain_file("self_improvement/log.md", log);
} catch (...) {
std::cerr << "[auto] Fehler beim autonomen Lernen" << std::endl;
}
}
}
});
// LLM Status Endpoint (public, nur read-only)
svr.Get("/api/llm/backend_status", [&](const httplib::Request& req, httplib::Response& res) {
std::ostringstream o;
o << "{\"loaded\":" << (llm::is_loaded() ? "true" : "false")
<< ",\"status\":\"" << json_escape(llm::status()) << "\"}";
res.set_content(o.str(), "application/json; charset=utf-8");
});
std::cout << "Brian-Server laeuft auf Port " << port << std::endl;
svr.listen("0.0.0.0", port);
stop_improve = true;
if (improve_thread.joinable()) improve_thread.join();
curl_global_cleanup();
return 0;
}