Design a Single-Loop Agent
Build the core agent loop the leading coding agents use: one model, one loop, tools in, results folded back into context.
The route
5 steps to Done
- 01
Define the loop contract
Write down exactly what one turn of the loop does before coding it.
Preview prompt + verify gate ▾ Hide ▴
Design the core loop for a single-agent system and write it as a contract before implementation. Specify: (1) INPUT: system prompt + message history + tool registry. (2) TURN: send to model; the model returns either final text or one or more tool calls. (3) EXECUTE: run each tool call in order, capture result or error. (4) FOLD: append tool results as tool-role messages, preserving call order and IDs. (5) TERMINATE: stop on explicit finish, max N turns, or K consecutive tool failures. Produce this as a short design doc with a state diagram and the exact message shapes you will use.
- ✓ Turn sequence is explicit
- ✓ Termination has 3 concrete conditions
- ✓ Message shapes are documented
- 02
Build the tool registry
Tools are the agent's hands - define them with strict schemas.
Preview prompt + verify gate ▾ Hide ▴
Implement a tool registry for the agent. Requirements: each tool has a name, a one-paragraph description written for the model (what it does, when to use it, when NOT to use it), a JSON schema for parameters, and a handler function. Include three starter tools: read_file(path), write_file(path, content), run_command(command). Validate every incoming tool call against its schema before executing; on validation failure, return a structured error the model can read and correct. Do not execute anything that fails validation.
- ✓ Each tool has schema + description + handler
- ✓ Invalid calls return structured errors
- ✓ Descriptions say when NOT to use the tool
- 03
Implement the loop with result folding
The loop's job is bookkeeping: order, roles, and IDs must be exact.
Preview prompt + verify gate ▾ Hide ▴
Implement the main loop. Requirements: maintain the full message history; on each turn send system prompt + history to the model; if the response contains tool calls, execute them sequentially and append each result as a tool message linked to its call ID; if the response is plain text, treat it as the final answer and stop; enforce max 20 turns and stop after 3 consecutive turns where every tool call failed. Log every turn to a JSONL transcript file with timestamp, role, and payload. Then run the demo task: 'read config.json, change the port to 8080, verify by reading it back'.
- ✓ Demo task completes end to end
- ✓ Tool results keep call order and IDs
- ✓ Transcript JSONL captures every turn
- 04
Harden termination and error paths
An agent that cannot stop is worse than one that cannot start.
Preview prompt + verify gate ▾ Hide ▴
Harden the loop against the classic failure modes. Requirements: (1) max-turn stop returns a partial-result summary, not a crash; (2) repeated identical tool calls (same tool, same args, 3x) trigger an intervention message telling the model it is looping; (3) any unhandled exception in a tool returns a structured error message to the model with the traceback summary; (4) a cancellation flag lets the caller stop the loop between turns; (5) the finish signal is explicit (a finish tool or a clear final-text rule), not inferred. Write a test that forces each termination path and verify the transcript shows the correct behavior.
- ✓ Loop detection interrupts repeated identical calls
- ✓ Max turns returns a summary
- ✓ Cancellation works between turns
- 05
Prove it with a transcript review
Judge the loop the way harness engineers do: by reading transcripts.
Preview prompt + verify gate ▾ Hide ▴
Run the agent on three tasks of increasing difficulty (single edit, multi-file change, task that must fail due to a missing file) and review the transcripts. For each: verify tool order matches the story the model tells, verify no result was dropped, verify the failure task ends with an honest report instead of a fabricated success. Produce a short review doc listing any turn where the model's claim and the tool evidence disagree, and fix the loop (not the prompt) where bookkeeping caused it.
- ✓ Three transcripts reviewed line by line
- ✓ Failure task ends with an honest report
- ✓ Any claim/evidence mismatch is explained and fixed
Research-backed
Sources behind this flow
Tier 1 · claude-code-internals
claudecode-source (annotated bundle)
Packages a deep source-level analysis of a Claude Code snapshot (~1,900 files) with HTML reports, architecture visuals, and walkthrough guides, plus an independently written source-analysis report in Chinese and English. One of the most complete single bundles for studying the tool definitions, main agent loop, and edit-validation path.
Tier 1 · claude-code-internals
claude-code-source-map
A full deobfuscated source map of the Claude Code npm bundle reconstructed from the published package's source maps - the largest single research artifact in this corpus (~160MB of mapped source). Its directory structure serves as the canonical map of Claude Code's internal modules.
Tier 1 · claude-code-internals
claude-code-sourcemap (leeyeel)
An independent, earlier source-map extraction of Claude Code (v0.2.8 research preview) capturing the agent's terminal-native design: codebase understanding, file edits, git workflows through natural language. Useful as a second witness when the SatoMini map is ambiguous, and for seeing how early the core loop stabilized.
Tier 1 · claude-code-internals
Claude Code Orange Book
A book-length analysis ('Orange Book') dissecting Anthropic's AI engineering decisions from the 510,000 lines / 1,902 TypeScript files that shipped inside an npm package. Chapters cover the agent loop, context compaction, the hook system, and sub-agents - the concepts, not just the code.
Tier 2 · harness-engineering
agentic-harness-patterns-skill
A distilled 'skill' file of agentic harness patterns - short, dense, and directly reusable as workflow steps. The compressed counterpart to the harness-engineering book.