Code-Agents-Playbook
Health Warn
- No license — Repository has no license file
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 5 GitHub stars
Code Pass
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Pass
- Permissions — No dangerous permissions requested
This project is an educational playbook and reference architecture for building AI code agents. It provides documentation, architecture patterns, and runnable Python code samples derived from analyzing the Claude Code CLI.
Security Assessment
The overall security risk is Low. The automated code scan reviewed 12 files and found no dangerous patterns, hardcoded secrets, or requests for dangerous permissions. The repository is strictly a reference guide containing Markdown documentation and basic Python samples rather than a functional application or server. Because it does not actively execute shell commands or connect to external networks on its own, it poses minimal direct threats to your system.
Quality Assessment
The project is highly active, with its most recent updates pushed today. However, there are significant concerns regarding maturity and intellectual property. It lacks a standard open-source license, which means you do not have explicit legal permission to use, modify, or distribute the provided code samples. Additionally, the repository has very low community visibility with only 5 stars, indicating it has not been widely peer-reviewed or tested by a broader developer audience.
Verdict
Safe to use for educational reading, but use with caution if you plan to implement the unlicensed code samples in a production environment.
Playbook for building production-grade AI code agents with architecture patterns distilled from Claude Code
Code Agents Playbook
A deep dissection of Claude Code's architecture for engineers building AI code agents
What This Is
Educational material derived from analysis of the Claude Code CLI (~200K LOC TypeScript). It is not a clone, tutorial, or product — it is a reference architecture for production AI code agents (patterns, design trade-offs, runnable Python in code-samples/). No Claude Code source — all code here is original to this repo (docs, diagrams, and code-samples/).
Chapter structure (same across all parts — from intuition to detail):
| Section | What you get |
|---|---|
| Overview | What the subsystem does and why it matters, in plain language. |
| How it fits together | Architecture, data flow, and mermaid diagrams — how the pieces connect. |
| Production concepts | Practices and mechanisms inferred from analysis of Claude Code. |
| Key design decisions | Trade-offs and non-obvious choices. |
| Insights | Gotchas, edge cases, and lessons worth remembering. |
| Code samples | Links to runnable Python in code-samples/ for that chapter. |
| Build your own | Concrete steps to reuse the pattern in your own system. |
Reading order within a chapter is easier at the top (Overview) and more specific toward the bottom (Insights, samples, Build your own).
Who This Is For
- Engineers building their own code agents — use this as a blueprint
- AI agents consuming this as documentation for building custom systems — see AGENTS.md
- Anyone curious about how a production LLM tool system works under the hood
How to use this material
| Audience | Suggested path |
|---|---|
| Learning (human) | Read each chapter top to bottom: Overview → How it fits → Key design decisions → Insights. Run code-samples/*.py to see patterns as code. |
| Building a production agent (human or AI) | Start with AGENTS.md: principles, anti-patterns, concept→chapter index, and staged build steps. Use each chapter’s Build your own as a checklist; cross-check Production … (concepts) bullets against your design. |
Mission & Contributing
Mission: Grow into a full Playbook for reliable, production-grade open-source coding agents — one reference for architecture, safety, operations, and implementation patterns instead of scattered tribal knowledge.
Contributing: Extend chapters, propose edits, fix mistakes, clarify text, or improve code-samples; issues and pull requests keep this resource accurate for everyone building coding agents in the open.
How to Read This
The chapters are ordered from fundamentals to advanced topics. Each chapter is self-contained but builds on earlier concepts.
| Part | Chapters | Focus |
|---|---|---|
| I — Foundations | 01–04 | The skeleton: agent loop, tools, permissions, prompts |
| II — Core Systems | 05–09 | The organs: tool implementations, streaming, context, memory, MCP |
| III — Advanced Patterns | 10–13 | The nervous system: subagents, multi-agent, skills, hooks |
| IV — Production | 14–16 | The skin: startup, cost tracking, IDE integration |
Recommended path: Read Part I first. Then jump to whichever Part II–IV chapter matches what you're building.
Table of Contents
Part I: Foundations
| # | Chapter | Description |
|---|---|---|
| 01 | The Agent Loop | Generator-based state machine that drives the entire agent. The heartbeat. |
| 02 | The Tool System | How tools are defined, registered, validated, and executed concurrently. |
| 03 | The Permission System | Four permission modes, speculative classification, and frozen contexts. |
| 04 | System Prompt Engineering | Priority-based prompt assembly, context injection, and cache-safe forking. |
Part II: Core Systems
| # | Chapter | Description |
|---|---|---|
| 05 | Tool Implementations | Deep dive into Bash, FileEdit, and Search tools — security, validation, patterns. |
| 06 | Streaming & Messages | Message type hierarchy, SSE streaming, normalization for the API. |
| 07 | Context Management | Compaction strategies, token budgets, circuit breakers, and cache interactions. |
| 08 | Memory System | Scoped persistent memory, auto-extraction, team sync, and CLAUDE.md. |
| 09 | MCP Integration | Model Context Protocol: connections, config merging, deferred tool discovery. |
Part III: Advanced Patterns
| # | Chapter | Description |
|---|---|---|
| 10 | Subagents | Nested agent spawning, tool filtering, cache sharing, sidechain transcripts. |
| 11 | Multi-Agent Coordination | Teammates, file-based mailboxes, leader bridge, AsyncLocalStorage isolation. |
| 12 | Skills & Plugins | Frontmatter-based skills, plugin manifests, argument substitution. |
| 13 | Hooks & Lifecycle | Event-driven hook registry with agent, HTTP, and prompt execution backends. |
Part IV: Production
| # | Chapter | Description |
|---|---|---|
| 14 | Startup Optimization | Parallelized boot, feature gates, lazy loading, API preconnect. |
| 15 | Cost & Observability | Per-model token tracking, PII-safe analytics, OpenTelemetry integration. |
| 16 | IDE Bridge | VS Code/JetBrains integration, session management, JWT auth, transport protocol. |
Architecture Overview
┌─────────────────────────────────────────────────────────────────┐
│ USER / IDE │
│ (Terminal, VS Code, JetBrains) │
└──────────────┬──────────────────────────────┬───────────────────┘
│ Input │ Bridge Protocol
▼ ▼
┌──────────────────────┐ ┌─────────────────────────┐
│ REPL / React+Ink │◄──────►│ IDE Bridge │
│ (screens, input, │ │ (JWT, sessions, │
│ permissions UI) │ │ transport) │
└──────────┬───────────┘ └─────────────────────────┘
│ handlePromptSubmit()
▼
┌──────────────────────────────────────────────────────────────┐
│ QUERY ENGINE │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ query() — async generator loop │ │
│ │ │ │
│ │ ┌──────────┐ ┌───────────┐ ┌────────────────┐ │ │
│ │ │ API Call │───►│ Stream │───►│ Tool Execution │ │ │
│ │ │ (retry, │ │ (SSE, │ │ (concurrent, │ │ │
│ │ │ fallback)│ │ thinking)│ │ permissions) │ │ │
│ │ └──────────┘ └───────────┘ └───────┬────────┘ │ │
│ │ ▲ │ │ │
│ │ └────────────────────────────────────┘ │ │
│ │ LOOP until end_turn / max turns │ │
│ └────────────────────────────────────────────────────────┘ │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ Compaction │ │ Token │ │ Recovery │ │
│ │ (full/micro/ │ │ Budget │ │ (collapse → │ │
│ │ partial) │ │ Tracking │ │ compact → │ │
│ │ │ │ │ │ max_tokens) │ │
│ └──────────────┘ └──────────────┘ └──────────────────┘ │
└──────────────────────────────────────────────────────────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌──────────────────────────────┐
│ TOOLS │ │ SERVICES │
│ ┌───────────────┐ │ │ ┌────────┐ ┌───────────┐ │
│ │ BashTool │ │ │ │ MCP │ │ Memory │ │
│ │ FileEditTool │ │ │ │ Client │ │ (memdir, │ │
│ │ FileReadTool │ │ │ └────────┘ │ extract) │ │
│ │ GrepTool │ │ │ ┌────────┐ └───────────┘ │
│ │ AgentTool ────┼──┼──► │ │ OAuth │ ┌───────────┐ │
│ │ SkillTool │ │ │ └────────┘ │ Analytics │ │
│ │ MCPTool │ │ │ ┌────────┐ │ (events, │ │
│ │ SendMessage │ │ │ │ API │ │ flags) │ │
│ │ ...40+ tools │ │ │ │ Client │ └───────────┘ │
│ └───────────────┘ │ │ └────────┘ │
└─────────────────────┘ └──────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ PERMISSION SYSTEM │
│ Modes: default │ plan │ auto │ bypass │
│ Rules: allow/deny lists, classifiers │
│ Handlers: interactive, coordinator, │
│ swarm worker │
└─────────────────────────────────────────┘
Key Principles Extracted from Claude Code
- Generator-based loops —
async function* for streaming, backpressure, and cancellation - Immutable permission contexts — freeze with
DeepImmutable<>to prevent self-modification - Cache-safe forking — share rendered system prompt bytes, not prompt builders
- Feature gates — compile-time dead code elimination via
feature()flags - File-based coordination — disk I/O over IPC for cross-process durability
- PII safety at the type level — verbose type names force conscious verification
- Recovery cascades — try the cheapest fix first, escalate to expensive
- Speculative work — run classifiers/prefetch during blocking operations
- Task budget after compaction — keep API-side
task_budget.remainingaligned with the client when autocompact hides prior context - Tool continuation from blocks — treat assembled
tool_useblocks as the signal to continue, notstop_reasonalone
Tech Stack (Original)
| Category | Technology |
|---|---|
| Runtime | Bun |
| Language | TypeScript (strict) |
| Terminal UI | React + Ink |
| CLI Parsing | Commander.js |
| Schema Validation | Zod v4 |
| Code Search | ripgrep |
| Protocols | MCP SDK, LSP |
| API | Anthropic SDK |
| Telemetry | OpenTelemetry + gRPC |
| Feature Flags | GrowthBook |
| Auth | OAuth 2.0, JWT, macOS Keychain |
Code Samples
Every chapter includes runnable Python code samples that implement the patterns from Claude Code, adapted to Python idioms:
asynciofor async generatorspydanticfor schema validationcontextvarsfor context isolationdataclasses/Protocolfor tool contracts
These are educational implementations — simplified but faithful to the original design.
Run the samples: from the repository root, install dependencies once with pip install -r docs/code-samples-requirements.txt, then run any sample with python3 docs/<chapter-folder>/code-samples/<file>.py (or python if that is your interpreter).
Disclaimer
This educational material is based on analysis of Claude Code CLI source code that was publicly exposed via a source map file in the npm registry on March 31, 2026. All original source code is the property of Anthropic. This repository is unofficial and not affiliated with Anthropic.
The purpose is strictly educational: understanding patterns, architecture, and design decisions in production AI agent systems. Code samples in this repository are original Python implementations inspired by the patterns — not copies of the proprietary TypeScript source.
Built with curiosity. Powered by reverse engineering.
Reviews (0)
Sign in to leave a review.
Leave a reviewNo results found