Agency comes from the model. Agent product = model + Harness

Before discussing code, let's make one thing clear.

Agency -- the ability to perceive, reason, and act -- comes from model training, not from orchestration by external code. But an agent product that can actually get work done needs both the model and the harness; neither can be missing. The model is the driver, and the harness is the vehicle. This repository teaches you how to build the vehicle.

Where Does Agency Come From?

At the core of an Agent is a neural network -- a Transformer, an RNN, a trained function -- which, through billions of gradient updates, has learned from action sequence data to perceive the environment, reason about goals, and take actions. Agency is never granted by the outer layer of code; it is learned by the model during training.

Humans are the best example. A biological neural network trained by millions of years of evolution perceives the world through senses, reasons through the brain, and acts through the body. When DeepMind, OpenAI, or Anthropic say "agent," they all mean the same core thing:a model that has learned to act through training, plus the infrastructure that enables it to work in a specific environment.

History has already written the ironclad proof:

  • 2013 -- DeepMind DQN plays Atari. A neural network, receiving only raw pixels and game scores, learned 7 Atari 2600 games -- surpassing all previous algorithms and beating human experts on 3 of them. By 2015, the same architecture was extended to 49 games, reaching the level of professional human testers, with the paper published in Nature. No game-specific rules. No decision trees. One model, learning from experience. That model is the agent.

  • 2019 -- OpenAI Five conquers Dota 2. Five neural networks, in 10 months, played against themselves for 45,000 years of Dota 2, defeated 2-0 at the live tournament in San Francisco OG -- the TI8 world champion. In the subsequent public arena, the AI achieved a 99.4% win rate across 42,729 matches. No scripted strategies. No meta-programmed team coordination logic. The model learned teamwork, tactics, and real-time adaptation entirely through self-play.

  • 2019 -- DeepMind AlphaStar dominated StarCraft II. AlphaStar in closed-door matches defeated professional players 10-1, and subsequently on European servers reachedGrandmaster Tier -- Top 0.15% of 90,000 players. A game with incomplete information, real-time decision-making, and a combinatorial action space far exceeding chess and Go. What is an Agent? It is a model. Trained. Not hand-coded.

  • 2019 -- Tencent Juewu dominated Honor of Kings.Tencent AI Lab's "JueWu" at the August 2, 2019 World Champion Cup semifinalsdefeated KPL professional players in 5v5. In 1v1 mode, professional playerswon only 1 of 15 matches, lasting at most less than 8 minutes. Training intensity: one day equals 440 human years. By 2021, JueWu comprehensively surpassed KPL professional player level in full-hero-pool BO5. No hand-written hero counter tables. No scripted lineup compositions. A model that learns the entire game from scratch through self-play.

  • 2024-2025 -- LLM Agents reshape software engineering. Claude, GPT, Gemini -- large language models trained on all human code and reasoning -- deployed as coding agents. They read codebases, write implementations, debug failures, collaborate as teams. The architecture is exactly the same as every previous agent: a trained model, placed into an environment, given tools for perception and action. The only difference is the scale of what they learn and the generality of the tasks they solve.

Every milestone points to the same fact:Agency -- the ability to perceive, reason, and act -- is trained, not programmed. But every agent also needs an environment to work: Atari emulators, Dota 2 clients, StarCraft II engines, IDEs and terminals. The model provides intelligence, the environment provides the action space. Together they form a complete agent.

What an Agent Is Not

The word "Agent" has been hijacked by an entire prompt-plumber industry.

Drag-and-drop workflow builders. No-code "AI Agent" platforms. Prompt chaining orchestration libraries. They all share the same hallucination: that stringing LLM API calls together with if-else branches, node graphs, and hardcoded routing logic counts as "building an Agent."

It doesn't. What they build is a Rube Goldberg machine -- an over-engineered, fragile procedural rule pipeline with an LLM wedged inside as a glorified text-completion node. That's not an Agent. That's a shell script with delusions of grandeur.

The prompt-plumber "Agent" is the wishful thinking of programmers who don't do models. They try to brute-force simulate intelligence by stacking procedural logic -- massive rule trees, node graphs, chained prompt waterfalls -- and then pray that enough glue code will make autonomous behavior emerge. It won't. You cannot engineer agency into existence. Agency is learned, not coded.

Those systems were dead on arrival: fragile, unscalable, and fundamentally incapable of generalization. They are the modern resurrection of GOFAI (Good Old-Fashioned AI, classical symbolic AI) -- symbolic rule systems abandoned by academia decades ago, now trotted out again with a coat of LLM paint. New packaging, same dead end.

Mindset shift: from "developing Agents" to developing Harnesses

When someone says "I'm developing an Agent," they can only mean one of two things:

1. Training models. Adjusting weights through reinforcement learning, fine-tuning, RLHF, or other gradient-based methods. Collecting task-process data -- the actual sequences of perception, reasoning, and action in real domains -- and using it to shape model behavior. This is what DeepMind, OpenAI, Tencent AI Lab, and Anthropic do. This is Agent development in the most literal sense.

2. Building Harnesses. Writing code that gives the model an operable environment. This is what most of us are doing, and it's the core of this repository.

A Harness is everything an agent needs to work in a specific domain:

Harness = Tools + Knowledge + Observation + Action Interfaces + Permissions

    Tools:          文件读写、Shell、网络、数据库、浏览器
    Knowledge:      产品文档、领域资料、API 规范、风格指南
    Observation:    git diff、错误日志、浏览器状态、传感器数据
    Action:         CLI 命令、API 调用、UI 交互
    Permissions:    沙箱隔离、审批流程、信任边界

The model makes decisions. The harness executes. The model reasons. The harness provides context. The model is the driver. The harness is the vehicle.

A coding agent's harness is its IDE, terminal, and file system. An agricultural agent's harness is the sensor array, irrigation controls, and weather data. A hotel agent's harness is the booking system, guest communication channels, and facility management APIs. The agent -- the intelligence, the decision-maker -- is always the model. The harness varies by domain. The agent generalizes across domains.

This repository teaches you to build vehicles. Vehicles for programming. But the design patterns generalize to any domain: estate management, farm operations, hotel operations, factory manufacturing, logistics scheduling, healthcare, education and training, scientific research. Whenever there is a task that needs to be perceived, reasoned about, and executed -- the agent needs a harness.

What a harness engineer actually does

If you are reading this repository, you are very likely a harness engineer -- and that is a powerful identity. Here is what you actually do:

  • Implement tools. Give the agent hands. File reading and writing, shell execution, API calls, browser control, database queries. Every tool is an action the agent can take in its environment. Design them to be atomic, composable, and clearly described.

  • Curate knowledge. Give the agent domain expertise. Product docs, architecture decision records, style guides, compliance requirements. Load on demand (s07), do not stuff in upfront. The agent should know what is available, then pull what it needs itself.

  • Manage context. Give the agent clean memory. Sub-agent isolation (s06) prevents noise leakage. Context compression (s08) prevents history from drowning it out. A task system (s12) lets goals persist beyond a single conversation.

  • Control permissions. Give the agent boundaries. Sandbox file access. Require approval for destructive operations. Enforce trust boundaries between the agent and external systems. This is where security engineering and harness engineering intersect.

  • Collect task process data.Every action sequence an Agent executes in your harness is a training signal. Perception-reasoning-action trajectories from real deployments are the raw material for fine-tuning the next generation of agent models. Your harness doesn't just serve the agent -- it can also help evolve the agent.

You are not writing intelligence. You are building the world that intelligence inhabits. The quality of this world -- how clearly the agent can see, how precisely it can act, how rich the available knowledge is -- directly determines how effectively intelligence can express itself.

Build the Harness well. The Agent will do the rest.

Why Claude Code -- a masterclass in harness engineering

Why does this repository specifically dissect Claude Code?

Because Claude Code is the most elegant and complete agent harness implementation we have ever seen. Not because of some clever trick, but because it is Not donething about it: it did not try to become the agent itself. It did not impose a rigid workflow. It did not use a carefully designed decision tree to make judgments on behalf of the model. It provided the model with tools, knowledge, context management, and permission boundaries -- and then got out of the way.

To strip Claude Code down to its essence:

Claude Code = 一个 agent loop
            + 工具 (bash, read, write, edit, glob, grep, browser...)
            + 按需 skill 加载
            + 上下文压缩
            + 子 agent 派生
            + 带依赖图的任务系统
            + 异步邮箱的团队协调
            + worktree 隔离的并行执行
            + 权限治理

That's it. That's the entire architecture. Every component is a harness mechanism -- part of the habitable world built for the agent. And the agent itself? It's Claude. A model. Trained by Anthropic across the full breadth of human reasoning and code. The harness didn't make Claude smart. Claude was already smart. The harness gave Claude hands, eyes, and a workspace.

This is the significance of Claude Code as a teaching specimen:it shows what happens when you trust the model and focus your engineering effort on the harness. The lessons in this repository (s01-s20) progressively disassemble and reassemble the harness mechanisms in Claude Code's architecture. After finishing, you'll understand not just how Claude Code works, but the general principles of harness engineering that apply to any domain and any agent.

The takeaway isn't "copy Claude Code." The takeaway is:the best agent products come from engineers who understand that their job is the harness, not intelligence.


Vision: Fill the universe with real agents

This isn't just about coding agents.

Every domain where humans do complex, multi-step work that requires judgment is a domain where agents can operate -- as long as there's the right harness. The patterns in this repository are universal:

庄园管理 agent  = 模型 + 物业传感器 + 维护工具 + 租户通信
农业 agent      = 模型 + 土壤/气象数据 + 灌溉控制 + 作物知识
酒店运营 agent  = 模型 + 预订系统 + 客户渠道 + 设施 API
医学研究 agent  = 模型 + 文献检索 + 实验仪器 + 协议文档
制造业 agent    = 模型 + 产线传感器 + 质量控制 + 物流系统
教育 agent      = 模型 + 课程知识 + 学生进度 + 评估工具

The loop never changes. Tools change. Knowledge changes. Permissions change. Agent = model (LLM) + generalized operating environment (Harness).

Every harness engineer who reads this repository is learning patterns that go far beyond software engineering. You're learning to build infrastructure for an intelligent, automated future. Every good harness deployed in a real domain is one more foothold where an agent can perceive, reason, and act.

First fill the studio. Then the farmland, the hospitals, the factories. Then the cities. Then the planet.

Bash is all you need. Real agents are all the universe needs.


20 progressive lessons, from a simple loop to a complete Harness. Each lesson adds one harness mechanism. Each mechanism has a motto.

s01   "One loop & Bash is all you need" — one tool + one loop = one Agent

s02   "Add one tool, add only one handler" — the loop doesn't need to change; just register the new tool into the dispatch map

s03   "Draw the boundaries first, then give freedom" — first decide whether an operation can be done, and whether to ask the user

s04   "Hook onto the loop, don't write into the loop" — leave slots before and after tools, so you can extend without changing the main loop

s05   "An agent without a plan just goes wherever it ends up" — list the steps before acting, and the completion rate doubles

s06   "Break big tasks into small ones, each small task with clean context" — sub-agents do the work themselves and only bring back the results

s07   "Load only when needed, don't stuff everything into the prompt" — skills list a directory first, then expand when needed

s08   "Context always fills up, you need a way to free up space" — four-layer compression strategy, run the cheap ones first and the expensive ones later

s09   "Remember what should be remembered, forget what should be forgotten" — three subsystems: filtering, extraction, organization

s10   "The prompt is assembled, not hardcoded" — segmented + concatenated on demand

s11   "Errors aren't the end, they're the starting point for retrying" — on error, retry, free up space, and try another way

s12   "Break big goals into small tasks, sort them, persist them" — task graph persisted to files, the foundation for multi-agent collaboration

s13   "Send slow operations to the background, the agent keeps thinking" — a background thread runs commands and injects a notification when complete

s14   "Trigger on a schedule, no human push needed" — automatically trigger tasks by time

s15   "If one can't handle it, team up" — persistent teammates + asynchronous mailbox

s16   "Teammates need conventions" — communicate using a fixed request-reply format

s17   "Teammates look at the board themselves and claim work" — no need for a leader to assign tasks one by one, self-organizing

s18   "Each works in its own directory, without interfering with others" — tasks manage goals, worktrees manage directories, bound by ID

s19   "Not capable enough? Plug in MCP" — connect external tools into the same tool pool

s20   "Many mechanisms, one loop" — all the preceding mechanisms return to one complete harness


Core pattern

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})

        if response.stop_reason != "tool_use":
            return

        results = []
        for block in response.content:
            if block.type == "tool_use":
                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})

Each lesson layers one harness mechanism on top of this loop -- the loop itself never changes. The loop belongs to the agent. The mechanisms belong to the harness.

Version notes

This repository now keeps two tutorial tracks at the same time:

  • **New main line: root directory **s01-s20 Under the root directory, s01_* to s20_*is the new major version and the currently recommended reading path. Each chapter includes a complete narrative README, English/Japanese translations, runnable code.py, as well as necessary diagrams.

  • Legacy transition:docs/、agents/** and current **web/ These still retain the old 12-chapter system, temporarily used for existing readers, old links, and Web platform transition.

New readers should start from the root directory s01_agent_loop/ and read through to s20_comprehensive/. If you enter from an old link or the current Web platform, you are most likely seeing the old 12-chapter version. The old chapter numbers and new version are not completely consistent; do not mix chapter numbers.

Mapping from old version to new version

Old 12-chapter version

New 20-chapter version

Topic

Old s01

New s01

Agent Loop

Old s02

New s02

Tool Use

Old s03

New s05

TodoWrite

Old s04

New s06

Subagent

Old s05

New s07

Skill Loading

Old s06

New s08

Context Compact

Old s07

New s12

Task System

Old s08

New s13

Background Tasks

Old s09

New s15

Agent Teams

Old s10

New s16

Team Protocols

Old s11

New s17

Autonomous Agents

Old s12

New s18

Worktree Isolation

New additions in the new version

s03、s04、s09、s10、s11、s14、s19、s20

Permission、Hooks、Memory、System Prompt、Error Recovery、Cron、MCP、Comprehensive Agent

Scope note (important)

This repository is a 0->1 harness engineering learning project -- building a working environment around the agent model. To keep the learning path clear, the repository intentionally simplifies or omits some production mechanisms:

  • A full event / hook bus (e.g., PreToolUse, SessionStart/End, ConfigChange). s12 only provides a minimal append-only lifecycle event stream for teaching purposes.

  • Rule-based permission governance and trust processes

  • Session lifecycle control (resume/fork) and more complete worktree lifecycle control

  • Complete MCP runtime details (transport/OAuth/resource subscription/polling)

The team JSONL mailbox protocol in the repository is a teaching implementation, not a claim about any particular production internal implementation.

Quick start

New 20-chapter main line

git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
pip install -r requirements.txt
cp .env.example .env   # 编辑 .env 填入你的 ANTHROPIC_API_KEY

python s01_agent_loop/code.py        # 起点 — 一个循环 + bash
python s08_context_compact/code.py    # 上下文压缩(复杂章)
python s20_comprehensive/code.py      # 终点章: 全部机制归到一个循环

Old version 12-chapter transition line

python agents/s01_agent_loop.py
python agents/s12_worktree_task_isolation.py
python agents/s_full.py

Web platform

The current Web platform still reads docs/old 12-chapter content in . For the new 20-chapter version, please read the root directory directly.s01-s20。

cd web && npm install && npm run dev   # http://localhost:3000

Learning path

Main line: able to take action → able to handle complex tasks → able to remember and recover → able to run long term → able to collaborate → able to extend and merge

flowchart TD
    %% 统一定义卡片样式:加入 text-align:left 保证列表不会居中乱飘
    classDef stage1 fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#0D47A1,rx:12,ry:12,text-align:left
    classDef stage2 fill:#E8F5E9,stroke:#388E3C,stroke-width:2px,color:#1B5E20,rx:12,ry:12,text-align:left
    classDef stage3 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#E65100,rx:12,ry:12,text-align:left
    classDef stage4 fill:#FCE4EC,stroke:#C2185b,stroke-width:2px,color:#880E4F,rx:12,ry:12,text-align:left
    classDef stage5 fill:#F3E5F5,stroke:#7B1FA2,stroke-width:2px,color:#4A148C,rx:12,ry:12,text-align:left
    classDef stage6 fill:#E0F7FA,stroke:#0097A7,stroke-width:2px,color:#006064,rx:12,ry:12,text-align:left
    
    %% 背景框样式
    classDef groupBox fill:#F8F9FA,stroke:#CED4DA,stroke-width:2px,stroke-dasharray: 5 5,rx:15,ry:15,color:#495057
    
    %% 第一层:1-3阶段
    subgraph Phase1 ["🌱 阶段 1-3:基础能力构建(从简单到复杂)"]
        direction LR
        S1["<b>第一阶段:让 Agent 能动手</b><br/>━━━━━━━━━━━━━<br/><b>s01 Agent Loop</b><br/>└─ 一个循环 + bash<br/><br/><b>s02 Tool Use</b><br/>└─ 单个到多个工具<br/><br/><b>s03 Permission</b><br/>└─ 判断能不能做<br/><br/><b>s04 Hooks</b><br/>└─ 工具前后留扩展插口"]:::stage1

        S2["<b>第二阶段:做复杂任务</b><br/>━━━━━━━━━━━━━<br/><b>s05 TodoWrite</b><br/>└─ 先列计划,再执行<br/><br/><b>s06 Subagent</b><br/>└─ 子节点干活带回结果<br/><br/><b>s08 Context Compact</b><br/>└─ 长下文腾空间"]:::stage2

        S3["<b>第三阶段:记住和恢复</b><br/>━━━━━━━━━━━━━<br/><b>s09 Memory</b><br/>└─ 该记记,该忘忘<br/><br/><b>s10 System Prompt</b><br/>└─ 运行时组装<br/><br/><b>s11 Error Recovery</b><br/>└─ 重试换路子"]:::stage3

        S1 ==> S2 ==> S3
    end

    %% 第二层:4-6阶段
    subgraph Phase2 ["🚀 阶段 4-6:高阶能力进化(长期、协作与融合)"]
        direction LR
        S4["<b>第四阶段:让任务长期运行</b><br/>━━━━━━━━━━━━━<br/><b>s12 Task System</b><br/>└─ 任务落盘记依赖<br/><br/><b>s13 Background Tasks</b><br/>└─ 慢操作丢后台<br/><br/><b>s14 Cron Scheduler</b><br/>└─ 按时自动触发"]:::stage4

        S5["<b>第五阶段:让多个 Agent 协作</b><br/>━━━━━━━━━━━━━<br/><b>s15 Agent Teams</b><br/>└─ 队友 + 邮箱通信<br/><br/><b>s16 Team Protocols</b><br/>└─ 固定收发格式<br/><br/><b>s17 Autonomous Agents</b><br/>└─ 自己看板认领活<br/><br/><b>s18 Worktree Isolation</b><br/>└─ 隔离目录"]:::stage5

        S6["<b>第六阶段:接外部能力合体</b><br/>━━━━━━━━━━━━━<br/><b>s07 Skill Loading</b><br/>└─ 技能按需展开<br/><br/><b>s19 MCP Plugin</b><br/>└─ 外部接进工具池<br/><br/><b>s20 Comprehensive Agent</b><br/>└─ 全机制回单循环"]:::stage6

        S4 ==> S5 ==> S6
    end

    %% 将两个模块连接起来,形成 Z 字形阅读流
    Phase1 ===> Phase2

    %% 应用背景样式
    class Phase1,Phase2 groupBox

All chapters

Chapter

Topic

Key concepts

s01

Agent Loop

messages / while True / stop_reason

s02

Tool Use

TOOL_HANDLERS / dispatch map / concurrency

s03

Permission

PermissionRule / approval pipeline

s04

Hooks

PreToolUse / PostToolUse / extension point

s05

TodoWrite

TodoItem / plan first, execute later

s06

Subagent

fresh messages[] / context isolation

s07

Skill Loading

SkillManifest / on-demand injection

s08

Context Compact

snip / micro / budget / auto four-layer compression

s09

Memory

selection / extraction / consolidation

s10

System Prompt

runtime assembly / segmented concatenation

s11

Error Recovery

token upgrade / fallback model / retry strategy

s12

Task System

TaskRecord / blockedBy / disk persistence

s13

Background Tasks

thread execution / notification queue

s14

Cron Scheduler

persistence scheduling / session-level triggering

s15

Agent Teams

MessageBus / inbox / permission bubbling

s16

Team Protocols

shutdown handshake / plan approval

s17

Autonomous Agents

Idle loop / automatic claiming

s18

Worktree Isolation

WorktreeRecord / task-directory binding

s19

MCP Plugin

Multi-transport / channel routing / tool pool assembly

s20

Comprehensive Agent

All mechanisms converge into one loop

Project structure

learn-claude-code/
  s01_agent_loop/          # 每章一个文件夹
    README.md              #   中文源文档(完整叙事)
    README.en.md           #   英文译本
    README.ja.md           #   日文译本
    code.py                #   独立可运行代码
    images/                #   SVG 流程图
  s02_tool_use/
  ...
  s19_mcp_plugin/
  s20_comprehensive/       # 终点章
  agents/                  # 旧 12 章可运行副本 + s_full.py
  skills/                  # s07 使用的 skill 文件
  docs/                    # 旧 12 章文档,过渡期保留
  web/                     # 当前仍基于 docs/ 旧版内容生成
  tests/

After learning -- from understanding to implementation

Having gone through all 20 lessons, you now understand how harness engineering works from the inside out. There are two ways to turn that knowledge into a product:

Kode Agent CLI -- open-source Coding Agent CLI

npm i -g @shareai-lab/kode

Supports Skill & LSP, works on Windows, and can connect to open models such as GLM / MiniMax / DeepSeek. Ready to use once installed.

GitHub: shareAI-lab/Kode-cli

Kode Agent SDK -- embed Agent capabilities into your application

The official Claude Code Agent SDK relies on full CLI process communication underneath -- each concurrent user = one terminal process. Kode SDK is a standalone library with no per-user process overhead, and can be embedded in any runtime such as backends, browser extensions, and embedded devices.

GitHub: shareAI-lab/Kode-agent-sdk


Sister tutorial: fromPassive temporary sessiontoProactive always-on assistant

The harness taught in this repository belongs to the use-and-discard type -- open a terminal, give the agent a task, close it when done; the next reopen is a brand-new session. Claude Code works exactly this way.

But OpenClaw proved another possibility: on top of the same agent core, adding two harness mechanisms can turn the agent from “moving only when kicked” into “waking itself up every 30 seconds to look for work”:

  • Heartbeat -- every 30 seconds the harness sends the agent a message telling it to check whether there is anything to do. If there is nothing, it keeps sleeping; if there is something, it acts immediately.

  • Cron -- the agent can schedule things for itself to do in the future, which execute automatically when the time comes.

Add IM multi-channel routing (WhatsApp/Telegram/Slack/Discord and 13+ other platforms), context memory that doesn't get cleared, and the Soul personality system, and the agent goes from a temporary tool to an always-on personal AI assistant.

claw0 is our sister teaching repository, breaking down these harness mechanisms from scratch:

claw agent = agent core + heartbeat + cron + IM chat + memory + soul
learn-claude-code                   claw0
(agent harness 内核:                 (主动式常驻 harness:
 循环、工具、规划、                    心跳、定时任务、IM 通道、
 团队、worktree 隔离)                  记忆、Soul 人格)

License

MIT


Agency comes from the model. Harness makes agency land. Build a good Harness, and the model will do the rest.

Bash is all you need. Real agents are all the universe needs.

THE AGENT PATTERN
=================

User --> messages[] --> LLM --> response
                  |
        stop_reason == "tool_use"?
       /                          \
     yes                           no
      |                             |
execute tools                    return text
append results
loop back -----------------> messages[]

这是最小循环。每个 AI Agent 都需要这个循环。
模型决定何时调用工具、何时停止。
代码只是执行模型的要求。
本仓库教你构建围绕这个循环的一切 --
让 agent 在特定领域高效工作的 harness。