从 Claude Code 学习 Agent Harness 的核心特性

从 Claude Code 学习 Agent Harness 的核心特性

Agent Harness 是什么?它是让 AI 从"聊天机器人"进化为"编程助手"的关键架构。Anthropic 的 Claude Code 是业界最成熟的实现之一,但它的闭源性质让学习者难以深入理解。

幸运的是,开源社区出现了两个优秀的学习资源:

通过这两个项目,我们可以完整地理解 Agent Harness 的核心设计理念。

什么是 Agent Harness?

简单来说,Agent Harness 是一个让 AI Agent 能够可靠执行复杂任务的框架。它不是简单地调用 LLM API,而是提供了一整套基础设施:

  • 工具系统 (Tool Use) — 让 AI 能够读写文件、执行命令、搜索网络
  • Agent 循环 (Agent Loop) — 自动处理工具调用的循环
  • 任务规划 (TodoWrite) — 将大目标拆解为小任务
  • 子 Agent (Subagents) — 派遣专门的助手处理子任务
  • 记忆系统 (Memory) — 持久化重要的上下文信息
  • 技能系统 (Skills) — 按需加载领域知识

这些组件协同工作,让 AI Agent 从"能对话"进化为"能干活"。

Learn-Claude-Code:12 节系统化课程

Learn-Claude-Code 是一个循序渐进的学习项目,它将 Agent Harness 拆解为 12 个核心主题:

Session Topic Motto
s01 The Agent Loop One loop & Bash is all you need
s02 Tool Use Adding a tool means adding one handler
s03 TodoWrite An agent without a plan drifts
s04 Subagents Break big tasks down; each subtask gets a clean context
s05 Skills Load knowledge when you need it, not upfront
s06 Context Compact Context will fill up; you need a way to make room
s07 Tasks Break big goals into small tasks, order them, persist to disk
s08 Background Tasks Run slow operations in the background; the agent keeps thinking
s09 Agent Teams When the task is too big for one, delegate to teammates
s10 Team Protocols Teammates need shared communication rules
s11 Autonomous Agents Teammates scan the board and claim tasks themselves
s12 Worktree + Task Isolation Each works in its own directory, no interference

核心设计哲学

每节课都有一个简洁的"座右铭"(Motto),概括了该主题的核心思想:

  1. The Agent Loop — 一个循环就够了
    - 接收用户输入
    - 调用 LLM
    - 执行工具调用
    - 将结果反馈给 LLM
    - 重复直到任务完成

  2. Tool Use — 添加工具就是添加一个处理器
    - 工具只是函数:输入参数 → 返回结果
    - LLM 通过 JSON Schema 理解工具接口
    - 工具调用会被自动解析和执行

  3. TodoWrite — 没有计划的 Agent 会迷失
    - 显式跟踪任务列表
    - 进度可视化
    - 防止 Agent 遗忘目标

  4. Subagents — 每个子任务获得干净的上下文
    - 主 Agent 负责协调
    - 子 Agent 专注于执行
    - 独立的对话历史避免干扰

  5. Skills — 按需加载知识,而不是预加载
    - 类似函数库:需要时才加载
    - 保持主上下文精简
    - 支持用户自定义技能

学习路径的价值

Learn-Claude-Code 的价值在于它的渐进式设计

  • 从最简单的 Agent Loop 开始(s01)
  • 逐步添加工具能力(s02)
  • 引入任务管理(s03)
  • 处理复杂任务(s04-s08)
  • 构建多 Agent 协作(s09-s12)

这种设计让学习者能够:
1. 理解每个组件的独立价值
2. 看清楚组件之间的协作方式
3. 最终掌握完整的系统架构

Nano-Claude-Code:5000 行的完整实现

如果 Learn-Claude-Code 是"教科书",那么 Nano-Claude-Code 就是"参考实现"。

这是一个用 Python 重写的 Claude Code,最初只有约 900 行代码,经过 3 个版本迭代后约 5000 行。它不仅复刻了 Claude Code 的核心功能,还增加了多提供商支持

核心特性对比

Feature Details
Multi-provider Anthropic · OpenAI · Gemini · Kimi · Qwen · Zhipu · DeepSeek · Ollama · LM Studio · Custom endpoint
Interactive REPL readline history, Tab-complete slash commands
Agent loop Streaming API + automatic tool-use loop
18 built-in tools Read · Write · Edit · Bash · Glob · Grep · WebFetch · WebSearch · MemorySave · MemoryDelete · MemorySearch · MemoryList · Agent · SendMessage · CheckAgentResult · ListAgentTasks · ListAgentTypes · Skill · SkillList
Diff view Git-style red/green diff display for Edit and Write
Context compression Auto-compact long conversations to stay within model limits
Persistent memory Dual-scope memory (user + project) with 4 types, AI search, staleness warnings
Multi-agent Spawn typed sub-agents (coder/reviewer/researcher/…), git worktree isolation, background mode
Skills Built-in /commit · /review + custom markdown skills with argument substitution and fork/inline execution
Plugin tools Register custom tools via tool_registry.py
Permission system auto / accept-all / manual modes
17 slash commands /model · /config · /save · /cost · /memory · /skills · /agents · …
Context injection Auto-loads CLAUDE.md, git status, cwd, persistent memory
Session persistence Save / load conversations to ~/.nano_claude/sessions/
Extended Thinking Toggle on/off (Claude models only)
Cost tracking Token usage + estimated USD cost
Non-interactive mode --print flag for scripting / CI

架构设计亮点

Nano-Claude-Code 的实现有几个值得学习的设计:

1. 生成器风格的 Agent 循环

def run(config, messages, tools):
    while True:
        # 调用 LLM API
        response = stream_completion(messages, tools)

        # 流式输出
        for chunk in response:
            if chunk.type == "text":
                yield TextChunk(chunk.content)
            elif chunk.type == "tool_use":
                tool_calls.append(chunk.tool_call)

        # 执行工具调用
        if tool_calls:
            for call in tool_calls:
                result = execute_tool(call)
                messages.append({"role": "tool", "result": result})

            # 继续循环
            continue
        else:
            # 没有工具调用,结束
            break

为什么这样设计?
- 生成器 (yield) 允许流式输出
- 单一循环处理所有逻辑
- 工具执行后自动继续,无需手动管理状态

2. 提供商无关的消息格式

内部使用"中性"消息格式,在调用 API 前转换为提供商特定格式:

def stream(messages, tools, model):
    if model.startswith("claude-"):
        return stream_anthropic(messages, tools, model)
    elif model.startswith("gpt-"):
        return stream_openai(messages, tools, model)
    # ... 其他提供商

好处?
- 核心逻辑与提供商解耦
- 添加新提供商只需实现一个适配器
- 统一的测试接口

3. 插件式工具注册

ToolDef(
    name="Read",
    description="Read a file",
    input_schema={
        "type": "object",
        "properties": {
            "file_path": {"type": "string"},
            "limit": {"type": "integer"}
        }
    },
    handler=read_file_handler
)

特点?
- 工具是独立的数据结构
- 自动生成 JSON Schema
- 运行时动态注册和查找

4. 双作用域记忆系统

~/.nano_claude/memory/          # 用户级记忆
├── project-conventions.md
└── coding-style.md

.nano_claude/memory/           # 项目级记忆
├── api-endpoints.md
└── database-schema.md

设计优势?
- 用户级:跨项目复用的知识
- 项目级:特定于当前项目的知识
- 自动注入到系统提示词中

5. Git Worktree 隔离的子 Agent

# 创建新的 worktree
git worktree add ../myfeature-task

# 在隔离环境中运行子 Agent
subagent = Agent(cwd="../myfeature-task")
result = subagent.run("implement feature X")

为什么需要隔离?
- 并行工作不会互相干扰
- 每个子任务有独立的文件系统视图
- 更安全:实验性代码不影响主分支

核心组件深度解析

Agent Loop:心跳所在

Agent Loop 是整个系统的引擎,它的本质是一个状态机

[用户输入] → [LLM 调用] → [工具调用?] → [执行工具] → [返回 LLM] → [完成?]
     ↑                                                           ↓
     └─────────────────────────────────── 循环 ──────────────────┘

关键点:
1. 循环直到完成 — 不是单次请求-响应,而是持续对话
2. 工具调用是触发器 — LLM 决定调用工具,系统执行后反馈结果
3. 自动化流程 — 用户不需要手动循环,系统自动处理

Tool Use:能力的扩展

工具系统让 AI 能够突破"纯文本"的限制:

工具类别 代表工具 能力
文件操作 Read, Write, Edit 读写代码文件
命令执行 Bash 运行测试、安装依赖
代码搜索 Glob, Grep 查找文件、搜索代码
网络能力 WebFetch, WebSearch 获取外部信息
记忆管理 MemorySave, MemorySearch 持久化知识
多 Agent Agent, SendMessage 派遣助手

设计的艺术
- 工具是"原语" (primitives),可以组合出复杂行为
- JSON Schema 提供了自文档化接口
- 权限系统确保安全性

TodoWrite:目标的显式化

TodoWrite([
    {"content": "Design API schema", "status": "completed"},
    {"content": "Implement endpoints", "status": "in_progress"},
    {"content": "Write tests", "status": "pending"},
    {"content": "Deploy to production", "status": "pending"}
])

价值
- 可视化进度
- 防止 Agent 遗忘任务
- 用户可以实时跟踪状态

Subagents:分而治之

Main Agent
    ├─> Coder Subagent (实现功能)
    ├─> Reviewer Subagent (代码审查)
    └─> Tester Subagent (编写测试)

设计要点
- 每个子 Agent 有独立的对话历史
- 专门的上下文避免干扰
- 主 Agent 负责协调和汇总

Memory:知识的持久化

记忆系统解决了 LLM 的"遗忘问题":

# 保存 API 密钥使用规范
MemorySave(
    name="api-key-conventions",
    type="convention",
    content="Use environment variables for API keys, never hardcode",
    scope="user"  # 所有项目共享
)

四种记忆类型
- fact — 事实性信息
- convention — 编码规范
- pattern — 设计模式
- context — 项目上下文

双作用域
- user — 跨项目知识(如编码风格)
- project — 项目特定知识(如 API 端点)

Skills:按需加载的知识库

技能系统允许"插件式"扩展 Agent 能力:

<!-- tdd-workflow.skill.md -->
---
name: tdd-workflow
trigger: "使用 TDD"
tools: [Write, Bash, Grep]
---

## Test-Driven Development Workflow

1. Write a failing test
2. Run the test to confirm it fails
3. Write minimal code to pass
4. Refactor

执行模式
- inline — 在当前对话中执行
- fork — 启动子 Agent 执行(隔离上下文)

参数替换

Create a test for $FEATURE_NAME using $TEST_FRAMEWORK

调用时:/tdd-workflow FEATURE_NAME=user-auth TEST_FRAMEWORK=jest

与真实 Claude Code 的对比

维度 Nano-Claude-Code 真实 Claude Code
开源 ✅ 完全开源 ❌ 闭源
语言 Python (~5000 行) TypeScript/Node.js
提供商 10+ 支持 仅 Anthropic
MCP 协议 ❌ 不支持 ✅ 原生支持
工具数量 18 更多(包括 NotebookEdit 等)
子 Agent 线程池 进程级隔离
终端 UI 简单 ANSI 完整 TUI
多模态 ❌ 不支持 ✅ 完整支持
成本 免费(自托管) 订阅制

关键相似点
- 相同的 Agent Loop 架构
- 相同的工具 Schema 格式
- 相同的 CLAUDE.md 约定
- 相同的 Edit 工具设计

关键差异
- Nano 使用生成器事件系统,真实版可能用回调/观察者
- Nano 没有 MCP 支持(这是主要架构差异)
- Nano 的子 Agent 是线程级隔离(更简单但隔离性较弱)

学习建议

对于初学者

  1. 先读 Learn-Claude-Code — 建立概念框架
  2. 逐节实践 — 自己实现每个组件
  3. 阅读 Nano-Claude-Code 源码 — 看真实实现

对于有经验者

  1. 直接阅读 Nano-Claude-Code 源码 — 关注架构设计
  2. 对比真实 Claude Code 的行为 — 理解未公开的部分
  3. 思考改进方案 — 如何做得更好?

重点关注

必读源文件
- agent.py — Agent Loop 的核心实现
- providers.py — 多提供商抽象
- tool_registry.py — 工具注册系统
- multi_agent/subagent.py — 子 Agent 管理

必学概念
- 生成器风格的事件系统
- 提供商无关的消息格式
- Git Worktree 隔离
- 双作用域记忆系统

实践建议

从零实现一个最小 Agent Harness

# 1. 定义最简单的工具
def read_file(file_path):
    with open(file_path) as f:
        return f.read()

# 2. 实现 Agent Loop
def agent_loop(user_message, tools):
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = llm_call(messages, tools)

        if response.tool_calls:
            for call in response.tool_calls:
                result = tools[call.name](**call.args)
                messages.append({
                    "role": "tool",
                    "name": call.name,
                    "content": result
                })
        else:
            return response.content

# 3. 添加工具 Schema
tools = {
    "read_file": {
        "name": "read_file",
        "input_schema": {
            "type": "object",
            "properties": {
                "file_path": {"type": "string"}
            }
        }
    }
}

扩展方向

  1. 添加 TodoWrite — 任务跟踪
  2. 实现记忆系统 — 持久化知识
  3. 支持子 Agent — 任务委派
  4. 构建技能系统 — 可扩展知识库

总结

Agent Harness 是 AI 编程助手的基础架构,通过两个开源项目我们能够完整地学习它:

Learn-Claude-Code 提供了系统化的学习路径,12 节课程涵盖了从基础到高级的所有核心概念。

Nano-Claude-Code 提供了生产级的参考实现,5000 行 Python 代码展示了如何构建一个完整可用的系统。

这些项目不仅让我们理解了 Agent Harness 的设计理念,更重要的是:它们展示了如何用简洁的代码实现复杂的能力。

核心教训
- Agent Loop 是心跳,其他组件都是围绕它构建
- 工具系统是能力的来源,设计要简单而强大
- 记忆和技能系统让 Agent 能够持续进化
- 子 Agent 让复杂任务变得可管理

掌握了这些,你就掌握了构建下一代 AI 编程助手的关键。


延伸阅读
- Claude Code 官方文档
- Model Context Protocol (MCP)
- Anthropic Tool Use API

posted @ 2026-04-03 23:16  iTech  阅读(32)  评论(0)    收藏  举报