-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconfig.cpp
More file actions
2643 lines (2482 loc) · 121 KB
/
Copy pathconfig.cpp
File metadata and controls
2643 lines (2482 loc) · 121 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 "config.hpp"
#include "config_recovery.hpp"
#include "model_provider_registry.hpp"
#include "request_headers.hpp"
#include "../utils/constants.hpp"
#include "../utils/atomic_file.hpp"
#include "../utils/logger.hpp"
#include "../utils/http_url_validation.hpp"
#include "../utils/paths.hpp"
#include "../utils/utf8_path.hpp"
#include <algorithm>
#include <atomic>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <filesystem>
#include <initializer_list>
#include <limits>
#include <set>
#include <sstream>
#include <stdexcept>
namespace fs = std::filesystem;
namespace acecode {
namespace {
std::atomic<bool> g_acecode_home_created_by_process{false};
class ConfigLoadFailure final : public std::runtime_error {
public:
ConfigLoadFailure(std::string category, std::string summary)
: std::runtime_error(std::move(summary)),
category_(std::move(category)) {}
const std::string& category() const noexcept { return category_; }
private:
std::string category_;
};
std::string trim_ascii_copy(const std::string& s) {
size_t first = 0;
while (first < s.size() && std::isspace(static_cast<unsigned char>(s[first]))) {
++first;
}
size_t last = s.size();
while (last > first && std::isspace(static_cast<unsigned char>(s[last - 1]))) {
--last;
}
return s.substr(first, last - first);
}
std::string normalized_web_bind(std::string value) {
value = trim_ascii_copy(value);
std::transform(
value.begin(), value.end(), value.begin(),
[](unsigned char ch) { return static_cast<char>(std::tolower(ch)); });
if (value.size() >= 2 && value.front() == '[' && value.back() == ']') {
value = value.substr(1, value.size() - 2);
}
return value;
}
bool web_bind_is_loopback(const std::string& raw_bind) {
const std::string bind = normalized_web_bind(raw_bind);
if (bind == "localhost" || bind == "::1") return true;
if (bind.rfind("127.", 0) == 0) return true;
constexpr const char* kMappedPrefix = "::ffff:";
if (bind.rfind(kMappedPrefix, 0) == 0) {
return bind.substr(std::char_traits<char>::length(kMappedPrefix))
.rfind("127.", 0) == 0;
}
return false;
}
bool is_one_of(const std::string& value, std::initializer_list<const char*> allowed) {
for (const char* item : allowed) {
if (value == item) return true;
}
return false;
}
std::string normalize_permission_mode_name(std::string value) {
if (value == "acceptEdits") value = "accept-edits";
if (is_one_of(value, {"default", "accept-edits", "plan", "yolo"})) {
return value;
}
if (!value.empty()) {
LOG_WARN("[config] default_permission_mode='" + value +
"' invalid; falling back to 'default'");
}
return "default";
}
std::optional<int> parse_positive_int(const std::string& value) {
const std::string trimmed = trim_ascii_copy(value);
if (trimmed.empty()) return std::nullopt;
try {
std::size_t pos = 0;
long long parsed = std::stoll(trimmed, &pos, 10);
if (pos != trimmed.size() ||
parsed <= 0 ||
parsed > std::numeric_limits<int>::max()) {
return std::nullopt;
}
return static_cast<int>(parsed);
} catch (...) {
return std::nullopt;
}
}
[[noreturn]] void fatal_config_value(const std::string& message) {
throw ConfigLoadFailure("semantic_validation", message);
}
[[noreturn]] void fatal_runtime_config_value(const std::string& message) {
std::cerr << "[config] fatal: " << message << std::endl;
LOG_ERROR("[config] " + message);
std::exit(1);
}
std::string legacy_model_profile_name(const AppConfig& cfg) {
if (cfg.provider == "openai") {
if (cfg.openai.models_dev_provider_id.has_value() &&
!cfg.openai.models_dev_provider_id->empty()) {
return *cfg.openai.models_dev_provider_id;
}
return "openai";
}
if (cfg.provider == "copilot") return "copilot";
if (cfg.provider == "grok") return "grok";
return "";
}
nlohmann::json connector_hook_to_json(const ConnectorHookConfig& hook) {
return {
{"command", hook.command},
{"args", hook.args},
{"timeout_ms", hook.timeout_ms},
};
}
bool parse_connector_hook(const nlohmann::json& item,
ConnectorHookConfig& out,
std::string& error_msg) {
if (!item.is_object() || !item.contains("command") || !item["command"].is_string()) {
error_msg = "must be an object with string command";
return false;
}
out.command = item["command"].get<std::string>();
if (out.command.empty()) {
error_msg = "command must not be empty";
return false;
}
out.args.clear();
if (item.contains("args")) {
if (!item["args"].is_array()) {
error_msg = "args must be an array of strings";
return false;
}
for (const auto& arg : item["args"]) {
if (!arg.is_string()) {
error_msg = "args must be an array of strings";
return false;
}
out.args.push_back(arg.get<std::string>());
}
}
if (item.contains("timeout_ms")) {
if (!item["timeout_ms"].is_number_integer()) {
error_msg = "timeout_ms must be an integer";
return false;
}
const int timeout = item["timeout_ms"].get<int>();
if (timeout > 0) out.timeout_ms = timeout;
}
return true;
}
} // namespace
std::string normalize_upgrade_base_url(std::string raw) {
raw = trim_ascii_copy(raw);
if (!raw.empty() && raw.back() != '/') {
raw.push_back('/');
}
return raw;
}
bool is_valid_upgrade_base_url(const std::string& raw) {
const std::string url = normalize_upgrade_base_url(raw);
return url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0;
}
bool is_valid_ui_locale(const std::string& locale) {
return locale == "auto" || locale == "zh-CN" || locale == "en-US";
}
bool is_valid_web_ui_theme(const std::string& theme) {
return theme == "system" || theme == "light" || theme == "dark";
}
bool is_valid_web_ui_color_theme(const std::string& color_theme) {
return color_theme == "blue" || color_theme == "orange";
}
bool is_valid_web_ui_font_size(const std::string& font_size) {
return font_size == "small" || font_size == "medium" ||
font_size == "large";
}
nlohmann::json connectors_to_json(const std::vector<ConnectorConfig>& connectors) {
nlohmann::json items = nlohmann::json::array();
for (const auto& connector : connectors) {
nlohmann::json item = {
{"id", connector.id},
{"name", connector.name},
{"description", connector.description},
{"enabled", connector.enabled},
};
nlohmann::json hooks = nlohmann::json::object();
if (connector.on_enable) {
hooks["on_enable"] = connector_hook_to_json(*connector.on_enable);
}
if (connector.on_auth_error) {
hooks["on_auth_error"] = connector_hook_to_json(*connector.on_auth_error);
}
if (connector.on_startup) {
hooks["on_startup"] = connector_hook_to_json(*connector.on_startup);
}
if (!hooks.empty()) item["hooks"] = std::move(hooks);
if (!connector.auth_error_base_url_prefix.empty()) {
item["auth_error_scope"] = {
{"base_url_prefix", connector.auth_error_base_url_prefix},
};
}
items.push_back(std::move(item));
}
return items;
}
bool parse_connectors_json(const nlohmann::json& value,
std::vector<ConnectorConfig>& out,
std::string* error) {
if (!value.is_array()) {
if (error) *error = "connectors must be an array";
return false;
}
std::vector<ConnectorConfig> parsed;
std::set<std::string> seen_ids;
parsed.reserve(value.size());
for (std::size_t i = 0; i < value.size(); ++i) {
const auto& item = value[i];
auto fail = [&](const std::string& message) {
if (error) {
*error = "connectors[" + std::to_string(i) + "] " + message;
}
return false;
};
if (!item.is_object()) return fail("must be an object");
if (!item.contains("id") || !item["id"].is_string()) {
return fail("must contain string id");
}
if (!item.contains("name") || !item["name"].is_string()) {
return fail("must contain string name");
}
if (!item.contains("description") || !item["description"].is_string()) {
return fail("must contain string description");
}
if (!item.contains("enabled") || !item["enabled"].is_boolean()) {
return fail("must contain boolean enabled");
}
ConnectorConfig connector;
connector.id = trim_ascii_copy(item["id"].get<std::string>());
connector.name = item["name"].get<std::string>();
connector.description = item["description"].get<std::string>();
connector.enabled = item["enabled"].get<bool>();
if (item.contains("hooks")) {
const auto& hooks = item["hooks"];
if (!hooks.is_object()) return fail("hooks must be an object");
std::string hook_error;
if (hooks.contains("on_enable")) {
ConnectorHookConfig hook;
if (!parse_connector_hook(hooks["on_enable"], hook, hook_error)) {
return fail("hooks.on_enable " + hook_error);
}
connector.on_enable = std::move(hook);
}
if (hooks.contains("on_auth_error")) {
ConnectorHookConfig hook;
if (!parse_connector_hook(hooks["on_auth_error"], hook, hook_error)) {
return fail("hooks.on_auth_error " + hook_error);
}
connector.on_auth_error = std::move(hook);
}
if (hooks.contains("on_startup")) {
ConnectorHookConfig hook;
if (!parse_connector_hook(hooks["on_startup"], hook, hook_error)) {
return fail("hooks.on_startup " + hook_error);
}
connector.on_startup = std::move(hook);
}
}
if (item.contains("auth_error_scope")) {
const auto& scope = item["auth_error_scope"];
if (!scope.is_object()) return fail("auth_error_scope must be an object");
if (scope.contains("base_url_prefix")) {
if (!scope["base_url_prefix"].is_string()) {
return fail("auth_error_scope.base_url_prefix must be a string");
}
connector.auth_error_base_url_prefix =
trim_ascii_copy(scope["base_url_prefix"].get<std::string>());
}
}
if (connector.id.empty()) return fail("id must not be empty");
if (connector.name.empty()) return fail("name must not be empty");
if (!seen_ids.insert(connector.id).second) {
return fail("id must be unique: " + connector.id);
}
parsed.push_back(std::move(connector));
}
out = std::move(parsed);
return true;
}
std::vector<ConnectorConfig> startup_hook_connectors(
const std::vector<ConnectorConfig>& connectors) {
std::vector<ConnectorConfig> out;
for (const auto& connector : connectors) {
if (connector.enabled && connector.on_startup) out.push_back(connector);
}
return out;
}
void load_connectors_lenient(const nlohmann::json& value,
std::vector<ConnectorConfig>& out) {
if (!value.is_array()) {
LOG_WARN("[config] 'connectors' must be an array, ignoring");
return;
}
std::set<std::string> seen_ids;
std::vector<ConnectorConfig> parsed;
parsed.reserve(value.size());
for (std::size_t i = 0; i < value.size(); ++i) {
const auto& item = value[i];
if (!item.is_object() ||
!item.contains("id") || !item["id"].is_string() ||
!item.contains("name") || !item["name"].is_string() ||
!item.contains("description") || !item["description"].is_string()) {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] missing required id/name/description strings, skipping");
continue;
}
ConnectorConfig connector;
connector.id = trim_ascii_copy(item["id"].get<std::string>());
connector.name = item["name"].get<std::string>();
connector.description = item["description"].get<std::string>();
connector.enabled = item.contains("enabled") && item["enabled"].is_boolean()
? item["enabled"].get<bool>()
: true;
if (item.contains("hooks") && item["hooks"].is_object()) {
const auto& hooks = item["hooks"];
if (hooks.contains("on_enable")) {
ConnectorHookConfig hook;
std::string hook_error;
if (parse_connector_hook(hooks["on_enable"], hook, hook_error)) {
connector.on_enable = std::move(hook);
} else {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] hooks.on_enable " + hook_error + ", ignoring hook");
}
}
if (hooks.contains("on_auth_error")) {
ConnectorHookConfig hook;
std::string hook_error;
if (parse_connector_hook(hooks["on_auth_error"], hook, hook_error)) {
connector.on_auth_error = std::move(hook);
} else {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] hooks.on_auth_error " + hook_error + ", ignoring hook");
}
}
if (hooks.contains("on_startup")) {
ConnectorHookConfig hook;
std::string hook_error;
if (parse_connector_hook(hooks["on_startup"], hook, hook_error)) {
connector.on_startup = std::move(hook);
} else {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] hooks.on_startup " + hook_error + ", ignoring hook");
}
}
} else if (item.contains("hooks")) {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] hooks must be an object, ignoring hooks");
}
if (item.contains("auth_error_scope")) {
const auto& scope = item["auth_error_scope"];
if (scope.is_object() && scope.contains("base_url_prefix") &&
scope["base_url_prefix"].is_string()) {
connector.auth_error_base_url_prefix =
trim_ascii_copy(scope["base_url_prefix"].get<std::string>());
} else if (scope.is_object() && scope.contains("base_url_prefix")) {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] auth_error_scope.base_url_prefix must be a string, ignoring");
} else if (!scope.is_object()) {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] auth_error_scope must be an object, ignoring");
}
}
if (connector.id.empty() || connector.name.empty()) {
LOG_WARN("[config] connectors[" + std::to_string(i) +
"] has empty id or name, skipping");
continue;
}
if (!seen_ids.insert(connector.id).second) {
LOG_WARN("[config] duplicate connector id '" + connector.id + "', skipping");
continue;
}
parsed.push_back(std::move(connector));
}
out = std::move(parsed);
}
ModelProfile legacy_model_profile_from_config(const AppConfig& cfg) {
ModelProfile profile;
profile.name = legacy_model_profile_name(cfg);
if (cfg.provider == "openai") {
OpenAiConfig defaults;
profile.provider = "openai";
profile.base_url = cfg.openai.base_url.empty()
? defaults.base_url
: cfg.openai.base_url;
profile.api_key = cfg.openai.api_key;
profile.model = cfg.openai.model.empty()
? defaults.model
: cfg.openai.model;
profile.stream_timeout_ms = cfg.openai.stream_timeout_ms;
profile.request_headers = cfg.openai.request_headers;
profile.models_dev_provider_id = cfg.openai.models_dev_provider_id;
return profile;
}
if (cfg.provider == "grok") {
profile.provider = "grok";
profile.model = "grok-4.5";
profile.models_dev_provider_id = "xai";
return profile;
}
if (cfg.provider != "copilot") return profile;
CopilotConfig defaults;
profile.provider = "copilot";
profile.model = cfg.copilot.model.empty()
? defaults.model
: cfg.copilot.model;
return profile;
}
std::string get_acecode_dir() {
// 数据目录路径解析全部委托给 paths.cpp,RunMode 决定 User vs Service 根目录
// (Decision 8)。User 模式行为与历史一致 — TUI / standalone daemon 不受影响。
return resolve_data_dir(get_run_mode());
}
std::string get_run_dir() {
// desktop 多 workspace 模式下 daemon 启动时会调 set_run_dir_override,
// 把 run/ 切到 per-workspace 路径(避免共享 ~/.acecode/run/ 互相覆盖锁文件)。
auto override_path = get_run_dir_override();
if (!override_path.empty()) return override_path;
return path_to_utf8(path_from_utf8(get_acecode_dir()) / constants::SUBDIR_RUN);
}
std::string get_logs_dir() {
return path_to_utf8(path_from_utf8(get_acecode_dir()) / constants::SUBDIR_LOGS);
}
std::vector<std::string> validate_config(const AppConfig& cfg) {
std::vector<std::string> errors;
if (cfg.web.port < 1 || cfg.web.port > 65535) {
errors.push_back("web.port out of range (1-65535): " + std::to_string(cfg.web.port));
}
if (cfg.web.bind.empty()) {
errors.push_back("web.bind is empty; expected an IP address (e.g. 127.0.0.1)");
}
if (!is_valid_web_ui_theme(cfg.web_ui.theme)) {
errors.push_back("web_ui.theme must be one of: system, light, dark");
}
if (!is_valid_web_ui_color_theme(cfg.web_ui.color_theme)) {
errors.push_back("web_ui.color_theme must be one of: blue, orange");
}
if (!is_valid_web_ui_font_size(cfg.web_ui.font_size)) {
errors.push_back("web_ui.font_size must be one of: small, medium, large");
}
if (cfg.web.remote_port < 0 || cfg.web.remote_port > 65535) {
errors.push_back(
"web.remote_port out of range (0-65535): " +
std::to_string(cfg.web.remote_port));
} else if (cfg.web.remote_port != 0 &&
cfg.web.remote_port == cfg.web.port) {
errors.push_back(
"web.remote_port must differ from web.port because the reverse "
"proxy and daemon cannot share a wildcard port");
}
if (cfg.daemon.heartbeat_interval_ms <= 0) {
errors.push_back("daemon.heartbeat_interval_ms must be > 0");
}
if (cfg.daemon.heartbeat_timeout_ms <= cfg.daemon.heartbeat_interval_ms) {
errors.push_back("daemon.heartbeat_timeout_ms must be > daemon.heartbeat_interval_ms");
}
if (cfg.daemon.service_name.empty()) {
errors.push_back("daemon.service_name is empty");
}
if (cfg.memory.max_index_bytes == 0) {
errors.push_back("memory.max_index_bytes must be > 0");
}
if (cfg.openai.stream_timeout_ms <= 0) {
errors.push_back("openai.stream_timeout_ms must be > 0");
}
if (cfg.session_title.max_input_bytes < 1 || cfg.session_title.max_input_bytes > 20000) {
errors.push_back("session_title.max_input_bytes out of range (1-20000)");
}
if (cfg.session_title.timeout_ms < 1000 || cfg.session_title.timeout_ms > 120000) {
errors.push_back("session_title.timeout_ms out of range (1000-120000)");
}
if (!cfg.openai.request_headers.empty()) {
std::string err;
if (!validate_request_headers(cfg.openai.request_headers, err)) {
errors.push_back("openai." + err);
}
}
if (cfg.project_instructions.max_depth < 1) {
errors.push_back("project_instructions.max_depth must be >= 1");
}
if (cfg.project_instructions.max_bytes == 0) {
errors.push_back("project_instructions.max_bytes must be > 0");
}
if (cfg.project_instructions.max_total_bytes < cfg.project_instructions.max_bytes) {
errors.push_back("project_instructions.max_total_bytes must be >= max_bytes");
}
if (cfg.custom_instructions.text_snapshot().size() > kCustomInstructionsMaxBytes) {
errors.push_back("custom_instructions.text exceeds " +
std::to_string(kCustomInstructionsMaxBytes) + " bytes");
}
std::set<std::string> connector_ids;
for (const auto& connector : cfg.connectors) {
if (trim_ascii_copy(connector.id).empty()) {
errors.push_back("connectors.id must not be empty");
} else if (!connector_ids.insert(trim_ascii_copy(connector.id)).second) {
errors.push_back("connectors.id must be unique: " + connector.id);
}
if (connector.name.empty()) {
errors.push_back("connectors.name must not be empty for id: " +
connector.id);
}
}
if (!is_valid_upgrade_base_url(cfg.upgrade.base_url)) {
errors.push_back("upgrade.base_url must be a non-empty http or https URL");
}
if (cfg.upgrade.timeout_ms < 1000 || cfg.upgrade.timeout_ms > 120000) {
errors.push_back("upgrade.timeout_ms out of range (1000-120000): " +
std::to_string(cfg.upgrade.timeout_ms));
}
if (cfg.remote_control.port < 1 || cfg.remote_control.port > 65535) {
errors.push_back("remote_control.port out of range (1-65535): " +
std::to_string(cfg.remote_control.port));
}
if (!cfg.remote_control.default_channel.empty() &&
cfg.remote_control.channels.find(cfg.remote_control.default_channel) ==
cfg.remote_control.channels.end()) {
errors.push_back("remote_control.default_channel references an undefined channel: " +
cfg.remote_control.default_channel);
}
for (const auto& [name, channel] : cfg.remote_control.channels) {
if (name.empty()) {
errors.push_back("remote_control.channels contains an empty channel name");
continue;
}
bool bad_name = false;
for (unsigned char ch : name) {
if (std::isspace(ch) || ch == '/' || ch == '\\') {
bad_name = true;
break;
}
}
if (bad_name) {
errors.push_back("remote_control.channels." + name +
" must not contain whitespace or path separators");
}
if (channel.manifest_path.empty()) {
errors.push_back("remote_control.channels." + name +
".manifest_path must not be empty");
}
if (channel.timeout_ms < 1000 || channel.timeout_ms > 120000) {
errors.push_back("remote_control.channels." + name +
".timeout_ms out of range (1000-120000): " +
std::to_string(channel.timeout_ms));
}
if (!channel.settings.is_object()) {
errors.push_back("remote_control.channels." + name +
".settings must be a JSON object");
}
}
for (const auto& fn : cfg.project_instructions.filenames) {
if (fn.empty()) {
errors.push_back("project_instructions.filenames contains empty entry");
break;
}
if (fn.find('/') != std::string::npos || fn.find('\\') != std::string::npos) {
errors.push_back("project_instructions.filenames entry must not contain path separator: " + fn);
break;
}
}
return errors;
}
static void write_default_config(const std::string& config_path) {
nlohmann::json j;
j["provider"] = "";
j["openai"]["base_url"] = "http://localhost:1234/v1";
j["openai"]["api_key"] = "";
j["openai"]["model"] = "local-model";
j["copilot"]["model"] = "gpt-4o";
j["codex"]["model"] = "gpt-5.5";
j["saved_models"] = nlohmann::json::array();
j["default_model_name"] = "";
j["default_permission_mode"] = "default";
j["ui"]["locale"] = "auto";
std::ofstream ofs(path_from_utf8(config_path));
if (ofs.is_open()) {
ofs << j.dump(2) << std::endl;
}
}
static void synthesize_legacy_saved_model_if_needed(AppConfig& cfg,
bool saved_models_key_present) {
if (!cfg.saved_models.empty()) return;
if (saved_models_key_present) {
if (!cfg.default_model_name.empty()) {
LOG_WARN("[config] default_model_name ignored because saved_models is empty: " +
cfg.default_model_name);
cfg.default_model_name.clear();
}
return;
}
ModelProfile legacy = legacy_model_profile_from_config(cfg);
std::vector<ModelProfile> candidate{legacy};
std::string err;
if (validate_saved_models(candidate, legacy.name, err)) {
cfg.saved_models = std::move(candidate);
cfg.default_model_name = legacy.name;
LOG_WARN("[config] saved_models missing; synthesized legacy model profile '" +
legacy.name + "' from provider/openai/copilot/codex fields");
return;
}
if (!cfg.default_model_name.empty()) {
LOG_WARN("[config] default_model_name ignored because saved_models is empty: " +
cfg.default_model_name);
cfg.default_model_name.clear();
}
LOG_WARN("[config] saved_models missing and legacy fields cannot be migrated: " + err);
}
static const ModelProfile* find_profile_by_name(const std::vector<ModelProfile>& entries,
const std::string& name) {
if (name.empty()) return nullptr;
for (const auto& entry : entries) {
if (entry.name == name) return &entry;
}
return nullptr;
}
static const ModelProfile* first_enabled_profile(const std::vector<ModelProfile>& entries) {
for (const auto& entry : entries) {
if (is_runtime_model_provider_enabled(entry.provider)) return &entry;
}
return nullptr;
}
static void sanitize_disabled_model_providers(AppConfig& cfg) {
bool provider_was_disabled = false;
if (!cfg.provider.empty() && !is_runtime_model_provider_enabled(cfg.provider)) {
LOG_WARN(std::string("[config] provider '") + cfg.provider +
"' is disabled; falling back to an enabled saved model");
provider_was_disabled = true;
}
if (cfg.saved_models.empty()) {
if (provider_was_disabled) cfg.provider.clear();
return;
}
const ModelProfile* default_profile =
find_profile_by_name(cfg.saved_models, cfg.default_model_name);
if (default_profile &&
is_runtime_model_provider_enabled(default_profile->provider)) {
if (provider_was_disabled) cfg.provider = default_profile->provider;
return;
}
if (default_profile) {
LOG_WARN(std::string("[config] default model '") + cfg.default_model_name +
"' uses disabled provider '" + default_profile->provider + "'");
}
if (const ModelProfile* fallback = first_enabled_profile(cfg.saved_models)) {
if (cfg.default_model_name != fallback->name) {
LOG_WARN("[config] switching default model to enabled profile '" +
fallback->name + "'");
}
cfg.default_model_name = fallback->name;
cfg.provider = fallback->provider;
return;
}
LOG_WARN("[config] no enabled saved model profiles; clearing default model");
cfg.default_model_name.clear();
cfg.provider.clear();
}
AppConfig load_config() {
const std::string config_path =
path_to_utf8(path_from_utf8(get_acecode_dir()) / "config.json");
return load_config_from_path(config_path, true);
}
static AppConfig load_config_from_path_once(
const std::string& explicit_path,
bool apply_environment_overrides,
std::optional<std::string>* proven_persisted_bytes = nullptr) {
AppConfig cfg;
bool saved_models_key_present = false;
std::optional<std::string> active_bytes;
if (proven_persisted_bytes) proven_persisted_bytes->reset();
fs::path native_config_path = path_from_utf8(explicit_path);
fs::path native_acecode_dir = native_config_path.parent_path();
const std::string config_path = path_to_utf8(native_config_path);
// Create directory and default config if missing
std::error_code home_ec;
bool home_exists =
native_acecode_dir.empty() || fs::exists(native_acecode_dir, home_ec);
if (home_ec) home_exists = false;
if (!home_exists) {
fs::create_directories(native_acecode_dir);
g_acecode_home_created_by_process.store(true);
}
if (!fs::exists(native_config_path)) {
write_default_config(config_path);
}
// Read config file
std::ifstream ifs(native_config_path, std::ios::binary);
if (ifs.is_open()) {
try {
std::ostringstream raw_stream;
raw_stream << ifs.rdbuf();
if (ifs.bad()) {
throw ConfigLoadFailure(
"filesystem_read",
"failed to read config file: " + config_path);
}
active_bytes = raw_stream.str();
nlohmann::json j = nlohmann::json::parse(*active_bytes);
if (j.contains("provider") && j["provider"].is_string()) {
cfg.provider = j["provider"].get<std::string>();
}
if (j.contains("openai") && j["openai"].is_object()) {
auto& oj = j["openai"];
if (oj.contains("base_url") && oj["base_url"].is_string())
cfg.openai.base_url = oj["base_url"].get<std::string>();
if (oj.contains("api_key") && oj["api_key"].is_string())
cfg.openai.api_key = oj["api_key"].get<std::string>();
if (oj.contains("model") && oj["model"].is_string())
cfg.openai.model = oj["model"].get<std::string>();
if (oj.contains("stream_timeout_ms") &&
oj["stream_timeout_ms"].is_number_integer()) {
int v = oj["stream_timeout_ms"].get<int>();
if (v <= 0) {
fatal_config_value("openai.stream_timeout_ms=" +
std::to_string(v) +
" out of range (>0)");
}
cfg.openai.stream_timeout_ms = v;
}
if (oj.contains("models_dev_provider_id") &&
oj["models_dev_provider_id"].is_string()) {
cfg.openai.models_dev_provider_id =
oj["models_dev_provider_id"].get<std::string>();
}
if (oj.contains("request_headers")) {
std::string err;
auto parsed = parse_request_headers_json(
oj["request_headers"],
"openai",
err);
if (!parsed.has_value()) {
fatal_config_value(err);
}
cfg.openai.request_headers = std::move(*parsed);
}
}
if (j.contains("copilot") && j["copilot"].is_object()) {
auto& cj = j["copilot"];
if (cj.contains("model") && cj["model"].is_string())
cfg.copilot.model = cj["model"].get<std::string>();
}
if (j.contains("codex") && j["codex"].is_object()) {
auto& cj = j["codex"];
if (cj.contains("model") && cj["model"].is_string())
cfg.codex.model = cj["model"].get<std::string>();
}
if (j.contains("context_window") && j["context_window"].is_number_integer()) {
cfg.context_window = j["context_window"].get<int>();
}
if (j.contains("max_sessions") && j["max_sessions"].is_number_integer()) {
cfg.max_sessions = j["max_sessions"].get<int>();
}
if (j.contains("default_permission_mode") &&
j["default_permission_mode"].is_string()) {
cfg.default_permission_mode = normalize_permission_mode_name(
j["default_permission_mode"].get<std::string>());
}
if (j.contains("features") && j["features"].is_object()) {
const auto& fj = j["features"];
if (fj.contains("hooks") && fj["hooks"].is_boolean()) {
cfg.features.hooks = fj["hooks"].get<bool>();
}
if (fj.contains("completed_turn_self_heal") &&
fj["completed_turn_self_heal"].is_boolean()) {
cfg.features.completed_turn_self_heal =
fj["completed_turn_self_heal"].get<bool>();
}
}
if (j.contains("skills") && j["skills"].is_object()) {
const auto& sj = j["skills"];
if (sj.contains("disabled") && sj["disabled"].is_array()) {
for (const auto& v : sj["disabled"]) {
if (v.is_string()) cfg.skills.disabled.push_back(v.get<std::string>());
}
}
if (sj.contains("external_dirs") && sj["external_dirs"].is_array()) {
for (const auto& v : sj["external_dirs"]) {
if (v.is_string()) cfg.skills.external_dirs.push_back(v.get<std::string>());
}
}
if (sj.contains("reuse_opencode") && sj["reuse_opencode"].is_boolean()) {
cfg.skills.reuse_opencode = sj["reuse_opencode"].get<bool>();
}
if (sj.contains("idle_days") && sj["idle_days"].is_number_integer()) {
cfg.skills.idle_days = sj["idle_days"].get<int>();
}
}
if (j.contains("memory") && j["memory"].is_object()) {
const auto& mj = j["memory"];
if (mj.contains("enabled") && mj["enabled"].is_boolean())
cfg.memory.enabled = mj["enabled"].get<bool>();
if (mj.contains("max_index_bytes") && mj["max_index_bytes"].is_number_integer()) {
long long v = mj["max_index_bytes"].get<long long>();
if (v > 0) cfg.memory.max_index_bytes = static_cast<std::size_t>(v);
}
}
if (j.contains("project_instructions") && j["project_instructions"].is_object()) {
const auto& pj = j["project_instructions"];
if (pj.contains("enabled") && pj["enabled"].is_boolean())
cfg.project_instructions.enabled = pj["enabled"].get<bool>();
if (pj.contains("max_depth") && pj["max_depth"].is_number_integer()) {
int v = pj["max_depth"].get<int>();
if (v > 0) cfg.project_instructions.max_depth = v;
}
if (pj.contains("max_bytes") && pj["max_bytes"].is_number_integer()) {
long long v = pj["max_bytes"].get<long long>();
if (v > 0) cfg.project_instructions.max_bytes = static_cast<std::size_t>(v);
}
if (pj.contains("max_total_bytes") && pj["max_total_bytes"].is_number_integer()) {
long long v = pj["max_total_bytes"].get<long long>();
if (v > 0) cfg.project_instructions.max_total_bytes = static_cast<std::size_t>(v);
}
if (pj.contains("filenames") && pj["filenames"].is_array()) {
std::vector<std::string> fns;
for (const auto& v : pj["filenames"]) {
if (v.is_string()) {
std::string s = v.get<std::string>();
if (!s.empty()) fns.push_back(std::move(s));
}
}
// Empty array -> keep the struct's default list so
// AGENT.md / CLAUDE.md still work out of the box.
if (!fns.empty()) cfg.project_instructions.filenames = std::move(fns);
}
if (pj.contains("read_claude_md") && pj["read_claude_md"].is_boolean())
cfg.project_instructions.read_claude_md = pj["read_claude_md"].get<bool>();
}
if (j.contains("custom_instructions") && j["custom_instructions"].is_object()) {
const auto& cj = j["custom_instructions"];
if (cj.contains("text") && cj["text"].is_string()) {
cfg.custom_instructions.set_text(cj["text"].get<std::string>());
}
}
if (j.contains("connectors")) {
load_connectors_lenient(j["connectors"], cfg.connectors);
}
if (j.contains("daemon") && j["daemon"].is_object()) {
const auto& dj = j["daemon"];
if (dj.contains("auto_start_on_double_click") && dj["auto_start_on_double_click"].is_boolean())
cfg.daemon.auto_start_on_double_click = dj["auto_start_on_double_click"].get<bool>();
if (dj.contains("service_name") && dj["service_name"].is_string())
cfg.daemon.service_name = dj["service_name"].get<std::string>();
if (dj.contains("heartbeat_interval_ms") && dj["heartbeat_interval_ms"].is_number_integer())
cfg.daemon.heartbeat_interval_ms = dj["heartbeat_interval_ms"].get<int>();
if (dj.contains("heartbeat_timeout_ms") && dj["heartbeat_timeout_ms"].is_number_integer())
cfg.daemon.heartbeat_timeout_ms = dj["heartbeat_timeout_ms"].get<int>();
}
if (j.contains("web") && j["web"].is_object()) {
const auto& wj = j["web"];
const bool remote_enabled_explicit =
wj.contains("remote_enabled") &&
wj["remote_enabled"].is_boolean();
if (wj.contains("enabled") && wj["enabled"].is_boolean())
cfg.web.enabled = wj["enabled"].get<bool>();
if (wj.contains("bind") && wj["bind"].is_string())
cfg.web.bind = wj["bind"].get<std::string>();
if (wj.contains("port") && wj["port"].is_number_integer())
cfg.web.port = wj["port"].get<int>();
if (remote_enabled_explicit)
cfg.web.remote_enabled = wj["remote_enabled"].get<bool>();
if (wj.contains("remote_port") && wj["remote_port"].is_number_integer())
cfg.web.remote_port = wj["remote_port"].get<int>();
// Legacy remote-Web mode used a non-loopback daemon bind as
// the persisted flag. Migrate intent only when the new flag
// is absent, then keep the daemon canonical and local.
if (!cfg.web.bind.empty()) {
if (!web_bind_is_loopback(cfg.web.bind) &&
!remote_enabled_explicit) {
cfg.web.remote_enabled = true;
}
// All accepted legacy loopback aliases and external binds
// converge on the one daemon runtime address.
cfg.web.bind = "127.0.0.1";
}
// static_dir is intentionally optional. null/missing -> embedded assets;
// string -> filesystem path. Empty string is treated the same as null.
if (wj.contains("static_dir") && wj["static_dir"].is_string())
cfg.web.static_dir = wj["static_dir"].get<std::string>();
}
if (j.contains("web_ui")) {
if (!j["web_ui"].is_object()) {
LOG_WARN("[config] 'web_ui' must be an object, ignoring");
} else {
const auto& uij = j["web_ui"];
if (uij.contains("theme")) {
if (uij["theme"].is_string() &&
is_valid_web_ui_theme(uij["theme"].get<std::string>())) {
cfg.web_ui.theme = uij["theme"].get<std::string>();
} else {
LOG_WARN("[config] invalid 'web_ui.theme', using 'system'");
}
}
if (uij.contains("color_theme")) {
if (uij["color_theme"].is_string() &&
is_valid_web_ui_color_theme(
uij["color_theme"].get<std::string>())) {
cfg.web_ui.color_theme =
uij["color_theme"].get<std::string>();
} else {
LOG_WARN("[config] invalid 'web_ui.color_theme', using 'blue'");
}
}
if (uij.contains("font_size")) {
if (uij["font_size"].is_string() &&
is_valid_web_ui_font_size(
uij["font_size"].get<std::string>())) {
cfg.web_ui.font_size =
uij["font_size"].get<std::string>();
} else {
LOG_WARN("[config] invalid 'web_ui.font_size', using 'medium'");
}
}
}
}
if (j.contains("models_dev") && j["models_dev"].is_object()) {
const auto& mj = j["models_dev"];
if (mj.contains("allow_network") && mj["allow_network"].is_boolean())
cfg.models_dev.allow_network = mj["allow_network"].get<bool>();