forked from lemonade-sdk/lemonade
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
5763 lines (5078 loc) · 243 KB
/
Copy pathserver.cpp
File metadata and controls
5763 lines (5078 loc) · 243 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 "lemon/server.h"
#include <optional>
#include "lemon/collection_orchestrator.h"
#include "lemon/hf_variants.h"
#include "lemon/config_file.h"
#include "lemon/mcp_server.h"
#include "lemon/ollama_api.h"
#include "lemon/backends/cloud/cloud_server.h"
#include "lemon/backends/sdcpp/sdcpp_server.h"
#include "lemon/backends/backend_utils.h"
#include <cstring>
#include "lemon/utils/json_utils.h"
#include "lemon/utils/path_utils.h"
#include "lemon/streaming_proxy.h"
#include "lemon/logging_config.h"
#include "lemon/prometheus_metrics.h"
#include "lemon/runtime_config.h"
#include "telemetry.h"
#include "lemon/system_info.h"
#include "lemon/version.h"
#include <cctype>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <map>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
#include <filesystem>
#include <system_error>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <lemon/utils/aixlog.hpp>
#ifdef _WIN32
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // sockaddr_in / sockaddr_in6
#include <arpa/inet.h> // inet_pton, htons
#include <netdb.h> // Crucial for getaddrinfo and addrinfo struct
#include <unistd.h>
#endif
#ifdef __APPLE__
#include <sys/sysctl.h>
#endif
#ifdef __linux__
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <libdrm/drm.h>
#include "lemon/amdxdna_accel.h"
#endif
namespace fs = std::filesystem;
namespace lemon {
namespace {
bool should_disable_thinking(const json& request_json) {
// enable_thinking takes precedence over thinking when both are present.
if (request_json.contains("enable_thinking") && request_json["enable_thinking"].is_boolean()) {
return request_json["enable_thinking"].get<bool>() == false;
}
if (request_json.contains("thinking")) {
const auto& thinking = request_json["thinking"];
if (thinking.is_boolean()) {
return thinking.get<bool>() == false;
}
if (thinking.is_object()) {
const std::string type = thinking.value("type", "");
if (type == "disabled") {
return true;
}
if (type == "enabled") {
return false;
}
}
}
return false;
}
bool strip_handled_thinking_fields(json& request_json) {
bool modified = false;
modified = request_json.erase("enable_thinking") > 0 || modified;
modified = request_json.erase("thinking") > 0 || modified;
return modified;
}
// Normalize client-provided model names: strip ":latest" suffix (Ollama/Docker convention)
// Returns true if the model name was modified
bool normalize_client_model_name(json& request_json) {
if (!request_json.contains("model") || !request_json["model"].is_string()) {
return false;
}
std::string model_name = request_json["model"].get<std::string>();
const std::string latest_suffix = ":latest";
if (model_name.size() > latest_suffix.size() &&
model_name.substr(model_name.size() - latest_suffix.size()) == latest_suffix) {
std::string normalized = model_name.substr(0, model_name.size() - latest_suffix.size());
request_json["model"] = normalized;
return true;
}
return false;
}
bool prepend_no_think_to_last_user_message(json& request_json) {
if (!request_json.contains("messages") || !request_json["messages"].is_array()) {
LOG(DEBUG, "Server") << "No messages array found for /no_think injection" << std::endl;
return false;
}
auto& messages = request_json["messages"];
for (int i = static_cast<int>(messages.size()) - 1; i >= 0; i--) {
if (messages[i].is_object() &&
messages[i].contains("role") &&
messages[i]["role"].is_string() &&
messages[i]["role"].get<std::string>() == "user" &&
messages[i].contains("content") &&
messages[i]["content"].is_string()) {
std::string original_content = messages[i]["content"].get<std::string>();
messages[i]["content"] = "/no_think\n" + original_content;
return true;
}
}
LOG(DEBUG, "Server") << "No string-content user message found for /no_think injection" << std::endl;
return false;
}
bool valid_error_status(int status_code) {
return status_code >= 400 && status_code <= 599;
}
int get_error_status_code(const json& response, int default_status_code = 500) {
if (!response.contains("error") || !response["error"].is_object()) {
return default_status_code;
}
const auto& error = response["error"];
if (error.contains("status_code") && error["status_code"].is_number_integer()) {
int status_code = error["status_code"].get<int>();
if (valid_error_status(status_code)) {
return status_code;
}
}
if (error.contains("details") && error["details"].is_object()) {
const auto& details = error["details"];
if (details.contains("status_code") && details["status_code"].is_number_integer()) {
int status_code = details["status_code"].get<int>();
if (valid_error_status(status_code)) {
return status_code;
}
}
}
return default_status_code;
}
void set_error_response(const json& response, httplib::Response& res,
int default_status_code = 500) {
res.status = get_error_status_code(response, default_status_code);
res.set_content(response.dump(), "application/json");
}
int get_http_status_from_error(const std::string& error_code) {
if (error_code == "slots_pinned_error") {
return 409;
} else if (error_code == "model_load_error") {
return 500;
} else {
return 404;
}
}
bool is_quiet_polling_path(const std::string& path) {
return path == "/api/v0/downloads" || path == "/api/v1/downloads" ||
path == "/v0/downloads" || path == "/v1/downloads" ||
path == "/api/v0/system-stats" || path == "/api/v1/system-stats" ||
path == "/v0/system-stats" || path == "/v1/system-stats" ||
path == "/api/v0/stats" || path == "/api/v1/stats" ||
path == "/v0/stats" || path == "/v1/stats";
}
std::string join_warnings(const std::vector<std::string>& warnings) {
std::ostringstream joined;
for (size_t i = 0; i < warnings.size(); ++i) {
if (i > 0) {
joined << " | ";
}
joined << warnings[i];
}
return joined.str();
}
void attach_warnings(json& response, const std::vector<std::string>& warnings) {
if (warnings.empty()) {
return;
}
response["warnings"] = warnings;
// Backward-compatible single-string field for older clients.
response["warning"] = join_warnings(warnings);
}
nlohmann::json get_model_storage_stats(const std::string& model_storage_path) {
auto make_error_result = [](const fs::path& path, const std::string& error) {
return nlohmann::json{
{"path", utils::path_to_utf8(path)},
{"used_bytes", nullptr},
{"total_bytes", nullptr},
{"free_bytes", nullptr},
{"error", error}
};
};
std::error_code ec;
fs::path configured_path;
if (!model_storage_path.empty()) {
configured_path = utils::path_from_utf8(model_storage_path);
}
if (configured_path.empty()) {
configured_path = fs::current_path(ec);
if (ec) {
LOG(WARNING, "Server") << "Unable to resolve current path for model storage stats: "
<< ec.message() << std::endl;
return make_error_result(
fs::path{},
"Unable to resolve current path: " + ec.message()
);
}
} else if (configured_path.is_relative()) {
configured_path = fs::absolute(configured_path, ec);
if (ec) {
LOG(WARNING, "Server") << "Unable to resolve model storage path "
<< model_storage_path << ": " << ec.message() << std::endl;
return make_error_result(
configured_path,
"Unable to resolve model storage path: " + ec.message()
);
}
}
configured_path = configured_path.lexically_normal();
fs::path probe_path = configured_path;
while (!probe_path.empty()) {
std::error_code exists_ec;
if (fs::exists(probe_path, exists_ec)) {
break;
}
if (exists_ec) {
LOG(WARNING, "Server") << "Unable to inspect model storage path "
<< utils::path_to_utf8(probe_path) << ": "
<< exists_ec.message() << std::endl;
return make_error_result(
configured_path,
"Unable to inspect model storage path: " + exists_ec.message()
);
}
fs::path parent_path = probe_path.parent_path();
if (parent_path == probe_path) {
break;
}
probe_path = parent_path;
}
auto space_info = fs::space(probe_path, ec);
if (ec) {
LOG(WARNING, "Server") << "Unable to read model storage stats for "
<< utils::path_to_utf8(probe_path) << ": "
<< ec.message() << std::endl;
return make_error_result(
configured_path,
"Unable to read model storage stats: " + ec.message()
);
}
const uintmax_t total_bytes = space_info.capacity;
const uintmax_t free_bytes = std::min(space_info.available, space_info.capacity);
const uintmax_t used_bytes = total_bytes - free_bytes;
return nlohmann::json{
{"path", utils::path_to_utf8(configured_path)},
{"used_bytes", static_cast<uint64_t>(used_bytes)},
{"total_bytes", static_cast<uint64_t>(total_bytes)},
{"free_bytes", static_cast<uint64_t>(free_bytes)}
};
}
} // namespace
static const json MIME_TYPES = {
{"mp3", "audio/mpeg"},
{"opus", "audio/opus"},
{"aac", "audio/aac"},
{"flac", "audio/flac"},
{"wav", "audio/wav"},
{"pcm", "audio/l16;rate=24000;endianness=little-endian"}
};
Server::Server(std::shared_ptr<RuntimeConfig> config, const std::string& cache_dir)
: config_(config),
cache_dir_(cache_dir),
port_(config->port()), running_(false), udp_beacon_(),
metrics_platform_(create_metrics_platform()) {
// Set global HttpClient timeout
utils::HttpClient::set_default_timeout(config->global_timeout());
cloud_registry_ = std::make_unique<CloudProviderRegistry>();
// Seed installed providers from config.json. Runtime keys stay empty
// until either an env var resolves them per-request or a client POSTs
// /v1/cloud/auth — by design we never persist secrets to disk.
{
json snap = config_->snapshot();
if (snap.contains("cloud_providers")) {
cloud_registry_->load_from_config(snap["cloud_providers"]);
}
}
model_manager_ = std::make_unique<ModelManager>(config_->extra_models_dir());
model_manager_->set_cloud_registry(cloud_registry_.get());
backend_manager_ = std::make_unique<BackendManager>();
BackendManager::set_global(backend_manager_.get());
router_ = std::make_unique<Router>(config_.get(),
model_manager_.get(),
backend_manager_.get());
router_->set_cloud_registry(cloud_registry_.get());
LOG(DEBUG, "Server") << "Debug logging enabled - subprocess output will be visible" << std::endl;
const char* api_key_env = std::getenv("LEMONADE_API_KEY");
api_key_ = api_key_env ? std::string(api_key_env) : "";
// Read admin API key - if not set, defaults to regular API key value
const char* admin_api_key_env = std::getenv("LEMONADE_ADMIN_API_KEY");
if (admin_api_key_env) {
admin_api_key_ = std::string(admin_api_key_env);
} else {
admin_api_key_ = api_key_;
}
setup_http_servers();
// Initialize WebSocket server for realtime API and log streaming
websocket_server_ = std::make_unique<WebSocketServer>(
router_.get(),
config_->host(),
config_->websocket_port());
start_model_cache_warmup();
}
void Server::start_model_cache_warmup() {
if (model_cache_warmup_thread_.joinable()) {
return;
}
model_cache_warmup_thread_ = std::thread([this]() {
try {
LOG(DEBUG, "Server") << "Warming model list cache..." << std::endl;
model_manager_->get_supported_models();
LOG(DEBUG, "Server") << "Model list cache warmup complete" << std::endl;
} catch (const std::exception& e) {
LOG(WARNING, "Server") << "Model list cache warmup failed: " << e.what() << std::endl;
} catch (...) {
LOG(WARNING, "Server") << "Model list cache warmup failed with unknown error" << std::endl;
}
});
}
// Extract the member-function pointer for httplib::Server's private virtual
// process_and_close_socket (see upgradable_http_server.h). Explicit
// instantiation is the one context where C++ permits naming a private member.
template struct lemon::detail::PrivateMemberInit<
lemon::detail::ProcessAndCloseSocketTag,
&httplib::Server::process_and_close_socket>;
void Server::setup_http_servers() {
http_server_ = std::make_unique<RoutedHttpServer>();
http_server_v6_ = std::make_unique<RoutedHttpServer>();
// Front listeners for the main port: WebSocket upgrades for /realtime and
// /logs/stream are adopted by the libwebsockets server; everything else is
// processed by the routed servers above. The dedicated websocket_port
// listener keeps running unchanged.
auto upgrade_handler = [this](socket_t sock) -> bool {
if (websocket_server_ && websocket_server_->is_running()) {
return websocket_server_->adopt_socket(static_cast<intptr_t>(sock));
}
return false;
};
http_front_ = std::make_unique<UpgradableFrontServer>(http_server_.get(), upgrade_handler);
http_front_v6_ = std::make_unique<UpgradableFrontServer>(http_server_v6_.get(), upgrade_handler);
// Keep cpp-httplib's default socket options here. httplib binds IPv6 with
// IPV6_V6ONLY=0, so "::" overlaps the IPv4 wildcard "0.0.0.0" and only the
// default SO_REUSEPORT lets the two coexist. Duplicate detection is done by
// port_is_available() in run(), not by making these listeners exclusive.
// CRITICAL: Enable multi-threading so the server can handle concurrent requests
// Without this, the server is single-threaded and blocks on long operations
std::function<httplib::TaskQueue *(void)> task_queue_factory = [this] {
LOG(DEBUG, "Server") << "Creating new thread pool with 8 threads" << std::endl;
return new httplib::ThreadPool(8);
};
// The fronts own the accept loops (and therefore the task queues)
http_front_->new_task_queue = task_queue_factory;
http_front_v6_->new_task_queue = task_queue_factory;
http_server_->new_task_queue = task_queue_factory;
http_server_v6_->new_task_queue = task_queue_factory;
setup_routes(*http_server_);
setup_routes(*http_server_v6_);
}
void Server::stop_http_listeners() {
// The routed servers never own the listen socket: clear the injected fd so
// their per-connection keep-alive loops exit, then close it once via the
// fronts (which are the servers actually listening).
if (http_server_) {
http_server_->set_listen_socket(INVALID_SOCKET);
}
if (http_server_v6_) {
http_server_v6_->set_listen_socket(INVALID_SOCKET);
}
if (http_front_) {
http_front_->stop();
}
if (http_front_v6_) {
http_front_v6_->stop();
}
}
Server::~Server() {
cancel_download_jobs();
stop();
}
void Server::log_request(const httplib::Request& req) {
if (req.path != "/api/v0/health" && req.path != "/api/v1/health" &&
req.path != "/v0/health" && req.path != "/v1/health" &&
req.path != "/live" &&
req.path != "/metrics" &&
!is_quiet_polling_path(req.path)) {
LOG(DEBUG, "Server") << req.method << " " << req.path << std::endl;
}
}
httplib::Server::HandlerResponse Server::authenticate_request(const httplib::Request& req, httplib::Response& res) {
// Check if path requires authentication (API routes and internal endpoints).
// /mcp is included here so that LEMONADE_API_KEY enforcement covers the MCP
// gateway (Critical Invariant #10). It is the only API route outside the
// /api/, /v0/, /v1/ prefixes — see register_routes() in McpServer for why.
bool is_api_route = (req.path.rfind("/api/", 0) == 0) ||
(req.path.rfind("/v0/", 0) == 0) ||
(req.path.rfind("/v1/", 0) == 0) ||
(req.path == "/mcp");
bool is_internal_route = (req.path.rfind("/internal/", 0) == 0);
bool is_metrics_route = (req.path == "/metrics");
// Authentication hierarchy. Two credentials gate two classes of endpoints:
// api_key_ gates the regular API endpoints (/api, /v0, /v1); admin_api_key_
// gates the internal control endpoints (/internal/*). admin_api_key_ defaults
// to api_key_ when LEMONADE_ADMIN_API_KEY is unset.
// - admin_api_key_ authenticates against both regular and internal endpoints.
// - api_key_ authenticates against the regular endpoints only. It cannot
// reach /internal/* when LEMONADE_ADMIN_API_KEY is set to a distinct value;
// when LEMONADE_ADMIN_API_KEY is unset, admin_api_key_ == api_key_, so the
// regular key also authenticates against /internal/*.
// - If api_key_ is empty, the regular endpoints require no authentication.
// - If admin_api_key_ is empty (neither key set), /internal/* requires none.
// Safely extract bearer token, guarding against malformed Authorization headers
std::string auth_token;
try {
if (req.has_header("Authorization")) {
auto auth_value = req.get_header_value("Authorization");
// httplib::get_bearer_token_auth does substr(7) for "Bearer ", so check length
if (auth_value.size() >= 7) {
auth_token = httplib::get_bearer_token_auth(req);
}
// Silently ignore malformed/short Authorization headers
}
} catch (const std::exception& e) {
LOG(DEBUG, "Server") << "Failed to parse Authorization header: " << e.what() << std::endl;
}
if (is_internal_route) {
// Internal routes require admin key authentication
if (!admin_api_key_.empty() && req.method != "OPTIONS") {
if (auth_token != admin_api_key_) {
res.status = 401;
res.set_content("{\"error\": \"Invalid or missing admin API key\"}", "application/json");
return httplib::Server::HandlerResponse::Handled;
}
}
} else if ((is_api_route || is_metrics_route) && req.method != "OPTIONS") {
if (!api_key_.empty()) {
if ((auth_token != api_key_) && (auth_token != admin_api_key_)) {
res.status = 401;
res.set_content("{\"error\": \"Invalid or missing API key\"}", "application/json");
return httplib::Server::HandlerResponse::Handled;
}
}
}
return httplib::Server::HandlerResponse::Unhandled;
}
void Server::setup_routes(httplib::Server &web_server) {
// Add pre-routing handler to log ALL incoming requests (except health checks)
web_server.set_pre_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
this->log_request(req);
return authenticate_request(req, res);
});
web_server.Get("/live", [this](const httplib::Request& req, httplib::Response& res) {
handle_live(req, res);
});
// Prometheus scrape endpoint for Lemonade, model, backend, and system metrics.
web_server.Get("/metrics", [this](const httplib::Request& req, httplib::Response& res) {
handle_metrics(req, res);
});
// Setup CORS for all routes
setup_cors(web_server);
// Helper lambda to register routes for both v0 and v1 (with and without /api prefix for OpenAI compatibility)
auto register_get = [this, &web_server](const std::string& endpoint,
std::function<void(const httplib::Request&, httplib::Response&)> handler) {
web_server.Get("/api/v0/" + endpoint, handler);
web_server.Get("/api/v1/" + endpoint, handler);
web_server.Get("/v0/" + endpoint, handler);
web_server.Get("/v1/" + endpoint, handler);
};
auto register_post = [this, &web_server](const std::string& endpoint,
std::function<void(const httplib::Request&, httplib::Response&)> handler) {
web_server.Post("/api/v0/" + endpoint, handler);
web_server.Post("/api/v1/" + endpoint, handler);
web_server.Post("/v0/" + endpoint, handler);
web_server.Post("/v1/" + endpoint, handler);
if (endpoint != "params") {
web_server.Get("/api/v0/" + endpoint, [](const httplib::Request&, httplib::Response& res) {
res.status = 405;
res.set_content("{\"error\": \"Method Not Allowed. Use POST for this endpoint\"}", "application/json");
});
web_server.Get("/api/v1/" + endpoint, [](const httplib::Request&, httplib::Response& res) {
res.status = 405;
res.set_content("{\"error\": \"Method Not Allowed. Use POST for this endpoint\"}", "application/json");
});
web_server.Get("/v0/" + endpoint, [](const httplib::Request&, httplib::Response& res) {
res.status = 405;
res.set_content("{\"error\": \"Method Not Allowed. Use POST for this endpoint\"}", "application/json");
});
web_server.Get("/v1/" + endpoint, [](const httplib::Request&, httplib::Response& res) {
res.status = 405;
res.set_content("{\"error\": \"Method Not Allowed. Use POST for this endpoint\"}", "application/json");
});
}
};
// Health check
register_get("health", [this](const httplib::Request& req, httplib::Response& res) {
handle_health(req, res);
});
// Models endpoints
register_get("models", [this](const httplib::Request& req, httplib::Response& res) {
handle_models(req, res);
});
// Model by ID (need to register for both versions with regex, with and without /api prefix)
web_server.Get(R"(/api/v0/models/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_model_by_id(req, res);
});
web_server.Get(R"(/api/v1/models/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_model_by_id(req, res);
});
web_server.Get(R"(/v0/models/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_model_by_id(req, res);
});
web_server.Get(R"(/v1/models/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_model_by_id(req, res);
});
// Chat completions (OpenAI compatible)
register_post("chat/completions", [this](const httplib::Request& req, httplib::Response& res) {
handle_chat_completions(req, res);
});
// Completions
register_post("completions", [this](const httplib::Request& req, httplib::Response& res) {
handle_completions(req, res);
});
// Embeddings
register_post("embeddings", [this](const httplib::Request& req, httplib::Response& res) {
handle_embeddings(req, res);
});
// Reranking
register_post("reranking", [this](const httplib::Request& req, httplib::Response& res) {
handle_reranking(req, res);
});
// Slots (llama.cpp backend information)
register_get("slots", [this](const httplib::Request& req, httplib::Response& res) {
handle_slots(req, res);
});
// Slots action endpoints (need to register for both versions with regex, with and without /api prefix)
web_server.Post(R"(/api/v0/slots/(\d+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_slots_by_id(req, res);
});
web_server.Post(R"(/api/v1/slots/(\d+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_slots_by_id(req, res);
});
web_server.Post(R"(/v0/slots/(\d+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_slots_by_id(req, res);
});
web_server.Post(R"(/v1/slots/(\d+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_slots_by_id(req, res);
});
// Tokenize endpoint (llama.cpp specific)
register_post("tokenize", [this](const httplib::Request& req, httplib::Response& res) {
handle_tokenize(req, res);
});
// Audio endpoints (OpenAI /v1/audio/* compatible)
register_post("audio/transcriptions", [this](const httplib::Request& req, httplib::Response& res) {
handle_audio_transcriptions(req, res);
});
// Speech
register_post("audio/speech", [this](const httplib::Request& req, httplib::Response& res) {
handle_audio_speech(req, res);
});
// Image endpoints (OpenAI /v1/images/* compatible)
register_post("images/generations", [this](const httplib::Request& req, httplib::Response& res) {
handle_image_generations(req, res);
});
register_post("images/edits", [this](const httplib::Request& req, httplib::Response& res) {
handle_image_edits(req, res);
});
register_post("images/variations", [this](const httplib::Request& req, httplib::Response& res) {
handle_image_variations(req, res);
});
register_post("images/upscale", [this](const httplib::Request& req, httplib::Response& res) {
handle_image_upscale(req, res);
});
// Responses endpoint
register_post("responses", [this](const httplib::Request& req, httplib::Response& res) {
handle_responses(req, res);
});
// Model management endpoints
register_post("pull", [this](const httplib::Request& req, httplib::Response& res) {
handle_pull(req, res);
});
register_get("pull/variants", [this](const httplib::Request& req, httplib::Response& res) {
handle_pull_variants(req, res);
});
register_get("downloads", [this](const httplib::Request& req, httplib::Response& res) {
handle_downloads(req, res);
});
register_post("downloads/control", [this](const httplib::Request& req, httplib::Response& res) {
handle_download_control(req, res);
});
register_post("load", [this](const httplib::Request& req, httplib::Response& res) {
handle_load(req, res);
});
register_post("unload", [this](const httplib::Request& req, httplib::Response& res) {
handle_unload(req, res);
});
register_post("delete", [this](const httplib::Request& req, httplib::Response& res) {
handle_delete(req, res);
});
register_post("params", [this](const httplib::Request& req, httplib::Response& res) {
handle_params(req, res);
});
register_get("params", [this](const httplib::Request& req, httplib::Response& res) {
handle_config_get(req, res);
});
// Backend management endpoints
register_post("install", [this](const httplib::Request& req, httplib::Response& res) {
handle_install(req, res);
});
register_post("install/dry-run", [this](const httplib::Request& req, httplib::Response& res) {
handle_install_dry_run(req, res);
});
register_post("uninstall", [this](const httplib::Request& req, httplib::Response& res) {
handle_uninstall(req, res);
});
// System endpoints
register_get("stats", [this](const httplib::Request& req, httplib::Response& res) {
handle_stats(req, res);
});
register_get("system-info", [this](const httplib::Request& req, httplib::Response& res) {
handle_system_info(req, res);
});
register_get("system-stats", [this](const httplib::Request& req, httplib::Response& res) {
handle_system_stats(req, res);
});
register_post("log-level", [this](const httplib::Request& req, httplib::Response& res) {
handle_log_level(req, res);
});
// NOTE: /api/v1/halt endpoint removed - use SIGTERM signal instead (like Python server)
// The stop command now sends termination signal directly to the process
// Internal shutdown endpoint (not part of public API)
web_server.Post("/internal/shutdown", [this](const httplib::Request& req, httplib::Response& res) {
handle_shutdown(req, res);
});
web_server.Post("/internal/telemetry/flush", [](const httplib::Request& req, httplib::Response& res) {
lemon::telemetry::flush();
res.status = 200;
res.set_content(nlohmann::json{{"status", "flushed"}}.dump(), "application/json");
});
web_server.Post("/internal/pin", [this](const httplib::Request& req, httplib::Response& res) {
handle_pin(req, res);
});
// Unified config endpoints (not part of public API)
web_server.Post("/internal/set", [this](const httplib::Request& req, httplib::Response& res) {
handle_config_set(req, res);
});
web_server.Get("/internal/config", [this](const httplib::Request& req, httplib::Response& res) {
handle_config_get(req, res);
});
web_server.Get("/internal/config/defaults", [this](const httplib::Request& req, httplib::Response& res) {
handle_config_defaults_get(req, res);
});
web_server.Post("/internal/cleanup-cache", [this](const httplib::Request& req, httplib::Response& res) {
handle_cleanup_cache(req, res);
});
web_server.Post("/internal/simulate-vram-pressure", [this](const httplib::Request& req, httplib::Response& res) {
handle_simulate_vram_pressure(req, res);
});
// Cloud auth: register quad-prefix POST and a parameterized DELETE.
// POST /v1/cloud/auth body: {provider, api_key}
// DELETE /v1/cloud/auth/{p}
// The runtime key lives in process memory only; env var
// LEMONADE_<PROVIDER>_API_KEY takes precedence (POST returns 409 if it
// is set). Both endpoints respect LEMONADE_ADMIN_API_KEY when configured
// via the standard authentication path applied to /v1/.
register_post("cloud/auth", [this](const httplib::Request& req, httplib::Response& res) {
handle_cloud_auth_set(req, res);
});
web_server.Delete(R"(/api/v0/cloud/auth/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_cloud_auth_clear(req, res);
});
web_server.Delete(R"(/api/v1/cloud/auth/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_cloud_auth_clear(req, res);
});
web_server.Delete(R"(/v0/cloud/auth/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_cloud_auth_clear(req, res);
});
web_server.Delete(R"(/v1/cloud/auth/(.+))", [this](const httplib::Request& req, httplib::Response& res) {
handle_cloud_auth_clear(req, res);
});
// Test endpoint to verify POST works
web_server.Post("/api/v1/test", [](const httplib::Request& req, httplib::Response& res) {
LOG(INFO, "Server") << "TEST POST endpoint hit!" << std::endl;
res.set_content("{\"test\": \"ok\"}", "application/json");
});
// Register Ollama-compatible API routes
auto ollama_api = std::make_shared<OllamaApi>(router_.get(), model_manager_.get());
ollama_api->register_routes(web_server);
// Register MCP gateway (POST /mcp). NOTE: /mcp is an INTENTIONAL EXCEPTION
// to the quad-prefix invariant (AGENTS.md #1) — the MCP spec mandates a
// single endpoint URL.
auto mcp_server = std::make_shared<McpServer>(
router_.get(),
model_manager_.get(),
[this](const std::string& m) { auto_load_model_if_needed(m); });
mcp_server->register_routes(web_server);
// Setup static file serving for web UI
setup_static_files(web_server);
}
void Server::setup_static_files(httplib::Server &web_server) {
// Determine static files directory (relative to executable)
std::string static_dir = utils::get_resource_path("resources/static");
// Create a reusable handler for serving index.html with template variable replacement
auto serve_index_html = [this, static_dir](const httplib::Request&, httplib::Response& res) {
std::string index_path = static_dir + "/index.html";
std::ifstream file(index_path);
if (!file.is_open()) {
LOG(ERROR, "Server") << "Could not open index.html at: " << index_path << std::endl;
res.status = 404;
res.set_content("{\"error\": \"index.html not found\"}", "application/json");
return;
}
// Read the entire file
std::string html_template((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
// Get filtered models from model manager
auto models_map = model_manager_->get_supported_models();
// Convert map to JSON
json filtered_models = json::object();
for (const auto& [model_name, info] : models_map) {
std::vector<std::string> public_components;
public_components.reserve(info.components.size());
for (const auto& component : info.components) {
public_components.push_back(model_manager_->get_public_model_name(component));
}
filtered_models[model_name] = {
{"model_name", model_name},
{"checkpoint", info.checkpoint()},
{"recipe", info.recipe},
{"labels", info.labels},
{"suggested", info.suggested},
{"components", public_components},
{"mmproj", info.mmproj()}
};
// Add size if available
if (info.size > 0.0) {
filtered_models[model_name]["size"] = info.size;
}
}
// Create JavaScript snippets
std::string server_models_js = "<script>window.SERVER_MODELS = " + filtered_models.dump() + ";</script>";
// Get platform name
std::string platform_name;
#ifdef _WIN32
platform_name = "Windows";
#elif __APPLE__
platform_name = "Darwin";
#elif __linux__
platform_name = "Linux";
#else
platform_name = "Unknown";
#endif
std::string platform_js = "<script>window.PLATFORM = '" + platform_name + "';</script>";
// Replace template variables
size_t pos;
// Replace {{SERVER_PORT}}
while ((pos = html_template.find("{{SERVER_PORT}}")) != std::string::npos) {
html_template.replace(pos, 15, std::to_string(port_));
}
// Replace {{SERVER_MODELS_JS}}
while ((pos = html_template.find("{{SERVER_MODELS_JS}}")) != std::string::npos) {
html_template.replace(pos, 20, server_models_js);
}
// Replace {{PLATFORM_JS}}
while ((pos = html_template.find("{{PLATFORM_JS}}")) != std::string::npos) {
html_template.replace(pos, 15, platform_js);
}
// Set no-cache headers
res.set_header("Cache-Control", "no-cache, no-store, must-revalidate");
res.set_header("Pragma", "no-cache");
res.set_header("Expires", "0");
res.set_content(html_template, "text/html");
};
// Keep status page at /status endpoint
web_server.Get("/status", serve_index_html);
// Also serve index.html at /api/v1 for compatibility
web_server.Get("/api/v1", serve_index_html);
// Mount static files directory for status page assets (CSS, JS, images)
if (!web_server.set_mount_point("/static", static_dir)) {
LOG(WARNING, "Server") << "Could not mount static files from: " << static_dir << std::endl;
LOG(WARNING, "Server") << "Status page assets will not be available" << std::endl;
}
// Web app UI endpoint - serve the React web app at root
std::string web_app_dir = utils::get_resource_path("resources/web-app");
// Check if web app directory exists
if (fs::exists(web_app_dir) && fs::is_directory(web_app_dir)) {
// Create a handler for serving web app index.html for SPA routing
auto serve_web_app_html = [web_app_dir](const httplib::Request&, httplib::Response& res) {
std::string index_path = web_app_dir + "/index.html";
std::ifstream file(index_path);
if (!file.is_open()) {
res.status = 404;
res.set_content("{\"error\": \"Web app not found\"}", "application/json");
return;
}
std::string html((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
// Inject mock window.api for web compatibility with the shared Tauri app renderer
std::string mock_api = R"(
<script>
// Mock window.api for web compatibility (the Tauri shim is skipped in pure-web mode)
window.api = {
isWebApp: true, // Explicit flag to indicate web mode
platform: navigator.platform || 'web',
minimizeWindow: () => {},
maximizeWindow: () => {},
closeWindow: () => {},
openExternal: (url) => window.open(url, '_blank'),
onMaximizeChange: () => {},
updateMinWidth: () => {},
zoomIn: () => document.body.style.zoom = (parseFloat(document.body.style.zoom || '1') + 0.1).toString(),
zoomOut: () => document.body.style.zoom = (parseFloat(document.body.style.zoom || '1') - 0.1).toString(),
getSettings: async () => {
const saved = localStorage.getItem('lemonade-settings');
if (saved) return JSON.parse(saved);
// Return defaults matching DEFAULT_LAYOUT_SETTINGS from appSettings.ts
return {
layout: {
isChatVisible: true,
isModelManagerVisible: true,
isCenterPanelVisible: true,
isLogsVisible: false,
modelManagerWidth: 280,
chatWidth: 350,
logsHeight: 200
},
theme: 'dark',
apiUrl: window.location.origin,
apiKey: { value: '' }
};
},
saveSettings: async (settings) => {
localStorage.setItem('lemonade-settings', JSON.stringify(settings));
return settings;
},
onSettingsUpdated: () => {},
getServerPort: () => parseInt(window.location.port) || 13305,