Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

learn-claude-code-java

A Java port of learn-claude-code — an educational project that progressively teaches AI agent architecture by building a Claude-powered coding agent. Each session (S01–S12) is a standalone CLI REPL demonstrating one agent pattern, culminating in SFull which combines all features.

中文文档

Quick Start

# 1. Configure environment
cp env.properties.example src/main/resources/env.properties
# Edit env.properties with your ANTHROPIC_API_KEY and MODEL_ID

# 2. Build
mvn compile

# 3. Run any session
mvn exec:java -Dexec.mainClass="com.bamboo.agents.S01AgentLoop"

Requires Java 21+.

Sessions

S01 — Agent Loop

The foundational pattern: call LLM, execute tool, feed result back, repeat until the model stops. Ships with a single bash tool.

Core pattern:

while stop_reason == "tool_use":
    response = LLM(messages, tools)
    execute tools
    append results

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S01AgentLoop"


S02 — Tool Dispatch

The loop stays the same — we just add tools. Introduces readFile, writeFile, editFile with a ToolWrapper dispatch map and PathUtils path-traversal protection.

Core pattern: Map<String, ToolWrapper<?>> TOOL_HANDLERS

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S02ToolUse"


S03 — Todo Tracking

The agent tracks its own progress via TodoManager. A nag reminder (<reminder>) is injected when the agent goes 3+ rounds without updating its todo list.

Core pattern: self-tracking progress + nag reminder

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S03ToDoWrite"


S04 — Subagent

The parent spawns a child agent with a fresh messages=[] context. The child shares the filesystem but not the conversation, and returns only a summary. Parent context stays clean.

Core pattern: process isolation gives context isolation for free

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S04Subagent"


S05 — Skill Loading

Two-layer skill injection to avoid bloating the system prompt:

  • Layer 1 (cheap): skill names and descriptions in system prompt (~100 tokens/skill)
  • Layer 2 (on demand): full skill body returned when model calls loadSkill

Skill files live in src/main/resources/skills/ with YAML frontmatter.

Core pattern: don't put everything in the system prompt — load on demand

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S05SkillLoading"


S06 — Context Compression

Three-layer compression pipeline so the agent can work forever:

  • Layer 1 — micro_compact (silent, every turn): replace old tool results (beyond last 3) with placeholders
  • Layer 2 — auto_compact (automatic, when tokens exceed threshold): save transcript to .transcripts/, ask LLM to summarize, replace all messages with summary
  • Layer 3 — compact (manual, model-triggered): model calls compact tool, same effect as auto_compact

Core pattern: the agent can forget strategically and keep working

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S06ContextCompact"


S07 — Task System

Tasks persist as JSON files in .tasks/, surviving context compression. Each task has a dependency graph (blockedBy / blocks); completing a task unblocks downstream tasks.

Tools: taskCreate, taskUpdate, taskList, taskGet

Core pattern: state that survives compression — because it's outside the conversation

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S07TaskSystem"


S08 — Background Tasks

Run commands in background threads. backgroundRun returns a task_id immediately without blocking. A notification queue is drained before each LLM call to deliver results.

Tools: backgroundRun, checkBackground

Core pattern: fire and forget — the agent doesn't block

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S08BackgroundTasks"


S09 — Agent Teams

Persistent named agents communicating via JSONL file-based inboxes. Each teammate runs its own agent loop in a separate thread.

Subagent (S04) vs Teammate (S09):

  • Subagent: spawn -> execute -> return summary -> destroyed
  • Teammate: spawn -> work -> idle -> work -> ... -> shutdown

Tools: spawnTeammate, sendMessage, broadcast, readInbox, listTeammates. REPL: /team, /inbox

Core pattern: teammates that can talk to each other

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S09AgentTeams"


S10 — Team Protocols

Two protocols built on S09's messaging, both using the same request_id correlation pattern:

  • Shutdown Protocol: lead sends shutdown_request, teammate approves via shutdown_response for graceful shutdown
  • Plan Approval Protocol: teammate submits plan, lead approves or rejects before execution

Tools: shutdownRequest, shutdownResponse, planApproval

Core pattern: same request_id correlation, two domains

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S10TeamProtocols"


S11 — Autonomous Agents

When idle, teammates automatically find work:

  1. Check inbox -> message found -> resume work
  2. Scan .tasks/ -> unclaimed task found -> claim it -> resume work
  3. Timeout after 60s -> shutdown

Identity is re-injected after context compression. Tool: claimTask

Core pattern: the agent finds work itself

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S11AutonomousAgents"


S12 — Worktree Task Isolation

Directory-level isolation for parallel task execution using Git Worktrees. Tasks are the control plane, worktrees are the execution plane.

Full worktree lifecycle: worktreeCreate, worktreeList, worktreeStatus, worktreeRun, worktreeKeep, worktreeRemove. Bind tasks with taskBindWorktree.

Core pattern: isolate by directory, coordinate by task ID

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.S12WorktreeTaskIsolation"


SFull — Full Agent

The capstone combining every mechanism from S01–S11:

  • Full tool set (bash, file ops, todo, skill, compact, background, task, team)
  • Three-layer context compression
  • Background notification drain
  • Inbox checking
  • Teammate auto-work-wait
  • Todo nag reminder
  • Subagent + persistent teammates
  • Shutdown / plan approval protocols

REPL commands: /compact, /tasks, /team, /inbox

Run: mvn exec:java -Dexec.mainClass="com.bamboo.agents.SFull"

Project Structure

src/main/java/com/bamboo/
  agents/          # Agent classes with main() entry points (interactive REPLs)
    Base.java      # Base class: Anthropic client init, config loading, addAssistants()
    S01-S12, SFull # Session implementations
  constant/        # Property key constants
  util/            # Utilities
    ToolWrapper         # Dispatch: JsonValue -> typed record -> Function<T, String>
    TeammateToolWrapper # Team extension: injects sender/member
    PathUtils           # File ops + path-traversal protection
    EnhancedBashExecutor# Bash command execution
    SkillLoader         # Skill file loading
    TodoManager         # In-memory todo tracking
    TaskManager         # Persistent task management (.tasks/)
    BackgroundManager   # Background threads + notification queue
    MessageBus          # JSONL inbox messaging
    TeammateManager*    # Teammate lifecycle (S09/S10/S11 variants)
    EventBus            # Event logging
    WorktreeManager     # Git Worktree management

Key Conventions

  • Tool inputs are Java records (e.g., BashCommand, ReadCommand, WriteCommand, EditCommand)
  • PathUtils.safePath() enforces path-traversal protection on all file operations
  • Skills are markdown files in src/main/resources/skills/ with YAML frontmatter
  • The work/ directory contains the original Python reference implementations

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages