Ce qu’il fait
- Budget par exécution
- Gestion du contexte et mémoire
- Checkpoints et replay déterministe
- API pas à pas pour le tick d'un serveur de jeu ou de toute boucle d'événements
Mesuré
- Orchestration par étape : 0.5 µs au p50 (GCC), 0.6 µs (MSVC)
- 34 scénarios prennent les mêmes décisions au replay
- ASan, TSan et 1 heure de libFuzzer
Limites connues
- L'appel au modèle dans l'agent n'est pas en streaming : pas de callback par token
- Un checkpoint n'est pas authentifié. N'en chargez pas un d'origine non fiable
Ethereal::Ai::Agent · AI pillar
The loop of an AI agent in C++. It talks to the model through Ai::Llm, runs the tools of an Ai::Tools registry (including the tools of MCP servers through Ai::Mcp), manages the context window, the long term memory and the budget, asks for approval before risky tool calls, and can be paused, resumed in another process and replayed deterministically from a trace.
It runs in two ways: Run() blocks until the run stops, and Step() advances as far as it can without waiting for the model, so a game server or an event loop can drive many agents from its own tick.
The module is optional: ETHEREAL_AI_AGENT, off by default. It needs ETHEREAL_AI_LLM (the model) and ETHEREAL_AI_TOOLS (the tools). With ETHEREAL_AI_RAG the long term memory is available, and with ETHEREAL_TELEMETRY the trace can go to spans. When this SDK was built with it, BUILD_INFO.txt lists it and the Ethereal::Ethereal target carries the definition ETL_AI_AGENT. Include agent_inc.hpp.
---
Synchronous
#include <ethereal/cpp/ai/agent/agent_inc.hpp>
namespace Agent = Ethereal::Ai::Agent;
Agent::SAgentConfig Config;
Config.pClient = &Client; // Ai::Llm, shared by many agents
Config.pTools = &Registry; // Ai::Tools, final
Config.sModel = "claude-opus-5-5";
Config.Budget.uMaxOutputTokens = 20000;
Agent::CAgent A;
Agent::CAgent::Create( Config, &A );
A.AddUserMessage( "Find the open tickets and summarize them." );
Agent::SRunResult R;
A.Run( R ); // stops at the end, or when a call waits for approvalStep by step, inside a tick
void CGameServer::Tick( void )
{
for( CNpc & Npc : m_Npcs )
{
switch( Npc.Agent.Step() )
{
case Agent::EState::eWaitingApproval:
for( ETL_UINT32 u = Npc.Agent.PendingCount(); u > 0u; --u )
{
const std::string sId( Npc.Agent.Pending( 0u ).sId );
Npc.Agent.Approve( sId, Decide( Npc ) ); // a moderator, a game rule
}
break;
case Agent::EState::eDone:
Npc.Say( Npc.Agent.LastText() );
break;
default:
break; // waiting for the model or the tools: the tick goes on
}
}
}Step() builds the request, starts the model call, takes the reply when it arrives, runs the tools and builds the next request, all without waiting for the model. With nothing to do it costs a few nanoseconds. Without bAsyncTools the tools run inside Step(), so a step lasts as long as the tool handlers. With bAsyncTools the batch runs on a thread of the agent and Step() only checks whether it finished.
examples/ai/agent_cli.cpp is a terminal agent with two tools, a budget and a checkpoint kept between runs (built by examples/installed as example_agent_cli, key in ANTHROPIC_API_KEY).
---
The API
CAgent | What it does |
|---|---|
Create( Config, &Agent ) | a new agent in eReady with an empty history |
AddUserMessage( sText, bPinned ) | the user message of the next turn. In eDone it opens a new turn |
Run( Result ) / Step() | until the run stops or waits for approval / as far as possible without waiting |
PendingCount, Pending( u ), Approve( sCallId, eDecision, sText ) | the calls waiting for a decision: Tools::EApproval::eApprove, eDeny (sText is the reason the model sees) or eModify (sText is the JSON of new arguments, validated again) |
Cancel() / RequestCancel() | cancels now / asks for a cancel from any thread (the next step cancels) |
Interrupt( sText ) | a user message from any thread, injected before the next model call |
State, StopReason, Used, LastText, MessageCount, Message( u ), HistoryTokens | inspection |
ReserveHistory( uMessages, uBlocks, uTextBytes ) | room up front: the steps then allocate nothing until it is used up |
SetScratch, GetScratch | the run's scratchpad (key and value) |
SaveCheckpoint / LoadCheckpoint | the whole state, binary or JSON (below) |
AsTool( sName, sDescription, Target ) | this agent as a tool of another registry (a sub-agent) |
Replay, ReplayText | run a recorded trace again and compare the decisions |
The main fields of SAgentConfig (the pointers must outlive the agent, and many agents may share the client, the registry and the memory index):
| Field | Default | Meaning |
|---|---|---|
pModel / pClient | null | a backend (IModel), or an Llm::CClient the agent wraps in CLlmModel |
eProvider | eAnthropic | the dialect of the tools and the context rules |
sModel, sSystem | the model and the system prompt | |
uMaxTokens, uMaxSteps | 4096, 50 | output limit per call, model calls per run |
pTools, eApprovalScope | null, eDestructive | a final registry, and which calls need approval |
pToolParallel, bAsyncTools, iToolTimeoutMs | the calls of a turn in parallel (Job::IParallelFor), the batch on the agent's thread, the tool time limit | |
TerminalTools | a successful call to one of these stops the run | |
Budget, Context, Memory | SBudget, SContextPolicy, SMemoryConfig (below) | |
bScratchTools | false | gives the model scratch_set and scratch_get |
pfnCount | null | the token counter of the history (bytes / 4 without one) |
uMaxUntrustedBytes, pfnFilter | 50,000 | untrusted content limit, and the content filter |
pfnStop, pfnNow | a stop hook after each step, the clock | |
pfnTrace, sTracePath, pTracer | the trace: a callback, a JSONL file (appended), the spans of a Telemetry::CTracer |
States and stop reasons
EState: eReady, eWaitingModel, eProcessing (only seen from inside a step), eRunningTools, eWaitingApproval, eDone, eFailed, eCancelled. eDone accepts a new user message. eFailed and eCancelled do not.
EStopReason: eEndTurn, eMaxSteps, eStopHook, eTerminalTool, eRefusal and eMaxTokens end in eDone. Every budget (eInputTokens, eOutputTokens, eCost, eWallTime, eToolCalls), eModelError and eFiltered end in eFailed. eCancelled ends in eCancelled. StateName, StopReasonName and StatusName give the names for a log.
---
Behavior
Budget. SBudget limits input tokens (cache reads and writes included), output tokens, cost (in the currency of Prices, a table for Llm::FindPrice), wall time, tool calls in total and per tool (PerTool), and the steps (uMaxSteps). Zero is no limit. The output limit of each call is cut to what is left, so the output budget is never exceeded. Input and cost are estimated before the call and checked after it: they can be exceeded by at most the call in flight, and the run stops right after it. A call over a per-tool limit is not run, and the model gets an error result and goes on. A cost budget for a model missing from the price table is refused by Create.
Context. With SContextPolicy::uMaxContextTokens set, the history is counted before each call. Above fTrigger (0.8) of the limit, the strategies run in the order of aOrder until it is below fTarget (0.6): eDropOldToolResults (old tool results become a marker, the newest uKeepRecentToolResults stay), eTruncateToolOutputs (large results keep their head and the rest goes to a stash, which the internal tool agent_fetch_output reads back), and eSummarize (the model summarizes the oldest messages, which counts in the budget but not in the steps). The system prompt, pinned messages and the last turn are never touched, a tool use is never separated from its result, and the reasoning blocks of the last assistant turn go back unchanged, as the providers require in a tool loop.
Approval. The default scope, Tools::EApprovalScope::eDestructive, makes destructive tools ask with no configuration. The agent waits in eWaitingApproval without holding a thread. When the last pending call is decided, the next step runs the batch.
Untrusted content. Tool results and recalled memories go to the model inside <tool_output untrusted="true"> and <memory untrusted="true">, cut at uMaxUntrustedBytes, with any closing tag inside the content broken. The filter (pfnFilter) sees user input, model output, tool output and retrieved documents (EFilterPoint) and can pass, replace or block (EFilterVerdict::eBlock stops the run with eFiltered). It is a hook for your own filter: the library ships no content classifier.
Memory. SMemoryConfig::pIndex is an Ai::Rag index. uAutoRecall sends the top k memories with each user turn, and bTools gives the model memory_remember and memory_search.
Sub-agents. AsTool adds a tool {"task": "..."} that runs a new agent with this agent's configuration and returns its final text. The sub-agent has its own history, and its budget is cut to what is left of the caller's, which is charged with what it uses. A sub-agent cannot ask for approval: its calls that need one are denied.
Checkpoint. SaveCheckpoint writes the history, usage, scratchpad, stash, per-tool counts and the pending batch with its decisions, in a versioned binary format (with a CRC) or in JSON. LoadCheckpoint resumes it, in another process if needed, with a configuration you pass again (it is not saved). A checkpoint of a newer format is eVersionMismatch, a damaged one eFormatError.
Trace and replay. The trace has one event per user message, model request (with a SHA-256 fingerprint of the history), reply, tool call, tool result, approval, context change, stop and error (ETraceKind). It never contains an API key: the agent never sees it, the Llm::CClient holds it. Replay runs a recorded trace again with the recorded replies and, with bReplayTools, the recorded tool results (so no side effect repeats), and compares every request, tool call and the way the run stops. SReplayReport::bSame says whether the agent decided the same, and uDivergedAtStep and sWhy say where and why it did not. That tests an agent with no network and no cost:
Agent::SReplayReport Rep;
Agent::Replay( "run.jsonl", Config, Rep );
if( !Rep.bSame )
std::printf( "diverged at step %u: %s\n", Rep.uDivergedAtStep, Rep.sWhy.c_str() );Testing your agent. CScriptedModel is a backend that answers from a script: PushText, PushToolUses, PushError or Push the replies in order, Hold and HoldFrom keep them pending, and OnRequest shows every request the agent sent. Put it in SAgentConfig::pModel.
Threads. An agent is used by one thread at a time. Interrupt and RequestCancel may come from any thread. A custom IModel must never block in Poll: Begin starts a call and returns, Poll hands the reply when it is there, and only Wait (used by Run) blocks.
---
C layer
Header ethereal/c/ai/agent.h. The agent (ETLC_AgentCreate with ETLC_AgentConfig, over an ETLC_LlmClient or a scripted backend), ETLC_AgentAddUserMessage, ETLC_AgentStep, ETLC_AgentRun, the pending calls and ETLC_AgentApprove, ETLC_AgentCancel, ETLC_AgentRequestCancel, ETLC_AgentInterrupt, the state, usage and last text, ETLC_AgentSaveCheckpoint and ETLC_AgentLoadCheckpoint, ETLC_AgentReplay (which returns ETLC_AI_AGENT_DIVERGENCE, -5817, with the step), and the scripted backend (ETLC_AgentScript*) for tests written in C.
The configuration has the model, the system prompt, the limits per call and per run, a final tool registry, the approval scope, the input, output, wall time and tool call budgets, the context limit (with the C++ defaults for the rest of the policy) and a trace file. C++ only: the cost and per-tool budgets, terminal tools, the memory, the content filter, sub-agents, the stop hook, the trace callback and spans, the scratchpad, ReplayText, and running tools in parallel or on the agent's thread (the C layer runs them inside the step).
---
Performance
Measured in Release on an Intel Core i7-6700 (3.4 GHz), with GCC on Linux and MSVC on Windows.
| Measure | GCC | MSVC | Target |
|---|---|---|---|
| Orchestration per step (no model, no tools), history of 400 to 800 messages | p50 0.5 µs | p50 0.6 µs | p50 5 µs: met |
Step() with nothing to do | p50 3.0 ns | p50 100 ns: met | |
| Checkpoint of an agent with 100 messages | 5.2 µs | 11.7 µs | 50 µs: met |
| Allocations per step beyond the growth of the history | 0 | 0: met |
The step request is built incrementally: only the new messages are appended to the previous request, and it is rebuilt in full when the history changes elsewhere (a dropped or truncated tool result, a summary, a recalled memory).
Every acceptance target is met. What was verified besides the table: 34 of 34 recorded scenarios replay with the same decisions, no budget or step limit was exceeded in 300 randomized behavior scripts, one hour of libFuzzer found nothing, AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer are clean, and line coverage is 90.0%.
---
Known limits
- A model call in flight is not saved in a checkpoint: the agent loaded from it calls the model again. A tool batch in flight on the agent's thread (
bAsyncTools) is saved as calls and runs again after loading, so those tools can run twice. - Input tokens and cost can pass their budget by at most one call.
- Without
pfnCount, the context policy estimates tokens as bytes / 4. - One
Step()makes at most 1,000 transitions, a guard against a backend that never stops answering. No distributed orchestration across machines.