Foundationscritical

The Agent Loop

An agent loop is: model receives messages → model emits text + tool calls → harness executes tools → tool results appended to messages → model runs again. Repeats until the model emits a final answer with no tool calls (or hits a stop condition).

Memory anchor

An agent loop is a kitchen line cook with a ticket window — read ticket, grab ingredients (tools), cook, plate, send back. They don't remember last shift. The system prompt is the menu; CLAUDE.md is the recipe binder.

Expected depth

The harness owns the loop, not the model. Each turn the model sees the full conversation (system prompt, user message, all prior tool calls and results). The model decides whether to call more tools or stop. The harness decides safety: which tools are allowed, what gets auto-approved, when to ask the user. Termination: explicit stop turn (no tool calls), max turns reached, user interrupt, or hook-blocked stop.

Deep — senior internals

Agent loops are stateful only in the messages array — there's no hidden 'agent state.' This is why context engineering matters: every reset means re-reading files, re-running greps. Anthropic's harness uses a Stop hook lifecycle: PreToolUse (approve/deny), PostToolUse (observe), Stop (block termination if work isn't done), UserPromptSubmit (inject context). The cost model is per-turn: each tool result extends the next request's input tokens. Long loops with verbose tool output are expensive and slow — prefer Read with offset/limit over cat-the-whole-file, prefer Grep over reading and scanning.

🎤Interview-ready answer

An agent loop is a wrapper around an LLM that lets it take actions through tools and observe results. Each turn, the harness runs the model, executes any tools it requested, and feeds the results back. The loop terminates when the model emits no tool calls. The key insight is that the harness — not the model — owns safety and policy: which tools exist, which are auto-approved, when to interrupt. Designing agents is mostly designing this harness.

Common trap

Thinking the agent 'remembers' across runs. There is no hidden state — only the message history. If you start a new session, the agent has zero knowledge of prior work unless it's in CLAUDE.md, memory files, or git history.

Related concepts