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
lines 300–300◇ if (ctx.locked_tier.empty() || tier_res_.get_tier_param == nullptr)lines 301–301return;lines 303–304auto mi = tier_res_.get_tier_param( ctx.locked_tier, "max_iterations", tier_res_.user_data);lines 305–305◇ if (!mi.empty())lines 306–306ctx.effective_max_iterations = std::atoi(mi.c_str());lines 307–308logger->info("[override] tier={} max_iterations={}", ctx.locked_tier, ctx.effective_max_iterations);lines 310–311auto mt = tier_res_.get_tier_param( ctx.locked_tier, "max_tool_calls_per_turn", tier_res_.user_data);lines 312–312◇ if (!mt.empty())lines 313–313ctx.effective_max_tool_calls_per_turn = std::atoi(mt.c_str());lines 314–315logger->info("[override] tier={} max_tool_calls_per_turn={}", ctx.locked_tier, ctx.effective_max_tool_calls_per_turn);

Requirements

REQ-IDEN-001

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

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
lines 390–390apply_identity_overrides(ctx);lines 391–391reinject_context_anchors(ctx);lines 392–392◇ if (ctx.metrics.start_time == 0.0)lines 393–393ctx.metrics.start_time = now_seconds();lines 395–395set_state(ctx, AgentState::PLANNING);

Requirements

REQ-COMPACT-002 REQ-IDEN-001 REQ-LOOP-001

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
lines 4080–4080std::lock_guard<std::mutex> guard(prompt_mutex_);lines 4081–4081session_workspace_[session] = workspace;

Requirements

REQ-MCP-027

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
lines 1017–1017◇ if (loop_config_.budget_mode == BudgetMode::tokens)lines 1022–1022constexpr size_t kCharsPerToken = 4;lines 1023–1024ctx.budget_tokens_since_tool += static_cast<int>(content_len / kCharsPerToken);lines 1025–1025return ctx.budget_tokens_since_tool;lines 1028–1028◇ if (ctx.budget_window_start_s == 0.0)lines 1029–1029ctx.budget_window_start_s = now_seconds();lines 1031–1031return static_cast<int>(now_seconds() - ctx.budget_window_start_s);

Requirements

REQ-LOOP-005

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
lines 2912–2915std::string body = "[COVERAGE GAP from " + tier + "]\n" "Summary so far: " + result.summary + "\n" "What's missing: " + result.gap_description;lines 2916–2916◇ if (!result.suggested_files.empty())lines 2917–2917body += "\nSuggested files to inspect:";lines 2918–2918◇ for (const auto& f : result.suggested_files)lines 2919–2919body += "\n - " + f;lines 2922–2922return body;

Requirements

REQ-DELEG-003

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

Show on the map →

Called by fire_post_generate_hook

Calls format_tool_evidence_entry

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
lines 2258–2258std::vector<const Message*> tool_msgs;lines 2259–2259◇ for (const auto& msg : messages)lines 2260–2260auto it = msg.metadata.find("tool_name");lines 2261–2261◇ if (it == msg.metadata.end() || it->second.empty())lines 2262–2262continue;lines 2264–2264tool_msgs.push_back(&msg);lines 2266–2266◇ if (tool_msgs.empty())lines 2266–2266return {};lines 2268–2269size_t elided = (tool_msgs.size() > max_results) ? (tool_msgs.size() - max_results) : 0;lines 2270–2270size_t start = elided;lines 2271–2271std::string out;lines 2272–2272◇ if (elided > 0)lines 2273–2274out += "(" + std::to_string(elided) + " earlier tool results elided for length)\n";lines 2276–2276◇ for (size_t i = start; i < tool_msgs.size(); ++i)lines 2277–2277out += format_tool_evidence_entry(*tool_msgs[i], chars_per_result);lines 2279–2279return out;

Requirements

REQ-HOOK-002

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
lines 2172–2172std::string manifest;lines 2173–2173◇ for (const auto& msg : messages)lines 2174–2174auto it = msg.metadata.find("tool_name");lines 2175–2175◇ if (it == msg.metadata.end() || it->second.empty())lines 2176–2176continue;lines 2183–2183auto orig = msg.metadata.find("original_content");lines 2184–2186size_t real_size = (orig != msg.metadata.end()) ? orig->second.size() : msg.content.size();lines 2187–2189manifest += "- " + it->second + " \xe2\x86\x92 " + std::to_string(real_size) + " chars\n";lines 2191–2191return manifest;

Requirements

REQ-HOOK-002

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

Show on the map →

Called by fire_complete_hook

Calls json_escape_engine

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
lines 2456–2456std::string arr = "[";lines 2457–2457bool first = true;lines 2458–2458◇ for (const auto& msg : messages)lines 2459–2459auto it = msg.metadata.find("tool_name");lines 2460–2460◇ if (it == msg.metadata.end() || it->second.empty())lines 2461–2461continue;lines 2463–2463◇ if (!first)lines 2463–2463arr += ",";lines 2464–2466arr += "{\"name\":\"" + json_escape_engine(it->second) + "\",\"content\":\"" + json_escape_engine(msg.content) + "\"}";lines 2467–2467first = false;lines 2469–2469arr += "]";lines 2470–2470return arr;

Requirements

REQ-HOOK-002

cancel_pause

void entropic::AgentEngine::cancel_pause()

Cancel pause and interrupt completely.

src/core/engine.cpp:1604

Show on the map →

Called by SCENARIO

Calls none

Source · 5 lines
void AgentEngine::cancel_pause() {
    logger->info("Pause cancelled, interrupting");
    pause_flag_.store(false);
    interrupt_flag_.store(true);
}
Activity · 3 steps
lines 1605–1605logger->info("Pause cancelled, interrupting");lines 1606–1606pause_flag_.store(false);lines 1607–1607interrupt_flag_.store(true);

Requirements

REQ-LOOP-006

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
lines 2418–2418◇ if (validation_provider_ == nullptr)lines 2418–2418return;lines 2419–2419char* v = validation_provider_(validation_provider_data_);lines 2420–2420◇ if (v == nullptr)lines 2420–2420return;lines 2421–2421std::string raw(v);lines 2422–2422free(v);lines 2423–2440try { 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. }

Requirements

REQ-LOOP-007

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

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
lines 988–988◇ if (loop_config_.budget_mode == BudgetMode::off)lines 988–988return;lines 992–992◇ if (made_tool_call)lines 993–993ctx.budget_tokens_since_tool = 0;lines 994–994ctx.budget_window_start_s = 0.0;lines 995–995ctx.budget_completion_nudged = false;lines 996–996return;lines 999–999int units = budget_units_consumed(ctx, content_len);lines 1000–1000◇ if (units < loop_config_.budget_limit)lines 1000–1000return;lines 1002–1002◇ if (!ctx.budget_completion_nudged)lines 1003–1003nudge_budget_completion(ctx);lines 1004–1004elselines 1005–1005hard_cut_budget(ctx);

Requirements

REQ-LOOP-005

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
lines 4497–4497std::lock_guard<std::mutex> guard(conversations_mutex_);lines 4498–4498auto it = conversations_.find(key);lines 4499–4499◇ if (it != conversations_.end())lines 4499–4499it->second.clear();

Requirements

REQ-LOOP-001

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
lines 4065–4066logger->info("[workspace] '{}' prompts cleared — its sessions use the " "handle's", workspace);lines 4067–4067std::lock_guard<std::mutex> guard(prompt_mutex_);lines 4068–4068workspace_prompts_.erase(workspace);

Requirements

REQ-MCP-027

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
lines 1619–1619int used = token_counter_.count_messages(messages);lines 1620–1620return {used, token_counter_.max_tokens};

Requirements

REQ-COMPACT-001

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

Show on the map →

Called by SCENARIO, process_tool_results

Calls none

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
lines 2012–2012auto tn = msg.metadata.find("tool_name");lines 2013–2014bool is_meta = tn != msg.metadata.end() && tn->second.rfind("entropic.", 0) == 0;lines 2015–2015◇ if (!is_meta)lines 2015–2015return;lines 2016–2016auto j = nlohmann::json::parse(msg.content, nullptr, false);lines 2017–2018bool is_envelope = j.is_object() && j.contains("action") && j["action"].is_string();lines 2019–2019◇ if (!is_envelope)lines 2019–2019return;lines 2020–2021msg.content = "(engine: " + j["action"].get<std::string>() + " directive accepted)";

Requirements

REQ-LOOP-007

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
lines 259–259std::lock_guard<std::mutex> lock(delegation_cb_mutex_);lines 260–260return delegation_cb_;

Requirements

REQ-DELEG-002

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
lines 1843–1843const auto& ca = static_cast<const ContextAnchorDirective&>(d);lines 1844–1844◇ if (ca.content.empty())lines 1846–1846std::lock_guard<std::mutex> guard(anchors_mutex_);lines 1847–1847context_anchors_.erase(ca.key);lines 1849–1849remove_anchor_messages(ctx, ca.key);lines 1850–1850logger->info("Removed anchor: {}", ca.key);lines 1851–1851return;lines 1854–1854std::lock_guard<std::mutex> guard(anchors_mutex_);lines 1855–1855context_anchors_[ca.key] = ca.content;lines 1857–1857remove_anchor_messages(ctx, ca.key);lines 1858–1858Message anchor;lines 1859–1859anchor.role = "user";lines 1860–1860anchor.content = ca.content;lines 1861–1861anchor.metadata["is_context_anchor"] = "true";lines 1862–1862anchor.metadata["anchor_key"] = ca.key;lines 1863–1863ctx.messages.push_back(std::move(anchor));lines 1864–1864logger->info("Updated anchor: {}", ca.key);

Requirements

REQ-COMPACT-002

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
lines 1754–1754const auto& cd = static_cast<const CompleteDirective&>(d);lines 1758–1758auto prior_state = ctx.state;lines 1759–1759set_state(ctx, AgentState::VERIFYING);lines 1762–1762◇ if (fire_complete_hook(cd.summary, ctx))lines 1763–1763logger->info("[DIRECTIVE] complete REJECTED by hook → revising");lines 1765–1765ctx.metadata["validator_phase"] = "revising";lines 1766–1766set_state(ctx, prior_state);lines 1767–1767r.stop_processing = false;lines 1768–1768return;lines 1771–1771ctx.metadata["explicit_completion_summary"] = cd.summary;lines 1778–1778◇ if (cd.coverage_gap)lines 1779–1779ctx.metadata["coverage_gap"] = "true";lines 1780–1780ctx.metadata["gap_description"] = cd.gap_description;lines 1781–1781nlohmann::json files_arr = cd.suggested_files;lines 1782–1782ctx.metadata["suggested_files_json"] = files_arr.dump();lines 1784–1784set_state(ctx, AgentState::COMPLETE);lines 1785–1785r.stop_processing = true;lines 1786–1787logger->info("[DIRECTIVE] complete coverage_gap={}", cd.coverage_gap);

Requirements

REQ-DELEG-003 REQ-HOOK-002

dir_delegate

void entropic::AgentEngine::dir_delegate(LoopContext &, const Directive &, DirectiveResult &)

@utility

src/core/engine.cpp:1709

Show on the map →

Called by none

Calls none

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
lines 1711–1711const auto& dl = static_cast<const DelegateDirective&>(d);lines 1712–1716ctx.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};lines 1717–1717r.stop_processing = true;lines 1718–1718◇ if (dl.resume_from_delegation_id.empty())lines 1719–1720logger->info("[DIRECTIVE] delegate: target={} task='{}'", dl.target, dl.task);lines 1721–1721elselines 1723–1724logger->info("[DIRECTIVE] resume_delegation: id={} task='{}'", dl.resume_from_delegation_id, dl.task);

Requirements

REQ-DELEG-002

dir_pipeline

void entropic::AgentEngine::dir_pipeline(LoopContext &, const Directive &, DirectiveResult &)

@utility

src/core/engine.cpp:1733

Show on the map →

Called by none

Calls none

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
lines 1735–1735const auto& pl = static_cast<const PipelineDirective&>(d);lines 1736–1736ctx.pending_pipeline = PendingPipeline{pl.stages, pl.task, pl.context};lines 1737–1737r.stop_processing = true;lines 1738–1738logger->info("[DIRECTIVE] pipeline: {} stages", pl.stages.size());

Requirements

REQ-DELEG-004

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
lines 1824–1824const auto& pm = static_cast<const PruneMessagesDirective&>(d);lines 1825–1826auto [pruned, freed] = context_manager_.prune_tool_results( ctx, pm.keep_recent);lines 1827–1827logger->info("[DIRECTIVE] prune: {} results, {} chars", pruned, freed);

Requirements

REQ-COMPACT-002

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
lines 1698–1698const auto& tc = static_cast<const TierChangeDirective&>(d);lines 1699–1699ctx.locked_tier = tc.tier;lines 1700–1700r.tier_changed = true;lines 1701–1701logger->info("[DIRECTIVE] tier_change: {}", tc.tier);

Requirements

REQ-IDEN-003

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

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
lines 1104–1104◇ if (run_interrupted() && !is_terminal_state(ctx))lines 1105–1106logger->info("[ITER] interrupt observed during tool processing — " "halting before pending dispatch");lines 1107–1107set_state(ctx, AgentState::INTERRUPTED);lines 1108–1108return;lines 1111–1111◇ if (is_terminal_state(ctx))lines 1112–1113◇ if (ctx.pending_delegation.has_value() || ctx.pending_pipeline.has_value())lines 1114–1117logger->info("[ITER] terminal state reached during batch " "tool processing — dropping pending {}", ctx.pending_delegation.has_value() ? "delegation" : "pipeline");lines 1119–1119return;lines 1122–1122◇ if (ctx.pending_delegation.has_value())lines 1123–1123ctx.metrics.iterations--;lines 1124–1124execute_pending_delegation(ctx);lines 1125–1125elselines 1125–1125◇ if (ctx.pending_pipeline.has_value())lines 1126–1126ctx.metrics.iterations--;lines 1127–1127execute_pending_pipeline(ctx);

Requirements

REQ-LOOP-003 REQ-LOOP-006

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

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
lines 2404–2404ctx.pending_validation_feedback.clear();lines 2405–2405ctx.pending_anti_spiral_warning.clear();lines 2406–2406fire_post_generate_hook(result, ctx.locked_tier, ctx.messages);lines 2409–2409capture_validation_feedback(ctx);

Requirements

REQ-HOOK-002 REQ-LOOP-003

drop_session

bool entropic::AgentEngine::drop_session(const std::string &key)

Forget a session entirely.

src/core/engine.cpp:4509

Show on the map →

Called by SCENARIO, entropic_session_drop

Calls none

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
lines 4510–4510std::lock_guard<std::mutex> guard(conversations_mutex_);lines 4511–4511◇ if (key.empty())lines 4512–4512conversations_[key].clear();lines 4513–4513return true;lines 4515–4515return conversations_.erase(key) > 0;

Requirements

REQ-LOOP-001

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

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, TEST_CASE, ~HandleTurnGuard

Calls none

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
lines 3850–3850std::lock_guard<std::mutex> guard(runs_mutex_);lines 3851–3851active_runs_.erase(key);lines 3852–3852running_flag_.store(!active_runs_.empty());lines 3855–3855◇ if (active_runs_.empty())lines 3855–3855exclusive_turn_ = false;lines 3859–3859◇ if (t_holds_claim && t_claimed_key == key)lines 3860–3860t_holds_claim = false;lines 3861–3861t_active_session_bound = false;lines 3862–3862t_active_session_key.clear();
void entropic::AgentEngine::end_turn()

Release the turn this thread claimed (gh#158).

src/core/engine.cpp:3871

Show on the map →

Called by none

Calls active_session_key

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
lines 3875–3875end_turn(t_holds_claim ? t_claimed_key : active_session_key());

Requirements

REQ-API-009

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
lines 3550–3550◇ if (root.empty())lines 3551–3551return nullptr;lines 3553–3553std::lock_guard<std::mutex> guard(sandbox_mutex_);lines 3554–3554auto it = sandbox_mgrs_.find(root);lines 3555–3555◇ if (it != sandbox_mgrs_.end())lines 3556–3556return &it->second;lines 3560–3563auto [pos, inserted] = sandbox_mgrs_.emplace( std::piecewise_construct, std::forward_as_tuple(root), std::forward_as_tuple(root));lines 3564–3564(void)inserted;lines 3565–3565return &pos->second;

Requirements

REQ-DELEG-002

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

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
lines 1143–1143◇ if (handle_terminal_finish_reasons(ctx, finish_reason))lines 1143–1143return;lines 1144–1144◇ if (try_auto_chain(ctx, finish_reason, content))lines 1145–1145logger->info("[DECISION] auto-chain triggered");lines 1146–1146return;lines 1148–1148◇ if (record_explicit_completion_failure(ctx, finish_reason, content))lines 1149–1149return;lines 1151–1151◇ if (response_generator_.is_response_complete(content, "[]"))lines 1152–1152logger->info("[DECISION] response complete");lines 1153–1153set_state(ctx, AgentState::COMPLETE);

Requirements

REQ-LOOP-004

execute_iteration

void entropic::AgentEngine::execute_iteration(LoopContext &ctx)

Execute a single loop iteration.

src/core/engine.cpp:886

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
lines 887–891logger->info("[LOOP] iter {}/{} state={} msgs={}", ctx.metrics.iterations, resolve_max_iterations(ctx), agent_state_name(ctx.state), ctx.messages.size());lines 893–893fire_loop_iteration_hook(hooks_, ctx);lines 895–895context_manager_.refresh_context_limit(ctx, 0);lines 896–896context_manager_.prune_old_tool_results(ctx);lines 897–897context_manager_.check_compaction(ctx);lines 899–899fire_context_assemble_hook(hooks_, ctx);lines 901–901set_state(ctx, AgentState::EXECUTING);lines 904–904◇ if (fire_pre_hook(ENTROPIC_HOOK_PRE_GENERATE, ctx.metrics.iterations))lines 905–905set_state(ctx, AgentState::COMPLETE);lines 906–906return;lines 909–909auto result = response_generator_.generate_response(ctx);lines 910–910dispatch_post_generate(ctx, result);lines 911–911process_generation_result(ctx, result);

Requirements

REQ-HOOK-002 REQ-LOOP-003

execute_pending_delegation

void entropic::AgentEngine::execute_pending_delegation(LoopContext &ctx)

Execute a pending delegation after tool processing.

src/core/engine.cpp:2823

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
lines 2824–2824auto pending = std::move(*ctx.pending_delegation);lines 2825–2825ctx.pending_delegation.reset();lines 2827–2827◇ if (reject_delegation_if_guarded(ctx, pending))lines 2827–2827return;lines 2829–2829set_state(ctx, AgentState::DELEGATING);lines 2838–2838std::vector<Message> resume_history;lines 2839–2839bool blocked = false;lines 2842–2843const bool is_resume = !pending.resume_from_delegation_id.empty() || pending.resume_by_target;lines 2844–2845◇ if (is_resume && !resolve_resume_delegation(ctx, pending, resume_history))lines 2846–2846blocked = true;lines 2847–2847elselines 2847–2847◇ if (fire_delegate_pre_hook(pending, ctx.delegation_depth))lines 2848–2848logger->info("ON_DELEGATE hook cancelled delegation");lines 2849–2849blocked = true;lines 2851–2851◇ if (blocked)lines 2852–2852set_state(ctx, AgentState::EXECUTING);lines 2853–2853return;lines 2856–2856fire_delegation_start(ctx, pending.target, pending.task);lines 2857–2858auto result = run_pending_delegation( ctx, pending, std::move(resume_history));lines 2859–2859push_delegation_result(ctx, pending.target, result);lines 2862–2862◇ if (result.success)lines 2863–2863ctx.last_failed_delegation_target.clear();lines 2864–2864ctx.consecutive_failed_delegations = 0;lines 2865–2865elselines 2865–2865◇ if (pending.target == ctx.last_failed_delegation_target)lines 2866–2866++ctx.consecutive_failed_delegations;lines 2867–2867elselines 2868–2868ctx.last_failed_delegation_target = pending.target;lines 2869–2869ctx.consecutive_failed_delegations = 1;lines 2872–2872fire_delegation_complete(ctx, pending.target, result);lines 2873–2874fire_delegate_complete_hook(pending.target, result.success, result.summary);lines 2876–2876finalize_delegation_result(ctx, result);

Requirements

REQ-DELEG-002 REQ-LOOP-003

execute_pending_pipeline

void entropic::AgentEngine::execute_pending_pipeline(LoopContext &ctx)

Execute a pending pipeline after tool processing.

src/core/engine.cpp:3110

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
lines 3111–3111auto pending = std::move(*ctx.pending_pipeline);lines 3112–3112ctx.pending_pipeline.reset();lines 3114–3114◇ if (reject_pipeline_if_guarded(ctx, pending))lines 3114–3114return;lines 3116–3116set_state(ctx, AgentState::DELEGATING);lines 3122–3122auto root = resolve_session_root(ctx.session_key);lines 3123–3125DelegationManager mgr(run_child_loop_trampoline, this, tier_res_, root, sandbox_for_session(ctx.session_key));lines 3126–3126auto swap = dir_swap_snapshot();lines 3127–3127mgr.set_dir_swap(swap.first, swap.second);lines 3128–3128◇ if (storage_.create_delegation != nullptr)lines 3129–3129mgr.set_storage(&storage_);lines 3134–3134auto cb_snap = delegation_callbacks_snapshot();lines 3135–3136mgr.set_delegation_callbacks( cb_snap.start, cb_snap.complete, cb_snap.user_data);lines 3137–3137std::vector<DelegationResult> stage_log;lines 3138–3139auto result = mgr.execute_pipeline( ctx, pending.stages, pending.task, stage_log, pending.context);lines 3141–3141std::string tag = result.success ? "COMPLETE" : "FAILED";lines 3142–3142std::string content = "[PIPELINE " + tag + "]";lines 3143–3143◇ for (size_t i = 0; i < stage_log.size(); ++i)lines 3144–3146content += "\nStage " + std::to_string(i + 1) + " (" + stage_log[i].target_tier + "): " + stage_log[i].summary;lines 3148–3148content += "\nFinal: " + result.summary;lines 3149–3149Message result_msg;lines 3150–3150result_msg.role = "user";lines 3151–3151result_msg.content = std::move(content);lines 3152–3152ctx.messages.push_back(std::move(result_msg));lines 3154–3154set_state(ctx, AgentState::EXECUTING);

Requirements

REQ-DELEG-001 REQ-DELEG-004

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
lines 3384–3384std::optional<std::string> error;lines 3385–3385std::string raw;lines 3386–3386◇ if (storage_.load_delegation_with_messages == nullptr)lines 3387–3387error = "storage unavailable";lines 3388–3388elselines 3388–3389◇ if (!storage_.load_delegation_with_messages( id.c_str(), raw, storage_.user_data))lines 3390–3390error = "unknown delegation_id";lines 3391–3391elselines 3392–3392parsed = nlohmann::json::parse(raw, nullptr, false);lines 3393–3393◇ if (parsed.is_discarded() || !parsed.is_object())lines 3394–3394error = "malformed storage payload";lines 3397–3397◇ if (error.has_value())lines 3398–3398logger->error("resume_delegation '{}': {}", id, *error);lines 3399–3399push_resume_failure(ctx, *error, id);lines 3400–3400return false;lines 3402–3402return true;

Requirements

REQ-DELEG-002

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

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
lines 2975–2976const bool in_relay_tier = relay_single_delegate_tiers_.count(ctx.locked_tier) > 0;lines 2977–2977◇ if (in_relay_tier && result.coverage_gap)lines 2978–2978Message gap;lines 2979–2979gap.role = "user";lines 2980–2981gap.content = build_coverage_gap_message( result.target_tier, result);lines 2982–2982ctx.messages.push_back(std::move(gap));lines 2983–2983ctx.metadata["relay_status"] = "coverage_gap_suppressed";lines 2984–2987logger->info( "[COVERAGE GAP] suppressing auto-relay for tier={} " "({} suggested files)", result.target_tier, result.suggested_files.size());lines 2988–2988set_state(ctx, AgentState::EXECUTING);lines 2989–2989return;lines 2991–2991◇ if (result.success && in_relay_tier)lines 2992–2992relay_partial_result(ctx, result.summary);lines 2993–2993log_relay_status(ctx);lines 2994–2994return;lines 2996–2996◇ if (!result.terminal_reason.empty() && in_relay_tier)lines 2997–2998relay_partial_result(ctx, "[partial — budget_exhausted] " + result.summary);lines 2999–2999log_relay_status(ctx, result.terminal_reason);lines 3000–3000return;lines 3002–3003bool needs_explicit = tier_requires_explicit_completion( ctx.locked_tier);lines 3004–3004◇ if (result.success && !needs_explicit)lines 3005–3005fold_delegation_summary(ctx, result.summary);lines 3007–3008set_state(ctx, (result.success && !needs_explicit) ? AgentState::COMPLETE : AgentState::EXECUTING);

Requirements

REQ-DELEG-003

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

Show on the map →

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
lines 803–803std::string carried = last_substantive_assistant(ctx);lines 804–804Message forced;lines 805–805forced.role = "assistant";lines 806–806forced.content = annotate_hard_stop(carried, reason, stop_noun);lines 807–807ctx.messages.push_back(std::move(forced));lines 808–808ctx.metadata["terminal_reason"] = terminal_reason;lines 809–810ctx.metadata["cap_carried_content"] = carried.empty() ? "false" : "true";lines 811–811set_state(ctx, AgentState::COMPLETE);

Requirements

REQ-LOOP-002 REQ-LOOP-005

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

Show on the map →

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
lines 2496–2496◇ if (hooks_.fire_pre == nullptr)lines 2496–2496return false;lines 2498–2498auto tool_results = build_tool_results_json(ctx.messages);lines 2502–2502std::string validation_block = ",\"validation\":null";lines 2503–2503◇ if (validation_provider_ != nullptr)lines 2504–2504char* v = validation_provider_(validation_provider_data_);lines 2505–2505◇ if (v != nullptr)lines 2506–2506validation_block = ",\"validation\":" + std::string(v);lines 2507–2507free(v);lines 2510–2516std::string json = "{\"summary\":\"" + json_escape_engine(summary) + "\",\"tier\":\"" + ctx.locked_tier + "\",\"tool_results\":" + tool_results + ",\"iteration\":" + std::to_string(ctx.metrics.iterations) + validation_block + "}";lines 2517–2517char* modified = nullptr;lines 2518–2519int rc = hooks_.fire_pre(hooks_.registry, ENTROPIC_HOOK_ON_COMPLETE, json.c_str(), &modified);lines 2520–2520◇ if (modified != nullptr)lines 2525–2525Message feedback;lines 2526–2526feedback.role = "user";lines 2527–2528feedback.content = std::string("[CITATION VALIDATION] ") + mcp::sanitize_utf8(modified);lines 2529–2530const_cast<LoopContext&>(ctx).messages.push_back( std::move(feedback));lines 2531–2531free(modified);lines 2533–2533return rc != 0;

Requirements

REQ-HOOK-002

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
lines 104–105std::string json = "{\"message_count\":" + std::to_string(ctx.messages.size()) + "}";lines 106–107fire_hook_info(hooks, ENTROPIC_HOOK_ON_CONTEXT_ASSEMBLE, json.c_str());

Requirements

REQ-HOOK-002

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
lines 2611–2611◇ if (hooks_.fire_post == nullptr)lines 2612–2612return;lines 2614–2615std::string json = detail::build_delegate_complete_json( target, success, summary);lines 2616–2616char* out = nullptr;lines 2617–2618hooks_.fire_post(hooks_.registry, ENTROPIC_HOOK_ON_DELEGATE_COMPLETE, json.c_str(), &out);lines 2619–2619free(out);

Requirements

REQ-HOOK-002

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
lines 2547–2547◇ if (hooks_.fire_pre == nullptr)lines 2548–2548return false;lines 2550–2553std::string json = "{\"target_tier\":\"" + pending.target + "\",\"task\":\"" + pending.task + "\",\"depth\":" + std::to_string(depth) + "}";lines 2554–2554char* modified = nullptr;lines 2555–2556int rc = hooks_.fire_pre(hooks_.registry, ENTROPIC_HOOK_ON_DELEGATE, json.c_str(), &modified);lines 2557–2557free(modified);lines 2558–2558return rc != 0;

Requirements

REQ-DELEG-002 REQ-HOOK-002

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
lines 3188–3188◇ if (callbacks_.on_delegation_complete != nullptr)lines 3189–3192callbacks_.on_delegation_complete( "", tier.c_str(), result.summary.c_str(), result.success ? 1 : 0, callbacks_.user_data);

Requirements

REQ-DELEG-002

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
lines 3169–3169◇ if (callbacks_.on_delegation_start != nullptr)lines 3170–3172callbacks_.on_delegation_start( "", tier.c_str(), task.c_str(), callbacks_.user_data);

Requirements

REQ-DELEG-002

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

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
lines 41–41◇ if (hooks.fire_info != nullptr)lines 42–42hooks.fire_info(hooks.registry, point, json);

Requirements

REQ-HOOK-002

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

Show on the map →

Called by loop

Calls agent_state_name, fire_hook_info

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
lines 71–74std::string json = "{\"final_state\":\"" + std::string(agent_state_name(ctx.state)) + "\",\"iterations\":" + std::to_string(ctx.metrics.iterations) + "}";lines 75–75fire_hook_info(hooks, ENTROPIC_HOOK_ON_LOOP_END, json.c_str());

Requirements

REQ-HOOK-002

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

Show on the map →

Called by execute_iteration

Calls agent_state_name, fire_hook_info

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
lines 87–91std::string json = "{\"iteration\":" + std::to_string(ctx.metrics.iterations) + ",\"state\":\"" + agent_state_name(ctx.state) + "\",\"consecutive_errors\":" + std::to_string(ctx.consecutive_errors) + "}";lines 92–92fire_hook_info(hooks, ENTROPIC_HOOK_ON_LOOP_ITERATION, json.c_str());

Requirements

REQ-HOOK-002

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
lines 55–58std::string json = "{\"message_count\":" + std::to_string(ctx.messages.size()) + ",\"delegation_depth\":" + std::to_string(ctx.delegation_depth) + "}";lines 59–59fire_hook_info(hooks, ENTROPIC_HOOK_ON_LOOP_START, json.c_str());

Requirements

REQ-HOOK-002

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

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
lines 2341–2341◇ if (hooks_.fire_post == nullptr)lines 2342–2342return;lines 2344–2344auto manifest = build_tool_manifest(messages);lines 2345–2345manifest = enrich_manifest_with_history(manifest, tool_exec_);lines 2346–2346auto sys = extract_system_prompt(messages);lines 2354–2354auto evidence = build_tool_evidence(messages, 20, 800);lines 2355–2361std::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) + "\"}";lines 2362–2362char* out = nullptr;lines 2363–2364hooks_.fire_post(hooks_.registry, ENTROPIC_HOOK_POST_GENERATE, json.c_str(), &out);lines 2365–2365◇ if (out != nullptr)lines 2371–2371result.content = mcp::sanitize_utf8(out);lines 2372–2372logger->info("POST_GENERATE hook revised content");lines 2373–2373free(out);

Requirements

REQ-HOOK-002

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
lines 2105–2105◇ if (hooks_.fire_pre == nullptr)lines 2106–2106return false;lines 2108–2109std::string json = "{\"iteration\":" + std::to_string(iteration) + "}";lines 2110–2110char* modified = nullptr;lines 2111–2112int rc = hooks_.fire_pre(hooks_.registry, point, json.c_str(), &modified);lines 2113–2113free(modified);lines 2114–2114return rc != 0;

Requirements

REQ-HOOK-002 REQ-LOOP-003

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

Show on the map →

Called by SCENARIO, process_tool_results

Calls none

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
lines 1376–1376auto tn_it = tool_result_msg.metadata.find("tool_name");lines 1377–1378bool is_complete = tn_it != tool_result_msg.metadata.end() && tn_it->second == "entropic.complete";lines 1379–1379◇ if (!is_complete || ctx.messages.empty())lines 1379–1379return false;lines 1380–1380auto& last = ctx.messages.back();lines 1381–1381auto sum_it = ctx.metadata.find("explicit_completion_summary");lines 1382–1383bool foldable = last.role == "assistant" && last.content.empty() && sum_it != ctx.metadata.end();lines 1384–1384◇ if (!foldable)lines 1384–1384return false;lines 1385–1385last.content = sum_it->second;lines 1386–1386return true;

Requirements

REQ-LOOP-007

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
lines 2942–2942◇ for (auto rit = ctx.messages.rbegin(); rit != ctx.messages.rend(); ++rit)lines 2944–2944◇ if (rit->role == "assistant" && rit->content.empty())lines 2945–2945rit->content = summary;lines 2946–2946break;

Requirements

REQ-LOOP-007

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
lines 826–831finish_with_carried_output( ctx, "iteration cap reached after " + std::to_string(ctx.metrics.iterations) + " iterations", "cap", "budget_exhausted");

Requirements

REQ-LOOP-002

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

Show on the map →

Called by TEST_CASE

Calls none

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
lines 4760–4760auto it = tier_info_.find(name);lines 4761–4761◇ if (it == tier_info_.end())lines 4761–4761return {};lines 4762–4762return it->second.allowed_tools;

Requirements

REQ-IDEN-001 REQ-LOOP-004

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
lines 1181–1181bool handled = true;lines 1182–1182◇ if (finish_reason == "interrupted")lines 1183–1183logger->info("[DECISION] interrupted");lines 1184–1184set_state(ctx, AgentState::INTERRUPTED);lines 1185–1185elselines 1185–1185◇ if (finish_reason == "context_overflow")lines 1186–1186ctx.metadata["failure_reason"] = "context_overflow";lines 1187–1187ctx.metadata["failure_tier"] = ctx.locked_tier;lines 1188–1191logger->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);lines 1192–1192set_state(ctx, AgentState::ERROR);lines 1193–1193elselines 1193–1193◇ if (finish_reason == "length")lines 1194–1194logger->info("[DECISION] length, continuing");lines 1195–1195elselines 1196–1196handled = false;lines 1198–1198return handled;

Requirements

REQ-INFER-026 REQ-LOOP-006

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
lines 1075–1076logger->warn("[BUDGET] thinking budget exhausted after nudge — " "hard-cutting turn");lines 1077–1082finish_with_carried_output( ctx, "thinking budget exhausted after the completion nudge went " "unheeded; no tool call was emitted", "cut", "budget_exhausted_thinking");

Requirements

REQ-LOOP-005

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

Show on the map →

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
lines 4747–4747return tier_info_.count(name) > 0;

Requirements

REQ-IDEN-001

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

Show on the map →

Called by run

Calls none

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
lines 529–529◇ if (storage_.create_conversation == nullptr)lines 529–529return;lines 530–530std::string conv_id;lines 531–532◇ if (storage_.create_conversation("session", conv_id, storage_.user_data) && !conv_id.empty())lines 533–533ctx.conversation_id = std::move(conv_id);lines 534–534elselines 535–536logger->warn("Storage create_conversation failed at run() init; " "delegations will not persist this session (gh#48)");

Requirements

REQ-DELEG-002

interrupt

void entropic::AgentEngine::interrupt()

Interrupt the running loop (thread-safe).

src/core/engine.cpp:1490

Show on the map →

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
lines 1496–1496std::lock_guard<std::mutex> guard(runs_mutex_);lines 1497–1497◇ for (auto& [key, run] : active_runs_)lines 1498–1498(void)key;lines 1499–1499run->interrupt.store(true, std::memory_order_release);lines 1502–1502◇ if (!interrupt_flag_.exchange(true))lines 1503–1503logger->info("Engine interrupted");lines 1508–1508◇ if (external_interrupt_cb_ != nullptr)lines 1509–1509external_interrupt_cb_(external_interrupt_data_);lines 1512–1512pause_flag_.store(false);

Requirements

REQ-LOOP-006

interrupt_session

bool entropic::AgentEngine::interrupt_session(const std::string &key)

Interrupt exactly one session's run (gh#158).

src/core/engine.cpp:3933

Show on the map →

Called by SCENARIO, entropic_interrupt_session

Calls none

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
lines 3934–3934std::shared_ptr<RunState> run;lines 3936–3936std::lock_guard<std::mutex> guard(runs_mutex_);lines 3937–3937auto it = active_runs_.find(key);lines 3938–3938◇ if (it != active_runs_.end())lines 3938–3938run = it->second;lines 3940–3940◇ if (!run)lines 3941–3941logger->info("interrupt_session('{}'): no run in flight", key);lines 3942–3942return false;lines 3944–3944run->interrupt.store(true, std::memory_order_release);lines 3945–3945logger->info("Session '{}' interrupted", key);lines 3946–3946return true;

Requirements

REQ-LOOP-006

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
lines 1345–1345◇ if (target == ctx.locked_tier)lines 1345–1345return true;lines 1346–1346◇ for (const auto& anc : ctx.delegation_ancestor_tiers)lines 1347–1347◇ if (anc == target)lines 1347–1347return true;lines 1349–1349return false;

Requirements

REQ-DELEG-001

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
lines 1361–1363return target == ctx.last_failed_delegation_target && ctx.consecutive_failed_delegations >= loop_config_.max_consecutive_failed_delegations;

Requirements

REQ-DELEG-001

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

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
lines 1430–1432return ctx.state == AgentState::COMPLETE || ctx.state == AgentState::ERROR || ctx.state == AgentState::INTERRUPTED;

Requirements

REQ-LOOP-001

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

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
lines 3659–3659SessionRootInterface iface;lines 3661–3661std::lock_guard<std::mutex> guard(sandbox_mutex_);lines 3662–3662iface = session_root_;lines 3664–3665◇ if (!loop_config_.delegation_isolation || iface.unsafe_external_tools == nullptr)lines 3666–3666return {};lines 3668–3670auto info = tier_res_.resolve_tier ? tier_res_.resolve_tier(target_tier, tier_res_.user_data) : ChildContextInfo{};lines 3671–3672return iface.unsafe_external_tools( ctx.session_key, info.allowed_tools, iface.user_data);

Requirements

REQ-DELEG-005

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
lines 3027–3027std::string verdict;lines 3028–3028◇ if (validation_provider_ != nullptr)lines 3029–3029char* v = validation_provider_(validation_provider_data_);lines 3030–3030◇ if (v != nullptr)lines 3031–3031std::string jv(v);lines 3032–3032free(v);lines 3033–3033auto pos = jv.find("\"verdict\":\"");lines 3034–3034◇ if (pos != std::string::npos)lines 3035–3035pos += 11;lines 3036–3036auto end = jv.find('"', pos);lines 3037–3037◇ if (end != std::string::npos)lines 3038–3038verdict = jv.substr(pos, end - pos);lines 3043–3043◇ if (!terminal_reason.empty())lines 3044–3044ctx.metadata["relay_status"] = "budget_exhausted_relayed";lines 3045–3048logger->warn( "Relay: single-delegate result used " "(partial — terminal_reason={}, verdict={})", terminal_reason, verdict.empty() ? "none" : verdict);lines 3049–3049return;lines 3051–3051◇ if (verdict == "skipped" || verdict.empty())lines 3052–3052ctx.metadata["relay_status"] = "validation_skipped";lines 3053–3055logger->info( "Relay: single-delegate result used " "(lead validation skipped per config)");lines 3056–3056elselines 3057–3057ctx.metadata["relay_status"] = "validated";lines 3058–3060logger->info( "Relay: single-delegate result used " "(passed lead validation)");

Requirements

REQ-DELEG-003

loop

void entropic::AgentEngine::loop(LoopContext &ctx)

Main loop implementation.

src/core/engine.cpp:841

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
lines 842–842fire_loop_start_hook(hooks_, ctx);lines 844–844◇ while (!should_stop(ctx))lines 845–845ctx.metrics.iterations++;lines 847–847◇ if (run_interrupted())lines 848–848set_state(ctx, AgentState::INTERRUPTED);lines 849–849break;lines 852–852execute_iteration(ctx);lines 854–854◇ if (ctx.state == AgentState::ERROR)lines 855–855break;lines 859–860◇ if (ctx.metrics.iterations >= resolve_max_iterations(ctx) && !is_terminal_state(ctx))lines 870–872logger->warn("Loop ended due to max iterations ({}/{}) — " "forcing synthetic entropic.complete", ctx.metrics.iterations, resolve_max_iterations(ctx));lines 873–873force_iteration_cap_completion(ctx);lines 876–876fire_loop_end_hook(hooks_, ctx);

Requirements

REQ-HOOK-002 REQ-LOOP-002

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

Show on the map →

Called by SCENARIO, entropic_session_context_get, seeded

Calls none

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
lines 4471–4471std::lock_guard<std::mutex> guard(conversations_mutex_);lines 4472–4472auto it = conversations_.find(key);lines 4473–4474return it == conversations_.end() ? std::vector<Message>{} : it->second.messages;

Requirements

REQ-LOOP-001

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
lines 1040–1040ctx.budget_completion_nudged = true;lines 1041–1041ctx.budget_tokens_since_tool = 0;lines 1042–1044ctx.budget_window_start_s = (loop_config_.budget_mode == BudgetMode::wall_clock) ? now_seconds() : 0.0;lines 1045–1048logger->warn("[BUDGET] thinking budget reached ({} {}); nudging completion", loop_config_.budget_limit, loop_config_.budget_mode == BudgetMode::tokens ? "tokens" : "seconds");lines 1049–1052Message 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."};lines 1053–1053ctx.messages.push_back(std::move(nudge));

Requirements

REQ-LOOP-005

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

Show on the map →

Called by none

Calls decode_tool_calls_json, sanitize_utf8

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
lines 1961–1961◇ if (inference_.parse_tool_calls == nullptr)lines 1962–1962return {raw_content, {}};lines 1965–1965char* cleaned = nullptr;lines 1966–1966char* tc_json = nullptr;lines 1967–1969int rc = inference_.parse_tool_calls( raw_content.c_str(), &cleaned, &tc_json, inference_.adapter_data);lines 1989–1990std::string cleaned_str = mcp::sanitize_utf8(cleaned ? cleaned : raw_content);lines 1991–1991std::string tc_str = mcp::sanitize_utf8(tc_json ? tc_json : "[]");lines 1993–1993◇ if (inference_.free_fn != nullptr)lines 1994–1994◇ if (cleaned != nullptr)lines 1994–1994inference_.free_fn(cleaned);lines 1995–1995◇ if (tc_json != nullptr)lines 1995–1995inference_.free_fn(tc_json);lines 1998–1998◇ if (rc != 0)lines 1998–1998return {cleaned_str, {}};lines 1999–1999auto calls = decode_tool_calls_json(tc_str);lines 2000–2000◇ if (!calls.empty())lines 2001–2001logger->info("Parsed tool calls from model output");lines 2003–2003return {cleaned_str, std::move(calls)};

Requirements

REQ-LOOP-003

pause

void entropic::AgentEngine::pause()

Pause generation (thread-safe).

src/core/engine.cpp:1594

Show on the map →

Called by SCENARIO

Calls none

Source · 4 lines
void AgentEngine::pause() {
    logger->info("Engine paused");
    pause_flag_.store(true);
}
Activity · 2 steps
lines 1595–1595logger->info("Engine paused");lines 1596–1596pause_flag_.store(true);

Requirements

REQ-LOOP-006

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

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
lines 939–939auto [cleaned, tool_calls] = parse_tool_calls(result.content);lines 940–942logger->info("[ITER] finish={}, {} tool call(s), {} chars", result.finish_reason, tool_calls.size(), cleaned.size());lines 943–943Message assistant_msg{"assistant", cleaned};lines 950–950◇ if (!tool_calls.empty())lines 951–951assistant_msg.metadata[tool_meta::kCallText] = result.content;lines 952–952assistant_msg.metadata[tool_meta::kCalls] = tool_calls_to_json(tool_calls);lines 954–954ctx.messages.push_back(std::move(assistant_msg));lines 956–957bool made_tool_call = !tool_calls.empty() && tool_exec_.process_tool_calls != nullptr;lines 961–961bool made_progress = false;lines 962–962◇ if (made_tool_call)lines 963–963made_progress = process_tool_results(ctx, tool_calls);lines 966–966◇ if (made_progress)lines 967–967ctx.metadata["zero_tool_call_retries"] = "0";lines 968–968ctx.metadata.erase("force_tool_call");lines 970–970elselines 971–971evaluate_no_tool_decision(ctx, cleaned, result.finish_reason);lines 976–976charge_thinking_budget(ctx, result.content.size(), made_progress);lines 978–978dispatch_pending_or_halt(ctx);

Requirements

REQ-LOOP-003

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

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
lines 2036–2036set_state(ctx, AgentState::WAITING_TOOL);lines 2038–2039auto results = tool_exec_.process_tool_calls( ctx, tool_calls, tool_exec_.user_data);lines 2041–2042logger->info("[TOOLS] {} call(s) -> {} result message(s)", tool_calls.size(), results.size());lines 2049–2049bool made_progress = false;lines 2050–2050◇ for (auto& msg : results)lines 2051–2051auto it = msg.metadata.find("result_kind");lines 2052–2053◇ if (it != msg.metadata.end() && (it->second == "ok" || it->second == "ok_empty"))lines 2054–2054made_progress = true;lines 2056–2056◇ if (fold_complete_into_assistant(ctx, msg))lines 2057–2057continue;lines 2059–2059defang_meta_action_envelope(msg);lines 2060–2060ctx.messages.push_back(std::move(msg));lines 2063–2063ctx.has_pending_tool_results = true;lines 2065–2065◇ if (!is_terminal_state(ctx))lines 2066–2066set_state(ctx, AgentState::EXECUTING);lines 2068–2068return made_progress;

Requirements

REQ-LOOP-003 REQ-LOOP-007

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
lines 2666–2666std::string chain;lines 2667–2667◇ for (const auto& anc : ctx.delegation_ancestor_tiers)lines 2668–2668chain += anc + " -> ";lines 2670–2670chain += ctx.locked_tier + " -> " + target;lines 2672–2672Message reject;lines 2673–2673reject.role = "user";lines 2674–2677reject.content = "[DELEGATION REJECTED] Circular delegation " "detected: tier '" + target + "' already in the active delegation chain " "(" + chain + "). Choose a different target.";lines 2678–2678ctx.metadata["failure_reason"] = "delegation_cycle";lines 2679–2679ctx.metadata["failure_target"] = target;lines 2680–2680ctx.messages.push_back(std::move(reject));

Requirements

REQ-DELEG-001

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
lines 2745–2745std::string names;lines 2746–2746◇ for (const auto& t : tools)lines 2747–2747◇ if (!names.empty())lines 2747–2747names += ", ";lines 2748–2748names += t;lines 2750–2750Message reject;lines 2751–2751reject.role = "user";lines 2752–2759reject.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.";lines 2760–2760ctx.metadata["failure_reason"] = "delegation_isolation_unsafe";lines 2761–2761ctx.metadata["failure_target"] = target;lines 2762–2762ctx.messages.push_back(std::move(reject));

Requirements

REQ-DELEG-001 REQ-DELEG-005

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
lines 2645–2645Message reject;lines 2646–2646reject.role = "user";lines 2647–2650reject.content = "[DELEGATION REJECTED] Maximum delegation " "depth (" + std::to_string( AgentEngine::MAX_DELEGATION_DEPTH) + ") reached.";lines 2651–2651ctx.messages.push_back(std::move(reject));

Requirements

REQ-DELEG-001

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
lines 2713–2713Message reject;lines 2714–2714reject.role = "user";lines 2715–2719reject.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.";lines 2720–2720ctx.metadata["failure_reason"] = "delegation_repeat_blocked";lines 2721–2721ctx.metadata["failure_target"] = target;lines 2722–2722ctx.messages.push_back(std::move(reject));

Requirements

REQ-DELEG-001

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
lines 2693–2693std::string tag = result.success ? "COMPLETE" : "FAILED";lines 2694–2694Message msg;lines 2695–2695msg.role = "user";lines 2696–2696msg.content = "[DELEGATION " + tag + ": " + target + "] " + result.summary;lines 2697–2697ctx.messages.push_back(std::move(msg));

Requirements

REQ-DELEG-002

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

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
lines 3360–3360Message m;lines 3361–3361m.role = "user";lines 3362–3363m.content = "[DELEGATION FAILED: resume_delegation] " + reason + " (delegation_id=" + delegation_id + ")";lines 3364–3364ctx.messages.push_back(std::move(m));

Requirements

REQ-DELEG-002

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

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
lines 1271–1271const bool owes_call = tier_requires_explicit_completion(ctx.locked_tier);lines 1272–1272◇ if (!owes_call && !content.empty())lines 1273–1273return false;lines 1275–1275auto& retries = ctx.metadata["zero_tool_call_retries"];lines 1276–1276int n = retries.empty() ? 0 : std::atoi(retries.c_str());lines 1277–1277const int ceiling = empty_turn_ceiling(ctx.locked_tier);lines 1278–1278◇ if (n >= ceiling)lines 1279–1282ctx.metadata["failure_reason"] = owes_call ? "zero_tool_calls_with_explicit_completion" : (finish_reason == "error" ? "generation_failed" : "empty_response");lines 1283–1283ctx.metadata["failure_tier"] = ctx.locked_tier;lines 1284–1286logger->error("[DECISION] empty-turn allowance exhausted " "(tier={}, n={}/{}, {}), failing turn", ctx.locked_tier, n, ceiling, ctx.metadata["failure_reason"]);lines 1287–1287set_state(ctx, AgentState::ERROR);lines 1288–1288return true;lines 1290–1293logger->info("[DECISION] tier '{}' {} turn {}/{} (finish_reason={}), " "nudging", ctx.locked_tier, owes_call ? "no-tool-call" : "empty", n + 1, ceiling, finish_reason);lines 1298–1298◇ if (owes_call)lines 1299–1299ctx.metadata["force_tool_call"] = content.empty() ? "1" : "complete";lines 1301–1301Message correction;lines 1302–1302correction.role = "user";lines 1303–1303correction.content = empty_turn_nudge(ctx, owes_call);lines 1304–1304ctx.messages.push_back(std::move(correction));lines 1305–1305retries = std::to_string(n + 1);lines 1306–1306set_state(ctx, AgentState::EXECUTING);lines 1307–1307return true;

Requirements

REQ-LOOP-004

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
lines 1638–1638std::unordered_map<std::string, std::string> snapshot;lines 1640–1640std::lock_guard<std::mutex> guard(anchors_mutex_);lines 1641–1641snapshot = context_anchors_;lines 1643–1643◇ for (const auto& [key, content] : snapshot)lines 1644–1644ContextAnchorDirective d(key, content);lines 1645–1645DirectiveResult r;lines 1646–1646dir_anchor(ctx, d, r);

Requirements

REQ-COMPACT-002

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

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
lines 2775–2775bool rejected = true;lines 2776–2776◇ if (ctx.delegation_depth >= MAX_DELEGATION_DEPTH)lines 2777–2778logger->warn("Delegation rejected: depth {} >= max {}", ctx.delegation_depth, MAX_DELEGATION_DEPTH);lines 2779–2779push_delegation_rejected(ctx);lines 2780–2780elselines 2780–2780◇ if (is_delegation_cycle(ctx, pending.target))lines 2782–2783logger->warn("Delegation rejected: cycle on target tier '{}'", pending.target);lines 2784–2784push_delegation_cycle_rejected(ctx, pending.target);lines 2785–2785elselines 2785–2786◇ if (auto unsafe = isolation_unsafe_tools(ctx, pending.target); !unsafe.empty())lines 2788–2790logger->error("Delegation rejected: isolation is on but '{}' can " "reach {} non-read-only external tool(s)", pending.target, unsafe.size());lines 2791–2791push_delegation_isolation_unsafe(ctx, pending.target, unsafe);lines 2792–2792elselines 2792–2792◇ if (is_delegation_repeat_blocked(ctx, pending.target))lines 2797–2801logger->warn("Delegation rejected: '{}' failed {}x in a row " "(>= max_consecutive_failed_delegations={})", pending.target, ctx.consecutive_failed_delegations, loop_config_.max_consecutive_failed_delegations);lines 2802–2803push_delegation_repeat_blocked( ctx, pending.target, ctx.consecutive_failed_delegations);lines 2804–2804elselines 2805–2805rejected = false;lines 2807–2807return rejected;

Requirements

REQ-DELEG-001

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
lines 3080–3080◇ if (ctx.delegation_depth >= MAX_DELEGATION_DEPTH)lines 3081–3082logger->warn("Pipeline rejected: depth {} >= max {}", ctx.delegation_depth, MAX_DELEGATION_DEPTH);lines 3083–3083Message reject;lines 3084–3084reject.role = "user";lines 3085–3086reject.content = "[PIPELINE REJECTED] Maximum delegation " "depth reached.";lines 3087–3087ctx.messages.push_back(std::move(reject));lines 3088–3088return true;lines 3090–3090◇ for (const auto& stage : pending.stages)lines 3091–3091auto unsafe = isolation_unsafe_tools(ctx, stage);lines 3092–3092◇ if (!unsafe.empty())lines 3093–3095logger->error("Pipeline rejected: isolation is on but stage " "'{}' can reach {} non-read-only external " "tool(s)", stage, unsafe.size());lines 3096–3096push_delegation_isolation_unsafe(ctx, stage, unsafe);lines 3097–3097return true;lines 3100–3100return false;

Requirements

REQ-DELEG-001 REQ-DELEG-004

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
lines 2893–2893GenerateResult relay_result;lines 2894–2894relay_result.content = summary;lines 2895–2895relay_result.finish_reason = "stop";lines 2896–2896relay_result.tool_calls_json = "[]";lines 2897–2898fire_post_generate_hook( relay_result, ctx.locked_tier, ctx.messages);lines 2899–2899ctx.metadata["explicit_completion_summary"] = relay_result.content;lines 2900–2900set_state(ctx, AgentState::COMPLETE);

Requirements

REQ-DELEG-003

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

Show on the map →

Called by dir_anchor

Calls none

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
lines 2082–2082auto& msgs = ctx.messages;lines 2083–2089msgs.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());

Requirements

REQ-COMPACT-002

reset_interrupt

void entropic::AgentEngine::reset_interrupt()

Reset interrupt flag for next run.

src/core/engine.cpp:1571

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, run, run_loop

Calls this_thread_run

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
lines 1572–1572interrupt_flag_.store(false);lines 1576–1576◇ if (auto run = this_thread_run())lines 1577–1577run->interrupt.store(false, std::memory_order_release);lines 1584–1584◇ if (external_reset_cb_ != nullptr)lines 1585–1585external_reset_cb_(external_reset_data_);

Requirements

REQ-LOOP-006

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
lines 3421–3421std::string id;lines 3422–3425bool found = storage_.latest_delegation_for_target != nullptr && storage_.latest_delegation_for_target( pending.target.c_str(), id, storage_.user_data) && !id.empty();lines 3426–3426◇ if (!found)lines 3427–3430push_resume_failure( ctx, "no prior delegation to this tier in storage — use " "entropic.delegate instead", pending.target);lines 3431–3431return false;lines 3433–3434logger->info("resume_delegation by target '{}' resolved to id '{}'", pending.target, id);lines 3435–3435pending.resume_from_delegation_id = id;lines 3436–3436return true;

Requirements

REQ-DELEG-006

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
lines 342–344int operator_limit = ctx.effective_max_iterations >= 0 ? ctx.effective_max_iterations : loop_config_.max_iterations;lines 345–345◇ if (ctx.delegated_max_turns < 1)lines 346–346return operator_limit;lines 348–348return std::min(operator_limit, ctx.delegated_max_turns);

Requirements

REQ-DELEG-002 REQ-IDEN-001 REQ-LOOP-002

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

Show on the map →

Called by none

Calls none

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
lines 359–361return ctx.effective_max_tool_calls_per_turn >= 0 ? ctx.effective_max_tool_calls_per_turn : loop_config_.max_tool_calls_per_turn;

Requirements

REQ-IDEN-001

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

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
lines 3459–3459nlohmann::json j;lines 3460–3461bool ok = !pending.resume_by_target || resolve_latest_for_target(ctx, pending);lines 3462–3462const auto& id = pending.resume_from_delegation_id;lines 3463–3463◇ if (ok)lines 3463–3463ok = fetch_resume_payload(ctx, id, j);lines 3464–3464std::string target;lines 3465–3465◇ if (ok)lines 3466–3466target = j.value("target_tier", std::string{});lines 3467–3467◇ if (target.empty())lines 3468–3468push_resume_failure(ctx, "target_tier missing in storage", id);lines 3469–3469ok = false;lines 3472–3472◇ if (!ok)lines 3473–3473return false;lines 3475–3475pending.target = target;lines 3476–3476◇ if (j.contains("messages") && j["messages"].is_array())lines 3477–3477◇ for (const auto& mj : j["messages"])lines 3478–3478Message m;lines 3479–3479m.role = mj.value("role", "");lines 3480–3480m.content = mj.value("content", "");lines 3481–3481◇ if (!m.role.empty())lines 3482–3482out_history.push_back(std::move(m));lines 3486–3487logger->info("resume_delegation '{}': loaded {} messages, target='{}'", id, out_history.size(), target);lines 3488–3488return true;

Requirements

REQ-DELEG-002 REQ-DELEG-006

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

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
lines 3622–3622SessionRootInterface iface;lines 3624–3624std::lock_guard<std::mutex> guard(sandbox_mutex_);lines 3625–3625iface = session_root_;lines 3627–3627◇ if (iface.resolve_root == nullptr)lines 3628–3628return get_repo_dir();lines 3630–3630auto root = iface.resolve_root(session_key, iface.user_data);lines 3631–3631return root.empty() ? get_repo_dir() : root;

Requirements

REQ-DELEG-002 REQ-DELEG-005

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

Show on the map →

Called by SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO, SCENARIO

13 moreSCENARIO, 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
lines 476–478last_activity_epoch_s_.store( std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now().time_since_epoch()).count());lines 482–482RunCancelScope cancel_scope(&run_cancel_flag());lines 484–484LoopContext ctx;lines 485–485ctx.messages = std::move(messages);lines 486–486ctx.locked_tier = tier_override;lines 489–489ctx.session_key = active_session_key();lines 490–490ctx.metrics.start_time = now_seconds();lines 492–492init_session_conversation(ctx);lines 497–497reset_interrupt();lines 498–498clear_pause_for_fresh_turn();lines 504–504begin_loop_preamble(ctx);lines 506–506loop(ctx);lines 508–508ctx.metrics.end_time = now_seconds();lines 509–509accumulate_run_metrics(ctx);lines 510–511logger->info("Loop complete: {} iterations, {}ms", ctx.metrics.iterations, ctx.metrics.duration_ms());lines 512–512return ctx.messages;

Requirements

REQ-COMPACT-002 REQ-IDEN-001 REQ-LOOP-001 REQ-LOOP-002

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
lines 3970–3970auto run = this_thread_run();lines 3971–3971return run ? run->interrupt : interrupt_flag_;

Requirements

REQ-LOOP-006

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

Show on the map →

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
lines 414–414RunCancelScope cancel_scope(&run_cancel_flag());lines 419–419◇ if (!inherit_interrupt)lines 420–420reset_interrupt();lines 421–421clear_pause_for_fresh_turn();lines 423–423begin_loop_preamble(ctx);lines 424–424loop(ctx);lines 425–425ctx.metrics.end_time = now_seconds();lines 426–426accumulate_per_tier(ctx);

Requirements

REQ-COMPACT-002 REQ-IDEN-001 REQ-LOOP-001 REQ-LOOP-006

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

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
lines 3509–3509std::optional<int> max_turns;lines 3510–3510◇ if (pending.max_turns > 0)lines 3510–3510max_turns = pending.max_turns;lines 3511–3513DelegationManager mgr(run_child_loop_trampoline, this, tier_res_, resolve_session_root(ctx.session_key), sandbox_for_session(ctx.session_key));lines 3514–3514auto swap = dir_swap_snapshot();lines 3515–3515mgr.set_dir_swap(swap.first, swap.second);lines 3516–3516◇ if (storage_.create_delegation != nullptr)lines 3517–3517mgr.set_storage(&storage_);lines 3519–3519auto cb_snap = delegation_callbacks_snapshot();lines 3520–3521mgr.set_delegation_callbacks( cb_snap.start, cb_snap.complete, cb_snap.user_data);lines 3522–3522◇ if (resume_history.empty())lines 3523–3524return mgr.execute_delegation( ctx, pending.target, pending.task, max_turns, pending.context);lines 3526–3528return mgr.execute_resume_delegation( ctx, pending.target, pending.task, std::move(resume_history), max_turns, pending.context);

Requirements

REQ-DELEG-002

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

Show on the map →

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
lines 4332–4332◇ if (session_logger_)lines 4333–4333session_logger_->log_user_input(input);lines 4336–4336StreamThinkFilter filter(on_token, user_data);lines 4337–4337◇ if (session_logger_ && session_logger_->is_open())lines 4338–4340filter.set_raw_callback( SessionLogger::raw_token_callback, session_logger_);lines 4343–4343StreamChunkCtx sctx{&filter, cancel_flag, this};lines 4348–4348RunStreamScope stream_scope(on_stream_chunk, &sctx);lines 4351–4351auto result = tier.empty() ? run_turn(input) : run_turn_as(tier, input);lines 4352–4352filter.flush();lines 4354–4354◇ if (session_logger_)lines 4355–4355session_logger_->end_turn();lines 4357–4357◇ if (cancel_flag && *cancel_flag)lines 4357–4357return 1;lines 4358–4358return 0;
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

Show on the map →

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
lines 4401–4401◇ if (session_logger_)lines 4402–4402session_logger_->log_user_input(concat_user_echo(new_messages));lines 4405–4405StreamThinkFilter filter(on_token, user_data);lines 4406–4406◇ if (session_logger_ && session_logger_->is_open())lines 4407–4409filter.set_raw_callback( SessionLogger::raw_token_callback, session_logger_);lines 4412–4412StreamChunkCtx sctx{&filter, cancel_flag, this};lines 4417–4417RunStreamScope stream_scope(on_stream_chunk, &sctx);lines 4419–4419auto result = run_turn(std::move(new_messages));lines 4420–4420filter.flush();lines 4422–4422◇ if (session_logger_)lines 4423–4423session_logger_->end_turn();lines 4425–4425◇ if (cancel_flag && *cancel_flag)lines 4425–4425return 1;lines 4426–4426return 0;

Requirements

REQ-LOOP-001 REQ-LOOP-008

run_turn

std::vector< Message > entropic::AgentEngine::run_turn(const std::string &input)

Run a single conversation turn (stateful).

src/core/engine.cpp:3987

Show on the map →

Called by none

Calls active_conversation, run_drain_loop, system_prompt_copy

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
lines 4000–4000const bool owns_turn = try_begin_turn();lines 4001–4001auto& convo = active_conversation();lines 4002–4002auto prompt = system_prompt_copy();lines 4003–4003◇ if (convo.messages.empty() && !prompt.empty())lines 4004–4004Message sys;lines 4005–4005sys.role = "system";lines 4006–4006sys.content = std::move(prompt);lines 4007–4007convo.messages.push_back(std::move(sys));lines 4009–4009auto result = run_drain_loop(input, /*tier_override=*/"");lines 4010–4010◇ if (owns_turn)lines 4010–4010end_turn();lines 4011–4011return result;
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

Show on the map →

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
lines 4255–4255const bool owns_turn = try_begin_turn();lines 4256–4256seed_system_prompt(new_messages);lines 4257–4257auto& convo = active_conversation();lines 4258–4258std::vector<Message> pending = std::move(new_messages);lines 4259–4259std::vector<Message> result;lines 4260–4260◇ while (true)lines 4261–4261const size_t turn_begin = convo.messages.size();lines 4262–4262◇ for (auto& m : pending)lines 4263–4263convo.messages.push_back(std::move(m));lines 4265–4265size_t sent_len = convo.messages.size();lines 4266–4266result = run(convo.messages);lines 4268–4269◇ if (!settle_turn(convo, result, turn_begin, sent_len) || !prepare_next_turn(pending))lines 4269–4269break;lines 4271–4271◇ if (owns_turn)lines 4271–4271end_turn();lines 4272–4272return result;

Requirements

REQ-LOOP-001

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

Show on the map →

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
lines 4035–4035const bool owns_turn = try_begin_turn();lines 4036–4036seed_system_prompt_for_tier(tier);lines 4037–4037auto result = run_drain_loop(input, tier);lines 4038–4038◇ if (owns_turn)lines 4038–4038end_turn();lines 4039–4039return result;

Requirements

REQ-IDEN-001

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

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
lines 3643–3643◇ if (!loop_config_.delegation_isolation)lines 3644–3644return nullptr;lines 3646–3646return ensure_sandbox_manager(resolve_session_root(session_key));

Requirements

REQ-DELEG-005

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

Show on the map →

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
lines 4136–4136auto& convo = active_conversation();lines 4137–4137◇ if (!convo.messages.empty())lines 4137–4137return;lines 4138–4138auto sp = workspace_prompt_for(active_session_key(), tier);lines 4139–4139auto it = tier_info_.find(tier);lines 4140–4140◇ if (!sp && it != tier_info_.end() && !it->second.system_prompt.empty())lines 4141–4141sp = it->second.system_prompt;lines 4143–4143◇ if (!sp)lines 4143–4143sp = system_prompt_copy();lines 4144–4144◇ if (sp->empty())lines 4144–4144return;lines 4145–4145Message sys;lines 4146–4146sys.role = "system";lines 4147–4147sys.content = *sp;lines 4148–4148convo.messages.push_back(std::move(sys));

Requirements

REQ-IDEN-001

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

Show on the map →

Called by prompt, system_prompt_copy

Calls workspace_prompt_for

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
lines 4117–4117auto ws = workspace_prompt_for(session, "");lines 4118–4118std::lock_guard<std::mutex> guard(prompt_mutex_);lines 4119–4119return ws.value_or(system_prompt_);

Requirements

REQ-MCP-027

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

Show on the map →

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
lines 3796–3796std::lock_guard<std::mutex> guard(conversations_mutex_);lines 3797–3797conversations_[key];lines 3799–3799t_active_session_key = key;lines 3800–3800t_active_session_bound = true;lines 3801–3801std::lock_guard<std::mutex> guard(session_key_mutex_);lines 3802–3802active_session_key_ = key;

Requirements

REQ-LOOP-001

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

Show on the map →

Called by SCENARIO, SCENARIO, TEST_CASE, init_engine_and_interfaces

Calls none

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
lines 3896–3896std::lock_guard<std::mutex> guard(runs_mutex_);lines 3897–3897concurrent_sessions_ = enabled;lines 3898–3899logger->info("Per-session run concurrency {} (gh#158)", enabled ? "ENABLED" : "disabled");

Requirements

REQ-LOOP-009

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

Show on the map →

Called by SCENARIO, SCENARIO, entropic_set_delegation_callbacks

Calls none

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
lines 245–245std::lock_guard<std::mutex> lock(delegation_cb_mutex_);lines 246–246delegation_cb_.start = on_start;lines 247–247delegation_cb_.complete = on_complete;lines 248–248delegation_cb_.user_data = user_data;

Requirements

REQ-DELEG-002

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

Show on the map →

Called by SCENARIO, SCENARIO, wire_external_interrupt

Calls none

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
lines 1544–1544external_interrupt_cb_ = cb;lines 1545–1545external_interrupt_data_ = user_data;

Requirements

REQ-LOOP-006

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

Show on the map →

Called by SCENARIO, wire_external_interrupt

Calls none

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
lines 1562–1562external_reset_cb_ = cb;lines 1563–1563external_reset_data_ = user_data;

Requirements

REQ-LOOP-006

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

Show on the map →

Called by SCENARIO, SCENARIO, TEST_CASE, wire_prompts_and_persistence

Calls wire_internal_tier_resolution

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
lines 4800–4800handoff_rules_ = rules;lines 4801–4801wire_internal_tier_resolution();

Requirements

REQ-IDEN-001 REQ-IDEN-003

set_hooks

void entropic::AgentEngine::set_hooks(const HookInterface &hooks)

Set the hook dispatch interface.

src/core/engine.cpp:210

Show on the map →

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
lines 211–211hooks_ = hooks;lines 212–212response_generator_.set_hooks(hooks);lines 213–213context_manager_.set_hooks(hooks);lines 214–214directive_processor_.set_hooks(hooks);

Requirements

REQ-HOOK-002

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

Show on the map →

Called by SCENARIO, apply_identity_frontmatter

Calls none

Source · 3 lines
void AgentEngine::set_relay_single_delegate(const std::string& name) {
    relay_single_delegate_tiers_.insert(name);
}
Activity · 1 steps
lines 4786–4786relay_single_delegate_tiers_.insert(name);

Requirements

REQ-DELEG-003

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

Show on the map →

Called by SCENARIO, session_context_set_inner

Calls none

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
lines 4550–4550std::lock_guard<std::mutex> guard(runs_mutex_);lines 4551–4551◇ if (active_runs_.count(key) > 0)lines 4552–4553logger->warn("session_context_set('{}') refused: a run on that " "session is in flight", key);lines 4554–4554return false;lines 4557–4557std::lock_guard<std::mutex> guard(conversations_mutex_);lines 4558–4558auto& convo = conversations_[key];lines 4559–4559convo.messages = std::move(messages);lines 4560–4561logger->info("Session '{}' conversation restored: {} messages", key, convo.messages.size());lines 4562–4562return true;

Requirements

REQ-LOOP-010

set_state

void entropic::AgentEngine::set_state(LoopContext &ctx, AgentState state)

Set agent state and fire callback.

src/core/engine.cpp:1443

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
lines 1444–1444auto prev = ctx.state;lines 1445–1445ctx.state = state;lines 1446–1446logger->info("State: {}", agent_state_name(state));lines 1447–1447◇ if (callbacks_.on_state_change != nullptr)lines 1448–1449callbacks_.on_state_change( static_cast<int>(state), callbacks_.user_data);lines 1455–1455◇ if (state_observer_ != nullptr)lines 1456–1456state_observer_(static_cast<int>(state), state_observer_data_);lines 1461–1464std::string json = "{\"previous\":\"" + std::string(agent_state_name(prev)) + "\",\"current\":\"" + std::string(agent_state_name(state)) + "\"}";lines 1465–1465fire_hook_info(hooks_, ENTROPIC_HOOK_ON_STATE_CHANGE, json.c_str());lines 1469–1469◇ if (state == AgentState::ERROR)lines 1470–1474std::string json = "{\"error_code\":\"STATE_ERROR\"" ",\"iteration\":" + std::to_string(ctx.metrics.iterations) + ",\"consecutive\":" + std::to_string(ctx.consecutive_errors) + "}";lines 1475–1475fire_hook_info(hooks_, ENTROPIC_HOOK_ON_ERROR, json.c_str());

Requirements

REQ-HOOK-002 REQ-LOOP-001

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

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
lines 4697–4697state_observer_ = observer;lines 4698–4698state_observer_data_ = user_data;lines 4699–4699response_generator_.set_state_observer(observer, user_data);

Requirements

REQ-LOOP-001

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

Show on the map →

Called by SCENARIO, SCENARIO, TEST_CASE, populate_tier_info

Calls info

Source · 6 lines
void AgentEngine::set_tier_info(
    const std::string& name,
    const ChildContextInfo& info)
{
    tier_info_[name] = info;
}
Activity · 1 steps
lines 4736–4736tier_info_[name] = info;

Requirements

REQ-IDEN-001

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

Show on the map →

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
lines 190–190tier_res_ = tier_res;

Requirements

REQ-IDEN-001

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

Show on the map →

Called by SCENARIO, wire_hooks_and_validator

Calls none

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
lines 272–272validation_provider_ = provider;lines 273–273validation_provider_data_ = user_data;

Requirements

REQ-DELEG-003

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
lines 4051–4053logger->info("[workspace] '{}' prompts set: default {} chars, {} tier(s)", workspace, prompts.default_prompt.size(), prompts.tier_prompts.size());lines 4054–4054std::lock_guard<std::mutex> guard(prompt_mutex_);lines 4055–4055workspace_prompts_[workspace] = std::move(prompts);

Requirements

REQ-MCP-027

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
lines 3211–3211◇ if (ctx.locked_tier.empty() || tier_res_.get_tier_param == nullptr)lines 3212–3212return false;lines 3215–3216std::string auto_chain = tier_res_.get_tier_param( ctx.locked_tier, "auto_chain", tier_res_.user_data);lines 3217–3217◇ if (auto_chain.empty())lines 3218–3218return false;lines 3221–3223bool triggered = (finish_reason == "length") || (finish_reason == "stop" && response_generator_.is_response_complete(content, "[]"));lines 3224–3224return triggered;

Requirements

REQ-IDEN-003

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
lines 1410–1411bool at_limit = ctx.metrics.iterations >= resolve_max_iterations(ctx) || ctx.consecutive_duplicate_attempts >= 3;lines 1412–1412return is_terminal_state(ctx) || at_limit;

Requirements

REQ-LOOP-002

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
lines 3920–3920◇ if (!t_holds_claim)lines 3920–3920return nullptr;lines 3921–3921std::lock_guard<std::mutex> guard(runs_mutex_);lines 3922–3922auto it = active_runs_.find(t_claimed_key);lines 3923–3923return it == active_runs_.end() ? nullptr : it->second;

Requirements

REQ-LOOP-006

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

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
lines 1324–1324◇ if (tier_res_.get_tier_param == nullptr)lines 1324–1324return false;lines 1325–1326auto val = tier_res_.get_tier_param( tier, "explicit_completion", tier_res_.user_data);lines 1327–1327return val == "true" || val == "1";

Requirements

REQ-IDEN-001

tier_resolution

const TierResolutionInterface & entropic::AgentEngine::tier_resolution() const

Get the tier resolution interface.

src/core/engine.cpp:282

Show on the map →

Called by SCENARIO, SCENARIO

Calls none

Source · 3 lines
const TierResolutionInterface& AgentEngine::tier_resolution() const {
    return tier_res_;
}
Activity · 1 steps
lines 283–283return tier_res_;

Requirements

REQ-IDEN-001

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

Show on the map →

Called by build_batch_messages

Calls none

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
lines 4774–4774static const std::string kEmpty;lines 4775–4775auto it = tier_info_.find(name);lines 4776–4776return it == tier_info_.end() ? kEmpty : it->second.system_prompt;

Requirements

REQ-IDEN-001

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

Show on the map →

Called by none

Calls none

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
lines 4856–4856auto* self = static_cast<AgentEngine*>(ud);lines 4857–4857auto it = self->handoff_rules_.find(name);lines 4858–4858std::vector<std::string> result;lines 4859–4859◇ if (it != self->handoff_rules_.end())lines 4859–4859result = it->second;lines 4860–4860return result;

Requirements

REQ-IDEN-001 REQ-IDEN-003

tri_get_tier_param

std::string entropic::AgentEngine::tri_get_tier_param(const std::string &name, const std::string &param, void *ud)

Look up named tier parameter ( TierResolutionInterface trampoline).

src/core/engine.cpp:4903

Show on the map →

Called by none

Calls join_csv

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
lines 4905–4905auto* self = static_cast<AgentEngine*>(ud);lines 4906–4906auto it = self->tier_info_.find(name);lines 4907–4907◇ if (it == self->tier_info_.end())lines 4907–4907return "";lines 4908–4908const auto& info = it->second;lines 4909–4909std::string result;lines 4910–4910◇ if (param == "explicit_completion")lines 4911–4911result = info.explicit_completion ? "true" : "false";lines 4913–4913◇ if (param == "max_iterations" && info.max_iterations_override >= 0)lines 4914–4914result = std::to_string(info.max_iterations_override);lines 4916–4917◇ if (param == "max_tool_calls_per_turn" && info.max_tool_calls_per_turn_override >= 0)lines 4918–4918result = std::to_string(info.max_tool_calls_per_turn_override);lines 4920–4921◇ if (param == "max_consecutive_empty_turns" && info.max_consecutive_empty_turns_override >= 0)lines 4922–4922result = std::to_string(info.max_consecutive_empty_turns_override);lines 4924–4924◇ if (param == "allowed_tools" && !info.allowed_tools.empty())lines 4925–4925result = join_csv(info.allowed_tools);lines 4927–4927return result;

Requirements

REQ-IDEN-001

tri_resolve_tier

ChildContextInfo entropic::AgentEngine::tri_resolve_tier(const std::string &name, void *ud)

Resolve tier ( TierResolutionInterface trampoline).

src/core/engine.cpp:4816

Show on the map →

Called by none

Calls active_session_key, workspace_prompt_for

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
lines 4818–4818auto* self = static_cast<AgentEngine*>(ud);lines 4819–4819auto it = self->tier_info_.find(name);lines 4820–4820ChildContextInfo info;lines 4821–4821◇ if (it == self->tier_info_.end())lines 4822–4822info.valid = false;lines 4823–4823elselines 4824–4824info = it->second;lines 4825–4827info.system_prompt = self->workspace_prompt_for( self->active_session_key(), name) .value_or(info.system_prompt);lines 4829–4829return info;

Requirements

REQ-IDEN-001

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

Show on the map →

Called by none

Calls none

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
lines 4841–4841auto* self = static_cast<AgentEngine*>(ud);lines 4842–4842return self->tier_info_.count(name) > 0;

Requirements

REQ-IDEN-001

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

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
lines 3240–3240◇ if (!should_auto_chain(ctx, finish_reason, content))lines 3241–3241return false;lines 3244–3244◇ if (ctx.delegation_depth > 0)lines 3245–3246logger->info("[AUTO-CHAIN] child depth={}, completing", ctx.delegation_depth);lines 3247–3247set_state(ctx, AgentState::COMPLETE);lines 3248–3248return true;lines 3252–3253std::string target = tier_res_.get_tier_param( ctx.locked_tier, "auto_chain", tier_res_.user_data);lines 3255–3255◇ if (!target.empty())lines 3256–3256logger->info("[AUTO-CHAIN] root, tier change to '{}'", target);lines 3257–3257TierChangeDirective tc(target, "auto_chain");lines 3258–3258DirectiveResult r;lines 3259–3259dir_tier_change(ctx, tc, r);lines 3261–3261return !target.empty();

Requirements

REQ-IDEN-003

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
lines 3814–3814std::lock_guard<std::mutex> guard(runs_mutex_);lines 3822–3823const bool blocked = active_runs_.count(key) > 0 || exclusive_turn_ || ((exclusive || !concurrent_sessions_) && !active_runs_.empty());lines 3824–3824◇ if (blocked)lines 3824–3824return false;lines 3825–3825exclusive_turn_ = exclusive;lines 3826–3826auto claimed = std::make_shared<RunState>();lines 3827–3827claimed->key = key;lines 3828–3828active_runs_[key] = claimed;lines 3829–3829running_flag_.store(true);lines 3835–3835t_claimed_key = key;lines 3836–3836t_holds_claim = true;lines 3837–3837t_active_session_key = key;lines 3838–3838t_active_session_bound = true;lines 3839–3839return true;

Requirements

REQ-API-009 REQ-LOOP-009

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);
}
Activity · 7 steps
lines 4936–4936TierResolutionInterface tri;lines 4937–4937tri.resolve_tier = &AgentEngine::tri_resolve_tier;lines 4938–4938tri.tier_exists = &AgentEngine::tri_tier_exists;lines 4939–4939tri.get_handoff_targets = &AgentEngine::tri_get_handoff_targets;lines 4940–4940tri.get_tier_param = &AgentEngine::tri_get_tier_param;lines 4941–4941tri.user_data = this;lines 4942–4942set_tier_resolution(tri);

Requirements

REQ-IDEN-001