Entropic 2.9.4
Local-first agentic inference engine
Loading...
Searching...
No Matches
entropic.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
13#include "engine_handle.h"
14
17#include <entropic/entropic.h>
20#include "llama_cpp_backend.h"
25#include "json_serializers.h"
26#include "utf8_safe.h"
27#include "../inference/tool_call_serialize.h" // gh#98: shared typed serializer
28
29#include <nlohmann/json.hpp>
30
31#include <atomic>
32
33#include <cstdlib>
34#include <fstream>
35#include <vector>
36#include <cstring>
37#include <filesystem>
38#include <new>
39#include <stdexcept>
40#include <string>
41
42static auto s_log = entropic::log::get("facade");
43
74template <typename Fn>
77 try {
78 rc = fn();
79 } catch (const std::filesystem::filesystem_error& e) {
80 if (handle) { handle->last_error = e.what(); }
81 s_log->error("c_api filesystem_error: {}", e.what());
83 } catch (const nlohmann::json::exception& e) {
84 if (handle) { handle->last_error = e.what(); }
85 s_log->error("c_api json::exception: {}", e.what());
87 } catch (const std::exception& e) {
88 if (handle) { handle->last_error = e.what(); }
89 s_log->error("c_api std::exception: {}", e.what());
91 }
92 return rc;
93}
94
106static char* alloc_cstr(const char* src) {
107 if (!src) { return nullptr; }
108 size_t len = std::strlen(src) + 1;
109 auto* dst = static_cast<char*>(entropic_alloc(len));
110 if (dst) { std::memcpy(dst, src, len); }
111 return dst;
112}
113
121static char* alloc_cstr(const std::string& src) {
122 return alloc_cstr(src.c_str());
123}
124
125/* setup_ggml_logging moved to ModelOrchestrator::initialize() — Step 7 */
126
127// gh#58 follow-up (v2.2.6): per-handle last_error. Pre-v2.2.6 the
128// public API in src/types/error.cpp ignored the handle parameter and
129// returned a single thread-local buffer, so every handle->last_error
130// assignment in the facade was unreadable from the consumer side.
131// Thread-local cache here means the returned const char* stays valid
132// until the *same* thread calls entropic_last_error again — matching
133// the documented v1.8.0 contract.
134static thread_local std::string s_last_error_cache;
135static thread_local char s_pre_create_error[512] = "";
136
150extern "C" const char* entropic_last_error(entropic_handle_t handle) {
151 if (!handle) { return s_pre_create_error; }
152 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
153 s_last_error_cache = handle->last_error;
154 return s_last_error_cache.c_str();
155}
156
165 if (!h) { return ENTROPIC_ERROR_INVALID_HANDLE; }
166 if (!h->configured.load() || !h->orchestrator) {
168 }
169 return ENTROPIC_OK;
170}
171
180 if (!h) { return ENTROPIC_ERROR_INVALID_HANDLE; }
181 if (!h->configured.load() || !h->mcp_auth) {
183 }
184 return ENTROPIC_OK;
185}
186
195 if (!h) { return ENTROPIC_ERROR_INVALID_HANDLE; }
196 if (!h->configured.load() || !h->identity_manager) {
198 }
199 return ENTROPIC_OK;
200}
201
202/* find_tier_by_model_path moved to ModelsConfig::find_tier_by_path() — v2.0.1 */
203
214 entropic_handle_t h, const char* tier_name)
215{
216 auto* backend = h->orchestrator->get_backend(tier_name);
217 if (!backend) {
218 throw std::runtime_error(
219 "no backend for tier: " + std::string(tier_name));
220 }
221 if (!backend->is_active()) {
222 throw std::runtime_error(
223 "model not active: " + std::string(tier_name));
224 }
225 return backend;
226}
227
228extern "C" {
229
242 if (handle == nullptr) {
244 }
245 entropic::log::init(spdlog::level::info);
246 entropic_inference_log_silence(); // silent until configure enables
247
248 auto* engine = new (std::nothrow) entropic_engine();
249 if (engine == nullptr) {
250 *handle = nullptr;
252 }
253
254 // gh#59 (v2.3.1): assign a monotonic log id. Used by the
255 // HandleAwareSink dispatcher to route session.log writes to the
256 // right file when multiple handles coexist. 0 is reserved for
257 // "no handle scope active."
258 static std::atomic<int> s_log_id_counter{0};
259 engine->log_id = ++s_log_id_counter;
260
261 s_log->info("entropic_create() — v{} (log_id={})",
262 CONFIG_ENTROPIC_VERSION_STRING, engine->log_id);
263
264 *handle = engine;
265 return ENTROPIC_OK;
266}
267
286/* preload_bundled_models moved to BundledModels::auto_discover_and_load() — Step 6 */
287
288/* InferenceInterface wiring moved to inference/interface_factory.cpp — Step 3 */
289
290/* InferenceInterface C-wrappers + factory moved to inference/interface_factory.cpp — Step 3 */
291
292/* facade_process_directives → engine->build_directive_hooks() — v2.0.2 */
293/* facade_resolve_tier/tier_exists/handoff/param → engine->set_tier_info() — v2.0.2 */
294/* wire_engine_interfaces → inline in configure_common — v2.0.2 */
295
296// ── Tool prompt injection (v2.0.4) ─────────────────────────
297
310static std::vector<std::string> resolve_allowed_tools(
311 entropic_engine* h, const std::string& tier) {
312 // Primary: cached from identity frontmatter (v2.0.4)
313 auto cached = h->tier_allowed_tools.find(tier);
314 if (cached != h->tier_allowed_tools.end()) {
315 return cached->second;
316 }
317 // Fallback: dynamic identity or model config
318 if (h->identity_manager) {
319 auto* cfg = h->identity_manager->get(tier);
320 if (cfg && !cfg->allowed_tools.empty()) {
321 return cfg->allowed_tools;
322 }
323 }
324 return {};
325}
326
336static std::vector<std::string> filter_tools(
337 const nlohmann::json& all_tools,
338 const std::vector<std::string>& allowed) {
339 std::vector<std::string> result;
340 for (const auto& tool : all_tools) {
341 std::string name = tool.value("name", "");
342 bool pass = allowed.empty()
343 || std::find(allowed.begin(), allowed.end(), name)
344 != allowed.end();
345 if (pass) { result.push_back(tool.dump()); }
346 }
347 return result;
348}
349
368static int facade_get_tool_prompt(const char* tier, char** result,
369 void* user_data) {
370 auto* h = static_cast<entropic_engine*>(user_data);
371 *result = nullptr;
372 if (!h || !h->server_manager) { return 1; }
373
374 std::string tier_name = tier ? tier : "";
375 auto all_json = h->server_manager->list_tools();
376 auto all_tools = nlohmann::json::parse(all_json, nullptr, false);
377 auto allowed = resolve_allowed_tools(h, tier_name);
378 auto tool_jsons = filter_tools(all_tools, allowed);
379 if (!all_tools.is_array() || all_tools.empty() || tool_jsons.empty()) {
380 return 1;
381 }
382
383 nlohmann::json arr = nlohmann::json::array();
384 for (const auto& tj : tool_jsons) {
385 auto obj = nlohmann::json::parse(tj, nullptr, false);
386 if (!obj.is_discarded()) { arr.push_back(std::move(obj)); }
387 }
388 *result = strdup(arr.dump().c_str());
389 return 0;
390}
391
405 h->engine->set_external_interrupt(
406 [](void* ud) {
407 auto* sm = static_cast<entropic::ServerManager*>(ud);
408 if (sm) { sm->interrupt_external_tools(); }
409 }, h->server_manager.get());
410}
411
425 if (h->stream_observer != nullptr && h->engine) {
426 h->engine->set_stream_observer(
428 }
429}
430
444 if (h->queue_observer != nullptr && h->engine) {
445 h->engine->set_queue_observer(
446 h->queue_observer, h->queue_observer_data);
447 }
448}
449
463 if (h->state_observer != nullptr && h->engine) {
464 h->engine->set_state_observer(
465 h->state_observer, h->state_observer_data);
466 }
467}
468
483 if ((h->critique_start_cb != nullptr || h->critique_end_cb != nullptr)
484 && h->validator) {
485 h->validator->set_critique_callbacks(
489 }
490}
491
508
523 const std::filesystem::path& data_dir,
524 const std::string& shared_prefix) {
525 for (const auto& [name, tier] : h->config.models.tiers) {
527 info.valid = true;
528 auto parsed = entropic::prompts::resolve_tier_identity_full(
529 tier, name, data_dir);
530 info.system_prompt = shared_prefix + parsed.body;
531 info.explicit_completion = !tier.auto_chain.has_value();
532 // E6 (2.0.6-rc18): propagate per-identity caps from frontmatter
533 // so AgentEngine::tri_get_tier_param surfaces them to the loop
534 // and tool executor. -1 = "use global loop_config default".
535 info.max_iterations_override =
536 parsed.frontmatter.max_iterations;
537 info.max_tool_calls_per_turn_override =
538 parsed.frontmatter.max_tool_calls_per_turn;
539 h->engine->set_tier_info(name, info);
540 }
541}
542
543// ── configure_common ───────────────────────────────────────
544
564 const char* parent_id, const char* delegating_tier,
565 const char* target_tier, const char* task, int max_turns,
566 std::string& delegation_id, std::string& child_conversation_id,
567 void* user_data) {
568 auto* sb = static_cast<entropic::SqliteStorageBackend*>(user_data);
569 if (sb == nullptr) { return false; }
570 return sb->create_delegation(
571 parent_id ? parent_id : "",
572 delegating_tier ? delegating_tier : "",
573 target_tier ? target_tier : "",
574 task ? task : "",
575 max_turns, delegation_id, child_conversation_id);
576}
577
591 const char* title, std::string& conversation_id,
592 void* user_data) {
593 auto* sb = static_cast<entropic::SqliteStorageBackend*>(user_data);
594 if (sb == nullptr) { return false; }
595 conversation_id = sb->create_conversation(
596 title ? title : "session", std::nullopt, std::nullopt);
597 return !conversation_id.empty();
598}
599
606 const char* delegation_id, const char* status,
607 const char* summary, void* user_data) {
608 auto* sb = static_cast<entropic::SqliteStorageBackend*>(user_data);
609 if (sb == nullptr || delegation_id == nullptr) { return false; }
610 std::optional<std::string> sum;
611 if (summary != nullptr) { sum = summary; }
612 return sb->complete_delegation(delegation_id,
613 status ? status : "completed", sum);
614}
615
622 const char* conversation_id, const char* messages_json,
623 void* user_data) {
624 auto* sb = static_cast<entropic::SqliteStorageBackend*>(user_data);
625 if (sb == nullptr || conversation_id == nullptr
626 || messages_json == nullptr) {
627 return false;
628 }
629 return sb->save_messages(conversation_id, messages_json);
630}
631
638 const char* conversation_id, const char* messages_json,
639 void* user_data) {
640 auto* sb = static_cast<entropic::SqliteStorageBackend*>(user_data);
641 if (sb == nullptr || conversation_id == nullptr
642 || messages_json == nullptr) {
643 return false;
644 }
645 return sb->save_snapshot(conversation_id, messages_json);
646}
647
659 const char* delegation_id, std::string& result_json,
660 void* user_data) {
661 auto* sb = static_cast<entropic::SqliteStorageBackend*>(user_data);
662 bool ok = sb != nullptr && delegation_id != nullptr;
663 std::string del_json;
664 nlohmann::json del, conv;
665 std::string child_id, target, conv_json;
666 if (ok) {
667 ok = sb->get_delegation_by_id(delegation_id, del_json);
668 }
669 if (ok) {
670 del = nlohmann::json::parse(del_json, nullptr, false);
671 ok = del.is_object();
672 }
673 if (ok) {
674 child_id = del.value("child_conversation_id", std::string{});
675 target = del.value("target_tier", std::string{});
676 ok = !child_id.empty() && !target.empty()
677 && sb->load_conversation(child_id, conv_json);
678 }
679 if (ok) {
680 conv = nlohmann::json::parse(conv_json, nullptr, false);
681 ok = conv.is_object();
682 }
683 if (ok) {
684 conv["target_tier"] = target;
685 conv["delegation_id"] = del.value("id", std::string{});
686 result_json = conv.dump();
687 }
688 return ok;
689}
690
708 si.create_delegation = si_create_delegation;
709 si.complete_delegation = si_complete_delegation;
710 si.save_conversation = si_save_conversation;
711 si.save_snapshot = si_save_snapshot;
712 si.load_delegation_with_messages = si_load_delegation_with_messages;
713 si.user_data = sb;
714 return si;
715}
716
723 if (h->config.log_dir.empty()) { return; }
724 auto db_path = h->config.log_dir / "entropic.db";
725 h->storage = std::make_unique<entropic::SqliteStorageBackend>(db_path);
726 if (h->storage->initialize()) {
727 s_log->info("storage: {}", db_path.string());
728 } else {
729 s_log->warn("storage init failed, continuing without persistence");
730 h->storage.reset();
731 }
732 // gh#32 (v2.1.6): wire StorageInterface into the engine so the
733 // create_delegation/save_conversation paths actually persist (they
734 // were dead code pre-2.1.6 because nothing populated the iface).
735 if (h->storage && h->engine) {
736 h->engine->set_storage(build_storage_iface(h->storage.get()));
737 }
738 h->session_logger = std::make_unique<entropic::SessionLogger>(
739 h->config.log_dir);
740}
741
759static std::vector<std::string> collect_delegatable_tiers(
760 const entropic::ParsedConfig& config) {
761 std::unordered_set<std::string> targets;
762 for (const auto& [source, dests] : config.routing.handoff_rules) {
763 for (const auto& t : dests) { targets.insert(t); }
764 }
765 if (targets.empty()) {
766 for (const auto& [name, tier] : config.models.tiers) {
767 if (name != config.models.default_tier) {
768 targets.insert(name);
769 }
770 }
771 }
772 return {targets.begin(), targets.end()};
773}
774
783 const std::filesystem::path& data_dir) {
784 auto root = h->config.mcp.working_dir.empty()
785 ? std::filesystem::current_path()
786 : std::filesystem::path(h->config.mcp.working_dir);
787 h->server_manager = std::make_unique<entropic::ServerManager>(
788 h->config.permissions, root);
789 auto tier_names = collect_delegatable_tiers(h->config);
790 h->server_manager->init_builtins(
791 h->config.mcp, tier_names, data_dir.string());
792}
793
802static std::string build_shared_prompt_prefix(
804 const std::filesystem::path& data_dir) {
805 std::string constitution, app_ctx;
806 entropic::prompts::load_constitution(
808 data_dir, constitution);
809 entropic::prompts::load_app_context(
811 data_dir, app_ctx);
812 std::string prefix;
813 if (!constitution.empty()) { prefix += constitution + "\n\n"; }
814 if (!app_ctx.empty()) { prefix += app_ctx + "\n\n"; }
815 return prefix;
816}
817
841 // gh#95 (v2.7.4): thread the identity `grammar:` key so the orchestrator's
842 // resolve_grammar_key() finds it and constrains the tier's generation.
843 // Without this the field is parsed but dropped here — registers OK, never
844 // enforces (same class as the gh#82/85/94 sampler-threading gaps).
845 if (fm.grammar.has_value()) {
846 tc.grammar = std::filesystem::path(*fm.grammar);
847 }
848 if (fm.temperature.has_value()) { tc.temperature = *fm.temperature; }
849 if (fm.max_output_tokens.has_value()) {
851 }
852 if (fm.top_p.has_value()) { tc.top_p = *fm.top_p; }
853 if (fm.top_k.has_value()) { tc.top_k = *fm.top_k; }
854 if (fm.min_p.has_value()) { tc.min_p = *fm.min_p; }
855 if (fm.presence_penalty.has_value()) {
857 }
858 if (fm.frequency_penalty.has_value()) {
860 }
861 // gh#86 (v2.5.4): repeat_penalty + enable_thinking.
862 if (fm.repeat_penalty.has_value()) { tc.repeat_penalty = *fm.repeat_penalty; }
863 if (fm.enable_thinking.has_value()) {
865 }
866}
867
878 const std::string& name,
880 if (fm.allowed_tools.has_value()) {
881 h->tier_allowed_tools[name] = *fm.allowed_tools;
882 }
883 if (!fm.validation_rules.empty()) {
885 }
886 if (fm.relay_single_delegate) {
887 h->engine->set_relay_single_delegate(name);
888 }
889 // gh#94 (v2.7.3): per-tier frontmatter SAMPLERS are threaded earlier, in
890 // thread_frontmatter_samplers() BEFORE init_orchestrator, so they land in
891 // the orchestrator's by-value config snapshot. Threading them HERE (after
892 // the snapshot) was the gh#94 ordering bug — the values reached h->config
893 // but never the orchestrator's frozen copy, so tiers ran defaults.
894}
895
905 const std::filesystem::path& data_dir) {
906 for (const auto& [name, tier] : h->config.models.tiers) {
907 std::filesystem::path id_path;
908 if (tier.identity.has_value()) {
909 id_path = tier.identity.value();
910 } else if (!tier.identity_disabled) {
911 id_path = data_dir / "prompts" / ("identity_" + name + ".md");
912 }
913 if (id_path.empty() || !std::filesystem::exists(id_path)) {
914 continue;
915 }
917 if (entropic::prompts::load_identity(id_path, id).empty()) {
918 apply_identity_frontmatter(h, name, id.frontmatter);
919 }
920 }
921 // gh#83 (v2.5.2): hand the populated allowlist map to the executor
922 // for dispatch-time enforcement. A pointer to the handle-owned map
923 // keeps this order-independent vs wire_tool_executor.
924 if (h->tool_executor) {
925 h->tool_executor->set_tier_allowed_tools(&h->tier_allowed_tools);
926 }
927}
928
950 const std::filesystem::path& data_dir) {
951 for (auto& [name, tier] : h->config.models.tiers) {
952 std::filesystem::path id_path;
953 if (tier.identity.has_value()) {
954 id_path = tier.identity.value();
955 } else if (!tier.identity_disabled) {
956 id_path = data_dir / "prompts" / ("identity_" + name + ".md");
957 }
958 if (id_path.empty() || !std::filesystem::exists(id_path)) {
959 continue;
960 }
962 if (entropic::prompts::load_identity(id_path, id).empty()) {
963 thread_frontmatter_sampler(tier, id.frontmatter);
964 }
965 }
966}
967
985static char* tool_history_json_thunk(size_t count, void* ud) {
986 auto* exec = static_cast<entropic::ToolExecutor*>(ud);
987 if (exec == nullptr) { return nullptr; }
988 auto s = exec->tool_history().to_json(count);
989 if (s.empty() || s == "[]") { return nullptr; }
990 auto* out = static_cast<char*>(std::malloc(s.size() + 1));
991 if (out != nullptr) {
992 std::memcpy(out, s.data(), s.size());
993 out[s.size()] = '\0';
994 }
995 return out;
996}
997
1010 h->tool_executor = std::make_unique<entropic::ToolExecutor>(
1011 *h->server_manager,
1012 h->engine->loop_config(),
1013 h->engine->callbacks(),
1014 h->engine->build_directive_hooks());
1017 const std::vector<entropic::ToolCall>& calls,
1018 void* ud) -> std::vector<entropic::Message> {
1019 return static_cast<entropic::ToolExecutor*>(ud)
1020 ->process_tool_calls(ctx, calls);
1021 };
1022 tei.user_data = h->tool_executor.get();
1024 tei.free_fn = [](char* p) { std::free(p); };
1025 h->engine->set_tool_executor(tei);
1026}
1027
1041static char* sp_get_validation(void* ud) {
1042 auto* h = static_cast<entropic_engine*>(ud);
1043 if (h == nullptr || h->validator == nullptr) { return nullptr; }
1044 auto r = h->validator->last_result();
1045 nlohmann::json v;
1046 v["ran"] = true;
1047 switch (r.verdict) {
1049 v["verdict"] = "passed"; break;
1051 v["verdict"] = "revised"; break;
1053 v["verdict"] = "rejected_reverted_length"; break;
1055 v["verdict"] = "rejected_max_revisions"; break;
1057 v["verdict"] = "skipped"; break;
1059 v["verdict"] = "paused_pending_consumer"; break;
1061 v["verdict"] = "passed_consumer_override"; break;
1062 }
1063 v["revisions_applied"] = r.revision_count;
1064 // gh#30 (v2.1.5): structured fields the consumer needs to render
1065 // a "retry / override / re-prompt" UI without parsing free-form
1066 // reason strings.
1067 v["attempt_n"] = r.attempt_n;
1068 nlohmann::json violations = nlohmann::json::array();
1069 for (const auto& vi : r.final_critique.violations) {
1070 violations.push_back({
1071 {"rule", vi.rule},
1072 {"rule_id", vi.rule}, // alias for gh#30 schema
1073 {"rule_text", vi.rule}, // alias for gh#30 schema
1074 {"excerpt", vi.excerpt},
1075 {"quote", vi.excerpt}, // alias matching gh#30 "evidence.quote"
1076 {"explanation", vi.explanation},
1077 {"severity", "error"}, // gh#30: hard rejection only today
1078 });
1079 }
1080 v["violations"] = violations;
1081 return strdup(v.dump().c_str());
1082}
1083
1101 entropic::InferenceInterface& iface,
1102 const std::string& constitution_text) {
1103 entropic::HookInterface hook_iface;
1104 hook_iface.registry = &h->hook_registry;
1105 hook_iface.fire_pre = [](void* reg, entropic_hook_point_t pt,
1106 const char* json, char** out) -> int {
1107 return static_cast<entropic::HookRegistry*>(reg)
1108 ->fire_pre(pt, json, out);
1109 };
1110 hook_iface.fire_post = [](void* reg, entropic_hook_point_t pt,
1111 const char* json, char** out) {
1112 static_cast<entropic::HookRegistry*>(reg)
1113 ->fire_post(pt, json, out);
1114 };
1115 hook_iface.fire_info = [](void* reg, entropic_hook_point_t pt,
1116 const char* json) {
1117 static_cast<entropic::HookRegistry*>(reg)->fire_info(pt, json);
1118 };
1119 h->engine->set_hooks(hook_iface);
1120 // E9 (2.0.6-rc19): forward the same hook dispatch to the tool
1121 // executor so PRE_TOOL_CALL / POST_TOOL_CALL actually fire.
1122 // Prior wiring only touched the engine; tool_executor_ held a
1123 // null HookInterface and silently skipped all tool hooks.
1124 if (h->tool_executor) {
1125 h->tool_executor->set_hooks(hook_iface);
1126 }
1127
1129 && !constitution_text.empty()) {
1130 h->validator = std::make_unique<entropic::ConstitutionalValidator>(
1131 h->config.constitutional_validation, constitution_text);
1132 h->validator->attach(&hook_iface, &iface);
1133 // E3 (2.0.6-rc17): expose validator verdict via ON_COMPLETE
1134 // hook context.
1135 h->engine->set_validation_provider(sp_get_validation, h);
1136 s_log->info("Constitutional validator attached (max_revisions={})",
1138 }
1139}
1140
1141// ── State provider callbacks ─────────────────────────────
1142
1148static char* sp_get_config(void* ud) {
1149 auto* h = static_cast<entropic_engine*>(ud);
1150 nlohmann::json j;
1151 j["default_tier"] = h->config.models.default_tier;
1152 j["log_level"] = h->config.log_level;
1153 j["log_dir"] = h->config.log_dir.string();
1154 j["ggml_logging"] = h->config.ggml_logging;
1155 return strdup(j.dump().c_str());
1156}
1157
1172 entropic_engine* h, const std::string& tier_name) {
1173 auto data_dir = entropic::config::resolve_data_dir(h->config);
1174 std::string constitution, app_ctx;
1175 entropic::prompts::load_constitution(
1177 data_dir, constitution);
1178 entropic::prompts::load_app_context(
1180 data_dir, app_ctx);
1181 std::string identity_body;
1182 auto it = h->config.models.tiers.find(tier_name);
1183 if (it != h->config.models.tiers.end()) {
1184 identity_body = entropic::prompts::resolve_tier_identity(
1185 it->second, tier_name, data_dir);
1186 }
1187 std::string out;
1188 if (!constitution.empty()) { out += constitution + "\n\n"; }
1189 if (!app_ctx.empty()) { out += app_ctx + "\n\n"; }
1190 if (!identity_body.empty()) { out += identity_body; }
1191
1192 // gh#87 (v2.7.0): tool defs are no longer string-injected into the
1193 // system prompt — they flow via params.tools and common_chat renders
1194 // them in the model's native format. So the assembled system-prompt
1195 // preview no longer includes a tool section.
1196 return out;
1197}
1198
1214static char* sp_get_identities(void* ud) {
1215 auto* h = static_cast<entropic_engine*>(ud);
1216 nlohmann::json arr = nlohmann::json::array();
1217 for (const auto& [name, _] : h->config.models.tiers) {
1218 nlohmann::json entry;
1219 entry["name"] = name;
1220 entry["assembled_prompt"] =
1222 arr.push_back(std::move(entry));
1223 }
1224 return strdup(arr.dump().c_str());
1225}
1226
1232static char* sp_get_tools(void* ud) {
1233 auto* h = static_cast<entropic_engine*>(ud);
1234 if (!h->server_manager) { return strdup("[]"); }
1235 return strdup(h->server_manager->list_tools().c_str());
1236}
1237
1256static char* sp_get_history(int max_entries, void* ud) {
1257 auto* h = static_cast<entropic_engine*>(ud);
1258 if (!h || !h->engine) { return strdup("[]"); }
1259 const auto& msgs = h->engine->get_messages();
1260 nlohmann::json arr = nlohmann::json::array();
1261 int start = 0;
1262 if (max_entries > 0
1263 && static_cast<int>(msgs.size()) > max_entries) {
1264 start = static_cast<int>(msgs.size()) - max_entries;
1265 }
1266 for (int i = start; i < static_cast<int>(msgs.size()); ++i) {
1267 const auto& m = msgs[static_cast<size_t>(i)];
1268 std::string preview = m.content.size() > 200
1269 ? entropic::facade::utf8_safe_substr(m.content, 200) + "..."
1270 : m.content;
1271 arr.push_back({
1272 {"role", m.role},
1273 {"content_preview", preview},
1274 {"token_count_est", m.content.size() / 4u}
1275 });
1276 }
1277 return strdup(arr.dump().c_str());
1278}
1279
1293static char* sp_get_residency(void* ud) {
1294 auto* h = static_cast<entropic_engine*>(ud);
1295 if (!h || !h->orchestrator) {
1296 return strdup("{\"vram_total_bytes\":0,\"vram_budget_bytes\":0,"
1297 "\"vram_headroom_bytes\":0,\"backend\":\"unknown\","
1298 "\"residency\":[]}");
1299 }
1300 return strdup(h->orchestrator->residency_snapshot_json().c_str());
1301}
1302
1308static char* sp_get_state(void* ud) {
1309 auto* h = static_cast<entropic_engine*>(ud);
1310 nlohmann::json j;
1311 j["engine_state"] = h->configured.load() ? "configured" : "init";
1312 j["default_tier"] = h->config.models.default_tier;
1313
1314 nlohmann::json tiers = nlohmann::json::array();
1315 for (const auto& [name, _] : h->config.models.tiers) {
1316 tiers.push_back(name);
1317 }
1318 j["active_tiers"] = tiers;
1319
1320 if (h->server_manager) {
1321 j["working_dir"] = h->server_manager->project_dir().string();
1322 j["registered_servers"] = h->server_manager->server_names();
1323 }
1324 j["data_dir"] = entropic::config::resolve_data_dir(
1325 h->config).string();
1326 j["log_dir"] = h->config.log_dir.string();
1327 return strdup(j.dump().c_str());
1328}
1329
1342static char* sp_get_metrics(void* ud) {
1343 auto* h = static_cast<entropic_engine*>(ud);
1344 if (!h || !h->engine) { return strdup("{}"); }
1345 auto m = h->engine->last_loop_metrics();
1346 nlohmann::json j;
1347 j["iterations"] = m.iterations;
1348 j["tool_calls"] = m.tool_calls;
1349 j["tokens_used"] = m.tokens_used;
1350 j["errors"] = m.errors;
1351 j["duration_ms"] = m.duration_ms();
1352 // Per-tier breakdown (P2-15 follow-up, 2.0.6-rc16.2)
1353 nlohmann::json per_tier = nlohmann::json::object();
1354 for (auto& [tier, tm] : h->engine->per_tier_metrics()) {
1355 per_tier[tier] = {
1356 {"iterations", tm.iterations},
1357 {"tool_calls", tm.tool_calls},
1358 {"tokens_used", tm.tokens_used},
1359 {"errors", tm.errors},
1360 {"duration_ms", tm.duration_ms()},
1361 };
1362 }
1363 j["per_tier"] = per_tier;
1364 return strdup(j.dump().c_str());
1365}
1366
1372static char* sp_get_docs(const char* section, void* ud) {
1373 (void)section;
1374 (void)ud;
1375 return strdup("");
1376}
1377
1388 const char* query, int max_results, void* ud) {
1389 auto* h = static_cast<entropic_engine*>(ud);
1390 if (h == nullptr || !h->storage || query == nullptr) {
1391 return nullptr;
1392 }
1393 std::string out;
1394 if (!h->storage->search_delegations(query, max_results, out)) {
1395 return nullptr;
1396 }
1397 return strdup(out.c_str());
1398}
1399
1410 const char* delegation_id, void* ud) {
1411 auto* h = static_cast<entropic_engine*>(ud);
1412 if (h == nullptr || !h->storage || delegation_id == nullptr) {
1413 return nullptr;
1414 }
1415 std::string out;
1417 delegation_id, out, h->storage.get())) {
1418 return nullptr;
1419 }
1420 return strdup(out.c_str());
1421}
1422
1435 if (!h->server_manager) { return; }
1436 auto* es = dynamic_cast<entropic::EntropicServer*>(
1437 h->server_manager->get_server("entropic"));
1438 if (es == nullptr) { return; }
1439
1442 sp.get_identities = sp_get_identities;
1443 sp.get_tools = sp_get_tools;
1444 sp.get_history = sp_get_history;
1445 sp.get_state = sp_get_state;
1446 sp.get_metrics = sp_get_metrics;
1447 sp.get_docs = sp_get_docs;
1448 // gh#32 (v2.1.6): storage-backed delegation recall + resume.
1449 sp.search_delegations = sp_search_delegations;
1450 sp.load_delegation_conversation = sp_load_delegation_conversation;
1451 // gh#57 (v2.2.4): VRAM residency-set snapshot.
1452 sp.get_residency = sp_get_residency;
1453 sp.user_data = h;
1454 es->set_state_provider(sp);
1455 s_log->info("State provider wired to entropic server");
1456}
1457
1465 if (!h->validator) { return; }
1466 for (const auto& [name, rules] : h->tier_validation_rules) {
1467 h->validator->set_tier_rules(name, rules);
1468 }
1469}
1470
1480 lc.stream_output = true;
1482 auto it = h->config.models.tiers.find(h->config.models.default_tier);
1483 if (it != h->config.models.tiers.end()) {
1484 lc.context_length = it->second.context_length;
1485 }
1486 // gh#80 (v2.5.0): map the generation.budget_mode string to the
1487 // BudgetMode enum. Unknown values resolve to off with a warning.
1488 const std::string& bm = h->config.generation.budget_mode;
1489 if (bm == "tokens") {
1491 } else if (bm == "wall_clock") {
1493 } else {
1494 if (bm != "off") {
1495 s_log->warn("Unknown generation.budget_mode '{}' — "
1496 "treating as 'off'", bm);
1497 }
1499 }
1501 // A non-positive limit can't gate anything — disable to avoid a
1502 // pathological "exhausted at zero" loop.
1503 if (lc.budget_limit <= 0) {
1505 }
1506 return lc;
1507}
1508
1521 if (!h->config.mcp.external.enabled) { return; }
1522 auto project_dir = h->config.config_dir.empty()
1523 ? std::filesystem::current_path()
1524 : h->config.config_dir;
1525 h->external_bridge = std::make_unique<entropic::ExternalBridge>(
1526 h, h->config.mcp.external, project_dir);
1527 if (!h->external_bridge->start()) {
1528 s_log->warn("External MCP bridge failed to start");
1529 h->external_bridge.reset();
1530 }
1531}
1532
1557 if (!h->configured.load()) { return ENTROPIC_OK; }
1558 h->last_error = "handle already configured";
1559 s_log->error("{}", h->last_error);
1561}
1562
1579 entropic_handle_t h, const std::filesystem::path& data_dir) {
1580 h->orchestrator = std::make_unique<entropic::ModelOrchestrator>();
1581 if (!h->orchestrator->initialize(h->config)) {
1582 h->last_error = "orchestrator initialization failed";
1583 s_log->error("{}", h->last_error);
1585 }
1586 // Fallback grammar loading: only if initialize() didn't find
1587 // grammars via config_dir. Avoids overwriting patched grammars.
1588 if (h->orchestrator->grammar_registry().size() == 0) {
1589 h->orchestrator->load_grammars_from(data_dir / "grammars");
1590 }
1591 return ENTROPIC_OK;
1592}
1593
1607 entropic_handle_t h, const std::filesystem::path& data_dir) {
1608 h->mcp_auth = std::make_unique<entropic::MCPAuthorizationManager>();
1609 h->identity_manager = std::make_unique<entropic::IdentityManager>(
1611 // P1-7: route identity changes to prompt-cache invalidation.
1612 h->identity_manager->set_cache_invalidator(
1613 [](void* ud) {
1614 auto* orch = static_cast<entropic::ModelOrchestrator*>(ud);
1615 if (orch) { orch->clear_all_prompt_caches(); }
1616 }, h->orchestrator.get());
1617 init_mcp_servers(h, data_dir);
1618
1619 // gh#58 follow-up (v2.2.6): per-handle InterfaceContext. Pre-v2.2.6
1620 // build_orchestrator_interface stored the context in a process-
1621 // global static, so a second configure freed the first handle's
1622 // context and h1.run() segfaulted on a use-after-free.
1626 h->inference_iface.get_tool_prompt = facade_get_tool_prompt;
1627 h->inference_iface.tool_prompt_data = h;
1628 auto lc = build_loop_config(h);
1629 h->engine = std::make_unique<entropic::AgentEngine>(
1630 h->inference_iface, lc, h->config.compaction);
1631 // gh#76 (v2.3.27): wire the compactor registry now that the engine
1632 // owns the CompactionManager that backs the default-compactor
1633 // fallback. Pre-v2.3.27 the field was declared but never
1634 // constructed, so every `entropic_register_compactor` /
1635 // `entropic_compact` call returned INVALID_STATE.
1637 std::make_unique<entropic::CompactorRegistry>(
1638 h->engine->compaction_manager());
1639 rewire_observers(h); // gh#40 + fallout (v2.1.10)
1640 wire_external_interrupt(h); // P1-10
1642}
1643
1655 entropic_handle_t h, const std::filesystem::path& data_dir) {
1656 auto shared_prefix = build_shared_prompt_prefix(h, data_dir);
1657 populate_tier_info(h, data_dir, shared_prefix);
1658 cache_tier_allowed_tools(h, data_dir);
1659 h->engine->set_handoff_rules(h->config.routing.handoff_rules);
1660
1661 wire_hooks_and_validator(h, h->inference_iface, shared_prefix);
1663
1666
1667 h->engine->set_system_prompt(
1668 entropic::prompts::assemble(h->config, data_dir));
1669 if (h->session_logger) {
1670 h->engine->set_session_logger(h->session_logger.get());
1671 }
1672}
1673
1680 if (auto rc = reject_if_configured(h); rc != ENTROPIC_OK) { return rc; }
1681 // gh#59 follow-up (v2.3.7): honor console_logging before any init
1682 // logging fires. When false, strip the stderr console sink so the
1683 // file sink (already installed by setup_session) is the only route
1684 // — TUI consumers paint to fd 2 and can't tolerate engine output
1685 // there. Default (true) is a no-op; operators keep stderr logs.
1686 entropic::log::set_console_enabled(h->config.console_logging);
1687 auto data_dir = entropic::config::resolve_data_dir(h->config);
1688 // gh#94 (v2.7.3): thread per-tier frontmatter samplers into the config
1689 // BEFORE the orchestrator snapshots it by value. The engine-bound
1690 // frontmatter wiring stays in wire_prompts_and_persistence (post-engine).
1691 thread_frontmatter_samplers(h, data_dir);
1692 if (auto rc = init_orchestrator(h, data_dir); rc != ENTROPIC_OK) {
1693 return rc;
1694 }
1695
1696 init_engine_and_interfaces(h, data_dir);
1697 wire_prompts_and_persistence(h, data_dir);
1698
1699 h->configured.store(true);
1701 s_log->info("configure complete");
1702 return ENTROPIC_OK;
1703}
1704
1711 entropic_handle_t handle, const char* config_json) {
1713 auto err = entropic::config::load_config_from_string(
1714 config_json, handle->bundled_models, handle->config);
1715 if (!err.empty()) {
1716 handle->last_error = err;
1717 s_log->error("configure: {}", err);
1719 }
1720 return configure_common(handle);
1721}
1722
1731 entropic_handle_t handle,
1732 const char* config_json) {
1733 if (!handle || !config_json) {
1734 return !handle ? ENTROPIC_ERROR_INVALID_HANDLE
1736 }
1737 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
1738 return c_api_try(handle,
1739 [&]() { return do_configure_json(handle, config_json); });
1740}
1741
1748 entropic_handle_t handle, const char* config_path) {
1750 auto err = entropic::config::load_config_from_file(
1751 config_path, handle->bundled_models, handle->config);
1752 if (!err.empty()) {
1753 handle->last_error = err;
1754 s_log->error("configure_from_file: {}", err);
1756 }
1757 // Parity with configure_dir: if the parsed config specifies a
1758 // log_dir, start session logging there. Without this, consumers
1759 // using the file-based API get no session.log on disk even when
1760 // their YAML declares log_dir.
1761 if (!handle->config.log_dir.empty()) {
1762 entropic::log::setup_session(handle->config.log_dir);
1763 // gh#59 (v2.3.1): per-handle dispatcher file sink so log lines
1764 // emitted within this handle's HandleLogScope route to this
1765 // handle's session.log only.
1766 entropic::log::register_handle_log(
1767 handle->log_id, handle->config.log_dir);
1768 }
1769 return configure_common(handle);
1770}
1771
1780 entropic_handle_t handle,
1781 const char* config_path) {
1782 if (!handle || !config_path) {
1783 return !handle ? ENTROPIC_ERROR_INVALID_HANDLE
1785 }
1786 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
1787 return c_api_try(handle,
1788 [&]() { return do_configure_from_file(handle, config_path); });
1789}
1790
1797 entropic_handle_t handle, const char* project_dir) {
1798 // Session logging FIRST — capture everything from preload through init.
1799 if (project_dir && project_dir[0] != '\0') {
1800 entropic::log::setup_session(project_dir);
1801 // gh#59 (v2.3.1): per-handle dispatcher registration. Routes
1802 // session.log writes for this handle's HandleLogScope-tagged
1803 // threads to this handle's file only — no cross-handle bleed.
1804 entropic::log::register_handle_log(handle->log_id, project_dir);
1805 }
1807 std::filesystem::path proj_dir = (project_dir && project_dir[0] != '\0')
1808 ? project_dir : "";
1809 auto err = entropic::config::load_layered(
1810 proj_dir, "default_config.yaml",
1811 handle->bundled_models, handle->config);
1812 if (!err.empty()) {
1813 handle->last_error = err;
1814 s_log->error("configure_dir: {}", err);
1816 }
1817 auto rc = configure_common(handle);
1818 // gh#31 (v2.1.6): propagate the configured project_dir into the
1819 // engine so `AgentEngine::get_repo_dir()` uses it as the sandbox
1820 // snapshot source.
1821 if (rc == ENTROPIC_OK && handle->engine && !proj_dir.empty()) {
1822 handle->engine->set_project_dir(std::filesystem::absolute(proj_dir));
1823 }
1824 return rc;
1825}
1826
1840 entropic_handle_t handle,
1841 const char* project_dir) {
1842 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
1843 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
1844 return c_api_try(handle,
1845 [&]() { return do_configure_dir(handle, project_dir); });
1846}
1847
1859 if (handle == nullptr) {
1860 return;
1861 }
1862 s_log->info("entropic_destroy()");
1863
1864 // Stop external bridge FIRST — it holds a raw pointer to handle
1865 if (handle->external_bridge) {
1866 handle->external_bridge->stop();
1867 handle->external_bridge.reset();
1868 }
1869
1871
1872 // gh#58 follow-up (v2.2.6): release per-handle InterfaceContext
1873 // before the orchestrator unloads, since the context holds a raw
1874 // orchestrator pointer used by the iface callbacks.
1876 handle->inference_iface_ctx = nullptr;
1877
1878 // gh#59 (v2.3.1): release the per-handle session.log file sink so
1879 // a subsequent handle that happens to reuse the same log_id can
1880 // open the file fresh. Safe on never-registered ids.
1881 entropic::log::unregister_handle_log(handle->log_id);
1882
1883 // Phase 1+ subsystem teardown will go here in reverse order.
1884 // Phase 0: struct itself owns hook_registry by value.
1885 delete handle;
1886}
1887
1894const char* entropic_version(void) {
1895 return CONFIG_ENTROPIC_VERSION_STRING;
1896}
1897
1905 return 2;
1906}
1907
1914 if (!handle || !handle->engine) { return 0; }
1915 return handle->engine->seconds_since_last_activity();
1916}
1917
1925void* entropic_alloc(size_t size) {
1926 return malloc(size);
1927}
1928
1935void entropic_free(void* ptr) {
1936 free(ptr);
1937}
1938
1956 entropic_handle_t handle,
1957 const char* input,
1958 char** result_json) {
1959 auto rc = check_orchestrator(handle);
1960 if (rc != ENTROPIC_OK || !input || !result_json || !handle->engine) {
1961 return rc != ENTROPIC_OK ? rc
1962 : (!input || !result_json) ? ENTROPIC_ERROR_INVALID_ARGUMENT
1964 }
1965 try {
1966 auto result = handle->engine->run_turn(input);
1967 *result_json = alloc_cstr(
1968 facade_json::serialize_messages(result));
1969 // Synthetic completion sentinel — lets observers detect the
1970 // end of a non-streaming run. Contract: (token="", len=0).
1971 // (P0-1, 2.0.6-rc16)
1972 if (handle->stream_observer != nullptr) {
1973 handle->stream_observer(
1974 "", 0, handle->stream_observer_data);
1975 }
1976 return ENTROPIC_OK;
1977 } catch (const std::exception& e) {
1978 handle->last_error = e.what();
1979 s_log->error("run: {}", handle->last_error);
1980 // P3-19 follow-up (2.0.6-rc16.2): surface partial context on
1981 // crash so callers can recover tool_results and any partial
1982 // assistant content accumulated before the failure.
1983 try {
1984 *result_json = alloc_cstr(
1985 facade_json::serialize_messages(
1986 handle->engine->get_messages()));
1987 } catch (...) {
1988 *result_json = nullptr;
1989 }
1991 }
1992}
1993
2003 entropic_handle_t handle, const char* tier, const char* input,
2004 char** result_json) {
2005 try {
2006 auto result = handle->engine->run_turn_as(tier, input);
2007 *result_json = alloc_cstr(facade_json::serialize_messages(result));
2008 // Synthetic completion sentinel (token="", len=0), matching run().
2009 if (handle->stream_observer != nullptr) {
2010 handle->stream_observer("", 0, handle->stream_observer_data);
2011 }
2012 return ENTROPIC_OK;
2013 } catch (const std::exception& e) {
2014 handle->last_error = e.what();
2015 s_log->error("run_as: {}", handle->last_error);
2016 // Define *result_json on the error path, matching entropic_run()'s
2017 // documented identical contract: surface partial context, else nullptr.
2018 try {
2019 *result_json = alloc_cstr(
2020 facade_json::serialize_messages(handle->engine->get_messages()));
2021 } catch (...) {
2022 *result_json = nullptr;
2023 }
2025 }
2026}
2027
2046 entropic_handle_t handle,
2047 const char* tier_or_identity,
2048 const char* input,
2049 char** result_json) {
2050 auto rc = check_orchestrator(handle);
2051 if (rc != ENTROPIC_OK || !tier_or_identity || !input || !result_json
2052 || !handle->engine) {
2053 return rc != ENTROPIC_OK ? rc
2054 : (!tier_or_identity || !input || !result_json)
2057 }
2058 if (!handle->engine->has_tier(tier_or_identity)) {
2059 handle->last_error =
2060 std::string("unknown tier: ") + tier_or_identity;
2061 s_log->error("run_as: {}", handle->last_error);
2063 }
2064 return run_as_inner(handle, tier_or_identity, input, result_json);
2065}
2066
2074static std::string serialize_batch_results(
2075 const std::vector<entropic::GenerationResult>& results) {
2076 nlohmann::json arr = nlohmann::json::array();
2077 for (const auto& r : results) {
2078 nlohmann::json obj;
2079 obj["content"] = r.content;
2080 obj["finish_reason"] = r.finish_reason;
2081 obj["tool_calls"] = nlohmann::json::parse(
2082 entropic::serialize_tool_calls(r.tool_calls), nullptr, false);
2083 arr.push_back(std::move(obj));
2084 }
2085 return arr.dump();
2086}
2087
2102static std::vector<std::vector<entropic::Message>> build_batch_messages(
2103 entropic_handle_t handle, const char** tiers, const char** prompts,
2104 size_t n, std::vector<std::string>& tiers_out) {
2105 std::vector<std::vector<entropic::Message>> msgs(n);
2106 tiers_out.resize(n);
2107 for (size_t i = 0; i < n; ++i) {
2108 tiers_out[i] = (tiers && tiers[i]) ? tiers[i] : "";
2109 const std::string& sys =
2110 handle->engine->tier_system_prompt(tiers_out[i]);
2111 std::vector<entropic::Message> m;
2112 if (!sys.empty()) {
2114 s.role = "system";
2115 s.content = sys;
2116 m.push_back(std::move(s));
2117 }
2119 u.role = "user";
2120 u.content = prompts[i] ? prompts[i] : "";
2121 m.push_back(std::move(u));
2122 msgs[i] = std::move(m);
2123 }
2124 return msgs;
2125}
2126
2146 entropic_handle_t handle,
2147 const char** tiers,
2148 const char** prompts,
2149 size_t n,
2150 char** result_json) {
2151 auto rc = check_orchestrator(handle);
2152 if (rc != ENTROPIC_OK || !prompts || !result_json || !handle->engine
2153 || n == 0) {
2154 return rc != ENTROPIC_OK ? rc
2155 : (!prompts || !result_json || n == 0)
2158 }
2159 try {
2160 std::vector<std::string> tiers_vec;
2161 auto msgs = build_batch_messages(handle, tiers, prompts, n, tiers_vec);
2162 std::vector<entropic::GenerationParams> params(n);
2163 std::atomic<bool> cancel{false};
2164 auto results = handle->orchestrator->generate_batch(
2165 msgs, params, tiers_vec, cancel);
2166 *result_json = alloc_cstr(serialize_batch_results(results));
2167 return ENTROPIC_OK;
2168 } catch (const std::exception& e) {
2169 handle->last_error = e.what();
2170 s_log->error("run_batch: {}", handle->last_error);
2171 // Define *result_json on the error path (C-ABI: output params must be
2172 // defined). No partial batch recovery — an empty JSON array.
2173 *result_json = alloc_cstr("[]");
2175 }
2176}
2177
2178/* StreamBridge + think filter moved to inference/stream_think_filter.cpp — Step 4 */
2179
2180/* StreamCtx + stream_chunk_cb → engine->run_streaming() — v2.0.2 */
2181
2195 entropic_handle_t handle,
2196 const char* input,
2197 void (*on_token)(const char* token, size_t len, void* user_data),
2198 void* user_data,
2199 int* cancel_flag) {
2200 auto rc = check_orchestrator(handle);
2201 if (rc != ENTROPIC_OK || !input || !on_token || !handle->engine) {
2202 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
2203 }
2204
2205 // Observer multiplexing is handled inside ResponseGenerator — the
2206 // facade passes on_token through untouched. (P0-1, 2.0.6-rc16)
2207 try {
2208 int code = handle->engine->run_streaming(
2209 input, on_token, user_data, cancel_flag);
2210 if (handle->stream_observer != nullptr) {
2211 handle->stream_observer(
2212 "", 0, handle->stream_observer_data);
2213 }
2214 return code == 1 ? ENTROPIC_ERROR_CANCELLED : ENTROPIC_OK;
2215 } catch (const std::exception& e) {
2216 handle->last_error = e.what();
2217 s_log->error("run_streaming: {}", handle->last_error);
2219 }
2220}
2221
2222// ── gh#37 (v2.1.8): multimodal messages entry points ──────────
2223
2241static std::vector<entropic::Message> parse_and_check_vision(
2242 entropic_handle_t handle,
2243 const char* messages_json,
2244 entropic_error_t& out_rc) {
2245 auto msgs = entropic::parse_messages_json(messages_json);
2247 && handle->orchestrator
2248 && !handle->orchestrator->has_vision_capable_tier()) {
2250 return {};
2251 }
2252 out_rc = ENTROPIC_OK;
2253 return msgs;
2254}
2255
2274 entropic_handle_t handle,
2275 const char* messages_json,
2276 char** result_json) {
2278 auto msgs = parse_and_check_vision(handle, messages_json, vrc);
2279 if (vrc != ENTROPIC_OK) { return vrc; }
2280 auto result = handle->engine->run_turn(std::move(msgs));
2281 *result_json = alloc_cstr(
2282 facade_json::serialize_messages(result));
2283 if (handle->stream_observer != nullptr) {
2284 handle->stream_observer(
2285 "", 0, handle->stream_observer_data);
2286 }
2287 return ENTROPIC_OK;
2288}
2289
2306 entropic_handle_t handle,
2307 const char* messages_json,
2308 char** result_json) {
2309 auto rc = check_orchestrator(handle);
2310 if (rc != ENTROPIC_OK
2311 || !messages_json || !result_json || !handle->engine) {
2312 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
2313 }
2314 try {
2315 return run_messages_inner(handle, messages_json, result_json);
2316 } catch (const std::exception& e) {
2317 handle->last_error = e.what();
2318 s_log->error("run_messages: {}", handle->last_error);
2320 }
2321}
2322
2334 entropic_handle_t handle,
2335 const char* messages_json,
2336 void (*on_token)(const char* token, size_t len, void* user_data),
2337 void* user_data,
2338 int* cancel_flag) {
2340 auto msgs = parse_and_check_vision(handle, messages_json, vrc);
2341 if (vrc != ENTROPIC_OK) { return vrc; }
2342 int code = handle->engine->run_streaming(
2343 std::move(msgs), on_token, user_data, cancel_flag);
2344 if (handle->stream_observer != nullptr) {
2345 handle->stream_observer(
2346 "", 0, handle->stream_observer_data);
2347 }
2348 return code == 1 ? ENTROPIC_ERROR_CANCELLED : ENTROPIC_OK;
2349}
2350
2369 entropic_handle_t handle,
2370 const char* messages_json,
2371 void (*on_token)(const char* token, size_t len, void* user_data),
2372 void* user_data,
2373 int* cancel_flag) {
2374 auto rc = check_orchestrator(handle);
2375 if (rc != ENTROPIC_OK
2376 || !messages_json || !on_token || !handle->engine) {
2377 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
2378 }
2379 try {
2381 handle, messages_json, on_token, user_data, cancel_flag);
2382 } catch (const std::exception& e) {
2383 handle->last_error = e.what();
2384 s_log->error("run_messages_streaming: {}", handle->last_error);
2386 }
2387}
2388
2399 entropic_handle_t handle,
2400 void (*observer)(const char* token, size_t len, void* user_data),
2401 void* user_data) {
2402 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2403 handle->stream_observer = observer;
2404 handle->stream_observer_data = user_data;
2405 // Propagate to engine so every generation path (streaming, batch,
2406 // and child-loop delegations) reaches the observer. (P0-1, 2.0.6-rc16)
2407 if (handle->engine) {
2408 handle->engine->set_stream_observer(observer, user_data);
2409 }
2410 return ENTROPIC_OK;
2411}
2412
2413// ── gh#30 (v2.1.5): validation retry controls ─────────────
2414
2421 entropic_handle_t handle, int enabled) {
2422 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2423 if (handle->validator) {
2424 handle->validator->set_auto_retry(enabled != 0);
2425 }
2426 return ENTROPIC_OK;
2427}
2428
2435 entropic_handle_t handle) {
2436 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2437 if (!handle->validator) { return ENTROPIC_ERROR_INVALID_STATE; }
2438 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2439 return handle->validator->resume_retry();
2440}
2441
2448 entropic_handle_t handle) {
2449 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2450 if (!handle->validator) { return ENTROPIC_ERROR_INVALID_STATE; }
2451 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2452 return handle->validator->accept_last();
2453}
2454
2461 entropic_handle_t handle,
2463 void* user_data) {
2464 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2465 if (handle->validator) {
2466 handle->validator->set_attempt_boundary_cb(cb, user_data);
2467 }
2468 return ENTROPIC_OK;
2469}
2470
2482 entropic_handle_t handle,
2483 ent_delegation_start_cb on_start,
2484 ent_delegation_complete_cb on_complete,
2485 void* user_data) {
2486 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2487 if (handle->engine) {
2488 handle->engine->set_delegation_callbacks(
2489 on_start, on_complete, user_data);
2490 }
2491 return ENTROPIC_OK;
2492}
2493
2511 entropic_handle_t handle,
2512 void (*observer)(int state, void* user_data),
2513 void* user_data) {
2514 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2515 handle->state_observer = observer;
2516 handle->state_observer_data = user_data;
2517 if (handle->engine) {
2518 // gh#40 fallout (v2.1.10): route through the engine's
2519 // persistent state-observer slot rather than the legacy
2520 // EngineCallbacks::on_state_change. The legacy path is
2521 // wiped by run_streaming's set_callbacks() shuffle, so
2522 // wiring there silently failed for streaming runs (the
2523 // exact bridge use case this API was designed for).
2524 handle->engine->set_state_observer(observer, user_data);
2525 }
2526 return ENTROPIC_OK;
2527}
2528
2548 entropic_handle_t handle,
2549 void (*start_cb)(void* user_data),
2550 void (*end_cb)(void* user_data),
2551 void* user_data) {
2552 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2553 handle->critique_start_cb = start_cb;
2554 handle->critique_end_cb = end_cb;
2555 handle->critique_cb_data = user_data;
2556 if (handle->validator) {
2557 handle->validator->set_critique_callbacks(
2558 start_cb, end_cb, user_data);
2559 }
2560 return ENTROPIC_OK;
2561}
2562
2572 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2573 if (!handle->engine) { return ENTROPIC_ERROR_INVALID_STATE; }
2574 handle->engine->interrupt();
2575 return ENTROPIC_OK;
2576}
2577
2578// ── Mid-generation user-message queue (gh#40, v2.1.10) ────────
2579
2593 entropic_handle_t handle, const char* message) {
2595 if (!handle) {
2597 } else if (!message) {
2599 } else if (!handle->engine || !handle->engine->is_running()) {
2601 } else if (!handle->engine->queue_user_message(message)) {
2603 }
2604 return rc;
2605}
2606
2613 entropic_handle_t handle, size_t* count) {
2614 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2615 if (!count) { return ENTROPIC_ERROR_INVALID_ARGUMENT; }
2616 *count = handle->engine
2617 ? handle->engine->user_message_queue_depth() : 0;
2618 return ENTROPIC_OK;
2619}
2620
2627 entropic_handle_t handle) {
2628 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2629 if (handle->engine) {
2630 handle->engine->clear_user_message_queue();
2631 }
2632 return ENTROPIC_OK;
2633}
2634
2647 entropic_handle_t handle,
2648 void (*observer)(const char*, size_t, void*),
2649 void* user_data) {
2650 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2651 handle->queue_observer = observer;
2652 handle->queue_observer_data = user_data;
2653 if (handle->engine) {
2654 handle->engine->set_queue_observer(observer, user_data);
2655 }
2656 return ENTROPIC_OK;
2657}
2658
2659// ── Conversation Context (v2.0.1) ────────────────────────────
2660
2669 if (!handle || !handle->engine) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2670 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2671 handle->engine->clear_conversation();
2672 return ENTROPIC_OK;
2673}
2674
2684 entropic_handle_t handle, char** messages_json) {
2685 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2686 if (!messages_json) { return ENTROPIC_ERROR_INVALID_ARGUMENT; }
2687 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2688 *messages_json = alloc_cstr(
2689 facade_json::serialize_messages(handle->engine->get_messages()));
2690 return ENTROPIC_OK;
2691}
2692
2702 entropic_handle_t handle, size_t* count) {
2703 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2704 if (!count) { return ENTROPIC_ERROR_INVALID_ARGUMENT; }
2705 *count = handle->engine->message_count();
2706 return ENTROPIC_OK;
2707}
2708
2724 entropic_handle_t handle,
2725 size_t* tokens_used,
2726 size_t* capacity) {
2727 if (!handle || !handle->engine) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2728 if (!tokens_used || !capacity) { return ENTROPIC_ERROR_INVALID_ARGUMENT; }
2729 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2730 auto [used, max] = handle->engine->context_usage(
2731 handle->engine->get_messages());
2732 *tokens_used = static_cast<size_t>(used);
2733 *capacity = static_cast<size_t>(max);
2734 return max > 0 ? ENTROPIC_OK : ENTROPIC_ERROR_INVALID_STATE;
2735}
2736
2743 entropic_handle_t handle, const char* tier_name, const char* path) {
2744 if (!handle->orchestrator) { return ENTROPIC_ERROR_INVALID_STATE; }
2745 auto* backend = require_active_backend(handle, tier_name);
2746 std::vector<uint8_t> buf;
2747 if (!backend->save_state(0, buf)) { return ENTROPIC_ERROR_INTERNAL; }
2748 std::ofstream out(path, std::ios::binary | std::ios::trunc);
2749 bool ok = out.is_open()
2750 && out.write(reinterpret_cast<const char*>(buf.data()),
2751 static_cast<std::streamsize>(buf.size())).good();
2752 return ok ? ENTROPIC_OK : ENTROPIC_ERROR_IO;
2753}
2754
2762 entropic_handle_t handle,
2763 const char* tier_name,
2764 const char* path) {
2765 if (!handle || !tier_name || !path) {
2766 return !handle ? ENTROPIC_ERROR_INVALID_HANDLE
2768 }
2769 entropic::HandleApiLock lock(handle);
2770 return c_api_try(handle,
2771 [&]() { return do_state_save(handle, tier_name, path); });
2772}
2773
2785static bool read_state_file(const char* path, std::vector<uint8_t>& out_buf) {
2786 std::ifstream in(path, std::ios::binary | std::ios::ate);
2787 if (!in.is_open()) { return false; }
2788 auto sz = static_cast<std::streamsize>(in.tellg());
2789 if (sz <= 0) { return false; }
2790 in.seekg(0, std::ios::beg);
2791 out_buf.resize(static_cast<size_t>(sz));
2792 return static_cast<bool>(
2793 in.read(reinterpret_cast<char*>(out_buf.data()), sz));
2794}
2795
2802 entropic_handle_t handle, const char* tier_name, const char* path) {
2803 if (!handle->orchestrator) { return ENTROPIC_ERROR_INVALID_STATE; }
2804 auto* backend = require_active_backend(handle, tier_name);
2805 std::vector<uint8_t> buf;
2806 if (!read_state_file(path, buf)) { return ENTROPIC_ERROR_IO; }
2807 return backend->restore_state(0, buf)
2809}
2810
2818 entropic_handle_t handle,
2819 const char* tier_name,
2820 const char* path) {
2821 if (!handle || !tier_name || !path) {
2822 return !handle ? ENTROPIC_ERROR_INVALID_HANDLE
2824 }
2825 entropic::HandleApiLock lock(handle);
2826 return c_api_try(handle,
2827 [&]() { return do_state_load(handle, tier_name, path); });
2828}
2829
2844 entropic_handle_t handle, char** out) {
2845 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
2846 if (!out) { return ENTROPIC_ERROR_INVALID_ARGUMENT; }
2847 *out = sp_get_metrics(handle);
2848 return ENTROPIC_OK;
2849}
2850
2851// ── LoRA Adapter APIs (v1.9.2 → v2.0.0) ────────────────────
2852
2866 entropic_handle_t handle,
2867 const char* adapter_name,
2868 const char* adapter_path,
2869 const char* base_model_path,
2870 float scale)
2871{
2872 auto rc = check_orchestrator(handle);
2873 if (rc != ENTROPIC_OK || !adapter_name || !adapter_path || !base_model_path) {
2874 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
2875 }
2876 try {
2877 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2878 auto tier = handle->config.models.find_tier_by_path(base_model_path);
2879 if (tier.empty()) {
2880 throw std::runtime_error("no tier for model: "
2881 + std::string(base_model_path));
2882 }
2883 auto* base = handle->orchestrator->get_backend(tier);
2884 auto* llama = dynamic_cast<entropic::LlamaCppBackend*>(base);
2885 if (!llama || !llama->llama_model_ptr()) {
2886 throw std::runtime_error("backend not ready for tier: " + tier);
2887 }
2888 bool ok = handle->orchestrator->adapter_manager().load(
2889 adapter_name, adapter_path, llama->llama_model_ptr(), scale);
2891 } catch (const std::exception& e) {
2892 handle->last_error = e.what();
2894 }
2895}
2896
2909 entropic_handle_t handle,
2910 const char* adapter_name)
2911{
2912 auto rc = check_orchestrator(handle);
2913 if (rc != ENTROPIC_OK || !adapter_name) {
2914 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
2915 }
2916 try {
2917 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2918 auto& mgr = handle->orchestrator->adapter_manager();
2919 auto info = mgr.info(adapter_name);
2920 if (info.state == entropic::AdapterState::COLD) {
2921 throw std::runtime_error("adapter not loaded: "
2922 + std::string(adapter_name));
2923 }
2924 auto tier = handle->orchestrator->last_used_tier();
2925 auto* base = handle->orchestrator->get_backend(tier);
2926 auto* llama = dynamic_cast<entropic::LlamaCppBackend*>(base);
2927 mgr.unload(adapter_name, llama ? llama->llama_context_ptr() : nullptr);
2928 return ENTROPIC_OK;
2929 } catch (const std::exception& e) {
2930 handle->last_error = e.what();
2932 }
2933}
2934
2947 entropic_handle_t handle,
2948 const char* adapter_name)
2949{
2950 auto rc = check_orchestrator(handle);
2951 if (rc != ENTROPIC_OK || !adapter_name) {
2952 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
2953 }
2954 try {
2955 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
2956 auto tier = handle->orchestrator->last_used_tier();
2957 auto* base = handle->orchestrator->get_backend(tier);
2958 auto* llama = dynamic_cast<entropic::LlamaCppBackend*>(base);
2959 if (!llama || !llama->llama_context_ptr()) {
2960 throw std::runtime_error("no active llama context for swap");
2961 }
2962 bool ok = handle->orchestrator->adapter_manager().swap(
2963 adapter_name, llama->llama_context_ptr());
2965 } catch (const std::exception& e) {
2966 handle->last_error = e.what();
2968 }
2969}
2970
2982 entropic_handle_t handle,
2983 const char* adapter_name)
2984{
2985 if (!handle || !handle->configured.load()
2986 || !handle->orchestrator || !adapter_name) {
2987 return -1;
2988 }
2989 try {
2990 auto st = handle->orchestrator->adapter_manager().state(adapter_name);
2991 return static_cast<int>(st);
2992 } catch (const std::exception& e) {
2993 handle->last_error = e.what();
2994 s_log->error("adapter_state: {}", handle->last_error);
2995 return -1;
2996 }
2997}
2998
3010 entropic_handle_t handle,
3011 const char* adapter_name)
3012{
3013 if (!handle || !handle->configured.load()
3014 || !handle->orchestrator || !adapter_name) {
3015 return nullptr;
3016 }
3017 try {
3018 auto ai = handle->orchestrator->adapter_manager().info(adapter_name);
3019 return alloc_cstr(
3020 facade_json::serialize_adapter_info(ai).c_str());
3021 } catch (const std::exception& e) {
3022 handle->last_error = e.what();
3023 s_log->error("adapter_info: {}", handle->last_error);
3024 return nullptr;
3025 }
3026}
3027
3039{
3040 if (!handle || !handle->configured.load() || !handle->orchestrator) {
3041 return nullptr;
3042 }
3043 try {
3044 auto adapters = handle->orchestrator->adapter_manager().list_adapters();
3045 return alloc_cstr(
3046 facade_json::serialize_adapter_list(adapters).c_str());
3047 } catch (const std::exception& e) {
3048 handle->last_error = e.what();
3049 s_log->error("adapter_list: {}", handle->last_error);
3050 return nullptr;
3051 }
3052}
3053
3054// ── Grammar Registry APIs (v1.9.3 → v2.0.0) ────────────────
3055
3069 entropic_handle_t handle,
3070 const char* key,
3071 const char* gbnf_content)
3072{
3073 auto rc = check_orchestrator(handle);
3074 if (rc != ENTROPIC_OK || !key || !gbnf_content) {
3075 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3076 }
3077 try {
3078 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3079 bool ok = handle->orchestrator->grammar_registry()
3080 .register_grammar(key, gbnf_content);
3081 s_log->info("grammar_register: key={} ok={}", key, ok);
3083 } catch (const std::exception& e) {
3084 handle->last_error = e.what();
3085 s_log->error("grammar_register: {}", handle->last_error);
3087 }
3088}
3089
3102 entropic_handle_t handle,
3103 const char* key,
3104 const char* path)
3105{
3106 auto rc = check_orchestrator(handle);
3107 if (rc != ENTROPIC_OK || !key || !path) {
3108 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3109 }
3110 try {
3111 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3112 bool ok = handle->orchestrator->grammar_registry()
3113 .register_from_file(key, path);
3114 s_log->info("grammar_register_file: key={} ok={}", key, ok);
3115 return ok ? ENTROPIC_OK : ENTROPIC_ERROR_IO;
3116 } catch (const std::exception& e) {
3117 handle->last_error = e.what();
3118 s_log->error("grammar_register_file: {}", handle->last_error);
3120 }
3121}
3122
3135 entropic_handle_t handle,
3136 const char* key)
3137{
3138 auto rc = check_orchestrator(handle);
3139 if (rc != ENTROPIC_OK || !key) {
3140 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3141 }
3142 try {
3143 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3144 bool ok = handle->orchestrator->grammar_registry().deregister(key);
3145 s_log->info("grammar_deregister: key={} ok={}", key, ok);
3147 } catch (const std::exception& e) {
3148 handle->last_error = e.what();
3149 s_log->error("grammar_deregister: {}", handle->last_error);
3151 }
3152}
3153
3165 entropic_handle_t handle,
3166 const char* key)
3167{
3168 if (!handle || !handle->configured.load()
3169 || !handle->orchestrator || !key) {
3170 return nullptr;
3171 }
3172 try {
3173 auto content = handle->orchestrator->grammar_registry().get(key);
3174 return content.empty() ? nullptr : alloc_cstr(content.c_str());
3175 } catch (const std::exception& e) {
3176 handle->last_error = e.what();
3177 s_log->error("grammar_get: {}", handle->last_error);
3178 return nullptr;
3179 }
3180}
3181
3193char* entropic_grammar_validate(const char* gbnf_content) {
3194 if (!gbnf_content) { return alloc_cstr("null input"); }
3195 try {
3196 auto err = entropic::GrammarRegistry::validate(gbnf_content);
3197 return err.empty() ? nullptr : alloc_cstr(err.c_str());
3198 } catch (const std::exception& e) {
3199 return alloc_cstr(e.what());
3200 }
3201}
3202
3215{
3216 if (!handle || !handle->configured.load() || !handle->orchestrator) {
3217 return nullptr;
3218 }
3219 try {
3220 auto entries = handle->orchestrator->grammar_registry().list();
3221 nlohmann::json arr = nlohmann::json::array();
3222 for (const auto& e : entries) {
3223 arr.push_back({{"key", e.key},
3224 {"source", e.source},
3225 {"validated", e.validated},
3226 {"error", e.error}});
3227 }
3228 return alloc_cstr(arr.dump().c_str());
3229 } catch (const std::exception& e) {
3230 handle->last_error = e.what();
3231 s_log->error("grammar_list: {}", handle->last_error);
3232 return nullptr;
3233 }
3234}
3235
3236// ── GPU Resource Profile APIs (v1.9.7 → v2.0.0) ─────────────
3237
3251 entropic_handle_t handle,
3252 const char* profile_json)
3253{
3254 auto rc = check_orchestrator(handle);
3255 if (rc != ENTROPIC_OK || !profile_json) {
3256 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3257 }
3258 try {
3259 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3260 auto j = nlohmann::json::parse(profile_json);
3262 p.name = j.value("name", "");
3263 if (p.name.empty()) { throw std::invalid_argument("missing 'name'"); }
3264 p.n_batch = j.value("n_batch", 512);
3265 p.n_threads = j.value("n_threads", 0);
3266 p.n_threads_batch = j.value("n_threads_batch", 0);
3267 p.description = j.value("description", "");
3268 bool ok = handle->orchestrator->profile_registry()
3269 .register_profile(p);
3270 s_log->info("profile_register: name={} ok={}", p.name, ok);
3272 } catch (const std::exception& e) {
3273 handle->last_error = e.what();
3274 s_log->error("profile_register: {}", handle->last_error);
3276 }
3277}
3278
3291 entropic_handle_t handle,
3292 const char* name)
3293{
3294 auto rc = check_orchestrator(handle);
3295 if (rc != ENTROPIC_OK || !name) {
3296 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3297 }
3298 try {
3299 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3300 bool ok = handle->orchestrator->profile_registry().deregister(name);
3301 s_log->info("profile_deregister: name={} ok={}", name, ok);
3303 } catch (const std::exception& e) {
3304 handle->last_error = e.what();
3305 s_log->error("profile_deregister: {}", handle->last_error);
3307 }
3308}
3309
3323 entropic_handle_t handle,
3324 const char* name)
3325{
3326 if (!handle || !handle->configured.load()
3327 || !handle->orchestrator || !name) {
3328 return nullptr;
3329 }
3330 try {
3331 auto p = handle->orchestrator->profile_registry().get(name);
3332 nlohmann::json j;
3333 j["name"] = p.name;
3334 j["n_batch"] = p.n_batch;
3335 j["n_threads"] = p.n_threads;
3336 j["n_threads_batch"] = p.n_threads_batch;
3337 j["description"] = p.description;
3338 return alloc_cstr(j.dump().c_str());
3339 } catch (const std::exception& e) {
3340 handle->last_error = e.what();
3341 s_log->error("profile_get: {}", handle->last_error);
3342 return nullptr;
3343 }
3344}
3345
3357{
3358 if (!handle || !handle->configured.load() || !handle->orchestrator) {
3359 return nullptr;
3360 }
3361 try {
3362 auto names = handle->orchestrator->profile_registry().list();
3363 nlohmann::json arr = nlohmann::json(names);
3364 return alloc_cstr(arr.dump().c_str());
3365 } catch (const std::exception& e) {
3366 handle->last_error = e.what();
3367 s_log->error("profile_list: {}", handle->last_error);
3368 return nullptr;
3369 }
3370}
3371
3372// ── Throughput Query APIs (v1.9.7 → v2.0.0) ─────────────────
3373
3387 entropic_handle_t handle,
3388 const char* model_path)
3389{
3390 (void)model_path;
3391 if (!handle || !handle->configured.load() || !handle->orchestrator) {
3392 return 0.0;
3393 }
3394 try {
3395 return handle->orchestrator->throughput_tracker().tok_per_sec();
3396 } catch (const std::exception& e) {
3397 handle->last_error = e.what();
3398 s_log->error("throughput_tok_per_sec: {}", handle->last_error);
3399 return 0.0;
3400 }
3401}
3402
3415 entropic_handle_t handle,
3416 const char* model_path)
3417{
3418 (void)model_path;
3419 if (!handle || !handle->configured.load() || !handle->orchestrator) {
3420 return;
3421 }
3422 try {
3423 handle->orchestrator->throughput_tracker().reset();
3424 s_log->info("throughput_reset: data cleared");
3425 } catch (const std::exception& e) {
3426 handle->last_error = e.what();
3427 s_log->error("throughput_reset: {}", handle->last_error);
3428 }
3429}
3430
3431// ── MCP Authorization APIs (v1.9.4 → v2.0.0) ────────────────
3432
3441 entropic_handle_t handle,
3442 const char* identity_name,
3443 const char* pattern,
3445{
3446 auto rc = check_mcp_auth(handle);
3447 if (rc != ENTROPIC_OK || !identity_name || !pattern) {
3448 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3449 }
3450 auto lvl = static_cast<entropic::MCPAccessLevel>(level);
3451 return handle->mcp_auth->grant(identity_name, pattern, lvl);
3452}
3453
3462 entropic_handle_t handle,
3463 const char* identity_name,
3464 const char* pattern)
3465{
3466 auto rc = check_mcp_auth(handle);
3467 if (rc != ENTROPIC_OK || !identity_name || !pattern) {
3468 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3469 }
3470 return handle->mcp_auth->revoke(identity_name, pattern);
3471}
3472
3481 entropic_handle_t handle,
3482 const char* identity_name,
3483 const char* tool_name,
3485{
3486 if (!handle || !handle->configured.load()
3487 || !handle->mcp_auth || !identity_name || !tool_name) {
3488 return -1;
3489 }
3490 auto lvl = static_cast<entropic::MCPAccessLevel>(level);
3491 return handle->mcp_auth->check_access(identity_name, tool_name, lvl) ? 1 : 0;
3492}
3493
3502 entropic_handle_t handle,
3503 const char* identity_name)
3504{
3505 if (!handle || !handle->configured.load()
3506 || !handle->mcp_auth || !identity_name) {
3507 return nullptr;
3508 }
3509 try {
3510 auto keys = handle->mcp_auth->list_keys(identity_name);
3511 nlohmann::json arr = nlohmann::json::array();
3512 for (const auto& k : keys) {
3513 arr.push_back({{"pattern", k.tool_pattern},
3514 {"level", static_cast<int>(k.level)}});
3515 }
3516 return alloc_cstr(arr.dump().c_str());
3517 } catch (const std::exception& e) {
3518 handle->last_error = e.what();
3519 return nullptr;
3520 }
3521}
3522
3531 entropic_handle_t handle,
3532 const char* granter,
3533 const char* grantee,
3534 const char* pattern,
3536{
3537 auto rc = check_mcp_auth(handle);
3538 if (rc != ENTROPIC_OK || !granter || !grantee || !pattern) {
3539 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3540 }
3541 auto lvl = static_cast<entropic::MCPAccessLevel>(level);
3542 return handle->mcp_auth->grant_from(granter, grantee, pattern, lvl);
3543}
3544
3553{
3554 if (!handle || !handle->configured.load() || !handle->mcp_auth) {
3555 return nullptr;
3556 }
3557 try {
3558 auto json = handle->mcp_auth->serialize_all();
3559 return alloc_cstr(json.c_str());
3560 } catch (const std::exception& e) {
3561 handle->last_error = e.what();
3562 return nullptr;
3563 }
3564}
3565
3574 entropic_handle_t handle,
3575 const char* json)
3576{
3577 auto rc = check_mcp_auth(handle);
3578 if (rc != ENTROPIC_OK || !json) {
3579 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3580 }
3581 bool ok = handle->mcp_auth->deserialize_all(json);
3583}
3584
3585// ── Dynamic Identity Management APIs (v1.9.6 → v2.0.0) ──────
3586
3595 entropic_handle_t handle,
3596 const char* config_json)
3597{
3598 auto rc = check_identity(handle);
3599 if (rc != ENTROPIC_OK || !config_json) {
3600 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3601 }
3602 try {
3603 auto j = nlohmann::json::parse(config_json);
3605 cfg.name = j.value("name", "");
3606 cfg.system_prompt = j.value("system_prompt", "");
3607 if (j.contains("focus") && j["focus"].is_array()) {
3608 cfg.focus = j["focus"].get<std::vector<std::string>>();
3609 }
3611 return handle->identity_manager->create(cfg);
3612 } catch (const std::exception& e) {
3613 handle->last_error = e.what();
3615 }
3616}
3617
3626 entropic_handle_t handle,
3627 const char* name,
3628 const char* config_json)
3629{
3630 auto rc = check_identity(handle);
3631 if (rc != ENTROPIC_OK || !name || !config_json) {
3632 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3633 }
3634 try {
3635 auto j = nlohmann::json::parse(config_json);
3637 cfg.name = name;
3638 cfg.system_prompt = j.value("system_prompt", "");
3639 if (j.contains("focus") && j["focus"].is_array()) {
3640 cfg.focus = j["focus"].get<std::vector<std::string>>();
3641 }
3643 return handle->identity_manager->update(name, cfg);
3644 } catch (const std::exception& e) {
3645 handle->last_error = e.what();
3647 }
3648}
3649
3658 entropic_handle_t handle,
3659 const char* name)
3660{
3661 auto rc = check_identity(handle);
3662 if (rc != ENTROPIC_OK || !name) {
3663 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3664 }
3665 return handle->identity_manager->destroy(name);
3666}
3667
3676 entropic_handle_t handle,
3677 const char* name)
3678{
3679 if (!handle || !handle->identity_manager || !name) { return nullptr; }
3680 try {
3681 auto* cfg = handle->identity_manager->get(name);
3682 if (!cfg) { throw std::runtime_error("identity not found"); }
3683 nlohmann::json j;
3684 j["name"] = cfg->name;
3685 j["system_prompt"] = cfg->system_prompt;
3686 j["origin"] = (cfg->origin == entropic::IdentityOrigin::STATIC)
3687 ? "static" : "dynamic";
3688 return alloc_cstr(j.dump().c_str());
3689 } catch (...) {
3690 return nullptr;
3691 }
3692}
3693
3702{
3703 if (!handle || !handle->identity_manager) { return nullptr; }
3704 try {
3705 auto names = handle->identity_manager->list();
3706 nlohmann::json arr(names);
3707 return alloc_cstr(arr.dump().c_str());
3708 } catch (...) {
3709 return nullptr;
3710 }
3711}
3712
3721 entropic_handle_t handle,
3722 size_t* total,
3723 size_t* dynamic)
3724{
3725 auto rc = check_identity(handle);
3726 if (rc != ENTROPIC_OK || !total) {
3727 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3728 }
3729 *total = handle->identity_manager->count();
3730 if (dynamic) { *dynamic = handle->identity_manager->count_dynamic(); }
3731 return ENTROPIC_OK;
3732}
3733
3734// ── Log-Probability Evaluation APIs (v1.9.10 → v2.0.0) ──────
3735
3748 entropic_handle_t handle,
3749 const char* model_id,
3750 const int32_t* tokens,
3751 int n_tokens,
3753{
3754 auto rc = check_orchestrator(handle);
3755 if (rc != ENTROPIC_OK || !model_id || !tokens || !result || n_tokens < 2) {
3756 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3757 }
3758 try {
3759 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3760 auto* backend = require_active_backend(handle, model_id);
3761 auto lr = backend->evaluate_logprobs(tokens, n_tokens);
3762 result->n_tokens = lr.n_tokens;
3763 result->n_logprobs = lr.n_logprobs;
3764 result->perplexity = lr.perplexity;
3765 result->total_logprob = lr.total_logprob;
3766 result->logprobs = static_cast<float*>(
3767 malloc(sizeof(float) * lr.logprobs.size()));
3768 std::copy(lr.logprobs.begin(), lr.logprobs.end(),
3769 result->logprobs);
3770 result->tokens = static_cast<int32_t*>(
3771 malloc(sizeof(int32_t) * lr.tokens.size()));
3772 std::copy(lr.tokens.begin(), lr.tokens.end(),
3773 result->tokens);
3774 return ENTROPIC_OK;
3775 } catch (const std::exception& e) {
3776 handle->last_error = e.what();
3777 s_log->error("get_logprobs: {}", handle->last_error);
3779 }
3780}
3781
3793 entropic_handle_t handle,
3794 const char* model_id,
3795 const int32_t* tokens,
3796 int n_tokens,
3797 float* perplexity)
3798{
3799 auto rc = check_orchestrator(handle);
3800 if (rc != ENTROPIC_OK || !model_id || !tokens || !perplexity || n_tokens < 2) {
3801 return rc != ENTROPIC_OK ? rc : ENTROPIC_ERROR_INVALID_ARGUMENT;
3802 }
3803 try {
3804 entropic::HandleApiLock lock(handle); // gh#59 v2.3.1: mutex + log scope
3805 auto* backend = require_active_backend(handle, model_id);
3806 *perplexity = backend->compute_perplexity(tokens, n_tokens);
3807 return ENTROPIC_OK;
3808 } catch (const std::exception& e) {
3809 handle->last_error = e.what();
3810 s_log->error("compute_perplexity: {}", handle->last_error);
3812 }
3813}
3814
3825{
3826 if (result == nullptr) {
3827 return;
3828 }
3829 free(result->logprobs);
3830 result->logprobs = nullptr;
3831 free(result->tokens);
3832 result->tokens = nullptr;
3833}
3834
3835// ── Vision Query API (v1.9.11 → v2.0.0) ─────────────────────
3836
3849 entropic_handle_t handle,
3850 const char* model_id)
3851{
3852 if (!handle || !handle->configured.load()
3853 || !handle->orchestrator || !model_id) {
3854 return 0;
3855 }
3856 try {
3857 auto* backend = handle->orchestrator->get_backend(model_id);
3858 return (backend && backend->supports(
3860 } catch (const std::exception& e) {
3861 handle->last_error = e.what();
3862 s_log->error("model_has_vision: {}", handle->last_error);
3863 return 0;
3864 }
3865}
3866
3867// ── Constitutional Validation APIs (v1.9.8 → v2.0.0) ────────
3868
3877 entropic_handle_t handle,
3878 bool enabled)
3879{
3880 if (!handle) { return ENTROPIC_ERROR_INVALID_HANDLE; }
3881 if (!handle->validator) { return ENTROPIC_ERROR_INVALID_STATE; }
3882 handle->validator->set_global_enabled(enabled);
3883 return ENTROPIC_OK;
3884}
3885
3894 entropic_handle_t handle,
3895 const char* identity_name,
3896 bool enabled)
3897{
3898 if (!handle || !handle->validator) {
3899 return !handle ? ENTROPIC_ERROR_INVALID_HANDLE
3901 }
3902 if (!identity_name) { return ENTROPIC_ERROR_INVALID_ARGUMENT; }
3903 handle->validator->set_identity_validation(identity_name, enabled);
3904 return ENTROPIC_OK;
3905}
3906
3915{
3916 if (!handle || !handle->validator) { return nullptr; }
3917 try {
3918 auto result = handle->validator->last_result();
3919 nlohmann::json j;
3920 j["content"] = result.content;
3921 j["was_revised"] = result.was_revised;
3922 j["revision_count"] = result.revision_count;
3923 return alloc_cstr(j.dump().c_str());
3924 } catch (...) {
3925 return nullptr;
3926 }
3927}
3928
3939 entropic_handle_t handle,
3940 char** prompt_out) {
3941 if (handle == nullptr || prompt_out == nullptr) {
3943 }
3944 (void)handle;
3945 static const char* prompt =
3946 "[SYSTEM DIRECTIVE: SELF-DIAGNOSIS]\n\n"
3947 "Analyze your recent actions and identify any issues. "
3948 "Follow these steps:\n\n"
3949 "1. Call entropic.diagnose to get a full engine state "
3950 "snapshot.\n"
3951 "2. Review the tool call history for:\n"
3952 " - Repeated failures (same tool, same error)\n"
3953 " - Duplicate tool calls (circuit breaker risk)\n"
3954 " - Tool calls that returned errors\n"
3955 " - Unexpected state (wrong phase, wrong tier)\n"
3956 "3. Review your reasoning for:\n"
3957 " - Actions that didn't achieve the stated goal\n"
3958 " - Unnecessary tool calls\n"
3959 " - Missing context that led to errors\n"
3960 "4. Produce a structured assessment:\n"
3961 " - FINDINGS: What went wrong (be specific)\n"
3962 " - ROOT CAUSE: Why it went wrong\n"
3963 " - RECOMMENDATION: What to do differently\n\n"
3964 "Be honest and specific. The goal is accurate "
3965 "self-assessment, not self-defense.\n";
3966 *prompt_out = alloc_cstr(prompt);
3967 return ENTROPIC_OK;
3968}
3969
3991 entropic_handle_t handle,
3992 int* compatible,
3993 char** diagnostic) {
3994 if (handle == nullptr || compatible == nullptr) {
3996 }
3997 if (!handle->orchestrator) {
3999 }
4000 auto info = handle->orchestrator->check_speculative_compat();
4001 *compatible = info.compatible ? 1 : 0;
4002 if (diagnostic != nullptr) {
4003 *diagnostic = info.compatible
4004 ? nullptr
4005 : alloc_cstr(info.diagnostic);
4006 }
4007 return ENTROPIC_OK;
4008}
4009
4010/* ── VRAM-aware tier residency (v2.2.4, gh#57) ─────────── */
4011
4025 entropic_handle_t handle,
4027 void* user_data) {
4028 if (handle == nullptr) { return ENTROPIC_ERROR_INVALID_HANDLE; }
4029 // Engine-not-configured (no orchestrator yet) and observer==nullptr
4030 // both collapse to a no-op set: pre-configure registration is
4031 // ignored (consumers must re-register after configure_*), and
4032 // an explicit nullptr clears any prior slot. Done as one branch
4033 // to stay under the knots return-count gate.
4035 if (observer != nullptr) {
4036 fn = [observer, user_data](
4038 const std::string& tier_name,
4039 const std::string& model_path,
4040 size_t footprint) {
4041 observer(static_cast<entropic_residency_event_t>(event),
4042 tier_name.c_str(),
4043 model_path.c_str(),
4044 footprint,
4045 user_data);
4046 };
4047 }
4048 if (handle->orchestrator) {
4049 handle->orchestrator->set_residency_observer(std::move(fn));
4050 }
4051 return ENTROPIC_OK;
4052}
4053
4067 entropic_handle_t handle,
4068 char** out_json) {
4070 if (handle == nullptr || out_json == nullptr) {
4072 } else if (!handle->orchestrator) {
4074 } else {
4075 std::string snapshot =
4076 handle->orchestrator->residency_snapshot_json();
4077 *out_json = alloc_cstr(snapshot);
4078 if (*out_json == nullptr) {
4080 }
4081 }
4082 return rc;
4083}
4084
4085} // extern "C"
gh#32 (v2.1.6) resume
static std::string validate(const std::string &gbnf_content)
Validate a GBNF grammar string.
gh#59 (v2.3.1): RAII guard combining api_mutex + log scope.
Thread-safe hook registration and dispatch.
int fire_pre(entropic_hook_point_t point, const char *context_json, char **out_json)
Fire pre-hooks.
void fire_post(entropic_hook_point_t point, const char *context_json, char **out_json)
Fire post-hooks.
void fire_info(entropic_hook_point_t point, const char *context_json)
Fire informational hooks (no modify, no cancel).
Concrete base class for inference backends (80% logic).
Definition backend.h:69
void unload()
Full unload (→ COLD).
Definition backend.cpp:139
LlamaCppBackend — common llama.cpp patterns (15% layer).
Multi-model lifecycle and routing orchestrator.
std::function< void(ResidencyEvent event, const std::string &tier_name, const std::string &model_path, size_t footprint)> ResidencyObserverFn
Residency observer callback type (internal C++ form).
void clear_all_prompt_caches()
Invalidate prompt/KV caches across every pooled backend.
ResidencyEvent
Residency observer event codes — mirror the C ABI enum entropic_residency_event_t exactly (LOADED=0,...
Manages MCP server instances and routes tool calls.
void interrupt_external_tools()
Abort in-flight tool calls across every external MCP client.
SQLite-based storage backend.
Definition backend.h:43
bool save_messages(const std::string &conversation_id, const std::string &messages_json)
Save messages to a conversation.
Definition backend.cpp:225
bool complete_delegation(const std::string &delegation_id, const std::string &status, const std::optional< std::string > &result_summary=std::nullopt)
Mark a delegation as completed or failed.
Definition backend.cpp:602
bool create_delegation(const std::string &parent_conversation_id, const std::string &delegating_tier, const std::string &target_tier, const std::string &task, int max_turns, std::string &delegation_id, std::string &child_conversation_id)
Create a delegation record with a child conversation.
Definition backend.cpp:540
bool save_snapshot(const std::string &conversation_id, const std::string &messages_json)
Save a pre-compaction snapshot of full conversation history.
Definition backend.cpp:774
std::string create_conversation(const std::string &title="New Conversation", const std::optional< std::string > &project_path=std::nullopt, const std::optional< std::string > &model_id=std::nullopt)
Create a new conversation.
Definition backend.cpp:131
std::string to_json(size_t count) const
Serialize recent entries to JSON array string.
Processes tool calls from model output.
const ToolCallHistory & tool_history() const
Access the tool-call history ring buffer.
std::string auto_discover_and_load()
Auto-discover and load bundled_models.yaml.
Private definition of the entropic_engine struct.
static entropic_error_t check_mcp_auth(entropic_handle_t h)
Check handle prerequisites for MCP auth APIs.
Definition entropic.cpp:179
static void thread_frontmatter_sampler(entropic::TierConfig &tc, const entropic::prompts::IdentityFrontmatter &fm)
Cache per-tier frontmatter fields (allowed_tools, validation_rules, relay).
Definition entropic.cpp:838
static entropic_error_t do_configure_dir(entropic_handle_t handle, const char *project_dir)
entropic_configure_dir body — wrapped by c_api_try.
static void apply_identity_frontmatter(entropic_handle_t h, const std::string &name, const entropic::prompts::IdentityFrontmatter &fm)
Apply a parsed identity's frontmatter to the engine handle.
Definition entropic.cpp:876
entropic_error_t entropic_run_messages(entropic_handle_t handle, const char *messages_json, char **result_json)
Blocking multimodal agentic run (gh#37, v2.1.8).
static entropic_error_t do_state_load(entropic_handle_t handle, const char *tier_name, const char *path)
Load tier's KV cache from file body (gh#23 v2.3.25).
entropic_error_t entropic_identity_count(entropic_handle_t handle, size_t *total, size_t *dynamic)
Get identity count (total and dynamic).
static bool si_create_delegation(const char *parent_id, const char *delegating_tier, const char *target_tier, const char *task, int max_turns, std::string &delegation_id, std::string &child_conversation_id, void *user_data)
Initialize persistence: storage + session logger.
Definition entropic.cpp:563
static entropic_error_t reject_if_configured(entropic_handle_t h)
Post-parse config setup: subsystem construction + wiring.
static std::vector< std::string > resolve_allowed_tools(entropic_engine *h, const std::string &tier)
Post-parse config setup: load bundled models, set configured.
Definition entropic.cpp:310
static entropic_error_t do_configure_json(entropic_handle_t handle, const char *config_json)
entropic_configure body — wrapped by c_api_try in the public entry.
static void start_external_bridge(entropic_handle_t h)
Start the external MCP bridge if enabled in config.
static char * sp_search_delegations(const char *query, int max_results, void *ud)
State provider: search_delegations (gh#32, v2.1.6).
entropic_error_t entropic_grammar_deregister(entropic_handle_t handle, const char *key)
Remove a grammar from the registry.
entropic_error_t entropic_context_usage(entropic_handle_t handle, size_t *tokens_used, size_t *capacity)
Read current context-window pressure (gh#39, v2.1.8).
char * entropic_adapter_list(entropic_handle_t handle)
List all known adapters as a JSON array.
entropic_error_t entropic_validation_resume_retry(entropic_handle_t handle)
Resume a paused constitutional revision pass.
static char * sp_load_delegation_conversation(const char *delegation_id, void *ud)
State provider: load_delegation_conversation (gh#32, v2.1.6).
static entropic_error_t run_messages_stream_inner(entropic_handle_t handle, const char *messages_json, void(*on_token)(const char *token, size_t len, void *user_data), void *user_data, int *cancel_flag)
Streaming multimodal run (gh#37, v2.1.8).
static char * sp_get_metrics(void *ud)
State provider: get_metrics.
static char * sp_get_state(void *ud)
State provider: get_state (runtime environment).
static void rewire_observers(entropic_handle_t h)
Re-bind every pre-configure observer to the new engine.
Definition entropic.cpp:502
entropic_error_t entropic_deserialize_mcp_keys(entropic_handle_t handle, const char *json)
Deserialize all identity key sets from JSON.
static char * sp_get_residency(void *ud)
State provider: get_residency — VRAM residency snapshot.
static std::string build_shared_prompt_prefix(entropic_handle_t h, const std::filesystem::path &data_dir)
Build shared system prompt prefix (constitution + app_context).
Definition entropic.cpp:802
entropic_error_t entropic_create(entropic_handle_t *handle)
Create a new engine instance.
Definition entropic.cpp:241
static void init_mcp_servers(entropic_handle_t h, const std::filesystem::path &data_dir)
Initialize MCP servers with resolved working directory.
Definition entropic.cpp:782
entropic_error_t entropic_grammar_register(entropic_handle_t handle, const char *key, const char *gbnf_content)
Register a grammar by key with GBNF content.
entropic_error_t entropic_set_stream_observer(entropic_handle_t handle, void(*observer)(const char *token, size_t len, void *user_data), void *user_data)
Set a global stream observer callback.
entropic_error_t entropic_validation_set_auto_retry(entropic_handle_t handle, int enabled)
Toggle automatic constitutional revision.
entropic_error_t entropic_update_identity(entropic_handle_t handle, const char *name, const char *config_json)
Update an existing dynamic identity.
entropic_error_t entropic_set_residency_observer(entropic_handle_t handle, entropic_residency_observer_t observer, void *user_data)
Register a residency observer on the orchestrator.
entropic_error_t entropic_metrics_json(entropic_handle_t handle, char **out)
Get loop metrics as JSON (flat + per_tier).
entropic_error_t entropic_validation_set_identity(entropic_handle_t handle, const char *identity_name, bool enabled)
Set per-identity validation override.
entropic_error_t entropic_grant_mcp_key_from(entropic_handle_t handle, const char *granter, const char *grantee, const char *pattern, entropic_mcp_access_level_t level)
Grant a key from one identity to another.
void entropic_free(void *ptr)
Free memory allocated by the engine.
entropic_error_t entropic_run_streaming(entropic_handle_t handle, const char *input, void(*on_token)(const char *token, size_t len, void *user_data), void *user_data, int *cancel_flag)
Streaming generation — delegates entirely to engine.
double entropic_throughput_tok_per_sec(entropic_handle_t handle, const char *model_path)
Get EWMA throughput estimate in tokens per second.
char * entropic_profile_get(entropic_handle_t handle, const char *name)
Get a GPU resource profile by name as JSON.
entropic_error_t entropic_validation_accept_last(entropic_handle_t handle)
Accept the last paused attempt as the final answer.
static void populate_tier_info(entropic_handle_t h, const std::filesystem::path &data_dir, const std::string &shared_prefix)
Register per-tier ChildContextInfo with the engine.
Definition entropic.cpp:522
static void init_persistence(entropic_handle_t h)
Initialize persistence: storage + session logger + StorageInterface.
Definition entropic.cpp:722
void entropic_throughput_reset(entropic_handle_t handle, const char *model_path)
Reset throughput tracking data.
entropic_error_t entropic_state_load(entropic_handle_t handle, const char *tier_name, const char *path)
Restore a tier's KV cache from a file (gh#23 v2.3.25).
static char * sp_get_docs(const char *section, void *ud)
State provider: get_docs.
static bool si_save_conversation(const char *conversation_id, const char *messages_json, void *user_data)
StorageInterface bridge: save_conversation trampoline.
Definition entropic.cpp:621
static void rewire_state_observer(entropic_handle_t h)
Propagate any pre-configure state observer to the new engine.
Definition entropic.cpp:462
static entropic_error_t run_as_inner(entropic_handle_t handle, const char *tier, const char *input, char **result_json)
Run + serialize for entropic_run_as (gh#99).
entropic_error_t entropic_set_critique_callbacks(entropic_handle_t handle, void(*start_cb)(void *user_data), void(*end_cb)(void *user_data), void *user_data)
Register critique start/end callbacks on the handle (gh#50, v2.1.12).
entropic_error_t entropic_queue_user_message(entropic_handle_t handle, const char *message)
Enqueue a follow-up user message while a run is in flight.
char * entropic_list_mcp_keys(entropic_handle_t handle, const char *identity_name)
List MCP keys for an identity as JSON array.
void entropic_destroy(entropic_handle_t handle)
Destroy an engine instance.
entropic_error_t entropic_adapter_load(entropic_handle_t handle, const char *adapter_name, const char *adapter_path, const char *base_model_path, float scale)
Load a LoRA adapter into RAM.
entropic_error_t entropic_run_batch(entropic_handle_t handle, const char **tiers, const char **prompts, size_t n, char **result_json)
Same-prefix batch run on a shared resident model (gh#98).
entropic_error_t entropic_validation_set_enabled(entropic_handle_t handle, bool enabled)
Enable or disable constitutional validation globally.
entropic_error_t entropic_configure_from_file(entropic_handle_t handle, const char *config_path)
Configure the engine from a YAML config file.
static std::vector< std::vector< entropic::Message > > build_batch_messages(entropic_handle_t handle, const char **tiers, const char **prompts, size_t n, std::vector< std::string > &tiers_out)
Build per-request messages for entropic_run_batch (gh#98).
static void thread_frontmatter_samplers(entropic_handle_t h, const std::filesystem::path &data_dir)
Thread per-tier frontmatter SAMPLERS into config pre-orchestrator.
Definition entropic.cpp:948
int entropic_adapter_state(entropic_handle_t handle, const char *adapter_name)
Query adapter lifecycle state.
static void rewire_critique_callbacks(entropic_handle_t h)
Propagate pre-configure critique callbacks to a newly- constructed ConstitutionalValidator (gh#50,...
Definition entropic.cpp:482
int64_t entropic_seconds_since_last_activity(entropic_handle_t handle)
gh#35: idle-time accessor for host-side idle-exit policies.
entropic_error_t entropic_set_state_observer(entropic_handle_t handle, void(*observer)(int state, void *user_data), void *user_data)
Register a state-change observer on the handle.
static void init_engine_and_interfaces(entropic_handle_t h, const std::filesystem::path &data_dir)
Build the engine + inference interfaces (configure step 2).
static void wire_hooks_and_validator(entropic_handle_t h, entropic::InferenceInterface &iface, const std::string &constitution_text)
Wire hook dispatch and attach the constitutional validator.
entropic_error_t entropic_grant_mcp_key(entropic_handle_t handle, const char *identity_name, const char *pattern, entropic_mcp_access_level_t level)
Grant an MCP tool key to an identity.
static entropic::LoopConfig build_loop_config(entropic_handle_t h)
Build LoopConfig from parsed config.
static entropic_error_t check_orchestrator(entropic_handle_t h)
Check handle prerequisites for orchestrator APIs.
Definition entropic.cpp:164
entropic_error_t entropic_context_count(entropic_handle_t handle, size_t *count)
Get conversation message count.
static void rewire_queue_observer(entropic_handle_t h)
Propagate any pre-configure queue observer to the new engine.
Definition entropic.cpp:443
char * entropic_validation_last_result(entropic_handle_t handle)
Get last validation result as JSON.
static char * sp_get_validation(void *ud)
Return the validator's last verdict as JSON for ON_COMPLETE.
char * entropic_grammar_validate(const char *gbnf_content)
Validate a GBNF grammar string without registering.
char * entropic_profile_list(entropic_handle_t handle)
List all registered profile names as a JSON array.
entropic_error_t entropic_compute_perplexity(entropic_handle_t handle, const char *model_id, const int32_t *tokens, int n_tokens, float *perplexity)
Compute perplexity for a token sequence.
entropic_error_t entropic_grammar_register_file(entropic_handle_t handle, const char *key, const char *path)
Register a grammar from a GBNF file.
static char * sp_get_config(void *ud)
State provider: get_config.
entropic_error_t entropic_speculative_compat(entropic_handle_t handle, int *compatible, char **diagnostic)
Query speculative-decoding compatibility for the configured target/draft pair.
entropic_error_t entropic_destroy_identity(entropic_handle_t handle, const char *name)
Destroy a dynamic identity.
static std::string serialize_batch_results(const std::vector< entropic::GenerationResult > &results)
Serialize batch results to a JSON array string (gh#98).
static entropic::InferenceBackend * require_active_backend(entropic_handle_t h, const char *tier_name)
Resolve tier name to an ACTIVE backend, or throw.
Definition entropic.cpp:213
static char * sp_get_history(int max_entries, void *ud)
State provider: get_history — conversation context snapshot.
int entropic_check_mcp_key(entropic_handle_t handle, const char *identity_name, const char *tool_name, entropic_mcp_access_level_t level)
Check MCP key authorization for an identity.
entropic_error_t entropic_run(entropic_handle_t handle, const char *input, char **result_json)
Single-turn blocking agentic run.
static void rewire_stream_observer(entropic_handle_t h)
Propagate any pre-configure stream observer to the new engine.
Definition entropic.cpp:424
char * entropic_adapter_info(entropic_handle_t handle, const char *adapter_name)
Get adapter info as JSON string.
static char * sp_get_tools(void *ud)
State provider: get_tools.
static entropic_error_t do_configure_from_file(entropic_handle_t handle, const char *config_path)
entropic_configure_from_file body — wrapped by c_api_try.
entropic_error_t entropic_configure(entropic_handle_t handle, const char *config_json)
Configure the engine from a JSON/YAML config string.
entropic_error_t entropic_profile_deregister(entropic_handle_t handle, const char *name)
Remove a GPU resource profile by name.
entropic_error_t entropic_set_queue_observer(entropic_handle_t handle, void(*observer)(const char *, size_t, void *), void *user_data)
Register the queue-consumption observer.
static std::vector< entropic::Message > parse_and_check_vision(entropic_handle_t handle, const char *messages_json, entropic_error_t &out_rc)
Parse messages_json and check vision-tier availability (gh#37/gh#41).
static char * tool_history_json_thunk(size_t count, void *ud)
Wire the ToolExecutor and attach it to the engine.
Definition entropic.cpp:985
static std::string build_assembled_prompt_for_tier(entropic_engine *h, const std::string &tier_name)
Build the assembled system prompt the engine would send for a given tier (constitution + app_context ...
static bool si_complete_delegation(const char *delegation_id, const char *status, const char *summary, void *user_data)
StorageInterface bridge: complete_delegation trampoline.
Definition entropic.cpp:605
static bool read_state_file(const char *path, std::vector< uint8_t > &out_buf)
Load tier's KV cache from file body (gh#23 v2.3.25).
entropic_error_t entropic_user_message_queue_depth(entropic_handle_t handle, size_t *count)
Snapshot the mid-gen queue depth.
static entropic_error_t init_orchestrator(entropic_handle_t h, const std::filesystem::path &data_dir)
Shared body of all entropic_configure* entry points.
char * entropic_grammar_get(entropic_handle_t handle, const char *key)
Get grammar GBNF content by key.
char * entropic_list_identities(entropic_handle_t handle)
List all identity names as JSON array.
entropic_error_t entropic_context_get(entropic_handle_t handle, char **messages_json)
Get conversation as JSON array.
entropic_error_t entropic_state_save(entropic_handle_t handle, const char *tier_name, const char *path)
Save a tier's KV cache to a file (gh#23 v2.3.25, MVP item 13).
entropic_error_t entropic_run_as(entropic_handle_t handle, const char *tier_or_identity, const char *input, char **result_json)
Single-turn blocking run under a named tier (gh#99).
static void wire_prompts_and_persistence(entropic_handle_t h, const std::filesystem::path &data_dir)
Assemble prompts + wire validation/persistence (config step 3).
static entropic_error_t configure_common(entropic_handle_t h)
Shared body of all entropic_configure* entry points.
entropic_error_t entropic_profile_register(entropic_handle_t handle, const char *profile_json)
Register a custom GPU resource profile from JSON.
char * entropic_serialize_mcp_keys(entropic_handle_t handle)
Serialize all identity key sets to JSON.
void entropic_free_logprob_result(entropic_logprob_result_t *result)
Free internal arrays of a logprob result.
entropic_error_t entropic_adapter_swap(entropic_handle_t handle, const char *adapter_name)
Swap active LoRA adapter.
static entropic_error_t run_messages_inner(entropic_handle_t handle, const char *messages_json, char **result_json)
Blocking multimodal run (gh#37, v2.1.8).
entropic_error_t entropic_set_delegation_callbacks(entropic_handle_t handle, ent_delegation_start_cb on_start, ent_delegation_complete_cb on_complete, void *user_data)
Register delegation start/complete callbacks (gh#29, v2.1.5).
entropic_error_t entropic_interrupt(entropic_handle_t handle)
Interrupt a running generation (thread-safe).
static std::vector< std::string > collect_delegatable_tiers(const entropic::ParsedConfig &config)
Collect valid delegation targets from handoff_rules.
Definition entropic.cpp:759
static std::vector< std::string > filter_tools(const nlohmann::json &all_tools, const std::vector< std::string > &allowed)
Filter tool definitions by allowed list.
Definition entropic.cpp:336
int entropic_model_has_vision(entropic_handle_t handle, const char *model_id)
Check if a model has vision (multimodal) capability.
entropic_error_t entropic_get_diagnostic_prompt(entropic_handle_t handle, char **prompt_out)
Get diagnostic prompt text for /diagnose command (stub).
static void wire_external_interrupt(entropic_handle_t h)
Wire engine interrupt propagation into MCP transports (P1-10).
Definition entropic.cpp:404
static entropic::StorageInterface build_storage_iface(entropic::SqliteStorageBackend *sb)
Build a populated StorageInterface bound to sb.
Definition entropic.cpp:704
static void cache_tier_allowed_tools(entropic_handle_t h, const std::filesystem::path &data_dir)
Cache per-tier frontmatter fields from identity files.
Definition entropic.cpp:903
const char * entropic_last_error(entropic_handle_t handle)
Read the per-handle last_error under api_mutex.
Definition entropic.cpp:150
entropic_error_t entropic_configure_dir(entropic_handle_t handle, const char *project_dir)
Configure using layered resolution (project dir).
entropic_error_t entropic_residency_snapshot(entropic_handle_t handle, char **out_json)
Return the engine's current residency-set snapshot as JSON.
entropic_error_t entropic_run_messages_streaming(entropic_handle_t handle, const char *messages_json, void(*on_token)(const char *token, size_t len, void *user_data), void *user_data, int *cancel_flag)
Streaming multimodal agentic run (gh#37, v2.1.8).
entropic_error_t entropic_context_clear(entropic_handle_t handle)
Clear conversation history.
static char * sp_get_identities(void *ud)
State provider: get_identities.
entropic_error_t entropic_create_identity(entropic_handle_t handle, const char *config_json)
Create a dynamic identity from JSON config.
entropic_error_t entropic_set_attempt_boundary_cb(entropic_handle_t handle, ent_validation_attempt_boundary_cb cb, void *user_data)
Register attempt-boundary callback on the validator.
int entropic_api_version(void)
Get the plugin API version number.
char * entropic_grammar_list(entropic_handle_t handle)
List all registered grammars as a JSON array.
static bool si_create_conversation(const char *title, std::string &conversation_id, void *user_data)
StorageInterface bridge: create_conversation trampoline.
Definition entropic.cpp:590
const char * entropic_version(void)
Get the library version string.
static entropic_error_t do_state_save(entropic_handle_t handle, const char *tier_name, const char *path)
Save tier's KV cache to file body (gh#23 v2.3.25).
static entropic_error_t check_identity(entropic_handle_t h)
Check handle prerequisites for identity manager APIs.
Definition entropic.cpp:194
static void wire_state_provider(entropic_handle_t h)
Wire state provider to the EntropicServer.
static int facade_get_tool_prompt(const char *tier, char **result, void *user_data)
Build formatted tool prompt for a tier.
Definition entropic.cpp:368
entropic_error_t entropic_get_logprobs(entropic_handle_t handle, const char *model_id, const int32_t *tokens, int n_tokens, entropic_logprob_result_t *result)
Evaluate per-token log-probabilities for a token sequence.
static void wire_tier_validation_rules(entropic_handle_t h)
Pass per-identity validation rules to the validator.
static void wire_tool_executor(entropic_handle_t h)
Wire the ToolExecutor and attach it to the engine.
static entropic_error_t c_api_try(entropic_handle_t handle, Fn &&fn)
Run a C-API entry-point body inside an exception barrier.
Definition entropic.cpp:75
entropic_error_t entropic_adapter_unload(entropic_handle_t handle, const char *adapter_name)
Unload a LoRA adapter.
static bool si_save_snapshot(const char *conversation_id, const char *messages_json, void *user_data)
StorageInterface bridge: save_snapshot trampoline.
Definition entropic.cpp:637
void * entropic_alloc(size_t size)
Allocate memory using the engine's allocator.
entropic_error_t entropic_clear_user_message_queue(entropic_handle_t handle)
Drop all queued mid-gen user messages.
entropic_error_t entropic_revoke_mcp_key(entropic_handle_t handle, const char *identity_name, const char *pattern)
Revoke an MCP tool key from an identity.
char * entropic_get_identity_config(entropic_handle_t handle, const char *name)
Get identity config as JSON by name.
static char * alloc_cstr(const char *src)
Allocate a C string copy via the engine allocator.
Definition entropic.cpp:106
static bool si_load_delegation_with_messages(const char *delegation_id, std::string &result_json, void *user_data)
StorageInterface bridge: load_delegation_with_messages.
Definition entropic.cpp:658
Public C API for the Entropic inference engine.
ent_decision_t(* ent_delegation_start_cb)(const ent_delegation_request_t *req, void *user_data)
Callback fired before a delegation runs.
Definition entropic.h:1058
ent_decision_t(* ent_delegation_complete_cb)(const ent_delegation_result_t *res, void *user_data)
Callback fired after a delegation produces a patch.
Definition entropic.h:1083
void(* entropic_residency_observer_t)(entropic_residency_event_t event, const char *tier_name, const char *model_path, size_t footprint_bytes, void *user_data)
Residency observer callback.
Definition entropic.h:748
entropic_residency_event_t
Reasons fired by entropic_residency_observer_t.
Definition entropic.h:723
entropic_mcp_access_level_t
Access level enum for MCP authorization.
Definition entropic.h:1744
void(* ent_validation_attempt_boundary_cb)(int attempt_n, void *user_data)
Stream-side callback fired between constitutional revision passes.
Definition entropic.h:1130
Entropic MCP server — engine-level tools including introspection.
entropic_error_t
Error codes returned by all C API functions.
Definition error.h:35
@ ENTROPIC_OK
Success.
Definition error.h:36
@ ENTROPIC_ERROR_NO_VISION_TIER
Image content present but no vision-capable tier (v2.1.8, gh#41)
Definition error.h:86
@ ENTROPIC_ERROR_ADAPTER_SWAP_FAILED
Swap failed (e.g., base model not ACTIVE) (v1.9.2)
Definition error.h:65
@ ENTROPIC_ERROR_CANCELLED
Operation cancelled via cancel token.
Definition error.h:48
@ ENTROPIC_ERROR_ALREADY_EXISTS
Named resource already exists (v1.9.6)
Definition error.h:71
@ ENTROPIC_ERROR_INTERNAL
Unexpected internal error (bug)
Definition error.h:51
@ ENTROPIC_ERROR_IDENTITY_NOT_FOUND
Identity name not in config (v1.8.9)
Definition error.h:58
@ ENTROPIC_ERROR_GRAMMAR_NOT_FOUND
Grammar key not in registry (v1.9.3)
Definition error.h:67
@ ENTROPIC_ERROR_INVALID_ARGUMENT
NULL pointer, empty string, out-of-range value.
Definition error.h:37
@ ENTROPIC_ERROR_QUEUE_FULL
Mid-gen user-message queue at capacity (v2.1.10, gh#40)
Definition error.h:87
@ ENTROPIC_ERROR_INVALID_HANDLE
NULL or destroyed handle (v1.8.9)
Definition error.h:55
@ ENTROPIC_ERROR_OUT_OF_MEMORY
Allocation failed (system RAM or VRAM)
Definition error.h:49
@ ENTROPIC_ERROR_EVAL_FAILED
Evaluation failed (llama_decode error) (v1.9.10)
Definition error.h:79
@ ENTROPIC_ERROR_ADAPTER_LOAD_FAILED
LoRA file invalid or incompatible with base model (v1.9.2)
Definition error.h:64
@ ENTROPIC_ERROR_PROFILE_NOT_FOUND
Profile name not in registry (v1.9.7)
Definition error.h:73
@ ENTROPIC_ERROR_IO
File/network I/O error.
Definition error.h:50
@ ENTROPIC_ERROR_GENERATE_FAILED
Generation failed (context overflow, model error)
Definition error.h:42
@ ENTROPIC_ERROR_INVALID_CONFIG
Config validation failed (missing fields, bad values)
Definition error.h:38
@ ENTROPIC_ERROR_INVALID_STATE
Operation not valid in current state (e.g., generate before activate)
Definition error.h:39
@ ENTROPIC_ERROR_LOAD_FAILED
Model load failed (corrupt file, OOM, unsupported format)
Definition error.h:41
entropic_hook_point_t
Hook points in the engine lifecycle.
Definition hooks.h:34
Pure C interface contract for inference backends.
void entropic_inference_log_silence(void)
Silence all llama/ggml log output.
Factory for building InferenceInterface from a ModelOrchestrator.
JSON serialization helpers for the facade.
LlamaCppBackend — llama.cpp C API integration.
Config loader — YAML to C++ structs with validation.
spdlog initialization and logger access.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
Definition logging.cpp:211
Prompt manager — frontmatter parsing, identity loading, assembly.
Shared parser: messages-JSON wire format → vector<Message>.
@ VISION
Vision / multimodal input (v1.9.11)
bool any_message_has_images(const std::vector< Message > &messages)
Convenience: true if any message carries image content_parts.
@ tokens
Gate on generated tokens since the last tool call.
@ off
Disabled (default) — no thinking-budget gating.
@ wall_clock
Gate on wall-clock seconds since the last tool call.
std::string serialize_tool_calls(const std::vector< ToolCall > &calls)
Serialize parsed tool calls to the C-ABI JSON array form.
@ passed_consumer_override
gh#30 (v2.1.5): consumer called accept_last() to override a paused rejection.
@ rejected_reverted_length
Revision gutted content >50%; original preserved.
@ passed
No violations, content unchanged.
@ revised
Violations found; revision applied.
@ paused_pending_consumer
gh#30 (v2.1.5): auto_retry disabled and a critique failed.
@ skipped
Validation did not run (skip_tiers / pure-tool-call / empty)
@ rejected_max_revisions
Revisions exhausted; last output returned as-is.
@ DYNAMIC
Created at runtime via API.
@ STATIC
Loaded from YAML frontmatter file at startup.
void destroy_orchestrator_interface(InterfaceContext *context)
Free a context returned by build_orchestrator_interface().
std::vector< Message > parse_messages_json(const char *json_str)
Parse a JSON array of messages into a vector of Message.
MCPAccessLevel
MCP tool access level for per-identity authorization.
Definition config.h:38
@ COLD
Not loaded. No resources consumed.
InferenceInterface build_orchestrator_interface(ModelOrchestrator *orchestrator, const std::string &default_tier, InterfaceContext **out_context)
Build an InferenceInterface wired to an orchestrator.
ModelOrchestrator — multi-model lifecycle and routing.
Resolved tier information for building child delegation contexts.
int max_revisions
Max re-generation attempts (0 = critique only)
Definition config.h:771
bool enabled
Global enable/disable (default OFF)
Definition config.h:770
bool enabled
Enable external MCP.
Definition config.h:613
Named GPU resource profile for controlling inference hardware knobs.
Definition config.h:290
int n_threads_batch
CPU threads for batch processing (0 = use n_threads)
Definition config.h:294
int n_batch
Batch size for prompt processing (1-2048)
Definition config.h:292
std::string name
Profile name ("maximum", "balanced", "background", "minimal")
Definition config.h:291
int n_threads
CPU threads for generation (0 = auto-detect)
Definition config.h:293
std::string description
Human-readable description.
Definition config.h:295
int budget_limit
gh#80 (v2.5.0) budget ceiling: generated tokens (budget_mode "tokens") or wall-clock seconds (budget_...
Definition config.h:730
std::string budget_mode
gh#80 (v2.5.0) thinking-budget mode: "off" (default), "tokens", or "wall_clock".
Definition config.h:723
Full identity configuration.
Definition identity.h:48
std::string name
Unique identity name (e.g., "eng", "npc_blacksmith")
Definition identity.h:49
std::vector< std::string > focus
Classification focus keywords (min 1)
Definition identity.h:51
IdentityOrigin origin
How this identity was created.
Definition identity.h:67
std::string system_prompt
Full system prompt text (markdown body)
Definition identity.h:50
Configuration for the identity manager.
Configuration for the agentic loop.
int budget_limit
Budget ceiling for the active budget_mode: generated tokens (mode tokens) or wall-clock seconds (mode...
int context_length
Context budget for compaction (v2.0.4)
bool stream_output
Stream vs batch generation.
bool auto_approve_tools
Skip tool approval (v1.8.5)
BudgetMode budget_mode
Thinking-budget gating mode (gh#80, v2.5.0).
Mutable state carried through the agentic loop.
ExternalMCPConfig external
External MCP server config (Entropic-as-server)
Definition config.h:652
std::string working_dir
Server working directory (empty = CWD) (v2.0.4)
Definition config.h:654
A message in a conversation.
Definition message.h:35
std::string content
Message text content (always populated)
Definition message.h:37
std::string role
Message role.
Definition message.h:36
std::unordered_map< std::string, TierConfig > tiers
Tier name → config.
Definition config.h:543
std::string find_tier_by_path(const std::filesystem::path &model_path) const
Find tier name by model path.
Definition config.h:558
std::string default_tier
Default tier name.
Definition config.h:545
Full parsed configuration.
Definition config.h:929
PermissionsConfig permissions
Tool permissions.
Definition config.h:933
std::optional< std::filesystem::path > app_context
App context: nullopt = disabled by default.
Definition config.h:946
CompactionConfig compaction
Auto-compaction settings.
Definition config.h:935
RoutingConfig routing
Routing rules.
Definition config.h:931
ModelsConfig models
Tiers + router.
Definition config.h:930
ConstitutionalValidationConfig constitutional_validation
Constitutional validation pipeline settings.
Definition config.h:981
std::filesystem::path log_dir
Session log directory (session.log + session_model.log).
Definition config.h:957
GenerationConfig generation
Default generation params.
Definition config.h:932
MCPConfig mcp
MCP server settings.
Definition config.h:934
bool console_logging
Emit engine spdlog output to the stderr console sink.
Definition config.h:978
bool app_context_disabled
true if app_context explicitly disabled
Definition config.h:947
std::optional< std::filesystem::path > constitution
Constitution: nullopt = bundled default, disabled = explicit false.
Definition config.h:942
bool constitution_disabled
true if constitution explicitly disabled
Definition config.h:943
std::filesystem::path config_dir
Config dir — base for bundled data discovery.
Definition config.h:953
bool auto_approve
Skip confirmation prompts.
Definition config.h:592
std::unordered_map< std::string, std::vector< std::string > > handoff_rules
Tier handoff rules.
Definition config.h:582
Storage interface for conversation persistence.
bool(* create_conversation)(const char *title, std::string &conversation_id, void *user_data)
Create a root conversation row.
Tier-specific model configuration.
Definition config.h:425
std::optional< float > frequency_penalty
gh#85
Definition config.h:478
std::optional< float > temperature
Per-tier sampler temperature from identity frontmatter (gh#82).
Definition config.h:462
std::optional< float > top_p
Per-tier sampler knobs from identity frontmatter (gh#85).
Definition config.h:474
std::optional< float > repeat_penalty
Per-tier repeat_penalty + enable_thinking from identity frontmatter (gh#86).
Definition config.h:485
std::optional< float > min_p
gh#85
Definition config.h:476
std::optional< float > presence_penalty
gh#85
Definition config.h:477
std::optional< int > max_output_tokens
Per-tier max output tokens from identity frontmatter (gh#82).
Definition config.h:467
std::optional< int > top_k
gh#85
Definition config.h:475
std::optional< bool > enable_thinking
gh#86
Definition config.h:486
std::optional< std::filesystem::path > grammar
Grammar file path.
Definition config.h:428
Tool execution interface for the engine.
void(* free_fn)(char *)
Free function for strings returned by history_json.
ToolExecutionFn process_tool_calls
Dispatches tool calls.
void * user_data
Opaque pointer (ToolExecutor*)
char *(* history_json)(size_t count, void *user_data)
Optional: return a compact JSON summary of recent tool calls (for validator retry enrichment / diagno...
Identity frontmatter — full tier identity metadata.
Definition manager.h:65
std::vector< std::string > validation_rules
Per-identity constitutional rules (v2.0.6)
Definition manager.h:88
std::optional< std::vector< std::string > > allowed_tools
Tool filter.
Definition manager.h:74
std::optional< float > top_p
Per-tier top_p (gh#85); nullopt = use param default.
Definition manager.h:78
std::optional< float > repeat_penalty
Per-tier repeat_penalty (gh#86); nullopt = use param default.
Definition manager.h:83
std::optional< float > min_p
Per-tier min_p (gh#85); nullopt = use param default.
Definition manager.h:80
std::optional< float > presence_penalty
Per-tier presence_penalty (gh#85); nullopt = use param default.
Definition manager.h:81
std::optional< bool > enable_thinking
Per-tier thinking mode (gh#86); nullopt = use param default.
Definition manager.h:84
std::optional< int > max_output_tokens
Per-tier max output tokens (gh#82); nullopt = use param default.
Definition manager.h:76
std::optional< int > top_k
Per-tier top_k (gh#85); nullopt = use param default.
Definition manager.h:79
bool relay_single_delegate
Skip re-synthesis when single delegate returns (v2.0.11)
Definition manager.h:89
std::optional< float > frequency_penalty
Per-tier frequency_penalty (gh#85); nullopt = use param default.
Definition manager.h:82
std::optional< std::string > grammar
Grammar file reference.
Definition manager.h:72
std::optional< float > temperature
Per-tier sampling temperature (gh#82); nullopt = use param default.
Definition manager.h:77
Parsed identity file: frontmatter + body.
Definition manager.h:110
Engine handle struct — owns all subsystems.
std::unique_ptr< entropic::ConstitutionalValidator > validator
Constitutional validation.
std::unique_ptr< entropic::ToolExecutor > tool_executor
Tool dispatch.
void(* critique_end_cb)(void *)
Fires after the critique generate returns.
int log_id
gh#59 (v2.3.1): unique handle id for per-handle log routing via entropic::log::HandleAwareSink.
std::unordered_map< std::string, std::vector< std::string > > tier_validation_rules
Per-tier validation_rules from identity frontmatter (v2.0.6).
std::unique_ptr< entropic::SqliteStorageBackend > storage
SQLite persistence.
entropic::InferenceInterface inference_iface
Stable copy for validator lifetime.
std::unique_ptr< entropic::SessionLogger > session_logger
Model transcript log.
std::unordered_map< std::string, std::vector< std::string > > tier_allowed_tools
Per-tier allowed_tools from identity frontmatter.
std::unique_ptr< entropic::CompactorRegistry > compactor_registry
Compaction strategies.
std::atomic< bool > configured
True after configure()
std::unique_ptr< entropic::ExternalBridge > external_bridge
Unix socket MCP bridge.
void(* state_observer)(int, void *)
Observer for engine state transitions.
entropic::config::BundledModels bundled_models
Model registry.
void * stream_observer_data
Observer user_data.
std::unique_ptr< entropic::IdentityManager > identity_manager
Identity lifecycle.
std::string last_error
Per-handle error message.
std::unique_ptr< entropic::AgentEngine > engine
Agentic loop (owns conversation state)
void * critique_cb_data
Forwarded to both callbacks.
std::unique_ptr< entropic::MCPAuthorizationManager > mcp_auth
Per-identity tool auth.
std::unique_ptr< entropic::ModelOrchestrator > orchestrator
Model pool + routing.
entropic::ParsedConfig config
Parsed config.
void(* stream_observer)(const char *, size_t, void *)
Global stream observer — fires for all streaming output.
void(* queue_observer)(const char *, size_t, void *)
Observer fired when a queued mid-gen user message is consumed and seeded as the next turn.
std::unique_ptr< entropic::ServerManager > server_manager
MCP server lifecycle.
entropic::InterfaceContext * inference_iface_ctx
Per-handle owned context backing inference_iface.user_data.
void(* critique_start_cb)(void *)
Fires before the constitutional validator's critique generate begins.
entropic::HookRegistry hook_registry
Hook dispatch.
Per-token log-probability result.
Definition entropic.h:2204
float perplexity
exp(-mean(logprobs)) over the sequence.
Definition entropic.h:2207
int32_t * tokens
Input tokens echoed back (N values).
Definition entropic.h:2206
int n_logprobs
Number of logprob values (n_tokens - 1).
Definition entropic.h:2210
int n_tokens
Number of input tokens.
Definition entropic.h:2209
float * logprobs
Per-token log-probabilities (N-1 values).
Definition entropic.h:2205
float total_logprob
Sum of all logprob values.
Definition entropic.h:2208
Read-only engine state provider for introspection tools.
char *(* get_config)(void *user_data)
Get current engine configuration as JSON.
UTF-8-boundary-aware string truncation helper for the facade.