File size: 42,485 Bytes
85b4c6d 3379ce6 af9ac87 027d3a0 4e830f4 447f4d6 85b4c6d 1d3606a 85b4c6d 1d3606a 85b4c6d 027d3a0 85b4c6d c01d940 af9ac87 c01d940 85b4c6d 959a290 85b4c6d 959a290 85b4c6d 1d3606a 85b4c6d 1d3606a 85b4c6d 959a290 aa7d3d8 959a290 d0853e9 6b51a04 d0853e9 1abd756 d0853e9 1abd756 6b51a04 1abd756 6b51a04 1abd756 6b51a04 d0853e9 2700cbe 027d3a0 2700cbe 027d3a0 85b4c6d d0853e9 85b4c6d | 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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 | // 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;
}
|