How Claude Code Works: Build the Agent Loop in 17 Lessons

2026-04-26
Brian

· Updated
Subscribe
JOIN OUR NEWSLETTER
Be the first to know. Get fresh AI/Tech updates instantly, no spam, unsubscribe anytime

If you want to know how Claude Code works under the hood, the clearest map right now is learn-claude-code, an MIT-licensed course from shareAI-lab. It rebuilds a Claude Code style coding agent in plain Python, one mechanism at a time, starting from a loop of about 150 lines. I cloned it, ran its test suite, and read the code for the first three lessons line by line.

The short version: an agent like Claude Code is a model in a loop. The model asks for a tool, your code runs the tool, the result goes back into the conversation, and the loop repeats until the model stops asking. Everything else you see in a real coding agent (permissions, hooks, subagents, memory, compaction, teams) is harness built around that loop.

Checked against commit ce8f9f1 (Sep 28, 2026) on Oct 23, 2026, Python 3.13 on Debian.

The loop at the centre of how Claude Code works

Lesson s01 is the whole idea in one file. s01_agent_loop/code.py is 151 lines, and the core function is a while True loop that calls the Messages API with a list of tools, appends the reply, and checks whether the reply contains any tool_use blocks. If it does not, the turn is over. If it does, each tool runs and its output goes back as a tool_result message.

def agent_loop(messages):
    while True:
        response = client.messages.create(
            model=MODEL, system=SYSTEM,
            messages=messages, tools=TOOLS,
        )
        messages.append({"role": "assistant", "content": response.content})
        tool_calls = [b for b in response.content if b.type == "tool_use"]
        if not tool_calls:
            return
        results = []
        for block in tool_calls:
            output = TOOL_HANDLERS[block.name](**block.input)
            results.append({"type": "tool_result",
                            "tool_use_id": block.id, "content": output})
        messages.append({"role": "user", "content": results})

Two details in the real file are worth noticing. The bash tool has a 120-second timeout, and any output longer than 50,000 characters is cut before it goes back to the model. Both limits exist for the same reason: every byte of tool output becomes input tokens on the next call. That is the same pressure that makes a real session grow expensive, which we measured separately in why Claude Code costs more the moment you start measuring it.

How Claude Code works: mind map of the learn-claude-code lessons, from the agent loop and tool use to subagents, skills and context compaction

What the 17 lessons add, in order

The repo now has two tracks. The current one lives in root folders s01 to s17, each with a README, a runnable code.py and diagrams. An older 12-lesson version stays in agents/ and docs/ so old links keep working. If you read an earlier write-up that says “12 sessions”, that was the old track.

I counted the lines in each lesson’s code.py. The growth tells you where the real complexity of a coding agent sits:

LessonMechanismLines in code.py
s01Agent loop151
s02Tool dispatch map206
s03Permission gates267
s04Hooks (PreToolUse / PostToolUse)280
s05Todo list, plan then execute368
s06Subagent with fresh context383
s07Skill loading on demand399
s08Context compaction601
s09Memory784
s10Task records on disk600
s11Background tasks542
s12Cron scheduler790
s13Agent teams and worktrees1,887
s14MCP tool discovery549
s15Integrated harness3,326
s16Workflow runtime888
s17Goal loop903

The loop itself never gets much bigger. What grows is everything that decides what goes into the loop (skills, memory, compaction) and everything that coordinates several loops (subagents, teams, scheduling). Lesson s13 alone is longer than s01 to s06 combined, because coordinating several agents means locks, task claims and separate git worktrees.

Setting up the course on your machine

The setup is three commands. You need an API key: the .env.example file asks for ANTHROPIC_API_KEY and MODEL_ID (it defaults to claude-sonnet-4-6), and it lists Anthropic-compatible endpoints from MiniMax, GLM, Kimi and DeepSeek if you would rather use one of those.

git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env        # add ANTHROPIC_API_KEY and MODEL_ID
python3 s01_agent_loop/code.py

On Debian and Ubuntu, use python3. The README writes python, and on a stock Debian box that command does not exist. The same thing bit the test suite, below.

Running the test suite

The repo ships a tests/ folder. With pytest in a fresh virtual environment, the full run took 11.57 seconds:

$ python3 -m pytest -q
...
3 failed, 479 passed, 100 subtests passed in 11.57s

One of the three failures was my environment, not the code: a test shells out to python and got /bin/sh: 1: python: not found (exit code 127). The other two were in the s16 workflow-runtime web scenarios, where expected and actual output did not match. None touched the s01 to s08 lessons most readers start with. If you want a clean run on Debian, install python-is-python3 first.

The safety check in lesson one is a substring match

This is the part I found most useful, because it shows why real agents need more than a blocklist. The s01 bash tool refuses commands containing any of five strings: rm -rf /, sudo, shutdown, reboot and > /dev/. It is a plain in check. I fed it a handful of commands using the exact same list:

'rm -rf /'                   BLOCKED
'rm  -rf /'                  allowed
'rm -r -f /'                 allowed
'sudo ls'                    BLOCKED
'echo hi > /dev/null'        BLOCKED
'git log --grep=reboot'      BLOCKED
'find / -delete'             allowed

An extra space or split flags get the dangerous command through, while harmless commands like redirecting to /dev/null or searching git history for the word reboot are blocked. That is not a bug in the course. s01 is meant to be minimal, and the next lessons exist to fix exactly this.

Lesson s03 adds three gates: a longer deny list (adding mkfs, dd if= and > /dev/sda), a regex rule that spots rm or del at the start of any command in a chain, and a prompt asking you to approve anything the rules flag. Run against the same inputs, the double-space and split-flag versions now stop and ask. But find / -delete and a Python one-liner calling shutil.rmtree still run without a prompt.

That is the honest lesson about agent safety: pattern matching on shell strings will always miss something. Real tools add sandboxes, workspace boundaries and checkpoints on top. If that is the problem you are trying to solve, our guide on how to stop Claude Code from deleting your files covers the settings that actually hold.

How the course maps to features you use in Claude Code

Once you have read a lesson, the matching Claude Code behaviour stops being magic. A few pairs I found helpful:

  • Todo list (s05). When Claude Code writes a checklist before editing, that is a plan stored as state the model can update, so it does not drift halfway through a long task.
  • Subagents (s06). A subagent is a second loop with a fresh, empty message list. It does the noisy exploring and returns only a summary, which keeps the parent conversation small.
  • Skills (s07). Only a short catalogue of skill names goes into the prompt. The full instructions load when the model asks for one, which is why a big skill folder does not cost much until it is used.
  • Compaction (s08). When the history gets too long, old tool results are trimmed or summarised. The lesson shows several layers, from cutting oversized tool output to summarising the whole history.
  • Project instructions. Files such as CLAUDE.md are just text added to the system prompt each turn. Our breakdown of Karpathy’s CLAUDE.md rules shows what a good one looks like, in about 530 tokens.

The course does not reproduce Claude Code’s actual source. It is a teaching rebuild of the same patterns. The README puts it plainly: this is not “copy the source code”, it is “grasp the key designs and build it yourself.” Treat it as a way to understand the design, not as a drop-in replacement.

Who should work through learn-claude-code

If you are…Start withWhy
Curious how coding agents works01, s02, s06Loop, tools and subagents explain most of what you see day to day
Building your own agents01 to s08, then s14Covers safety, planning, context limits and MCP tools
Running several agents at onces10, s11, s13Task records, background work and worktrees
Choosing between existing agentss15The integrated harness shows what a full product has to juggle

If you already use more than one agent, the patterns here also explain why they feel different on the same model. We compared two of them side by side in Claude Code and Codex together.

Every lesson makes real API calls once you run it, and later lessons such as teams and the goal loop can make many calls per task. Set a spending limit on your key before you start, and read each lesson’s README before its code.

Common questions about how Claude Code works

Is learn-claude-code the real Claude Code source?

No. It is an independent teaching project that rebuilds the same patterns in small Python files. It explains the ideas well, but the real product has far more engineering around each mechanism.

Do I need an Anthropic API key to follow the course?

You need a key for an Anthropic-compatible API. The .env.example file lists Anthropic plus compatible endpoints from MiniMax, GLM, Kimi and DeepSeek. Reading the code and running the test suite need no key.

How many lessons are there now?

The current track has 17 lessons, s01 to s17. The older 12-lesson track is still in the agents/ folder for people following earlier links.

Is the bash tool in lesson one safe to point at my real machine?

Not on its own. Its blocklist is a substring check that an extra space defeats. Run the lessons inside a throwaway folder or a container, and read s03 before you let it near anything you care about.

JOIN OUR NEWSLETTER
Be the first to know. Get fresh AI/Tech updates instantly, no spam, unsubscribe anytime

15 comments

Leave a comment