-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
5206 lines (4979 loc) · 211 KB
/
Copy pathmain.cpp
File metadata and controls
5206 lines (4979 loc) · 211 KB
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iterator>
#include <thread>
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstdio>
#include <ctime>
#include <functional>
#include <atomic>
#include <mutex>
#include <set>
#include "rag_client.h"
#include "coli_sse.h"
#include "local_edit.h"
#include "local_tools.h"
#include "thinking_cmd.h"
#include "tool_round.h"
#include "browser_evidence.h"
#include "unused49.h"
#include "kernel_request.h"
#include "memory.h"
#include "telemetry.h"
// 3 minute ceiling on a single Colibri invocation. Defined once so the wait
// timeout and the message we return on expiry can never drift apart.
static const DWORD COLIBRI_TIMEOUT_MS = 180000;
// One GPU slot. 160 tokens is one paging-safe decode. The kernel auto-continues
// up to 4 chunks so a normal answer finishes without the user babysitting.
static const int kColiChunkTokens = 160;
static const int kColiMaxChunks = 4;
// Gemma/llama on this 4080 Super decodes at ~140 tok/s with VRAM to spare.
// 160+tank-CONTINUE was for GLM paging; it makes 12B restate the system prompt.
static const int kLlamaChunkTokens = 1024;
static const int kLlamaMaxChunks = 2;
// 160 tokens at ~3s plus a 78-layer prefill misses 720s on this 16 GB box.
static const int kColiChunkTimeoutMs = 1200000;
#include "kernel.h"
using json = nlohmann::json;
GodBrainKernel kernel_hub; // Global kernel instance
// Bearer token required for any request that carries a "command_type" (i.e. a
// privileged kernel dispatch). Loaded once from the environment at startup so
// the arbitrary-command capability stays available to trusted callers while
// being gated behind an explicit secret instead of open to any local process.
static std::string g_api_token;
// Directory that holds the static Galaxy UI. Resolved once at startup from
// GODBRAIN_FRONTEND_DIR or a portable default (see resolve_frontend_dir()).
static std::string g_frontend_dir;
// Tick when this kernel process started the in-flight serve generate.
// /status reads it from another httplib thread so busy stops looking dead.
static std::atomic<DWORD> g_coli_job_started_ms{0};
struct LastOracleTurn {
std::string question;
std::string answer;
std::string stable_id;
std::string status = "candidate";
DWORD elapsed_ms = 0;
bool ok = false;
bool stored = false;
bool complete = true;
};
constexpr size_t kMaxOracleTurns = 8;
static std::mutex g_last_oracle_mu;
static std::vector<LastOracleTurn> g_oracle_turns;
static json last_oracle_json();
static json last_oracle_turns_json();
static std::string format_brief_text();
static void handle_brief(const httplib::Request&, httplib::Response&);
static void handle_vram(const httplib::Request&, httplib::Response&);
static void handle_host_snap(const httplib::Request&, httplib::Response&);
static void handle_doors(const httplib::Request&, httplib::Response&);
static void handle_desk(const httplib::Request&, httplib::Response&);
static void handle_pending(const httplib::Request&, httplib::Response&);
static void handle_heal(const httplib::Request&, httplib::Response&);
static void handle_sre(const httplib::Request&, httplib::Response&);
static void handle_last_edit(const httplib::Request&, httplib::Response&);
static void handle_chain(const httplib::Request&, httplib::Response&);
static void handle_events(const httplib::Request&, httplib::Response&);
static void handle_cancel_chain(const httplib::Request&, httplib::Response&);
static json load_chain();
static json pending_body();
static std::string clip_pending_line(std::string text, size_t max);
static int file_age_minutes(const std::string& path);
static json collect_pending_items(const json& turns, const json& host_rec);
static std::string resolve_judgment_id(const std::string& raw, std::string& error);
static bool ids_equal_ignore_case(const std::string& a, const std::string& b);
static bool id_has_prefix(const std::string& id, const std::string& prefix);
static json heal_status_body();
static bool is_displayable_oracle_turn(const LastOracleTurn& turn);
static LastOracleTurn display_oracle_turn(LastOracleTurn turn);
static std::string sanitize_oracle_body(std::string answer);
static void load_oracle_turns();
static void remember_oracle_turn(
const std::string& question,
const std::string& answer,
DWORD elapsed_ms);
static void note_oracle_partial(
const std::string& question,
const std::string& partial,
DWORD elapsed_ms);
static void retry_unstored_oracle_turns();
static json load_mouth();
static bool llama_thinking_enabled();
static bool write_thinking_enabled(bool on);
static json load_last_edit();
static json load_heal_last();
static json inbox_desk();
static json load_last_desk_test();
static json gpu_desk();
static bool maybe_restart_mouth(bool even_if_up = false);
static bool cs2_should_sleep_mouth();
static bool maybe_bind_tailscale_door();
static bool tailscale_door_bound_to(const std::string& ip);
static json cs2_desk();
static std::string read_env(const char* name) {
char* value = nullptr;
size_t length = 0;
if (_dupenv_s(&value, &length, name) != 0 || value == nullptr) return "";
std::string result(value);
std::free(value);
return result;
}
static std::string get_exe_dir() {
char path[MAX_PATH];
DWORD len = GetModuleFileNameA(NULL, path, MAX_PATH);
if (len == 0 || len == MAX_PATH) return "";
std::string full(path, len);
size_t pos = full.find_last_of("\\/");
return pos == std::string::npos ? "" : full.substr(0, pos);
}
static bool path_exists(const std::string& p) {
if (p.empty()) return false;
DWORD attrs = GetFileAttributesA(p.c_str());
return attrs != INVALID_FILE_ATTRIBUTES;
}
static int file_age_minutes(const std::string& path) {
WIN32_FILE_ATTRIBUTE_DATA attrs{};
if (!GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &attrs)) {
return -1;
}
FILETIME now_ft{};
GetSystemTimeAsFileTime(&now_ft);
ULARGE_INTEGER written{};
ULARGE_INTEGER now{};
written.LowPart = attrs.ftLastWriteTime.dwLowDateTime;
written.HighPart = attrs.ftLastWriteTime.dwHighDateTime;
now.LowPart = now_ft.dwLowDateTime;
now.HighPart = now_ft.dwHighDateTime;
if (now.QuadPart < written.QuadPart) return 0;
return static_cast<int>(
(now.QuadPart - written.QuadPart) / 10000000ull / 60ull);
}
static json oracle_turn_to_json(const LastOracleTurn& turn) {
return {
{"question", turn.question},
{"answer", turn.answer},
{"elapsed_ms", turn.elapsed_ms},
{"ok", turn.ok},
{"stored", turn.stored},
{"complete", turn.complete},
{"stable_id", turn.stable_id},
{"status", turn.status},
};
}
static json last_oracle_json() {
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
for (auto it = g_oracle_turns.rbegin(); it != g_oracle_turns.rend(); ++it) {
if (is_displayable_oracle_turn(*it)) {
return oracle_turn_to_json(display_oracle_turn(*it));
}
}
return json::object();
}
static json last_oracle_turns_json() {
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
json turns = json::array();
for (const auto& turn : g_oracle_turns) {
if (!is_displayable_oracle_turn(turn)) continue;
turns.push_back(oracle_turn_to_json(display_oracle_turn(turn)));
}
return turns;
}
static std::string last_oracle_path() {
const std::string dir = get_exe_dir();
if (dir.empty()) return "last_oracle.json";
return dir + "\\last_oracle.json";
}
// Replace the file in place. Never unlink the live file first — a failed
// write must leave the previous turns readable (the Gemini-class footgun).
static void persist_oracle_turns_locked() {
json body = {{"version", 1}, {"turns", json::array()}};
for (const auto& turn : g_oracle_turns) {
body["turns"].push_back(oracle_turn_to_json(turn));
}
const std::string path = last_oracle_path();
const std::string tmp = path + ".tmp";
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out) {
std::cerr << "[MEMORY] could not write " << tmp << std::endl;
return;
}
out << body.dump(2);
out.flush();
if (!out) {
std::cerr << "[MEMORY] incomplete write " << tmp << std::endl;
return;
}
}
if (MoveFileExA(
tmp.c_str(),
path.c_str(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) == 0) {
std::cerr << "[MEMORY] could not replace " << path
<< " (win32=" << GetLastError() << "); previous file kept"
<< std::endl;
}
}
static void load_oracle_turns() {
const std::string path = last_oracle_path();
std::ifstream in(path, std::ios::binary);
if (!in) return;
try {
const json body = json::parse(in);
const json turns = body.value("turns", json::array());
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
g_oracle_turns.clear();
for (const auto& item : turns) {
if (!item.is_object()) continue;
LastOracleTurn turn;
turn.question = item.value("question", "");
turn.answer = item.value("answer", "");
turn.elapsed_ms = item.value("elapsed_ms", 0);
turn.ok = item.value("ok", false);
turn.stored = item.value("stored", false);
turn.complete = item.value("complete", true);
turn.stable_id = item.value("stable_id", "");
turn.status = item.value("status", "candidate");
if (turn.question.empty() && turn.answer.empty()) continue;
g_oracle_turns.push_back(std::move(turn));
}
if (g_oracle_turns.size() > kMaxOracleTurns) {
g_oracle_turns.erase(
g_oracle_turns.begin(),
g_oracle_turns.begin() + static_cast<std::ptrdiff_t>(
g_oracle_turns.size() - kMaxOracleTurns));
}
bool cleaned = false;
for (auto& turn : g_oracle_turns) {
if (!turn.ok || turn.answer.empty()) continue;
const std::string cleaned_a = sanitize_oracle_body(turn.answer);
if (cleaned_a != turn.answer && !cleaned_a.empty()) {
turn.answer = cleaned_a;
cleaned = true;
}
}
if (cleaned) persist_oracle_turns_locked();
std::cout << "[MEMORY] Loaded " << g_oracle_turns.size()
<< " oracle turns from " << path << std::endl;
} catch (const json::exception& error) {
std::cerr << "[MEMORY] last_oracle.json ignored: " << error.what()
<< std::endl;
}
}
static std::string oracle_turn_body(
const std::string& question, const std::string& answer) {
std::string body = "Oracle turn (candidate, not verified)\nQ: " + question +
"\nA: " + answer;
if (body.size() > 2000) body.resize(2000);
return body;
}
static void mark_oracle_stored(
const std::string& question,
const std::string& answer,
const std::string& stable_id) {
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
for (auto it = g_oracle_turns.rbegin(); it != g_oracle_turns.rend(); ++it) {
if (it->question == question && it->answer == answer) {
it->stored = true;
if (!stable_id.empty()) it->stable_id = stable_id;
break;
}
}
persist_oracle_turns_locked();
}
static bool mark_oracle_status(const std::string& id, const std::string& to) {
if (id.empty() || (to != "verified" && to != "rejected")) return false;
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
bool hit = false;
for (auto& turn : g_oracle_turns) {
if (turn.stable_id.empty()) continue;
if (ids_equal_ignore_case(turn.stable_id, id) ||
id_has_prefix(turn.stable_id, id) ||
id_has_prefix(id, turn.stable_id)) {
turn.status = to;
hit = true;
}
}
if (hit) persist_oracle_turns_locked();
return hit;
}
static void store_oracle_turn_async(
const std::string& question, const std::string& answer) {
std::thread([question, answer]() {
try {
const json receipt = memory::save_thought(
{{"content", oracle_turn_body(question, answer)},
{"sector", "oracle"}});
mark_oracle_stored(question, answer, receipt.value("stable_id", ""));
} catch (const std::exception& error) {
std::cerr << "[MEMORY] oracle turn not stored: " << error.what()
<< std::endl;
}
}).detach();
}
static std::string ensure_last_oracle_id() {
LastOracleTurn turn;
{
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
for (auto it = g_oracle_turns.rbegin(); it != g_oracle_turns.rend();
++it) {
if (!is_displayable_oracle_turn(*it)) continue;
turn = *it;
break;
}
if (turn.question.empty() && turn.answer.empty()) return "";
if (!turn.stable_id.empty()) return turn.stable_id;
}
if (!turn.ok || turn.answer.empty()) return "";
const json receipt = memory::save_thought(
{{"content", oracle_turn_body(turn.question, turn.answer)},
{"sector", "oracle"}});
const std::string stable_id = receipt.value("stable_id", "");
mark_oracle_stored(turn.question, turn.answer, stable_id);
return stable_id;
}
static void note_oracle_partial(
const std::string& question,
const std::string& partial,
DWORD elapsed_ms) {
if (question.empty() || partial.empty()) return;
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
if (!g_oracle_turns.empty() && !g_oracle_turns.back().complete &&
g_oracle_turns.back().question == question) {
g_oracle_turns.back().answer = partial;
g_oracle_turns.back().elapsed_ms = elapsed_ms;
} else {
LastOracleTurn turn;
turn.question = question;
turn.answer = partial;
turn.elapsed_ms = elapsed_ms;
turn.ok = false;
turn.stored = false;
turn.complete = false;
g_oracle_turns.push_back(std::move(turn));
if (g_oracle_turns.size() > kMaxOracleTurns) {
g_oracle_turns.erase(g_oracle_turns.begin());
}
}
persist_oracle_turns_locked();
}
static void retry_unstored_oracle_turns() {
std::vector<std::pair<std::string, std::string>> pending;
{
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
for (const auto& turn : g_oracle_turns) {
if (turn.ok && turn.complete && !turn.stored &&
!turn.question.empty() && !turn.answer.empty()) {
pending.emplace_back(turn.question, turn.answer);
}
}
}
for (const auto& item : pending) {
std::cout << "[MEMORY] Retrying unstored oracle turn" << std::endl;
store_oracle_turn_async(item.first, item.second);
}
}
static void remember_oracle_turn(
const std::string& question,
const std::string& answer,
DWORD elapsed_ms) {
LastOracleTurn turn;
turn.question = question;
turn.answer = answer.compare(0, 6, "Error:") == 0
? answer
: sanitize_oracle_body(answer);
turn.elapsed_ms = elapsed_ms;
turn.ok = answer.compare(0, 6, "Error:") != 0;
turn.stored = false;
turn.complete = turn.ok && answer.find("[cut") == std::string::npos;
{
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
if (!g_oracle_turns.empty() && !g_oracle_turns.back().complete &&
g_oracle_turns.back().question == question) {
g_oracle_turns.back() = turn;
} else {
g_oracle_turns.push_back(turn);
if (g_oracle_turns.size() > kMaxOracleTurns) {
g_oracle_turns.erase(g_oracle_turns.begin());
}
}
persist_oracle_turns_locked();
}
if (!turn.ok) return;
store_oracle_turn_async(question, answer);
}
static std::string trim_copy(std::string value) {
const auto not_space = [](unsigned char character) {
return std::isspace(character) == 0;
};
value.erase(value.begin(), std::find_if(value.begin(), value.end(), not_space));
value.erase(std::find_if(value.rbegin(), value.rend(), not_space).base(), value.end());
return value;
}
static bool is_continue_command(const std::string& text) {
std::string t = trim_copy(text);
if (t.empty()) return false;
if (t[0] == '/') t.erase(0, 1);
for (char& ch : t) {
ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
return t == "continue" || t == "cont";
}
static bool is_cancel_command(const std::string& text) {
std::string t = trim_copy(text);
if (t.empty()) return false;
if (t[0] == '/') t.erase(0, 1);
for (char& ch : t) {
ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
return t == "cancel";
}
static bool is_refuse_answer(const std::string& answer) {
return answer.find("I cannot fulfill") != std::string::npos ||
answer.find("I cannot help with that") != std::string::npos ||
answer.find("I cannot help with this") != std::string::npos;
}
static std::string strip_cut_marker(std::string answer) {
const std::string marker = "[cut";
const size_t pos = answer.find(marker);
if (pos != std::string::npos) {
answer.resize(pos);
}
return trim_copy(std::move(answer));
}
static std::string ascii_lower_copy(std::string value) {
for (char& ch : value) {
ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
return value;
}
static std::string normalize_heading_key(std::string line) {
line = trim_copy(std::move(line));
while (!line.empty() && (line[0] == '#' || line[0] == '*' ||
line[0] == ' ')) {
line.erase(0, 1);
}
return ascii_lower_copy(trim_copy(std::move(line)));
}
// GLM got stuck repeating "### Verified Facts: Combat Record & Capabilities".
// Cut at the second copy of any heading, and split a ### glued onto a sentence.
static std::string trim_repetition_loop(std::string text) {
const std::string glued = "### ";
size_t glue = text.find(glued, 1);
while (glue != std::string::npos) {
if (text[glue - 1] != '\n') {
text.insert(glue, "\n");
glue += 1;
}
glue = text.find(glued, glue + 4);
}
std::istringstream in(text);
std::string line;
std::string kept;
std::set<std::string> seen_headings;
while (std::getline(in, line)) {
std::string t = trim_copy(line);
const bool heading =
t.size() >= 3 && t[0] == '#' && t[1] == '#';
if (heading) {
const std::string key = normalize_heading_key(t);
if (!key.empty() && seen_headings.count(key)) {
return trim_copy(kept);
}
if (!key.empty()) seen_headings.insert(key);
}
kept += line;
kept += '\n';
}
// Do not leave a bare ### heading as the continue anchor.
for (;;) {
kept = trim_copy(kept);
if (kept.empty()) break;
const size_t nl = kept.find_last_of('\n');
const std::string last_line =
nl == std::string::npos ? kept : trim_copy(kept.substr(nl + 1));
if (last_line.size() >= 3 && last_line[0] == '#' && last_line[1] == '#') {
kept = nl == std::string::npos ? std::string() : kept.substr(0, nl);
continue;
}
break;
}
return trim_copy(std::move(kept));
}
static bool is_heading_loop(const std::string& text) {
int verified = 0;
int headings = 0;
const std::string lower = ascii_lower_copy(text);
for (size_t pos = 0;
(pos = lower.find("verified facts", pos)) != std::string::npos;
pos += 8) {
++verified;
}
for (size_t pos = 0;
(pos = text.find("### ", pos)) != std::string::npos;
pos += 4) {
++headings;
}
return verified >= 3 || headings >= 5;
}
// T-90AM/T-90AM/T-90AM... — same 6–32 char block three times in a row.
static bool find_ngram_loop(
const std::string& text,
size_t* at,
size_t* unit,
size_t* copies) {
constexpr size_t kMin = 6;
constexpr size_t kMax = 32;
if (text.size() < kMin * 3) return false;
for (size_t n = kMin; n <= kMax; ++n) {
if (text.size() < n * 3) continue;
for (size_t i = 0; i + n * 3 <= text.size(); ++i) {
if (text.compare(i, n, text, i + n, n) != 0) continue;
if (text.compare(i, n, text, i + 2 * n, n) != 0) continue;
size_t k = 3;
while (i + (k + 1) * n <= text.size() &&
text.compare(i, n, text, i + k * n, n) == 0) {
++k;
}
if (at) *at = i;
if (unit) *unit = n;
if (copies) *copies = k;
return true;
}
}
return false;
}
static bool is_ngram_loop(const std::string& text) {
const std::string t =
text.size() > 480 ? text.substr(text.size() - 480) : text;
return find_ngram_loop(t, nullptr, nullptr, nullptr);
}
static bool is_resume_jail(const std::string& text) {
return text.find("END>>") != std::string::npos ||
text.find("Resume immediately after these exact characters") !=
std::string::npos ||
text.find("Do not mention the prompt, corrections") !=
std::string::npos;
}
static bool is_generation_loop(const std::string& text) {
return is_heading_loop(text) || is_ngram_loop(text) || is_resume_jail(text);
}
static std::string trim_ngram_loop(std::string text) {
size_t at = 0;
size_t unit = 0;
size_t copies = 0;
if (!find_ngram_loop(text, &at, &unit, &copies)) return text;
return trim_copy(text.substr(0, at + unit));
}
static std::string sanitize_oracle_body(std::string answer) {
answer = unused49::strip_tail(std::move(answer));
answer = strip_cut_marker(std::move(answer));
for (;;) {
const size_t begin = answer.find("*(");
if (begin == std::string::npos) break;
const size_t end = answer.find(")*", begin);
if (end == std::string::npos) break;
answer.erase(begin, end + 2 - begin);
}
const char* kills[] = {
"Wait, I made a mistake",
"I made a mistake in the prompt",
"**Correction",
"Correction:",
"I apologize for the confusion",
"I need to finish the previous sentence",
"This conversation is finished",
};
for (const char* kill : kills) {
const size_t pos = answer.find(kill);
if (pos != std::string::npos) answer.resize(pos);
}
return trim_ngram_loop(trim_repetition_loop(trim_copy(std::move(answer))));
}
static bool is_unused49_junk(const std::string& text) {
return unused49::is_junk(text);
}
static bool is_displayable_oracle_turn(const LastOracleTurn& turn) {
if (!turn.ok || turn.answer.empty()) return false;
if (is_continue_command(turn.question)) return false;
if (turn.answer.compare(0, 6, "Error:") == 0) return false;
if (is_unused49_junk(turn.answer)) return false;
if (is_refuse_answer(turn.answer)) return false;
if (is_resume_jail(turn.answer)) return false;
if (turn.answer.find("TABLESPACE") != std::string::npos) return false;
if (turn.answer.find("Oracle Partition") != std::string::npos) return false;
if (turn.answer.find("Understanding Oracle") != std::string::npos) {
return false;
}
return sanitize_oracle_body(turn.answer).size() >= 40;
}
static LastOracleTurn display_oracle_turn(LastOracleTurn turn) {
turn.answer = sanitize_oracle_body(turn.answer);
return turn;
}
static std::string last_anchor(const std::string& text, size_t n = 90) {
const std::string t = trim_copy(text);
if (t.size() <= n) return t;
return t.substr(t.size() - n);
}
static std::string continue_history_tail(const std::string& text, size_t n = 450) {
const std::string t = trim_copy(text);
if (t.size() <= n) return t;
std::string tail = t.substr(t.size() - n);
const size_t nl = tail.find('\n');
if (nl != std::string::npos && nl + 1 < tail.size()) {
tail = tail.substr(nl + 1);
}
return tail;
}
static bool looks_like_restart(const std::string& text) {
const std::string t = ascii_lower_copy(trim_copy(text));
if (t.compare(0, 14, "to determine if") == 0) return true;
if (t.compare(0, 16, "this evaluation") == 0) return true;
if (t.compare(0, 12, "analyze why") == 0) return true;
if (t.compare(0, 15, "whether the m1") == 0) return true;
if (t.find("### firepower") != std::string::npos &&
t.find("analyze why") != std::string::npos) {
return true;
}
return false;
}
static std::string last_coherent_essay(std::string text) {
text = sanitize_oracle_body(std::move(text));
const char* marks[] = {
"To determine if",
"This evaluation assesses",
"### Firepower",
};
size_t last = std::string::npos;
for (const char* mark : marks) {
const size_t pos = text.rfind(mark);
if (pos != std::string::npos &&
(last == std::string::npos || pos > last)) {
last = pos;
}
}
if (last != std::string::npos && last > 80) {
return trim_copy(text.substr(last));
}
return text;
}
static std::string make_continue_prompt(const std::string& prior) {
return std::string(
"Resume immediately after these exact characters. "
"Write only new words. Do not restart the essay. "
"Do not repeat the question. Do not repeat any earlier "
"sentence, heading, or tank designation. "
"Do not start a new ### heading. "
"Next output must be a bullet or a finished sentence. "
"Do not mention the prompt, corrections, mistakes, or "
"Oracle Database. No parenthetical stage directions.\n\n"
"END>>") +
last_anchor(prior);
}
static bool wants_apply_continue(
const std::string& system, const std::string& user) {
if (system.find("apply blocks") != std::string::npos) return true;
if (system.find("local file editor") != std::string::npos) return true;
return local_edit::looks_like_edit_request(user);
}
static bool looks_unfinished(const std::string& text) {
const std::string t = trim_copy(text);
if (t.empty()) return true;
const char end = t.back();
return end != '.' && end != '!' && end != '?' && end != '"' && end != ')';
}
static std::string make_edit_continue_prompt(const std::string& prior) {
return std::string(
"Continue the repo patch. Emit only apply blocks, no essay:\n"
"*** APPLY\n"
"path: relative/from/repo\n"
"<<<<\n"
"exact old text\n"
"====\n"
"exact new text\n"
">>>>\n"
"*** END\n\n"
"Last tokens:\n") +
last_anchor(prior);
}
static std::string strip_replayed_prefix(
const std::string& prior, std::string next) {
next = trim_copy(std::move(next));
if (prior.empty() || next.empty()) return next;
const size_t probe = prior.size() < 48 ? prior.size() : 48;
if (next.compare(0, probe, prior, 0, probe) == 0) {
size_t i = 0;
const size_t n =
prior.size() < next.size() ? prior.size() : next.size();
while (i < n && prior[i] == next[i]) ++i;
return trim_copy(next.substr(i));
}
const size_t max_ol =
prior.size() < next.size() ? prior.size() : next.size();
for (size_t len = max_ol; len >= 24; --len) {
if (next.compare(0, len, prior, prior.size() - len, len) == 0) {
return trim_copy(next.substr(len));
}
}
return next;
}
// Last turn that is a real Q/A. Skip CONTINUE, serve-down errors, and refuses
// so a follow-up does not inherit Oracle-DB derails or "I cannot fulfill".
static bool find_last_real_oracle_turn(LastOracleTurn& out) {
std::lock_guard<std::mutex> lock(g_last_oracle_mu);
for (auto it = g_oracle_turns.rbegin(); it != g_oracle_turns.rend(); ++it) {
if (!it->ok || it->question.empty() || it->answer.empty()) continue;
if (is_continue_command(it->question)) continue;
if (it->answer.compare(0, 6, "Error:") == 0) continue;
if (is_unused49_junk(it->answer)) continue;
if (is_refuse_answer(it->answer)) continue;
if (is_resume_jail(it->answer)) continue;
if (is_generation_loop(it->answer) &&
sanitize_oracle_body(it->answer).size() < 80) {
continue;
}
out = *it;
if (is_generation_loop(it->answer)) {
out.answer = sanitize_oracle_body(it->answer);
}
return true;
}
return false;
}
// Resolves the Colibri C-Engine executable path. Order of preference:
// 1. GODBRAIN_COLIBRI_PATH environment override (explicit, always wins).
// 2. A handful of repo-relative candidates, tried both from the running
// executable's own directory and from the current working directory, so
// this works whether cpp_kernel.exe lives at godbrain_core/cpp_kernel/
// or a build subdirectory beneath it, without baking in any one user's
// absolute path.
static std::string resolve_colibri_path() {
const std::string env = read_env("GODBRAIN_COLIBRI_PATH");
if (!env.empty()) return env;
static const char* candidates[] = {
"\\..\\..\\..\\colibri\\c\\colibri.exe",
"\\..\\..\\colibri\\c\\colibri.exe",
"\\..\\..\\LLM\\colibri_LLM\\c\\colibri.exe",
"\\..\\..\\..\\LLM\\colibri_LLM\\c\\colibri.exe",
"\\LLM\\colibri_LLM\\c\\colibri.exe",
};
std::string exe_dir = get_exe_dir();
for (const char* rel : candidates) {
if (!exe_dir.empty()) {
std::string cand = exe_dir + rel;
if (path_exists(cand)) return cand;
}
}
// Fall back to a cwd-relative guess (matches the "../frontend" convention
// used elsewhere in this file when launched from godbrain_core/cpp_kernel).
std::string fallback = "..\\..\\LLM\\colibri_LLM\\c\\colibri.exe";
if (path_exists(fallback)) return fallback;
std::cerr << "[SYS] WARNING: could not locate colibri.exe via GODBRAIN_COLIBRI_PATH or repo-relative defaults; "
"using best-effort path '" << fallback << "'." << std::endl;
return fallback;
}
// Resolves the frontend static directory the same way (env override first,
// then a repo-relative default). Returns a path suitable for both
// std::ifstream and httplib::Server::set_mount_point.
static std::string resolve_frontend_dir() {
const std::string env = read_env("GODBRAIN_FRONTEND_DIR");
if (!env.empty()) return env;
return "../frontend";
}
// Origins allowed to talk to this loopback-only API: localhost/127.0.0.1 on
// any port (dev servers, the packaged UI, etc.) plus the Tauri webview
// origins. No wildcard is ever accepted.
static bool is_trusted_origin(const std::string& origin) {
if (origin.empty()) return false;
if (origin == "tauri://localhost") return true;
size_t scheme_end = origin.find("://");
if (scheme_end == std::string::npos) return false;
std::string rest = origin.substr(scheme_end + 3);
size_t slash = rest.find('/');
if (slash != std::string::npos) rest = rest.substr(0, slash);
size_t colon = rest.find(':');
std::string host = (colon != std::string::npos) ? rest.substr(0, colon) : rest;
return host == "localhost" || host == "127.0.0.1" || host == "tauri.localhost";
}
// Constant-time-ish comparison so an invalid bearer token doesn't leak length
// information via early-exit timing any more than necessary.
static bool token_matches(const std::string& provided) {
if (g_api_token.empty() || provided.empty()) return false;
if (provided.size() != g_api_token.size()) return false;
unsigned char diff = 0;
for (size_t i = 0; i < provided.size(); i++) {
diff |= (unsigned char)(provided[i] ^ g_api_token[i]);
}
return diff == 0;
}
static std::string extract_bearer_token(const httplib::Request& req) {
auto it = req.headers.find("Authorization");
if (it == req.headers.end()) return "";
const std::string& val = it->second;
const std::string prefix = "Bearer ";
if (val.size() > prefix.size() && val.compare(0, prefix.size(), prefix) == 0) {
return val.substr(prefix.size());
}
return "";
}
static bool write_authorized(const httplib::Request& req, httplib::Response& res) {
if (g_api_token.empty()) return true;
if (token_matches(extract_bearer_token(req))) return true;
res.status = extract_bearer_token(req).empty() ? 401 : 403;
res.set_content(
json({{"error", "bearer token required for this write"}}).dump(),
"application/json");
return false;
}
bool colibri_serve_up();
static json coli_serve_status();
static bool is_host_inventory_text(const std::string& text) {
if (text.find("Windows host inventory") == std::string::npos) return false;
if (text.find("os_pin=") == std::string::npos) return false;
if (text.find("Playbook") != std::string::npos) return false;
return true;
}
static std::string host_inventory_text(const json& row) {
for (const char* key : {"label", "snippet", "content"}) {
const std::string text = row.value(key, "");
if (is_host_inventory_text(text)) return text;
}
return "";
}
static json host_record_from_row(const json& row, const std::string& text) {
return {
{"stable_id", row.value("stable_id", "")},
{"status", row.value("status", "")},
{"label", text},
{"kind", row.value("kind", "claim")},
{"sector", row.value("sector", "windows-sre")},
};
}
static json host_record_from_rag() {
godbrain_rag::Client client;
json response;
std::string error;
if (client.search("Windows host inventory os_pin", response, error)) {
json fallback;
for (const auto& row : response.value("results", json::array())) {
const std::string text = host_inventory_text(row);
if (text.empty()) continue;
json rec = host_record_from_row(row, text);
if (rec.value("status", "") == "verified") return rec;
if (fallback.empty()) fallback = rec;
}
if (!fallback.empty()) return fallback;
}
json graph;
if (client.graph(80, graph, error)) {
json fallback;
for (const auto& node : graph.value("nodes", json::array())) {
const std::string text = host_inventory_text(node);
if (text.empty()) continue;
json rec = host_record_from_row(node, text);
if (rec.value("status", "") == "verified") return rec;
if (fallback.empty()) fallback = rec;
}
if (!fallback.empty()) return fallback;
}
return json::object();
}
static json kernel_status_body() {
json rag_health = json::object();
httplib::Client health("127.0.0.1", 8084);
health.set_connection_timeout(0, 200000);
health.set_read_timeout(1, 0);
if (const auto probe = health.Get("/health")) {
try {
rag_health = json::parse(probe->body);
} catch (const json::exception&) {
}
}
json tailscale = telemetry::get_tailscale();
if (tailscale.value("up", false)) {
if (g_api_token.empty()) {
tailscale["writes"] = "disabled_no_token";
tailscale["bound"] = false;
} else {
maybe_bind_tailscale_door();
tailscale["writes"] = "token_required";
tailscale["bound"] = tailscale_door_bound_to(
tailscale.value("ip", ""));
}
} else {
tailscale["bound"] = false;
if (tailscale.value("writes", "") == "") {
tailscale["writes"] = "loopback_only";
}
}
const json coli = coli_serve_status();
bool mouth_restarting = false;
if (!coli.value("up", false)) {
mouth_restarting = maybe_restart_mouth();
}
json host = telemetry::get_host_inventory();
const json live = telemetry::get_current_state();
host["ram_available_gb"] = live.value("ram_available_gb", 0.0);
host["ram_used_percent"] = live.value("system_ram_percent", 0);
const json host_record = host_record_from_rag();
const json turns = last_oracle_turns_json();
const json pending_items = collect_pending_items(turns, host_record);
int oracle_pending = 0;
int host_pending = 0;