A visual guide to agent harnesses

What sits around the model, how each piece works, and how one harness becomes many agents

AgentsEngineering10 min read

An agent harness is a carefully crafted program built out of a few moving parts working in sync: a model, context (system instructions, tool descriptions, short-term conversation, and long-term memory), and the tools the model can call.

Over the past few months I built Symphony, an open-source agent harness in Python. This guide walks through those moving parts, how they fit together in Symphony, and the practical lessons from building it.

The model is not the agent

A large language model (LLM) is stateless: text goes in, text comes out. It cannot read a file, run a command, or recall yesterday's work unless an outer runtime executes those actions and feeds the results back into the next request.

That outer runtime is the harness—it shapes what enters context, executes tools, manages memory, enforces limits, and streams events to whatever interface you use.

HARNESS RUNTIME1. assemble contextContextprompt + schemasshort-term turnslong-term DBModelswappable engineToolsfiles · mediashell · testsweb · subagentstool results + events loop back into contextWorkspace · Files · Network
Inside the harness runtime: context, a swappable model engine, and tools wired to the workspace.

Swapping the model takes one config string; designing the harness around it is where an agent's reliability is won or lost.

1. The run cycle: completing the loop

At first glance, an agent loop is just a 20-line while loop that relies on whatever the model sends back: call the model, run any requested tools, append the results, and repeat until the model stops asking for tools.

The harness is what completes that loop and makes it reliable enough to trust on a real task—something meant to save you twenty minutes or days of work instead of failing silently halfway through.

1 · task in

A task arrives. The harness sends the prompt and history to the model.

The run cycle. Limits and stop conditions keep the loop bounded.

Production reliability lives in the edge cases around that loop:

  • Runaway loops: Models can retry failing calls forever. Enforce explicit caps on turns, wall-clock time, token spend, and total tool calls.
  • Ambiguous exits: Callers need to know whether a run finished, hit a budget cap, was cancelled, or crashed. Symphony ends every run with one explicit terminal status (completed, limit exceeded, cancelled, or error).
  • Mid-run steering: When you spot the agent heading down a bad path, killing the run wastes all gathered context. Symphony queues incoming user messages and injects them at the start of the next turn so you can steer without restarting.

2. Tools: basic, specific, and error-tolerant

Tools are the contract between the model and the environment. To the model, a tool is a name, a description, and a typed parameter schema. To the harness, a tool is a function guarded by validation and output caps.

1 · ask

The model names a tool and fills in its arguments.

Every tool call passes through validation, execution, and a hard cap on output.

Three design principles matter most for tool interfaces:

  • Make tools basic and specific at the same time. A single read_file tool should natively handle UTF-8 text (paged with line offsets), CSVs, images, and sampled video frames—otherwise you end up relying on the model's ability to call bash reliably and continuously just to inspect basic project files.
  • Return errors to the model instead of crashing. When a model passes a missing path or invalid argument, sending a clear hint back as the tool result lets it self-correct on the next turn.
  • Treat the tool list as the capability boundary. Fewer, well-scoped tools mean a smaller attack surface, lower token overhead, and fewer ambiguous choices for the model.

3. Context: managing a finite window

The context window is the agent's working memory, and it degrades before it overflows. Before you type a prompt, the window already holds the system prompt, project instructions, tool schemas, and skill listings. Every file read and command output shrinks the remaining budget—and as token count grows, models lose recall precision on earlier details.

~16,000/ 200,000 tokens·8.0%
80%
  • System2.0%
  • Tool schemas5.0%
  • Skills1.0%
  • Messages0.0%
  • Assistant0.0%
  • Tool results0.0%
  • Summary0.0%
  • Remaining92.0%
Illustrative 200,000-token window: cross 80%, summarize older turns, keep recent context.

There are several ways to keep a long session inside that window: dropping stale tool calls outright, shrinking or stubbing old tool logs while keeping only the assistant and user turns, or summarizing older slices of the conversation. Each trades off detail for space.

What worked best in Symphony is a two-stage process that keeps the saved transcript intact while compacting only what the model sees:

  • Cap large outputs at insert time. Every tool output is bounded once as it enters history (keeping a 40/60 head-and-tail split), so one cat of a huge log never burns thirty turns of budget.
  • Pin the goal + recent window, summarize the middle. When context crosses the compaction threshold, Symphony pins the system prompt, the first user ask (so the original task never drifts away), and the most recent tool window. The middle slice is rendered into a bounded transcript and summarized once into a single [compacted earlier context] checkpoint—falling back to a deterministic template summary if the model call fails.

4. Memory: structured stores, scratchpads, and scenarios

Short-term context ends when the session ends. Long-term memory gives an agent continuity across sessions—without forcing you to re-explain repository conventions, past fixes, or recurring workflows every time you start a new run.

In practice, long-term memory works best when you combine three mechanisms rather than relying on one giant file:

  • Structured database memory. Store durable facts—like workspace conventions, test commands, and user preferences—as indexed records in a relational database (such as SQLite or Postgres) so the harness can fetch exact matches cleanly without re-reading raw transcripts.
  • An in-run scratchpad. Give the agent a lightweight scratchpad it can read and write while working through a task. Mid-run discoveries stay pinned in the scratchpad even if older tool outputs get compacted away.
  • Scenario documents queried by task key. Keep text-based scenario documents (for example in MongoDB) tagged by task type—such as migrations, auth debugging, or release checks. Before a run begins, a simple key search on the incoming task type pulls the relevant playbook in practically real time.
1. Task starts · recall before turn 1
key query < 10ms

Before the first model call, the harness queries structured facts and searches scenario docs by task type.

How all three memory layers work together: recall before turn 1, scratchpad mid-run, promote after.

Symphony combines file-backed topics with a rebuildable SQLite index and runs reflection in the background after runs finish. Because model-written memory can still go stale or overgeneralize a one-off preference, every recalled entry is labeled explicitly as untrusted reference data—hints to verify, never blind rules.

5. Subagents: isolated branches for big tasks

Large investigations fill a single context window quickly. Instead of letting one agent read forty files into its main history, the parent forks scoped subtasks onto isolated subagent branches—just like checking out feature branches in git, doing heavy work in isolation, and merging back only a short answer.

parent taskforkchild A · inspect authreads 40 files in own windowchild B · run testsruns suite in own windowshort answersparent continues
Horizontal branch flow: children absorb the heavy reading; only short answers merge back to the parent.

Isolating child context keeps the parent's window small and focused. In Symphony, children cannot spawn further children—one simple rule that prevents recursive fan-out and runaway token spend.

When not to fork: Subagents add startup latency, duplicate prompt overhead, and cannot see each other's intermediate edits. Skip subagents when two steps modify the same files or depend tightly on each other's discoveries.

6. Approval policy: gates vs. OS-level locks

The harness is the checkpoint between a model's tool call and your machine. Putting an approval policy directly in front of tool execution ensures every risky action is checked consistently, regardless of which UI triggered it.

1 · gate

Nothing runs until the approval policy sees the call.

A policy gate before every tool call: allow, ask, or deny.

Symphony uses a before_tool approval policy with ask and always_allow modes plus ordered deny and allow patterns (where deny always wins, even in unattended runs). Before matching any rule, the harness normalizes relative segments and resolves symlinks so path tricks cannot slip past a rule.

Protecting API keys and credentials from being read or leaked takes a layered approach:

  • Store credentials outside the workspace. Keep provider keys in a dedicated user-scoped store with strict owner-only permissions (0o600) or in the OS keychain—never inside the project tree where file search and read tools operate.
  • Deny before execution, not after. Evaluate deny patterns against normalized paths and commands before a tool runs, blocking secret stores and credential directories from reads, searches, and writes alike.
  • Inject at the boundary, scrub inside shells. Load keys inside the runtime only when making provider HTTP requests, and avoid echoing or leaking sensitive environment variables into agent-controlled shell output or transcripts.
Credential boundary
Agent tool
read_file via ../ or symlink
Normalize path -> match deny rules
x deny
User vault (0600)untouched
Outside workspace
blocked before disk read
Click any probe to see how the harness blocks secret reads and injects keys only at the API boundary.

Where user-space policies stop and OS locks begin: an approval policy is still user-space code—once you approve a shell command, that child process runs with your user permissions unless the kernel restricts it. Stronger setups enforce OS-level read and write locks directly on the process:

  • macOS Seatbelt (sandbox-exec) profiles lock a child process to explicit file-read* and file-write* paths and can disable outbound network sockets at the kernel level.
  • Linux Landlock, seccomp, and namespaces (bubblewrap) restrict which directory file descriptors a process can read or modify and which syscalls it can invoke—so even a rogue shell command cannot read credentials outside the granted tree.
Enforced rules
  • - before_tool: match deny -> allow -> ask
  • - normalize ../ and resolve symlinks first
  • - shell child: inherits user permissions
What happens at runtime
  • patch outside workspaceasked / denied
  • approved bash -> curlallowed as user

Checked before each tool runs. Stops bad paths early, but an approved shell still runs as your user.

Compare user-space approval policies against OS-level kernel locks on macOS and Linux.

7. Events: one stream, multiple form factors

An agent harness should never print directly to stdout or assume a single screen. Symphony emits structured events for everything that happens—turns starting, text streaming, tool calls running, and token usage updating.

stream01 · turn_startedturn: 2 · message_count: 602 · tool_execution_startedtool: "read_file" · path: "README.md"03 · usageturn: 2 · in: 11,420 · out: 318
Every turn, tool call, and usage update flows down the stream as structured events.
Symphonyone event streameventsTUIZed (ACP)WebMobile
One event stream, multiple interfaces. Clients only render events; the harness does the work.

Today, Symphony ships three listeners on that same event stream: the terminal UI (TUI), editors such as Zed over the Agent Client Protocol (ACP), and a web interface. Because the harness knows nothing about layout, adding a new client—such as a mobile app—requires zero changes to the agent loop.

Porting one harness to different products

Look back at sections 1 through 7: the core mechanics—the run loop, budgets, compaction, memory, subagents, approval policy, and event streams—are not coding-specific. Only the tools, policies, and clients change.

Separating the generic harness from product logic turns a new agent into a thin layer of tools and prompts instead of a new codebase. Symphony's harness powers three distinct products:

the core

The loop, budgets, memory, and events stay the same.

One generic harness, three products. Only the tools and prompts change.
Osmo, a voice assistant delegating work to Symphony

Osmo ↗ · Voice workspace

Osmo is a voice-first assistant you run locally. You talk, Osmo answers immediately, and when a question needs deep work it delegates to a background agent while the conversation continues. The harness underneath is unchanged—the tools are voice, a notes canvas, and background runs instead of file patches.

Somnia dashboard with session handoffs between agents

Somnia ↗ · Shared agent memory

Somnia is shared memory for coding agents. Agents submit completed sessions, and scheduled dreaming passes consolidate them into durable memories and a resume checkpoint so the next agent starts with context. It extracts the memory cycle from Section 4 into a standalone service shared across agents.

9. Lessons from building Symphony

Most of the real engineering in an agent harness happens after the first working loop—in latency, caching, edge cases, and deleting features you outgrow.

Keep the prefix stable, and prompt caching does the rest

Providers cache prompts strictly in order: tools → system → messages. When a request matches a prior prefix up to a cache breakpoint, the model reuses saved key-value (KV) states instead of recomputing those tokens—cutting both input cost and time to first token. Change a single byte early (like editing system), and that layer plus everything after it misses the cache:

~26,000/ 50,000 tokens·0% cached
  • Cached read~0 · 0%
  • Computed (new)~26,000 · 100%
  • Recomputed (busted)~0 · 0%

Turn 1 (cold start): tools, system, and turn 1 are computed fresh and saved as the initial prefix.

Growing context across turns: append-only turns reuse the cached prefix; editing system mid-run busts everything after it.
  • Never mutate the system prompt mid-session. Injecting recalled memory into the system prompt on every turn silently busted the cache. Putting dynamic memory right next to the latest user message and lazy-loading full skill text only on demand keeps the early prefix byte-identical.
  • Make history append-only and meter cache hits. Cap tool outputs once when they enter history instead of rewriting older turns, pass each provider's cache hints, and track cached read/write tokens separately so you can actually see whether caching is working.

What else mattered in practice

  • Save the full transcript; compact only what the model sees. Keep persisted session logs append-only with a boundary marker, and feed the model the compacted copy so you never lose auditability or overwrite history.
  • Treat failed tool calls as feedback. A patch with no match, a non-zero exit code, or a timeout with partial output tells the model what to fix next—returning clear diagnostics lets it recover instead of guessing.
  • Never let the model pick its own permissions. Arbitrary turn caps cut long coding runs short, and subagents should inherit limits from their parent without being able to escalate into auto-approve modes on their own.
  • Memory fails on timing, not storage. Wait for idle quiet time before running background reflection, cancel it if the user sends a new message, and cap reasoning effort during extraction so thinking tokens don't crowd out the summary.
  • The bottleneck is usually around the model. Reusing one persistent HTTP connection pool, normalizing provider usage quirks inside the provider layer, and avoiding synchronous file rereads or full-screen TUI redraws on every token saved seconds per turn.
  • Enforce boundaries with tests, and delete aggressively. Architecture rules like "the UI only renders events" only stay true once tests check imports. Removing half-used modes and thin wrappers shrank the core harness down to a handful of focused modules—and made everything left much easier to change.

What I took away

Agent harnesses are powerful and fun to build, but the real takeaway wasn't some new AI trick—it was core software engineering principles. Clear boundaries, append-only state, explicit failure modes, and decoupled event streams are what actually make a harness durable.

Those same fundamentals are what let one harness scale across completely different form factors—whether it runs in the cloud or as a local-first JSON-RPC agent—without turning every new product into a rewrite.

Symphony is up for developer preview—open source on GitHub (Python 3.11+ on macOS or Linux). Try it in your terminal or visit the Symphony site for demos and editor setup.

Explore Symphony