21#include <nlohmann/json.hpp>
45 const std::filesystem::path& repo_dir,
47 : run_child_fn_(run_child),
48 run_child_data_(run_child_data),
49 tier_res_(tier_resolution),
50 sandbox_mgr_(sandbox_mgr),
61 todo_callbacks_ = callbacks;
73 swap_dir_fn_ = swap_fn;
74 swap_dir_data_ = user_data;
99 delegation_start_cb_ = on_start;
100 delegation_complete_cb_ = on_complete;
101 delegation_cb_data_ = user_data;
122 const std::string& delegation_id,
123 const std::string& target_tier,
124 const std::string& task,
127 if (delegation_start_cb_ ==
nullptr) {
128 return ENT_DECISION_ACCEPT;
132 req.target_tier = target_tier.c_str();
133 req.task = task.c_str();
135 req.is_pipeline = is_pipeline ? 1 : 0;
142 return delegation_start_cb_(&req, delegation_cb_data_);
144 logger->warn(
"delegation_start_cb threw for {}; treating as "
145 "REJECT (gh#29 exception shield)",
147 return ENT_DECISION_REJECT;
181 const std::vector<const char*>& files_c,
size_t files_len) {
185 res.success = result.
success ? 1 : 0;
186 res.summary = result.
summary.c_str();
187 res.patch = sandbox_result.
patch.c_str();
188 res.patch_len = sandbox_result.
patch.size();
189 res.files_touched = files_c.data();
190 res.files_touched_len = files_len;
199void DelegationManager::deliver_sandbox_result(
200 const SandboxInfo& sb_info,
201 const SandboxResult& sandbox_result,
202 const DelegationResult& result) {
204 if (delegation_complete_cb_ ==
nullptr) {
205 persist_pending_patch(sb_info, sandbox_result,
206 "no complete callback registered");
210 std::vector<std::string> files_owned;
211 files_owned.reserve(sandbox_result.files_touched.size());
212 for (
const auto& p : sandbox_result.files_touched) {
213 files_owned.push_back(p.string());
215 std::vector<const char*> files_c;
216 files_c.reserve(files_owned.size() + 1);
217 for (
const auto& s : files_owned) { files_c.push_back(s.c_str()); }
218 files_c.push_back(
nullptr);
221 sb_info, sandbox_result, result, files_c, files_owned.size());
224 invoke_complete_cb(res, sb_info.delegation_id);
225 if (decision == ENT_DECISION_REJECT) {
226 persist_pending_patch(sb_info, sandbox_result,
227 "consumer REJECTED");
229 logger->info(
"Delegation {}: consumer ACCEPTED ({} files, "
231 sb_info.delegation_id,
232 sandbox_result.files_touched.size(),
233 sandbox_result.patch.size());
251 return delegation_complete_cb_(&res, delegation_cb_data_);
253 logger->warn(
"delegation_complete_cb threw for {}; treating as "
254 "REJECT (patch preserved to pending/)", delegation_id);
255 return ENT_DECISION_REJECT;
264void DelegationManager::persist_pending_patch(
265 const SandboxInfo& sb_info,
266 const SandboxResult& sandbox_result,
267 const char* reason) {
269 sb_info.delegation_id, sandbox_result.patch);
271 logger->warn(
"Delegation {}: {}; patch saved to {} "
272 "({} files, {} bytes)",
273 sb_info.delegation_id, reason, path->string(),
274 sandbox_result.files_touched.size(),
275 sandbox_result.patch.size());
306std::optional<DelegationResult>
307DelegationManager::check_delegation_preconditions(
308 const ChildContextInfo& info,
309 const std::string& target_tier,
310 const std::string& task,
311 const std::string& del_id,
313 std::optional<SandboxInfo>& sb_info) {
314 std::optional<DelegationResult> early;
316 logger->error(
"Tier '{}' not found", target_tier);
317 early = DelegationResult{
318 "Unknown tier: " + target_tier,
false, target_tier, task};
319 }
else if (fire_start_cb(del_id, target_tier, task, depth,
false)
320 == ENT_DECISION_REJECT) {
321 logger->info(
"Delegation {} ({}) rejected by start callback",
322 del_id, target_tier);
323 early = DelegationResult{
324 "Delegation rejected by consumer",
false, target_tier, task};
325 }
else if (sandbox_mgr_ !=
nullptr) {
327 if (!sb_info.has_value()) {
334 "Delegation {} ({}): session sandbox unavailable",
335 del_id, target_tier);
336 early = DelegationResult{
337 "(DELEGATION FAILED: session sandbox unavailable)",
338 false, target_tier, task};
356 const std::string& target_tier,
357 const std::string& task,
358 std::optional<int> max_turns) {
360 logger->info(
"Delegation: target_tier='{}', task='{}', depth={}",
369 std::optional<SandboxInfo> sb_info;
370 if (
auto early = check_delegation_preconditions(
371 info, target_tier, task, del_id,
376 auto child_ctx = build_child_context(parent_ctx, info, task);
377 child_ctx.locked_tier = target_tier;
381 if (sb_info && swap_dir_fn_ !=
nullptr) {
383 sb_info->path, repo_dir_);
384 result = run_child(child_ctx, target_tier, task, max_turns);
386 result = run_child(child_ctx, target_tier, task, max_turns);
389 finalize_sandbox_for(sb_info, result);
418LoopContext DelegationManager::build_resumed_child_context(
421 const std::string& target_tier,
422 const std::string& task,
423 std::vector<Message> seed_history) {
433 child_ctx.
messages = std::move(seed_history);
434 bool has_system = !child_ctx.
messages.empty()
435 && child_ctx.
messages.front().role ==
"system";
436 if (!has_system && !info.system_prompt.empty()) {
439 sys.
content = info.system_prompt;
446 if (!info.completion_instructions.empty()) {
447 user.content +=
"\n\n" + info.completion_instructions;
449 child_ctx.
messages.push_back(std::move(user));
462 const std::string& target_tier,
463 const std::string& task,
464 std::vector<Message> seed_history,
465 std::optional<int> max_turns) {
467 logger->info(
"Resume delegation: target_tier='{}' task='{}' "
468 "history_messages={}",
469 target_tier, task, seed_history.size());
476 std::optional<SandboxInfo> sb_info;
477 if (
auto early = check_delegation_preconditions(
478 info, target_tier, task, del_id,
483 auto child_ctx = build_resumed_child_context(
484 parent_ctx, info, target_tier, task, std::move(seed_history));
487 if (sb_info && swap_dir_fn_ !=
nullptr) {
489 sb_info->path, repo_dir_);
490 result = run_child(child_ctx, target_tier, task, max_turns);
492 result = run_child(child_ctx, target_tier, task, max_turns);
494 finalize_sandbox_for(sb_info, result);
522 size_t stage_idx,
size_t total,
523 const std::vector<std::string>& stages,
524 const std::string& prior_output) {
525 std::string ctx =
"[PIPELINE CONTEXT]\n";
526 ctx +=
"Stage " + std::to_string(stage_idx + 1) +
527 " of " + std::to_string(total) +
"\n";
528 ctx +=
"Role: " + stages[stage_idx] +
"\n";
529 ctx +=
"Stay within your role. Do not perform work "
530 "outside your stage's responsibility.\n";
531 if (!prior_output.empty()) {
532 ctx +=
"\n[PRIOR STAGE OUTPUT]\n";
558 const std::vector<std::string>& stages,
559 const std::string& task,
560 std::vector<DelegationResult>& stage_log) {
562 logger->info(
"Pipeline: {} stages, task='{}'", stages.size(), task);
565 auto first = stages.empty() ? std::string{} : stages.front();
566 if (fire_start_cb(
"pipeline", first, task,
568 == ENT_DECISION_REJECT) {
569 logger->info(
"Pipeline rejected by start callback");
570 return {
"Pipeline rejected by consumer",
false, first, task};
576 std::optional<SandboxInfo> shared_sb;
577 if (sandbox_mgr_ !=
nullptr) {
579 if (!shared_sb.has_value()) {
582 "Pipeline ({} stages): session sandbox unavailable",
584 return {
"(DELEGATION FAILED: session sandbox unavailable)",
590 last_result.
task = task;
592 for (
size_t i = 0; i < stages.size(); ++i) {
593 if (!run_pipeline_stage(parent_ctx, stages, i, task,
594 shared_sb, stage_log, last_result)) {
599 finalize_sandbox_for(shared_sb, last_result);
622bool DelegationManager::run_pipeline_stage(
624 const std::vector<std::string>& stages,
626 const std::string& task,
627 const std::optional<SandboxInfo>& shared_sb,
628 std::vector<DelegationResult>& stage_log,
631 const auto& tier_name = stages[stage_idx];
632 std::string prior = (stage_idx == 0) ? std::string{} : last_result.
summary;
633 std::string stage_task =
638 : ChildContextInfo{};
641 logger->error(
"Pipeline stage {}: tier '{}' not found",
642 stage_idx, tier_name);
644 last_result.
summary =
"Unknown tier: " + tier_name;
648 auto child_ctx = build_child_context(parent_ctx, info, stage_task);
651 if (shared_sb && swap_dir_fn_ !=
nullptr) {
652 ScopedSandbox scope(swap_dir_fn_, swap_dir_data_,
653 shared_sb->path, repo_dir_);
654 last_result = run_child(child_ctx, tier_name, stage_task,
657 last_result = run_child(child_ctx, tier_name, stage_task,
661 stage_log.push_back(last_result);
662 logger->info(
"Pipeline stage {} ({}): {}", stage_idx, tier_name,
663 last_result.
success ?
"complete" :
"failed");
678LoopContext DelegationManager::build_child_context(
679 const LoopContext& parent_ctx,
680 const ChildContextInfo& info,
681 const std::string& task) {
684 child.delegation_depth = parent_ctx.delegation_depth + 1;
691 child.parent_conversation_id = parent_ctx.conversation_id;
694 child.delegation_ancestor_tiers = parent_ctx.delegation_ancestor_tiers;
695 if (!parent_ctx.locked_tier.empty()) {
696 child.delegation_ancestor_tiers.push_back(parent_ctx.locked_tier);
698 child.locked_tier = info.system_prompt.empty()
699 ? parent_ctx.locked_tier :
"";
700 child.all_tools = info.tools;
701 child.active_phase =
"default";
706 sys.content = info.system_prompt;
707 child.messages.push_back(std::move(sys));
710 std::string user_content = task;
711 if (!info.completion_instructions.empty()) {
712 user_content +=
"\n\n" + info.completion_instructions;
716 user.content = std::move(user_content);
717 child.messages.push_back(std::move(user));
729std::string DelegationManager::extract_summary(
730 const LoopContext& child_ctx)
const {
732 auto it = child_ctx.metadata.find(
"explicit_completion_summary");
733 if (it != child_ctx.metadata.end() && !it->second.empty()) {
734 return mcp::sanitize_utf8(it->second);
738 for (
auto rit = child_ctx.messages.rbegin();
739 rit != child_ctx.messages.rend(); ++rit) {
740 if (rit->role ==
"assistant" && !rit->content.empty()) {
741 return mcp::sanitize_utf8(rit->content);
745 return "(No response from delegate)";
768std::string DelegationManager::create_storage_record(
769 LoopContext& child_ctx,
const std::string& target_tier,
770 const std::string& task, std::optional<int> max_turns) {
774 std::string del_id, child_conv_id;
775 auto src_tier = child_ctx.locked_tier.empty()
776 ?
"root" : child_ctx.locked_tier.c_str();
778 child_ctx.parent_conversation_id.c_str(),
779 src_tier, target_tier.c_str(), task.c_str(),
780 max_turns.value_or(0), del_id, child_conv_id,
782 child_ctx.conversation_id = child_conv_id;
793void DelegationManager::complete_storage_record(
794 const std::string& delegation_id,
795 const DelegationResult& result) {
797 || delegation_id.empty()) {
800 const char* status = result.success ?
"completed" :
"failed";
802 delegation_id.c_str(), status,
803 result.summary.c_str(), storage_->
user_data);
816DelegationResult DelegationManager::run_child(
817 LoopContext& child_ctx,
818 const std::string& target_tier,
819 const std::string& task,
820 std::optional<int> max_turns) {
823 std::string saved_todo;
824 if (todo_callbacks_.
save !=
nullptr) {
825 saved_todo = todo_callbacks_.
save(todo_callbacks_.
user_data);
831 auto delegation_id = create_storage_record(
832 child_ctx, target_tier, task, max_turns);
834 logger->info(
"Running child loop: tier={} depth={} msgs={} "
835 "system_hash={:016x}",
836 target_tier, child_ctx.delegation_depth,
837 child_ctx.messages.size(),
838 std::hash<std::string>{}(
839 child_ctx.messages.empty()
841 : child_ctx.messages[0].content));
843 if (run_child_fn_ !=
nullptr) {
844 run_child_fn_(child_ctx, run_child_data_);
848 if (todo_callbacks_.
restore !=
nullptr && !saved_todo.empty()) {
852 auto result = build_child_result(
853 target_tier, task, child_ctx);
854 complete_storage_record(delegation_id, result);
855 log_child_result(result);
880DelegationResult DelegationManager::build_child_result(
881 const std::string& target_tier,
882 const std::string& task,
883 LoopContext& child_ctx) {
884 DelegationResult result;
885 result.target_tier = target_tier;
887 auto tr = child_ctx.metadata.find(
"terminal_reason");
888 if (tr != child_ctx.metadata.end()) {
889 result.terminal_reason = tr->second;
891 result.success = (child_ctx.state == AgentState::COMPLETE
892 && result.terminal_reason.empty());
893 result.turns_used = child_ctx.metrics.iterations;
894 result.summary = extract_summary(child_ctx);
900 auto cg = child_ctx.metadata.find(
"coverage_gap");
901 if (cg != child_ctx.metadata.end() && cg->second ==
"true") {
902 result.coverage_gap =
true;
903 auto gd = child_ctx.metadata.find(
"gap_description");
904 if (gd != child_ctx.metadata.end()) {
905 result.gap_description = gd->second;
907 auto sf = child_ctx.metadata.find(
"suggested_files_json");
908 if (sf != child_ctx.metadata.end()) {
909 auto parsed = nlohmann::json::parse(
910 sf->second,
nullptr,
false);
911 if (parsed.is_array()) {
912 result.suggested_files =
913 parsed.get<std::vector<std::string>>();
917 result.child_messages = std::move(child_ctx.messages);
927void DelegationManager::log_child_result(
928 const DelegationResult& result) {
929 if (result.terminal_reason.empty()) {
930 logger->info(
"Child loop done: tier={} success={} turns={}",
931 result.target_tier, result.success,
934 logger->warn(
"Child loop done: tier={} success=false "
935 "turns={} reason={}",
936 result.target_tier, result.turns_used,
937 result.terminal_reason);
956void DelegationManager::finalize_sandbox_for(
957 const std::optional<SandboxInfo>& sb_info,
958 const DelegationResult& result) {
959 if (!sb_info || !sandbox_mgr_) {
963 if (result.success) {
966 deliver_sandbox_result(*sb_info, *patch_result, result);
968 logger->error(
"Delegation {}: finalize_sandbox failed; "
969 "no patch delivered", sb_info->delegation_id);
972 logger->info(
"Delegation {} failed: discarding sandbox without "
973 "generating patch", sb_info->delegation_id);
DelegationResult execute_delegation(LoopContext &parent_ctx, const std::string &target_tier, const std::string &task, std::optional< int > max_turns=std::nullopt)
Run a child inference loop for the target tier.
DelegationResult execute_pipeline(LoopContext &parent_ctx, const std::vector< std::string > &stages, const std::string &task, std::vector< DelegationResult > &stage_log)
Run a multi-stage delegation pipeline sequentially.
void set_todo_callbacks(const TodoCallbacks &callbacks)
Set todo list save/restore callbacks.
DelegationResult execute_resume_delegation(LoopContext &parent_ctx, const std::string &target_tier, const std::string &task, std::vector< Message > seed_history, std::optional< int > max_turns=std::nullopt)
Resume a prior delegation with pre-loaded conversation history.
void set_dir_swap(ScopedSandbox::SwapDirFn swap_fn, void *user_data)
Set directory swap callback for ScopedSandbox.
DelegationManager(RunChildLoopFn run_child, void *run_child_data, const TierResolutionInterface &tier_resolution, const std::filesystem::path &repo_dir={}, SandboxManager *sandbox_mgr=nullptr)
Construct with engine loop callback and tier resolution.
void set_storage(const struct StorageInterface *storage)
Set storage interface for delegation record persistence.
void set_delegation_callbacks(ent_decision_t(*on_start)(const ent_delegation_request_t *, void *), ent_decision_t(*on_complete)(const ent_delegation_result_t *, void *), void *user_data)
Set delegation start/complete callbacks (gh#29, v2.1.5).
Create, finalize, and discard per-delegation filesystem sandboxes.
void discard_sandbox(const SandboxInfo &info)
Remove a sandbox directory.
std::optional< SandboxResult > finalize_sandbox(const SandboxInfo &info)
Produce the final patch artifact for a sandbox.
std::optional< SandboxInfo > create_sandbox(const std::string &delegation_id, std::optional< SandboxInfo > chain_from=std::nullopt)
Create a new delegation sandbox.
std::optional< std::filesystem::path > write_pending_patch(const std::string &delegation_id, const std::string &patch)
Write a patch to the session's pending/ directory.
RAII directory swapper for sandbox-scoped tool execution.
void(*)(const std::filesystem::path &path, void *user_data) SwapDirFn
Callback type for directory swapping.
DelegationManager — child loop creation and execution.
Types for the agentic loop engine.
ent_decision_t
Consumer decision returned from delegation callbacks.
spdlog initialization and logger access.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
Activate model on GPU (WARM → ACTIVE).
static std::string pipeline_context(size_t stage_idx, size_t total, const std::vector< std::string > &stages, const std::string &prior_output)
Build pipeline context prefix for a stage.
static ent_delegation_result_t build_delegation_result_struct(const SandboxInfo &sb_info, const SandboxResult &sandbox_result, const DelegationResult &result, const std::vector< const char * > &files_c, size_t files_len)
Deliver a finalized patch to consumer or pending/.
void(*)(LoopContext &ctx, void *user_data) RunChildLoopFn
Callback type for running a child engine loop.
Request describing a delegation that is about to run.
const char * delegation_id
Short id ("d1", "d2", "pipeline")
Result of a finalized delegation, delivered to the consumer.
const char * delegation_id
Short id (matches request)
Resolved tier information for building child delegation contexts.
Result returned from a child delegation loop.
bool success
Whether child reached COMPLETE via real entropic.complete.
std::string summary
Final summary from child.
std::string task
Original task text.
std::string target_tier
Tier that executed.
Mutable state carried through the agentic loop.
std::vector< std::string > delegation_ancestor_tiers
Tier stack from root to this loop (P1-9, 2.0.6-rc16)
std::string active_phase
Active inference phase.
std::string conversation_id
Conversation ID for storage (v1.8.8)
int delegation_depth
0 = root, 1+ = child
std::vector< Message > messages
Conversation history.
std::string locked_tier
Tier locked for this loop ("" = none)
std::string parent_conversation_id
Parent conv ID (delegation)
std::vector< std::string > all_tools
Full tool list as raw JSON strings.
A message in a conversation.
std::string content
Message text content (always populated)
std::string role
Message role.
Identifies one delegation's sandbox directory.
std::string delegation_id
Short delegation id (e.g. "d1", "pipeline")
Final artifact emitted by a finalized sandbox.
std::string patch
Unified diff text.
Storage interface for conversation persistence.
bool(* 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)
Create a delegation record with child conversation.
bool(* complete_delegation)(const char *delegation_id, const char *status, const char *summary, void *user_data)
Complete a delegation record.
void * user_data
Opaque pointer (storage backend)
Tier resolution callbacks for delegation and auto-chain.
void * user_data
Opaque pointer (facade context)
ChildContextInfo(* resolve_tier)(const std::string &tier_name, void *user_data)
Build context info for a child delegation to the given tier.
Callback type for saving/restoring todo list state.
std::string(* save)(void *user_data)
Save current todo list state. Returns opaque state string.
void(* restore)(const std::string &saved, void *user_data)
Restore a previously saved todo list state.
void(* install_fresh)(void *user_data)
Install a fresh empty todo list for child.
void * user_data
Opaque pointer (facade context)
UTF-8 validation + replacement at every system boundary where bytes change ownership.