44#include <unordered_map>
45#include <unordered_set>
48#include <nlohmann/json_fwd.hpp>
94 void* user_data =
nullptr;
105 std::vector<Message>
run(std::vector<Message> messages,
106 const std::string& tier_override =
"");
142 void set_hooks(
const HookInterface& hooks);
304 const std::vector<Message>& messages)
const;
359 std::unordered_map<std::string, LoopMetrics>
388 std::vector<Message>
run_turn(
const std::string& input);
404 std::vector<Message>
run_turn_as(
const std::string& tier,
405 const std::string& input);
427 std::vector<Message>
run_turn(std::vector<Message> new_messages);
457 const std::string& tier_override);
616 void (*observer)(
const char*,
size_t,
void*),
639 void (*observer)(
int state,
void* user_data),
680 bool has_tier(
const std::string& name)
const;
713 const std::unordered_map<std::string,
714 std::vector<std::string>>& rules);
727 const std::string& tier)
const;
741 const LoopContext& ctx,
const std::string& target)
const;
759 const LoopContext& ctx,
const std::string& target)
const;
892 const std::string& content,
893 const std::string& finish_reason);
903 bool handle_terminal_finish_reasons(
904 LoopContext& ctx,
const std::string& finish_reason);
915 bool record_explicit_completion_failure(
916 LoopContext& ctx,
const std::string& finish_reason);
930 void finalize_delegation_result(
940 void relay_partial_result(
LoopContext& ctx,
const std::string& summary);
950 const std::string& terminal_reason = {});
958 bool should_stop(
const LoopContext& ctx)
const;
974 static bool is_terminal_state(
const LoopContext& ctx);
982 void set_state(LoopContext& ctx,
AgentState state);
989 void reinject_context_anchors(LoopContext& ctx);
995 void register_directive_handlers();
998 void dir_stop(LoopContext&,
const Directive&, DirectiveResult&);
999 void dir_tier_change(LoopContext&,
const Directive&, DirectiveResult&);
1000 void dir_delegate(LoopContext&,
const Directive&, DirectiveResult&);
1001 void dir_pipeline(LoopContext&,
const Directive&, DirectiveResult&);
1002 void dir_complete(LoopContext&,
const Directive&, DirectiveResult&);
1003 void dir_clear_todos(LoopContext&,
const Directive&, DirectiveResult&);
1004 void dir_inject(LoopContext&,
const Directive&, DirectiveResult&);
1005 void dir_prune(LoopContext&,
const Directive&, DirectiveResult&);
1006 void dir_anchor(LoopContext&,
const Directive&, DirectiveResult&);
1007 void dir_phase(LoopContext&,
const Directive&, DirectiveResult&);
1008 void dir_notify(LoopContext&,
const Directive&, DirectiveResult&);
1016 std::pair<std::string, std::vector<ToolCall>> parse_tool_calls(
1017 const std::string& raw_content);
1029 bool process_tool_results(LoopContext& ctx,
1030 const std::vector<ToolCall>& tool_calls);
1039 void execute_pending_delegation(LoopContext& ctx);
1054 bool reject_delegation_if_guarded(LoopContext& ctx,
1055 const PendingDelegation& pending);
1062 void execute_pending_pipeline(LoopContext& ctx);
1072 bool should_auto_chain(
const LoopContext& ctx,
1073 const std::string& finish_reason,
1074 const std::string& content);
1084 bool try_auto_chain(LoopContext& ctx,
1085 const std::string& finish_reason,
1086 const std::string& content);
1110 void fire_post_generate_hook(GenerateResult& result,
1111 const std::string& tier,
1112 const std::vector<Message>& messages);
1127 void capture_validation_feedback(LoopContext& ctx);
1149 void dispatch_post_generate(LoopContext& ctx,
1150 GenerateResult& result);
1165 void process_generation_result(LoopContext& ctx,
1166 GenerateResult& result);
1179 void dispatch_pending_or_halt(LoopContext& ctx);
1199 void charge_thinking_budget(LoopContext& ctx,
size_t content_len,
1200 bool made_tool_call);
1210 int budget_units_consumed(LoopContext& ctx,
size_t content_len);
1218 void nudge_budget_completion(LoopContext& ctx);
1226 void hard_cut_budget(LoopContext& ctx);
1240 bool fire_complete_hook(
const std::string& summary,
1241 const LoopContext& ctx);
1250 bool fire_delegate_pre_hook(
const PendingDelegation& pending,
1264 void fire_delegate_complete_hook(
const std::string& target,
1266 const std::string& summary =
"");
1285 std::filesystem::path get_repo_dir();
1307 SandboxManager* ensure_sandbox_manager();
1326 bool resolve_resume_delegation(
1328 PendingDelegation& pending,
1329 std::vector<Message>& out_history);
1345 bool fetch_resume_payload(
1347 const std::string&
id,
1348 nlohmann::json& parsed);
1366 DelegationResult run_pending_delegation(
1368 const PendingDelegation& pending,
1369 std::vector<Message> resume_history);
1378 void fire_delegation_start(
const LoopContext& ctx,
1379 const std::string& tier,
1380 const std::string& task);
1389 void fire_delegation_complete(
const LoopContext& ctx,
1390 const std::string& tier,
1391 const struct DelegationResult& result);
1394 LoopMetrics last_metrics_;
1395 std::unordered_map<std::string, LoopMetrics>
1397 InferenceInterface inference_;
1398 LoopConfig loop_config_;
1399 EngineCallbacks callbacks_;
1400 std::atomic<bool> interrupt_flag_{
false};
1401 std::atomic<bool> pause_flag_{
false};
1402 void (*external_interrupt_cb_)(
void*) =
nullptr;
1403 void* external_interrupt_data_ =
nullptr;
1409 DelegationCallbacks delegation_cb_;
1410 mutable std::mutex delegation_cb_mutex_;
1411 char* (*validation_provider_)(
void*) =
nullptr;
1412 void* validation_provider_data_ =
nullptr;
1413 std::unordered_map<std::string, std::string> context_anchors_;
1414 ToolExecutionInterface tool_exec_;
1415 TierResolutionInterface tier_res_;
1416 StorageInterface storage_;
1417 DirectiveProcessor directive_processor_;
1418 TokenCounter token_counter_;
1419 CompactionManager compaction_manager_;
1420 ContextManager context_manager_;
1421 ResponseGenerator response_generator_;
1422 HookInterface hooks_;
1423 std::optional<std::filesystem::path> cached_repo_dir_;
1424 bool repo_dir_checked_ =
false;
1425 std::filesystem::path project_dir_override_;
1426 std::optional<SandboxManager> sandbox_mgr_;
1429 mutable std::mutex queue_mutex_;
1430 std::deque<std::string> user_message_queue_;
1431 std::atomic<bool> running_flag_{
false};
1434 std::atomic<int64_t> last_activity_epoch_s_{0};
1435 void (*queue_observer_)(
const char*, size_t,
void*) =
nullptr;
1436 void* queue_observer_data_ =
nullptr;
1439 void (*state_observer_)(int,
void*) =
nullptr;
1440 void* state_observer_data_ =
nullptr;
1451 std::optional<std::string> pop_queued_user_message();
1460 void fire_queue_consumed(
const std::string& consumed,
size_t remaining);
1463 std::vector<Message> conversation_;
1464 std::string system_prompt_;
1465 SessionLogger* session_logger_ =
nullptr;
1468 std::unordered_map<std::string, ChildContextInfo> tier_info_;
1469 std::unordered_map<std::string, std::vector<std::string>> handoff_rules_;
1471 std::unordered_set<std::string> relay_single_delegate_tiers_;
1478 void wire_internal_tier_resolution();
1491 void apply_identity_overrides(LoopContext& ctx);
1500 int resolve_max_iterations(
const LoopContext& ctx)
const;
1509 int resolve_max_tool_calls(
const LoopContext& ctx)
const;
1520 static ChildContextInfo tri_resolve_tier(
1521 const std::string& name,
void* ud);
1530 static bool tri_tier_exists(
1531 const std::string& name,
void* ud);
1540 static std::vector<std::string> tri_get_handoff_targets(
1541 const std::string& name,
void* ud);
1551 static std::string tri_get_tier_param(
1552 const std::string& name,
const std::string& param,
void* ud);
Core agent execution engine.
void cancel_pause()
Cancel pause and interrupt completely.
bool queue_user_message(const std::string &message)
Append a user message to the mid-gen queue.
CompactionManager & compaction_manager()
Borrowed reference to the engine's built-in CompactionManager.
void set_validation_provider(char *(*provider)(void *), void *user_data)
Register a JSON provider for the validation block in ON_COMPLETE hook context.
bool is_delegation_cycle(const LoopContext &ctx, const std::string &target) const
Check whether pending delegation would close a cycle.
size_t user_message_queue_depth() const
Snapshot of the queue depth.
std::vector< Message > run(std::vector< Message > messages, const std::string &tier_override="")
Run the engine on a set of messages.
void seed_system_prompt_for_tier(const std::string &tier)
Seed a tier's system prompt on an empty conversation (gh#99).
void clear_user_message_queue()
Drop all queued user messages.
const std::vector< Message > & get_messages() const
Get conversation messages (read-only).
bool prepare_next_turn(std::vector< Message > &pending)
Pull the next queued user message into pending (gh#40).
void set_callbacks(const EngineCallbacks &callbacks)
Set callback functions for loop events.
void seed_system_prompt(const std::vector< Message > &new_messages)
Prepend the configured system prompt if this turn needs it.
std::vector< Message > run_turn(const std::string &input)
Run a single conversation turn (stateful).
DelegationCallbacks delegation_callbacks_snapshot() const
Atomically snapshot the registered delegation callbacks.
void set_stream_observer(TokenCallback observer, void *user_data)
Set the global stream observer.
LoopMetrics last_loop_metrics() const
Get metrics from the most recent completed run.
const LoopConfig & loop_config() const
Get loop configuration.
void set_project_dir(const std::filesystem::path &project_dir)
Set the configured project directory (gh#31, v2.1.6).
bool is_running() const
Whether a top-level run_turn is currently in progress.
DirectiveProcessor & directive_processor()
Get directive processor for external hook wiring.
std::vector< Message > run_drain_loop(std::string pending, const std::string &tier_override)
Shared drain loop for run_turn / run_turn_as (gh#99).
void interrupt()
Interrupt the running loop (thread-safe).
void pause()
Pause generation (thread-safe).
bool 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?...
void set_hooks(const HookInterface &hooks)
Set the hook dispatch interface.
void set_tier_resolution(const TierResolutionInterface &tier_res)
Set the tier resolution interface for delegation.
void run_loop(LoopContext &ctx, bool inherit_interrupt=false)
Run the engine loop on a pre-built context.
void set_session_logger(SessionLogger *logger)
Set session logger for model transcript logging.
const TierResolutionInterface & tier_resolution() const
Get the tier resolution interface.
void set_storage(const StorageInterface &storage)
Set the storage interface for persistence.
std::unordered_map< std::string, LoopMetrics > per_tier_metrics() const
Per-tier aggregated metrics since engine start.
void clear_conversation()
Clear conversation history.
std::vector< Message > run_turn_as(const std::string &tier, const std::string &input)
Run a single turn under a named tier's grammar/identity (gh#99).
void set_queue_observer(void(*observer)(const char *, size_t, void *), void *user_data)
Register an observer that fires when a queued user message is consumed and seeded as the next turn.
std::pair< int, int > context_usage(const std::vector< Message > &messages) const
Get context usage for a message list.
bool 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...
void set_system_prompt(const std::string &prompt)
Set the system prompt for conversation state.
void set_relay_single_delegate(const std::string &name)
Mark a tier as relay-on-single-delegate.
void set_state_observer(void(*observer)(int state, void *user_data), void *user_data)
Register a persistent state-transition observer.
size_t message_count() const
Get conversation message count.
static constexpr int MAX_DELEGATION_DEPTH
Max delegation nesting depth (0=root, 1=child, 2=max).
void set_delegation_callbacks(ent_decision_t(*on_start)(const ent_delegation_request_t *, void *), ent_decision_t(*on_complete)(const ent_delegation_result_t *, void *), void *user_data)
Register delegation start/complete callbacks (gh#29, v2.1.5).
ToolExecutorHooks build_directive_hooks()
Build ToolExecutorHooks wired to this engine's DirectiveProcessor.
void 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...
void set_handoff_rules(const std::unordered_map< std::string, std::vector< std::string > > &rules)
Store handoff rules for tier delegation.
void set_tier_info(const std::string &name, const ChildContextInfo &info)
Store pre-resolved tier context info.
int run_streaming(const std::string &input, TokenCallback on_token, void *user_data, int *cancel_flag)
Run a streaming conversation turn (stateful).
void set_message_queue_capacity(int cap)
Set the runtime capacity of the mid-gen queue.
const std::string & tier_system_prompt(const std::string &name) const
A tier's resolved system prompt (gh#98).
EngineCallbacks & callbacks()
Get mutable reference to engine callbacks.
void reset_interrupt()
Reset interrupt flag for next run.
bool has_tier(const std::string &name) const
Whether a tier name is known (gh#99).
void set_external_interrupt(void(*cb)(void *user_data), void *user_data)
Register a callback invoked alongside interrupt().
bool 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 ...
int64_t seconds_since_last_activity() const
gh#35: seconds since the engine last serviced a run().
void set_tool_executor(const ToolExecutionInterface &tool_exec)
Set the tool execution interface.
Manages automatic context compaction.
Processes tool directives via registry-based dispatch.
Manages session_model.log for raw streaming content.
Auto-compaction for context management.
Context management subsystem for the agentic loop.
Directive processing for tool-to-engine communication.
Types for the agentic loop engine.
Public C API for the Entropic inference engine.
ent_decision_t
Consumer decision returned from delegation callbacks.
entropic_hook_point_t
Hook points in the engine lifecycle.
Hook dispatch interface injected into engine subsystems.
Function pointer types for core-to-inference communication.
Activate model on GPU (WARM → ACTIVE).
void(*)(const char *, size_t, void *) TokenCallback
Token callback type matching the C API signature.
AgentState
C++ enum class for agent execution states.
Response generation subsystem for the agentic loop.
Filesystem-based sandbox isolation for delegations.
Session model log — raw streaming transcript.
Streaming filter that strips <think>...</think> blocks.
Request describing a delegation that is about to run.
Result of a finalized delegation, delivered to the consumer.
Grouped consumer-registered delegation callbacks (gh#29).
Resolved tier information for building child delegation contexts.
Auto-compaction configuration.
Result returned from a child delegation loop.
Callback function pointer types for engine events.
Configuration for the agentic loop.
Mutable state carried through the agentic loop.
Metrics collected during loop execution.
A message in a conversation.
Storage interface for conversation persistence.
Tier resolution callbacks for delegation and auto-chain.