記事一覧へ
偶然のオープンソース:リークされたClaude Codeリポジトリの深掘り分析
今朝(2026年3月31日)、axiosへのハック注入により、Claude Codeの完全なTypeScriptソースコード(全51万2千行)が意図せず公開されました。@fried_rice(Chaofan Shou)がそのパスを特定し、コードベースがダウンロード可能な状態になっていました。
私は一日かけてsrc/ディレクトリの詳細な監査を行いました。そこで見つけたのは、エージェント型エンジニアリングの真骨頂でした。
I. 「頭脳」:システムプロンプトの組み立て方
プロンプトはgetSystemPrompt()を通じて環境に応じて段階的に構築されます。単なる「あなたは親切なアシスタントです」ではなく、「あなたは特定のGit履歴・特定の日付・特定のアクティブツールを持つディレクトリの上級エンジニアです」という内容です。
プロンプトキャッシング:Anthropicはセクションキャッシングレジストリを使用しています。プロンプトをキャッシュブロックに分割することで、「ルール」を再処理せずに「コンテキスト」だけを入れ替えられ、レイテンシとコストを大幅に削減しています。
CLAUDE.md:「メモリファイル」として扱われます。コードはこれらのファイルを検索し、プロジェクトの長期的な指示をユーザーコンテキストに直接注入します。
II. 「心臓部」:メインエージェントループ
query.tsの307行目にあるwhile(true)ループがエージェントを駆動しています。ターミナルを観察し、ファイルに対して自分の状況を把握し、ツールを決定して実行—タスクが完了するまでこれを繰り返します。
マルチエージェント生成:AgentTool.tsxにより、メインのClaudeインスタンスが「ワーカー」サブエージェントを生成できます。
III. 「筋肉」:ツールシステム
全ツールがTypeScriptクラスとして実装されています(BashTool、FileReadTool、FileEditTool等)。各ツールにはschema(モデルへの説明)とcall()メソッドがあります。
承認レイヤー:ツールは実行前に「人間の確認」を要求できます。ローカルでは「はい/いいえ」のプロンプト。エンタープライズでは、これが監査証跡になります。
インジェクション防止:ファイルを読み込む際、コンテンツをタグでラップします。モデルがコンテンツを実際の指示と混同しないようにするためです。
IV. 「本能」:費用対効果の決断
これが最も賢い部分です。ショートカットの決定ロジックが存在します:
- タスクが簡単?→ 安価な「Haiku」モデルを使用
- タスクが難しい?→ 強力な「Sonnet」または「Opus」モデルを使用
具体的に言うと:シンプルなファイル読み込みは3.5セント/100万トークン。複雑な推論は15ドル/100万トークン。このルーターが自動的にコストを50〜90%削減します。
V. 「記憶」:コンテキスト管理
会話履歴は単純にRAMに保持されるわけではありません。コンテキストウィンドウ管理システムが存在します:
サマリー:会話が長くなると、Claudeは自動的に古い部分を要約します(claude --resumeで確認できます)
優先度付きコンテキスト:全ての情報が同等ではありません。ファイル、エラー、ユーザー指示は通常のチャットよりも優先されます。
まとめ
Claude Codeのソースが何百万人もの開発者にとって最良のエージェントエンジニアリング教科書になるとは、Anthropicも予想していなかったでしょう。
ソースコードの中で特に感銘を受けた部分は何ですか?
claude-setupclaude-workflowharness-design
MCPは誰も語らない最重要AI基盤
♥ 122↻ 22🔖 231👁 40,000
原文を表示 / Show original
The Accidental Open Source: A Deep Dive into the Leaked Claude Code Repository
This morning (March 31, 2026), due to an axios hack injection, the complete TypeScript source code for Claude Code was inadvertently exposed. All 512,000 lines. @fried_rice (Chaofan Shou) identified the path, and the codebase was available for download.
I spent the day performing a deep-tissue audit of the src/ directory. What I found is a masterclass in Agentic Engineering.
I. THE "BRAINS": HOW SYSTEM PROMPTS ARE ASSEMBLED
The prompt is built piece-by-piece based on your environment via getSystemPrompt(). It's not just "You are a helpful assistant." It's "You are a senior engineer in a directory with a specific Git history, a specific date, and a specific set of active tools."
Prompt Caching: Anthropic uses a section caching registry. By splitting the prompt into cached blocks, they can swap out the "Context" without re-processing the "Rules", saving massive amounts of latency and cost.
CLAUDE.md: Treated as a "Memory File." The code specifically looks for these files to inject long-term project instructions directly into the user context.
II. THE "HEARTBEAT": THE MAIN AGENT LOOP
The while(true) loop at line 307 in query.ts drives the agent. It observes the terminal, orients itself to your files, decides on a tool, and acts — repeating until the task is complete.
Multi-Agent Spawning: AgentTool.tsx allows the main Claude instance to spawn "worker" sub-agents (like Explore or Plan) to handle massive codebases in parallel.
III. THE "HANDS": A SOPHISTICATED TOOL SYSTEM
Concurrent vs. Serial Execution: In toolOrchestration.ts, the code decides whether it can run multiple tools at once or needs to wait. It's essentially a "scheduler" for AI actions.
MCP Bridge: Deep integration with the Model Context Protocol. Claude Code can "plug in" to any external data source that speaks MCP.
IV. THE "INFINITE HORIZON": CONTEXT & COMPACTION
Auto-Compaction: When conversation hits the 13,000-token buffer, the agent triggers a "summarization flow." It stops, writes a summary, clears old messages, and keeps the summary. This maintains "working memory" over hours of coding.
Token Estimation: Three-tier estimation system to predict costs before they happen.
V. THE "YOLO" CLASSIFIER: AUTONOMOUS PERMISSION ENGINE
Two-Stage XML Validation:
- Fast-reject stage (64 tokens) to catch obvious violations
- "Deep Thinking" stage (4096 tokens) where Sonnet 4.6 analyzes conversation transcript
Transcript Sanitization: The classifier only sees tool calls, not conversational text — prevents "prompt injection."
Safe List: Read-only ops (ls, grep, glob, LSP lookups), task management (TodoWrite, TaskCreate), and a literal Sleep tool skip the classifier.
Circuit Breakers:
- 3 consecutive denials → falls back to manual mode
- 20 total denials in a session → assumes agent has "gone rogue"
Dangerous Rule Stripping: In Auto Mode, the system proactively strips dangerous permissions (iex, invoke-expression, nested shells like wsl or pwsh).
VI. THE HIDDEN AUTOFIX-PR ARCHITECTURE
Claude Code Remote (CCR): autofix-pr isn't a local tool — it's a Remote Agent Task. It teleports the agent's "consciousness" to an Anthropic-hosted environment.
The PR "Observer" Loop:
1. Trigger: Developer points Claude at a PR URL
2. Teleport: Agent moves to CCR session
3. Analyze: Reads PR diff, scans CI failure logs, parses reviewer comments
4. Fix: Runs in high-permission "Auto Mode"
5. Verify: Polls CI/CD pipeline. If tests fail again, loop restarts automatically
VII. THE "TELEPORT" PROTOCOL
Pre-flight check (validateGitState): Ensures repo is clean, syncs with remote, uses Haiku to auto-name session.
The Bridge: 33+ files for controlling local computer from Claude Mobile App. Local machine runs a "Long-Polling" server (POST /v1/environments/{id}/work/poll).
Two Transport Generations:
- V1 (Hybrid): WebSockets for reading + batched HTTP POST (500 messages) for writing
- V2 (SSE): Server-Sent Events with sequence numbers for resilience
Remote Permissions: SDKControlRequest sends permission requests through the bridge. Your phone pops up a dialog. "Allow" fires SDKControlResponse back to cloud.
CONCLUSION:
Anthropic isn't winning because they have the "smartest" model. They are winning because they have built a Distributed Operating System for Intelligence.
The era of the "AI Chatbot" is over. We are now in the era of the Autonomous Teammate — a system that thinks while you sleep, fixes your PRs before you wake up, and maintains a "personality" that evolves with you.