Key Source Files in learn-claude-code: A Complete Guide to the Agents Framework

The 13 Python files in the agents/ directory implement a progressive curriculum for building autonomous coding agents, from basic LLM loops to full multi-agent orchestration with background processing and Git work-tree isolation.

The shareAI-lab/learn-claude-code repository provides a modular, pedagogical framework for constructing Claude-powered autonomous agents. Understanding the key source files in learn-claude-code reveals an architecture where each script (s01 through s12) teaches a specific capability, culminating in s_full.py which composes all features into a production-ready reference agent.

Foundation: The Core Agent Loop (s01-s04)

s01_agent_loop.py - Basic REPL Implementation

The file agents/s01_agent_loop.py establishes the fundamental interaction pattern: a persistent LLM → tool → feedback loop. It initializes a static SYSTEM prompt that binds the model to the current working directory, reads the Anthropic model ID from the MODEL_ID environment variable, and repeatedly calls client.messages.create with an accumulated messages list. When the LLM returns tool_use blocks, the script executes them (currently limited to a sandboxed bash tool) and appends tool_result blocks to the conversation history.

s02_tool_use.py - Tool Dispatch Framework

agents/s02_tool_use.py extends the core loop with a comprehensive tool dispatch system. It defines a TOOL_HANDLERS dictionary that maps tool names to native Python functions, adding file-system operations (read_file, write_file, edit_file) alongside the existing bash command. The message flow remains identical to s01, but the handler registry enables modular capability expansion.

s03_todo_write.py - Task Checklist Management

The todo management system resides in agents/s03_todo_write.py, which implements the TodoManager class. This utility parses, validates, and renders markdown-style todo lists, providing the TodoWrite tool that agents invoke to maintain short-term checklists during execution.

s04_subagent.py - Sub-Agent Execution Pattern

agents/s04_subagent.py introduces hierarchical agent execution through the run_subagent() function. This spawns short-lived "child" LLM instances that operate with their own isolated tool sets, enabling delegation of sub-tasks without polluting the parent agent's conversation context.

State Management and Context Control (s05-s08)

s05_skill_loading.py - Skill System

The skill loading mechanism in agents/s05_skill_loading.py parses markdown files from skills/*/SKILL.md, extracts YAML front-matter metadata, and makes structured documentation available via the load_skill tool. This allows agents to dynamically load domain-specific knowledge bases.

s06_context_compact.py - Memory Management

agents/s06_context_compact.py solves token limit constraints through two compression strategies: microcompact() (which prunes old tool-result payloads while preserving critical context) and auto_compact() (which summarizes the full conversation history and stores a transcript). These functions automatically trigger when approaching model context windows.

s07_task_system.py - Persistent Task Tracking

The task management system in agents/s07_task_system.py implements the TaskManager class, which persists long-running work items as JSON files in the .tasks/ directory. It provides CRUD operations through tools like task_create, task_update, and task_list, enabling agents to maintain state across separate conversation sessions.

s08_background_tasks.py - Asynchronous Execution

agents/s08_background_tasks.py provides the BackgroundManager class for daemon-thread execution of long-running shell commands. It offers background_run for initiation, check_background for status polling, and a notification queue that injects completion messages into the active conversation when commands finish.

Multi-Agent Coordination and Isolation (s09-s12)

s09_message_bus.py - Inter-Agent Messaging

The message bus implementation in agents/s09_message_bus.py provides a lightweight file-based MessageBus class using JSON-lines format for inter-agent communication. This file also contains the initial TeammateManager class for spawning persistent autonomous teammates that run independent loops and claim unassigned tasks from the shared queue.

s10_shutdown_and_plan.py - Control Flow Mediation

agents/s10_shutdown_and_plan.py implements governance tools including shutdown_request and plan_approval. These mediate graceful termination and plan review workflows between lead agents and teammates, ensuring coordinated shutdowns rather than abrupt exits.

s11_autonomous_agents.py - Teammate Orchestration

agents/s11_autonomous_agents.py completes the autonomous teammate framework, providing full TeammateManager capabilities for spawning named agents (like "builder" or "researcher") that idle when no work is available, poll the task queue continuously, and execute their own tool loops in separate threads.

s12_worktree_task_isolation.py - Repository Isolation

agents/s12_worktree_task_isolation.py demonstrates Git work-tree isolation, showing how to execute tasks in separate Git work-trees. This ensures that file modifications, experimental changes, and temporary artifacts remain isolated from the main repository branch, enabling safe parallel task execution.

Full Integration: The Reference Implementation

s_full.py - Complete Agent Composition

The file agents/s_full.py serves as the comprehensive reference implementation, importing and instantiating all previous managers (TodoManager, TaskManager, BackgroundManager, MessageBus, TeammateManager). It registers every tool from s01 through s12, implements rich context handling (including background task draining, inbox message injection, and auto-compaction), and provides a REPL-driven interface for the fully-capable agent.

Practical Implementation Examples

Running the Minimal Agent Loop

Import and execute the basic loop from s01 to process a single request:

from agents.s01_agent_loop import agent_loop

history = [{"role": "user", "content": "List all .py files in the repo"}]
agent_loop(history)
print(history[-1]["content"])   # → tool result containing the `ls` output

Managing Checklists with TodoWrite

Use the integrated todo system via s_full.py:

from agents.s_full import agent_loop, TODO

prompt = "Create a todo list for implementing a new feature."
history = [{"role": "user", "content": prompt}]
agent_loop(history)

print(TODO.render())

Spawning Persistent Teammates

Create autonomous sub-agents that operate independently:

from agents.s_full import TEAM

TEAM.spawn(
    name="builder",
    role="file_editor",
    prompt="Edit README.md to add a new section about the agent architecture."
)

print(TEAM.list_all())

Executing Background Tasks

Run long operations without blocking the main conversation:

from agents.s_full import BG, agent_loop

history = [{"role": "user", "content": "Compile the project in the background."}]
agent_loop(history)

print(BG.check())

Summary

  • s01 through s04 establish the core agent loop, tool dispatch, todo management, and sub-agent patterns
  • s05 through s08 add skill loading, context compression, persistent JSON task tracking, and background execution
  • s09 through s12 enable multi-agent messaging, graceful shutdown mediation, autonomous teammate orchestration, and Git work-tree isolation
  • s_full.py composes all 12 modules into a single REPL-driven reference agent with complete capability integration
  • All agents rely on the MODEL_ID environment variable and a static SYSTEM prompt bound to the working directory

Frequently Asked Questions

What is the difference between the todo system and the task system?

s03_todo_write.py implements TodoManager for ephemeral, markdown-style checklists that exist only during a single conversation session, while s07_task_system.py provides TaskManager for persistent JSON-based tasks stored in .tasks/ that survive across agent restarts and can be claimed by autonomous teammates.

How does context compaction prevent token limit errors?

According to the source in agents/s06_context_compact.py, the system uses microcompact() to surgically remove old tool-result payloads while keeping conversation structure intact, and auto_compact() to generate full conversation summaries when approaching context limits, storing transcripts for later reference without losing critical execution history.

Which file should I run to use the complete agent?

Import agents/s_full.py, which instantiates all managers (todo, tasks, background, messaging, teammates) and registers every tool from the curriculum, providing the full autonomous-agent experience in a single REPL interface.

How do sub-agents differ from teammates?

s04_subagent.py provides run_subagent() for spawning short-lived, single-use child LLMs that terminate after one task, while s11_autonomous_agents.py implements TeammateManager for spawning persistent, named agents (like "builder") that run continuous loops, poll for work independently, and maintain state across multiple task executions.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →