# You Could've Invented Claude Code
**作者**: nader dabit
**日期**: 2026-01-09T16:47:38.000Z
**来源**: [https://x.com/dabit3/status/2009668398691582315](https://x.com/dabit3/status/2009668398691582315)
---

What makes Claude Code powerful is surprisingly simple: it's a loop that lets an AI read files, run commands, and iterate until a task is done.
The complexity comes from handling edge cases, building a good UX, and integrating with real development workflows.
In this post, I'll start from scratch and build up to Claude Code's architecture step by step, showing how you could have invented it yourself from first principles, using nothing but a terminal, an LLM API, and the desire to make AI actually useful.
## End goal: learn how powerful agents work, so you can build your own
First, let's establish the problem we're trying to solve.
When you use ChatGPT or Claude in a browser, you're doing a lot of manual labor:
- Copy-paste code from the chat into files
- Run commands yourself, then copy errors back
- Provide context by uploading files or pasting content
- Manually iterate through the fix-test-debug cycle
You're essentially acting as the AI's hands. The AI thinks; you execute.
What if the AI could execute too?
Imagine telling an AI: "Fix the bug in auth.py" and walking away. When you come back, the bug is fixed. The AI read the file, understood it, tried a fix, ran the tests, saw them fail, tried another approach, and eventually succeeded.
This is what an agent does. It's an AI that can:
Take actions in the real world (read files, run commands)
Observe the results
Decide what to do next
Repeat until the task is complete
Let's build one from scratch.
## The Simplest Possible Agent
Let's start with the absolute minimum: an AI that can run a single bash command.
Usage
This is... not very useful. The AI can suggest one command, then you're back to doing everything manually.
But here's the key insight: what if we put this in a loop?
## Goal: Creating the agent loop
The fundamental insight behind all AI agents is the agent loop:
Let's implement exactly this. The AI needs to tell us:
- What action to take
- Whether it's done
We'll use a simple JSON format:
Now we have something that can actually iterate:
The AI ran two commands and then told us it was done. We've created an agent loop!
But wait! We're executing arbitrary commands with no safety checks. The AI could rm -rf / and we'd blindly execute it.
## Goal: Adding permission controls
Let's add a human-in-the-loop for dangerous operations. First, we define a function that wraps command execution with a safety check:
Then, inside the agent loop, we replace the direct eval call with our new function:
That's it! The function sits between the AI's request and actual execution, giving you a chance to block dangerous commands. When denied, you can feed that back to the AI so it can try a different approach.
Try it out:
Type y to allow the deletion, or n to block it.
This is the beginning of a permission system. Claude Code takes this much further with:
- Tool-specific permissions (file edits vs. bash commands)
- Pattern-based allowlists (Bash(npm test:*) allows any npm test command)
- Session-level "accept all" modes for when you trust the AI
The key insight: the human should be able to control what the AI can do, but with enough granularity that it's not annoying.
## Goal: Beyond bash - Adding tools
Running bash commands is powerful, but it's also:
- Dangerous: unlimited access to the system
- Inefficient: reading a file shouldn't spawn a subprocess
- Imprecise: output parsing is fragile
What if we gave the AI structured tools instead?
We'll switch to Python here since it handles JSON and API calls more cleanly:
Now we're using Anthropic's native tool use API. This is much better because:
Type safety: the AI knows exactly what parameters each tool accepts
Explicit actions: reading a file is a read_file call, not cat
Controlled surface area: we decide what tools exist
Try it out:
## Goal: Making edits precise
Our write_file tool has a problem: it replaces the entire file. If the AI makes a small change to a 1000-line file, it has to output all 1000 lines. This is:
- Expensive: more output tokens = more cost
- Error-prone: the AI might accidentally drop lines
- Slow: generating that much text takes time
What if we had a tool for surgical edits?
Implementation:
This is exactly how Claude Code's str_replace tool works. The requirement for uniqueness might seem annoying, but it's actually a feature:
- Forces the AI to include enough context to be unambiguous
- Creates a natural diff that's easy for humans to review
- Prevents accidental mass replacements
## Goal: Searching the Codebase
So far our agent can read files it knows about. But what about a task like "find where the authentication bug is"?
The AI needs to search the codebase. Let's add tools for that.
Now the AI can:
glob("**/*.py") → Find all Python files
grep("def authenticate", "src/") → Find authentication code
read_file("src/auth.py") → Read the relevant file
edit_file(...) → Fix the bug
This is the pattern: give the AI tools to explore, and it can navigate codebases it's never seen before.
## Goal: Context management
Here's a problem you'll hit quickly: context windows are finite.
If you're working on a large codebase, the conversation might look like:
- User: "Fix the bug in authentication"
- AI: reads 10 files, runs 20 commands, tries 3 approaches
- ...conversation is now 100,000 tokens
- AI: runs out of context and starts forgetting earlier information
How do we handle this?
Option 1: summarization (compaction)
When context gets too long, summarize what happened:
Option 2: sub-agents (delegation)
For complex tasks, spawn a sub-agent with its own context:
This is why Claude Code has the concept of subagents: specialized agents that handle focused tasks in their own context, returning just the results.
## Goal: the system prompt
We've been glossing over something important: how does the AI know how to behave?
The system prompt is where you encode:
- The AI's identity and capabilities
- Guidelines for tool usage
- Project-specific context
- Behavioral rules
Here's a simplified version of what makes Claude Code effective:
But here's the problem: what if the project has specific conventions? What if the team uses a particular testing framework, or has a non-standard directory structure?
## Goal: Project-Specific Context (CLAUDE.md)
Claude Code solves this with CLAUDE.md - a file at the project root that gets automatically included in context:
Now the AI knows:
- How to run tests for this project
- Where to find things
- What conventions to follow
- Known gotchas to watch out for
This is one of Claude Code's most powerful features: project knowledge that travels with the code.
## Putting it all together
Let's see what we've built. The core of an AI coding agent is this loop:
1. Setup (runs once)
- Load the system prompt with tool descriptions, behavioral guidelines, and project context (CLAUDE.md)
- Initialize an empty conversation history
2. Agent Loop (repeats until done)
- Send conversation history to the LLM
- LLM decides: use a tool or respond to user
- If tool use:
- If final answer:
That's it. Every AI coding agent, from our 50-line bash script to Claude Code, follows this pattern.
Now let's build a complete, working mini-Claude Code that you can actually use. It combines everything we've learned: the agent loop, structured tools, permission checks, and an interactive REPL:
Save this as mini-claude-code.py and run it:
Here's what a session looks like:
That's a working mini Claude Code clone in ~150 lines. It has:
- Interactive REPL: keeps conversation context between prompts
- Multiple tools: read, write, list files, run commands
- Permission checks: asks before writing files or running dangerous commands
- Conversation memory: each follow-up builds on previous context
This is essentially what Claude Code does, plus:
- A polished terminal UI
- Sophisticated permission system
- Context compaction when conversations get long
- Subagent delegation for complex tasks
- Hooks for custom automation
- Integration with git and other dev tools
## The Claude Agent SDK
If you want to build on this foundation without reinventing the wheel, Anthropic offers the Claude Agent SDK. It's the same engine that powers Claude Code, exposed as a library.
Here's what our simple agent looks like using the SDK:
The SDK handles:
- The agent loop (so you don't have to)
- All the built-in tools (Read, Write, Edit, Bash, Glob, Grep, etc.)
- Permission management
- Context tracking
- Sub-agent coordination
## What We've Learned
Starting from a simple bash script, we discovered:
The agent loop: AI decides → execute → observe → repeat
Structured tools: better than raw bash for safety and precision
Surgical edits: str_replace beats full file rewrites
Search tools: let the AI explore codebases
Context management: compaction and delegation handle long tasks
Project knowledge: CLAUDE.md gives project-specific context
Each of these emerged from a practical problem:
- "How do I make the AI do more than one thing?" → agent loop
- "How do I prevent it from destroying my system?" → permission system
- "How do I make edits efficient?" → str_replace tool
- "How does it find code it doesn't know about?" → search tools
- "What happens when context runs out?" → compaction
- "How does it know my project's conventions?" → CLAUDE.md
This is how you could have invented Claude Code. The core ideas are simple.
Again - the complexity comes from handling edge cases, building a good UX, and integrating with real development workflows.
## Next Steps
If you want to build your own agents:
Start simple: a basic agent loop with 2-3 tools
Add tools incrementally: each new capability should solve a real problem
Handle errors gracefully: tools fail; your agent should recover
Test on real tasks: the edge cases will teach you what's missing
Consider using the Claude Agent SDK: why reinvent the wheel?
The future of software development is agents that can actually do things. Now we know how they work!
Resources:
- Claude Agent SDK Documentation
- Claude Code Documentation
- Anthropic API Reference
> If you're interested in building verifiable agents, check out the work we're doing at @eigencloud here.
## 相关链接
- [nader dabit](https://x.com/dabit3)
- [@dabit3](https://x.com/dabit3)
- [309K](https://x.com/dabit3/status/2009668398691582315/analytics)
- [auth.py](https://auth.py/)
- [str_replace](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool#str-replace)
- [CLAUDE.md](https://claude.md/)
- [CLAUDE.md](https://claude.md/)
- [CLAUDE.md](https://claude.md/)
- [mini-claude-code.py](https://mini-claude-code.py/)
- [Claude Agent SDK](https://platform.claude.com/docs/en/agent-sdk/overview)
- [CLAUDE.md](https://claude.md/)
- [CLAUDE.md](https://claude.md/)
- [Claude Agent SDK Documentation](https://platform.claude.com/docs/en/agent-sdk/overview)
- [Claude Code Documentation](https://code.claude.com/docs)
- [Anthropic API Reference](https://docs.anthropic.com/)
- [@eigencloud](https://x.com/@eigencloud)
- [here](https://developers.eigencloud.xyz/?utm_source=x&utm_medium=social&utm_campaign=claude_from_scratch)
- [Upgrade to Premium](https://x.com/i/premium_sign_up)
- [12:47 AM · Jan 10, 2026](https://x.com/dabit3/status/2009668398691582315)
---
*导出时间: 2026/1/13 10:38:50*