Agent Harness Design: Architecture and Implementation Essentials
An agent harness provides the runtime infrastructure needed to turn an LLM into a persistent, task-oriented system. This article examines common agent limitations and the architectural patterns used to address them, including layered execution, event-driven scheduling, asynchronous channels, external state storage, and independent watchdogs. A Python runtime skeleton illustrates key implementation considerations for retries, idempotency, context management, and recovery.
1. Why AI Agents Need a Runtime Framework
A large language model is an inference engine. On its own, it does not schedule tasks, persist context, or coordinate multiple workstreams. Without supporting infrastructure, progress from one interaction is not automatically retained, and unfinished subtasks are not tracked.
An agent harness is the software infrastructure built around an LLM to support more complex work. It typically provides task scheduling, context management, tool invocation, state persistence, and failure recovery. In practical terms, it is the system that allows an agent to keep operating beyond an individual interaction.
Some teams have publicly reported user and plugin growth for harness products. Because their measurement methods, reporting periods, and sources are often difficult to verify, this article does not cite specific figures. The broader trend is that agent runtimes are moving beyond proofs of concept toward production deployment, making their architecture worth examining carefully.
2. Three Bottlenecks in Common Agent Designs
Many agent implementations share three limitations:
- Session dependence. Agents are often tightly coupled to a manually initiated session. When that session closes, execution stops, context may be lost, and long-running work cannot continue.
- Human attention limits throughput. Users must track tasks across individual chat windows. The person supervising the system becomes a bottleneck, making team-scale parallel work difficult.
- State is difficult to recover. Without persistence and external monitoring, an unexpected process exit can leave task state impossible to reconstruct. This undermines the reliability of long, multi-step workflows.
The architectural shift is to make the agent a continuously operating entity rather than an extension of a chat session. It should retain context across sessions, advance multiple complex tasks, and keep those tasks isolated from one another. This type of system can be described as a super-agent.
A harness is most useful for well-defined, multi-step, long-running work, such as continuous monitoring, batch processing, and multi-step research. For highly exploratory tasks that require human judgment at every step, a session-based agent may be more appropriate. Adding a harness in those cases can introduce unnecessary complexity.
3. Core Design Principles for a Super-Agent
3.1 Separate Decision-Making from Execution
A two-layer architecture separates planning from execution:
- Decision layer: Defines plans, decomposes goals into tasks, and checks whether results meet acceptance criteria.
- Execution layer: Performs tool calls and runs individual sessions.
Instead of issuing instructions one at a time, users define goals and review results. The system manages the work in between.
This separation allows one agent to launch multiple execution units in parallel, with human involvement reserved for key checkpoints.
Three metrics help assess whether the design is working:
- The proportion of decomposed tasks that require rework.
- The number of execution units running concurrently.
- The number of human interventions per task.
A persistently high rework rate often indicates that the decision layer’s decomposition rules are unclear. Task templates or more explicit acceptance criteria may be needed.
3.2 Use Events Instead of Polling
An agent should not depend on continuous human input. It can respond to events generated by scheduled jobs, external callbacks, or subtask completion signals. These events enter a unified queue for consumption by the agent.
A message queue supports reliable delivery and absorbs traffic spikes. Three implementation details are especially important:
- Expect at-least-once delivery. The same event may arrive more than once, so handlers must be idempotent. A common approach is to use the event ID as an idempotency key and check whether it has already been completed before processing it.
- Bound retries and apply backoff. For example, allow up to five retries, doubling the delay between attempts with a maximum delay of 30 seconds.
- Move exhausted events to a dead-letter queue. An operator can then inspect the failure and decide whether to replay or discard the event. This prevents a bad event from repeatedly blocking the queue.
3.3 Support Asynchronous, Multi-Channel Interaction
An agent can listen to several input channels, such as chat, API calls, and timers, and route results back to the appropriate channel. Context must remain isolated so that unrelated tasks do not interfere with one another.
The following runtime skeleton uses only the Python standard library and requires Python 3.10 or later. It is not a complete standalone service: the protocols need concrete implementations. Connect EventBus, ContextStore, and Router to the actual message queue and storage SDKs, and pin dependency versions in the project’s dependency file.
import asyncioimport loggingfrom dataclasses import dataclass, fieldfrom typing import Any, AsyncIterator, Protocollogger = logging.getLogger("agent.runtime")@dataclassclass Event:event_id: strsession_id: strchannel: strpayload: dict[str, Any] = field(default_factory=dict)class EventBus(Protocol):def subscribe(self, agent_id: str) -> AsyncIterator[Event]: ...async def ack(self, event: Event) -> None: ...async def nack(self, event: Event) -> None: ... # Move to the dead-letter queueclass ContextStore(Protocol):async def load(self, session_id: str) -> dict[str, Any]: ...async def save(self, session_id: str, ctx: dict[str, Any]) -> None: ...class Executor(Protocol):async def handle(self, event: Event, ctx: dict[str, Any]) -> dict[str, Any]: ...class Router(Protocol):async def dispatch(self, result: dict[str, Any], channel: str, idempotency_key: str) -> None: ...class AgentRuntime:def __init__(self,agent_id: str,event_bus: EventBus,context_store: ContextStore,executor: Executor,router: Router,timeout_s: float = 120.0,max_retries: int = 5,) -> None:self.agent_id = agent_idself.event_bus = event_busself.context_store = context_storeself.executor = executorself.router = routerself.timeout_s = timeout_sself.max_retries = max_retriesself._locks: dict[str, asyncio.Lock] = {}# Use a persistent idempotency table in production.# This in-memory set is lost when the process restarts.self._done: set[str] = set()async def run(self) -> None:async for event in self.event_bus.subscribe(self.agent_id):# Serialize events within a session to prevent conflicting context writes.lock = self._locks.setdefault(event.session_id, asyncio.Lock())async with lock:await self._process(event)async def _process(self, event: Event) -> None:if event.event_id in self._done:await self.event_bus.ack(event)returnfor attempt in range(1, self.max_retries + 1):try:ctx = await self.context_store.load(event.session_id)result = await asyncio.wait_for(self.executor.handle(event, ctx), timeout=self.timeout_s)await self.context_store.save(event.session_id, ctx)await self.router.dispatch(result, event.channel, event.event_id)self._done.add(event.event_id)await self.event_bus.ack(event)returnexcept asyncio.TimeoutError:logger.warning("event %s timed out on attempt %d", event.event_id, attempt)except Exception:logger.exception("event %s failed on attempt %d", event.event_id, attempt)await asyncio.sleep(min(2 ** attempt, 30))logger.error("event %s exhausted retries, sending to dead letter queue", event.event_id)await self.event_bus.nack(event)
Several details deserve attention:
- Session ordering: Per-session locks protect context from concurrent writes. The intended architecture allows independent sessions to run concurrently, but this minimal
run()loop awaits each event and therefore processes events sequentially. - Persistence before delivery: Context is saved before the result is dispatched. If the process crashes after saving but before dispatching, processing may run again. The router must honor the event ID as an idempotency key to prevent duplicate user-facing delivery. This does not, by itself, make repeated executor operations idempotent.
- Timeouts:
asyncio.wait_forlimits executor runtime. Tools that call external services should also have their own timeout and retry settings. - Retry counting: In this skeleton,
max_retriescontrols the total number of processing attempts, including the initial attempt. - Lock cleanup: The lock dictionary grows with the number of sessions. A long-running service should clean up locks for idle sessions.
3.4 Separate Compute from Storage
External state is a prerequisite for continuity across sessions.
Inference itself does not persist runtime state. Session context, task progress, and intermediate artifacts must be written to external storage. This allows an agent to be suspended, moved, or recovered, and provides a foundation for horizontal scaling across multiple replicas.
Choose storage according to the data:
- Object storage: Artifact files such as reports, code archives, and screenshots.
- Key-value stores or document databases: Task state and context snapshots.
Snapshot frequency is a central trade-off. More frequent snapshots reduce the amount of work that can be lost, but increase write and storage costs. Common approaches include taking a snapshot after each tool call or at the end of each conversation turn.
The potential loss window is the work completed since the most recent snapshot but not yet persisted. Recovery time depends on how long it takes to load the snapshot and reconstruct the context.
Start with the amount of lost work the business can tolerate, use that to determine the snapshot interval, and then assess whether the storage cost is acceptable.
3.5 Run an Independent Watchdog
A watchdog should run outside the agent process. It monitors task heartbeats and execution state, terminates abnormal execution, raises alerts, and initiates recovery from the latest snapshot.
Thresholds depend on the workload. The following values are starting points to refine during trial operation:
- Send a heartbeat every 10 seconds. Treat three consecutive missed heartbeats as an abnormal condition.
- Interrupt execution if the same tool is called with identical arguments more than five consecutive times, indicating a possible loop.
- If a task exceeds its configured total runtime, raise an alert and pause it for human review.
Route alerts by severity:
- P1: A task is stuck and automatic recovery has failed. Notify the on-call operator immediately.
- P2: Retries are approaching the limit. Investigate the same day.
- P3: A single timeout occurred, but automatic recovery succeeded. Record it for reference.
Apply least privilege to the watchdog. It needs permission to stop and restart execution units and read snapshots. It should not be able to modify business data or send external messages.
High-risk operations, such as payments, data deletion, and outbound email, should require human approval. When execution reaches one of these operations, the watchdog should pause the task until approval is provided.
Recovery must also be tested regularly. A practical recommendation is to select a random snapshot in a test environment each month, run the full recovery procedure, and record both the actual recovery time and the amount of work lost.
