Building Pluggable AI Agents: Minimal Harness and Component-Based Practices
This article explores how to build a minimal AI agent harness to avoid code coupling and debugging bottlenecks. It covers defining clear plugin boundaries for models, tools, memory, and sandboxes, while detailing the kernel's three core responsibilities: model and tool orchestration, high-risk operation approval, and task plan maintenance. Additionally, it provides practical guidance on component evaluation, deployment steps, and mitigating common risks.
1. Why the Agent Harness Should Stay Thin
An AI agent system can be described by a simple formula: Agent = Model + Harness. The model is responsible for understanding tasks, generating reasoning, and making decisions. The harness is responsible for translating the model’s decisions into actual actions and applying constraints before and after those actions.
When the responsibilities of the harness bloat, three common problems typically arise. First, the harness code becomes deeply coupled with specific models and tools, meaning changing any component requires modifying core logic. Second, security policies are scattered, making unified auditing difficult. Third, during debugging, it becomes hard to determine whether the issue lies with the model’s output or the harness logic.
Therefore, a more robust approach is to shrink the harness to a minimal kernel. This kernel retains only three responsibilities: orchestrating models and tools, requesting human approval before high-risk operations, and maintaining a task plan. Capabilities such as search, memory, and code execution are all integrated as plugins.
2. Boundaries of Pluggable Components
The key to pluginization lies in defining clear interface boundaries. Each category of components only needs to satisfy a unified protocol; the kernel does not need to understand its internal implementation.
2.1 Model Plugins
Model plugins are responsible for encapsulating inference services. Common capabilities include text generation, image generation, video generation, and vectorization. Vectorization is used for semantic retrieval, while generative models handle reasoning and content production.
When designing model plugins, you can follow these conventions:
- Standardize input and output structures, including message lists, tool definitions, and the return format for function calls.
- Inject API keys through environment variables or a key management service; never hardcode them in configuration files or source code.
- Record the model identifier, input/output length, and latency for each call to facilitate cost accounting and performance analysis.
2.2 Tool Plugins
Tool plugins wrap external capabilities into callable functions. Typical tools include web search, database queries, file I/O, and code execution.
Tool plugins should declare the types and value constraints of input parameters and return structured results. Error messages should also be structured, allowing the model to decide whether to retry or switch to a different tool based on the information.
2.3 Memory Plugins
Memory plugins are responsible for persisting information across sessions. In practice, memory is often divided into three layers:
- In-session context, cleared when the conversation ends.
- Working memory, storing intermediate results for the current task.
- Long-term memory, storing user preferences, stable facts, and verified experiences.
The timing for writing to long-term memory must be explicit. A safer approach is to extract key points in a separate step after the session ends, perform deduplication and expiration checks, and then commit to the database. This prevents unverified content from being permanently stored.
2.4 Sandbox Plugins
Sandbox plugins provide an isolated environment for code execution and file operations. A sandbox should restrict network access scopes, writable paths, and execution duration, and clean up temporary resources after the task completes.
2.5 Agent Plugins
Agent plugins define roles, goals, and the set of available tools. The same kernel can mount different agent configurations, thereby reusing the orchestration logic.
3. Implementing the Three Core Kernel Responsibilities
3.1 Orchestrating Models and Tools
The core of orchestration is a loop. The system sends the current context and tool definitions to the model. If the model returns a function call request, the kernel executes the corresponding tool, appends the result to the context, and queries the model again. The loop continues until the model provides a final answer or the step limit is reached.
The sample code is as follows:
def run_agent(task, model, tools, gate, plan, max_steps=20):context = [{"role": "user", "content": task}]for _ in range(max_steps):reply = model.chat(context, tools=tools.schemas())if not reply.tool_calls:return reply.textfor call in reply.tool_calls:tool = tools.get(call.name)if tool.risk_level == "high" and not gate.approve(call):result = {"error": "User did not approve the operation"}else:result = tool.run(**call.arguments)plan.record(call, result)context.append({"role": "tool", "content": str(result)})raise RuntimeError("Max steps exceeded")
Three points in the code require attention. First, the step limit prevents infinite loops. Second, the approval check is placed before tool execution, rather than as a post-execution remedy. Third, every call is written to the plan record for traceability.
3.2 Approving High-Risk Operations
The goal of the approval mechanism is to keep humans in control at critical nodes while avoiding interrupting the user for every low-risk operation.
Operations can be categorized by risk level:
- Low risk: Read-only queries, local computations; execute directly.
- Medium risk: Writing to temporary directories, calling external read-only APIs; execute after logging.
- High risk: Deleting data, sending messages, modifying permissions, deploying to production; must wait for human confirmation.
An approval request should include the operation type, target object, parameter summary, and expected impact, allowing the approver to make a judgment without reading the entire context. All approval results should be written to an audit log, recording the approver, time, and decision.
3.3 Maintaining the Task Plan
The task plan is a structured to-do list, where each item contains a description, status, and dependencies. The kernel updates the plan status after each round of orchestration. The model can read the plan during reasoning to determine the next step.
The value of the plan lies in breaking down long tasks into checkable steps. When a step fails, the harness can pinpoint the specific step and retry specifically, rather than executing from the beginning.
4. Evaluation Dimensions for Component Selection
When selecting plugins, you should start from business requirements and compare them across the following dimensions:
- Timeliness: Does the task depend on the latest facts? Tasks requiring timeliness need search capabilities and support for time-range filtering.
- Source Credibility: Can search results provide citations, and can they be filtered by authoritative sources?
- Data Coverage: Is structured data sourcing required for professional data like financial reports, corporate information, or academic papers?
- Query Quality: Is query rewriting supported to improve recall rates?
- Cost Control: Can usage-based billing be tracked, and can budget limits be set?
- Replaceability: Are interfaces standardized, and does swapping implementations require modifying the kernel?
During evaluation, it is recommended to run comparative tests using real task samples, recording hit rates, response latency, and cost per call, rather than merely looking at feature lists.
5. Deployment and Implementation Steps
Implementation can be divided into four steps.
Step one: Start the local service of the harness and verify that the default listening address is accessible. In production environments, bind to an internal IP address and configure access control to avoid direct exposure to the public internet.
Step two: Add model providers in the configuration and connect using dedicated API keys. Keys should be loaded via environment variables or a key management service, with regular rotation enabled.
Step three: Integrate tool and memory plugins incrementally. For each plugin integrated, run regression test cases to ensure the call chain and error handling work correctly.
Step four: Enable observability. Log the latency, input/output length, tool call count, and approval results for each model call round. This data is used for both troubleshooting and cost analysis.
6. Common Risks and Mitigations
Prompt Injection. Web content, file contents, and tool return values may contain deceptive instructions. The harness should process these contents as data, not execute them as instructions. For critical actions, human confirmation is still required.
Unauthorized Operations. Tools should follow the principle of least privilege, granting only the permissions necessary to complete the task. File and network scopes for sandboxes need to be explicitly configured.
Context Bloat. In long tasks, historical tool results can quickly fill the context window. You can summarize or truncate tool outputs, keeping only the parts relevant to the current step, while writing the full results to working memory for future reference.
Memory Pollution. Once incorrect information is written to long-term memory, it will be repeatedly called in subsequent sessions. Sources should be verified before writing, and expiration times should be set for memory entries.
7. Conclusion
Keep the harness lean and extend capabilities through plugins. This structure makes it easy to swap components, audit behaviors, and control costs. During implementation, you can start by running a complete task through the minimal kernel, then gradually add plugins, validating the results with real samples at each step.
