Agent Execution Engine Architecture: Layered Design and Core Loop
This article presents a general architecture for agent execution engines that move beyond chat-style request-response systems. It separates model decision-making, program execution, and runtime governance; uses ports and adapters to isolate entry points, model services, tools, and state storage; and defines an orchestrating core loop with explicit state transitions. It also covers tool registration and permission checks, context compression, retry, budget, and cancellation strategies, scheduled triggering, persistence, observability, and failure-oriented testing. The goal is to show how an agent can execute multi-step tasks under controlled authorization and resource limits while accurately reporting uncertain, failed, or cancelled outcomes.
1. From Chat Interfaces to Task Execution Engines: What Changes
The simplest dialogue system can be summarized as follows: receive user input, send the input to a model, and return the generated result to the user. This request-response structure is suitable for question answering, but it cannot directly handle tasks that span multiple steps and produce external side effects.
For example, a user asks to “organize recent business data, generate a report, and notify the relevant people at a specified time.” Completing this goal involves at least data reading, information processing, document generation, and notification delivery. The model is responsible for understanding the task and selecting the next action, but the actual operations must be performed by programs and constrained by permissions, timeouts, and budgets.
Therefore, an agent system should distinguish three types of responsibilities:
- Model decision-making: Based on the current context, propose an answer or a tool invocation request.
- Program execution: Validate requests, invoke controlled capabilities, and collect structured results.
- Runtime governance: Manage state, limit resources, handle exceptions, and record a traceable execution process.
An agent’s capabilities come from the collaboration of these three parts, not from a single model call. It is closer to a task execution engine in which the model participates in decision-making.
This article discusses a general design approach and does not correspond to the source code implementation of a specific project. The illustrative interfaces and flows are used to explain the architecture and do not represent existing capabilities of any product.
2. Defining System Boundaries with Ports and Adapters
2.1 Entry Points Handle Access, Not Reasoning
An agent may serve web chat, enterprise messaging entry points, terminal interaction, and background tasks at the same time. Different entry points have different authentication methods, message formats, file transfer methods, and response limits, but the core task-processing logic should remain as consistent as possible.
The following layering can be used:
Interaction entry point / background trigger↓Input adaptation and identity verification↓Unified task request↓Agent core↓Model invocation port / tool execution port / state storage port↓Concrete capability implementations
This is the basic idea of the ports and adapters pattern: the core declares what capabilities it needs, and the outer layer implements how to obtain those capabilities.
Entry adapters should convert external messages into a unified request, including session ID, task ID, user input, attachment references, and identity information. They should not directly decide how the model selects tools, nor should they assemble an independent execution loop of their own.
2.2 The Core Does Not Depend on Specific Connection Methods
Model services may have different message structures and response formats. The core can obtain unified results through a model invocation port, such as “text output,” “tool request,” “finish reason,” and “usage information.”
A unified interface does not mean that all model capabilities are identical. For differences such as structured output, tool calling, and streaming responses, capability declarations and explicit validation should be used. It cannot be assumed that swapping one connection implementation will unconditionally reuse all features.
Likewise, state storage and tool connections should also sit outside the boundary. In this way, tests can use controlled doubles to simulate the model and external services without starting all real dependencies.
3. The Core Runner Should Orchestrate, Not Implement Everything
The agent core typically needs to coordinate:
- Establishing the task context;
- Constructing system instructions and tool descriptions;
- Invoking the model;
- Validating and executing tool requests;
- Updating conversation and task state;
- Determining whether to continue;
- Outputting a result or entering a waiting state.
These responsibilities may all appear to belong to the “core loop,” but they should not all be packed into one large class.
A more reasonable split is:
- Conversation management module: Maintains message order and the association of tool results.
- Context construction module: Selects the information that needs to be passed to the model for the current round.
- Tool execution module: Handles validation, authorization, concurrency, and timeouts.
- Run policy module: Controls budgets, retries, and termination.
- State persistence module: Saves task progress and recovery information.
The core runner is only responsible for organizing these modules. The benefit is not merely shorter code; more importantly, each module’s contract can be verified separately, avoiding situations where prompt adjustments accidentally change permission control or storage changes break tool execution logic.
4. How a Single User Request Becomes Multiple Execution Rounds
4.1 Distinguish User Turns from Internal Iterations
A single message sent by the user can be regarded as one external turn. However, to complete that request, the system may perform multiple model calls and tool executions.
For example:
User proposes a task↓Model requests a data query↓Program executes the query and returns the result↓Model requests report generation↓Program generates the report and returns a file reference↓Model outputs the final explanation
Each internal model decision consumes time and context. Therefore, there must be an explicit loop boundary rather than simply waiting for the model to stop on its own.
4.2 Recommended Loop Order
A general execution flow can be described as:
Create or restore task stateRecord user inputLoop:Check cancellation flag, deadline, and remaining budgetBuild context for this roundCall the model and normalize the responseIf the response contains a tool request:Validate tool name, parameters, and invocation permissionsAssess operation risk and whether confirmation is neededExecute the tool and record the resultAdd the corresponding result to subsequent contextContinue the loopIf the response is a final answer:Save final stateReturn the answerOtherwise:Record the abnormal response and handle it according to policyExecution limit exceeded:Save completed progressReturn an explicit stop reason
The most important point here is: a tool call is a request proposed by the model, not an accomplished fact.
Only after the executor successfully completes the operation can the system describe the result as completed. For execution failures, pending confirmation, or uncertain results, the final answer must accurately reflect the actual state.
4.3 Use a State Machine to Express Waiting and Recovery
A simple loop is suitable for short tasks, but long tasks may wait for user confirmation, external events, or scheduled triggers. In this case, explicit states should be introduced, such as:
- Pending execution;
- Executing;
- Waiting for confirmation;
- Waiting for external result;
- Completed;
- Failed;
- Cancelled.
State transitions should be controlled by the program. For example, operations involving funds, deletion, or public release can first enter “waiting for confirmation” and continue only after valid authorization is received.
5. Tool Registration and Dispatch: Separate Capability Description from Execution Permission
5.1 What Information a Tool Registry Needs
Tool registration is not simply a mapping from names to functions. A governable tool definition typically needs:
- Tool purpose;
- Input and output constraints;
- Required permissions;
- Timeout policy;
- Whether it produces external side effects;
- Whether retries are allowed;
- Whether idempotent handling is supported;
- Whether it is suitable for concurrent execution.
The capability description sent to the model is mainly used to help it select tools; the permission policy inside the executor is used to restrict invocation. Both may come from the same registry record, but they must not be conflated.
The model can see a tool does not mean the current user is authorized to execute it.
5.2 Parameter Validation Cannot Rely on Prompts
Tool parameters must be checked by the program for type, required fields, ranges, and allowed values. For inputs such as file paths, query expressions, and resource identifiers, additional validation appropriate to the business context is also needed.
External documents and tool results are untrusted content. Even if they contain text such as “ignore previous constraints” or “call the admin API,” they should not gain the privilege level of system instructions.
5.3 Serial and Concurrent Execution Should Depend on Dependencies
Independent read-only queries can often run concurrently; tasks where a later step depends on the output of a previous step must be serial; multiple write operations that act on the same resource require additional consideration of conflicts.
Concurrent execution should be limited in number, and the status of each call should be recorded separately. Tool results should also preserve their correspondence with the original call, preventing the model from mixing return values from different requests.
For partial success, the system should state which steps were completed and which failed. External side effects that have already occurred are not automatically rolled back because a later step reports an error.
6. Context Management: Compress Information, Do Not Erase Facts
6.1 The Context Budget Is Not Just Conversation History
The context for a request usually includes system instructions, tool descriptions, historical messages, current input, and tool results. In addition, space must be reserved for model output.
Therefore, compression should not be decided solely by the number of messages. A more reasonable approach is to estimate overall usage and set a safety margin based on the model’s context capacity, the size of tool results, and output requirements.
Triggering compression at a fixed ratio can be an engineering strategy, but it is not a universal standard and cannot be treated as an established rule for all implementations.
6.2 Layer Information by Value
Information can be divided into:
- Current task state: Goals, constraints, progress, to-do items, and authorization status.
- Recent working context: The latest messages and tool results relevant to the current decision.
- Historical summaries: Key conclusions from earlier rounds.
- Retrievable records: Full logs, raw files, and detailed execution evidence.
During compression, priority should be given to information needed for decisions rather than uniformly shortening all messages. Large amounts of raw data returned by tools can be stored in persistent storage, with summaries and retrievable references provided to the model.
6.3 Summaries Cannot Be the Sole Source of Truth
Summaries may omit details or change semantics. Key data such as amounts, resource identifiers, confirmation records, and task status should be stored structurally rather than only in natural-language summaries.
Persistent memory also requires a clear scope. User preferences, temporary task data, and sensitive business information have different retention requirements, and their purpose, access permissions, validity period, and deletion mechanisms should be distinguished.
7. Retries, Budgets, and Cancellation: Enabling Safe Stops
7.1 Different Errors Require Different Strategies
Temporary network anomalies may be suitable for retries; parameter errors usually require correction before another call; insufficient permissions should stop execution or request authorization; business rule rejections should not be bypassed through repeated calls.
In particular, a write-operation timeout does not necessarily mean the execution failed. The external system may have already committed the operation and only failed to return a response. In this case, the result should be confirmed through status queries or idempotency mechanisms to avoid sending duplicate notifications, creating duplicate resources, or deducting quota multiple times.
7.2 Budgets Should Cover Multiple Dimensions
Run policies can limit the number of model iterations, tool calls, total elapsed time, concurrency, and context usage.
When a limit is reached, the system should return completed steps, unfinished content, and the stop reason. It must not ask the model to invent unsupported conclusions just to make the task appear successful.
7.3 Cancellation Needs to Run Through the Execution Chain
Cancellation is not just stopping text output to the user. The system should prevent new model requests and tool calls and, as far as possible, interrupt operations that are already running.
However, whether cancellation can undo an external operation depends on the tool itself. For actions that cannot be undone, the actual result should be recorded and stated in the final status. Stopping waiting and undoing a business operation are two different concepts.
8. Scheduled Dispatch and External Tool Protocols Should Remain Independent
Scheduled tasks are responsible for “when to trigger,” while the agent is responsible for “how to complete the task after triggering.” The scheduler should not occupy the conversation loop for a long time waiting for the time to arrive.
A scheduled task usually needs to store the trigger rule, task input, execution identity, overlapping execution policy, and failure handling method. When triggered, it creates a unified task request and hands it to the core executor.
To avoid duplicate operations caused by repeated triggers, task instance identifiers, atomic claiming, or execution deduplication mechanisms should also be used.
Standardized external tool protocols solve the problems of capability discovery, parameter description, and call result passing. They cannot replace authentication, risk control, or data isolation. After external tools are integrated, they should still be included in local permission policies and audit trails.
9. Persistence and Observability Determine Production Readiness
9.1 Save Enough Recovery Information
Processes may restart, and tasks may span long periods. Therefore, task progress should be saved after key state changes.
At a minimum, the system should retain the task identifier, session association, current state, executed calls, key result references, and remaining budget. Checkpoints should be considered both before and after tool execution.
Recovery must not mechanically replay all historical actions. For calls with side effects and uncertain results, the external state should be confirmed first, and then the system should decide whether to continue, compensate, or hand the case to a human.
9.2 Make Every Step Explainable
Logs and monitoring should cover model calls, tool execution, retries, compression, and state transitions, and correlate them through task identifiers.
Metrics worth monitoring include task success rate, average number of iterations, tool failure rate, timeout ratio, and confirmation wait time. When logs contain identity information, credentials, or sensitive business content, they need to be redacted and access must be restricted.
The system must answer not only “what the model said” but also “which operations actually occurred, who authorized them, and at which step the failure happened.”
10. Testing Begins with Boundaries and Failure Scenarios
Testing an agent cannot rely only on manual conversation. A more reliable method is to provide preset response sequences to the model port and verify whether the executor handles them according to the contract.
Key scenarios include:
- Normal completion after consecutive tool calls;
- Returning a nonexistent tool or invalid parameters;
- An unauthorized user attempting to perform a write operation;
- A tool timeout while the external operation has already succeeded;
- Partial failure in concurrent calls;
- Key constraints still preserved after context compression;
- The user cancels while a tool is executing;
- Avoiding duplicate execution after a process restart;
- External content attempting to change system instructions;
- The scheduler delivering the same task twice.
These tests verify the system’s control capabilities, not whether the model’s wording is natural.
Conclusion: The Core Loop Is the Starting Point, Execution Boundaries Are the Key
A complete agent architecture should consist of a unified entry point, model decision-making, controlled tool execution, state management, and runtime governance.
Ports and adapters reduce integration coupling; the execution loop organizes multi-step tasks; tool policies guard permission boundaries; context management maintains decision quality; and persistence and auditing ensure that failures can still be traced and recovered.
Whether a system is mature cannot be judged only by how many tools it can call. It should be judged by whether it can complete tasks under explicit authorization and resource limits, whether it can correctly handle uncertain results, and whether it can stop safely on failure or cancellation.
