-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.cpp
More file actions
2027 lines (1857 loc) · 90.5 KB
/
Copy pathapp.cpp
File metadata and controls
2027 lines (1857 loc) · 90.5 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
#include <iostream>
#include <string>
#include <memory>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <functional>
#include <vector>
#include <cstdlib>
#include <mutex>
#include <format>
#include <filesystem>
#include <nlohmann/json.hpp>
#include "servic.cpp/servic.hpp"
#include "servic.cpp/router/router.hpp"
#include "agent.hpp"
#include "servic.cpp/tiny_sha.h"
using json = nlohmann::json;
namespace fs = std::filesystem;
namespace app
{
// 默认配置模板 —— settings.json 找不到时自动生成
static const std::string DEFAULT_SETTINGS = R"({
"agent_name": "assistant",
"filesystem": {
"auto_expand": false
},
"channels": [
{
"config": {
"backend_url": "http://127.0.0.1:8080/api/input",
"model": "default",
"proxy": "http://127.0.0.1:10809",
"think": false,
"timeout": 600
},
"name": "Telegram",
"path": "sys/tg_bot.py",
"status": "active",
"user_count": 1
},
{
"config": {
"backend_url": "http://127.0.0.1:8080/api/input",
"ilink_base": "https://ilinkai.weixin.qq.com",
"model": "default",
"think": false,
"timeout": 600
},
"name": "WeChat",
"path": "sys/wx_bot.py",
"status": "active",
"user_count": 1
}
],
"current_provider": "openai-default",
"max_context": 1048576,
"max_mpc_rounds": 5,
"model": "uGemma4",
"webui_password": "a2aba198385559c15dc12398e197d556ef3cd6b45329d003b8886a0eecedec05",
"prompt": "agent.txt",
"providers": [
{
"has_key": false,
"id": "openai-default",
"name": "OpenAI",
"server_address": "http://localhost:11434",
"type": "openai"
}
],
"stream": true,
"user_name": "Yauntyours",
"workspace": "./workspace/"
})";
void replaceAll(std::string &str, const std::string &from, const std::string &to)
{
if (from.empty())
return;
size_t pos = 0;
while ((pos = str.find(from, pos)) != std::string::npos)
{
str.replace(pos, from.length(), to);
pos += to.length();
}
}
static std::string Admin;
static std::string system_prompt;
// 日志工具:将所有错误写入 webui.log
static void webui_log(const std::string &level, const std::string &context, const std::string &message)
{
try
{
auto now = std::chrono::system_clock::now();
std::time_t t = std::chrono::system_clock::to_time_t(now);
std::string time_str = std::asctime(std::localtime(&t));
if (!time_str.empty() && time_str.back() == '\n')
time_str.pop_back();
std::string ws = run_unit::settings.value("workspace", ".");
std::string log_path = ws + "/webui.log";
std::ofstream log_file(log_path, std::ios::app);
if (log_file.is_open())
{
log_file << "[" << time_str << "] [" << level << "] [" << context << "] " << message << std::endl;
}
}
catch (...)
{
// 日志本身不抛出异常
}
}
static std::string tools_list_str; // 工具列表的字符串表示
// ==================== 模型供应商支持 ====================
enum class ProviderType
{
OpenAI,
Ollama,
Llama
};
static ProviderType current_provider = ProviderType::OpenAI;
static LLMProviders::OpenAIClient openai_client;
static LLMProviders::OllamaClient ollama_client;
static LLMProviders::LlamaClient llama_client;
std::string client_models()
{
switch (current_provider)
{
case ProviderType::OpenAI:
return openai_client.models();
case ProviderType::Ollama:
return ollama_client.models();
case ProviderType::Llama:
return llama_client.models();
}
return "";
}
bool client_generate(nlohmann::json &req, nlohmann::json &resp)
{
switch (current_provider)
{
case ProviderType::OpenAI:
return openai_client.generate(req, resp);
case ProviderType::Ollama:
return ollama_client.generate(req, resp);
case ProviderType::Llama:
return llama_client.generate(req, resp);
}
return false;
}
std::string client_stream_generate(
nlohmann::json &req,
std::function<void(const std::string &)> on_token,
std::function<void(const std::string &)> on_thinking = nullptr)
{
switch (current_provider)
{
case ProviderType::OpenAI:
return openai_client.stream_generate(req, on_token, on_thinking);
case ProviderType::Ollama:
case ProviderType::Llama:
{
// Ollama/Llama 不支持流式,回退到非流式
nlohmann::json resp;
if (current_provider == ProviderType::Ollama)
ollama_client.generate(req, resp);
else
llama_client.generate(req, resp);
if (resp.contains("choices") && !resp["choices"].empty())
{
std::string content = resp["choices"][0]["message"]["content"].get<std::string>();
if (on_token)
on_token(content);
return content;
}
return "";
}
}
return "";
}
void switch_provider(const std::string &provider_type, const std::string &base_url, const std::string &api_key)
{
if (provider_type == "ollama")
{
current_provider = ProviderType::Ollama;
ollama_client.set_base_url(base_url);
ollama_client.set_api_key(api_key);
std::cout << "Provider switched to Ollama: " << base_url << std::endl;
}
else if (provider_type == "llama")
{
current_provider = ProviderType::Llama;
llama_client.set_base_url(base_url);
llama_client.set_api_key(api_key);
std::cout << "Provider switched to Llama: " << base_url << std::endl;
}
else
{
current_provider = ProviderType::OpenAI;
openai_client.set_base_url(base_url);
openai_client.set_api_key(api_key);
std::cout << "Provider switched to OpenAI: " << base_url << std::endl;
}
}
// 根据 provider id 从 providers 数组中查找并切换
bool switch_provider_by_id(const std::string &provider_id)
{
if (!run_unit::settings.contains("providers"))
return false;
auto &providers = run_unit::settings["providers"];
for (auto &p : providers)
{
if (p.value("id", "") == provider_id)
{
std::string type = p.value("type", "openai");
std::string base_url = p.value("server_address", "");
// 从加密文件读取 api_key
std::string api_key = "";
std::string ws = run_unit::settings.value("workspace", ".");
std::string key_file = ws + "/tokens/providers/" + provider_id + ".enc";
if (std::filesystem::exists(key_file))
{
std::string encrypted = tool_unit::readFile(key_file);
if (!encrypted.empty())
{
if (encrypted.back() == '\n')
encrypted.pop_back();
api_key = crypto_unit::decrypt(encrypted, crypto_context::key());
}
}
switch_provider(type, base_url, api_key);
run_unit::settings["current_provider"] = provider_id;
tool_unit::writeFile(run_unit::setting_file_path, run_unit::settings.dump(4));
return true;
}
}
return false;
}
// 根据 provider id 从 providers 数组中查找
json *find_provider(const std::string &provider_id)
{
if (!run_unit::settings.contains("providers"))
return nullptr;
auto &providers = run_unit::settings["providers"];
for (auto &p : providers)
{
if (p.value("id", "") == provider_id)
{
return &p;
}
}
return nullptr;
}
std::string provider_to_string()
{
switch (current_provider)
{
case ProviderType::OpenAI:
return "openai";
case ProviderType::Ollama:
return "ollama";
case ProviderType::Llama:
return "llama";
}
return "openai";
}
std::string to_hex_string(const uint8_t *hash, size_t len)
{
std::stringstream ss;
for (size_t i = 0; i < len; i++)
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
return ss.str();
}
int init_app(const std::string &setting_path = "settings.json", const std::string &password = "", const std::string &apikey = "")
{
// 当 settings.json 不存在时,自动使用默认配置模板生成
if (!std::filesystem::exists(setting_path))
{
std::cout << "Warning - settings.json not found, creating default..." << std::endl;
tool_unit::writeFile(setting_path, DEFAULT_SETTINGS);
}
run_unit::init_check(setting_path);
// 初始化供应商(使用 providers 数组)
{
std::string current_prov_id = run_unit::settings.value("current_provider", "openai-default");
// 兼容旧版配置:如果 providers 数组不存在,从旧的 provider 和 server_address 迁移
if (!run_unit::settings.contains("providers") || run_unit::settings["providers"].empty())
{
std::string old_provider = run_unit::settings.value("provider", "openai");
std::string old_server = run_unit::settings.value("server_address", "http://localhost:11434");
json new_provider = {
{"id", "openai-default"},
{"name", "OpenAI"},
{"type", old_provider},
{"server_address", old_server},
{"has_key", false}};
run_unit::settings["providers"] = json::array({new_provider});
run_unit::settings["current_provider"] = "openai-default";
tool_unit::writeFile(run_unit::setting_file_path, run_unit::settings.dump(4));
current_prov_id = "openai-default";
}
if (!switch_provider_by_id(current_prov_id))
{
// 如果找不到指定的 provider,使用第一个
auto &providers = run_unit::settings["providers"];
if (!providers.empty())
{
std::string first_id = providers[0].value("id", "");
if (!first_id.empty())
switch_provider_by_id(first_id);
}
}
}
// 初始化 libsodium(必须在任何 crypto_* 函数前调用)
if (sodium_init() < 0)
{
std::cerr << "Error: libsodium initialization failed" << std::endl;
exit(1);
}
// ——— 启动密码校验:workspace/sys/key 存储 Argon2id 哈希,输入密码必须匹配 ———
{
std::string ws = run_unit::settings["workspace"].get<std::string>();
std::string key_path = ws + "/sys/key";
if (!std::filesystem::exists(key_path))
{
// 首次运行:生成 key 文件
if (!password.empty())
{
char stored_hash[crypto_pwhash_STRBYTES];
if (crypto_pwhash_str(stored_hash, password.c_str(), password.size(),
crypto_pwhash_OPSLIMIT_MODERATE,
crypto_pwhash_MEMLIMIT_MODERATE) != 0)
{
std::cerr << "Error: failed to hash password" << std::endl;
exit(1);
}
tool_unit::writeFile(key_path, std::string(stored_hash));
std::cout << "Password hash saved to workspace/sys/key" << std::endl;
}
}
else
{
// 已有 key 文件:强制验证
if (password.empty())
{
std::cerr << "Error: password required but not provided" << std::endl;
exit(1);
}
std::string stored_hash_str = tool_unit::readFile(key_path);
if (!stored_hash_str.empty() && stored_hash_str.back() == '\n')
stored_hash_str.pop_back();
if (crypto_pwhash_str_verify(stored_hash_str.c_str(),
password.c_str(), password.size()) != 0)
{
std::cerr << "Error: incorrect password — system terminated" << std::endl;
exit(1);
}
std::cout << "Password verified OK" << std::endl;
}
}
// 用密码派生 32 字节加密密钥,API key 以密文形式保存在内存中
crypto_context::init_key_from_password(password);
// 设置 API key 到当前供应商
if (current_provider == ProviderType::OpenAI)
openai_client.set_api_key(apikey);
else if (current_provider == ProviderType::Ollama)
ollama_client.set_api_key(apikey);
else
llama_client.set_api_key(apikey);
// SHA3-256 密码哈希注入 settings(供 Web UI 会话认证)
{
uint8_t password_hash[SHA3_256_DIGEST_SIZE];
if (!SHA3_256((const uint8_t *)password.c_str(), password.length(), password_hash))
exit(1);
run_unit::settings.emplace("webui_password", to_hex_string(password_hash, SHA3_256_DIGEST_SIZE));
}
Admin = run_unit::settings["user_name"].get<std::string>();
// 仅启用 enabled 的工具
{
nlohmann::json enabled_tools = nlohmann::json::array();
for (auto &t : run_unit::tools_list)
{
if (t.value("enabled", true))
enabled_tools.push_back(t);
}
tools_list_str = enabled_tools.dump();
}
system_prompt = tool_unit::readFile(
run_unit::settings["workspace"].get_ref<const std::string &>() +
run_unit::settings["prompt"].get_ref<const std::string &>()) +
run_unit::cs_prompt;
replaceAll(system_prompt, " ", "");
replaceAll(system_prompt, "\r\n", "");
return 0;
}
// 辅助:提取消息中的文本内容(用于统计长度等)
static std::string extract_text(const json &msg)
{
if (msg["content"].is_string())
return msg["content"].get<std::string>();
if (msg["content"].is_array())
{
std::string text;
for (auto &part : msg["content"])
if (part["type"] == "text")
text += part["text"].get<std::string>();
return text;
}
return "";
}
// ------------- 记忆管理(基于会话) -------------
int save_memory(std::shared_ptr<run_unit::SessionContext> session_ptr, const std::string &model)
{
try
{
size_t total_prompt_tokens = 0;
size_t total_completion_tokens = 0;
auto [aq, kq] = session_ptr->summary_query();
nlohmann::json response;
nlohmann::json req = {
{"model", model},
{"messages", {{{"role", "system"}, {"content", aq}}}},
{"stream", false}};
client_generate(req, response);
if (response.contains("usage"))
{
auto &usage = response["usage"];
if (usage.contains("prompt_tokens"))
total_prompt_tokens += usage["prompt_tokens"].get<size_t>();
if (usage.contains("completion_tokens"))
total_completion_tokens += usage["completion_tokens"].get<size_t>();
}
session_ptr->memory["abstracts"] = response["choices"][0]["message"]["content"].get<std::string>();
std::cout << "Abstracts generated successfully." << std::endl;
req["messages"][0]["content"] = kq;
client_generate(req, response);
if (response.contains("usage"))
{
auto &usage = response["usage"];
if (usage.contains("prompt_tokens"))
total_prompt_tokens += usage["prompt_tokens"].get<size_t>();
if (usage.contains("completion_tokens"))
total_completion_tokens += usage["completion_tokens"].get<size_t>();
}
session_ptr->memory["keywords"] = response["choices"][0]["message"]["content"].get<std::string>();
std::cout << "Keywords generated successfully." << std::endl;
session_ptr->memory["created_at"] = std::to_string(std::time(nullptr));
auto &mem_usage = run_unit::agent_data_manager.data["usages"]["memory"];
mem_usage["prompt_cost"] = mem_usage.value("prompt_cost", 0) + total_prompt_tokens;
mem_usage["completion_cost"] = mem_usage.value("completion_cost", 0) + total_completion_tokens;
mem_usage["total_cost"] = mem_usage.value("total_cost", 0) + total_prompt_tokens + total_completion_tokens;
}
catch (const std::exception &e)
{
std::cerr << "ERROR - Memory summarize: " << e.what() << '\n';
webui_log("ERROR", "save_memory", e.what());
}
return 0;
}
namespace server
{
std::string build_http_response(int status_code, const std::string &content_type, const std::string &body, bool cors = true)
{
std::string final_content_type = "";
// 自动为常见文本类型添加 charset,避免中文乱码
if (final_content_type.find("application/json") != std::string::npos ||
final_content_type.find("text/") != std::string::npos)
{
if (final_content_type.find("charset=") == std::string::npos)
{
final_content_type += "; charset=utf-8";
}
}
std::ostringstream oss;
oss << "HTTP/1.1 " << status_code << " " << (status_code == 200 ? "OK" : "Not Found") << "\r\n";
oss << "Content-Type: " << content_type + final_content_type << "\r\n";
oss << "Content-Length: " << body.length() << "\r\n";
if (cors)
{
oss << "Access-Control-Allow-Origin: *\r\n";
oss << "Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n";
oss << "Access-Control-Allow-Headers: Content-Type\r\n";
}
oss << "\r\n"
<< body;
return oss.str();
}
int handle_root(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_input_packed(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_models(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_settings(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_data(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_provider(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
// ——— 供应商管理 ———
int handle_providers_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_providers_add(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_providers_update(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_providers_delete(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
// ——— 供应商 API Key 加密存储 ———
int handle_provider_key_set(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_provider_key_get(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_channels_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
// ——— 频道 Token 管理 ———
int handle_channel_token_set(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_channel_token_get(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_tools_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_todos_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_todos_setting(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_todos_delete(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_todos_new(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_new_session(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_session_clear(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_session_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_session_get_msg(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_session_delete(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_session_memory(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_tools_toggle(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_fs_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
int handle_fs_used(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms);
void handle_input_streaming(std::string &input, rt::WriteCallback write, const std::map<std::string, std::string> ¶ms);
void register_routes(rt::router &router)
{
router.on("/", handle_root);
router.on("/api/models", handle_models);
router.on("/api/settings", handle_settings);
router.on("/api/data", handle_data);
router.on("/api/provider", handle_provider);
// 供应商管理 API
router.on("/api/providers", handle_providers_list);
router.on("/api/providers/add", handle_providers_add);
router.on("/api/providers/update", handle_providers_update);
router.on("/api/providers/delete", handle_providers_delete);
// 供应商 API Key 加密存储 API
router.on("/api/provider/key", handle_provider_key_set); // POST — 加密存储
router.on("/api/provider/key/:id", handle_provider_key_get); // GET — 解密读取
router.on("/api/input", handle_input_packed);
router.on("/api/session", handle_session_list);
router.on("/api/session/new", handle_new_session);
router.on("/api/session/msg", handle_session_get_msg);
router.on("/api/session/delete", handle_session_delete);
router.on("/api/session/memory", handle_session_memory);
router.on("/api/session/clear", handle_session_clear);
router.on("/api/channels", handle_channels_list);
router.on("/api/channel/token", handle_channel_token_set); // POST — 加密存储
router.on("/api/channel/token/:name", handle_channel_token_get); // GET — 解密读取
router.on("/api/tools", handle_tools_list);
router.on("/api/tools/toggle", handle_tools_toggle);
router.on("/api/fs/list", handle_fs_list);
router.on("/api/fs/used", handle_fs_used);
router.on("/api/todos", handle_todos_list);
router.on("/api/todos/new", handle_todos_new);
router.on("/api/todos/delete/:id", handle_todos_delete);
router.on("/api/todos/:id", handle_todos_setting);
// 流式路由
router.on_stream("/api/input/stream", handle_input_streaming);
}
int handle_root(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
std::string html;
try
{
html = tool_unit::readFile(run_unit::settings["workspace"].get_ref<const std::string &>() + "/webui.html");
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_root", e.what());
html = "<h1>Welcome</h1><p>Error loading webui.html</p>";
}
catch (...)
{
webui_log("ERROR", "handle_root", "unknown error");
html = "<h1>Welcome</h1><p>Error loading webui.html</p>";
}
output = build_http_response(200, "text/html", html);
return rt::FLAG_DONE;
}
int handle_models(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
output = build_http_response(200, "application/json", client_models());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_models", e.what());
output = build_http_response(500, "application/json", R"({"error":"cannot connect to Ollama"})");
return rt::FLAG_ERROR;
}
catch (...)
{
webui_log("ERROR", "handle_models", "unknown error");
output = build_http_response(500, "application/json", R"({"error":"cannot connect to Ollama"})");
return rt::FLAG_ERROR;
}
}
int handle_session_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
json resp = {{"session_list", run_unit::agent_session_manager.list_sessions()}};
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
int handle_new_session(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
auto new_session = run_unit::agent_session_manager.create();
json resp = {{"status", "OK"}, {"session_id", new_session->session_id}};
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
int handle_session_clear(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
run_unit::agent_session_manager.clear_current();
json resp = {{"status", "cleared"}};
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
int handle_session_delete(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
size_t header_end = input.find("\r\n\r\n");
std::string body = (header_end != std::string::npos) ? input.substr(header_end + 4) : "";
json request = json::parse(body);
std::string session_id = request["session_id"];
// 检查是否为频道会话(系统频道不可删除)
auto &channels = run_unit::settings["channels"];
bool is_channel = false;
for (auto &ch : channels)
{
if (ch["name"].get<std::string>() == session_id)
{
is_channel = true;
break;
}
}
if (is_channel)
{
output = build_http_response(403, "application/json",
R"({"error":"Cannot delete a channel session"})");
return rt::FLAG_ERROR;
}
// 从内存移除
run_unit::agent_session_manager.remove_session(session_id);
// 删除磁盘文件
std::string ws = run_unit::settings["workspace"].get<std::string>();
std::string session_file = ws + "/sessions/" + session_id + ".json";
std::string memory_file = ws + "/memorys/" + session_id + ".json";
std::string asset_file = ws + "/assets/messages/" + session_id + ".json";
if (std::filesystem::exists(session_file))
std::filesystem::remove(session_file);
if (std::filesystem::exists(memory_file))
std::filesystem::remove(memory_file);
if (std::filesystem::exists(asset_file))
std::filesystem::remove(asset_file);
output = build_http_response(200, "application/json", R"({"status":"deleted"})");
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_session_delete", e.what());
output = build_http_response(500, "application/json", json{{"error", e.what()}}.dump());
return rt::FLAG_ERROR;
}
}
int handle_session_get_msg(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
size_t header_end = input.find("\r\n\r\n");
std::string body = (header_end != std::string::npos) ? input.substr(header_end + 4) : "";
json request = json::parse(body);
std::string session_id = request["session_id"];
auto session = run_unit::agent_session_manager.get(session_id);
if (!session)
{
output = build_http_response(404, "application/json", "{}");
return rt::FLAG_ERROR;
}
run_unit::agent_session_manager.change_session(session_id);
bool has_memory = !session->is_memory_empty();
json resp = {{"messages", session->messages}, {"memory", has_memory}};
if (has_memory)
resp["memory_created_at"] = session->memory["created_at"];
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_session_get_msg", e.what());
output = build_http_response(500, "application/json", "{}");
return rt::FLAG_ERROR;
}
catch (...)
{
webui_log("ERROR", "handle_session_get_msg", "unknown error");
output = build_http_response(500, "application/json", "{}");
return rt::FLAG_ERROR;
}
}
int handle_session_memory(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
auto session = run_unit::agent_session_manager.get_current();
save_memory(session, run_unit::settings["model"].get<std::string>());
json resp = {{"status", "done"}};
resp["memory_created_at"] = session->memory["created_at"];
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_session_memory", e.what());
output = build_http_response(500, "application/json", json{{"status", "failed"}}.dump());
return rt::FLAG_ERROR;
}
}
int handle_settings(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
size_t header_end = input.find("\r\n\r\n");
std::string body = (header_end != std::string::npos) ? input.substr(header_end + 4) : "";
json input_data = json::parse(body);
if (input_data["updata"].get<bool>() && input_data.contains("settings"))
{
if (run_unit::validateJsonFormat(input_data["settings"]))
{
run_unit::settings = input_data["settings"];
tool_unit::writeFile(run_unit::setting_file_path, run_unit::settings.dump(4));
}
else
{
output = build_http_response(500, "text/plain", "Settings saved failed.");
return rt::FLAG_ERROR;
}
}
output = build_http_response(200, "application/json", run_unit::settings.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_settings", e.what());
output = build_http_response(500, "text/plain", "Settings saved failed.");
return rt::FLAG_ERROR;
}
catch (...)
{
webui_log("ERROR", "handle_settings", "unknown error");
output = build_http_response(500, "text/plain", "Settings saved failed.");
return rt::FLAG_ERROR;
}
}
int handle_data(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
output = build_http_response(200, "application/json", run_unit::agent_data_manager.data.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_data", e.what());
output = build_http_response(500, "application/json", R"({"error":"Fail to get data"})");
return rt::FLAG_ERROR;
}
catch (...)
{
webui_log("ERROR", "handle_data", "unknown error");
output = build_http_response(500, "application/json", R"({"error":"Fail to get data"})");
return rt::FLAG_ERROR;
}
}
int handle_provider(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
size_t header_end = input.find("\r\n\r\n");
std::string body = (header_end != std::string::npos) ? input.substr(header_end + 4) : "";
json request = json::parse(body);
std::string provider_id = request.value("provider_id", "");
if (provider_id.empty())
{
output = build_http_response(400, "application/json", R"({"error":"missing provider_id"})");
return rt::FLAG_ERROR;
}
if (!switch_provider_by_id(provider_id))
{
output = build_http_response(404, "application/json", R"({"error":"provider not found"})");
return rt::FLAG_ERROR;
}
json resp = {
{"status", "OK"},
{"provider_id", provider_id}};
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_provider", e.what());
output = build_http_response(500, "application/json", json{{"error", e.what()}}.dump());
return rt::FLAG_ERROR;
}
}
// —————————————— 供应商管理 API ——————————————
// GET /api/providers → 返回所有供应商列表
int handle_providers_list(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
json resp = {
{"providers", run_unit::settings.value("providers", json::array())},
{"current_provider", run_unit::settings.value("current_provider", "")}};
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_providers_list", e.what());
output = build_http_response(500, "application/json", json{{"error", e.what()}}.dump());
return rt::FLAG_ERROR;
}
}
// POST /api/providers/add → 添加新供应商
int handle_providers_add(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
size_t header_end = input.find("\r\n\r\n");
std::string body = (header_end != std::string::npos) ? input.substr(header_end + 4) : "";
json request = json::parse(body);
std::string id = request.value("id", "");
std::string name = request.value("name", "");
std::string type = request.value("type", "openai");
std::string server_address = request.value("server_address", "");
std::string api_key = request.value("api_key", "");
if (id.empty() || name.empty())
{
output = build_http_response(400, "application/json", R"({"error":"missing id or name"})");
return rt::FLAG_ERROR;
}
// 检查 id 是否已存在
if (!run_unit::settings.contains("providers"))
run_unit::settings["providers"] = json::array();
for (auto &p : run_unit::settings["providers"])
{
if (p.value("id", "") == id)
{
output = build_http_response(409, "application/json", R"({"error":"provider id already exists"})");
return rt::FLAG_ERROR;
}
}
// 如果提供了 api_key,加密存储到文件
if (!api_key.empty())
{
std::string ws = run_unit::settings["workspace"].get<std::string>();
std::string key_dir = ws + "/tokens/providers";
std::filesystem::create_directories(key_dir);
std::string file_path = key_dir + "/" + id + ".enc";
std::string encrypted = crypto_unit::encrypt(api_key, crypto_context::key());
if (encrypted.empty())
{
output = build_http_response(500, "application/json", R"({"error":"encryption failed"})");
return rt::FLAG_ERROR;
}
tool_unit::writeFile(file_path, encrypted);
}
// 不在 settings.json 中存储 api_key,只标记是否有 key
json new_provider = {
{"id", id},
{"name", name},
{"type", type},
{"server_address", server_address},
{"has_key", !api_key.empty()}};
run_unit::settings["providers"].push_back(new_provider);
tool_unit::writeFile(run_unit::setting_file_path, run_unit::settings.dump(4));
json resp = {{"status", "OK"}, {"provider", new_provider}};
output = build_http_response(200, "application/json", resp.dump());
return rt::FLAG_DONE;
}
catch (const std::exception &e)
{
webui_log("ERROR", "handle_providers_add", e.what());
output = build_http_response(500, "application/json", json{{"error", e.what()}}.dump());
return rt::FLAG_ERROR;
}
}
// POST /api/providers/update → 更新供应商配置
int handle_providers_update(std::string &input, std::string &output, const std::map<std::string, std::string> ¶ms)
{
try
{
size_t header_end = input.find("\r\n\r\n");
std::string body = (header_end != std::string::npos) ? input.substr(header_end + 4) : "";
json request = json::parse(body);
std::string id = request.value("id", "");
if (id.empty())
{
output = build_http_response(400, "application/json", R"({"error":"missing id"})");
return rt::FLAG_ERROR;
}
json *provider = find_provider(id);
if (!provider)
{
output = build_http_response(404, "application/json", R"({"error":"provider not found"})");
return rt::FLAG_ERROR;
}
// 更新字段(只更新提供的字段)
if (request.contains("name"))
(*provider)["name"] = request["name"];
if (request.contains("type"))
(*provider)["type"] = request["type"];
if (request.contains("server_address"))
(*provider)["server_address"] = request["server_address"];
// 如果提供了 api_key,加密存储到文件
if (request.contains("api_key"))
{
std::string api_key = request["api_key"].get<std::string>();
std::string ws = run_unit::settings["workspace"].get<std::string>();
std::string key_dir = ws + "/tokens/providers";
std::filesystem::create_directories(key_dir);
std::string file_path = key_dir + "/" + id + ".enc";
if (api_key.empty())
{
// 空 api_key → 删除文件
if (std::filesystem::exists(file_path))
std::filesystem::remove(file_path);
(*provider)["has_key"] = false;