Skip to content
Back to search

learn-claude-code

SkillWorks with Claude CodeGitHub

Bash is all you need - A nano claude code–like 「agent harness」, built from 0 to 1

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/shareAI-lab/learn-claude-code with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/shareAI-lab/learn-claude-code'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/shareai-lab--learn-claude-code/badge.svg)](/listings/shareai-lab--learn-claude-code)

HTML

<a href="/listings/shareai-lab--learn-claude-code"><img src="/api/listings/shareai-lab--learn-claude-code/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Current 17-Lesson Track

git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
pip install -r requirements.txt
cp .env.example .env   # configure ANTHROPIC_API_KEY

python s01_agent_loop/code.py        # Start here -- one loop + bash
python s08_context_compact/code.py   # Context compaction (complex)
python s17_goal_loop/code.py         # Endpoint: continue until a checkable goal is met

Legacy 12-Lesson Track

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

Web Platform

The web app extracts the root-level course. Lessons s16 and s17 include reading, source, simulator, and architecture views; only their dedicated hero visualizations remain intentionally minimal.

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

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 456 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. [English](./README.md) | [中文](./README-zh.md) | [日本語](./README-ja.md)
  2. <a href="https://trendshift.io/repositories/19746" target="_blank"><img src="https://trendshift.io/api/badge/repositories/19746" alt="shareAI-lab%2Flearn-claude-code | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
  3. # Learn Claude Code -- Harness Engineering for Real Agents
  4. ## Agency Comes from the Model. An Agent Product = Model + Harness.
  5. Before we write any code, one thing needs to be clear.
  6. **Agency -- the capacity to perceive, reason, and act -- comes from model training, not from external code orchestration.** But a working agent product needs both the model and the harness. The model is the driver. The harness is the vehicle. This repository teaches you how to build the vehicle.
  7. ### Where Agency Comes From
  8. At the core of every agent is a neural network -- a Transformer, an RNN, a trained function -- shaped by billions of gradient updates on sequences of perception, reasoning, and action. Agency was never bestowed by the surrounding code. It was learned during training.
  9. Humans are the original proof. A biological neural network, refined by millions of years of evolutionary pressure, perceives the world through senses, reasons through a brain, and acts through a body. When DeepMind, OpenAI, or Anthropic say "agent," they all mean the same core thing: **a model that learned to act through training, plus the infrastructure that lets it operate in a specific environment.**
  10. The historical record is unambiguous:
  11. - **2013 -- DeepMind DQN plays Atari.** A single neural network, receiving only raw pixels and game scores, learned 7 Atari 2600 games -- surpassing prior algorithms and beating human experts in 3 of them. By 2015, scaled to [49 games at professional tester level](https://www.nature.com/articles/nature14236), published in *Nature*. No game-specific rules. One model, learning from experience.
  12. - **2019 -- OpenAI Five conquers Dota 2.** Five neural networks played [45,000 years of Dota 2 against themselves](https://openai.com/index/openai-five-defeats-dota-2-world-champions/) over 10 months, then defeated **OG** -- the TI8 world champions -- 2-0 in a live match. In the public arena, the AI won 99.4% of 42,729 games. No scripted strategies. Models learned teamwork through self-play.
  13. - **2019 -- DeepMind AlphaStar masters StarCraft II.** AlphaStar [beat a professional player 10-1](https://deepmind.google/blog/alphastar-mastering-the-real-time-strategy-game-starcraft-ii/) in closed matches, then reached [Grandmaster rank](https://www.nature.com/articles/d41586-019-03298-6) on the European server -- top 0.15% of 90,000 players. An incomplete-information, real-time game with a combinatorial action space far exceeding chess or Go.
  14. - **2019 -- Tencent Jueyu dominates Honor of Kings.** Tencent AI Lab's "Jueyu" system [defeated KPL professional players in full 5v5](https://www.jiemian.com/article/3371171.html) at the World Champion Cup semifinal. In 1v1 mode, pros [won just 1 out of 15 matches, lasting under 8 minutes at best](https://developer.aliyun.com/article/851058). Training intensity: one day equaled 440 human years. A model that learned the entire game from scratch through self-play.
  15. - **2024-2025 -- LLM agents reshape software engineering.** Claude, GPT, Gemini -- large language models trained on the full breadth of human code and reasoning -- are deployed as coding agents. They read codebases, write implementations, debug failures, and coordinate as teams. The architecture is identical to every previous agent: a trained model, placed in an environment, given tools for perception and action.
  16. Every milestone points to the same fact: **Agency -- the ability to perceive, reason, and act -- is trained, not coded.** But every agent also needs an environment to operate in: an Atari emulator, the Dota 2 client, the StarCraft II engine, an IDE and a terminal. The model supplies the intelligence. The environment supplies the action space. Together they form a complete agent.
  17. ### What an Agent Is NOT
  18. The word "agent" has been hijacked by an entire prompt-plumbing industry.
  19. Drag-and-drop workflow builders. No-code "AI Agent" platforms. Prompt-chain orchestration libraries. They share a single delusion: that stringing LLM API calls together with if-else branches, node graphs, and hardcoded routing logic constitutes "building an agent."
  20. It does not. What they produce are Rube Goldberg machines -- over-engineered, brittle, procedural rule pipelines with an LLM wedged in as a glorified text-completion node. That is not an agent. That is a shell script with grandiose pretensions.
  21. You cannot brute-force intelligence by stacking procedural logic -- sprawling rule trees, node graphs, chained prompt waterfalls -- and praying that enough glue code will spontaneously produce autonomous behavior. It will not. You cannot engineer agency into existence. Agency is learned, not coded.
  22. ### The Mindshift: From "Building Agents" to Building Harnesses
  23. When someone says "I am building an agent," they can only mean one of two things:
  24. **1. Training a model.** Adjusting weights through reinforcement learning, fine-tuning, RLHF, or another gradient-based method. Collecting trajectory data -- real-world sequences of perception, reasoning, and action in a target domain -- and using it to shape the model's behavior. This is what DeepMind, OpenAI, Tencent AI Lab, and Anthropic do.
  25. **2. Building a harness.** Writing the code that gives a model an operational environment. This is what most of us do, and it is the core of this repository.
  26. A harness is everything an agent needs to work in a specific domain:
  27. ```
  28. Harness = Tools + Knowledge + Observation + Action Interfaces + Permissions
  29. Tools: file I/O, shell, network, database, browser
  30. Knowledge: product docs, domain references, API specs, style guides
  31. Observation: git diff, error logs, browser state, sensor data
  32. Action: CLI commands, API calls, UI interactions
  33. Permissions: sandbox isolation, approval workflows, trust boundaries
  34. ```
  35. The model decides. The harness executes. The model reasons. The harness provides context. The model is the driver. The harness is the vehicle.
  36. This repository teaches you to build the vehicle. A vehicle for coding. But the design patterns generalize to any domain.
  37. ### What Harness Engineers Actually Do
  38. If you are reading this repository, you are most likely a harness engineer. Here is what the job actually entails:
  39. - **Implement tools.** Give the agent hands. File read/write, shell execution, API calls, browser control, database queries. Each tool is one action the agent can take in its environment. Design them atomic, composable, and clearly described.
  40. - **Curate knowledge.** Give the agent domain expertise. Product documentation, architecture decision records, style guides, compliance requirements. Load on demand, not upfront.
  41. - **Manage context.** Subagents keep focused work in a separate message list. Context compaction shortens older history. Task systems let goals persist beyond a single conversation.
  42. - **Control permissions.** Give the agent boundaries. Sandbox file access. Require approval for destructive operations. Enforce trust boundaries between the agent and external systems.
  43. - **Collect trajectory data.** Every action sequence the agent executes in your harness is training signal. Real deployment trajectories are the raw material for fine-tuning the next generation of agent models.
  44. You are not writing intelligence. You are building the world that intelligence inhabits. The quality of that world directly determines how effectively the intelligence can express itself.
  45. **Build the harness well. The model will do the rest.**
  46. ### Why Claude Code
  47. Because Claude Code is the most elegant, most complete agent harness implementation we have seen. Not because of any clever trick, but because of what it *does not* do: it does not try to be the agent. It does not impose rigid workflows. It does not substitute hand-crafted decision trees for the model's own judgment. It gives the model tools, knowledge, context management, and permission boundaries -- then gets out of the way.
  48. Strip Claude Code down to its essence:
  49. ```
  50. Claude Code = one agent loop
  51. + tools (bash, read, write, edit, glob, grep, browser...)
  52. + on-demand skill loading
  53. + context compaction
  54. + subagent spawning
  55. + task system with dependency graphs
  56. + async mailbox team coordination
  57. + task-bound worktrees for parallel edits
  58. + permission governance
  59. + hooks extension system
  60. + memory persistence
  61. + MCP external capability routing
  62. ```
  63. That is it. The agent itself? Claude. A model. Trained by Anthropic on the full breadth of human reasoning and code. The harness did not make Claude smart. Claude was already smart. The harness gave Claude hands, eyes, and a workspace.
  64. The takeaway is not "copy Claude Code." The takeaway is: **the best agent products come from engineers who understand that their job is the harness, not the intelligence.**
  65. ---
  66. ```
  67. THE AGENT PATTERN
  68. =================
  69. User --> messages[] --> LLM --> response
  70. |
  71. contains tool_use block?
  72. / \
  73. yes no
  74. | |
  75. execute tools return text
  76. append results
  77. loop back -----------------> messages[]
  78. The model decides when to call tools and when to stop.
  79. The code just executes what the model asks for.
  80. This repo teaches you to build everything around this loop --
  81. the harness that makes the agent effective in a specific domain.
  82. ```
  83. ## Core Pattern
  84. ```python
  85. def agent_loop(messages):
  86. while True:
  87. response = client.messages.create(
  88. model=MODEL, system=SYSTEM,
  89. messages=messages, tools=TOOLS,
  90. )
  91. messages.append({"role": "assistant",
  92. "content": response.content})
  93. tool_calls = [
  94. block for block in response.content if block.type == "tool_use"
  95. ]
  96. if not tool_calls:
  97. return
  98. results = []
  99. for block in tool_calls:
  100. output = TOOL_HANDLERS[block.name](**block.input)
  101. results.append({
  102. "type": "tool_result",
  103. "tool_use_id": block.id,
  104. "content": output,
  105. })
  106. messages.append({"role": "user", "content": results})
  107. ```
  108. Each lesson isolates one harness mechanism around this loop. s15 reconnects the cumulative runtime; s16 and s17 then study workflow orchestration and goal closure as focused examples. The loop belongs to the agent. The mechanisms belong to the harness.
  109. The loop is constant. Tools, knowledge, and permissions change. Agent = Model (LLM) + a generalized operational environment (Harness).
  110. ---
  111. ## Version Status
  112. This repository currently contains two tutorial tracks:
  113. - **Current track: root-level `s01-s17`**
  114. The root-level `s01_*` ... `s17_*` folders are the canonical version. Each chapter contains an English default README, Chinese/Japanese translations, runnable `code.py`, and diagrams where needed.
  115. - **Legacy transition track: `docs/` and `agents/`**
  116. These preserve the older 12-lesson version for existing readers and old links during migration.
  117. If you are starting now, read the root-level `s01_agent_loop/` through `s17_goal_loop/` chapters. The legacy and current chapter numbers do not always match, so avoid mixing chapter numbers across tracks.
  118. ### Legacy-to-Current Mapping
  119. | Legacy 12-lesson track | Current 17-lesson track | Topic |
  120. |---|---|---|
  121. | old s01 | new s01 | Agent Loop |
  122. | old s02 | new s02 | Tool Use |
  123. | old s03 | new s05 | TodoWrite |
  124. | old s04 | new s06 | Subagent |
  125. | old s05 | new s07 | Skill Loading |
  126. | old s06 | new s08 | Context Compact |
  127. | old s07 | new s10 | Task System |
  128. | old s08 | new s11 | Background Tasks |
  129. | old s09 | new s13 | Agent Teams |
  130. | old s10 | new s13 | Team Protocols |
  131. | old s11 | new s13 | Autonomous task claiming |
  132. | old s12 | new s13 | Task-bound worktrees |
  133. | new only | s03, s04, s09, s12, s14, s15, s16, s17 | Permission, Hooks, Memory, Cron, MCP, Integrated Harness, Workflow Runtime, Goal Loop |
  134. ---
  135. ## Course Boundary
  136. This is a 0-to-1 harness engineering course. Each chapter isolates one mechanism, then s15 reconnects the cumulative runtime in a complete agent loop. s16 extends that loop with workflow orchestration. s17 uses a smaller tool pool to focus on goal-controlled continuation; it is a mechanism example, not another cumulative runtime.
  137. ---
  138. ## 17 Progressive Lessons
  139. **Each lesson adds one harness mechanism. Each mechanism has a motto.**
  140. > **s01** &nbsp; *"One loop & Bash is all you need"* &mdash; one tool + one loop = one agent
  141. >
  142. > **s02** &nbsp; *"Adding a tool means adding one handler"* &mdash; the loop stays untouched; new tools register into the dispatch map
  143. >
  144. > **s03** &nbsp; *"Set boundaries first, then grant freedom"* &mdash; check what can run, what must stop, and what needs approval
  145. >
  146. > **s04** &nbsp; *"Hook around the loop, never rewrite the loop"* &mdash; add extension points without changing the main loop
  147. >
  148. > **s05** &nbsp; *"An agent without a plan drifts"* &mdash; list the steps before starting; completion rate doubles
  149. >
  150. > **s06** &nbsp; Give a subtask fresh `messages[]`; its final text returns as one tool result
  151. >
  152. > **s07** &nbsp; *"Load knowledge on demand, not upfront"* &mdash; list skills first, expand them only when needed
  153. >
  154. > **s08** &nbsp; *"Context always fills up -- have a way to make room"* &mdash; four compaction steps reduce tool results first, then summarize history when it remains over the limit
  155. >
  156. > **s09** &nbsp; *"Remember what matters, forget what doesn't"* &mdash; three subsystems: selection, extraction, consolidation
  157. >
  158. > **s10** &nbsp; *"Big goals break into small tasks, ordered, persisted to disk"* &mdash; a file-backed task graph that lays the groundwork for multi-agent coordination
  159. >
  160. > **s11** &nbsp; *"Slow ops go background, agent keeps thinking"* &mdash; background threads run commands; notifications inject on completion
  161. >
  162. > **s12** &nbsp; *"Fire on schedule, no human kick needed"* &mdash; trigger tasks automatically by time
  163. >
  164. > **s13** &nbsp; *"Too big for one agent -- let teammates divide the work"* &mdash; persistent teammates coordinate, claim ready tasks, and use task-bound working directories
  165. >
  166. > **s14** &nbsp; *"Not enough capability? Plug in more via MCP"* &mdash; connect external tools into the same tool pool
  167. >
  168. > **s15** &nbsp; *"Many mechanisms, one loop"* &mdash; the mechanisms used by the integrated example share one harness
  169. >
  170. > **s16** &nbsp; *"When the orchestration shape is fixed, put it in code"* &mdash; saved workflows with resumable journals
  171. >
  172. > **s17** &nbsp; *"A goal decides when the loop may stop"* &mdash; an independent evaluator reviews each proposed stop; impossible, failed, or over-limit goals return control to the user
  173. ---
  174. ## Learning Path
  175. Main line: act → handle complex work → remember across sessions → run long tasks → collaborate → extend and assemble → orchestrate and close goals.
  176. ```mermaid
  177. flowchart TD
  178. %% Card styles
  179. classDef stage1 fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#0D47A1,rx:12,ry:12,text-align:left
  180. classDef stage2 fill:#E8F5E9,stroke:#388E3C,stroke-width:2px,color:#1B5E20,rx:12,ry:12,text-align:left
  181. classDef stage3 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#E65100,rx:12,ry:12,text-align:left
  182. classDef stage4 fill:#FCE4EC,stroke:#C2185b,stroke-width:2px,color:#880E4F,rx:12,ry:12,text-align:left
  183. classDef stage5 fill:#F3E5F5,stroke:#7B1FA2,stroke-width:2px,color:#4A148C,rx:12,ry:12,text-align:left
  184. classDef stage6 fill:#E0F7FA,stroke:#0097A7,stroke-width:2px,color:#006064,rx:12,ry:12,text-align:left
  185. %% Group style
  186. classDef groupBox fill:#F8F9FA,stroke:#CED4DA,stroke-width:2px,stroke-dasharray: 5 5,rx:15,ry:15,color:#495057
  187. %% Layer 1: stages 1-3
  188. subgraph Phase1 ["🌱 Stages 1-3: Core capabilities (simple to complex)"]
  189. direction LR
  190. S1["<b>1. Let the Agent act</b><br/>━━━━━━━━━━━━━<br/><b>s01 Agent Loop</b><br/>└─ one loop + bash<br/><br/><b>s02 Tool Use</b><br/>└─ one tool to many tools<br/><br/><b>s03 Permission</b><br/>└─ decide what can run<br/><br/><b>s04 Hooks</b><br/>└─ extension points around tools"]:::stage1
  191. S2["<b>2. Handle complex work</b><br/>━━━━━━━━━━━━━<br/><b>s05 TodoWrite</b><br/>└─ plan first, then execute<br/><br/><b>s06 Subagent</b><br/>└─ fresh messages, final text back<br/><br/><b>s08 Context Compact</b><br/>└─ make room in long context"]:::stage2
  192. S3["<b>3. Remember across sessions</b><br/>━━━━━━━━━━━━━<br/><b>s09 Memory</b><br/>└─ persist and recall reusable knowledge"]:::stage3
  193. S1 ==> S2 ==> S3
  194. end
  195. %% Layer 2: stages 4-6
  196. subgraph Phase2 ["🚀 Stages 4-6: Advanced capabilities (long-running, collaboration, integration)"]
  197. direction LR
  198. S4["<b>4. Run long tasks</b><br/>━━━━━━━━━━━━━<br/><b>s10 Task System</b><br/>└─ persist tasks and deps<br/><br/><b>s11 Background Tasks</b><br/>└─ send slow work background<br/><br/><b>s12 Cron Scheduler</b><br/>└─ trigger by time"]:::stage4
  199. S5["<b>5. Coordinate many Agents</b><br/>━━━━━━━━━━━━━<br/><b>s13 Agent Teams</b><br/>└─ teammates + delivery + protocols<br/>└─ atomic task claims<br/>└─ task-bound worktrees"]:::stage5
  200. S6["<b>6. Extend and assemble</b><br/>━━━━━━━━━━━━━<br/><b>s07 Skill Loading</b><br/>└─ expand skills on demand<br/><br/><b>s14 MCP Plugin</b><br/>└─ external tools, one pool<br/><br/><b>s15 Integrated Harness</b><br/>└─ course mechanisms, one loop"]:::stage6
  201. S4 ==> S5 ==> S6
  202. end
  203. %% Layer 3: orchestration and goal closure
  204. subgraph Phase3 ["🎯 Stage 7: Orchestration and goal closure"]
  205. direction LR
  206. S7["<b>7. Orchestrate and finish</b><br/>━━━━━━━━━━━━━<br/><b>s16 Workflow Runtime</b><br/>└─ scripts own fixed orchestration<br/><br/><b>s17 Goal Loop</b><br/>└─ independent evaluation decides when to stop"]:::stage1
  207. S6 ==> S7
  208. end
  209. %% Connect the three layers
  210. Phase1 ===> Phase2 ===> Phase3
  211. class Phase1,Phase2,Phase3 groupBox
  212. ```
  213. ---
  214. ## All Chapters
  215. | Chapter | Topic | Key Concepts |
  216. |---|---|---|
  217. | [s01](./s01_agent_loop/) | Agent Loop | `messages` / `while True` / `tool_use` |
  218. | [s02](./s02_tool_use/) | Tool Use | `TOOL_HANDLERS` / dispatch map / concurrency |
  219. | [s03](./s03_permission/) | Permission System | `PermissionRule` / approval pipeline |
  220. | [s04](./s04_hooks/) | Hook System | `PreToolUse` / `PostToolUse` / extension points |
  221. | [s05](./s05_todo_write/) | TodoWrite | `TodoItem` / plan-then-execute |
  222. | [s06](./s06_subagent/) | Subagent | `fresh messages[]` / context isolation |
  223. | [s07](./s07_skill_loading/) | Skill Loading | `SkillLoader` / catalog / on-demand injection |
  224. | [s08](./s08_context_compact/) | Context Compact | tool_result_budget / snip_compact / micro_compact / compact_history |
  225. | [s09](./s09_memory/) | Memory System | selection / extraction / consolidation |
  226. | [s10](./s10_task_system/) | Task System | `TaskRecord` / `blockedBy` / disk persistence |
  227. | [s11](./s11_background_tasks/) | Background Tasks | threaded execution / notification queue |
  228. | [s12](./s12_cron_scheduler/) | Cron Scheduler | durable scheduling / session-scoped triggers |
  229. | [s13](./s13_agent_teams/) | Agent Teams | persistent teammates / atomic task claims / task-bound worktrees / typed protocols |
  230. | [s14](./s14_mcp_plugin/) | MCP Plugin | tool discovery / namespaced tools / tool pool assembly |
  231. | [s15](./s15_integrated_harness/) | Integrated Harness | tools, runtime context, tasks, teams, scheduling, and MCP around one loop |
  232. | [s16](./s16_workflow_runtime/) | Workflow Runtime | script orchestration / lifecycle events / journal resume |
  233. | [s17](./s17_goal_loop/) | Goal Loop | goal gate / conversation evaluation / automatic continuation |
  234. ---
  235. ## How to Read
  236. Each chapter is a folder. Open one and you will find:
  237. ```
  238. s08_context_compact/
  239. README.md # English, the default chapter README
  240. README.zh.md # Chinese translation
  241. README.ja.md # Japanese translation
  242. code.py # standalone runnable implementation
  243. images/ # SVG diagrams (where needed)
  244. ```
  245. Read the `README.md` for the core idea and work through the code. Complex chapters have `<details>` folds for deep dives -- open them when you want to go deeper. Simple chapters have 0-1 diagrams, complex chapters have more.
  246. Read from s01 through s17 in order. Some mechanisms build directly on the previous runtime; independent mechanism chapters state which earlier kernel they use.
  247. ---
  248. ## Quick Start
  249. ### Current 17-Lesson Track
  250. ```sh
  251. git clone https://github.com/shareAI-lab/learn-claude-code
  252. cd learn-claude-code
  253. pip install -r requirements.txt
  254. cp .env.example .env # configure ANTHROPIC_API_KEY
  255. python s01_agent_loop/code.py # Start here -- one loop + bash
  256. python s08_context_compact/code.py # Context compaction (complex)
  257. python s17_goal_loop/code.py # Endpoint: continue until a checkable goal is met
  258. ```
  259. ### Legacy 12-Lesson Track
  260. ```sh
  261. python agents/s01_agent_loop.py
  262. python agents/s12_worktree_task_isolation.py
  263. python agents/s_full.py
  264. ```
  265. ### Web Platform
  266. The web app extracts the root-level course. Lessons s16 and s17 include reading, source, simulator, and architecture views; only their dedicated hero visualizations remain intentionally minimal.
  267. ```sh
  268. cd web && npm install && npm run dev # http://localhost:3000
  269. ```
  270. ---
  271. ## Project Structure
  272. ```
  273. learn-claude-code/
  274. s01_agent_loop/ # one folder per chapter
  275. README.md # English default (complete narrative)
  276. README.zh.md # Chinese translation
  277. README.ja.md # Japanese translation
  278. code.py # standalone runnable code
  279. images/ # SVG diagrams
  280. s02_tool_use/
  281. ...
  282. s14_mcp_plugin/
  283. s15_integrated_harness/
  284. s16_workflow_runtime/
  285. s17_goal_loop/ # endpoint chapter
  286. agents/ # legacy 12 runnable copies + s_full.py
  287. skills/ # skill files used by s07
  288. docs/ # legacy 12-lesson docs, kept during transition
  289. web/ # generated from the root-level course
  290. tests/
  291. ```
  292. ---
  293. ## What's Next
  294. After 17 lessons, you understand harness engineering from the inside out. Two paths to turn that knowledge into product:
  295. ### Kode Agent CLI -- Open-Source Coding Agent CLI
  296. > `npm i -g @shareai-lab/kode`
  297. Skill and LSP support, Windows compatible, works with GLM / MiniMax / DeepSeek and other open models. Install and go.
  298. GitHub: **[shareAI-lab/Kode-CLI](https://github.com/shareAI-lab/Kode-CLI)**
  299. ### Kode Agent SDK -- Embed Agent Capabilities in Your Application
  300. A standalone library with no per-user process overhead. Embed it in backends, browser extensions, embedded devices, or any runtime.
  301. GitHub: **[shareAI-lab/kode-agent-sdk](https://github.com/shareAI-lab/kode-agent-sdk)**
  302. ---
  303. ## Sister Tutorial: From Passive Sessions to Always-On Assistants
  304. The harness taught in this repository is the **use-and-discard** kind -- open a terminal, give the agent a task, close when done, next session starts fresh. Claude Code works this way.
  305. But [OpenClaw](https://github.com/openclaw/openclaw) proves another possibility: on the same agent core, two additional harness mechanisms turn an agent from "poke it and it moves" into "wakes itself every 30 seconds to look for work":
  306. - **Heartbeat** -- every 30 seconds the harness sends the agent a message, letting it check for pending work. Nothing to do? Keep sleeping. Something appeared? Act immediately.
  307. - **Cron** -- the agent can schedule its own future tasks, which fire automatically when the time arrives.
  308. Add IM multi-channel routing (WhatsApp / Telegram / Slack / Discord and 13+ other platforms), persistent context memory, and a Soul personality system, and the agent transforms from a disposable tool into an always-on personal AI assistant.
  309. **[claw0](https://github.com/shareAI-lab/claw0)** is our sister teaching repository, breaking down these harness mechanisms from scratch:
  310. ```
  311. claw agent = agent core + heartbeat + cron + IM chat + memory + soul
  312. ```
  313. ```
  314. learn-claude-code claw0
  315. (agent harness internals: (always-on harness:
  316. loop, tools, planning, heartbeat, cron, IM channels,
  317. teams, task-bound worktrees) memory, Soul personality)
  318. ```
  319. ## License
  320. MIT
  321. ---
  322. **Agency comes from the model. The harness gives agency a place to land. Build the harness well, and the model will do the rest.**
  323. **Bash is all you need. Real agents are all the universe needs.**
  324. **This is not "copy the source code." This is "grasp the key designs and build it yourself."**
skills/agent-builder/references/tool-templates.py · Bundled script · 271 lines · 1 finding marked
  1. """
  2. Tool Templates - Copy and customize these for your agent.
  3. Each tool needs:
  4. 1. Definition (JSON schema for the model)
  5. 2. Implementation (Python function)
  6. """
  7. from pathlib import Path
  8. import subprocess
  9. WORKDIR = Path.cwd()
  10. # =============================================================================
  11. # TOOL DEFINITIONS (for TOOLS list)
  12. # =============================================================================
  13. BASH_TOOL = {
  14. "name": "bash",
  15. "description": "Run a shell command. Use for: ls, find, grep, git, npm, python, etc.",
  16. "input_schema": {
  17. "type": "object",
  18. "properties": {
  19. "command": {
  20. "type": "string",
  21. "description": "The shell command to execute"
  22. }
  23. },
  24. "required": ["command"],
  25. },
  26. }
  27. READ_FILE_TOOL = {
  28. "name": "read_file",
  29. "description": "Read file contents. Returns UTF-8 text.",
  30. "input_schema": {
  31. "type": "object",
  32. "properties": {
  33. "path": {
  34. "type": "string",
  35. "description": "Relative path to the file"
  36. },
  37. "limit": {
  38. "type": "integer",
  39. "description": "Max lines to read (default: all)"
  40. },
  41. },
  42. "required": ["path"],
  43. },
  44. }
  45. WRITE_FILE_TOOL = {
  46. "name": "write_file",
  47. "description": "Write content to a file. Creates parent directories if needed.",
  48. "input_schema": {
  49. "type": "object",
  50. "properties": {
  51. "path": {
  52. "type": "string",
  53. "description": "Relative path for the file"
  54. },
  55. "content": {
  56. "type": "string",
  57. "description": "Content to write"
  58. },
  59. },
  60. "required": ["path", "content"],
  61. },
  62. }
  63. EDIT_FILE_TOOL = {
  64. "name": "edit_file",
  65. "description": "Replace exact text in a file. Use for surgical edits.",
  66. "input_schema": {
  67. "type": "object",
  68. "properties": {
  69. "path": {
  70. "type": "string",
  71. "description": "Relative path to the file"
  72. },
  73. "old_text": {
  74. "type": "string",
  75. "description": "Exact text to find (must match precisely)"
  76. },
  77. "new_text": {
  78. "type": "string",
  79. "description": "Replacement text"
  80. },
  81. },
  82. "required": ["path", "old_text", "new_text"],
  83. },
  84. }
  85. TODO_WRITE_TOOL = {
  86. "name": "TodoWrite",
  87. "description": "Update the task list. Use to plan and track progress.",
  88. "input_schema": {
  89. "type": "object",
  90. "properties": {
  91. "items": {
  92. "type": "array",
  93. "description": "Complete list of tasks",
  94. "items": {
  95. "type": "object",
  96. "properties": {
  97. "content": {"type": "string", "description": "Task description"},
  98. "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]},
  99. "activeForm": {"type": "string", "description": "Present tense, e.g. 'Reading files'"},
  100. },
  101. "required": ["content", "status", "activeForm"],
  102. },
  103. }
  104. },
  105. "required": ["items"],
  106. },
  107. }
  108. TASK_TOOL_TEMPLATE = """
  109. # Generate dynamically with agent types
  110. TASK_TOOL = {
  111. "name": "Task",
  112. "description": f"Spawn a subagent for a focused subtask.\\n\\nAgent types:\\n{get_agent_descriptions()}",
  113. "input_schema": {
  114. "type": "object",
  115. "properties": {
  116. "description": {"type": "string", "description": "Short task name (3-5 words)"},
  117. "prompt": {"type": "string", "description": "Detailed instructions"},
  118. "agent_type": {"type": "string", "enum": list(AGENT_TYPES.keys())},
  119. },
  120. "required": ["description", "prompt", "agent_type"],
  121. },
  122. }
  123. """
  124. # =============================================================================
  125. # TOOL IMPLEMENTATIONS
  126. # =============================================================================
  127. def safe_path(p: str) -> Path:
  128. """
  129. Security: Ensure path stays within workspace.
  130. Prevents ../../../etc/passwd attacks.
  131. """
  132. path = (WORKDIR / p).resolve()
  133. if not path.is_relative_to(WORKDIR):
  134. raise ValueError(f"Path escapes workspace: {p}")
  135. return path
  136. def run_bash(command: str) -> str:
  137. """
  138. Execute shell command with safety checks.
  139. Safety features:
  140. - Blocks obviously dangerous commands
  141. - 60 second timeout
  142. - Output truncated to 50KB
  143. """
  144. dangerous = ["rm -rf /", "sudo", "shutdown", "reboot", "> /dev/"]
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 161 on GitHub
  145. if any(d in command for d in dangerous):
  146. return "Error: Dangerous command blocked"
  147. try:
  148. result = subprocess.run(
  149. command,
  150. shell=True,
  151. cwd=WORKDIR,
  152. capture_output=True,
  153. text=True, errors="replace",
  154. timeout=60
  155. )
  156. output = (result.stdout + result.stderr).strip()
  157. return output[:50000] if output else "(no output)"
  158. except subprocess.TimeoutExpired:
  159. return "Error: Command timed out (60s)"
  160. except Exception as e:
  161. return f"Error: {e}"
  162. def run_read_file(path: str, limit: int = None) -> str:
  163. """
  164. Read file contents with optional line limit.
  165. Features:
  166. - Safe path resolution
  167. - Optional line limit for large files
  168. - Output truncated to 50KB
  169. """
  170. try:
  171. text = safe_path(path).read_text(encoding="utf-8")
  172. lines = text.splitlines()
  173. if limit and limit < len(lines):
  174. lines = lines[:limit]
  175. lines.append(f"... ({len(text.splitlines()) - limit} more lines)")
  176. return "\n".join(lines)[:50000]
  177. except Exception as e:
  178. return f"Error: {e}"
  179. def run_write_file(path: str, content: str) -> str:
  180. """
  181. Write content to file, creating parent directories if needed.
  182. Features:
  183. - Safe path resolution
  184. - Auto-creates parent directories
  185. - Returns byte count for confirmation
  186. """
  187. try:
  188. fp = safe_path(path)
  189. fp.parent.mkdir(parents=True, exist_ok=True)
  190. fp.write_text(content, encoding="utf-8")
  191. return f"Wrote {len(content)} bytes to {path}"
  192. except Exception as e:
  193. return f"Error: {e}"
  194. def run_edit_file(path: str, old_text: str, new_text: str) -> str:
  195. """
  196. Replace exact text in a file (surgical edit).
  197. Features:
  198. - Exact string matching (not regex)
  199. - Only replaces first occurrence (safety)
  200. - Clear error if text not found
  201. """
  202. try:
  203. fp = safe_path(path)
  204. content = fp.read_text(encoding="utf-8")
  205. if old_text not in content:
  206. return f"Error: Text not found in {path}"
  207. new_content = content.replace(old_text, new_text, 1)
  208. fp.write_text(new_content, encoding="utf-8")
  209. return f"Edited {path}"
  210. except Exception as e:
  211. return f"Error: {e}"
  212. # =============================================================================
  213. # DISPATCHER PATTERN
  214. # =============================================================================
  215. def execute_tool(name: str, args: dict) -> str:
  216. """
  217. Dispatch tool call to implementation.
  218. This pattern makes it easy to add new tools:
  219. 1. Add definition to TOOLS list
  220. 2. Add implementation function
  221. 3. Add case to this dispatcher
  222. """
  223. if name == "bash":
  224. return run_bash(args["command"])
  225. if name == "read_file":
  226. return run_read_file(args["path"], args.get("limit"))
  227. if name == "write_file":
  228. return run_write_file(args["path"], args["content"])
  229. if name == "edit_file":
  230. return run_edit_file(args["path"], args["old_text"], args["new_text"])
  231. # Add more tools here...
  232. return f"Unknown tool: {name}"
skills/agent-builder/scripts/init_agent.py · Bundled script · 282 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Agent Scaffold Script - Create a new agent project with best practices.
  4. Usage:
  5. python init_agent.py <agent-name> [--level 0-4] [--path <output-dir>]
  6. Examples:
  7. python init_agent.py my-agent # Level 1 (4 tools)
  8. python init_agent.py my-agent --level 0 # Minimal (bash only)
  9. python init_agent.py my-agent --level 2 # With TodoWrite
  10. python init_agent.py my-agent --path ./bots # Custom output directory
  11. """
  12. import argparse
  13. import sys
  14. from pathlib import Path
  15. # Agent templates for each level
  16. TEMPLATES = {
  17. 0: '''#!/usr/bin/env python3
  18. """
  19. Level 0 Agent - Bash is All You Need (~50 lines)
  20. Core insight: One tool (bash) can do everything.
  21. Subagents via self-recursion: python {name}.py "subtask"
  22. """
  23. from anthropic import Anthropic
  24. from dotenv import load_dotenv
  25. import subprocess
  26. import os
  27. load_dotenv()
  28. client = Anthropic(
  29. api_key=os.getenv("ANTHROPIC_API_KEY"),
  30. base_url=os.getenv("ANTHROPIC_BASE_URL")
  31. )
  32. MODEL = os.getenv("MODEL_NAME", "claude-sonnet-5-5")
  33. SYSTEM = """You are a coding agent. Use bash for everything:
  34. - Read: cat, grep, find, ls
  35. - Write: echo 'content' > file
  36. - Subagent: python {name}.py "subtask"
  37. """
  38. TOOL = [{{
  39. "name": "bash",
  40. "description": "Execute shell command",
  41. "input_schema": {{"type": "object", "properties": {{"command": {{"type": "string"}}}}, "required": ["command"]}}
  42. }}]
  43. def run(prompt, history=[]):
  44. history.append({{"role": "user", "content": prompt}})
  45. while True:
  46. r = client.messages.create(model=MODEL, system=SYSTEM, messages=history, tools=TOOL, max_tokens=8000)
  47. history.append({{"role": "assistant", "content": r.content}})
  48. if r.stop_reason != "tool_use":
  49. return "".join(b.text for b in r.content if hasattr(b, "text"))
  50. results = []
  51. for b in r.content:
  52. if b.type == "tool_use":
  53. print(f"> {{b.input['command']}}")
  54. try:
  55. out = subprocess.run(b.input["command"], shell=True, capture_output=True, text=True, errors="replace", timeout=60)
  56. output = (out.stdout + out.stderr).strip() or "(empty)"
  57. except Exception as e:
  58. output = f"Error: {{e}}"
  59. results.append({{"type": "tool_result", "tool_use_id": b.id, "content": output[:50000]}})
  60. history.append({{"role": "user", "content": results}})
  61. if __name__ == "__main__":
  62. h = []
  63. print("{name} - Level 0 Agent\\nType 'q' to quit.\\n")
  64. while (q := input(">> ").strip()) not in ("q", "quit", ""):
  65. print(run(q, h), "\\n")
  66. ''',
  67. 1: '''#!/usr/bin/env python3
  68. """
  69. Level 1 Agent - Model as Agent (~200 lines)
  70. Core insight: 4 tools cover 90% of coding tasks.
  71. The model IS the agent. Code just runs the loop.
  72. """
  73. from anthropic import Anthropic
  74. from dotenv import load_dotenv
  75. from pathlib import Path
  76. import subprocess
  77. import os
  78. load_dotenv()
  79. client = Anthropic(
  80. api_key=os.getenv("ANTHROPIC_API_KEY"),
  81. base_url=os.getenv("ANTHROPIC_BASE_URL")
  82. )
  83. MODEL = os.getenv("MODEL_NAME", "claude-sonnet-5-5")
  84. WORKDIR = Path.cwd()
  85. SYSTEM = f"""You are a coding agent at {{WORKDIR}}.
  86. Rules:
  87. - Prefer tools over prose. Act, don't just explain.
  88. - Never invent file paths. Use ls/find first if unsure.
  89. - Make minimal changes. Don't over-engineer.
  90. - After finishing, summarize what changed."""
  91. TOOLS = [
  92. {{"name": "bash", "description": "Run shell command",
  93. "input_schema": {{"type": "object", "properties": {{"command": {{"type": "string"}}}}, "required": ["command"]}}}},
  94. {{"name": "read_file", "description": "Read file contents",
  95. "input_schema": {{"type": "object", "properties": {{"path": {{"type": "string"}}}}, "required": ["path"]}}}},
  96. {{"name": "write_file", "description": "Write content to file",
  97. "input_schema": {{"type": "object", "properties": {{"path": {{"type": "string"}}, "content": {{"type": "string"}}}}, "required": ["path", "content"]}}}},
  98. {{"name": "edit_file", "description": "Replace exact text in file",
  99. "input_schema": {{"type": "object", "properties": {{"path": {{"type": "string"}}, "old_text": {{"type": "string"}}, "new_text": {{"type": "string"}}}}, "required": ["path", "old_text", "new_text"]}}}},
  100. ]
  101. def safe_path(p: str) -> Path:
  102. """Prevent path escape attacks."""
  103. path = (WORKDIR / p).resolve()
  104. if not path.is_relative_to(WORKDIR):
  105. raise ValueError(f"Path escapes workspace: {{p}}")
  106. return path
  107. def execute(name: str, args: dict) -> str:
  108. """Execute a tool and return result."""
  109. if name == "bash":
  110. dangerous = ["rm -rf /", "sudo", "shutdown", "> /dev/"]
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 132 on GitHub
  111. if any(d in args["command"] for d in dangerous):
  112. return "Error: Dangerous command blocked"
  113. try:
  114. r = subprocess.run(args["command"], shell=True, cwd=WORKDIR, capture_output=True, text=True, errors="replace", timeout=60)
  115. return (r.stdout + r.stderr).strip()[:50000] or "(empty)"
  116. except subprocess.TimeoutExpired:
  117. return "Error: Timeout (60s)"
  118. except Exception as e:
  119. return f"Error: {{e}}"
  120. if name == "read_file":
  121. try:
  122. return safe_path(args["path"]).read_text(encoding="utf-8")[:50000]
  123. except Exception as e:
  124. return f"Error: {{e}}"
  125. if name == "write_file":
  126. try:
  127. p = safe_path(args["path"])
  128. p.parent.mkdir(parents=True, exist_ok=True)
  129. p.write_text(args["content"], encoding="utf-8")
  130. return f"Wrote {{len(args['content'])}} bytes to {{args['path']}}"
  131. except Exception as e:
  132. return f"Error: {{e}}"
  133. if name == "edit_file":
  134. try:
  135. p = safe_path(args["path"])
  136. content = p.read_text(encoding="utf-8")
  137. if args["old_text"] not in content:
  138. return f"Error: Text not found in {{args['path']}}"
  139. p.write_text(
  140. content.replace(args["old_text"], args["new_text"], 1),
  141. encoding="utf-8",
  142. )
  143. return f"Edited {{args['path']}}"
  144. except Exception as e:
  145. return f"Error: {{e}}"
  146. return f"Unknown tool: {{name}}"
  147. def agent(prompt: str, history: list = None) -> str:
  148. """Run the agent loop."""
  149. if history is None:
  150. history = []
  151. history.append({{"role": "user", "content": prompt}})
  152. while True:
  153. response = client.messages.create(
  154. model=MODEL, system=SYSTEM, messages=history, tools=TOOLS, max_tokens=8000
  155. )
  156. history.append({{"role": "assistant", "content": response.content}})
  157. if response.stop_reason != "tool_use":
  158. return "".join(b.text for b in response.content if hasattr(b, "text"))
  159. results = []
  160. for block in response.content:
  161. if block.type == "tool_use":
  162. print(f"> {{block.name}}: {{str(block.input)[:100]}}")
  163. output = execute(block.name, block.input)
  164. print(f" {{output[:100]}}...")
  165. results.append({{"type": "tool_result", "tool_use_id": block.id, "content": output}})
  166. history.append({{"role": "user", "content": results}})
  167. if __name__ == "__main__":
  168. print(f"{name} - Level 1 Agent at {{WORKDIR}}")
  169. print("Type 'q' to quit.\\n")
  170. h = []
  171. while True:
  172. try:
  173. query = input(">> ").strip()
  174. except (EOFError, KeyboardInterrupt):
  175. break
  176. if query in ("q", "quit", "exit", ""):
  177. break
  178. print(agent(query, h), "\\n")
  179. ''',
  180. }
  181. ENV_TEMPLATE = '''# API Configuration
  182. ANTHROPIC_API_KEY=sk-xxx
  183. ANTHROPIC_BASE_URL=https://api.anthropic.com
  184. MODEL_NAME=claude-sonnet-5-5
  185. '''
  186. def create_agent(name: str, level: int, output_dir: Path):
  187. """Create a new agent project."""
  188. # Validate level
  189. if level not in TEMPLATES and level not in (2, 3, 4):
  190. print(f"Error: Level {level} not yet implemented in scaffold.")
  191. print("Available levels: 0 (minimal), 1 (4 tools)")
  192. print("For levels 2-4, copy from mini-claude-code repository.")
  193. sys.exit(1)
  194. # Create output directory
  195. agent_dir = output_dir / name
  196. agent_dir.mkdir(parents=True, exist_ok=True)
  197. # Write agent file
  198. agent_file = agent_dir / f"{name}.py"
  199. template = TEMPLATES.get(level, TEMPLATES[1])
  200. agent_file.write_text(template.format(name=name), encoding="utf-8")
  201. print(f"Created: {agent_file}")
  202. # Write .env.example
  203. env_file = agent_dir / ".env.example"
  204. env_file.write_text(ENV_TEMPLATE, encoding="utf-8")
  205. print(f"Created: {env_file}")
  206. # Write .gitignore
  207. gitignore = agent_dir / ".gitignore"
  208. gitignore.write_text(".env\n__pycache__/\n*.pyc\n", encoding="utf-8")
  209. print(f"Created: {gitignore}")
  210. print(f"\nAgent '{name}' created at {agent_dir}")
  211. print(f"\nNext steps:")
  212. print(f" 1. cd {agent_dir}")
  213. print(f" 2. cp .env.example .env")
  214. print(f" 3. Edit .env with your API key")
  215. print(f" 4. pip install anthropic python-dotenv")
  216. print(f" 5. python {name}.py")
  217. def main():
  218. parser = argparse.ArgumentParser(
  219. description="Scaffold a new AI coding agent project",
  220. formatter_class=argparse.RawDescriptionHelpFormatter,
  221. epilog="""
  222. Levels:
  223. 0 Minimal (~50 lines) - Single bash tool, self-recursion for subagents
  224. 1 Basic (~200 lines) - 4 core tools: bash, read, write, edit
  225. 2 Todo (~300 lines) - + TodoWrite for structured planning
  226. 3 Subagent (~450) - + Task tool for context isolation
  227. 4 Skills (~550) - + Skill tool for domain expertise
  228. """
  229. )
  230. parser.add_argument("name", help="Name of the agent to create")
  231. parser.add_argument("--level", type=int, default=1, choices=[0, 1, 2, 3, 4],
  232. help="Complexity level (default: 1)")
  233. parser.add_argument("--path", type=Path, default=Path.cwd(),
  234. help="Output directory (default: current directory)")
  235. args = parser.parse_args()
  236. create_agent(args.name, args.level, args.path)
  237. if __name__ == "__main__":
  238. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.