Repository navigation
Expand file tree
/
Copy pathconfig_access.cpp
More file actions
457 lines (415 loc) · 19.2 KB
/
Copy pathconfig_access.cpp
File metadata and controls
457 lines (415 loc) · 19.2 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
/**
* Generic string-keyed Config access — see config_access.h.
*
* Maps each schema key to its Config struct field via member pointers,
* grouped by field type. Keeping the mapping here (one table per C++ type)
* is the single place that knows "key X lives in field Y"; everything else
* (CLI, dashboard, DB overlay) goes through the generic get/validate/apply.
*/
#include "config_access.h"
#include "lang.h" // ragger::lang::config_schema / config_meta
#include "user_store.h"
#include "util/fs.h"
#include <charconv>
#include <cstdlib>
#include <cerrno>
#include <algorithm>
#include <cctype>
#include <cmath>
#include <unordered_map>
#include <filesystem>
namespace ragger {
using lang::CfgType;
using lang::CfgEdit;
using lang::ConfigMeta;
namespace {
// ---- key -> Config member pointer, one map per storage type -------------
// Key names sometimes differ from field names (socket_enable ->
// socket_enabled, bind -> bind_address, default_limit ->
// default_search_limit, cert/key -> tls_cert/tls_key, normalize_home ->
// normalize_home_path); the map is the authority.
const std::unordered_map<std::string_view, bool Config::*>& bool_fields() {
static const std::unordered_map<std::string_view, bool Config::*> m = {
{"socket_enable", &Config::socket_enabled},
{"tcp_enable", &Config::tcp_enabled},
{"capture_turns", &Config::capture_turns},
{"build_context", &Config::build_context},
{"auto_recall", &Config::auto_recall},
{"bm25_enabled", &Config::bm25_enabled},
{"fts_literal_enabled", &Config::fts_literal_enabled},
{"normalize_home", &Config::normalize_home_path},
};
return m;
}
const std::unordered_map<std::string_view, int Config::*>& int_fields() {
static const std::unordered_map<std::string_view, int Config::*> m = {
{"port", &Config::port},
{"desired_port", &Config::desired_port},
{"embedding_dimensions", &Config::embedding_dimensions},
{"desired_embedding_dimensions", &Config::desired_embedding_dimensions},
{"embedding_external_port", &Config::embedding_external_port},
{"embed_timeout_ms", &Config::embed_timeout_ms},
{"embed_retries", &Config::embed_retries},
{"embed_max_workers", &Config::embed_max_workers},
{"default_limit", &Config::default_search_limit},
{"summarizer_max_tokens", &Config::summarizer_max_tokens},
{"summarizer_target_pct", &Config::summarizer_target_pct},
{"summarizer_max_pct", &Config::summarizer_max_pct},
{"log_max_age_days", &Config::log_max_age_days},
{"housekeeping_interval", &Config::housekeeping_interval},
{"episode_idle_minutes", &Config::episode_idle_minutes},
{"catch_up_batch_size", &Config::catch_up_batch_size},
{"max_turn_failures", &Config::max_turn_failures},
{"minimum_chunk_size", &Config::minimum_chunk_size},
};
return m;
}
const std::unordered_map<std::string_view, float Config::*>& float_fields() {
static const std::unordered_map<std::string_view, float Config::*> m = {
{"default_min_score", &Config::default_min_score},
{"decision_supersede_threshold", &Config::decision_supersede_threshold},
{"bm25_weight", &Config::bm25_weight},
{"vector_weight", &Config::vector_weight},
{"fts_w_unigram", &Config::fts_w_unigram},
{"fts_w_bigram", &Config::fts_w_bigram},
{"fts_w_metaphone", &Config::fts_w_metaphone},
{"cleanup_max_age_hours", &Config::cleanup_max_age_hours},
{"episode_threshold_base", &Config::episode_threshold_base},
{"episode_threshold_cap", &Config::episode_threshold_cap},
{"episode_threshold_step", &Config::episode_threshold_step},
{"episode_step_minutes", &Config::episode_step_minutes},
};
return m;
}
const std::unordered_map<std::string_view, std::string Config::*>& string_fields() {
static const std::unordered_map<std::string_view, std::string Config::*> m = {
{"bind", &Config::bind_address},
{"server_name", &Config::server_name},
{"cert", &Config::tls_cert},
{"key", &Config::tls_key},
{"embedding_model", &Config::embedding_model},
{"embedding_vector_type", &Config::embedding_vector_type},
{"desired_embedding_model", &Config::desired_embedding_model},
{"desired_embedding_vector_type", &Config::desired_embedding_vector_type},
{"desired_embedding_engine", &Config::desired_embedding_engine},
{"embedding_engine", &Config::embedding_engine},
{"embedding_external_host", &Config::embedding_external_host},
{"embedding_external_api_key", &Config::embedding_external_api_key},
{"embedding_external_model", &Config::embedding_external_model},
{"summarizer_model", &Config::summarizer_model},
{"summarizer_api_url", &Config::summarizer_api_url},
{"summarizer_api_key", &Config::summarizer_api_key},
{"summarizer_prompt", &Config::summarizer_prompt},
{"log_level", &Config::log_level},
{"default_recipe", &Config::default_recipe},
};
return m;
}
// log_max_size_mb is the lone `long` field — handled specially.
std::string fmt_float(float v) {
// Shortest round-trippable representation, no trailing zeros.
char buf[32];
auto [ptr, ec] = std::to_chars(buf, buf + sizeof(buf), v);
if (ec != std::errc{}) return "0";
return std::string(buf, ptr);
}
bool parse_bool_strict(std::string_view v, bool& out) {
std::string s(v);
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
if (s == "true" || s == "yes" || s == "1") { out = true; return true; }
if (s == "false"|| s == "no" || s == "0") { out = false; return true; }
return false;
}
bool parse_int_strict(std::string_view v, long& out) {
auto s = v;
while (!s.empty() && std::isspace((unsigned char)s.front())) s.remove_prefix(1);
while (!s.empty() && std::isspace((unsigned char)s.back())) s.remove_suffix(1);
if (s.empty()) return false;
long val{};
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), val);
if (ec != std::errc{} || ptr != s.data() + s.size()) return false;
out = val;
return true;
}
bool parse_float_strict(std::string_view v, double& out) {
auto s = v;
while (!s.empty() && std::isspace((unsigned char)s.front())) s.remove_prefix(1);
while (!s.empty() && std::isspace((unsigned char)s.back())) s.remove_suffix(1);
if (s.empty()) return false;
// std::from_chars(double) is unavailable on this macOS SDK; use strtod on
// a NUL-terminated copy and require the whole token to be consumed.
std::string str(s);
char* end = nullptr;
errno = 0;
double val = std::strtod(str.c_str(), &end);
if (end != str.c_str() + str.size() || errno == ERANGE) return false;
out = val;
return true;
}
} // namespace
std::optional<std::string> get_config_value(const Config& cfg, std::string_view key) {
const ConfigMeta* meta = lang::config_meta(key);
if (!meta) return std::nullopt;
if (auto it = bool_fields().find(key); it != bool_fields().end())
return (cfg.*(it->second)) ? "true" : "false";
if (auto it = int_fields().find(key); it != int_fields().end())
return std::to_string(cfg.*(it->second));
if (auto it = float_fields().find(key); it != float_fields().end())
return fmt_float(cfg.*(it->second));
if (auto it = string_fields().find(key); it != string_fields().end())
return cfg.*(it->second);
if (key == "log_max_size_mb")
return std::to_string(cfg.log_max_size_mb);
return std::nullopt;
}
nlohmann::json config_entry_json(const lang::ConfigMeta& m,
const std::string& value) {
const char* type = "string";
switch (m.type) {
case CfgType::Boolean: type = "boolean"; break;
case CfgType::Integer: type = "integer"; break;
case CfgType::Float: type = "float"; break;
case CfgType::Enum: type = "enum"; break;
case CfgType::String: type = "string"; break;
case CfgType::Path: type = "path"; break;
case CfgType::Text: type = "text"; break;
}
const char* edit = "live";
switch (m.edit) {
case CfgEdit::Live: edit = "live"; break;
case CfgEdit::RestartRequired: edit = "restart"; break;
case CfgEdit::RebuildRequired: edit = "rebuild"; break;
case CfgEdit::Locked: edit = "locked"; break;
}
nlohmann::json j = {
{"key", std::string(m.key)},
{"section", std::string(m.section)},
{"label", std::string(m.pretty)},
{"type", type},
{"edit", edit},
{"default", std::string(m.default_value)},
{"help", std::string(m.help)},
{"value", value},
};
if (m.secret) {
// Never echo a credential through the read surfaces; a non-empty
// secret shows as the "<set>" marker (writing "<set>" back is a
// no-op, so a dashboard that round-trips the mask cannot clobber
// the real key). Empty stays "" (C §1.7).
j["secret"] = true;
if (!value.empty()) j["value"] = "<set>";
}
if (m.type == CfgType::Enum) {
nlohmann::json opts = nlohmann::json::array();
std::string_view o = m.options;
size_t pos = 0;
while (pos <= o.size()) {
size_t c = o.find(',', pos);
std::string_view tok = (c == std::string_view::npos)
? o.substr(pos) : o.substr(pos, c - pos);
if (!tok.empty()) opts.push_back(std::string(tok));
if (c == std::string_view::npos) break;
pos = c + 1;
}
j["options"] = opts;
}
return j;
}
nlohmann::json build_config_json(const Config& cfg) {
nlohmann::json arr = nlohmann::json::array();
for (const auto& m : lang::config_schema()) {
auto v = get_config_value(cfg, m.key);
arr.push_back(config_entry_json(m, v.value_or("")));
}
return nlohmann::json{{"config", arr}};
}
std::expected<void, ConfigSetError> validate_config_value(std::string_view key,
std::string_view value) {
const ConfigMeta* meta = lang::config_meta(key);
if (!meta) return std::unexpected(ConfigSetError::UnknownKey);
// Empty = reset to default: always valid.
if (value.empty()) return {};
switch (meta->type) {
case CfgType::Boolean: {
bool b;
if (!parse_bool_strict(value, b))
return std::unexpected(ConfigSetError::InvalidValue);
return {};
}
case CfgType::Integer: {
long n;
if (!parse_int_strict(value, n))
return std::unexpected(ConfigSetError::InvalidValue);
return {};
}
case CfgType::Float: {
double d;
if (!parse_float_strict(value, d))
return std::unexpected(ConfigSetError::InvalidValue);
return {};
}
case CfgType::Enum: {
// value must be one of the comma-separated options.
std::string_view opts = meta->options;
// Empty options list => choices are populated dynamically at
// runtime (e.g. desired_embedding_model, sourced from the models
// dir via GET /models). There is no static set to check against,
// so accept any non-empty value; the dashboard already constrains
// the user to real choices client-side.
if (opts.empty()) return {};
size_t pos = 0;
while (pos <= opts.size()) {
size_t comma = opts.find(',', pos);
std::string_view tok = (comma == std::string_view::npos)
? opts.substr(pos)
: opts.substr(pos, comma - pos);
if (tok == value) return {};
if (comma == std::string_view::npos) break;
pos = comma + 1;
}
return std::unexpected(ConfigSetError::InvalidValue);
}
case CfgType::String:
case CfgType::Path:
case CfgType::Text:
return {};
}
return {};
}
std::expected<ConfigSetResult, ConfigSetError> apply_config_value(
Config& cfg, std::string_view key, std::string_view value,
bool allow_locked) {
const ConfigMeta* meta = lang::config_meta(key);
if (!meta) return std::unexpected(ConfigSetError::UnknownKey);
if (meta->edit == CfgEdit::Locked && !allow_locked)
return std::unexpected(ConfigSetError::Locked);
if (auto v = validate_config_value(key, value); !v.has_value())
return std::unexpected(v.error());
// Empty means "reset to schema default" — re-run apply with the default.
std::string_view eff = value.empty() ? meta->default_value : value;
if (auto it = bool_fields().find(key); it != bool_fields().end()) {
bool b; parse_bool_strict(eff, b);
cfg.*(it->second) = b;
} else if (auto it = int_fields().find(key); it != int_fields().end()) {
long n{}; parse_int_strict(eff, n);
cfg.*(it->second) = static_cast<int>(n);
} else if (auto it = float_fields().find(key); it != float_fields().end()) {
double d{}; parse_float_strict(eff, d);
cfg.*(it->second) = static_cast<float>(d);
} else if (auto it = string_fields().find(key); it != string_fields().end()) {
cfg.*(it->second) = std::string(eff);
} else if (key == "log_max_size_mb") {
long n{}; parse_int_strict(eff, n);
cfg.log_max_size_mb = n;
} else {
return std::unexpected(ConfigSetError::UnknownKey);
}
ConfigSetResult r;
r.restart_required = (meta->edit == CfgEdit::RestartRequired);
r.rebuild_required = (meta->edit == CfgEdit::RebuildRequired);
return r;
}
bool set_config_field_raw(Config& cfg, std::string_view key, const std::string& value) {
if (auto it = bool_fields().find(key); it != bool_fields().end()) {
// Permissive: unrecognized strings parse as false, same as the
// INI loader's historical parse_bool().
std::string lower = value;
std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
cfg.*(it->second) = (lower == "true" || lower == "yes" || lower == "1");
return true;
}
if (auto it = int_fields().find(key); it != int_fields().end()) {
cfg.*(it->second) = std::stoi(value);
return true;
}
if (auto it = float_fields().find(key); it != float_fields().end()) {
cfg.*(it->second) = std::stof(value);
return true;
}
if (auto it = string_fields().find(key); it != string_fields().end()) {
cfg.*(it->second) = value;
return true;
}
if (key == "log_max_size_mb") {
cfg.log_max_size_mb = std::stol(value);
return true;
}
return false;
}
void overlay_settings_from_db(Config& cfg, const std::string& db_path) {
namespace fs = std::filesystem;
if (db_path.empty() || !fs::exists(db_path)) return;
UserStore store(db_path);
for (const auto& meta : lang::config_schema()) {
auto v = store.get_setting(std::string(meta.key));
if (!v.has_value()) continue; // no row -> keep INI/default
// Best-effort: ignore invalid rows rather than fail startup.
// allow_locked: DB rows are the authoritative persisted state, so
// they must apply even for Locked keys (e.g. `port`). Locked only
// gates USER writes (CLI/dashboard), not the DB->live overlay.
(void)apply_config_value(cfg, meta.key, *v, /*allow_locked=*/true);
}
// NOTE: no provider is prepended to a bare embedding_model.
//
// Ragger-managed ONNX models live at ~/.ragger/models/<provider>/<model>/,
// and the dashboard only offers paths that exist in that layout, so a
// valid internal model name always contains '/'. A bare name is a broken
// value, and assuming "sentence-transformers/" silently resolves it to a
// real but *different* model — wrong for anything under onnx-community/ or
// any other provider, and enough to re-embed the corpus against a model
// nobody chose. Leave it bare: RaggerMemory reports it, the model fails to
// load, and the server degrades to keyword-only search while still
// recording conversations.
// Seed the desired_* embedding identity from current when unset, so the
// dashboard shows the live values as the starting target rather than
// blanks. "current" here is the config's embedding_* (which the drift
// guard keeps in sync with the stored vectors).
if (cfg.desired_embedding_model.empty())
cfg.desired_embedding_model = cfg.embedding_model;
if (cfg.desired_embedding_vector_type.empty())
cfg.desired_embedding_vector_type = cfg.embedding_vector_type;
if (cfg.desired_embedding_dimensions == 0)
cfg.desired_embedding_dimensions = cfg.embedding_dimensions;
if (cfg.desired_embedding_engine.empty())
cfg.desired_embedding_engine = cfg.embedding_engine;
// Seed desired_port from the committed port when unset, so the dashboard
// shows the live port as the starting target. The startup rectify (see
// main serve) then adopts any UI change into `port` on the next restart.
if (cfg.desired_port == 0)
cfg.desired_port = cfg.port;
}
std::vector<std::string_view> all_config_keys() {
std::vector<std::string_view> keys;
for (const auto& meta : lang::config_schema())
keys.push_back(meta.key);
return keys;
}
std::expected<ConfigSetResult, ConfigSetError> set_config_persisted(
std::string_view key, std::string_view value, bool allow_locked) {
const ConfigMeta* meta = lang::config_meta(key);
if (!meta) return std::unexpected(ConfigSetError::UnknownKey);
if (meta->edit == CfgEdit::Locked && !allow_locked)
return std::unexpected(ConfigSetError::Locked);
// A secret key written back as the "<set>" mask is a no-op: the read
// surfaces only ever show "<set>", so a client that echoes the field
// unchanged must never overwrite the real credential (C §1.7). Shared
// path — covers both PUT /config/:key and `ragger config set`.
if (meta->secret && value == "<set>")
return ConfigSetResult{};
// Update the live config first (also validates). On failure, nothing is
// persisted.
Config& cfg = mutable_config();
auto applied = apply_config_value(cfg, key, value, allow_locked);
if (!applied.has_value()) return std::unexpected(applied.error());
// Persist to the DB settings table. Empty value stores an empty row,
// which overlay_settings_from_db() re-interprets as "use default" — so
// the round-trip stays consistent. Best-effort: if the DB isn't there
// yet, the live change still stands.
const std::string db_path = cfg.resolved_db_path();
if (std::filesystem::exists(db_path)) {
UserStore store(db_path);
store.set_setting(std::string(key), std::string(value));
}
return applied;
}
} // namespace ragger