Harness Engineering for Agents

Structured Loop Hierarchy

A single agent conversation looks linear to the user, but the harness sees three nested levels of execution, each with its own lifecycle, failure modes, and state machine. A naive loop collapses these into one flat while-LLM-responds block and pays the price when a tool hangs for thirty seconds, the user types mid-response, or the session needs to survive a crash. The structured loop hierarchy separates session (the full conversation), turn (one LLM response cycle), and step (one tool call within a turn) into explicit, independently managed units. This decomposition lets the harness pause a turn at a step boundary, stream progress without blocking the UI, and enforce hard time budgets per level without corrupting the others.

Session Turn Step Lifecycle

A session is the outermost container: it owns the message transcript, the tool registry, and the storage backend. It starts when the user opens a conversation and ends when they close it or hit a session-level timeout. Within the session, the harness runs a sequence of turns. Each turn begins with a model request (sending the message history plus a system prompt to the LLM) and ends when the model produces a final answer or the harness terminates the turn due to budget exhaustion. Inside a single turn, the model may issue multiple steps: each step is one tool call, from the moment the harness receives the tool name and arguments to the moment it commits the tool result back into the message history. The kernel orchestrates these levels through a state machine that enforces valid transitions. A step cannot start before the preceding step in the same turn has completed, committed, or failed. A new turn cannot start until the previous turn has terminated, no interleaving. Sessions can pause between turns (saving the transcript to storage) but never mid-turn unless the crash recovery layer handles it. The lifecycle state of each level is explicit: sessions are active, paused, or closed; turns are pending, running, step-locked, or done; steps are submitted, executing, succeeded, or failed.

spec: static diagram of three nested boxes labeled Session, Turn, and Step. Session box has a line from "active" to "paused" to "closed". Inside Session, a sequence of Turn boxes each transitioning through "pending", "running", "step-locked", "done". Inside one Turn, a sequence of Step boxes transitioning through "submitted", "executing", "succeeded" or "failed". A dashed arrow shows that after a failed step the Turn can go directly to "done" (skip remaining steps).

Common trap: Treating "turn" and "step" as synonyms. A turn contains multiple steps in sequence. If you design recovery logic around "retry the turn" you re-run every step from scratch, including side-effecting tool calls that already completed. The separation lets you retry a single step or abort the turn without replaying earlier steps.

Live State Projections and SSE Event Streaming

The raw event log of a session is append-only: every step start, tool result, LLM token, and user message gets recorded as an immutable event. Clients, however, do not want to replay the entire log to see the current state. The harness derives live state projections from the event log by applying events incrementally to an in-memory model. Each projection is a read-optimized view: the current message list, the active turn's status, the remaining step budget. These projections update atomically every time a new event is committed. To push these updates to remote clients efficiently, the harness streams them as structured SSE events over a single long-lived HTTP connection. Each SSE event carries a type field (turn_start, step_result, token_chunk, session_paused) and a payload serialized as JSON. The client never polls; it subscribes to the projection stream and recomputes its UI from the delta. The key invariant is that a projection is always behind the committed log by at most one event: the harness commits the event to storage first, then broadcasts the projection update. This ensures that if the client disconnects mid-stream, it can reconnect and replay from the last committed event without losing state or seeing phantom states that never got persisted.

spec: static diagram of a timeline with three layers: top line shows committed events (E1, E2, E3, E4) written to storage. Middle line shows projections (P1, P2, P3, P4) that update after each commit. Bottom line shows SSE stream with arrows from each projection to a client box labelled "UI", each arrow labeled with event type (turn_start, step_result, token_chunk). A dashed arrow from committed E3 directly to SSE stream skipping projection shows a token_chunk that bypasses the projection layer.

Watch out: Token chunks are the exception. Projections are expensive to recompute on every token (hundreds per second). Modern harnesses stream raw token events directly via SSE, bypassing the projection layer, and only update the projection at step boundaries. The client merges raw tokens into its own local message buffer until the next projection confirms the definitive state.

Mid-Turn Steering Versus Message Queuing

A user who types a correction while the model is mid-turn creates a conflict. The harness must decide: inject the message into the current turn's context, or queue it for the next turn. Mid-turn steering delivers the user's message as an interrupt: the harness appends it to the message list, cancels any pending tool step, and re-invokes the LLM with the updated history. The model sees the new instruction immediately, which is essential for fixing a tool call that went off track. Message queuing, by contrast, holds the user's input until the current turn finishes naturally, then starts a new turn with the queued message as the first user utterance. Queuing preserves ordering: the model never sees a message out of sequence with respect to tool results. The trade-off is latency, queuing can delay a course correction by minutes if the current turn is running a long bash command. The harness resolves the conflict by examining the current step's state. If the step has not yet started (still queued or waiting on a approval gate), the harness can safely abort the entire turn and re-run with the new input. But if a tool step is already executing with side effects (a file write, a git commit), mid-turn steering would orphan that operation and leave partial state. In those cases, the harness falls back to queuing, and the user sees a confirmation dialog or a notification that their input will take effect after the current step completes.

Aspect Mid-Turn Steering Message Queuing
When used Before step execution or after a completed step During an executing step with side effects
Ordering Message inserted before current position Message appended after current turn
Latency Immediate Delayed until turn ends
Risk Orphaned side effects if tool is mid-execution User perceives unresponsive agent

Mental hook: The harness never cancels an executing tool call unless it has proven idempotent or its side effects can be rolled back. If you cannot undo the tool, you cannot steer. Everything else is queuing.

AI-generated study article from SophistAI. Sign up free to study it with an AI tutor.

Loading SophistAI