Agent Harness in Practice: Keeping Long-Running AI Agent Tasks Under Control
This article explains how an Agent Harness manages the steps, permissions, and state of an AI agent that runs long, multi-step enterprise workflows. It covers the typical failures of long-running tasks, the core harness components (execution loop, tool permissions and sandboxing, memory management, and replayable logs), and methods for controlling cost and checking readiness before launch.
Large language models handle single-turn reasoning well. Many enterprise business processes, however, require dozens of steps and calls to several internal systems. Once a task goes beyond a single API call, a layer of surrounding code must manage the model’s steps, permissions, and state. This layer is the Agent Harness.
This article starts with the typical failures of long-running tasks, then explains each core component of a harness. It ends with methods for cost optimization and a pre-launch checklist.
1. Why Long Tasks Fail
Without a unified supporting framework, agents running long task chains often show four types of failure.
- Context decay: Each step adds to the interaction history until it exceeds the model’s context window. Once early key instructions or task state are pushed out, the model gradually drifts from its goal.
- Infinite loops: When a tool returns an unexpected result, the model may repeat the “call, fail, call again” cycle, wasting compute and cost.
- Hallucinated tool calls: The model may invent an API that does not exist or pass parameters of the wrong type, which causes errors in downstream services.
- Resource runaway and state loss: Without an isolated execution environment, faulty code can exhaust host machine resources. If a task is interrupted midway and its state cannot be recovered, it must restart from the beginning.
The harness keeps these risks outside the model. It sits between the model and business systems, controls the workflow, limits permissions, and records every step.
2. How to Design the Execution Loop to Prevent Runaway Tasks
The execution loop is the core of the harness. It usually follows a state machine structure that advances the task in three phases: perceive, think, and act. Each iteration does three things. It checks whether the task is complete, validates whether the action proposed by the model is allowed, and executes the action and saves the result.
The pseudocode below shows only the control flow. The implementations of llm_infer, validate_action, execute_tool, compress_context_if_needed, and other functions are omitted.
MAX_STEPS = 20MAX_RETRIES_PER_ACTION = 2def run_agent(task, store, alert):state = store.load(task.id) or init_state(task) # Resume from a checkpoint if one existsretries = 0for step in range(state.step, MAX_STEPS):if state.is_complete:return state.resulttry:action = llm_infer(state.context)except ModelError as e:log_event(task.id, step, "model_error", str(e))raise# Check the tool name, parameter types, and whether the tool is on the task's allowlistif not validate_action(action, task.policy):retries += 1if retries > MAX_RETRIES_PER_ACTION:alert(task.id, "Too many consecutive invalid actions. Task stopped.")raise PolicyViolation(task.id)state.context.append("Invalid action. Choose a tool from the allowed list.")continueretries = 0result = execute_tool(action.tool_name, action.params) # Execute in the sandboxstate.update(action, result)state.context = compress_context_if_needed(state.context)store.save(task.id, state) # Save a checkpoint after every steplog_event(task.id, step, action, result)store.save(task.id, state)alert(task.id, "Maximum step count exceeded. Task suspended for manual review.")raise TimeoutError(task.id)
This code has three key design points.
- Step limit: When the limit is reached, the task is not discarded. The system saves a checkpoint, sends an alert, and hands the task to a human.
- Retry limit: If the same type of invalid action occurs more times in a row than the configured limit, the task stops. This prevents wasted retries.
- Checkpoint at every step: If a task is interrupted, it can resume from the most recent step instead of rerunning all steps.
No standard value exists for these limits. Test with a set of representative tasks first. Observe how many steps normal tasks typically need, then set the limit with a reasonable margin above that.
3. How to Configure Tool Calls and Sandbox Permissions
Preventing hallucinated tool calls and resource runaway depends on permission design. The recommended default policy is “deny all, allow as needed.”
Each task typically runs in its own container, such as an isolated Docker-based environment. Permissions are declared centrally in a configuration file. For example:
task: sales_reporttools:allow:- name: query_ordersmode: read_onlytables: [orders_2026]deny_all_others: truenetwork:outbound: denyfilesystem:root: read_onlyscratch_dir: /tmp/agent # The only writable directory, cleared when the task endscredentials:source: secret_managerttl_minutes: 30
This configuration means the agent can only run read-only queries against one orders table. It cannot use any other tools or make outbound network requests, and it can write only to a temporary directory. A secrets manager issues credentials on demand. They are valid for only 30 minutes and are never written into prompts or logs.
Keep these security practices in mind:
- Outbound network access is disabled by default. If it is needed, allow specific domains individually.
- The file system is read-only by default, with a single writable temporary directory.
- Credentials are kept separate from code, use short-lived tokens, and are rotated regularly.
- Every tool call is written to an audit log, and unusual calls trigger alerts.
4. How to Manage Memory and Prevent Context Decay
Memory management has two parts: short-term memory and long-term memory.
Short-term memory stores the conversation history and intermediate state of the current task. When the token count approaches the window limit, the harness triggers compression. A workable
