Repository navigation
Expand file tree
/
Copy pathserver.cppm
More file actions
2183 lines (2092 loc) · 111 KB
/
Copy pathserver.cppm
File metadata and controls
2183 lines (2092 loc) · 111 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
// The session: one editor window's backend. It holds the mcpp it found, the
// projects of the window's folders, the jobs, and the watchers, and answers
// the methods of protocol/protocol.schema.json.
//
// THE ADAPTER DECIDES NOTHING. Which argv a build runs, how much confirmation a
// clean needs, what a cache panel shows, what a setting may hold, which
// commands an editor offers and what a test record means: answered here, so VS
// Code, CLion and Neovim behave alike and an agent reading the backend's log
// sees the same reasons a person sees in the editor.
//
// The editors (the protocol's `editor`): vscode (mcpp-vscode), jetbrains
// (mcpp-clion: the IntelliJ platform's id), nvim (mcpp-nvim), cli (an agent).
export module mcppide.server;
import std;
import nlohmann.json;
import mcppide.rpc;
import mcppide.mcpp;
import mcppide.jobs;
import mcppide.projects;
import mcppide.views;
import mcppide.policy;
import mcppide.settings;
import mcppide.i18n;
import mcppide.documents;
import mcppide.spec;
import mcppide.languageservice;
import mcppide.scan;
import mcpplibs.mtest.manifest;
import mcppide.testing;
import mcppide.teststore;
import mcpplibs.os;
export namespace mcppide::server {
using Json = nlohmann::json;
inline constexpr std::string_view kVersion = "1.4.0";
// THE SERIES (mcpp design 2026-11-07, D15): `X.Y` of `X.Y.Z`, shared by the backend and every editor
// plugin; components of one series work together. A plugin refuses a backend of another series,
// naming both versions. The backend is always `X.Y.0`: the VS Code and CLion packages carry it, so a
// change of the backend is a change of every package, and it begins a series (1.3.0). `Z` is an
// editor plugin's own patch.
inline constexpr std::string_view kSeries = "1.4";
static_assert(kVersion.starts_with(kSeries) && kVersion.size() == kSeries.size() + 2 && kVersion.ends_with(".0"));
inline constexpr int kProtocol = 2;
// The methods `install` registers, for the protocol schema's test: a method
// here and not in protocol/protocol.schema.json (or the other way) fails it. The session is an LSP
// server (protocol 2, design 2026-10-30 part 2 §8): LSP's own methods, and mcpp-ide's under
// `mcpp-ide/`.
inline constexpr std::array<std::string_view, 55> kMethods = {
"initialize", "shutdown", "exit", "textDocument/completion", "textDocument/hover", "textDocument/definition",
"textDocument/documentSymbol", "mcpp-ide/settings/update", "mcpp-ide/settings/registry",
"mcpp-ide/settings/preset", "mcpp-ide/i18n/bundle", "mcpp-ide/selfCheck", "mcpp-ide/commands/list",
"mcpp-ide/menu/quick", "mcpp-ide/languageService/status", "mcpp-ide/projects/list", "mcpp-ide/projects/forFile",
"mcpp-ide/project/summary", "mcpp-ide/project/new", "mcpp-ide/result/last", "mcpp-ide/job/start",
"mcpp-ide/job/cancel", "mcpp-ide/job/list", "mcpp-ide/run/launch", "mcpp-ide/debug/configuration",
"mcpp-ide/test/list", "mcpp-ide/library/search", "mcpp-ide/library/indexes", "mcpp-ide/library/add",
"mcpp-ide/library/updateIndex", "mcpp-ide/toolchains/list", "mcpp-ide/toolchains/install",
"mcpp-ide/toolchains/setDefault", "mcpp-ide/targets/list", "mcpp-ide/cache/inventory", "mcpp-ide/cache/plan",
"mcpp-ide/cache/apply", "mcpp-ide/graph/packages", "mcpp-ide/graph/modules", "mcpp-ide/pack/formats",
"mcpp-ide/pack/start", "mcpp-ide/manifest/check", "mcpp-ide/mcpp/exec", "mcpp-ide/mcpp/availability", "mcpp-ide/project/files",
"mcpp-ide/languageService/exec", "mcpp-ide/project/mcpp", "mcpp-ide/project/refresh",
"mcpp-ide/capabilities/explain", "mcpp-ide/report/collect", "mcpp-ide/source/entries", "mcpp-ide/test/cases",
"mcpp-ide/test/runCases", "mcpp-ide/test/history", "mcpp-ide/test/insights"};
// The notifications the backend reads.
inline constexpr std::array<std::string_view, 5> kReceived = {
"initialized", "textDocument/didOpen", "textDocument/didChange", "textDocument/didClose", "$/cancelRequest"};
// The notifications the backend sends.
inline constexpr std::array<std::string_view, 19> kNotifications = {
"textDocument/publishDiagnostics", "window/showMessage", "mcpp-ide/job/started", "mcpp-ide/job/output",
"mcpp-ide/job/plan", "mcpp-ide/job/progress", "mcpp-ide/job/diagnostic", "mcpp-ide/job/artifact",
"mcpp-ide/job/record", "mcpp-ide/job/finished", "mcpp-ide/test/result", "mcpp-ide/test/summary",
"mcpp-ide/result/changed", "mcpp-ide/manifest/changed", "mcpp-ide/manifest/diagnostics",
"mcpp-ide/project/mcppChanged", "mcpp-ide/languageService/changed", "mcpp-ide/test/caseResult",
"mcpp-ide/test/caseEvent"};
class Session {
public:
explicit Session(rpc::Server& server);
~Session();
void install();
// The self-check report (also `mcpp-ide self-check`).
Json self_check();
private:
using Result = std::expected<Json, rpc::Error>;
Result initialize(const Json& p);
Result update_settings(const Json& p);
// `after` runs when the job has ended, before the editors are told (jobs::Request::after).
Result job_start(const Json& p, std::function<void(std::string_view, const Json&)> after = {});
Result run_launch(const Json& p, const rpc::Context& ctx);
Result debug_configuration(const Json& p, const rpc::Context& ctx);
Result library_search(const Json& p);
Result cache_plan(const Json& p);
Result cache_apply(const Json& p);
Result graph(const Json& p, bool modules);
Result project_summary(const Json& p);
Result mcpp_exec(const Json& p);
Result mcpp_availability();
Result language_service_exec(const Json& p);
Result project_new(const Json& p);
Result manifest_check(const Json& p);
Result language_service(const Json& p);
Result targets(const Json& p);
Result commands(const Json& p);
Json server_actions();
Result quick_menu(const Json& p);
Result test_list(const Json& p);
Result source_entries(const Json& p);
Result test_cases(const Json& p);
Result test_run_cases(const Json& p);
Result test_history(const Json& p);
Result test_insights(const Json& p);
// The programs of `mcpp test --list` (kept per project), and lookups among them.
std::vector<testing::Program> list_programs(const std::filesystem::path& root, const Json& p);
std::vector<testing::Program> programs_of(const std::filesystem::path& root);
std::optional<testing::Program> program_named(const std::filesystem::path& root, std::string_view name);
std::optional<testing::Program> program_of_file(const std::filesystem::path& root, const std::filesystem::path& file);
std::optional<std::vector<testing::Case>> listed_cases(const std::filesystem::path& root, const std::string& test, const Json& p,
const std::vector<testing::Case>& statics);
std::optional<std::vector<std::string>> framework_listing(const std::filesystem::path& root, const std::string& test,
const Json& p, const testing::Framework& f);
// A record of a test job, with the program and part it belongs to, and its cases as the editors
// receive them (design 2026-11-10).
Json test_result_of(const std::filesystem::path& root, const Json& record, Json n);
void protocol_case_results(std::string_view jobId, const std::filesystem::path& root, const std::string& test, const Json& record);
// The store's last runs (kept per project; a run is read once).
std::vector<teststore::Run> store_runs(const std::filesystem::path& root, std::size_t count);
// `mcpp.test.macros` as testing reads it: {"gtest": ["MY_TEST"]}.
Json test_macros() const;
// The packages of a project's plan, from its build database when one was read.
std::vector<std::string> plan_packages(const std::filesystem::path& root, bool read);
Result project_mcpp(const Json& p);
Result project_refresh(const Json& p);
Result capabilities_explain(const Json& p);
Result report_collect(const Json& p);
// The rules layer's switches for the documents, from the settings.
documents::Options document_options() const;
// A document's diagnostics, to the editor.
void publish(const documents::Document& d);
// mcpp's catalogue for version completion, when it was read; asked in the background otherwise.
std::optional<Json> catalogue(const std::filesystem::path& cwd);
// LSP's document methods and notifications.
void install_documents();
// THE PROJECT'S mcpp (design 2026-10-30 part 2 §4.2): asked in the project, once, and asked again
// when its manifest changes, when the editor regains focus, or when a job's envelope names
// another version. Never more than two asked at once.
mcpp::ProjectMcpp probe_of(const std::filesystem::path& root);
Json probe_json(const std::filesystem::path& root, const mcpp::ProjectMcpp& probe) const;
bool has_feature(const std::filesystem::path& root, std::string_view feature);
std::vector<std::string> launch_args(const Json& p, bool stream, bool programArgs);
// A line of the backend's log, at a level (0 error, 1 warning, 2 info, 3 debug): written to
// standard error, which every editor keeps in its log, when mcpp.backend.logLevel lets it
// through, and kept for the IDE report either way (§3.2).
void log(int level, std::string_view text);
std::expected<mcpp::Client::EnvelopeResult, rpc::Error> query(const std::filesystem::path& cwd,
std::vector<std::string> args) const;
std::expected<Json, rpc::Error> build_database(const std::filesystem::path& root);
std::vector<std::string> deny() const;
std::string client_label() const;
std::string t(std::string_view key, const std::vector<std::string>& args = {}) const;
Json setting(std::string_view key) const;
// `--target <t>` for a request: its own `target`, else `mcpp.build.target`; nothing for the host.
std::vector<std::string> target_args(const Json& p) const;
std::filesystem::path any_root(const Json& p) const;
void locate_mcpp();
void on_changed(const std::filesystem::path& root, std::string_view what, const Json& detail);
void on_record(std::string_view jobId, const Json& record);
rpc::Server& rpc_;
mutable std::mutex mutex_;
mcpp::Client client_;
std::optional<mcpp::Located> located_;
std::string mcppError_;
bool mcppMissing_ = false;
Json settings_ = Json::object();
bool trusted_ = true;
mutable std::mutex localeMutex_;
std::string locale_ = "en";
std::string clientName_ = "mcpp-ide";
std::string editor_ = "vscode";
std::vector<std::string> mcpplsCandidates_;
// Whether C++ Modules serves build.mcpp in the editor (it then answers what it answers better).
bool mcpplsServes_ = false;
// The documents the editor keeps open (mcpp.toml, build.mcpp), and the catalogue a dependency
// version is completed from: asked once in the background, the editor told once that it was.
documents::Store documents_;
bool catalogueAsked_ = false;
bool catalogueNoticed_ = false;
// mcppls's actions as its last report named them (null until one was asked), and what the editors
// were last told about it, so that a change is sent once.
Json mcpplsActions_;
std::string mcpplsSeen_;
std::vector<std::filesystem::path> folders_;
std::unique_ptr<jobs::Jobs> jobs_;
std::unique_ptr<projects::Watcher> watcher_;
// `mcpp search` takes a few hundred milliseconds and answers the same
// catalogue for minutes: kept until an index changes or the user asks.
Json searchCache_;
std::chrono::steady_clock::time_point searchAt_{};
std::map<std::filesystem::path, Json> buildDatabases_;
// The project and kind of each job, for the notifications its records become.
std::map<std::string, std::pair<std::filesystem::path, std::string>, std::less<>> jobOf_;
// The whole output of the last test record of each running test job, for a case run to divide
// among its cases when the job ends (test/runCases).
std::map<std::string, std::string, std::less<>> programOutput_;
// The test records of each running test job, whole: a program that implements the test protocol
// reports its cases in them, one record per part of a program of several files (test/runCases).
std::map<std::string, std::vector<Json>, std::less<>> testRecords_;
// The programs of each project as `mcpp test --list` last named them.
std::map<std::filesystem::path, std::vector<testing::Program>> programs_;
// The runs of each project's store already read, by id.
std::map<std::filesystem::path, std::map<std::string, teststore::Run>> storeRuns_;
// The configuration (and platforms) the last plan of each project named.
std::map<std::filesystem::path, Json> plans_;
// What `mcpp pack` accepts, read from its help once per mcpp (SPEC-014: `--pkg-format` names the
// package format since the platforms release; an earlier mcpp knows it as `--format`).
struct PackOptions {
std::filesystem::path program;
std::string pkgFormatFlag = "--format";
bool linkage = false;
};
std::optional<PackOptions> packOptions_;
PackOptions pack_options(const std::filesystem::path& cwd);
std::map<std::filesystem::path, mcpp::ProjectMcpp> probes_;
std::counting_semaphore<2> probeSlots_{2};
// The backend's log level (mcpp.backend.logLevel): what reaches standard error.
std::deque<std::string> recentLog_;
};
} // namespace mcppide::server
namespace mcppide::server {
namespace {
rpc::Error invalid(std::string message) { return rpc::Error{rpc::INVALID_PARAMS, std::move(message)}; }
// A name an editor or the environment spells in the host's rules (`C:\Users\x` on Windows), in the
// generic spelling every name the backend builds, compares and reports uses: `/` between components
// (mcpplibs.os). The backend runs as an ok image, whose names are `/`-separated on every system; a
// `\` left in a name is read as part of a component there, so `C:\a\b` would be one relative name.
std::filesystem::path host_path(std::string_view text) {
if (text.empty()) return {};
namespace fs = mcpplibs::os::fs;
return fs::from_utf8(fs::generic(fs::from_utf8(text)));
}
std::filesystem::path root_of(const Json& p) {
return p.contains("root") && p["root"].is_string() ? host_path(p["root"].get<std::string>()) : std::filesystem::path{};
}
Json project_json(const projects::Project& p) {
return Json{{"root", p.root.generic_string()}, {"workspaceRoot", p.workspaceRoot.generic_string()},
{"name", p.root.filename().string()}, {"isWorkspaceRoot", p.isWorkspaceRoot}};
}
std::vector<std::string> strings_of(const Json& v) {
std::vector<std::string> out;
if (v.is_array()) for (const auto& x : v) if (x.is_string()) out.push_back(x.get<std::string>());
return out;
}
} // namespace
Session::Session(rpc::Server& server) : rpc_(server) {
jobs_ = std::make_unique<jobs::Jobs>(mcpp::Client{}, jobs::Sink{
.narration = [this](std::string_view id, std::string_view text) {
rpc_.notify("mcpp-ide/job/output", Json{{"jobId", id}, {"text", text}});
},
.record = [this](std::string_view id, const Json& record) { on_record(id, record); },
.finished = [this](std::string_view id, const Json& summary) {
Json s = summary;
s["jobId"] = id;
// The envelope's own diagnostics and artifacts, as the adapters consume them.
if (summary.contains("envelope")) {
s["diagnostics"] = mcpp::diagnostics_of(summary["envelope"]);
const auto& env = summary["envelope"];
if (env.is_object() && env.contains("data") && env["data"].is_object() && env["data"].contains("artifacts"))
s["artifacts"] = env["data"]["artifacts"];
// A launch job ends with the program it built, described (`mcpp.launch`).
if (env.is_object() && env.value("kind", "") == "mcpp.launch" && env.contains("data"))
s["launch"] = env["data"];
}
std::filesystem::path root;
{
std::lock_guard lock(mutex_);
if (auto it = jobOf_.find(id); it != jobOf_.end()) {
s["root"] = it->second.first.generic_string();
s["kind"] = it->second.second;
root = it->second.first;
jobOf_.erase(it);
}
if (auto it = programOutput_.find(id); it != programOutput_.end()) programOutput_.erase(it);
if (auto it = testRecords_.find(id); it != testRecords_.end()) testRecords_.erase(it);
}
rpc_.notify("mcpp-ide/job/finished", s);
// Every envelope names the mcpp that wrote it: another version than the one probed (a
// `xlings use`, a pin changed) is asked again, and the editor is told (§4.2).
const auto& env = summary.contains("envelope") ? summary["envelope"] : Json(nullptr);
if (!root.empty() && env.is_object() && env.contains("mcpp") && env["mcpp"].is_object()) {
const auto seen = env["mcpp"].value("version", "");
bool changed = false;
{
std::lock_guard lock(mutex_);
if (auto it = probes_.find(root); it != probes_.end() && !seen.empty() && it->second.version != seen) {
probes_.erase(it);
changed = true;
}
}
if (changed) rpc_.notify("mcpp-ide/project/mcppChanged", Json{{"root", root.generic_string()}, {"version", seen}});
}
},
.started = [this](std::string_view id, const Json& started) {
{
std::lock_guard lock(mutex_);
jobOf_[std::string(id)] = {std::filesystem::path(started.value("root", "")), started.value("kind", "")};
}
Json s = started;
s["jobId"] = id;
rpc_.notify("mcpp-ide/job/started", s);
},
});
watcher_ = std::make_unique<projects::Watcher>(
[this](const std::filesystem::path& root, std::string_view what, const Json& detail) { on_changed(root, what, detail); });
}
Session::~Session() {
watcher_.reset();
jobs_.reset();
}
// The locale has a lock of its own: a message is often composed while `mutex_` is held.
std::string Session::t(std::string_view key, const std::vector<std::string>& args) const {
std::string locale;
{
std::lock_guard lock(localeMutex_);
locale = locale_;
}
return i18n::translate(key, locale, args);
}
Json Session::setting(std::string_view key) const {
std::lock_guard lock(mutex_);
if (auto it = settings_.find(std::string(key)); it != settings_.end()) return *it;
if (auto* s = settings::find(key)) return settings::default_of(*s);
return nullptr;
}
std::vector<std::string> Session::target_args(const Json& p) const {
std::string target = p.contains("target") && p["target"].is_string() ? p["target"].get<std::string>() : std::string{};
if (!p.contains("target")) {
const auto chosen = setting("mcpp.build.target");
if (chosen.is_string()) target = chosen.get<std::string>();
}
if (target.empty()) return {};
return {"--target", target};
}
std::filesystem::path Session::any_root(const Json& p) const {
if (auto r = root_of(p); !r.empty()) return r;
std::lock_guard lock(mutex_);
return folders_.empty() ? std::filesystem::current_path() : folders_.front();
}
std::vector<std::string> Session::deny() const {
std::lock_guard lock(mutex_);
if (trusted_) return {};
return strings_of(settings_.value("mcpp.trust.denyEffects", Json::array()));
}
std::string Session::client_label() const {
std::lock_guard lock(mutex_);
return clientName_;
}
void Session::locate_mcpp() {
std::string configured;
{
std::lock_guard lock(mutex_);
configured = settings_.value("mcpp.path", "");
}
auto located = mcpp::locate(configured);
std::lock_guard lock(mutex_);
if (!located) {
mcppError_ = located.error();
// An invalid explicit path is a setting error when another local mcpp exists.
mcppMissing_ = configured.empty() || !mcpp::locate("").has_value();
located_.reset();
client_ = mcpp::Client{};
jobs_->set_client(client_);
return;
}
auto protocol = mcpp::handshake(located->program);
mcppMissing_ = false;
if (!protocol) {
mcppError_ = protocol.error();
located_.reset();
client_ = mcpp::Client{};
} else {
mcppError_.clear();
located_ = *located;
client_ = mcpp::Client(located->program, *protocol);
}
probes_.clear();
jobs_->set_client(client_);
if (located && protocol)
std::println(std::cerr, "[info] mcpp {} at {} ({})", protocol->version, located->program.generic_string(), located->source);
}
void Session::on_changed(const std::filesystem::path& root, std::string_view what, const Json& detail) {
{
std::lock_guard lock(mutex_);
buildDatabases_.erase(root);
if (what != "result") probes_.erase(root); // a manifest may state another mcpp floor or pin
if (what != "result") programs_.erase(root); // and other tests
}
if (what == "result") {
rpc_.notify("mcpp-ide/result/changed", Json{{"root", root.generic_string()}, {"result", detail}});
return;
}
rpc_.notify("mcpp-ide/manifest/changed", Json{{"root", root.generic_string()}});
// The manifest's problems, from mcpp, located (mcpp docs/50 §2).
auto checked = manifest_check(Json{{"root", root.generic_string()}});
if (checked) rpc_.notify("mcpp-ide/manifest/diagnostics", *checked);
}
// A record of a job's stream becomes the notification its meaning names: the plan (with the
// platforms mcpp reports, kept per project for the panels), progress, a located diagnostic, a test's
// result, the tests' summary. What has no meaning here goes out as it came (`job/record`).
void Session::on_record(std::string_view jobId, const Json& record) {
auto n = views::stream_record(record);
std::string root;
{
std::lock_guard lock(mutex_);
if (auto it = jobOf_.find(jobId); it != jobOf_.end()) root = it->second.first.generic_string();
}
n["jobId"] = jobId;
n["root"] = root;
const auto type = n.value("type", "other");
if (type == "plan") {
{
std::lock_guard lock(mutex_);
plans_[std::filesystem::path(root)] = n;
}
rpc_.notify("mcpp-ide/job/plan", n);
} else if (type == "progress") {
rpc_.notify("mcpp-ide/job/progress", n);
} else if (type == "diagnostic") {
rpc_.notify("mcpp-ide/job/diagnostic", n);
} else if (type == "artifact") {
rpc_.notify("mcpp-ide/job/artifact", n);
} else if (type == "test") {
{
std::lock_guard lock(mutex_);
programOutput_[std::string(jobId)] += record.value("compile_output", "") + record.value("run_output", "");
testRecords_[std::string(jobId)].push_back(record);
}
rpc_.notify("mcpp-ide/test/result", test_result_of(std::filesystem::path(root), record, std::move(n)));
} else if (type == "case") {
// A case as it begins or ends while its program runs (mcpp#917, `test-case-stream`).
const auto& c = n["case"];
Json event = c.value("event", "") == "end" ? testing::protocol_case(c) : Json{{"case", c.value("id", "")}};
const auto part = c.value("test", "");
std::vector<testing::Program> programs;
{
std::lock_guard lock(mutex_);
if (auto it = programs_.find(std::filesystem::path(root)); it != programs_.end()) programs = it->second;
}
event["jobId"] = jobId;
event["root"] = root;
event["member"] = c.value("member", "");
event["program"] = testing::owner_of(part, c.value("part_of", ""), programs);
event["part"] = part;
event["event"] = c.value("event", "");
if (c.contains("t_ms") && c["t_ms"].is_number()) event["tMs"] = c["t_ms"];
rpc_.notify("mcpp-ide/test/caseEvent", event);
} else if (type == "summary") {
rpc_.notify("mcpp-ide/test/summary", n);
} else if (!(record.is_object() && record.contains("schemaVersion") && record.value("kind", "") != "mcpp.event")) {
// The envelope that closes a stream reaches the adapter in `job/finished`.
rpc_.notify("mcpp-ide/job/record", n);
}
}
std::expected<mcpp::Client::EnvelopeResult, rpc::Error> Session::query(const std::filesystem::path& cwd,
std::vector<std::string> args) const {
mcpp::Client client;
{
std::lock_guard lock(mutex_);
client = client_;
}
if (!client.ready()) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, mcppError_.empty() ? "mcpp is not available" : mcppError_});
mcpp::RunOptions o;
o.cwd = cwd;
o.args = std::move(args);
o.deny = deny();
o.client = client_label();
auto r = client.envelope(o);
if (!r) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, r.error()});
return *r;
}
// One command of mcpp, as an editor's own parsers read it (mcpp-vscode's views): what it printed and
// how it ended. The backend runs it as it runs every command -- the mcpp it located, the session's
// client, the effects an untrusted workspace denies -- bounded in time and in output.
std::expected<Json, rpc::Error> Session::mcpp_exec(const Json& p) {
mcpp::Client client;
{
std::lock_guard lock(mutex_);
client = client_;
}
if (!client.ready()) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, mcppError_.empty() ? "mcpp is not available" : mcppError_});
if (!p.contains("args") || !p["args"].is_array()) return std::unexpected(rpc::Error{rpc::INVALID_PARAMS, "args: an array of strings"});
mcpp::RunOptions o;
for (const auto& a : p["args"]) {
if (!a.is_string()) return std::unexpected(rpc::Error{rpc::INVALID_PARAMS, "args: an array of strings"});
o.args.push_back(a.get<std::string>());
}
o.cwd = p.contains("cwd") && p["cwd"].is_string() ? host_path(p["cwd"].get<std::string>()) : std::filesystem::path{};
o.deny = deny();
o.client = client_label();
const auto timeoutMs = p.contains("timeoutMs") && p["timeoutMs"].is_number_integer() && p["timeoutMs"].get<std::int64_t>() > 0
? p["timeoutMs"].get<std::int64_t>() : std::int64_t{24} * 3600 * 1000;
const auto limit = p.contains("maxOutputBytes") && p["maxOutputBytes"].is_number_integer() && p["maxOutputBytes"].get<std::int64_t>() > 0
? static_cast<std::size_t>(p["maxOutputBytes"].get<std::int64_t>()) : std::size_t{16} << 20;
auto r = client.exec(o, std::chrono::milliseconds(timeoutMs), limit);
if (!r) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, r.error()});
return Json{{"exitCode", r->exitCode}, {"stdout", r->out}, {"stderr", r->err}, {"timedOut", r->timedOut},
{"truncated", r->truncated}};
}
// One command of mcppls (`query module`, for the module graph), run as the command languageService/status
// found: a payload's runner and image, or a program. Bounded as mcpp/exec is.
std::expected<Json, rpc::Error> Session::language_service_exec(const Json& p) {
if (!p.contains("args") || !p["args"].is_array()) return std::unexpected(rpc::Error{rpc::INVALID_PARAMS, "args: an array of strings"});
std::vector<std::string> candidates;
{
std::lock_guard lock(mutex_);
candidates = mcpplsCandidates_;
}
const auto found = languageservice::probe(candidates);
if (found.command.empty())
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("mcppls was not found: C++ files have no completion, navigation or diagnostics from mcpp's build. Install the C++ Modules language server ({0} or later).",
{std::string(languageservice::kRequired)})});
mcpplibs::os::process::spawn_options o;
o.program = found.command.front();
for (std::size_t i = 1; i < found.command.size(); ++i) o.args.push_back(found.command[i].string());
for (const auto& a : p["args"]) {
if (!a.is_string()) return std::unexpected(rpc::Error{rpc::INVALID_PARAMS, "args: an array of strings"});
o.args.push_back(a.get<std::string>());
}
o.in = mcpplibs::os::process::stdio::null;
if (p.contains("cwd") && p["cwd"].is_string()) o.cwd = p["cwd"].get<std::string>();
mcpplibs::os::process::bounds limits;
limits.hard = std::chrono::milliseconds(p.contains("timeoutMs") && p["timeoutMs"].is_number_integer() && p["timeoutMs"].get<std::int64_t>() > 0
? p["timeoutMs"].get<std::int64_t>() : std::int64_t{120000});
const auto limit = p.contains("maxOutputBytes") && p["maxOutputBytes"].is_number_integer() && p["maxOutputBytes"].get<std::int64_t>() > 0
? static_cast<std::size_t>(p["maxOutputBytes"].get<std::int64_t>()) : std::size_t{16} << 20;
limits.out_limit = limit;
limits.err_limit = limit;
auto r = mcpplibs::os::process::run(o, limits);
if (!r) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, r.error().message()});
return Json{{"exitCode", r->status.shell_code()}, {"stdout", r->out}, {"stderr", r->err}, {"timedOut", r->timed_out},
{"truncated", r->out_truncated || r->err_truncated}};
}
std::expected<Json, rpc::Error> Session::build_database(const std::filesystem::path& root) {
{
std::lock_guard lock(mutex_);
if (auto it = buildDatabases_.find(root); it != buildDatabases_.end()) return it->second;
}
auto r = query(root, {"emit", "build-database", "--format", "json"});
if (!r) return std::unexpected(r.error());
if (r->exitCode != 0) {
const auto diagnostics = mcpp::diagnostics_of(r->envelope);
auto message = t("mcpp {0} failed with exit code {1}", {"emit build-database", std::to_string(r->exitCode)});
if (!r->narration.empty()) message += "\n" + r->narration;
else if (!diagnostics.empty()) message += "\n" + diagnostics.front().value("message", "");
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, std::move(message),
Json{{"exitCode", r->exitCode}, {"diagnostics", diagnostics}}});
}
if (r->envelope.is_null())
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("mcpp emit build-database printed no document")});
std::lock_guard lock(mutex_);
buildDatabases_[root] = r->envelope;
return r->envelope;
}
std::expected<Json, rpc::Error> Session::mcpp_availability() {
bool retry;
{
std::lock_guard lock(mutex_);
retry = !client_.ready();
}
if (retry) locate_mcpp();
std::lock_guard lock(mutex_);
return Json{{"available", client_.ready()}, {"missing", mcppMissing_}};
}
Json Session::self_check() {
Json mcppPart = nullptr;
std::string error;
{
std::lock_guard lock(mutex_);
error = mcppError_;
if (client_.ready()) {
const auto& p = client_.protocol();
mcppPart = Json{{"path", client_.program().generic_string()},
{"source", located_ ? located_->source : ""},
{"version", p.version},
{"contract", p.contract},
{"contractFloor", mcpp::kContractFloor},
{"kinds", p.kinds}};
}
}
Json checks = Json::array();
auto add = [&](std::string id, std::string status, std::string message) {
checks.push_back(Json{{"id", id}, {"status", status}, {"message", message}});
};
if (mcppPart.is_null()) add("mcpp", "error", error.empty() ? t("mcpp was not found") : error);
else {
add("mcpp", "ok", t("mcpp {0} at {1}", {mcppPart["version"].get<std::string>(), mcppPart["path"].get<std::string>()}));
if (!mcppPart["contract"].get<bool>())
add("contract", "warning",
t("mcpp {0} predates the control contract ({1}): builds run without events, records or launch descriptors",
{mcppPart["version"].get<std::string>(), std::string(mcpp::kContractFloor)}));
else add("contract", "ok", t("the control contract is available"));
}
std::vector<std::string> candidates;
{
std::lock_guard lock(mutex_);
candidates = mcpplsCandidates_;
}
auto ls = language_service(Json{{"candidates", candidates}});
if (ls) add("languageService", (*ls)["state"] == "ok" ? "ok" : (*ls)["state"] == "missing" ? "error" : "warning",
(*ls)["message"].get<std::string>());
if (auto xlings = mcpplibs::os::env::find_executable("xlings")) add("xlings", "ok", t("xlings at {0}", {xlings->generic_string()}));
else add("xlings", "info", t("xlings is not on PATH; mcpp uses the one it bundles"));
{
std::lock_guard lock(mutex_);
add("trust", trusted_ ? "ok" : "info",
trusted_ ? t("the workspace is trusted") : t("the workspace is not trusted: mcpp runs with effects denied"));
}
return Json{{"backend", Json{{"version", kVersion}, {"protocol", kProtocol}}},
{"mcpp", mcppPart},
{"languageService", ls ? *ls : Json(nullptr)},
{"checks", checks}};
}
std::expected<Json, rpc::Error> Session::initialize(const Json& p) {
// LSP's `initialize`: the client and the workspace in LSP's fields, what mcpp-ide asks in
// `initializationOptions` (the editor, trust, the settings, mcppls's candidates).
const Json options = p.contains("initializationOptions") && p["initializationOptions"].is_object() ? p["initializationOptions"]
: Json::object();
{
std::lock_guard lock(mutex_);
if (p.contains("clientInfo") && p["clientInfo"].is_object()) {
const auto name = p["clientInfo"].value("name", "editor");
const auto version = p["clientInfo"].value("version", "");
clientName_ = std::format("mcpp-ide/{} ({}{}{})", kVersion, name, version.empty() ? "" : " ", version);
}
editor_ = options.value("editor", "vscode");
{
std::lock_guard localeLock(localeMutex_);
locale_ = i18n::normalize_locale(options.value("locale", p.value("locale", "en")));
}
trusted_ = options.value("trusted", true);
mcpplsServes_ = options.value("mcpplsServes", false);
settings_ = settings::resolve(options.contains("settings") ? options["settings"] : Json::object())["values"];
folders_.clear();
if (p.contains("workspaceFolders") && p["workspaceFolders"].is_array())
for (const auto& f : p["workspaceFolders"])
if (f.is_object() && f.contains("uri") && f["uri"].is_string())
if (auto path = documents::path_of(f["uri"].get<std::string>()); !path.empty()) folders_.push_back(path);
if (folders_.empty() && p.contains("rootUri") && p["rootUri"].is_string())
if (auto path = documents::path_of(p["rootUri"].get<std::string>()); !path.empty()) folders_.push_back(path);
if (options.contains("languageService") && options["languageService"].is_object())
mcpplsCandidates_ = strings_of(options["languageService"].value("candidates", Json::array()));
}
locate_mcpp();
Json found = Json::array();
for (const auto& folder : folders_)
for (const auto& proj : projects::discover(folder)) {
watcher_->watch(proj.root);
found.push_back(project_json(proj));
}
rpc_.set_initialized(true);
auto check = self_check();
return Json{{"capabilities", documents::server_capabilities()},
{"serverInfo", Json{{"name", "mcpp-ide"}, {"version", kVersion}}},
{"protocol", kProtocol},
{"series", kSeries},
{"mcpp", check["mcpp"]},
{"languageService", check["languageService"]},
{"checks", check["checks"]},
{"projects", found},
{"features", Json::array({"jobs", "results", "launch", "debug", "tests", "library", "toolchains",
"targets", "platforms", "cache", "graphs", "pack", "settings", "i18n",
"commands", "manifest", "toml", "buildscript", "languageService"})}};
}
std::expected<Json, rpc::Error> Session::update_settings(const Json& p) {
Json resolved = settings::resolve(p.contains("settings") ? p["settings"] : Json::object());
std::string before;
{
std::lock_guard lock(mutex_);
before = settings_.value("mcpp.path", "");
settings_ = resolved["values"];
if (p.contains("trusted")) trusted_ = p["trusted"].get<bool>();
if (p.contains("mcpplsServes") && p["mcpplsServes"].is_boolean()) mcpplsServes_ = p["mcpplsServes"].get<bool>();
if (p.contains("locale")) {
std::lock_guard localeLock(localeMutex_);
locale_ = i18n::normalize_locale(p["locale"].get<std::string>());
}
}
if (before != resolved["values"].value("mcpp.path", "")) locate_mcpp();
// A switch or a severity may have changed what each open document earns.
for (const auto& d : documents_.all()) publish(d);
return resolved;
}
std::expected<Json, rpc::Error> Session::job_start(const Json& p, std::function<void(std::string_view, const Json&)> after) {
const auto kindName = p.value("kind", "");
auto kind = jobs::kind_from(kindName);
if (!kind) return std::unexpected(invalid(std::format("unknown job kind {}", kindName)));
const auto root = root_of(p);
if (root.empty()) return std::unexpected(invalid("a job names its project's root"));
{
std::lock_guard lock(mutex_);
if (!client_.ready()) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, mcppError_});
}
jobs::Request r;
r.kind = *kind;
r.root = root;
r.deny = deny();
r.client = client_label();
r.supersede = p.value("supersede", false);
r.color = p.value("color", true);
const auto extra = strings_of(p.value("args", Json::array()));
const auto profile = p.value("profile", setting("mcpp.build.profile").is_string() ? setting("mcpp.build.profile").get<std::string>() : "dev");
const bool release = profile == "release";
const auto target = target_args(p);
auto append = [&](const std::vector<std::string>& v) { r.args.insert(r.args.end(), v.begin(), v.end()); };
switch (*kind) {
case jobs::Kind::build:
r.args = {"build", "--message-format", "json"};
if (release) r.args.push_back("--release");
append(target);
append(strings_of(setting("mcpp.task.buildArgs")));
r.mode = jobs::Mode::ndjson;
break;
case jobs::Kind::test:
// The programs, so that each part's record is attributed to its program (design 2026-11-10).
(void)programs_of(root);
r.args = {"test", "--message-format", "json"};
if (release) r.args.push_back("--release");
append(target);
if (p.contains("filter") && p["filter"].is_string() && !p["filter"].get<std::string>().empty())
r.args.push_back(p["filter"].get<std::string>());
append(strings_of(setting("mcpp.task.testArgs")));
r.mode = jobs::Mode::ndjson;
break;
case jobs::Kind::pack: {
const auto options = pack_options(root);
r.args = {"pack"};
if (auto f = p.value("pkgFormat", ""); !f.empty()) { r.args.push_back(options.pkgFormatFlag); r.args.push_back(f); }
if (auto m = p.value("mode", ""); !m.empty()) { r.args.push_back("--mode"); r.args.push_back(m); }
if (auto l = p.value("linkage", ""); !l.empty() && options.linkage) { r.args.push_back("--linkage"); r.args.push_back(l); }
if (release) r.args.push_back("--release");
append(target);
r.args.push_back("--message-format");
r.args.push_back("json");
r.mode = jobs::Mode::envelope;
break;
}
case jobs::Kind::clean:
return std::unexpected(invalid("a clean goes through cache/apply, which holds its confirmation"));
case jobs::Kind::toolchain: {
const auto spec = p.value("spec", "");
if (spec.empty()) return std::unexpected(invalid("a toolchain job names a spec"));
r.args = {"toolchain", "install", spec};
if (p.contains("target") && p["target"].is_string() && !p["target"].get<std::string>().empty()) {
r.args.push_back("--target");
r.args.push_back(p["target"].get<std::string>());
}
break;
}
case jobs::Kind::add: {
const auto dep = p.value("dependency", "");
if (dep.empty()) return std::unexpected(invalid("`mcpp add` names a dependency"));
r.args = {"add", dep};
break;
}
case jobs::Kind::launch: {
// A Run's or a Debug's build, reported as it goes: mcpp's narration, and with
// `launch-stream` its events, then the launch in `job/finished` (design 2026-11-07 §4.9).
const bool stream = p.value("test", "").empty() && has_feature(root, "launch-stream");
r.args = launch_args(p, stream, true);
r.mode = stream ? jobs::Mode::ndjson : jobs::Mode::envelope;
break;
}
case jobs::Kind::command:
r.args = {};
break;
}
if (*kind != jobs::Kind::launch)
for (const auto& a : extra) r.args.push_back(a);
if (r.args.empty()) return std::unexpected(invalid("a command job names its arguments"));
r.after = std::move(after);
const auto id = jobs_->submit(std::move(r));
watcher_->watch(root);
return Json{{"jobId", id}};
}
// The mcpp command that builds a program and describes its launch: `mcpp run --print-launch`, or
// `mcpp test <name> --print-launch` for a test (mcpp's `test-launch`), with its framework's filter
// after `--` when cases are asked for. `stream` asks a run for the build's events before the
// envelope (mcpp's `launch-stream`), and `programArgs` are the program's own arguments, after `--`.
std::vector<std::string> Session::launch_args(const Json& p, bool stream, bool programArgs) {
const auto test = p.value("test", "");
std::vector<std::string> args{test.empty() ? "run" : "test", "--print-launch"};
if (stream && test.empty()) {
args.push_back("--message-format");
args.push_back("json");
}
const auto profile = p.value("profile", setting("mcpp.build.profile").is_string() ? setting("mcpp.build.profile").get<std::string>() : "dev");
if (profile == "release") args.push_back("--release");
else if (!profile.empty() && profile != "dev") {
args.push_back("--profile");
args.push_back(profile);
}
for (const auto& a : target_args(p)) args.push_back(a);
if (auto runner = p.value("runner", ""); !runner.empty()) {
args.push_back("--runner");
args.push_back(runner);
}
if (!test.empty()) {
args.push_back(test);
if (const auto* f = testing::framework(p.value("framework", "")))
if (const auto filter = testing::filter_args(*f, strings_of(p.value("cases", Json::array()))); !filter.empty()) {
args.push_back("--");
for (const auto& a : filter) args.push_back(a);
}
} else {
if (auto bin = p.value("bin", ""); !bin.empty()) args.push_back(bin);
if (const auto program = strings_of(p.value("args", Json::array())); programArgs && !program.empty()) {
args.push_back("--");
args.insert(args.end(), program.begin(), program.end());
}
}
return args;
}
std::expected<Json, rpc::Error> Session::run_launch(const Json& p, const rpc::Context& ctx) {
const auto root = root_of(p);
if (root.empty()) return std::unexpected(invalid("run/launch names its project's root"));
auto r = query(root, launch_args(p, false, false));
if (!r) return std::unexpected(r.error());
if (ctx.cancelled()) return std::unexpected(rpc::Error{rpc::REQUEST_CANCELLED, "cancelled"});
if (r->exitCode != 0 || !r->envelope.is_object() || r->envelope.value("kind", "") != "mcpp.launch")
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("the program could not be built"),
Json{{"exitCode", r->exitCode}, {"narration", r->narration},
{"diagnostics", mcpp::diagnostics_of(r->envelope)}}});
Json launch = r->envelope["data"];
// A program in a terminal: the user's arguments after mcpp's own (a runner's, an image's).
for (const auto& a : strings_of(p.value("args", Json::array()))) launch["argv"].push_back(a);
return launch;
}
// A debug session starts the launch selected by mcpp. A named `debuggee`
// declares the host-debugger form; other runner names retain their own meaning.
// Configurations come from that actual build, including target-set selection
// and custom-profile build-program declarations.
std::expected<Json, rpc::Error> Session::debug_configuration(const Json& p, const rpc::Context& ctx) {
auto launch = run_launch(p, ctx);
if (!launch) return launch;
if (!p.contains("runner")) {
const auto configuration = launch->value("configuration", Json::object());
const auto runners = configuration.is_object()
? strings_of(configuration.value("runners", Json::array())) : std::vector<std::string>{};
if (std::ranges::find(runners, "debuggee") != runners.end()) {
const auto triple = configuration.value("triple", "");
const auto profile = configuration.value("profile", "");
if (triple.empty() || profile.empty())
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("mcpp's launch configuration omits its target or profile")});
Json parameters = p;
parameters["target"] = triple;
parameters["profile"] = profile;
parameters["runner"] = "debuggee";
launch = run_launch(parameters, ctx);
if (!launch) return launch;
const auto selected = launch->value("configuration", Json::object());
if (!selected.is_object() || selected.value("triple", "") != triple
|| selected.value("profile", "") != profile
|| selected.value("platform", Json(nullptr)) != configuration.value("platform", Json(nullptr)))
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("mcpp's debug launch changed the selected target, profile or platform")});
}
}
const auto& l = *launch;
std::string engine = p.value("engine", setting("mcpp.debug.engine").is_string() ? setting("mcpp.debug.engine").get<std::string>() : "auto");
const auto available = strings_of(p.value("available", Json::array()));
auto has = [&](std::string_view e) { return std::ranges::find(available, e) != available.end(); };
if (engine == "auto") {
if (has("lldb")) engine = "lldb";
else if (has("cppdbg")) engine = "cppdbg";
else if (has("lldb-dap")) engine = "lldb-dap";
else engine = "cppdbg";
}
const auto argv = strings_of(l.value("argv", Json::array()));
const std::string program = argv.empty() ? l.value("program", "") : argv.front();
std::vector<std::string> args(argv.size() > 1 ? argv.begin() + 1 : argv.end(), argv.end());
Json env = l.value("env", Json::object());
const bool through = !l.value("via", Json(nullptr)).is_null();
const auto jit = std::string("settings set plugin.jit-loader.gdb.enable on");
Json cfg{{"name", std::format("mcpp: {}", std::filesystem::path(l.value("program", program)).filename().string())},
{"request", "launch"}, {"program", program}, {"args", args}, {"cwd", l.value("cwd", root_of(p).generic_string())}};
if (engine == "cppdbg") {
cfg["type"] = "cppdbg";
Json envList = Json::array();
for (auto it = env.begin(); it != env.end(); ++it) envList.push_back(Json{{"name", it.key()}, {"value", it.value()}});
cfg["environment"] = envList;
cfg["MIMode"] = p.value("platform", "linux") == "macos" ? "lldb" : "gdb";
cfg["externalConsole"] = false;
if (through && cfg["MIMode"] == "lldb") cfg["setupCommands"] = Json::array({Json{{"text", jit}}});
} else if (engine == "lldb") {
cfg["type"] = "lldb";
cfg["env"] = env;
if (through) cfg["initCommands"] = Json::array({jit});
} else if (engine == "lldb-dap") {
cfg["type"] = "lldb-dap";
Json envList = Json::array();
for (auto it = env.begin(); it != env.end(); ++it) envList.push_back(std::format("{}={}", it.key(), it.value().get<std::string>()));
cfg["env"] = envList;
if (through) cfg["initCommands"] = Json::array({jit});
} else if (engine == "gdb") {
cfg["type"] = "gdb";
cfg["env"] = env;
} else {
return std::unexpected(invalid(std::format("unknown debug engine {}", engine)));
}
if (through)
cfg["mcppNote"] = t("the debugger starts {0}; source symbols depend on the runner's debugger support",
{l["via"].is_string() ? l["via"].get<std::string>() : program});
return Json{{"engine", engine}, {"configuration", cfg}, {"launch", l}};
}
std::expected<Json, rpc::Error> Session::library_search(const Json& p) {
const bool refresh = p.value("refresh", false);
Json envelope;
{
std::lock_guard lock(mutex_);
if (!refresh && !searchCache_.is_null() && std::chrono::steady_clock::now() - searchAt_ < std::chrono::minutes(10))
envelope = searchCache_;
}
if (envelope.is_null()) {
auto r = query(any_root(p), {"search", "--format", "json"});
if (!r) return std::unexpected(r.error());
if (r->envelope.is_null() || r->envelope.value("kind", "") != "mcpp.search")
return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("mcpp search printed no catalogue"),
Json{{"narration", r->narration}}});
std::lock_guard lock(mutex_);
searchCache_ = r->envelope;
searchAt_ = std::chrono::steady_clock::now();
envelope = searchCache_;
}
if (p.contains("id")) {
auto detail = views::library_detail(envelope, p["id"].get<std::string>());
if (detail.is_null()) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("no such package")});
return detail;
}
views::LibraryQuery q;
q.keyword = p.value("keyword", "");
q.index = p.value("index", "");
q.sort = p.value("sort", "name");
q.limit = p.value("limit", 500);
return views::library(envelope, q);
}
namespace {
policy::CleanOptions clean_options(const Json& p, const Json& settings) {
policy::CleanOptions o;
o.staleDays = p.value("staleDays", settings.value("mcpp.cache.staleDays", 3));
o.budgetGiB = p.value("budgetGiB", settings.value("mcpp.cache.gc.defaultBudgetGiB", 0.0));
o.pruneAgeDays = p.value("pruneAgeDays", settings.value("mcpp.cache.pruneAgeDays", 30));
return o;
}
} // namespace
std::expected<Json, rpc::Error> Session::cache_plan(const Json& p) {
Json settings;
{
std::lock_guard lock(mutex_);
settings = settings_;
}
const auto o = clean_options(p, settings);
auto plan = policy::plan(p.value("action", ""), o);
if (!plan) return std::unexpected(invalid(std::format("unknown cache action {}", p.value("action", ""))));
Json out = policy::to_json(*plan);