Agent Execution Framework Design Patterns: Context, Tools, and Control Loops

    This article breaks down the core design patterns behind a reliable agent execution framework (agent harness). It explains how to manage a limited context window through layered context assembly, how to structure the tool-calling loop around an observe-decide-act cycle with explicit termination conditions, and how to apply least-privilege permissions and sandboxing. It also covers sub-agent orchestration, observability, evaluation, cost control, common anti-patterns, and a practical step-by-step adoption path.

    1. Why the Execution Framework Is an Engineering Discipline

    When building agent applications in practice, teams often focus on model capabilities and overlook what actually determines success: the execution framework (the agent harness) wrapped around the model. It turns a single natural-language request into a multi-turn, interruptible, and auditable execution process. The reason a widely adopted class of AI coding tools feels stable is not a standout single capability, but the fact that it treats five things as a system: context, tools, permissions, orchestration, and observability.

    The execution framework essentially solves four problems:

    • Context is limited while tasks are effectively unlimited, so information must be prioritized.
    • Tool calls have side effects, so risk must be controlled.
    • As the task chain grows longer, consistency must be preserved.
    • Failures are inevitable, so they must be located and recovered from.

    Around these four points, you can abstract a set of design patterns that are independent of any specific product.

    2. Context Engineering: Spend the Limited Window Where It Matters

    Context is the agent’s scarcest resource. Mature frameworks usually do not stuff the entire history into the window indiscriminately; they adopt a layered strategy:

    • System layer: stable role constraints, output specifications, and safety boundaries, kept as concise as possible.
    • Task layer: the goal, acceptance criteria, and known constraints, kept resident.
    • Working layer: intermediate results and the to-do list for the current step, updated as work progresses.
    • Archive layer: historical details written to external storage, retrieved on demand rather than injected in full.

    An illustrative context assembly logic looks like this:

    1. def build_context(system, task, todo, retrieved):
    2. return {
    3. "system": system, # stable and short
    4. "task": task, # goal and acceptance criteria
    5. "todo": todo, # rolling step list
    6. "memory": retrieved, # retrieved on demand, not injected in full
    7. }

    Three practices are key. First, explicitly maintain a to-do list for long tasks so the model can realign with the goal every turn and drift is reduced. Second, turn large logs and file contents into a “summary plus retrievable reference” so the window is not filled with noise. Third, when compressing context, preserve the basis for decisions and discard only repeated phrasing.

    3. The Tool-Calling Loop: Converging on Observe-Decide-Act

    Tool use should be modeled as a controlled loop, not a one-shot output. A robust loop includes: parsing the request, selecting a tool, validating parameters, executing, reading back the result, and checking whether the acceptance criteria are met. Termination conditions must be defined explicitly, for example reaching the maximum number of steps, two consecutive steps with no new information, or the acceptance criteria being satisfied.

    1. while not done and step < MAX_STEPS:
    2. action = plan(context)
    3. result = execute(action) # parameter validation + permission check
    4. context = update(context, result)
    5. done = check_acceptance(context)

    A few engineering points also matter: tool descriptions should state clearly when the tool applies and when it does not; parameters should be validated against a structured schema, returning a readable error rather than throwing an exception on failure; idempotent tools and side-effect tools should be handled at different levels, with side-effect operations requiring a second confirmation.

    4. Permissions and Sandboxing: Least Privilege by Default

    Once an agent can write files, execute commands, and access the network, the main risk comes from overly broad permissions. A workable approach is to default to read-only and elevate only when needed; place the execution environment in a container or an isolated directory, limiting accessible paths and outbound network scope; introduce a human confirmation gate for high-risk actions and keep a complete operation trail. Decoupling permission checks from business logic is what allows the same policy to be reused across different environments.

    5. Sub-Agents and Task Orchestration

    For large tasks, a single context can hardly balance breadth and depth. A common pattern is for the main agent to handle decomposition and aggregation, while sub-agents complete specialized work such as retrieval and verification in independent contexts and return only conclusions and evidence, protecting the main context from being polluted. For orchestration, you can use a serial pipeline, a parallel fan-out followed by a merge, or a “generate-review” setup where two roles check each other. Note that the number of sub-agents and the degree of concurrency should be controlled to avoid resource amplification.

    6. Observability, Evaluation, and Cost Control

    Without observability there is no optimization. It is recommended to record the input summary, tool calls, elapsed time, and result status of each execution in a unified way, forming a replayable trail; build an offline evaluation set covering common tasks and edge cases, and measure improvements with pass rate and rework count; on the cost side, suppress overhead through context compression, cache reuse, and tiered model routing (simple tasks go to lightweight models). If you use general-purpose cloud capabilities, you can rely on log services, monitoring and alerting, object storage, and message queues to archive trails and decouple work asynchronously. These are general industry categories, independent of any specific vendor.

    7. Common Anti-Patterns

    • A free-running loop with no termination condition, causing idle spinning and runaway costs.
    • Stuffing the entire history into the context, where early noise drowns out key constraints.
    • Tools with too coarse a granularity, where one tool takes on too many responsibilities and errors are hard to locate.
    • Missing acceptance criteria, so the model ends as soon as it believes it is done.
    • Permissions opened up across the board, leaving incidents impossible to trace afterward.

    8. A Practical Adoption Path

    Step one: define the task family and acceptance criteria, and write the termination conditions clearly first. Step two: implement a minimal tool set with structured parameter validation. Step three: add a to-do list and layered context to control window usage. Step four: complete isolated execution and confirmation gates. Step five: connect trail recording and offline evaluation to enter continuous iteration. Following this order, in a general-purpose cloud environment such as Baidu AI Cloud, you can use a container platform to host the execution sandbox, object storage to archive trails, and monitoring and alerting to ensure stability, gradually building reusable agent execution framework capabilities.