engine.cpp¶
src/core/engine.cpp
@file engine.cpp @brief AgentEngine implementation — the agentic loop.
Owners: @tvanfossen
apply_identity_overrides
void entropic::AgentEngine::apply_identity_overrides(LoopContext &ctx)
Apply per-identity overrides to effective limits in the context.
src/core/engine.cpp:299
Source · 19 lines
void AgentEngine::apply_identity_overrides(LoopContext& ctx) {
if (ctx.locked_tier.empty() || tier_res_.get_tier_param == nullptr) {
return;
}
auto mi = tier_res_.get_tier_param(
ctx.locked_tier, "max_iterations", tier_res_.user_data);
if (!mi.empty()) {
ctx.effective_max_iterations = std::atoi(mi.c_str());
logger->info("[override] tier={} max_iterations={}",
ctx.locked_tier, ctx.effective_max_iterations);
}
auto mt = tier_res_.get_tier_param(
ctx.locked_tier, "max_tool_calls_per_turn", tier_res_.user_data);
if (!mt.empty()) {
ctx.effective_max_tool_calls_per_turn = std::atoi(mt.c_str());
logger->info("[override] tier={} max_tool_calls_per_turn={}",
ctx.locked_tier, ctx.effective_max_tool_calls_per_turn);
}
}Activity · 10 steps
Requirements
begin_loop_preamble
void entropic::AgentEngine::begin_loop_preamble(LoopContext &ctx)
The setup both loop entry points share (gh#183).
src/core/engine.cpp:389
Calls apply_identity_overrides, now_seconds, reinject_context_anchors, set_state
Source · 8 lines
void AgentEngine::begin_loop_preamble(LoopContext& ctx) {
apply_identity_overrides(ctx);
reinject_context_anchors(ctx);
if (ctx.metrics.start_time == 0.0) {
ctx.metrics.start_time = now_seconds();
}
set_state(ctx, AgentState::PLANNING);
}Activity · 5 steps
Requirements
bind_session_workspace
void entropic::AgentEngine::bind_session_workspace(const std::string &session, const std::string &workspace)
Record that session belongs to workspace .
src/core/engine.cpp:4078
Source · 5 lines
void AgentEngine::bind_session_workspace(const std::string& session,
const std::string& workspace) {
std::lock_guard<std::mutex> guard(prompt_mutex_);
session_workspace_[session] = workspace;
}Activity · 2 steps
Requirements
budget_units_consumed
int entropic::AgentEngine::budget_units_consumed(LoopContext &ctx, size_t content_len)
Accumulate + return budget units consumed this window.
src/core/engine.cpp:1016
Source · 17 lines
int AgentEngine::budget_units_consumed(LoopContext& ctx, size_t content_len) {
if (loop_config_.budget_mode == BudgetMode::tokens) {
// Estimate generated tokens from content length — the
// function-pointer inference ABI doesn't thread an exact count
// back. ~4 chars/token; content includes <think> blocks, which
// is exactly the deliberation we want to charge.
constexpr size_t kCharsPerToken = 4;
ctx.budget_tokens_since_tool +=
static_cast<int>(content_len / kCharsPerToken);
return ctx.budget_tokens_since_tool;
}
// wall_clock
if (ctx.budget_window_start_s == 0.0) {
ctx.budget_window_start_s = now_seconds();
}
return static_cast<int>(now_seconds() - ctx.budget_window_start_s);
}Activity · 7 steps
Requirements
build_coverage_gap_message
static std::string entropic::build_coverage_gap_message(const std::string &tier, const DelegationResult &result)
Build the [COVERAGE GAP] message body that goes back to lead when a relay-tier child returns coverage_gap=true (#10, v2.1.4).
src/core/engine.cpp:2910
Source · 14 lines
static std::string build_coverage_gap_message(
const std::string& tier, const DelegationResult& result) {
std::string body =
"[COVERAGE GAP from " + tier + "]\n"
"Summary so far: " + result.summary + "\n"
"What's missing: " + result.gap_description;
if (!result.suggested_files.empty()) {
body += "\nSuggested files to inspect:";
for (const auto& f : result.suggested_files) {
body += "\n - " + f;
}
}
return body;
}Activity · 6 steps
Requirements
build_tool_evidence
static std::string entropic::build_tool_evidence(const std::vector< Message > &messages, size_t max_results, size_t chars_per_result)
Build un-pruned tool-result evidence for the validator.
src/core/engine.cpp:2254
Source · 27 lines
static std::string build_tool_evidence(
const std::vector<Message>& messages,
size_t max_results,
size_t chars_per_result) {
std::vector<const Message*> tool_msgs;
for (const auto& msg : messages) {
auto it = msg.metadata.find("tool_name");
if (it == msg.metadata.end() || it->second.empty()) {
continue;
}
tool_msgs.push_back(&msg);
}
if (tool_msgs.empty()) { return {}; }
size_t elided = (tool_msgs.size() > max_results)
? (tool_msgs.size() - max_results) : 0;
size_t start = elided;
std::string out;
if (elided > 0) {
out += "(" + std::to_string(elided)
+ " earlier tool results elided for length)\n";
}
for (size_t i = start; i < tool_msgs.size(); ++i) {
out += format_tool_evidence_entry(*tool_msgs[i], chars_per_result);
}
return out;
}Activity · 16 steps
Requirements
build_tool_manifest
static std::string entropic::build_tool_manifest(const std::vector< Message > &messages)
Build tool call manifest from conversation messages.
src/core/engine.cpp:2170
Source · 23 lines
static std::string build_tool_manifest(
const std::vector<Message>& messages) {
std::string manifest;
for (const auto& msg : messages) {
auto it = msg.metadata.find("tool_name");
if (it == msg.metadata.end() || it->second.empty()) {
continue;
}
// Issue #5 (v2.1.3): when prune has stubbed this message, the
// original (pre-stub) content size is preserved in
// metadata["original_content"]. Report the real size so the
// validator sees accurate evidence sizes instead of the stub
// length (which is always ~50 chars regardless of original).
auto orig = msg.metadata.find("original_content");
size_t real_size = (orig != msg.metadata.end())
? orig->second.size()
: msg.content.size();
manifest += "- " + it->second
+ " \xe2\x86\x92 " + std::to_string(real_size)
+ " chars\n";
}
return manifest;
}Activity · 9 steps
Requirements
build_tool_results_json
static std::string entropic::build_tool_results_json(const std::vector< Message > &messages)
Build a JSON array of tool results from context messages.
src/core/engine.cpp:2454
Source · 18 lines
static std::string build_tool_results_json(
const std::vector<Message>& messages) {
std::string arr = "[";
bool first = true;
for (const auto& msg : messages) {
auto it = msg.metadata.find("tool_name");
if (it == msg.metadata.end() || it->second.empty()) {
continue;
}
if (!first) { arr += ","; }
arr += "{\"name\":\"" + json_escape_engine(it->second)
+ "\",\"content\":\"" + json_escape_engine(msg.content)
+ "\"}";
first = false;
}
arr += "]";
return arr;
}Activity · 12 steps
Requirements
cancel_pause
void entropic::AgentEngine::cancel_pause()
Cancel pause and interrupt completely.
src/core/engine.cpp:1604
Source · 5 lines
void AgentEngine::cancel_pause() {
logger->info("Pause cancelled, interrupting");
pause_flag_.store(false);
interrupt_flag_.store(true);
}Activity · 3 steps
Requirements
capture_validation_feedback
void entropic::AgentEngine::capture_validation_feedback(LoopContext &ctx)
Pull rejection text from validation_provider_ into ctx.pending_validation_feedback for the next turn.
src/core/engine.cpp:2417
Source · 25 lines
void AgentEngine::capture_validation_feedback(LoopContext& ctx) {
if (validation_provider_ == nullptr) { return; }
char* v = validation_provider_(validation_provider_data_);
if (v == nullptr) { return; }
std::string raw(v);
free(v);
try {
auto j = nlohmann::json::parse(raw);
auto verdict = j.value("verdict", "");
if (verdict.rfind("rejected", 0) != 0) { return; }
std::string joined;
if (j.contains("violations") && j["violations"].is_array()) {
for (const auto& vio : j["violations"]) {
if (!joined.empty()) { joined += "; "; }
joined += vio.is_string()
? vio.get<std::string>()
: vio.dump();
}
}
if (joined.empty()) { joined = verdict; }
ctx.pending_validation_feedback = joined;
} catch (const nlohmann::json::exception&) {
// Malformed provider output is non-fatal; just skip.
}
}Activity · 8 steps
Requirements
charge_thinking_budget
void entropic::AgentEngine::charge_thinking_budget(LoopContext &ctx, size_t content_len, bool made_tool_call)
Charge the thinking budget for this iteration.
src/core/engine.cpp:986
Called by process_generation_result
Calls budget_units_consumed, hard_cut_budget, nudge_budget_completion
Source · 22 lines
void AgentEngine::charge_thinking_budget(
LoopContext& ctx, size_t content_len, bool made_tool_call) {
if (loop_config_.budget_mode == BudgetMode::off) { return; }
// A tool call is productive action — reset the window and the
// nudge latch so the model earns a fresh thinking allowance.
if (made_tool_call) {
ctx.budget_tokens_since_tool = 0;
ctx.budget_window_start_s = 0.0;
ctx.budget_completion_nudged = false;
return;
}
int units = budget_units_consumed(ctx, content_len);
if (units < loop_config_.budget_limit) { return; }
if (!ctx.budget_completion_nudged) {
nudge_budget_completion(ctx);
} else {
hard_cut_budget(ctx);
}
}Activity · 14 steps
Requirements
clear_conversation_for
void entropic::AgentEngine::clear_conversation_for(const std::string &key)
Clear one session's history, keeping the session itself.
src/core/engine.cpp:4496
Source · 5 lines
void AgentEngine::clear_conversation_for(const std::string& key) {
std::lock_guard<std::mutex> guard(conversations_mutex_);
auto it = conversations_.find(key);
if (it != conversations_.end()) { it->second.clear(); }
}Activity · 4 steps
Requirements
clear_workspace_prompts
void entropic::AgentEngine::clear_workspace_prompts(const std::string &workspace)
Forget a workspace's prompts; its sessions fall back to the handle's.
src/core/engine.cpp:4064
Source · 6 lines
void AgentEngine::clear_workspace_prompts(const std::string& workspace) {
logger->info("[workspace] '{}' prompts cleared — its sessions use the "
"handle's", workspace);
std::lock_guard<std::mutex> guard(prompt_mutex_);
workspace_prompts_.erase(workspace);
}Activity · 3 steps
Requirements
context_usage
std::pair< int, int > entropic::AgentEngine::context_usage(const std::vector< Message > &messages) const
Get context usage for a message list.
src/core/engine.cpp:1617
Source · 5 lines
std::pair<int, int> AgentEngine::context_usage(
const std::vector<Message>& messages) const {
int used = token_counter_.count_messages(messages);
return {used, token_counter_.max_tokens};
}Activity · 2 steps
Requirements
defang_meta_action_envelope
void entropic::AgentEngine::defang_meta_action_envelope(Message &msg) const
gh#88: reshape a meta-tool {"action":...} result so the model is not primed to parrot the call-shaped envelope.
src/core/engine.cpp:2011
Source · 12 lines
void AgentEngine::defang_meta_action_envelope(Message& msg) const {
auto tn = msg.metadata.find("tool_name");
bool is_meta = tn != msg.metadata.end()
&& tn->second.rfind("entropic.", 0) == 0;
if (!is_meta) { return; }
auto j = nlohmann::json::parse(msg.content, nullptr, false);
bool is_envelope = j.is_object() && j.contains("action")
&& j["action"].is_string();
if (!is_envelope) { return; }
msg.content = "(engine: " + j["action"].get<std::string>()
+ " directive accepted)";
}Activity · 9 steps
Requirements
delegation_callbacks_snapshot
AgentEngine::DelegationCallbacks entropic::AgentEngine::delegation_callbacks_snapshot() const
Atomically snapshot the registered delegation callbacks.
src/core/engine.cpp:258
Source · 4 lines
AgentEngine::delegation_callbacks_snapshot() const {
std::lock_guard<std::mutex> lock(delegation_cb_mutex_);
return delegation_cb_;
}Activity · 2 steps
Requirements
dir_anchor
void entropic::AgentEngine::dir_anchor(LoopContext &, const Directive &, DirectiveResult &)
@utility
src/core/engine.cpp:1841
Source · 25 lines
void AgentEngine::dir_anchor(
LoopContext& ctx, const Directive& d, DirectiveResult&) {
const auto& ca = static_cast<const ContextAnchorDirective&>(d);
if (ca.content.empty()) {
{
std::lock_guard<std::mutex> guard(anchors_mutex_);
context_anchors_.erase(ca.key);
}
remove_anchor_messages(ctx, ca.key);
logger->info("Removed anchor: {}", ca.key);
return;
}
{
std::lock_guard<std::mutex> guard(anchors_mutex_);
context_anchors_[ca.key] = ca.content;
}
remove_anchor_messages(ctx, ca.key);
Message anchor;
anchor.role = "user";
anchor.content = ca.content;
anchor.metadata["is_context_anchor"] = "true";
anchor.metadata["anchor_key"] = ca.key;
ctx.messages.push_back(std::move(anchor));
logger->info("Updated anchor: {}", ca.key);
}Activity · 17 steps
Requirements
dir_complete
void entropic::AgentEngine::dir_complete(LoopContext &, const Directive &, DirectiveResult &)
@utility
src/core/engine.cpp:1752
Source · 37 lines
void AgentEngine::dir_complete(
LoopContext& ctx, const Directive& d, DirectiveResult& r) {
const auto& cd = static_cast<const CompleteDirective&>(d);
// P1-5 follow-up (2.0.6-rc16.2): signal validating phase so async
// subscribers can progress queued/running/running:<tier> → validating.
auto prior_state = ctx.state;
set_state(ctx, AgentState::VERIFYING);
// Fire ON_COMPLETE pre-hook — application can validate/reject
if (fire_complete_hook(cd.summary, ctx)) {
logger->info("[DIRECTIVE] complete REJECTED by hook → revising");
// Revision path: inform subscribers the validator is rewriting.
ctx.metadata["validator_phase"] = "revising";
set_state(ctx, prior_state);
r.stop_processing = false; // don't stop — model should retry
return;
}
ctx.metadata["explicit_completion_summary"] = cd.summary;
// Issue #10 (v2.1.4): persist coverage_gap signal in metadata so
// delegation.cpp::build_child_result can hoist it onto the
// DelegationResult that flows back to the parent. The metadata
// path is the only channel that survives between the child loop
// (which sees the directive) and the parent's
// finalize_delegation_result (which reads the result).
if (cd.coverage_gap) {
ctx.metadata["coverage_gap"] = "true";
ctx.metadata["gap_description"] = cd.gap_description;
nlohmann::json files_arr = cd.suggested_files;
ctx.metadata["suggested_files_json"] = files_arr.dump();
}
set_state(ctx, AgentState::COMPLETE);
r.stop_processing = true;
logger->info("[DIRECTIVE] complete coverage_gap={}",
cd.coverage_gap);
}Activity · 18 steps
Requirements
dir_delegate
void entropic::AgentEngine::dir_delegate(LoopContext &, const Directive &, DirectiveResult &)
@utility
src/core/engine.cpp:1709
Source · 18 lines
void AgentEngine::dir_delegate(
LoopContext& ctx, const Directive& d, DirectiveResult& r) {
const auto& dl = static_cast<const DelegateDirective&>(d);
ctx.pending_delegation = PendingDelegation{
dl.target, dl.task, dl.max_turns,
dl.resume_from_delegation_id,
dl.context, // gh#162 (v2.13.0)
dl.resume_by_target}; // gh#162 (v2.13.0)
r.stop_processing = true;
if (dl.resume_from_delegation_id.empty()) {
logger->info("[DIRECTIVE] delegate: target={} task='{}'",
dl.target, dl.task);
} else {
// gh#32 (v2.1.6): target will be resolved from storage later.
logger->info("[DIRECTIVE] resume_delegation: id={} task='{}'",
dl.resume_from_delegation_id, dl.task);
}
}Activity · 7 steps
Requirements
dir_pipeline
void entropic::AgentEngine::dir_pipeline(LoopContext &, const Directive &, DirectiveResult &)
@utility
src/core/engine.cpp:1733
Source · 7 lines
void AgentEngine::dir_pipeline(
LoopContext& ctx, const Directive& d, DirectiveResult& r) {
const auto& pl = static_cast<const PipelineDirective&>(d);
ctx.pending_pipeline = PendingPipeline{pl.stages, pl.task, pl.context};
r.stop_processing = true;
logger->info("[DIRECTIVE] pipeline: {} stages", pl.stages.size());
}Activity · 4 steps
Requirements
dir_prune
void entropic::AgentEngine::dir_prune(LoopContext &, const Directive &, DirectiveResult &)
@utility
src/core/engine.cpp:1822
Source · 7 lines
void AgentEngine::dir_prune(
LoopContext& ctx, const Directive& d, DirectiveResult&) {
const auto& pm = static_cast<const PruneMessagesDirective&>(d);
auto [pruned, freed] = context_manager_.prune_tool_results(
ctx, pm.keep_recent);
logger->info("[DIRECTIVE] prune: {} results, {} chars", pruned, freed);
}Activity · 3 steps
Requirements
dir_tier_change
void entropic::AgentEngine::dir_tier_change(LoopContext &, const Directive &, DirectiveResult &)
@utility
src/core/engine.cpp:1696
Source · 7 lines
void AgentEngine::dir_tier_change(
LoopContext& ctx, const Directive& d, DirectiveResult& r) {
const auto& tc = static_cast<const TierChangeDirective&>(d);
ctx.locked_tier = tc.tier;
r.tier_changed = true;
logger->info("[DIRECTIVE] tier_change: {}", tc.tier);
}Activity · 4 steps
Requirements
dispatch_pending_or_halt
void entropic::AgentEngine::dispatch_pending_or_halt(LoopContext &ctx)
Dispatch a queued delegation/pipeline, or halt the turn.
src/core/engine.cpp:1103
Called by process_generation_result
Calls execute_pending_delegation, execute_pending_pipeline, is_terminal_state, run_interrupted, set_state
Source · 27 lines
void AgentEngine::dispatch_pending_or_halt(LoopContext& ctx) {
if (run_interrupted() && !is_terminal_state(ctx)) {
logger->info("[ITER] interrupt observed during tool processing — "
"halting before pending dispatch");
set_state(ctx, AgentState::INTERRUPTED);
return;
}
if (is_terminal_state(ctx)) {
if (ctx.pending_delegation.has_value()
|| ctx.pending_pipeline.has_value()) {
logger->info("[ITER] terminal state reached during batch "
"tool processing — dropping pending {}",
ctx.pending_delegation.has_value()
? "delegation" : "pipeline");
}
return;
}
if (ctx.pending_delegation.has_value()) {
ctx.metrics.iterations--;
execute_pending_delegation(ctx);
} else if (ctx.pending_pipeline.has_value()) {
ctx.metrics.iterations--;
execute_pending_pipeline(ctx);
}
}Activity · 15 steps
Requirements
dispatch_post_generate
void entropic::AgentEngine::dispatch_post_generate(LoopContext &ctx, GenerateResult &result)
Run post-generate bookkeeping in one call.
src/core/engine.cpp:2398
Called by execute_iteration
Source · 13 lines
void AgentEngine::dispatch_post_generate(
LoopContext& ctx, GenerateResult& result) {
// The per-turn reminders built from pending_validation_feedback
// and pending_anti_spiral_warning were just consumed by
// generate_response — clear both so neither leaks into a later
// iteration. (#42, #45 — both one-shot.)
ctx.pending_validation_feedback.clear();
ctx.pending_anti_spiral_warning.clear();
fire_post_generate_hook(result, ctx.locked_tier, ctx.messages);
// After POST_GENERATE the validator may have rejected — stash
// its reason for the NEXT iteration's system prompt.
capture_validation_feedback(ctx);
}Activity · 4 steps
Requirements
drop_session
bool entropic::AgentEngine::drop_session(const std::string &key)
Forget a session entirely.
src/core/engine.cpp:4509
Source · 8 lines
bool AgentEngine::drop_session(const std::string& key) {
std::lock_guard<std::mutex> guard(conversations_mutex_);
if (key.empty()) {
conversations_[key].clear();
return true;
}
return conversations_.erase(key) > 0;
}Activity · 5 steps
Requirements
end_turn
void entropic::AgentEngine::end_turn(const std::string &key)
Release a turn claimed by try_begin_turn (gh#144 / gh#158).
src/core/engine.cpp:3848
Source · 17 lines
void AgentEngine::end_turn(const std::string& key) {
{
std::lock_guard<std::mutex> guard(runs_mutex_);
active_runs_.erase(key);
running_flag_.store(!active_runs_.empty());
// gh#217: an exclusive claim admits no other run, so the engine is
// empty exactly when the exclusive holder releases.
if (active_runs_.empty()) { exclusive_turn_ = false; }
}
// Releasing the claim releases the binding with it — see try_begin_turn.
// Guarded on the key so a nested release cannot unbind an outer run.
if (t_holds_claim && t_claimed_key == key) {
t_holds_claim = false;
t_active_session_bound = false;
t_active_session_key.clear();
}
}Activity · 9 steps
void entropic::AgentEngine::end_turn()
Release the turn this thread claimed (gh#158).
src/core/engine.cpp:3871
Source · 6 lines
void AgentEngine::end_turn() {
// Release by the key claimed on THIS thread. An unkeyed release that
// assumed `""` would free the wrong session for every pre-gh#158 call
// site the moment a consumer started naming sessions.
end_turn(t_holds_claim ? t_claimed_key : active_session_key());
}Activity · 1 steps
Requirements
ensure_sandbox_manager
SandboxManager * entropic::AgentEngine::ensure_sandbox_manager(const std::filesystem::path &root)
Lazily construct (or return) the session-scoped SandboxManager .
src/core/engine.cpp:3548
Source · 19 lines
SandboxManager* AgentEngine::ensure_sandbox_manager(
const std::filesystem::path& root) {
if (root.empty()) {
return nullptr;
}
std::lock_guard<std::mutex> guard(sandbox_mutex_);
auto it = sandbox_mgrs_.find(root);
if (it != sandbox_mgrs_.end()) {
return &it->second;
}
// piecewise_construct: SandboxManager holds a mutex and an atomic, so it
// is neither copyable nor movable — the map node must build it in place.
auto [pos, inserted] = sandbox_mgrs_.emplace(
std::piecewise_construct,
std::forward_as_tuple(root),
std::forward_as_tuple(root));
(void)inserted;
return &pos->second;
}Activity · 9 steps
Requirements
evaluate_no_tool_decision
void entropic::AgentEngine::evaluate_no_tool_decision(LoopContext &ctx, const std::string &content, const std::string &finish_reason)
Evaluate decision when no tool calls were effective.
src/core/engine.cpp:1139
Called by process_generation_result
Calls handle_terminal_finish_reasons, is_response_complete, record_explicit_completion_failure, set_state, try_auto_chain
Source · 17 lines
void AgentEngine::evaluate_no_tool_decision(
LoopContext& ctx,
const std::string& content,
const std::string& finish_reason) {
if (handle_terminal_finish_reasons(ctx, finish_reason)) { return; }
if (try_auto_chain(ctx, finish_reason, content)) {
logger->info("[DECISION] auto-chain triggered");
return;
}
if (record_explicit_completion_failure(ctx, finish_reason, content)) {
return;
}
if (response_generator_.is_response_complete(content, "[]")) {
logger->info("[DECISION] response complete");
set_state(ctx, AgentState::COMPLETE);
}
}Activity · 10 steps
Requirements
execute_iteration
void entropic::AgentEngine::execute_iteration(LoopContext &ctx)
Execute a single loop iteration.
src/core/engine.cpp:886
Called by loop
Calls agent_state_name, check_compaction, dispatch_post_generate, fire_context_assemble_hook, fire_loop_iteration_hook, fire_pre_hook, generate_response, process_generation_result, prune_old_tool_results, refresh_context_limit, resolve_max_iterations, set_state
Source · 27 lines
void AgentEngine::execute_iteration(LoopContext& ctx) {
logger->info("[LOOP] iter {}/{} state={} msgs={}",
ctx.metrics.iterations,
resolve_max_iterations(ctx),
agent_state_name(ctx.state),
ctx.messages.size());
fire_loop_iteration_hook(hooks_, ctx); // ON_LOOP_ITERATION (v1.9.1)
context_manager_.refresh_context_limit(ctx, 0);
context_manager_.prune_old_tool_results(ctx);
context_manager_.check_compaction(ctx);
fire_context_assemble_hook(hooks_, ctx); // ON_CONTEXT_ASSEMBLE (v1.9.1)
set_state(ctx, AgentState::EXECUTING);
// Hook: PRE_GENERATE — can cancel (v1.9.1)
if (fire_pre_hook(ENTROPIC_HOOK_PRE_GENERATE, ctx.metrics.iterations)) {
set_state(ctx, AgentState::COMPLETE);
return;
}
auto result = response_generator_.generate_response(ctx);
dispatch_post_generate(ctx, result);
process_generation_result(ctx, result);
}Activity · 13 steps
Requirements
execute_pending_delegation
void entropic::AgentEngine::execute_pending_delegation(LoopContext &ctx)
Execute a pending delegation after tool processing.
src/core/engine.cpp:2823
Called by dispatch_pending_or_halt
Calls finalize_delegation_result, fire_delegate_complete_hook, fire_delegate_pre_hook, fire_delegation_complete, fire_delegation_start, push_delegation_result, reject_delegation_if_guarded, resolve_resume_delegation, run_pending_delegation, set_state
Source · 55 lines
void AgentEngine::execute_pending_delegation(LoopContext& ctx) {
auto pending = std::move(*ctx.pending_delegation);
ctx.pending_delegation.reset();
if (reject_delegation_if_guarded(ctx, pending)) { return; }
set_state(ctx, AgentState::DELEGATING);
// gh#32 (v2.1.6): resume_delegation tool emits a directive with
// resume_from_delegation_id set; the target tier is unknown to the
// tool and must be resolved from storage. Failure to load (unknown
// id, no storage) surfaces a typed error to the lead.
//
// The pre-hook gate is interleaved with resume so both share a
// single early-exit (knots returns gate).
std::vector<Message> resume_history;
bool blocked = false;
// gh#162 (v2.13.0): `resume_by_target` is the second way in — the id is
// empty precisely because the lead did not have to look it up.
const bool is_resume = !pending.resume_from_delegation_id.empty()
|| pending.resume_by_target;
if (is_resume
&& !resolve_resume_delegation(ctx, pending, resume_history)) {
blocked = true;
} else if (fire_delegate_pre_hook(pending, ctx.delegation_depth)) {
logger->info("ON_DELEGATE hook cancelled delegation");
blocked = true;
}
if (blocked) {
set_state(ctx, AgentState::EXECUTING);
return;
}
fire_delegation_start(ctx, pending.target, pending.task);
auto result = run_pending_delegation(
ctx, pending, std::move(resume_history));
push_delegation_result(ctx, pending.target, result);
// gh#64: track consecutive failures against the same target.
if (result.success) {
ctx.last_failed_delegation_target.clear();
ctx.consecutive_failed_delegations = 0;
} else if (pending.target == ctx.last_failed_delegation_target) {
++ctx.consecutive_failed_delegations;
} else {
ctx.last_failed_delegation_target = pending.target;
ctx.consecutive_failed_delegations = 1;
}
fire_delegation_complete(ctx, pending.target, result);
fire_delegate_complete_hook(pending.target, result.success,
result.summary);
finalize_delegation_result(ctx, result);
}Activity · 32 steps
Requirements
execute_pending_pipeline
void entropic::AgentEngine::execute_pending_pipeline(LoopContext &ctx)
Execute a pending pipeline after tool processing.
src/core/engine.cpp:3110
Called by dispatch_pending_or_halt
Calls delegation_callbacks_snapshot, dir_swap_snapshot, execute_pipeline, reject_pipeline_if_guarded, resolve_session_root, sandbox_for_session, set_delegation_callbacks, set_dir_swap, set_state, set_storage
Source · 46 lines
void AgentEngine::execute_pending_pipeline(LoopContext& ctx) {
auto pending = std::move(*ctx.pending_pipeline);
ctx.pending_pipeline.reset();
if (reject_pipeline_if_guarded(ctx, pending)) { return; }
set_state(ctx, AgentState::DELEGATING);
// gh#33 (v2.1.6): engine-scoped sandbox; non-owning pointer.
// gh#160 (v2.13.0): both the root and the sandbox are per SESSION now,
// and the dir-swap callback is finally passed on — without it every
// ScopedSandbox took the non-sandboxed branch.
auto root = resolve_session_root(ctx.session_key);
DelegationManager mgr(run_child_loop_trampoline, this,
tier_res_, root,
sandbox_for_session(ctx.session_key));
auto swap = dir_swap_snapshot();
mgr.set_dir_swap(swap.first, swap.second);
if (storage_.create_delegation != nullptr) {
mgr.set_storage(&storage_);
}
// gh#29 (v2.1.5): snapshot under the mutex (see execute_pending_
// delegation comment); avoids a torn read against a concurrent
// set_delegation_callbacks call.
auto cb_snap = delegation_callbacks_snapshot();
mgr.set_delegation_callbacks(
cb_snap.start, cb_snap.complete, cb_snap.user_data);
std::vector<DelegationResult> stage_log;
auto result = mgr.execute_pipeline(
ctx, pending.stages, pending.task, stage_log, pending.context);
std::string tag = result.success ? "COMPLETE" : "FAILED";
std::string content = "[PIPELINE " + tag + "]";
for (size_t i = 0; i < stage_log.size(); ++i) {
content += "\nStage " + std::to_string(i + 1)
+ " (" + stage_log[i].target_tier + "): "
+ stage_log[i].summary;
}
content += "\nFinal: " + result.summary;
Message result_msg;
result_msg.role = "user";
result_msg.content = std::move(content);
ctx.messages.push_back(std::move(result_msg));
set_state(ctx, AgentState::EXECUTING);
}Activity · 25 steps
Requirements
fetch_resume_payload
bool entropic::AgentEngine::fetch_resume_payload(LoopContext &ctx, const std::string &id, nlohmann::json &parsed)
Helper for resolve_resume_delegation (gh#32, v2.1.6).
src/core/engine.cpp:3380
Source · 24 lines
bool AgentEngine::fetch_resume_payload(
LoopContext& ctx,
const std::string& id,
nlohmann::json& parsed) {
std::optional<std::string> error;
std::string raw;
if (storage_.load_delegation_with_messages == nullptr) {
error = "storage unavailable";
} else if (!storage_.load_delegation_with_messages(
id.c_str(), raw, storage_.user_data)) {
error = "unknown delegation_id";
} else {
parsed = nlohmann::json::parse(raw, nullptr, false);
if (parsed.is_discarded() || !parsed.is_object()) {
error = "malformed storage payload";
}
}
if (error.has_value()) {
logger->error("resume_delegation '{}': {}", id, *error);
push_resume_failure(ctx, *error, id);
return false;
}
return true;
}Activity · 16 steps
Requirements
finalize_delegation_result
void entropic::AgentEngine::finalize_delegation_result(LoopContext &ctx, const struct DelegationResult &result)
Decide post-delegation engine state.
src/core/engine.cpp:2971
Called by execute_pending_delegation
Calls build_coverage_gap_message, fold_delegation_summary, log_relay_status, relay_partial_result, set_state, tier_requires_explicit_completion
Source · 39 lines
void AgentEngine::finalize_delegation_result(
LoopContext& ctx, const DelegationResult& result) {
// delegation.cpp sets success=false when terminal_reason is non-empty,
// so the two relay branches are disjoint — check them independently.
const bool in_relay_tier =
relay_single_delegate_tiers_.count(ctx.locked_tier) > 0;
if (in_relay_tier && result.coverage_gap) {
Message gap;
gap.role = "user";
gap.content = build_coverage_gap_message(
result.target_tier, result);
ctx.messages.push_back(std::move(gap));
ctx.metadata["relay_status"] = "coverage_gap_suppressed";
logger->info(
"[COVERAGE GAP] suppressing auto-relay for tier={} "
"({} suggested files)",
result.target_tier, result.suggested_files.size());
set_state(ctx, AgentState::EXECUTING);
return;
}
if (result.success && in_relay_tier) {
relay_partial_result(ctx, result.summary);
log_relay_status(ctx);
return;
}
if (!result.terminal_reason.empty() && in_relay_tier) {
relay_partial_result(ctx,
"[partial — budget_exhausted] " + result.summary);
log_relay_status(ctx, result.terminal_reason);
return;
}
bool needs_explicit = tier_requires_explicit_completion(
ctx.locked_tier);
if (result.success && !needs_explicit) {
fold_delegation_summary(ctx, result.summary); // gh#119
}
set_state(ctx, (result.success && !needs_explicit)
? AgentState::COMPLETE : AgentState::EXECUTING);
}Activity · 22 steps
Requirements
finish_with_carried_output
void entropic::AgentEngine::finish_with_carried_output(LoopContext &ctx, const std::string &reason, const std::string &stop_noun, const std::string &terminal_reason)
Synthesize the final assistant message a forced stop owes.
src/core/engine.cpp:798
Called by force_iteration_cap_completion, hard_cut_budget
Calls annotate_hard_stop, last_substantive_assistant, set_state
Source · 15 lines
void AgentEngine::finish_with_carried_output(
LoopContext& ctx,
const std::string& reason,
const std::string& stop_noun,
const std::string& terminal_reason) {
std::string carried = last_substantive_assistant(ctx);
Message forced;
forced.role = "assistant";
forced.content = annotate_hard_stop(carried, reason, stop_noun);
ctx.messages.push_back(std::move(forced));
ctx.metadata["terminal_reason"] = terminal_reason;
ctx.metadata["cap_carried_content"] =
carried.empty() ? "false" : "true";
set_state(ctx, AgentState::COMPLETE);
}Activity · 8 steps
Requirements
fire_complete_hook
bool entropic::AgentEngine::fire_complete_hook(const std::string &summary, const LoopContext &ctx)
Fire ON_COMPLETE pre-hook for summary validation.
src/core/engine.cpp:2493
Called by dir_complete
Calls build_tool_results_json, json_escape_engine, provider, sanitize_utf8
Source · 42 lines
bool AgentEngine::fire_complete_hook(
const std::string& summary,
const LoopContext& ctx) {
if (hooks_.fire_pre == nullptr) { return false; }
auto tool_results = build_tool_results_json(ctx.messages);
// E3 (2.0.6-rc17): splice validator verdict/violations so
// ON_COMPLETE consumers can distinguish clean pass from
// reverted-for-length / max-revisions-exhausted.
std::string validation_block = ",\"validation\":null";
if (validation_provider_ != nullptr) {
char* v = validation_provider_(validation_provider_data_);
if (v != nullptr) {
validation_block = ",\"validation\":" + std::string(v);
free(v);
}
}
std::string json =
"{\"summary\":\"" + json_escape_engine(summary)
+ "\",\"tier\":\"" + ctx.locked_tier
+ "\",\"tool_results\":" + tool_results
+ ",\"iteration\":" + std::to_string(ctx.metrics.iterations)
+ validation_block
+ "}";
char* modified = nullptr;
int rc = hooks_.fire_pre(hooks_.registry,
ENTROPIC_HOOK_ON_COMPLETE, json.c_str(), &modified);
if (modified != nullptr) {
// Hook provided rejection feedback — inject as user message.
// Same inbound-boundary gap as fire_post_generate_hook above:
// sanitize the hook's returned bytes before they enter a
// Message that later flows to json::dump() call sites.
Message feedback;
feedback.role = "user";
feedback.content =
std::string("[CITATION VALIDATION] ") + mcp::sanitize_utf8(modified);
const_cast<LoopContext&>(ctx).messages.push_back(
std::move(feedback));
free(modified);
}
return rc != 0;
}Activity · 19 steps
Requirements
fire_context_assemble_hook
static void entropic::fire_context_assemble_hook(const HookInterface &hooks, const LoopContext &ctx)
Build + fire the ON_CONTEXT_ASSEMBLE info hook.
src/core/engine.cpp:102
Source · 7 lines
static void fire_context_assemble_hook(const HookInterface& hooks,
const LoopContext& ctx) {
std::string json = "{\"message_count\":"
+ std::to_string(ctx.messages.size()) + "}";
fire_hook_info(hooks, ENTROPIC_HOOK_ON_CONTEXT_ASSEMBLE,
json.c_str());
}Activity · 2 steps
Requirements
fire_delegate_complete_hook
void entropic::AgentEngine::fire_delegate_complete_hook(const std::string &target, bool success, const std::string &summary="")
Fire ON_DELEGATE_COMPLETE post-hook.
src/core/engine.cpp:2608
Source · 13 lines
void AgentEngine::fire_delegate_complete_hook(
const std::string& target, bool success,
const std::string& summary) {
if (hooks_.fire_post == nullptr) {
return;
}
std::string json = detail::build_delegate_complete_json(
target, success, summary);
char* out = nullptr;
hooks_.fire_post(hooks_.registry,
ENTROPIC_HOOK_ON_DELEGATE_COMPLETE, json.c_str(), &out);
free(out);
}Activity · 6 steps
Requirements
fire_delegate_pre_hook
bool entropic::AgentEngine::fire_delegate_pre_hook(const PendingDelegation &pending, int depth)
Fire ON_DELEGATE pre-hook.
src/core/engine.cpp:2545
Source · 15 lines
bool AgentEngine::fire_delegate_pre_hook(
const PendingDelegation& pending, int depth) {
if (hooks_.fire_pre == nullptr) {
return false;
}
std::string json = "{\"target_tier\":\""
+ pending.target + "\",\"task\":\""
+ pending.task + "\",\"depth\":"
+ std::to_string(depth) + "}";
char* modified = nullptr;
int rc = hooks_.fire_pre(hooks_.registry,
ENTROPIC_HOOK_ON_DELEGATE, json.c_str(), &modified);
free(modified);
return rc != 0;
}Activity · 7 steps
Requirements
fire_delegation_complete
void entropic::AgentEngine::fire_delegation_complete(const LoopContext &ctx, const std::string &tier, const struct DelegationResult &result)
Fire on_delegation_complete callback.
src/core/engine.cpp:3184
Source · 11 lines
void AgentEngine::fire_delegation_complete(
const LoopContext& /*ctx*/,
const std::string& tier,
const DelegationResult& result) {
if (callbacks_.on_delegation_complete != nullptr) {
callbacks_.on_delegation_complete(
"", tier.c_str(), result.summary.c_str(),
result.success ? 1 : 0,
callbacks_.user_data);
}
}Activity · 2 steps
Requirements
fire_delegation_start
void entropic::AgentEngine::fire_delegation_start(const LoopContext &ctx, const std::string &tier, const std::string &task)
Fire on_delegation_start callback.
src/core/engine.cpp:3165
Source · 10 lines
void AgentEngine::fire_delegation_start(
const LoopContext& /*ctx*/,
const std::string& tier,
const std::string& task) {
if (callbacks_.on_delegation_start != nullptr) {
callbacks_.on_delegation_start(
"", tier.c_str(), task.c_str(),
callbacks_.user_data);
}
}Activity · 2 steps
Requirements
fire_hook_info
static void entropic::fire_hook_info(const HookInterface &hooks, entropic_hook_point_t point, const char *json)
Fire an informational hook if the interface is wired.
src/core/engine.cpp:38
Called by fire_context_assemble_hook, fire_loop_end_hook, fire_loop_iteration_hook, fire_loop_start_hook, set_state
Calls none
Source · 7 lines
static void fire_hook_info(const HookInterface& hooks,
entropic_hook_point_t point,
const char* json) {
if (hooks.fire_info != nullptr) {
hooks.fire_info(hooks.registry, point, json);
}
}Activity · 2 steps
Requirements
fire_loop_end_hook
static void entropic::fire_loop_end_hook(const HookInterface &hooks, const LoopContext &ctx)
Build + fire the ON_LOOP_END info hook.
src/core/engine.cpp:69
Source · 8 lines
static void fire_loop_end_hook(const HookInterface& hooks,
const LoopContext& ctx) {
std::string json = "{\"final_state\":\""
+ std::string(agent_state_name(ctx.state))
+ "\",\"iterations\":"
+ std::to_string(ctx.metrics.iterations) + "}";
fire_hook_info(hooks, ENTROPIC_HOOK_ON_LOOP_END, json.c_str());
}Activity · 2 steps
Requirements
fire_loop_iteration_hook
static void entropic::fire_loop_iteration_hook(const HookInterface &hooks, const LoopContext &ctx)
Build + fire the ON_LOOP_ITERATION info hook.
src/core/engine.cpp:85
Source · 9 lines
static void fire_loop_iteration_hook(const HookInterface& hooks,
const LoopContext& ctx) {
std::string json = "{\"iteration\":"
+ std::to_string(ctx.metrics.iterations)
+ ",\"state\":\"" + agent_state_name(ctx.state)
+ "\",\"consecutive_errors\":"
+ std::to_string(ctx.consecutive_errors) + "}";
fire_hook_info(hooks, ENTROPIC_HOOK_ON_LOOP_ITERATION, json.c_str());
}Activity · 2 steps
Requirements
fire_loop_start_hook
static void entropic::fire_loop_start_hook(const HookInterface &hooks, const LoopContext &ctx)
Build + fire the ON_LOOP_START info hook.
src/core/engine.cpp:53
Source · 8 lines
static void fire_loop_start_hook(const HookInterface& hooks,
const LoopContext& ctx) {
std::string json = "{\"message_count\":"
+ std::to_string(ctx.messages.size())
+ ",\"delegation_depth\":"
+ std::to_string(ctx.delegation_depth) + "}";
fire_hook_info(hooks, ENTROPIC_HOOK_ON_LOOP_START, json.c_str());
}Activity · 2 steps
Requirements
fire_post_generate_hook
void entropic::AgentEngine::fire_post_generate_hook(GenerateResult &result, const std::string &tier, const std::vector< Message > &messages)
Fire POST_GENERATE hook.
src/core/engine.cpp:2337
Called by dispatch_post_generate, relay_partial_result
Calls build_tool_evidence, build_tool_manifest, enrich_manifest_with_history, json_escape_engine, sanitize_utf8
Source · 39 lines
void AgentEngine::fire_post_generate_hook(
GenerateResult& result,
const std::string& tier,
const std::vector<Message>& messages) {
if (hooks_.fire_post == nullptr) {
return;
}
auto manifest = build_tool_manifest(messages);
manifest = enrich_manifest_with_history(manifest, tool_exec_);
auto sys = extract_system_prompt(messages);
// Issue #5 (v2.1.3): include un-pruned tool-result evidence so the
// constitutional validator can verify file:line citations against
// actual content rather than the stubs that prune leaves behind.
// Bounded at 20 most-recent results × 800 chars each (~16KB max
// evidence), well within any sane critique-prompt budget. The
// field is OPTIONAL on the hook contract — pre-2.1.3 consumers
// ignore it; v2.1.3 validator augments its critique prompt.
auto evidence = build_tool_evidence(messages, 20, 800);
std::string json =
"{\"finish_reason\":\"" + result.finish_reason
+ "\",\"content\":\"" + json_escape_engine(result.content)
+ "\",\"tier\":\"" + tier
+ "\",\"tool_context\":\"" + json_escape_engine(manifest)
+ "\",\"tool_evidence\":\"" + json_escape_engine(evidence)
+ "\",\"system_prompt\":\"" + json_escape_engine(sys) + "\"}";
char* out = nullptr;
hooks_.fire_post(hooks_.registry,
ENTROPIC_HOOK_POST_GENERATE, json.c_str(), &out);
if (out != nullptr) {
// gh#3 recurrence (v2.9.6): a hook's revised content is an
// inbound boundary crossing a plugin .so, same class as the
// MCP tool-result boundary — sanitize before it re-enters the
// engine so downstream json::dump() (delegate-complete hook,
// facade serialization, storage) cannot throw type_error 316.
result.content = mcp::sanitize_utf8(out);
logger->info("POST_GENERATE hook revised content");
free(out);
}
}Activity · 13 steps
Requirements
fire_pre_hook
bool entropic::AgentEngine::fire_pre_hook(entropic_hook_point_t point, int iteration)
Fire a pre-hook and return true if cancelled.
src/core/engine.cpp:2103
Source · 13 lines
bool AgentEngine::fire_pre_hook(
entropic_hook_point_t point, int iteration) {
if (hooks_.fire_pre == nullptr) {
return false;
}
std::string json = "{\"iteration\":"
+ std::to_string(iteration) + "}";
char* modified = nullptr;
int rc = hooks_.fire_pre(hooks_.registry,
point, json.c_str(), &modified);
free(modified);
return rc != 0;
}Activity · 7 steps
Requirements
fold_complete_into_assistant
bool entropic::AgentEngine::fold_complete_into_assistant(LoopContext &ctx, const Message &tool_result_msg) const
gh#68 (v2.3.4): fold entropic.complete summary into the prior assistant message, suppressing the JSON tool-result user message that would otherwise land in history.
src/core/engine.cpp:1374
Source · 14 lines
bool AgentEngine::fold_complete_into_assistant(
LoopContext& ctx, const Message& tool_result_msg) const {
auto tn_it = tool_result_msg.metadata.find("tool_name");
bool is_complete = tn_it != tool_result_msg.metadata.end()
&& tn_it->second == "entropic.complete";
if (!is_complete || ctx.messages.empty()) { return false; }
auto& last = ctx.messages.back();
auto sum_it = ctx.metadata.find("explicit_completion_summary");
bool foldable = last.role == "assistant" && last.content.empty()
&& sum_it != ctx.metadata.end();
if (!foldable) { return false; }
last.content = sum_it->second;
return true;
}Activity · 11 steps
Requirements
fold_delegation_summary
static void entropic::fold_delegation_summary(LoopContext &ctx, const std::string &summary)
gh#119 (v2.9.17): fold child summary into the lead's empty delegate turn.
src/core/engine.cpp:2940
Source · 10 lines
static void fold_delegation_summary(
LoopContext& ctx, const std::string& summary) {
for (auto rit = ctx.messages.rbegin();
rit != ctx.messages.rend(); ++rit) {
if (rit->role == "assistant" && rit->content.empty()) {
rit->content = summary;
break;
}
}
}Activity · 4 steps
Requirements
force_iteration_cap_completion
void entropic::AgentEngine::force_iteration_cap_completion(LoopContext &ctx)
Force the synthetic completion the iteration cap owes.
src/core/engine.cpp:825
Source · 8 lines
void AgentEngine::force_iteration_cap_completion(LoopContext& ctx) {
finish_with_carried_output(
ctx,
"iteration cap reached after "
+ std::to_string(ctx.metrics.iterations) + " iterations",
"cap",
"budget_exhausted");
}Activity · 1 steps
Requirements
get_tier_allowed_tools
std::vector< std::string > entropic::AgentEngine::get_tier_allowed_tools(const std::string &name) const
Return the allowed tool names registered for a tier (gh#121 regression).
src/core/engine.cpp:4758
Source · 6 lines
std::vector<std::string> AgentEngine::get_tier_allowed_tools(
const std::string& name) const {
auto it = tier_info_.find(name);
if (it == tier_info_.end()) { return {}; }
return it->second.allowed_tools;
}Activity · 4 steps
Requirements
handle_terminal_finish_reasons
bool entropic::AgentEngine::handle_terminal_finish_reasons(LoopContext &ctx, const std::string &finish_reason)
Short-circuit for interrupted / length finish reasons.
src/core/engine.cpp:1179
Source · 21 lines
bool AgentEngine::handle_terminal_finish_reasons(
LoopContext& ctx, const std::string& finish_reason) {
bool handled = true;
if (finish_reason == "interrupted") {
logger->info("[DECISION] interrupted");
set_state(ctx, AgentState::INTERRUPTED);
} else if (finish_reason == "context_overflow") {
ctx.metadata["failure_reason"] = "context_overflow";
ctx.metadata["failure_tier"] = ctx.locked_tier;
logger->error("[DECISION] prompt does not fit tier '{}' context — "
"failing the turn instead of retrying it; the "
"inference log carries the token breakdown",
ctx.locked_tier);
set_state(ctx, AgentState::ERROR);
} else if (finish_reason == "length") {
logger->info("[DECISION] length, continuing");
} else {
handled = false;
}
return handled;
}Activity · 16 steps
Requirements
hard_cut_budget
void entropic::AgentEngine::hard_cut_budget(LoopContext &ctx)
Second-exhaustion hard cut (failure note + terminal).
src/core/engine.cpp:1074
Source · 10 lines
void AgentEngine::hard_cut_budget(LoopContext& ctx) {
logger->warn("[BUDGET] thinking budget exhausted after nudge — "
"hard-cutting turn");
finish_with_carried_output(
ctx,
"thinking budget exhausted after the completion nudge went "
"unheeded; no tool call was emitted",
"cut",
"budget_exhausted_thinking");
}Activity · 2 steps
Requirements
has_tier
bool entropic::AgentEngine::has_tier(const std::string &name) const
Whether a tier name is known (gh#99).
src/core/engine.cpp:4746
Called by TEST_CASE, check_stream_args, entropic_run_as, entropic_run_session_as
Calls none
Source · 3 lines
bool AgentEngine::has_tier(const std::string& name) const {
return tier_info_.count(name) > 0;
}Activity · 1 steps
Requirements
init_session_conversation
void entropic::AgentEngine::init_session_conversation(LoopContext &ctx)
Create the root conversation row for a run (gh#48).
src/core/engine.cpp:521
Source · 18 lines
void AgentEngine::init_session_conversation(LoopContext& ctx) {
// gh#48 (v2.1.12): create the root conversation row when storage
// is wired so `ctx.conversation_id` carries a valid FK into
// `conversations(id)`. Every downstream delegation copies
// `parent_ctx.conversation_id` into `child_ctx.parent_conversation_id`
// (`delegation.cpp:387`); without this, the empty string propagates
// and every `INSERT INTO delegations` violates the FK silently,
// making `entropic.followup` return empty across an entire session.
if (storage_.create_conversation == nullptr) { return; }
std::string conv_id;
if (storage_.create_conversation("session", conv_id, storage_.user_data)
&& !conv_id.empty()) {
ctx.conversation_id = std::move(conv_id);
} else {
logger->warn("Storage create_conversation failed at run() init; "
"delegations will not persist this session (gh#48)");
}
}Activity · 7 steps
Requirements
interrupt
void entropic::AgentEngine::interrupt()
Interrupt the running loop (thread-safe).
src/core/engine.cpp:1490
Called by SCENARIO, SCENARIO, SCENARIO, TEST_CASE, entropic_interrupt, interrupt_during_tools_executor, join_async_workers, on_stream_chunk
Calls none
Source · 24 lines
void AgentEngine::interrupt() {
// gh#158 (v2.13.0): `interrupt()` means EVERY run on this handle and
// keeps that meaning. Each in-flight run carries its own token now, so
// the handle-wide flag alone would not reach a run that started before
// it was set and polls its own. Fan out explicitly.
{
std::lock_guard<std::mutex> guard(runs_mutex_);
for (auto& [key, run] : active_runs_) {
(void)key;
run->interrupt.store(true, std::memory_order_release);
}
}
if (!interrupt_flag_.exchange(true)) {
logger->info("Engine interrupted");
// P1-10: propagate to external MCP transports so in-flight
// tool calls abort alongside the generation loop. This is the
// handle-wide latch and stays handle-wide: `interrupt_session`
// deliberately does NOT fire it (see its declaration).
if (external_interrupt_cb_ != nullptr) {
external_interrupt_cb_(external_interrupt_data_);
}
}
pause_flag_.store(false);
}Activity · 9 steps
Requirements
interrupt_session
bool entropic::AgentEngine::interrupt_session(const std::string &key)
Interrupt exactly one session's run (gh#158).
src/core/engine.cpp:3933
Source · 15 lines
bool AgentEngine::interrupt_session(const std::string& key) {
std::shared_ptr<RunState> run;
{
std::lock_guard<std::mutex> guard(runs_mutex_);
auto it = active_runs_.find(key);
if (it != active_runs_.end()) { run = it->second; }
}
if (!run) {
logger->info("interrupt_session('{}'): no run in flight", key);
return false;
}
run->interrupt.store(true, std::memory_order_release);
logger->info("Session '{}' interrupted", key);
return true;
}Activity · 11 steps
Requirements
is_delegation_cycle
bool entropic::AgentEngine::is_delegation_cycle(const LoopContext &ctx, const std::string &target) const
Check whether pending delegation would close a cycle.
src/core/engine.cpp:1343
Source · 8 lines
bool AgentEngine::is_delegation_cycle(
const LoopContext& ctx, const std::string& target) const {
if (target == ctx.locked_tier) { return true; }
for (const auto& anc : ctx.delegation_ancestor_tiers) {
if (anc == target) { return true; }
}
return false;
}Activity · 6 steps
Requirements
is_delegation_repeat_blocked
bool entropic::AgentEngine::is_delegation_repeat_blocked(const LoopContext &ctx, const std::string &target) const
Predicate: should this delegation be blocked because the same target has just failed too many times? (gh#64)
src/core/engine.cpp:1359
Source · 6 lines
bool AgentEngine::is_delegation_repeat_blocked(
const LoopContext& ctx, const std::string& target) const {
return target == ctx.last_failed_delegation_target
&& ctx.consecutive_failed_delegations
>= loop_config_.max_consecutive_failed_delegations;
}Activity · 1 steps
Requirements
is_terminal_state
bool entropic::AgentEngine::is_terminal_state(const LoopContext &ctx)
True when ctx.state is COMPLETE / ERROR / INTERRUPTED.
src/core/engine.cpp:1429
Called by dispatch_pending_or_halt, loop, process_tool_results, should_stop
Calls none
Source · 5 lines
bool AgentEngine::is_terminal_state(const LoopContext& ctx) {
return ctx.state == AgentState::COMPLETE
|| ctx.state == AgentState::ERROR
|| ctx.state == AgentState::INTERRUPTED;
}Activity · 1 steps
Requirements
isolation_unsafe_tools
std::vector< std::string > entropic::AgentEngine::isolation_unsafe_tools(const LoopContext &ctx, const std::string &target_tier)
Child-visible external tools that break the isolation claim.
src/core/engine.cpp:3657
Called by SCENARIO, reject_delegation_if_guarded, reject_pipeline_if_guarded
Calls info
Source · 17 lines
std::vector<std::string> AgentEngine::isolation_unsafe_tools(
const LoopContext& ctx, const std::string& target_tier) {
SessionRootInterface iface;
{
std::lock_guard<std::mutex> guard(sandbox_mutex_);
iface = session_root_;
}
if (!loop_config_.delegation_isolation
|| iface.unsafe_external_tools == nullptr) {
return {};
}
auto info = tier_res_.resolve_tier
? tier_res_.resolve_tier(target_tier, tier_res_.user_data)
: ChildContextInfo{};
return iface.unsafe_external_tools(
ctx.session_key, info.allowed_tools, iface.user_data);
}Activity · 7 steps
Requirements
log_relay_status
void entropic::AgentEngine::log_relay_status(LoopContext &ctx, const std::string &terminal_reason={})Emit disambiguating log + metadata for relay path.
src/core/engine.cpp:3025
Source · 38 lines
void AgentEngine::log_relay_status(LoopContext& ctx,
const std::string& terminal_reason) {
std::string verdict;
if (validation_provider_ != nullptr) {
char* v = validation_provider_(validation_provider_data_);
if (v != nullptr) {
std::string jv(v);
free(v);
auto pos = jv.find("\"verdict\":\"");
if (pos != std::string::npos) {
pos += 11;
auto end = jv.find('"', pos);
if (end != std::string::npos) {
verdict = jv.substr(pos, end - pos);
}
}
}
}
if (!terminal_reason.empty()) {
ctx.metadata["relay_status"] = "budget_exhausted_relayed";
logger->warn(
"Relay: single-delegate result used "
"(partial — terminal_reason={}, verdict={})",
terminal_reason, verdict.empty() ? "none" : verdict);
return;
}
if (verdict == "skipped" || verdict.empty()) {
ctx.metadata["relay_status"] = "validation_skipped";
logger->info(
"Relay: single-delegate result used "
"(lead validation skipped per config)");
} else {
ctx.metadata["relay_status"] = "validated";
logger->info(
"Relay: single-delegate result used "
"(passed lead validation)");
}
}Activity · 22 steps
Requirements
loop
void entropic::AgentEngine::loop(LoopContext &ctx)
Main loop implementation.
src/core/engine.cpp:841
Calls execute_iteration, fire_loop_end_hook, fire_loop_start_hook, force_iteration_cap_completion, is_terminal_state, resolve_max_iterations, run_interrupted, set_state, should_stop
Source · 37 lines
void AgentEngine::loop(LoopContext& ctx) {
fire_loop_start_hook(hooks_, ctx); // ON_LOOP_START (v1.9.1)
while (!should_stop(ctx)) {
ctx.metrics.iterations++;
if (run_interrupted()) {
set_state(ctx, AgentState::INTERRUPTED);
break;
}
execute_iteration(ctx);
if (ctx.state == AgentState::ERROR) {
break;
}
}
if (ctx.metrics.iterations >= resolve_max_iterations(ctx)
&& !is_terminal_state(ctx)) {
// P3-18 follow-up (2.0.6-rc16.2): force synthetic completion
// so the facade returns a proper result when the cap is hit.
// E7 (2.0.6-rc18): mark ctx.metadata with the terminal reason
// so delegate result and parent-tier relay can surface that
// the child did not complete naturally.
// gh#169 (v2.13.0): the cap ANNOTATES the agent's last
// substantive output instead of replacing it with a placeholder
// — the parent reads the last assistant message, and the child's
// real summary exists at cap time.
logger->warn("Loop ended due to max iterations ({}/{}) — "
"forcing synthetic entropic.complete",
ctx.metrics.iterations, resolve_max_iterations(ctx));
force_iteration_cap_completion(ctx);
}
fire_loop_end_hook(hooks_, ctx); // ON_LOOP_END (v1.9.1)
}Activity · 13 steps
Requirements
messages_for
std::vector< Message > entropic::AgentEngine::messages_for(const std::string &key) const
Messages held by a named session.
src/core/engine.cpp:4470
Source · 6 lines
std::vector<Message> AgentEngine::messages_for(const std::string& key) const {
std::lock_guard<std::mutex> guard(conversations_mutex_);
auto it = conversations_.find(key);
return it == conversations_.end() ? std::vector<Message>{}
: it->second.messages;
}Activity · 3 steps
Requirements
nudge_budget_completion
void entropic::AgentEngine::nudge_budget_completion(LoopContext &ctx)
First-exhaustion budget nudge (push "emit completion now").
src/core/engine.cpp:1039
Source · 16 lines
void AgentEngine::nudge_budget_completion(LoopContext& ctx) {
ctx.budget_completion_nudged = true;
ctx.budget_tokens_since_tool = 0;
ctx.budget_window_start_s =
(loop_config_.budget_mode == BudgetMode::wall_clock)
? now_seconds() : 0.0;
logger->warn("[BUDGET] thinking budget reached ({} {}); nudging completion",
loop_config_.budget_limit,
loop_config_.budget_mode == BudgetMode::tokens
? "tokens" : "seconds");
Message nudge{"user",
"[engine] thinking budget reached — emit entropic.complete now "
"with your best current answer. Further deliberation without a "
"tool call will be cut off."};
ctx.messages.push_back(std::move(nudge));
}Activity · 6 steps
Requirements
parse_tool_calls
std::pair< std::string, std::vector< ToolCall > > entropic::AgentEngine::parse_tool_calls(const std::string &raw_content)
Parse tool calls from model output via adapter.
src/core/engine.cpp:1960
Source · 45 lines
AgentEngine::parse_tool_calls(const std::string& raw_content) {
if (inference_.parse_tool_calls == nullptr) {
return {raw_content, {}};
}
char* cleaned = nullptr;
char* tc_json = nullptr;
int rc = inference_.parse_tool_calls(
raw_content.c_str(), &cleaned, &tc_json,
inference_.adapter_data);
// gh#111 (v2.9.8): the tool-call parse callback is a SEPARATE inbound
// boundary from response_generator's content sanitize. The backend derives
// both `*cleaned` and `*tool_calls_json` from its own parse of the RAW
// generation (common_chat / adapter parse_response), so a split multi-byte
// UTF-8 codepoint — routine under MTP speculative decode — arrives here as
// invalid bytes EVEN THOUGH result.content was already sanitized upstream
// (response_generator.cpp:470). Both outputs cross into engine-owned state
// at this one function:
// cleaned_str -> assistant Message.content -> (delegation) extract_summary
// fallback -> DelegationResult.summary
// -> fire_delegate_complete_hook j.dump() [the gh#111 throw]
// tc_str -> decode_tool_calls_json -> build_tool_call_from_json
// obj["arguments"].dump() + CompleteTool result.dump()
// v2.9.7 patched only the plugin-revised (out!=null) hook branches, which
// never run on the headless path — so the raw summary still reached the
// dump. Sanitize BOTH channels at this single boundary (the tool-call-channel
// sibling of the content sanitize) so no downstream nlohmann::json::dump()
// can throw type_error.316. (gh#3 recurrence.)
std::string cleaned_str =
mcp::sanitize_utf8(cleaned ? cleaned : raw_content);
std::string tc_str = mcp::sanitize_utf8(tc_json ? tc_json : "[]");
if (inference_.free_fn != nullptr) {
if (cleaned != nullptr) { inference_.free_fn(cleaned); }
if (tc_json != nullptr) { inference_.free_fn(tc_json); }
}
if (rc != 0) { return {cleaned_str, {}}; }
auto calls = decode_tool_calls_json(tc_str);
if (!calls.empty()) {
logger->info("Parsed tool calls from model output");
}
return {cleaned_str, std::move(calls)};
}Activity · 18 steps
Requirements
pause
void entropic::AgentEngine::pause()
Pause generation (thread-safe).
src/core/engine.cpp:1594
Source · 4 lines
void AgentEngine::pause() {
logger->info("Engine paused");
pause_flag_.store(true);
}Activity · 2 steps
Requirements
process_generation_result
void entropic::AgentEngine::process_generation_result(LoopContext &ctx, GenerateResult &result)
Turn a generation result into the next loop state.
src/core/engine.cpp:937
Called by execute_iteration
Calls charge_thinking_budget, dispatch_pending_or_halt, evaluate_no_tool_decision, process_tool_results, tool_calls_to_json
Source · 43 lines
void AgentEngine::process_generation_result(LoopContext& ctx,
GenerateResult& result) {
auto [cleaned, tool_calls] = parse_tool_calls(result.content);
logger->info("[ITER] finish={}, {} tool call(s), {} chars",
result.finish_reason, tool_calls.size(),
cleaned.size());
Message assistant_msg{"assistant", cleaned};
// v2.14.6: keep the model's own call for the prompt it is shown next.
// Only the cleaned text was stored, so the history read "question, empty
// reply, result" — results with no call — and the model began writing
// result-shaped prose ("Error: not_found") instead of calling the tool.
// `content` stays clean for consumers, storage and answer selection;
// ResponseGenerator::serialize_messages renders this instead.
if (!tool_calls.empty()) {
assistant_msg.metadata[tool_meta::kCallText] = result.content;
assistant_msg.metadata[tool_meta::kCalls] = tool_calls_to_json(tool_calls);
}
ctx.messages.push_back(std::move(assistant_msg));
bool made_tool_call =
!tool_calls.empty() && tool_exec_.process_tool_calls != nullptr;
// gh#84 (v2.5.1): the budget resets on genuine progress, not on a
// merely-parsed call — process_tool_results reports whether any
// tool actually executed (ok / ok_empty).
bool made_progress = false;
if (made_tool_call) {
made_progress = process_tool_results(ctx, tool_calls);
// gh#123: reset retry counter so a genuine tool call clears prior
// consecutive-empty-turn debt.
if (made_progress) {
ctx.metadata["zero_tool_call_retries"] = "0";
ctx.metadata.erase("force_tool_call"); // v2.14.6: complied
}
} else {
evaluate_no_tool_decision(ctx, cleaned, result.finish_reason);
}
// gh#80 (v2.5.0): charge the thinking budget before dispatch so a
// budget-triggered terminal is honored by dispatch_pending_or_halt.
charge_thinking_budget(ctx, result.content.size(), made_progress);
dispatch_pending_or_halt(ctx);
}Activity · 18 steps
Requirements
process_tool_results
bool entropic::AgentEngine::process_tool_results(LoopContext &ctx, const std::vector< ToolCall > &tool_calls)
Process tool calls and handle directives.
src/core/engine.cpp:2033
Called by process_generation_result
Calls defang_meta_action_envelope, fold_complete_into_assistant, is_terminal_state, set_state
Source · 37 lines
bool AgentEngine::process_tool_results(
LoopContext& ctx,
const std::vector<ToolCall>& tool_calls) {
set_state(ctx, AgentState::WAITING_TOOL);
auto results = tool_exec_.process_tool_calls(
ctx, tool_calls, tool_exec_.user_data);
logger->info("[TOOLS] {} call(s) -> {} result message(s)",
tool_calls.size(), results.size());
// gh#84 (v2.5.1): "progress" = at least one tool genuinely
// executed (result_kind ok / ok_empty), not merely parsed. The
// thinking budget resets only on progress so a duplicate/rejected
// -spam spiral (rejected_duplicate, rejected_schema, anti-spiral)
// can no longer keep its budget perpetually fresh.
bool made_progress = false;
for (auto& msg : results) {
auto it = msg.metadata.find("result_kind");
if (it != msg.metadata.end()
&& (it->second == "ok" || it->second == "ok_empty")) {
made_progress = true;
}
if (fold_complete_into_assistant(ctx, msg)) {
continue; // gh#68: folded; skip pushing JSON user message
}
defang_meta_action_envelope(msg); // gh#88: strip call-shaped envelope
ctx.messages.push_back(std::move(msg));
}
ctx.has_pending_tool_results = true;
// Don't overwrite terminal states set by directive handlers
if (!is_terminal_state(ctx)) {
set_state(ctx, AgentState::EXECUTING);
}
return made_progress;
}Activity · 16 steps
Requirements
push_delegation_cycle_rejected
static void entropic::push_delegation_cycle_rejected(LoopContext &ctx, const std::string &target)
Append a structured cycle-rejection message to the loop context so the model can recover.
src/core/engine.cpp:2664
Source · 18 lines
static void push_delegation_cycle_rejected(
LoopContext& ctx, const std::string& target) {
std::string chain;
for (const auto& anc : ctx.delegation_ancestor_tiers) {
chain += anc + " -> ";
}
chain += ctx.locked_tier + " -> " + target;
Message reject;
reject.role = "user";
reject.content = "[DELEGATION REJECTED] Circular delegation "
"detected: tier '" + target +
"' already in the active delegation chain "
"(" + chain + "). Choose a different target.";
ctx.metadata["failure_reason"] = "delegation_cycle";
ctx.metadata["failure_target"] = target;
ctx.messages.push_back(std::move(reject));
}Activity · 10 steps
Requirements
push_delegation_isolation_unsafe
static void entropic::push_delegation_isolation_unsafe(LoopContext &ctx, const std::string &target, const std::vector< std::string > &tools)
Append the "isolation cannot be honoured" reject message (gh#160).
src/core/engine.cpp:2742
Source · 22 lines
static void push_delegation_isolation_unsafe(
LoopContext& ctx, const std::string& target,
const std::vector<std::string>& tools) {
std::string names;
for (const auto& t : tools) {
if (!names.empty()) { names += ", "; }
names += t;
}
Message reject;
reject.role = "user";
reject.content =
"[DELEGATION REJECTED] delegation.isolation is 'sandbox', but '"
+ target + "' can reach external MCP tools that are not declared "
"read-only (" + names + "). An external server runs in its own "
"process and cannot be moved into the sandbox, so its writes "
"would escape it. Either restrict the tier's allowed_tools to "
"read-only tools, have the server declare readOnlyHint, or set "
"delegation.isolation: none.";
ctx.metadata["failure_reason"] = "delegation_isolation_unsafe";
ctx.metadata["failure_target"] = target;
ctx.messages.push_back(std::move(reject));
}Activity · 11 steps
Requirements
push_delegation_rejected
static void entropic::push_delegation_rejected(LoopContext &ctx)
Append a delegation rejection message to the loop context.
src/core/engine.cpp:2644
Source · 9 lines
static void push_delegation_rejected(LoopContext& ctx) {
Message reject;
reject.role = "user";
reject.content = "[DELEGATION REJECTED] Maximum delegation "
"depth (" + std::to_string(
AgentEngine::MAX_DELEGATION_DEPTH) +
") reached.";
ctx.messages.push_back(std::move(reject));
}Activity · 4 steps
Requirements
push_delegation_repeat_blocked
static void entropic::push_delegation_repeat_blocked(LoopContext &ctx, const std::string &target, int n)
Append a "stop retrying same target" reject message (gh#64).
src/core/engine.cpp:2711
Source · 13 lines
static void push_delegation_repeat_blocked(
LoopContext& ctx, const std::string& target, int n) {
Message reject;
reject.role = "user";
reject.content = "[DELEGATION REJECTED] '" + target
+ "' has just failed " + std::to_string(n)
+ " times in a row. Stop retrying this target. Either "
"respond to the user with what you have, or delegate to "
"a different tier.";
ctx.metadata["failure_reason"] = "delegation_repeat_blocked";
ctx.metadata["failure_target"] = target;
ctx.messages.push_back(std::move(reject));
}Activity · 6 steps
Requirements
push_delegation_result
static void entropic::push_delegation_result(LoopContext &ctx, const std::string &target, const DelegationResult &result)
Append a delegation result message to the loop context.
src/core/engine.cpp:2691
Source · 8 lines
static void push_delegation_result(LoopContext& ctx,
const std::string& target, const DelegationResult& result) {
std::string tag = result.success ? "COMPLETE" : "FAILED";
Message msg;
msg.role = "user";
msg.content = "[DELEGATION " + tag + ": " + target + "] " + result.summary;
ctx.messages.push_back(std::move(msg));
}Activity · 5 steps
Requirements
push_resume_failure
static void entropic::push_resume_failure(LoopContext &ctx, const std::string &reason, const std::string &delegation_id)
Lazy session-scoped SandboxManager accessor (gh#33, v2.1.6).
src/core/engine.cpp:3356
Called by fetch_resume_payload, resolve_latest_for_target, resolve_resume_delegation
Calls none
Source · 10 lines
static void push_resume_failure(
LoopContext& ctx,
const std::string& reason,
const std::string& delegation_id) {
Message m;
m.role = "user";
m.content = "[DELEGATION FAILED: resume_delegation] "
+ reason + " (delegation_id=" + delegation_id + ")";
ctx.messages.push_back(std::move(m));
}Activity · 4 steps
Requirements
record_explicit_completion_failure
bool entropic::AgentEngine::record_explicit_completion_failure(LoopContext &ctx, const std::string &finish_reason, const std::string &content)
Record failure when explicit_completion is required but zero tool calls were emitted.
src/core/engine.cpp:1268
Called by evaluate_no_tool_decision
Calls empty_turn_ceiling, empty_turn_nudge, set_state, tier_requires_explicit_completion
Source · 41 lines
bool AgentEngine::record_explicit_completion_failure(
LoopContext& ctx, const std::string& finish_reason,
const std::string& content) {
const bool owes_call = tier_requires_explicit_completion(ctx.locked_tier);
if (!owes_call && !content.empty()) {
return false;
}
auto& retries = ctx.metadata["zero_tool_call_retries"];
int n = retries.empty() ? 0 : std::atoi(retries.c_str());
const int ceiling = empty_turn_ceiling(ctx.locked_tier);
if (n >= ceiling) {
ctx.metadata["failure_reason"] = owes_call
? "zero_tool_calls_with_explicit_completion"
: (finish_reason == "error" ? "generation_failed"
: "empty_response");
ctx.metadata["failure_tier"] = ctx.locked_tier;
logger->error("[DECISION] empty-turn allowance exhausted "
"(tier={}, n={}/{}, {}), failing turn", ctx.locked_tier,
n, ceiling, ctx.metadata["failure_reason"]);
set_state(ctx, AgentState::ERROR);
return true;
}
logger->info("[DECISION] tier '{}' {} turn {}/{} (finish_reason={}), "
"nudging", ctx.locked_tier,
owes_call ? "no-tool-call" : "empty", n + 1, ceiling,
finish_reason);
// v2.14.6: the nudge only ASKED; a stalled model kept emitting
// thinking-only turns. The retry for a tier that owes a call is forced.
// A turn that already answered in prose may only conclude: its forced
// retry is offered entropic.complete alone (e7 re-delegated instead).
if (owes_call) {
ctx.metadata["force_tool_call"] = content.empty() ? "1" : "complete";
}
Message correction;
correction.role = "user";
correction.content = empty_turn_nudge(ctx, owes_call);
ctx.messages.push_back(std::move(correction));
retries = std::to_string(n + 1);
set_state(ctx, AgentState::EXECUTING);
return true;
}Activity · 22 steps
Requirements
reinject_context_anchors
void entropic::AgentEngine::reinject_context_anchors(LoopContext &ctx)
Reinject all cached context anchors.
src/core/engine.cpp:1637
Source · 12 lines
void AgentEngine::reinject_context_anchors(LoopContext& ctx) {
std::unordered_map<std::string, std::string> snapshot;
{
std::lock_guard<std::mutex> guard(anchors_mutex_);
snapshot = context_anchors_;
}
for (const auto& [key, content] : snapshot) {
ContextAnchorDirective d(key, content);
DirectiveResult r;
dir_anchor(ctx, d, r);
}
}Activity · 7 steps
Requirements
reject_delegation_if_guarded
bool entropic::AgentEngine::reject_delegation_if_guarded(LoopContext &ctx, const PendingDelegation &pending)
Apply the pre-run delegation guards (depth/cycle/repeat).
src/core/engine.cpp:2773
Called by execute_pending_delegation
Calls is_delegation_cycle, is_delegation_repeat_blocked, isolation_unsafe_tools, push_delegation_cycle_rejected, push_delegation_isolation_unsafe, push_delegation_rejected, push_delegation_repeat_blocked
Source · 36 lines
bool AgentEngine::reject_delegation_if_guarded(
LoopContext& ctx, const PendingDelegation& pending) {
bool rejected = true;
if (ctx.delegation_depth >= MAX_DELEGATION_DEPTH) {
logger->warn("Delegation rejected: depth {} >= max {}",
ctx.delegation_depth, MAX_DELEGATION_DEPTH);
push_delegation_rejected(ctx);
} else if (is_delegation_cycle(ctx, pending.target)) {
// P1-9: reject A→B→A and longer cycles before running a child.
logger->warn("Delegation rejected: cycle on target tier '{}'",
pending.target);
push_delegation_cycle_rejected(ctx, pending.target);
} else if (auto unsafe = isolation_unsafe_tools(ctx, pending.target);
!unsafe.empty()) {
// gh#160: refuse rather than silently run uncontained.
logger->error("Delegation rejected: isolation is on but '{}' can "
"reach {} non-read-only external tool(s)",
pending.target, unsafe.size());
push_delegation_isolation_unsafe(ctx, pending.target, unsafe);
} else if (is_delegation_repeat_blocked(ctx, pending.target)) {
// gh#64: refuse re-delegation to a target that has just failed
// N times in a row. Pre-fix, a lead retrying a Q4 specialist
// that couldn't emit a tool call would burn 30+ identical
// delegations before its own iteration cap stopped it.
logger->warn("Delegation rejected: '{}' failed {}x in a row "
"(>= max_consecutive_failed_delegations={})",
pending.target,
ctx.consecutive_failed_delegations,
loop_config_.max_consecutive_failed_delegations);
push_delegation_repeat_blocked(
ctx, pending.target, ctx.consecutive_failed_delegations);
} else {
rejected = false;
}
return rejected;
}Activity · 19 steps
Requirements
reject_pipeline_if_guarded
bool entropic::AgentEngine::reject_pipeline_if_guarded(LoopContext &ctx, const PendingPipeline &pending)
Apply the pre-run pipeline guards (depth, isolation reach).
src/core/engine.cpp:3078
Source · 24 lines
bool AgentEngine::reject_pipeline_if_guarded(
LoopContext& ctx, const PendingPipeline& pending) {
if (ctx.delegation_depth >= MAX_DELEGATION_DEPTH) {
logger->warn("Pipeline rejected: depth {} >= max {}",
ctx.delegation_depth, MAX_DELEGATION_DEPTH);
Message reject;
reject.role = "user";
reject.content = "[PIPELINE REJECTED] Maximum delegation "
"depth reached.";
ctx.messages.push_back(std::move(reject));
return true;
}
for (const auto& stage : pending.stages) {
auto unsafe = isolation_unsafe_tools(ctx, stage);
if (!unsafe.empty()) {
logger->error("Pipeline rejected: isolation is on but stage "
"'{}' can reach {} non-read-only external "
"tool(s)", stage, unsafe.size());
push_delegation_isolation_unsafe(ctx, stage, unsafe);
return true;
}
}
return false;
}Activity · 14 steps
Requirements
relay_partial_result
void entropic::AgentEngine::relay_partial_result(LoopContext &ctx, const std::string &summary)
Shared relay machinery: fire hook, write summary, set COMPLETE.
src/core/engine.cpp:2891
Source · 11 lines
void AgentEngine::relay_partial_result(
LoopContext& ctx, const std::string& summary) {
GenerateResult relay_result;
relay_result.content = summary;
relay_result.finish_reason = "stop";
relay_result.tool_calls_json = "[]";
fire_post_generate_hook(
relay_result, ctx.locked_tier, ctx.messages);
ctx.metadata["explicit_completion_summary"] = relay_result.content;
set_state(ctx, AgentState::COMPLETE);
}Activity · 7 steps
Requirements
remove_anchor_messages
static void entropic::remove_anchor_messages(LoopContext &ctx, const std::string &key)
Remove messages with a specific anchor key.
src/core/engine.cpp:2080
Source · 11 lines
static void remove_anchor_messages(LoopContext& ctx,
const std::string& key) {
auto& msgs = ctx.messages;
msgs.erase(
std::remove_if(msgs.begin(), msgs.end(),
[&key](const Message& m) {
auto it = m.metadata.find("anchor_key");
return it != m.metadata.end() && it->second == key;
}),
msgs.end());
}Activity · 2 steps
Requirements
reset_interrupt
void entropic::AgentEngine::reset_interrupt()
Reset interrupt flag for next run.
src/core/engine.cpp:1571
Source · 17 lines
void AgentEngine::reset_interrupt() {
interrupt_flag_.store(false);
// gh#158: a run's own token is what its decode and its MCP transport
// poll, so clearing only the handle flag would leave a re-used run
// state latched — the same shape of bug gh#150 fixed one layer up.
if (auto run = this_thread_run()) {
run->interrupt.store(false, std::memory_order_release);
}
// gh#150: an interrupt is scoped to a RUN, not to the process. This
// used to clear the engine's flag and stop, leaving every external
// MCP transport latched shut with no path in the tree that could
// reopen it — so the first Ctrl+C, or the first bridge client to
// disconnect, silently disabled external tools until restart.
if (external_reset_cb_ != nullptr) {
external_reset_cb_(external_reset_data_);
}
}Activity · 5 steps
Requirements
resolve_latest_for_target
bool entropic::AgentEngine::resolve_latest_for_target(LoopContext &ctx, PendingDelegation &pending)
Resolve a resume_delegation pending request against storage.
src/core/engine.cpp:3419
Source · 19 lines
bool AgentEngine::resolve_latest_for_target(
LoopContext& ctx, PendingDelegation& pending) {
std::string id;
bool found = storage_.latest_delegation_for_target != nullptr
&& storage_.latest_delegation_for_target(
pending.target.c_str(), id, storage_.user_data)
&& !id.empty();
if (!found) {
push_resume_failure(
ctx, "no prior delegation to this tier in storage — use "
"entropic.delegate instead",
pending.target);
return false;
}
logger->info("resume_delegation by target '{}' resolved to id '{}'",
pending.target, id);
pending.resume_from_delegation_id = id;
return true;
}Activity · 8 steps
Requirements
resolve_max_iterations
int entropic::AgentEngine::resolve_max_iterations(const LoopContext &ctx) const
Resolve effective max_iterations, honouring per-identity override.
src/core/engine.cpp:341
Source · 9 lines
int AgentEngine::resolve_max_iterations(const LoopContext& ctx) const {
int operator_limit = ctx.effective_max_iterations >= 0
? ctx.effective_max_iterations
: loop_config_.max_iterations;
if (ctx.delegated_max_turns < 1) {
return operator_limit;
}
return std::min(operator_limit, ctx.delegated_max_turns);
}Activity · 4 steps
Requirements
resolve_max_tool_calls
int entropic::AgentEngine::resolve_max_tool_calls(const LoopContext &ctx) const
Resolve effective max_tool_calls_per_turn, honouring override.
src/core/engine.cpp:358
Source · 5 lines
int AgentEngine::resolve_max_tool_calls(const LoopContext& ctx) const {
return ctx.effective_max_tool_calls_per_turn >= 0
? ctx.effective_max_tool_calls_per_turn
: loop_config_.max_tool_calls_per_turn;
}Activity · 1 steps
Requirements
resolve_resume_delegation
bool entropic::AgentEngine::resolve_resume_delegation(LoopContext &ctx, PendingDelegation &pending, std::vector< Message > &out_history)
Resolve a resume_delegation request via storage (gh#32, v2.1.6).
src/core/engine.cpp:3451
Called by execute_pending_delegation
Calls fetch_resume_payload, push_resume_failure, resolve_latest_for_target
Source · 39 lines
bool AgentEngine::resolve_resume_delegation(
LoopContext& ctx,
PendingDelegation& pending,
std::vector<Message>& out_history) {
// gh#162 (v2.13.0): a lead that remembers the specialist but not the
// storage id addresses the tier directly; the id is resolved here,
// because the tool cannot see storage. Two round trips become one.
// Single-exit accumulator — the knots returns gate is 3.
nlohmann::json j;
bool ok = !pending.resume_by_target
|| resolve_latest_for_target(ctx, pending);
const auto& id = pending.resume_from_delegation_id;
if (ok) { ok = fetch_resume_payload(ctx, id, j); }
std::string target;
if (ok) {
target = j.value("target_tier", std::string{});
if (target.empty()) {
push_resume_failure(ctx, "target_tier missing in storage", id);
ok = false;
}
}
if (!ok) {
return false;
}
pending.target = target;
if (j.contains("messages") && j["messages"].is_array()) {
for (const auto& mj : j["messages"]) {
Message m;
m.role = mj.value("role", "");
m.content = mj.value("content", "");
if (!m.role.empty()) {
out_history.push_back(std::move(m));
}
}
}
logger->info("resume_delegation '{}': loaded {} messages, target='{}'",
id, out_history.size(), target);
return true;
}Activity · 23 steps
Requirements
resolve_session_root
std::filesystem::path entropic::AgentEngine::resolve_session_root(const std::string &session_key)
Resolve the root a session's tools operate in (gh#160).
src/core/engine.cpp:3620
Called by execute_pending_pipeline, run_pending_delegation, sandbox_for_session
Calls get_repo_dir
Source · 13 lines
std::filesystem::path AgentEngine::resolve_session_root(
const std::string& session_key) {
SessionRootInterface iface;
{
std::lock_guard<std::mutex> guard(sandbox_mutex_);
iface = session_root_;
}
if (iface.resolve_root == nullptr) {
return get_repo_dir();
}
auto root = iface.resolve_root(session_key, iface.user_data);
return root.empty() ? get_repo_dir() : root;
}Activity · 7 steps
Requirements
run
std::vector< Message > entropic::AgentEngine::run(std::vector< Message > messages, const std::string &tier_override="")
Run the engine on a set of messages.
src/core/engine.cpp:471
Called by SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO 13 more
SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, run_owing_lead
Calls accumulate_run_metrics, active_session_key, begin_loop_preamble, clear_pause_for_fresh_turn, duration_ms, init_session_conversation, loop, now_seconds, reset_interrupt, run_cancel_flag
Source · 43 lines
std::vector<Message> AgentEngine::run(std::vector<Message> messages,
const std::string& tier_override) {
// gh#35: update activity timestamp at run() entry so any host
// polling `seconds_since_last_activity` for an idle-exit policy
// sees a fresh value as soon as work begins.
last_activity_epoch_s_.store(
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()).count());
// gh#158 (v2.13.0): see run_loop — this run's cancel token, published
// to this run's thread for the duration of the loop.
RunCancelScope cancel_scope(&run_cancel_flag());
LoopContext ctx;
ctx.messages = std::move(messages);
ctx.locked_tier = tier_override; // gh#99: "" routes; non-empty locks
// gh#144 (v2.12.0): carry the caller-scoped session down to the backend,
// which maps it to a KV sequence. "" is the default session.
ctx.session_key = active_session_key();
ctx.metrics.start_time = now_seconds();
init_session_conversation(ctx);
// A fresh top-level turn always starts un-interrupted and un-paused;
// only a child loop inherits (gh#81). That asymmetry is why these two
// are NOT part of the shared preamble below.
reset_interrupt();
clear_pause_for_fresh_turn();
// gh#183 (v2.13.0): the same preamble run_loop runs — which is how a
// tier's identity overrides finally reach a run where that tier is the
// LEAD and not somebody's delegate. start_time is already set above, so
// the preamble leaves it alone.
begin_loop_preamble(ctx);
loop(ctx);
ctx.metrics.end_time = now_seconds();
accumulate_run_metrics(ctx);
logger->info("Loop complete: {} iterations, {}ms",
ctx.metrics.iterations, ctx.metrics.duration_ms());
return ctx.messages;
}Activity · 16 steps
Requirements
run_cancel_flag
std::atomic< bool > & entropic::AgentEngine::run_cancel_flag()
The cancel flag of the run executing on THIS thread (gh#158).
src/core/engine.cpp:3969
Source · 4 lines
std::atomic<bool>& AgentEngine::run_cancel_flag() {
auto run = this_thread_run();
return run ? run->interrupt : interrupt_flag_;
}Activity · 2 steps
Requirements
run_loop
void entropic::AgentEngine::run_loop(LoopContext &ctx, bool inherit_interrupt=false)
Run the engine loop on a pre-built context.
src/core/engine.cpp:408
Called by SCENARIO, TEST_CASE, TEST_CASE, delegate_once, run_child_loop_trampoline
Calls accumulate_per_tier, begin_loop_preamble, clear_pause_for_fresh_turn, loop, now_seconds, reset_interrupt, run_cancel_flag
Source · 20 lines
void AgentEngine::run_loop(LoopContext& ctx, bool inherit_interrupt) {
// gh#158 (v2.13.0): publish THIS run's cancel token to THIS thread, so
// an external MCP tool call made from inside the loop aborts when its
// own session is interrupted and not when some other session is. The
// scope restores the previous token, so a child delegation loop nested
// inside a parent turn cannot orphan the parent's.
RunCancelScope cancel_scope(&run_cancel_flag());
// gh#81 (v2.4.3): child delegation loops inherit the parent's
// interrupt state — clearing it here would swallow a parent
// interrupt raised just before the child was dispatched. Only a
// fresh top-level turn resets.
if (!inherit_interrupt) {
reset_interrupt();
clear_pause_for_fresh_turn();
}
begin_loop_preamble(ctx); // gh#183: shared with run()
loop(ctx);
ctx.metrics.end_time = now_seconds();
accumulate_per_tier(ctx);
}Activity · 8 steps
Requirements
run_pending_delegation
DelegationResult entropic::AgentEngine::run_pending_delegation(LoopContext &ctx, const PendingDelegation &pending, std::vector< Message > resume_history)
Run a pending delegation (cold or resume).
src/core/engine.cpp:3505
Called by execute_pending_delegation
Calls delegation_callbacks_snapshot, dir_swap_snapshot, execute_delegation, execute_resume_delegation, resolve_session_root, sandbox_for_session, set_delegation_callbacks, set_dir_swap, set_storage
Source · 25 lines
DelegationResult AgentEngine::run_pending_delegation(
LoopContext& ctx,
const PendingDelegation& pending,
std::vector<Message> resume_history) {
std::optional<int> max_turns;
if (pending.max_turns > 0) { max_turns = pending.max_turns; }
DelegationManager mgr(run_child_loop_trampoline, this,
tier_res_, resolve_session_root(ctx.session_key),
sandbox_for_session(ctx.session_key));
auto swap = dir_swap_snapshot(); // gh#160
mgr.set_dir_swap(swap.first, swap.second);
if (storage_.create_delegation != nullptr) {
mgr.set_storage(&storage_);
}
auto cb_snap = delegation_callbacks_snapshot();
mgr.set_delegation_callbacks(
cb_snap.start, cb_snap.complete, cb_snap.user_data);
if (resume_history.empty()) {
return mgr.execute_delegation(
ctx, pending.target, pending.task, max_turns, pending.context);
}
return mgr.execute_resume_delegation(
ctx, pending.target, pending.task,
std::move(resume_history), max_turns, pending.context);
}Activity · 13 steps
Requirements
run_streaming
int entropic::AgentEngine::run_streaming(const std::string &input, TokenCallback on_token, void *user_data, int *cancel_flag, const std::string &tier="")
Run a streaming conversation turn (stateful).
src/core/engine.cpp:4325
Called by stream_session_turn
Calls end_turn, flush, is_open, log_user_input, on_token, run_turn_as, set_raw_callback
Source · 35 lines
int AgentEngine::run_streaming(
const std::string& input,
TokenCallback on_token,
void* user_data,
int* cancel_flag,
const std::string& tier)
{
if (session_logger_) {
session_logger_->log_user_input(input);
}
StreamThinkFilter filter(on_token, user_data);
if (session_logger_ && session_logger_->is_open()) {
filter.set_raw_callback(
SessionLogger::raw_token_callback,
session_logger_);
}
StreamChunkCtx sctx{&filter, cancel_flag, this};
// gh#208 (v2.14.2): this run's sink, published to this run's thread. It
// was stored in the handle-wide callbacks_ slot, where a concurrent
// streaming run overwrote it: tokens crossed between clients, and the
// first run to return left the other streaming into a dead frame.
RunStreamScope stream_scope(on_stream_chunk, &sctx);
// gh#205: a tier (or identity) locks this turn exactly as run_turn_as does.
auto result = tier.empty() ? run_turn(input) : run_turn_as(tier, input);
filter.flush();
if (session_logger_) {
session_logger_->end_turn();
}
if (cancel_flag && *cancel_flag) { return 1; }
return 0;
}Activity · 14 steps
int entropic::AgentEngine::run_streaming(std::vector< Message > new_messages, TokenCallback on_token, void *user_data, int *cancel_flag)
Streaming conversation turn from a pre-built message list (gh#37).
src/core/engine.cpp:4395
Called by SCENARIO, SCENARIO, SCENARIO, entropic_run_streaming, run_messages_stream_inner
Calls concat_user_echo, end_turn, flush, is_open, log_user_input, on_token, set_raw_callback
Source · 33 lines
int AgentEngine::run_streaming(
std::vector<Message> new_messages,
TokenCallback on_token,
void* user_data,
int* cancel_flag)
{
if (session_logger_) {
session_logger_->log_user_input(concat_user_echo(new_messages));
}
StreamThinkFilter filter(on_token, user_data);
if (session_logger_ && session_logger_->is_open()) {
filter.set_raw_callback(
SessionLogger::raw_token_callback,
session_logger_);
}
StreamChunkCtx sctx{&filter, cancel_flag, this};
// gh#208 (v2.14.2): this run's sink, published to this run's thread. It
// was stored in the handle-wide callbacks_ slot, where a concurrent
// streaming run overwrote it: tokens crossed between clients, and the
// first run to return left the other streaming into a dead frame.
RunStreamScope stream_scope(on_stream_chunk, &sctx);
auto result = run_turn(std::move(new_messages));
filter.flush();
if (session_logger_) {
session_logger_->end_turn();
}
if (cancel_flag && *cancel_flag) { return 1; }
return 0;
}Activity · 14 steps
Requirements
run_turn
std::vector< Message > entropic::AgentEngine::run_turn(const std::string &input)
Run a single conversation turn (stateful).
src/core/engine.cpp:3987
Source · 26 lines
std::vector<Message> AgentEngine::run_turn(const std::string& input) {
// gh#40 (v2.1.10): the drain loop turns mid-generation queued user
// messages into subsequent turns at this single top-level COMPLETE
// boundary. running_flag_ lets the facade reject
// entropic_queue_user_message with INVALID_STATE when idle.
//
// gh#144 (v2.12.0): claim only if the caller has not already. The
// facade claims BEFORE calling in, and must keep the claim until it
// has finished serialising results out of conversation_ — if this
// function released the flag on its way out, a second thread could
// start appending to that vector while the first was still reading it.
// A direct engine caller (tests, embedders) still gets is_running()
// set for the duration, preserving the gh#40 contract.
const bool owns_turn = try_begin_turn();
auto& convo = active_conversation();
auto prompt = system_prompt_copy();
if (convo.messages.empty() && !prompt.empty()) {
Message sys;
sys.role = "system";
sys.content = std::move(prompt);
convo.messages.push_back(std::move(sys));
}
auto result = run_drain_loop(input, /*tier_override=*/"");
if (owns_turn) { end_turn(); }
return result;
}Activity · 12 steps
std::vector< Message > entropic::AgentEngine::run_turn(std::vector< Message > new_messages)
Run a single conversation turn from a pre-built message list (gh#37).
src/core/engine.cpp:4249
Called by none
Calls active_conversation, prepare_next_turn, seed_system_prompt, settle_turn
Source · 25 lines
std::vector<Message> AgentEngine::run_turn(std::vector<Message> new_messages) {
// gh#40 (v2.1.10): mirror the single-string overload's drain
// loop. Queued messages enqueued via entropic_queue_user_message
// become subsequent plain-text user turns at this top-level
// boundary (no content_parts — the queue ABI is text-only).
// gh#144 (v2.12.0): see run_turn(const std::string&).
const bool owns_turn = try_begin_turn();
seed_system_prompt(new_messages);
auto& convo = active_conversation();
std::vector<Message> pending = std::move(new_messages);
std::vector<Message> result;
while (true) {
const size_t turn_begin = convo.messages.size();
for (auto& m : pending) {
convo.messages.push_back(std::move(m));
}
size_t sent_len = convo.messages.size();
result = run(convo.messages);
// gh#209/#212: see run_drain_loop.
if (!settle_turn(convo, result, turn_begin, sent_len)
|| !prepare_next_turn(pending)) { break; }
}
if (owns_turn) { end_turn(); }
return result;
}Activity · 16 steps
Requirements
run_turn_as
std::vector< Message > entropic::AgentEngine::run_turn_as(const std::string &tier, const std::string &input)
Run a single turn under a named tier's grammar/identity (gh#99).
src/core/engine.cpp:4031
Called by SCENARIO, TEST_CASE, run_as_inner, run_streaming
Calls run_drain_loop, seed_system_prompt_for_tier
Source · 10 lines
std::vector<Message> AgentEngine::run_turn_as(const std::string& tier,
const std::string& input) {
// gh#144 (v2.12.0): see run_turn(const std::string&) — claim only if
// the caller has not already.
const bool owns_turn = try_begin_turn();
seed_system_prompt_for_tier(tier);
auto result = run_drain_loop(input, tier);
if (owns_turn) { end_turn(); }
return result;
}Activity · 6 steps
Requirements
sandbox_for_session
SandboxManager * entropic::AgentEngine::sandbox_for_session(const std::string &session_key)
Sandbox manager for a session, or nullptr when isolation is off (gh#160).
src/core/engine.cpp:3641
Called by SCENARIO, execute_pending_pipeline, run_pending_delegation
Source · 7 lines
SandboxManager* AgentEngine::sandbox_for_session(
const std::string& session_key) {
if (!loop_config_.delegation_isolation) {
return nullptr;
}
return ensure_sandbox_manager(resolve_session_root(session_key));
}Activity · 3 steps
Requirements
seed_system_prompt_for_tier
void entropic::AgentEngine::seed_system_prompt_for_tier(const std::string &tier)
Seed a tier's system prompt on an empty conversation (gh#99).
src/core/engine.cpp:4135
Called by run_turn_as
Calls active_conversation, active_session_key, system_prompt_copy, workspace_prompt_for
Source · 15 lines
void AgentEngine::seed_system_prompt_for_tier(const std::string& tier) {
auto& convo = active_conversation();
if (!convo.messages.empty()) { return; }
auto sp = workspace_prompt_for(active_session_key(), tier);
auto it = tier_info_.find(tier);
if (!sp && it != tier_info_.end() && !it->second.system_prompt.empty()) {
sp = it->second.system_prompt;
}
if (!sp) { sp = system_prompt_copy(); }
if (sp->empty()) { return; }
Message sys;
sys.role = "system";
sys.content = *sp;
convo.messages.push_back(std::move(sys));
}Activity · 15 steps
Requirements
session_system_prompt
std::string entropic::AgentEngine::session_system_prompt(const std::string &session) const
The untiered system prompt a fresh conversation in session would be seeded with (gh#179).
src/core/engine.cpp:4116
Source · 5 lines
std::string AgentEngine::session_system_prompt(const std::string& session) const {
auto ws = workspace_prompt_for(session, "");
std::lock_guard<std::mutex> guard(prompt_mutex_);
return ws.value_or(system_prompt_);
}Activity · 3 steps
Requirements
set_active_session
void entropic::AgentEngine::set_active_session(const std::string &key)
Bind this turn to a caller-scoped session (gh#144, v2.12.0).
src/core/engine.cpp:3794
Called by SCENARIO, SCENARIO, SCENARIO, SCENARIO, entropic_run_session, entropic_run_session_as, stream_session_turn
Calls none
Source · 10 lines
void AgentEngine::set_active_session(const std::string& key) {
{
std::lock_guard<std::mutex> guard(conversations_mutex_);
conversations_[key]; // default-construct on first use
}
t_active_session_key = key;
t_active_session_bound = true;
std::lock_guard<std::mutex> guard(session_key_mutex_);
active_session_key_ = key;
}Activity · 6 steps
Requirements
set_concurrent_sessions
void entropic::AgentEngine::set_concurrent_sessions(bool enabled)
Allow runs on DIFFERENT session keys to proceed together.
src/core/engine.cpp:3895
Source · 6 lines
void AgentEngine::set_concurrent_sessions(bool enabled) {
std::lock_guard<std::mutex> guard(runs_mutex_);
concurrent_sessions_ = enabled;
logger->info("Per-session run concurrency {} (gh#158)",
enabled ? "ENABLED" : "disabled");
}Activity · 3 steps
Requirements
set_delegation_callbacks
void entropic::AgentEngine::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)
Register delegation start/complete callbacks (gh#29, v2.1.5).
src/core/engine.cpp:241
Source · 9 lines
void AgentEngine::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) {
std::lock_guard<std::mutex> lock(delegation_cb_mutex_);
delegation_cb_.start = on_start;
delegation_cb_.complete = on_complete;
delegation_cb_.user_data = user_data;
}Activity · 4 steps
Requirements
set_external_interrupt
void entropic::AgentEngine::set_external_interrupt(void(*cb)(void *user_data), void *user_data)
Register a callback invoked alongside interrupt() .
src/core/engine.cpp:1542
Source · 5 lines
void AgentEngine::set_external_interrupt(void (*cb)(void*),
void* user_data) {
external_interrupt_cb_ = cb;
external_interrupt_data_ = user_data;
}Activity · 2 steps
Requirements
set_external_reset
void entropic::AgentEngine::set_external_reset(void(*cb)(void *user_data), void *user_data)
Register the external transport interrupt-release callback.
src/core/engine.cpp:1560
Source · 5 lines
void AgentEngine::set_external_reset(void (*cb)(void*),
void* user_data) {
external_reset_cb_ = cb;
external_reset_data_ = user_data;
}Activity · 2 steps
Requirements
set_handoff_rules
void entropic::AgentEngine::set_handoff_rules(const std::unordered_map< std::string, std::vector< std::string > > &rules)
Store handoff rules for tier delegation.
src/core/engine.cpp:4796
Called by SCENARIO, SCENARIO, TEST_CASE, wire_prompts_and_persistence
Source · 7 lines
void AgentEngine::set_handoff_rules(
const std::unordered_map<std::string,
std::vector<std::string>>& rules)
{
handoff_rules_ = rules;
wire_internal_tier_resolution();
}Activity · 2 steps
Requirements
set_hooks
void entropic::AgentEngine::set_hooks(const HookInterface &hooks)
Set the hook dispatch interface.
src/core/engine.cpp:210
Called by SCENARIO, SCENARIO, SCENARIO, delegate_once, wire_hooks_and_validator
Calls set_hooks, set_hooks, set_hooks
Source · 6 lines
void AgentEngine::set_hooks(const HookInterface& hooks) {
hooks_ = hooks;
response_generator_.set_hooks(hooks);
context_manager_.set_hooks(hooks);
directive_processor_.set_hooks(hooks);
}Activity · 4 steps
Requirements
set_relay_single_delegate
void entropic::AgentEngine::set_relay_single_delegate(const std::string &name)
Mark a tier as relay-on-single-delegate.
src/core/engine.cpp:4785
Source · 3 lines
void AgentEngine::set_relay_single_delegate(const std::string& name) {
relay_single_delegate_tiers_.insert(name);
}Activity · 1 steps
Requirements
set_session_messages
bool entropic::AgentEngine::set_session_messages(const std::string &key, std::vector< Message > messages)
Replace one session's conversation wholesale (gh#165, v2.13.0).
src/core/engine.cpp:4547
Source · 17 lines
bool AgentEngine::set_session_messages(const std::string& key,
std::vector<Message> messages) {
{
std::lock_guard<std::mutex> guard(runs_mutex_);
if (active_runs_.count(key) > 0) {
logger->warn("session_context_set('{}') refused: a run on that "
"session is in flight", key);
return false;
}
}
std::lock_guard<std::mutex> guard(conversations_mutex_);
auto& convo = conversations_[key];
convo.messages = std::move(messages);
logger->info("Session '{}' conversation restored: {} messages", key,
convo.messages.size());
return true;
}Activity · 9 steps
Requirements
set_state
void entropic::AgentEngine::set_state(LoopContext &ctx, AgentState state)
Set agent state and fire callback.
src/core/engine.cpp:1443
Called by begin_loop_preamble, dir_complete, dispatch_pending_or_halt, evaluate_no_tool_decision, execute_iteration, execute_pending_delegation, execute_pending_pipeline, finalize_delegation_result, finish_with_carried_output, handle_terminal_finish_reasons, loop, process_tool_results
Calls agent_state_name, fire_hook_info
Source · 35 lines
void AgentEngine::set_state(LoopContext& ctx, AgentState state) {
auto prev = ctx.state;
ctx.state = state;
logger->info("State: {}", agent_state_name(state));
if (callbacks_.on_state_change != nullptr) {
callbacks_.on_state_change(
static_cast<int>(state), callbacks_.user_data);
}
// Persistent slot (gh#40 fallout, v2.1.10): the streaming entry
// points overwrite callbacks_ via set_callbacks(), so the legacy
// on_state_change is silent for streaming runs. The persistent
// slot is unaffected by that shuffle.
if (state_observer_ != nullptr) {
state_observer_(static_cast<int>(state), state_observer_data_);
}
// Hook: ON_STATE_CHANGE (v1.9.1)
{
std::string json = "{\"previous\":\""
+ std::string(agent_state_name(prev))
+ "\",\"current\":\""
+ std::string(agent_state_name(state)) + "\"}";
fire_hook_info(hooks_, ENTROPIC_HOOK_ON_STATE_CHANGE, json.c_str());
}
// Hook: ON_ERROR when entering ERROR state (v1.9.1)
if (state == AgentState::ERROR) {
std::string json = "{\"error_code\":\"STATE_ERROR\""
",\"iteration\":"
+ std::to_string(ctx.metrics.iterations)
+ ",\"consecutive\":" + std::to_string(ctx.consecutive_errors)
+ "}";
fire_hook_info(hooks_, ENTROPIC_HOOK_ON_ERROR, json.c_str());
}
}Activity · 12 steps
Requirements
set_state_observer
void entropic::AgentEngine::set_state_observer(void(*observer)(int state, void *user_data), void *user_data)
Register a persistent state-transition observer.
src/core/engine.cpp:4694
Called by SCENARIO, TEST_CASE, entropic_set_state_observer, rewire_state_observer
Calls set_state_observer
Source · 7 lines
void AgentEngine::set_state_observer(
void (*observer)(int, void*),
void* user_data) {
state_observer_ = observer;
state_observer_data_ = user_data;
response_generator_.set_state_observer(observer, user_data);
}Activity · 3 steps
Requirements
set_tier_info
void entropic::AgentEngine::set_tier_info(const std::string &name, const ChildContextInfo &info)
Store pre-resolved tier context info.
src/core/engine.cpp:4732
Source · 6 lines
void AgentEngine::set_tier_info(
const std::string& name,
const ChildContextInfo& info)
{
tier_info_[name] = info;
}Activity · 1 steps
Requirements
set_tier_resolution
void entropic::AgentEngine::set_tier_resolution(const TierResolutionInterface &tier_res)
Set the tier resolution interface for delegation.
src/core/engine.cpp:188
Called by SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, TEST_CASE, TEST_CASE, delegate_once, run_owing_lead, wire_internal_tier_resolution
Calls none
Source · 4 lines
void AgentEngine::set_tier_resolution(
const TierResolutionInterface& tier_res) {
tier_res_ = tier_res;
}Activity · 1 steps
Requirements
set_validation_provider
void entropic::AgentEngine::set_validation_provider(char *(*provider)(void *), void *user_data)
Register a JSON provider for the validation block in ON_COMPLETE hook context.
src/core/engine.cpp:270
Source · 5 lines
void AgentEngine::set_validation_provider(
char* (*provider)(void*), void* user_data) {
validation_provider_ = provider;
validation_provider_data_ = user_data;
}Activity · 2 steps
Requirements
set_workspace_prompts
void entropic::AgentEngine::set_workspace_prompts(const std::string &workspace, WorkspacePrompts prompts)
Register (or replace) one workspace's assembled prompts.
src/core/engine.cpp:4049
Source · 8 lines
void AgentEngine::set_workspace_prompts(const std::string& workspace,
WorkspacePrompts prompts) {
logger->info("[workspace] '{}' prompts set: default {} chars, {} tier(s)",
workspace, prompts.default_prompt.size(),
prompts.tier_prompts.size());
std::lock_guard<std::mutex> guard(prompt_mutex_);
workspace_prompts_[workspace] = std::move(prompts);
}Activity · 3 steps
Requirements
should_auto_chain
bool entropic::AgentEngine::should_auto_chain(const LoopContext &ctx, const std::string &finish_reason, const std::string &content)
Check if auto-chain should fire.
src/core/engine.cpp:3207
Source · 19 lines
bool AgentEngine::should_auto_chain(
const LoopContext& ctx,
const std::string& finish_reason,
const std::string& content) {
if (ctx.locked_tier.empty() || tier_res_.get_tier_param == nullptr) {
return false;
}
std::string auto_chain = tier_res_.get_tier_param(
ctx.locked_tier, "auto_chain", tier_res_.user_data);
if (auto_chain.empty()) {
return false;
}
bool triggered = (finish_reason == "length") ||
(finish_reason == "stop" &&
response_generator_.is_response_complete(content, "[]"));
return triggered;
}Activity · 7 steps
Requirements
should_stop
bool entropic::AgentEngine::should_stop(const LoopContext &ctx) const
Check if loop should stop.
src/core/engine.cpp:1409
Source · 5 lines
bool AgentEngine::should_stop(const LoopContext& ctx) const {
bool at_limit = ctx.metrics.iterations >= resolve_max_iterations(ctx)
|| ctx.consecutive_duplicate_attempts >= 3;
return is_terminal_state(ctx) || at_limit;
}Activity · 2 steps
Requirements
this_thread_run
std::shared_ptr< AgentEngine::RunState > entropic::AgentEngine::this_thread_run() const
Resolve the run this thread owns, if any (gh#158).
src/core/engine.cpp:3919
Source · 6 lines
std::shared_ptr<AgentEngine::RunState> AgentEngine::this_thread_run() const {
if (!t_holds_claim) { return nullptr; }
std::lock_guard<std::mutex> guard(runs_mutex_);
auto it = active_runs_.find(t_claimed_key);
return it == active_runs_.end() ? nullptr : it->second;
}Activity · 5 steps
Requirements
tier_requires_explicit_completion
bool entropic::AgentEngine::tier_requires_explicit_completion(const std::string &tier) const
Check if a tier requires an explicit entropic.complete / entropic.delegate tool call to conclude its turn.
src/core/engine.cpp:1322
Called by SCENARIO, finalize_delegation_result, record_explicit_completion_failure
Calls none
Source · 7 lines
bool AgentEngine::tier_requires_explicit_completion(
const std::string& tier) const {
if (tier_res_.get_tier_param == nullptr) { return false; }
auto val = tier_res_.get_tier_param(
tier, "explicit_completion", tier_res_.user_data);
return val == "true" || val == "1";
}Activity · 4 steps
Requirements
tier_resolution
const TierResolutionInterface & entropic::AgentEngine::tier_resolution() const
Get the tier resolution interface.
src/core/engine.cpp:282
Source · 3 lines
const TierResolutionInterface& AgentEngine::tier_resolution() const {
return tier_res_;
}Activity · 1 steps
Requirements
tier_system_prompt
const std::string & entropic::AgentEngine::tier_system_prompt(const std::string &name) const
A tier's resolved system prompt (gh#98).
src/core/engine.cpp:4772
Source · 6 lines
const std::string& AgentEngine::tier_system_prompt(
const std::string& name) const {
static const std::string kEmpty;
auto it = tier_info_.find(name);
return it == tier_info_.end() ? kEmpty : it->second.system_prompt;
}Activity · 3 steps
Requirements
tri_get_handoff_targets
std::vector< std::string > entropic::AgentEngine::tri_get_handoff_targets(const std::string &name, void *ud)
Look up handoff targets ( TierResolutionInterface trampoline).
src/core/engine.cpp:4854
Source · 8 lines
std::vector<std::string> AgentEngine::tri_get_handoff_targets(
const std::string& name, void* ud) {
auto* self = static_cast<AgentEngine*>(ud);
auto it = self->handoff_rules_.find(name);
std::vector<std::string> result;
if (it != self->handoff_rules_.end()) { result = it->second; }
return result;
}Activity · 6 steps
Requirements
tri_get_tier_param
std::string entropic::AgentEngine::tri_get_tier_param(const std::string &name, const std::string ¶m, void *ud)
Look up named tier parameter ( TierResolutionInterface trampoline).
src/core/engine.cpp:4903
Source · 26 lines
std::string AgentEngine::tri_get_tier_param(const std::string& name,
const std::string& param, void* ud) {
auto* self = static_cast<AgentEngine*>(ud);
auto it = self->tier_info_.find(name);
if (it == self->tier_info_.end()) { return ""; }
const auto& info = it->second;
std::string result;
if (param == "explicit_completion") {
result = info.explicit_completion ? "true" : "false";
}
if (param == "max_iterations" && info.max_iterations_override >= 0) {
result = std::to_string(info.max_iterations_override);
}
if (param == "max_tool_calls_per_turn"
&& info.max_tool_calls_per_turn_override >= 0) {
result = std::to_string(info.max_tool_calls_per_turn_override);
}
if (param == "max_consecutive_empty_turns"
&& info.max_consecutive_empty_turns_override >= 0) {
result = std::to_string(info.max_consecutive_empty_turns_override);
}
if (param == "allowed_tools" && !info.allowed_tools.empty()) {
result = join_csv(info.allowed_tools);
}
return result;
}Activity · 17 steps
Requirements
tri_resolve_tier
ChildContextInfo entropic::AgentEngine::tri_resolve_tier(const std::string &name, void *ud)
Resolve tier ( TierResolutionInterface trampoline).
src/core/engine.cpp:4816
Source · 15 lines
ChildContextInfo AgentEngine::tri_resolve_tier(
const std::string& name, void* ud) {
auto* self = static_cast<AgentEngine*>(ud);
auto it = self->tier_info_.find(name);
ChildContextInfo info;
if (it == self->tier_info_.end()) {
info.valid = false;
} else {
info = it->second;
info.system_prompt = self->workspace_prompt_for(
self->active_session_key(), name)
.value_or(info.system_prompt);
}
return info;
}Activity · 9 steps
Requirements
tri_tier_exists
bool entropic::AgentEngine::tri_tier_exists(const std::string &name, void *ud)
Check tier existence ( TierResolutionInterface trampoline).
src/core/engine.cpp:4840
Source · 4 lines
bool AgentEngine::tri_tier_exists(const std::string& name, void* ud) {
auto* self = static_cast<AgentEngine*>(ud);
return self->tier_info_.count(name) > 0;
}Activity · 2 steps
Requirements
try_auto_chain
bool entropic::AgentEngine::try_auto_chain(LoopContext &ctx, const std::string &finish_reason, const std::string &content)
Attempt auto-chain: child→COMPLETE, root→TierChange.
src/core/engine.cpp:3236
Called by evaluate_no_tool_decision
Source · 27 lines
bool AgentEngine::try_auto_chain(
LoopContext& ctx,
const std::string& finish_reason,
const std::string& content) {
if (!should_auto_chain(ctx, finish_reason, content)) {
return false;
}
if (ctx.delegation_depth > 0) {
logger->info("[AUTO-CHAIN] child depth={}, completing",
ctx.delegation_depth);
set_state(ctx, AgentState::COMPLETE);
return true;
}
// Root: tier change to auto_chain target
std::string target = tier_res_.get_tier_param(
ctx.locked_tier, "auto_chain", tier_res_.user_data);
if (!target.empty()) {
logger->info("[AUTO-CHAIN] root, tier change to '{}'", target);
TierChangeDirective tc(target, "auto_chain");
DirectiveResult r;
dir_tier_change(ctx, tc, r);
}
return !target.empty();
}Activity · 13 steps
Requirements
try_begin_turn
bool entropic::AgentEngine::try_begin_turn(const std::string &key, bool exclusive=false)
Try to claim one turn for a named session (gh#144 / gh#158).
src/core/engine.cpp:3812
Source · 29 lines
bool AgentEngine::try_begin_turn(const std::string& key, bool exclusive) {
{
std::lock_guard<std::mutex> guard(runs_mutex_);
// Same key twice is a genuine conflict whatever the configuration:
// the two runs share one conversation. A DIFFERENT key is refused
// only while per-session concurrency is off, which is the shipped
// default and reproduces v2.12.0 exactly.
// gh#217 (v2.14.6): an EXCLUSIVE claim (model release) needs no run
// in flight on ANY key, and while held refuses every other claim —
// unloading frees the context a decode in another session is using.
const bool blocked = active_runs_.count(key) > 0 || exclusive_turn_
|| ((exclusive || !concurrent_sessions_) && !active_runs_.empty());
if (blocked) { return false; }
exclusive_turn_ = exclusive;
auto claimed = std::make_shared<RunState>();
claimed->key = key;
active_runs_[key] = claimed;
running_flag_.store(true);
}
// The claim IS the session binding. Keeping them separate was a defect:
// the binding is thread-local, so a binding that outlived its run stayed
// on that thread and silently captured the NEXT unkeyed run — including
// one on a different handle entirely.
t_claimed_key = key;
t_holds_claim = true;
t_active_session_key = key;
t_active_session_bound = true;
return true;
}Activity · 14 steps
Requirements
wire_internal_tier_resolution
void entropic::AgentEngine::wire_internal_tier_resolution()
Wire internal TierResolutionInterface from stored tier data.
src/core/engine.cpp:4935
Source · 9 lines
void AgentEngine::wire_internal_tier_resolution() {
TierResolutionInterface tri;
tri.resolve_tier = &AgentEngine::tri_resolve_tier;
tri.tier_exists = &AgentEngine::tri_tier_exists;
tri.get_handoff_targets = &AgentEngine::tri_get_handoff_targets;
tri.get_tier_param = &AgentEngine::tri_get_tier_param;
tri.user_data = this;
set_tier_resolution(tri);
}