### Project Setup and Execution
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README.md
These shell commands outline the steps to clone the repository, install dependencies, configure API keys, and run different agent implementations.
```shell
git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
pip install -r requirements.txt
cp .env.example .env # Edit .env with your ANTHROPIC_API_KEY
python agents/s01_agent_loop.py # Start here
python agents/s12_worktree_task_isolation.py # Full progression endpoint
python agents/s_full.py # Capstone: all mechanisms combined
```
```shell
cd web && npm install && npm run dev # http://localhost:3000
```
--------------------------------
### Project Setup and Requirements
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Provides instructions for cloning the repository, installing dependencies, and setting up the environment variables, including the ANTHROPIC_API_KEY.
```sh
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
```
--------------------------------
### Basic Agent Setup (Bash)
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Demonstrates the fundamental concept that a single loop and Bash can be sufficient for a basic agent. This serves as the starting point for understanding agent construction.
```bash
One loop & Bash is all you need
```
--------------------------------
### Start the Next.js development server
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/web/README.md
Use these commands to launch the local development environment. Ensure the project dependencies are installed before running.
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
--------------------------------
### Run Task System Example
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
Execute the task system example script to interact with the task management features.
```sh
cd learn-claude-code
python agents/s07_task_system.py
```
--------------------------------
### Run Autonomous Agent Example
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s11-autonomous-agents.md
Command to execute the autonomous agent demonstration script.
```sh
cd learn-claude-code
python agents/s11_autonomous_agents.py
```
--------------------------------
### SKILL.md File Format Example
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
Example of a skill definition file using YAML frontmatter and Markdown content.
```markdown
---
name: pdf
description: Process PDF files - extract text, create PDFs, merge documents.
---
# PDF Processing Skill
## Reading PDFs
```bash
pdftotext input.pdf - # Output to stdout
```
## Creating PDFs
```bash
pandoc input.md -o output.pdf
```
## Merging PDFs
```python
import fitz
result = fitz.open()
for pdf_path in ["file1.pdf", "file2.pdf"]:
result.insert_pdf(fitz.open(pdf_path))
result.save("merged.pdf")
```
```
--------------------------------
### Run Agent Teams Example
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s09-agent-teams.md
Command to execute the agent teams demonstration script.
```sh
cd learn-claude-code
python agents/s09_agent_teams.py
```
--------------------------------
### Web Platform Development Setup
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Steps to set up and run the web platform for interactive visualization, step-by-step animations, and source code viewing.
```sh
cd web && npm install && npm run dev # http://localhost:3000
```
--------------------------------
### Initialize Python MCP Project
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
Commands to create a project directory, set up a virtual environment, and install the MCP SDK.
```bash
# Create project
mkdir my-mcp-server && cd my-mcp-server
python3 -m venv venv && source venv/bin/activate
# Install MCP SDK
pip install mcp
```
--------------------------------
### Initialize TypeScript MCP Project
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
Commands to set up a new TypeScript project and install the required SDK.
```bash
mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk
```
--------------------------------
### Install Kode Agent CLI
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README.md
Command to install the open-source coding agent CLI globally via npm.
```bash
npm i -g @shareai-lab/kode
```
--------------------------------
### Create Sequential Tasks
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
Create three tasks with sequential dependencies: Setup project -> Write code -> Write tests.
```sh
1. `Create 3 tasks: "Setup project", "Write code", "Write tests". Make them depend on each other in order.`
```
--------------------------------
### Running Individual Agent Lessons
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Shows how to run specific agent lessons, starting from the basic loop in s01 and progressing to the final lesson on worktree isolation in s12.
```sh
python agents/s01_agent_loop.py # 从这里开始
python agents/s12_worktree_task_isolation.py # 完整递进终点
```
--------------------------------
### Execute Subagent Script
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s04-subagent.md
Command to run the subagent example from the terminal. Navigate to the project directory first.
```sh
cd learn-claude-code
python agents/s04_subagent.py
```
--------------------------------
### Define MCP Resources
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
Examples of exposing read-only data as resources in an MCP server.
```python
@server.resource("config://settings")
async def get_settings() -> str:
"""Application settings."""
return open("settings.json").read()
@server.resource("file://{path}")
async def read_file(path: str) -> str:
"""Read a file from the workspace."""
return open(path).read()
```
--------------------------------
### Minimal Agent Implementation
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/agent-builder/SKILL.md
A reference Python script for a complete, working agent. This serves as a starting point for building your own agents, demonstrating a minimal implementation.
```python
references/minimal-agent.py
```
--------------------------------
### Implement Database Access in Python
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
Example of executing read-only SQL queries against a SQLite database.
```python
import sqlite3
from mcp.server import Server
server = Server("db-server")
@server.tool()
async def query_db(sql: str) -> str:
"""Execute a read-only SQL query."""
if not sql.strip().upper().startswith("SELECT"):
return "Error: Only SELECT queries allowed"
conn = sqlite3.connect("data.db")
cursor = conn.execute(sql)
rows = cursor.fetchall()
conn.close()
return str(rows)
```
--------------------------------
### Python Anti-patterns and Best Practices
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/code-review/SKILL.md
Examples of common Python vulnerabilities and their secure alternatives.
```python
# Bad: SQL injection
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
# Good:
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
# Bad: Command injection
os.system(f"ls {user_input}")
# Good:
subprocess.run(["ls", user_input], check=True)
# Bad: Mutable default argument
def append(item, lst=[]): # Bug: shared mutable default
# Good:
def append(item, lst=None):
lst = lst or []
```
--------------------------------
### Start Background Tasks
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s08-background-tasks.md
Spawns a daemon thread to execute a command and returns a task identifier immediately.
```python
def run(self, command: str) -> str:
task_id = str(uuid.uuid4())[:8]
self.tasks[task_id] = {"status": "running", "command": command}
thread = threading.Thread(
target=self._execute, args=(task_id, command), daemon=True)
thread.start()
return f"Background task {task_id} started"
```
--------------------------------
### JavaScript/TypeScript Anti-patterns and Best Practices
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/code-review/SKILL.md
Examples of common JavaScript/TypeScript vulnerabilities and their secure alternatives.
```javascript
// Bad: Prototype pollution
Object.assign(target, userInput)
// Good:
Object.assign(target, sanitize(userInput))
// Bad: eval usage
eval(userCode)
// Good: Never use eval with user input
// Bad: Callback hell
getData(x => process(x, y => save(y, z => done(z))))
// Good:
const data = await getData();
const processed = await process(data);
await save(processed);
```
--------------------------------
### Progressive Complexity Levels for AI Harnesses
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/agent-builder/references/agent-philosophy.md
Illustrates a staged approach to building AI agent harnesses, starting with basic tools and progressing to more complex systems involving planning, subagents, and teams.
```text
Level 0: Model + one tool (bash) -- s01
Level 1: Model + tool dispatch map -- s02
Level 2: Model + planning -- s03
Level 3: Model + subagents + skills -- s04, s05
Level 4: Model + context management + persistence -- s06, s07, s08
Level 5: Model + teams + autonomy + isolation -- s09-s12
```
--------------------------------
### Integrate External API in Python
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
Example of using httpx to fetch data from an external API within an MCP tool.
```python
import httpx
from mcp.server import Server
server = Server("weather-server")
@server.tool()
async def get_weather(city: str) -> str:
"""Get current weather for a city."""
async with httpx.AsyncClient() as client:
resp = await client.get(
f"https://api.weatherapi.com/v1/current.json",
params={"key": "YOUR_API_KEY", "q": city}
)
data = resp.json()
return f"{city}: {data['current']['temp_c']}C, {data['current']['condition']['text']}"
```
--------------------------------
### Domain-Specific Agent Structures
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README.md
Provides examples of how the universal agent pattern can be applied to different domains by combining a core model with specific sensors, tools, and knowledge bases.
```text
Estate management agent = model + property sensors + maintenance tools + tenant comms
Agricultural agent = model + soil/weather data + irrigation controls + crop knowledge
Hotel operations agent = model + booking system + guest channels + facility APIs
Medical research agent = model + literature search + lab instruments + protocol docs
Manufacturing agent = model + production line sensors + quality controls + logistics
Education agent = model + curriculum knowledge + student progress + assessment tools
```
--------------------------------
### Lifecycle Event Log Entry
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s12-worktree-task-isolation.md
Example of a JSON event entry recorded in the lifecycle log.
```json
{
"event": "worktree.remove.after",
"task": {"id": 1, "status": "completed"},
"worktree": {"name": "auth-refactor", "status": "removed"},
"ts": 1730000000
}
```
--------------------------------
### Convert HTML to PDF using wkhtmltopdf
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/pdf/SKILL.md
Use wkhtmltopdf command-line tool or its Python wrapper (pdfkit) to convert HTML files to PDF. Ensure wkhtmltopdf is installed separately.
```bash
# Using wkhtmltopdf
wkhtmltopdf input.html output.pdf
# Or with Python
python3 -c "
import pdfkit
pdfkit.from_file('input.html', 'output.pdf')
"
```
--------------------------------
### Initialize TeammateManager
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s09-agent-teams.md
Sets up the directory structure and loads the team configuration.
```python
class TeammateManager:
def __init__(self, team_dir: Path):
self.dir = team_dir
self.dir.mkdir(exist_ok=True)
self.config_path = self.dir / "config.json"
self.config = self._load_config()
self.threads = {}
```
--------------------------------
### Run the Tool Use Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s02-tool-use.md
Commands to execute the tool use demonstration script.
```sh
cd learn-claude-code
python agents/s02_tool_use.py
```
--------------------------------
### Running the Full Integration Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Instructions for running the s_full.py script, which integrates all harness mechanisms into a single agent.
```sh
python agents/s_full.py # 总纲: 全部机制合一
```
--------------------------------
### Execute Skill Loading Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s05-skill-loading.md
Command to run the skill loading demonstration script.
```sh
cd learn-claude-code
python agents/s05_skill_loading.py
```
--------------------------------
### Agent Planning with Steps
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Highlights the benefit of planning steps before execution for improved completion rates. This approach helps agents manage complex tasks more effectively.
```bash
没有计划的 agent 走哪算哪
```
--------------------------------
### Command to Run the Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s06-context-compact.md
Navigate to the project directory and execute the s06 agent script to observe the context compression in action.
```sh
cd learn-claude-code
python agents/s06_context_compact.py
```
--------------------------------
### Implement Basic Python MCP Server
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
A template for creating an MCP server with defined tools using the Python SDK.
```python
#!/usr/bin/env python3
"""my_server.py - A simple MCP server"""
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
# Create server instance
server = Server("my-server")
# Define a tool
@server.tool()
async def hello(name: str) -> str:
"""Say hello to someone.
Args:
name: The name to greet
"""
return f"Hello, {name}!"
@server.tool()
async def add_numbers(a: int, b: int) -> str:
"""Add two numbers together.
Args:
a: First number
b: Second number
"""
return str(a + b)
# Run server
async def main():
async with stdio_server() as (read, write):
await server.run(read, write)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
```
--------------------------------
### Create and Bind Worktree
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s12-worktree-task-isolation.md
Initialize a new worktree directory and link it to a specific task ID.
```python
WORKTREES.create("auth-refactor", task_id=1)
# -> git worktree add -b wt/auth-refactor .worktrees/auth-refactor HEAD
# -> index.json gets new entry, task_1.json gets worktree="auth-refactor"
```
--------------------------------
### Initialize User Prompt
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s01-the-agent-loop.md
Adds the initial user query to the message history.
```python
messages.append({"role": "user", "content": query})
```
--------------------------------
### Extract Text from PDF using pdftotext
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/pdf/SKILL.md
Use pdftotext for quick text extraction from a PDF. Output can be directed to standard output or a file. Ensure poppler-utils is installed.
```bash
# Using pdftotext (poppler-utils)
pdftotext input.pdf - # Output to stdout
pdftotext input.pdf output.txt # Output to file
```
--------------------------------
### List Tasks and Show Dependency Graph
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
List all current tasks and display their dependency graph to visualize the workflow.
```sh
2. `List all tasks and show the dependency graph`
```
--------------------------------
### Tool Templates for Capabilities
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/agent-builder/SKILL.md
This Python file contains definitions for various capabilities that an agent can perform. Use these as templates when defining the actions your agent can take.
```python
references/tool-templates.py
```
--------------------------------
### Execute Background Task Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s08-background-tasks.md
Command to run the background task demonstration script.
```sh
cd learn-claude-code
python agents/s08_background_tasks.py
```
--------------------------------
### Initialize New Agent Project
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/agent-builder/SKILL.md
A Python script used for scaffolding and generating new agent projects. This helps in setting up the basic structure for a new AI agent.
```python
scripts/init_agent.py
```
--------------------------------
### Agent Session Execution Commands
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
Commands to clone the repository and run individual agent sessions or the full capstone.
```bash
# Clone and setup
git clone https://github.com/shareAI-lab/learn-claude-code
cd learn-claude-code
pip install -r requirements.txt
cp .env.example .env # Add your ANTHROPIC_API_KEY
# Run individual sessions
python agents/s01_agent_loop.py # Minimal agent with bash
python agents/s02_tool_use.py # Multiple tools with dispatch map
python agents/s03_todo_write.py # Progress tracking with TodoManager
python agents/s04_subagent.py # Subagent spawning
python agents/s05_skill_loading.py # On-demand knowledge loading
python agents/s06_context_compact.py # Context compression
python agents/s07_task_system.py # Persistent task board
python agents/s08_background_tasks.py # Async execution
python agents/s09_agent_teams.py # Multi-agent teams
python agents/s10_team_protocols.py # Shutdown and plan approval
python agents/s11_autonomous_agents.py # Self-governing agents
python agents/s12_worktree_task_isolation.py # Directory isolation
# Full capstone with all mechanisms
python agents/s_full.py
# Interactive web platform
cd web && npm install && npm run dev # http://localhost:3000
```
--------------------------------
### Implement SkillLoader Class
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s05-skill-loading.md
Parses skill directories and provides methods to retrieve descriptions for the system prompt and full content for tool execution.
```python
class SkillLoader:
def __init__(self, skills_dir: Path):
self.skills = {}
for f in sorted(skills_dir.rglob("SKILL.md")):
text = f.read_text()
meta, body = self._parse_frontmatter(text)
name = meta.get("name", f.parent.name)
self.skills[name] = {"meta": meta, "body": body}
def get_descriptions(self) -> str:
lines = []
for name, skill in self.skills.items():
desc = skill["meta"].get("description", "")
lines.append(f" - {name}: {desc}")
return "\n".join(lines)
def get_content(self, name: str) -> str:
skill = self.skills.get(name)
if not skill:
return f"Error: Unknown skill '{name}'."
return f"\n{skill['body']}\n"
```
--------------------------------
### Task Persistence and Graphing
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Explains the importance of breaking down large goals into small, ordered tasks that are persisted on disk as a task graph, laying the foundation for multi-agent collaboration.
```bash
大目标要拆成小任务, 排好序, 记在磁盘上
```
--------------------------------
### On-Demand Knowledge Loading
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Describes how to load knowledge on demand through tool results, rather than stuffing it into the system prompt. This keeps the system prompt concise and focused.
```bash
用到什么知识, 临时加载什么知识
```
--------------------------------
### Create a Task
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s12-worktree-task-isolation.md
Persist a new task goal to the task board.
```python
TASKS.create("Implement auth refactor")
# -> .tasks/task_1.json status=pending worktree=""
```
--------------------------------
### Define Skill Directory Structure
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s05-skill-loading.md
Organize skills into directories containing a SKILL.md file with YAML frontmatter.
```text
skills/
pdf/
SKILL.md # ---
name: pdf
description: Process PDF files
---
...
code-review/
SKILL.md # ---
name: code-review
description: Review code
---
...
```
--------------------------------
### Create a New Task
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
Creates a new task with a given subject and description, assigning it a unique ID and setting its initial status to 'pending'. Returns the task as a JSON string.
```python
def create(self, subject, description=""):
task = {"id": self._next_id, "subject": subject,
"status": "pending", "blockedBy": [],
"owner": ""}
self._save(task)
self._next_id += 1
return json.dumps(task, indent=2)
```
--------------------------------
### Adding a New Tool
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README-zh.md
Illustrates how to add new tools to an agent without modifying the core loop. New tools are registered within a dispatch map, simplifying extensibility.
```bash
加一个工具, 只加一个 handler
```
--------------------------------
### Complete Task and Unblock Next
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
Complete the first task to observe how the next task in the sequence becomes unblocked.
```sh
3. `Complete task 1 and then list tasks to see task 2 unblocked`
```
--------------------------------
### Implement Context Compression Pipeline
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
Provides functions for micro-compaction of tool results and auto-compaction via LLM summarization to manage token usage.
```python
import json
import time
THRESHOLD = 50000
TRANSCRIPT_DIR = WORKDIR / ".transcripts"
KEEP_RECENT = 3
PRESERVE_RESULT_TOOLS = {"read_file"}
def estimate_tokens(messages: list) -> int:
return len(str(messages)) // 4 # ~4 chars per token
def micro_compact(messages: list) -> list:
"""Layer 1: Replace old tool results with placeholders."""
tool_results = []
for msg_idx, msg in enumerate(messages):
if msg["role"] == "user" and isinstance(msg.get("content"), list):
for part_idx, part in enumerate(msg["content"]):
if isinstance(part, dict) and part.get("type") == "tool_result":
tool_results.append((msg_idx, part_idx, part))
if len(tool_results) <= KEEP_RECENT:
return messages
# Build tool_name map from assistant messages
tool_name_map = {}
for msg in messages:
if msg["role"] == "assistant":
for block in msg.get("content", []):
if hasattr(block, "type") and block.type == "tool_use":
tool_name_map[block.id] = block.name
# Clear old results (preserve read_file outputs)
to_clear = tool_results[:-KEEP_RECENT]
for _, _, result in to_clear:
if not isinstance(result.get("content"), str) or len(result["content"]) <= 100:
continue
tool_id = result.get("tool_use_id", "")
tool_name = tool_name_map.get(tool_id, "unknown")
if tool_name in PRESERVE_RESULT_TOOLS:
continue
result["content"] = f"[Previous: used {tool_name}]"
return messages
def auto_compact(messages: list) -> list:
"""Layer 2: Save transcript, summarize, replace messages."""
TRANSCRIPT_DIR.mkdir(exist_ok=True)
transcript_path = TRANSCRIPT_DIR / f"transcript_{int(time.time())}.jsonl"
with open(transcript_path, "w") as f:
for msg in messages:
f.write(json.dumps(msg, default=str) + "\n")
# Ask LLM to summarize
conversation_text = json.dumps(messages, default=str)[-80000:]
response = client.messages.create(
model=MODEL,
messages=[{"role": "user", "content":
"Summarize this conversation for continuity. Include: "
"1) What was accomplished, 2) Current state, 3) Key decisions.\n\n" + conversation_text}],
max_tokens=2000,
)
summary = next((block.text for block in response.content if hasattr(block, "text")), "No summary.")
return [{"role": "user", "content": f"[Compressed. Transcript: {transcript_path}]\n\n{summary}"}]
```
--------------------------------
### Create PDF from Markdown using pandoc
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/pdf/SKILL.md
Convert Markdown files to PDF using pandoc. For custom styling or specific PDF engines like xelatex, use appropriate flags.
```bash
# Using pandoc
pandoc input.md -o output.pdf
# With custom styling
pandoc input.md -o output.pdf --pdf-engine=xelatex -V geometry:margin=1in
```
--------------------------------
### Initialize TaskManager
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
Initializes the TaskManager with a directory for task files and determines the next available task ID. Ensures the task directory exists.
```python
class TaskManager:
def __init__(self, tasks_dir: Path):
self.dir = tasks_dir
self.dir.mkdir(exist_ok=True)
self._next_id = self._max_id() + 1
```
--------------------------------
### Run Worktree Task Isolation Script
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s12-worktree-task-isolation.md
Navigate to the project directory and execute the Python script to demonstrate worktree task isolation.
```sh
cd learn-claude-code
python agents/s12_worktree_task_isolation.py
```
--------------------------------
### Implement MessageBus for Async Communication
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
Uses JSONL files as mailboxes for teammates. Requires a valid inbox directory path.
```python
VALID_MSG_TYPES = {"message", "broadcast", "shutdown_request", "shutdown_response", "plan_approval_response"}
class MessageBus:
def __init__(self, inbox_dir: Path):
self.dir = inbox_dir
self.dir.mkdir(parents=True, exist_ok=True)
def send(self, sender: str, to: str, content: str, msg_type: str = "message", extra: dict = None) -> str:
if msg_type not in VALID_MSG_TYPES:
return f"Error: Invalid type '{msg_type}'"
msg = {"type": msg_type, "from": sender, "content": content, "timestamp": time.time()}
if extra:
msg.update(extra)
inbox_path = self.dir / f"{to}.jsonl"
with open(inbox_path, "a") as f:
f.write(json.dumps(msg) + "\n")
return f"Sent {msg_type} to {to}"
def read_inbox(self, name: str) -> list:
inbox_path = self.dir / f"{name}.jsonl"
if not inbox_path.exists():
return []
messages = [json.loads(line) for line in inbox_path.read_text().strip().splitlines() if line]
inbox_path.write_text("") # Drain inbox
return messages
def broadcast(self, sender: str, content: str, teammates: list) -> str:
count = sum(1 for name in teammates if name != sender and self.send(sender, name, content, "broadcast"))
return f"Broadcast to {count} teammates"
BUS = MessageBus(WORKDIR / ".team" / "inbox")
```
--------------------------------
### Run Sub-agent with Specific Tools
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
This function spawns a sub-agent with a defined set of tools and a fresh context. It iteratively calls the agent, processes tool uses, and returns a summary. The child agent's context is discarded after execution.
```python
CHILD_TOOLS = [
{"name": "bash", "description": "Run a shell command.",
"input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
{"name": "read_file", "description": "Read file contents.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
{"name": "write_file", "description": "Write content to file.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
]
def run_subagent(prompt: str) -> str:
"""Spawn subagent with fresh context, return only summary."""
sub_messages = [{"role": "user", "content": prompt}] # Fresh context
for _ in range(30): # Safety limit
response = client.messages.create(
model=MODEL, system=SUBAGENT_SYSTEM, messages=sub_messages,
tools=CHILD_TOOLS, max_tokens=8000,
)
sub_messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
results = []
for block in response.content:
if block.type == "tool_use":
handler = TOOL_HANDLERS.get(block.name)
output = handler(**block.input) if handler else f"Unknown tool: {block.name}"
results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(output)[:50000]})
sub_messages.append({"role": "user", "content": results})
# Only final text returns - child context is discarded
return "".join(b.text for b in response.content if hasattr(b, "text")) or "(no summary)"
# Add task tool for parent
TOOL_HANDLERS["task"] = lambda **kw: run_subagent(kw["prompt"])
```
--------------------------------
### Define Tool Handlers and Schemas
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
Maps tool names to execution functions and defines the input schemas for the agent's available tools.
```python
# Dispatch map: {tool_name: handler}
TOOL_HANDLERS = {
"bash": lambda **kw: run_bash(kw["command"]),
"read_file": lambda **kw: run_read(kw["path"], kw.get("limit")),
"write_file": lambda **kw: run_write(kw["path"], kw["content"]),
"edit_file": lambda **kw: run_edit(kw["path"], kw["old_text"], kw["new_text"]),
}
TOOLS = [
{"name": "bash", "description": "Run a shell command.",
"input_schema": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
{"name": "read_file", "description": "Read file contents.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "limit": {"type": "integer"}}, "required": ["path"]}},
{"name": "write_file", "description": "Write content to file.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
{"name": "edit_file", "description": "Replace exact text in file.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "old_text": {"type": "string"}, "new_text": {"type": "string"}}, "required": ["path", "old_text", "new_text"]}},
]
```
--------------------------------
### Implement Basic TypeScript MCP Server
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
A template for creating an MCP server in TypeScript using request handlers for tools.
```typescript
// src/index.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server({
name: "my-server",
version: "1.0.0",
});
// Define tools
server.setRequestHandler("tools/list", async () => ({
tools: [
{
name: "hello",
description: "Say hello to someone",
inputSchema: {
type: "object",
properties: {
name: { type: "string", description: "Name to greet" },
},
required: ["name"],
},
},
],
}));
server.setRequestHandler("tools/call", async (request) => {
if (request.params.name === "hello") {
const name = request.params.arguments.name;
return { content: [{ type: "text", text: `Hello, ${name}!` }] };
}
throw new Error("Unknown tool");
});
// Start server
const transport = new StdioServerTransport();
server.connect(transport);
```
--------------------------------
### Command to Run TodoWrite Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s03-todo-write.md
Execute this command in the terminal to run the s03_todo_write.py agent. This is useful for testing the agent's ability to manage multi-step tasks.
```sh
cd learn-claude-code
python agents/s03_todo_write.py
```
--------------------------------
### Harness Comparison Diagram
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/README.md
Comparison between the learn-claude-code harness and the claw0 proactive harness.
```text
learn-claude-code claw0
(agent harness core: (proactive always-on harness:
loop, tools, planning, heartbeat, cron, IM channels,
teams, worktree isolation) memory, soul personality)
```
--------------------------------
### Define Parent Tools with Task Dispatch
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s04-subagent.md
Extends base child tools with a 'task' tool for spawning subagents. This tool takes a prompt to initialize the subagent's task.
```python
PARENT_TOOLS = CHILD_TOOLS + [
{"name": "task",
"description": "Spawn a subagent with fresh context.",
"input_schema": {
"type": "object",
"properties": {"prompt": {"type": "string"}},
"required": ["prompt"],
}},
]
```
--------------------------------
### Initialize BackgroundManager
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s08-background-tasks.md
Defines the structure for tracking tasks and managing thread-safe notifications.
```python
class BackgroundManager:
def __init__(self):
self.tasks = {}
self._notification_queue = []
self._lock = threading.Lock()
```
--------------------------------
### Agent Loop with Context Compression
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s06-context-compact.md
Integrates the three compression layers into the main agent loop. Micro-compact is applied every turn, auto-compact is triggered by token thresholds, and manual compact can be invoked explicitly.
```python
def agent_loop(messages: list):
while True:
micro_compact(messages) # Layer 1
if estimate_tokens(messages) > THRESHOLD:
messages[:] = auto_compact(messages) # Layer 2
response = client.messages.create(...)
# ... tool execution ...
if manual_compact:
messages[:] = auto_compact(messages) # Layer 3
```
--------------------------------
### Run Agent Script
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s01-the-agent-loop.md
Command to execute the agent loop script.
```sh
cd learn-claude-code
python agents/s01_agent_loop.py
```
--------------------------------
### Spawn Teammate
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s09-agent-teams.md
Creates a new teammate entry in the configuration and initiates its agent loop in a background thread.
```python
def spawn(self, name: str, role: str, prompt: str) -> str:
member = {"name": name, "role": role, "status": "working"}
self.config["members"].append(member)
self._save_config()
thread = threading.Thread(
target=self._teammate_loop,
args=(name, role, prompt), daemon=True)
thread.start()
return f"Spawned teammate '{name}' (role: {role})"
```
--------------------------------
### Python Plan Review and Approval
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s10-team-protocols.md
Handles the review and approval of a submitted plan. Updates the plan status and sends a response back to the originator.
```python
def handle_plan_review(request_id, approve, feedback=""):
req = plan_requests[request_id]
req["status"] = "approved" if approve else "rejected"
BUS.send("lead", req["from"], feedback,
"plan_approval_response",
{"request_id": request_id, "approve": approve})
```
--------------------------------
### Integrate SkillLoader into Agent
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s05-skill-loading.md
Injects skill descriptions into the system prompt and registers the load_skill tool handler.
```python
SYSTEM = f"""You are a coding agent at {WORKDIR}.
Skills available:
{SKILL_LOADER.get_descriptions()}"""
TOOL_HANDLERS = {
# ...base tools...
"load_skill": lambda **kw: SKILL_LOADER.get_content(kw["name"]),
}
```
--------------------------------
### Create Parallel Task Board
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/docs/en/s07-task-system.md
Define a task board for refactoring with parallelizable steps: parse -> transform -> emit -> test. Transform and emit can run concurrently after parse.
```sh
4. `Create a task board for refactoring: parse -> transform -> emit -> test, where transform and emit can run in parallel after parse`
```
--------------------------------
### Code Review CLI Commands
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/code-review/SKILL.md
Utility commands for inspecting changes, searching for markers, and checking project health.
```bash
# Show recent changes
git diff HEAD~5 --stat
git log --oneline -10
# Find potential issues
grep -rn "TODO\|FIXME\|HACK\|XXX" .
grep -rn "password\|secret\|token" . --include="*.py"
# Check complexity (Python)
pip install radon && radon cc . -a
# Check dependencies
npm outdated # Node
pip list --outdated # Python
```
--------------------------------
### Register MCP Server with Claude
Source: https://github.com/shareai-lab/learn-claude-code/blob/main/skills/mcp-builder/SKILL.md
Configuration format for adding a local MCP server to the Claude configuration file.
```json
{
"mcpServers": {
"my-server": {
"command": "python3",
"args": ["/path/to/my_server.py"]
}
}
}
```
--------------------------------
### SkillLoader for On-Demand Knowledge
Source: https://context7.com/shareai-lab/learn-claude-code/llms.txt
This class implements a two-layer skill injection mechanism to avoid bloating the system prompt. It loads skill names and descriptions for the system prompt (Layer 1) and full skill bodies when requested via tool results (Layer 2).
```python
import re
import yaml
class SkillLoader:
def __init__(self, skills_dir: Path):
self.skills_dir = skills_dir
self.skills = {}
self._load_all()
def _load_all(self):
if not self.skills_dir.exists():
return
for f in sorted(self.skills_dir.rglob("SKILL.md")):
text = f.read_text()
meta, body = self._parse_frontmatter(text)
name = meta.get("name", f.parent.name)
self.skills[name] = {"meta": meta, "body": body, "path": str(f)}
def _parse_frontmatter(self, text: str) -> tuple:
match = re.match(r"^---\n(.*?)\n---\n(.*)", text, re.DOTALL)
if not match:
return {},
text
try:
meta = yaml.safe_load(match.group(1)) or {}
except yaml.YAMLError:
meta = {}
return meta, match.group(2).strip()
def get_descriptions(self) -> str:
"""Layer 1: Short descriptions for system prompt."""
if not self.skills:
return "(no skills available)"
lines = []
for name, skill in self.skills.items():
desc = skill["meta"].get("description", "No description")
lines.append(f" - {name}: {desc}")
return "\n".join(lines)
def get_content(self, name: str) -> str:
"""Layer 2: Full skill body in tool_result."""
skill = self.skills.get(name)
if not skill:
return f"Error: Unknown skill '{name}'. Available: {', '.join(self.skills.keys())}"
return f"
{skill['body']}
"
# Usage
SKILL_LOADER = SkillLoader(WORKDIR / "skills")
SYSTEM = f"""You are a coding agent. Use load_skill to access specialized knowledge.
Skills available:
{SKILL_LOADER.get_descriptions()}"""
TOOL_HANDLERS["load_skill"] = lambda **kw: SKILL_LOADER.get_content(kw["name"])
```