AI Agent Harness: Architecture, Cost, and Security in Agent Execution Frameworks
This article breaks down how AI agent execution frameworks (Agent Harnesses) move large language models from giving suggestions to completing end-to-end tasks. It explains the shift in technical paradigm, clarifies how model API usage is billed in tokens, and outlines a common five-layer architecture covering interaction, planning, tools, runtime sandboxing, and governance. You will find a general setup workflow, sample configuration, and three core engineering concerns—cost control, context management, and reliability—along with security boundaries such as prompt injection, least privilege, supply chain risk, and observability, plus a practical adoption checklist.
1. From Giving Advice to Finishing the Job: A Shift in Technical Paradigm
Over the past two years, the typical interaction with large language models has been conversational: a user asks a question, and the model returns a block of text or a code snippet. Whether it is usable, how to integrate it, and how to verify it are all left to the human. As capabilities such as tool calling, code execution, file system access, and long-task orchestration have matured, a new class of software has emerged—the agent execution framework (Agent Harness). Its core goal is not to “say it better” but to “get it done completely”: given a goal, it autonomously breaks down steps, calls tools, reads and writes files, runs tests, iterates based on failure information, and continues until a deliverable result is produced.
It is important to emphasize that this type of framework is essentially a combination of “model + runtime + tool layer + permissions and auditing.” The model is only responsible for decision-making and generation; what actually produces side effects is the runtime. Understanding this is the prerequisite for assessing its capability boundaries and security risks.
2. Understanding Billing Correctly: Why Developer-Facing Calls Are Charged
Most of the controversy around charging for large model services comes from conflating a “chat product” with “model capability supply.” These are things at different layers:
- Conversational products for ordinary users are typically offered free or via subscription, covering the vast majority of daily needs such as Q&A, writing, data processing, and coding assistance.
- Model calls for developers are essentially purchasing compute and inference services based on usage—the rental of a production factor. You use the capability to create value, and the provider charges by measured consumption. This is standard practice across the industry.
Billing typically uses the token as the basic unit. A rough rule of thumb: one Chinese character is roughly 2 tokens, while punctuation, spaces, and English words each take up a number of tokens as well. Input refers to your prompt and context; output refers to the content generated by the model. Some services differentiate between busy and idle periods, with higher unit prices during busy times, which is directly related to the supply and demand of compute.
An illustrative cost estimate (the numbers are only to explain the method and do not represent the price of any specific service):
Task: Generate an 800-word articleInput: prompt and background ~100 words -> ~200 tokensOutput: body ~800 words -> ~1600 tokensTotal: ~1800 tokensCost = input tokens × input unit price + output tokens × output unit price
For agent scenarios, the cost structure changes significantly: a single task often involves multiple rounds of model calls, tool return content being fed back in, and retries after failures, so actual consumption may be dozens of times that of a single conversation. Therefore, cost control must be designed upfront rather than reviewed after the bill arrives.
3. The General Architecture of an Agent Execution Framework
A usable execution framework typically consists of five layers:
- Interaction layer: receives the goal description and displays the execution plan, intermediate artifacts, and final deliverables.
- Planning layer: breaks the goal into verifiable subtasks and decides the call order and termination conditions.
- Tool layer: adapters for common cloud capabilities such as file read/write, command execution, dependency installation, test running, log retrieval, object storage, and message queues.
- Runtime and sandbox: an isolated execution environment that restricts network, file system, and resource quotas.
- Governance layer: permission control, key management, full-chain auditing, cost tracking, and alerting.
A schematic task loop can be abstracted as:
while not done and steps < MAX_STEPS:plan = model.plan(goal, context) # decide the next stepresult = tool_registry.run(plan) # produce side effectscontext = summarize(context, result) # compress context, control tokensdone = verify(goal, context) # use tests/checks instead of subjective judgment
Here, verify is the most critical part in engineering: if something can be determined by compilation, unit tests, static checks, or interface probing, do not let the model “feel good about itself.”
4. General Setup and Installation Workflow
Implementation details vary, but the skeleton of the steps is highly consistent:
- Confirm that runtime dependencies (language runtime, package manager, container runtime) meet the required versions.
- Obtain the framework release package or repository address (please use official channels and avoid install scripts of unknown origin).
- Configure the model service address and access key. The key should be injected via environment variables or a key management service, not written into the code repository.
- Initialize the working directory and configuration file, declaring the allowed tool whitelist and prohibited operations.
- Run a minimal verification task to confirm the “read—execute—write back—verify” chain works.
A minimal configuration example (fields are generic illustrations):
model:endpoint: "<your-endpoint>"api_key_env: "MODEL_API_KEY"sandbox:network: restrictedcpu: 2memory: 4Giworkdir: "./workspace"tools:allow: [fs_read, fs_write, shell, test_runner]deny: [network_egress, package_publish]limits:max_steps: 40max_tokens_per_task: 400000
5. Three Main Threads: Cost, Context, and Reliability
Cost control: prioritize using small models for subtasks such as classification, extraction, and formatting, and only escalate when complex reasoning is needed; summarize and truncate tool return results; set per-task token and step limits; cache repeated call results.
Context management: the failure of long tasks is often not due to insufficient model capability but to context being flooded by irrelevant logs. It is recommended to use a three-part “goal—plan—evidence” context, keeping only the file fragments and error stacks relevant to the current subtask.
Reliability design: make “verifiable” the delivery standard—for example, existing tests must pass; enable diff review for write operations; require manual confirmation for high-risk actions (deletion, release, permission changes); and retain complete audit logs for traceability.
6. Security Boundaries and Common Risks
- Prompt injection: repository files and web content may carry malicious instructions. Treat external content as untrusted data and prohibit it from changing system instructions.
- Least privilege: default to read-only and grant write permission on demand; use different credentials for production and development environments.
- Supply chain risk: do not execute scripts of unknown origin, lock dependency versions, and verify artifact signatures.
- Data compliance: clarify which data may leave the domain, and desensitize sensitive fields before they enter the context.
- Observability: establish monitoring and alerting for call volume, failure rate, and per-task cost, and automatically trip a circuit breaker on anomalies.
7. A Practical Adoption Checklist
- Start with “low-risk, verifiable” tasks, such as batch refactoring, test completion, and log categorization.
- Define acceptance criteria first, then hand the task to the agent, avoiding open-ended goals.
- Establish human-machine collaboration checkpoints: plan confirmation, write-operation confirmation, and release confirmation.
- Use a small-sample baseline to compare human time and token cost, quantify the benefits, and then expand the scope.
- Build team standards: tool whitelist, key management, audit retention period, and cost budget.
Overall, the value of an agent execution framework lies in handing a “verifiable engineering loop” to the machine, while the human role shifts to defining goals, setting constraints, and reviewing results. Understanding its architectural layers, billing basis, and security boundaries matters more than chasing any specific tool. Building your own execution pipeline on top of the general capabilities of cloud platforms such as Baidu AI Cloud (e.g., container platform, object storage, log service, monitoring and alerting) is a relatively sound engineering path.
