kwj.ai · acquisition inquiries from >$999view prospectus →
The Domesday Book ofKWJ · AI

Engineering · 14 min

Building an agent loop you can read in a single sitting

Every operator eventually writes their own harness. Here is the shape of a maintainable one.

By C.W. Jameson · Published 19 May 2026 · Last reviewed 19 May 2026

The frameworks come and go. The operators who keep shipping write their own harness and read it. This guide describes the shape of one — not the only shape, but a defensible one.

Three loops

The outer loop is task-level: take a goal, return a result. The middle loop is turn-level: prompt the model, parse the response, dispatch tool calls. The inner loop is tool-level: execute, capture, format the result back to the model.

Most frameworks conflate these and the result is unreadable. Keep them separate and the code stays under three hundred lines for a serious harness.

Termination conditions

Every loop needs all four termination guards: self-declared done, turn-count cap, wall-clock budget, error threshold. Skip any and the loop will eventually run forever.

State management

Persist the message history. Persist the tool-call history separately. When context bloats, compact — not by truncating, but by summarising the early turns and replacing them.

Observability

Log every prompt, every response, every tool call, every error. Structured. Searchable. The cheapest debugging is the kind you can grep for.

Frequently asked

Frameworks worth using?

Anthropic's SDK, OpenAI's Agents SDK, and the LangChain primitives are all readable enough. Skip the magic.

Partner offer

Anthropic's Claude family is the model lineage most operators end up on for serious agent work. The free tier remains useful.

Try Claude →

Affiliate link — see disclosure.

From the Almanac shop

The Operator's Compendium

Every agent harness, every routing pattern, every cost trick. 90-page PDF.

$29Coming soon

All guides