メインコンテンツまでスキップ

Claude Code ソースコード詳細研究レポート

1. 調査範囲と要約

1.1 今回実際に調べたこと

今回の調査は、単一の prompt ファイルを読むだけでも、リポジトリ構造を眺めるだけでもありません。cli.js.map に含まれる sourcesContent から可読なソースコードを復元し、実際の runtime の流れに沿って解剖しました。

主な対象は以下です。

  • Claude Code 全体のソース構造
  • メイン system prompt の動的組み立て
  • AgentTool / SkillTool のモデル向けプロトコル
  • built-in agents の役割分担
  • agent orchestration chain の実行経路
  • plugins、skills、hooks、MCP の runtime への組み込み方
  • permissions、tool execution、hook decisions の連携
  • なぜ Claude Code が単純な「LLM + tool caller」より強く感じられるのか

1.2 確認できた事実

復元結果から、少なくとも次が確認できました。

  1. cli.js.map に完全な sourcesContent が含まれている
  2. 少なくとも 4756 個のソースファイルを復元できた
  3. メイン system prompt の中心ファイルは src/constants/prompts.ts
  4. Agent Tool Prompt の中心ファイルは src/tools/AgentTool/prompt.ts
  5. Skill Tool Prompt の中心ファイルは src/tools/SkillTool/prompt.ts
  6. Agent orchestration の中心には src/tools/AgentTool/AgentTool.tsxsrc/tools/AgentTool/runAgent.ts がある
  7. Tool execution chain の中心には src/services/tools/toolExecution.tssrc/services/tools/toolHooks.ts がある

1.3 最初に言うべき結論

Claude Code の強さは、1 本の魔法の system prompt ではなく、完全なソフトウェアシステムにあります。

強さの源は次の統合です。

  • modular prompt assembly
  • 制御された tool execution
  • permission model
  • specialized agents
  • skill による workflow packaging
  • plugin metadata と runtime constraints
  • policy layer としての hooks
  • capability と usage guidance の両方を注入する MCP
  • cache-aware な prompt construction
  • async / background lifecycle management

一言でまとめるとこうです。

Claude Code は prompt ではない。prompt、tools、permissions、agents、skills、plugins、hooks、MCP、cache、product-grade runtime を統合した Agent Operating System である。

2. ソース構造: なぜ Agent Operating System に見えるのか

2.1 トップレベル構造だけでも複雑さが見える

復元した src/ には次のようなモジュールが見えます。

  • src/entrypoints/
  • src/constants/
  • src/tools/
  • src/services/
  • src/utils/
  • src/commands/
  • src/components/
  • src/coordinator/
  • src/memdir/
  • src/plugins/
  • src/hooks/
  • src/bootstrap/
  • src/tasks/

これは薄い CLI ラッパーではなく、完全な runtime platform です。

2.2 entrypoints は platform mindset を示す

確認できる entrypoints:

  • src/entrypoints/cli.tsx
  • src/entrypoints/init.ts
  • src/entrypoints/mcp.ts
  • src/entrypoints/sdk/

つまり、同じ agent runtime が CLI、初期化フロー、MCP、SDK consumer を支える前提で設計されています。

2.3 command system は control plane である

command layer は以下のような system-level commands を持ちます。

  • /mcp
  • /memory
  • /permissions
  • /hooks
  • /plugin
  • /reload-plugins
  • /skills
  • /tasks
  • /plan
  • /review
  • /status
  • /model
  • /output-style
  • /agents
  • /sandbox-toggle

しかも built-in commands だけでなく、plugin commands、skill commands、bundled skills、dynamic skills も統合して読み込みます。command system 自体が ecosystem entrypoint です。

2.4 tools がモデルを executor に変える

重要な tools には次のものがあります。

  • FileRead
  • FileEdit
  • FileWrite
  • Bash
  • Glob
  • Grep
  • TodoWrite
  • TaskCreate
  • AskUserQuestion
  • Skill
  • Agent
  • MCPTool
  • Sleep

この層が、モデルを単なる responder から actor に変えます。

3. prompts.ts の本当の役割

3.1 src/constants/prompts.ts は system control point

このファイルの価値は、長い prompt を持つことではなく、main-thread の runtime instructions を組み立てることです。

主な役割:

  • main system prompt assembly
  • environment injection
  • tool usage guidance
  • risky-action guidance
  • session-specific guidance
  • language / output style injection
  • MCP instructions
  • memory prompt injection
  • scratchpad guidance
  • function result clearing
  • brief mode や token budget などの feature-gated sections

つまり Claude Code の prompt は static string ではなく prompt assembly architecture です。

3.2 getSystemPrompt() は orchestrator である

設計の中心は static prefix と dynamic suffix の分離です。

static prefix:

  • getSimpleIntroSection()
  • getSimpleSystemSection()
  • getSimpleDoingTasksSection()
  • getActionsSection()
  • getUsingYourToolsSection()
  • getSimpleToneAndStyleSection()
  • getOutputEfficiencySection()

dynamic suffix:

  • session guidance
  • memory
  • model override
  • env info
  • language
  • output style
  • MCP instructions
  • scratchpad
  • function result clearing
  • summarize tool results
  • numeric anchors
  • token budget
  • brief mode

Claude Code は prompt を runtime resource として扱っています。

3.3 prompt cache boundary は infrastructure thinking を示す

ソースには SYSTEM_PROMPT_DYNAMIC_BOUNDARY のような境界があり、目的は明確です。

  • prefix は cache-friendly に保つ
  • user/session specific content は境界の後に置く
  • 境界を軽率に変えると cache behavior を壊す

これは単なる prompt writing ではなく、cache economics を意識した prompt assembly です。

4. prompt section の分解

4.1 getSimpleIntroSection()

ここでは次を定義します。

  • Claude は interactive agent である
  • software engineering task を助ける存在である
  • output style は外部から制御される
  • cyber-risk guidance が最初から入る
  • URL を推測や捏造してはいけない

重要なのは自己紹介ではなく behavioral framing です。

4.2 getSimpleSystemSection()

ここでは runtime reality が定義されます。

  • non-tool output は直接ユーザーに見える
  • tools は permission modes の下で動く
  • denied tool call はそのまま再実行できない
  • tool results や user messages に <system-reminder> が含まれることがある
  • external tool output は prompt injection を含みうる
  • hooks が存在する
  • context は自動圧縮されうる

モデルを controlled runtime world に戻す役割です。

4.3 getSimpleDoingTasksSection()

この section は Claude Code の一貫性を支える中核です。

  • 頼まれていない機能を追加しない
  • 過度に抽象化しない
  • 不要な refactor をしない
  • 不要な comments や docstrings や type annotations を追加しない
  • 不要な fallback や validation を入れない
  • speculative future-proof abstraction を作らない
  • edit の前に read する
  • 不要に新規ファイルを作らない
  • time estimates を安易に出さない
  • 失敗時は strategy 変更前に diagnosis する
  • security issues に気を配る
  • 明らかに不要なものは削除する
  • 実行していない verification を実行したかのように報告しない

Anthropic が engineering behavior を policy 化している部分です。

4.4 getActionsSection()

確認対象となる risky actions を定義します。

  • destructive operations
  • hard-to-reverse operations
  • shared-state modification
  • externally visible actions
  • third-party uploads

4.5 getUsingYourToolsSection()

tool usage grammar は非常に明確です。

  • 読むときは FileRead
  • 編集するときは FileEdit
  • 新規作成は FileWrite
  • file discovery は Glob
  • content search は Grep
  • Bash は shell-native work に限定
  • task management があるなら TodoWrite / TaskCreate を使う
  • independent tool calls は parallelize する

4.6 session-specific guidance

この dynamic section は会話状況に応じて次を注入します。

  • AskUserQuestion の有無
  • non-interactive mode の差分
  • AgentTool が有効か
  • Explore / Plan agents が使えるか
  • slash skill のルール
  • DiscoverSkills の guidance
  • verification contract

Claude Code の system prompt は global rules + local runtime rules です。

4.7 output efficiency

ここは product quality に直結しています。

  • logs ではなく自然言語を返す
  • 先に action か conclusion を言う
  • 必要な更新はするが冗長にならない
  • 過度に説明しない
  • 不要な table を避ける
  • 短く直接的に書く

4.8 tone and style

細かな規則には以下があります。

  • emoji を乱用しない
  • concise に答える
  • code location は file_path:line_number
  • GitHub issue / PR は owner/repo#123
  • tool call 前に余計な前置きをしない

4.9 DEFAULT_AGENT_PROMPT

sub-agent の baseline role は次の通りです。

  • Claude Code の agent である
  • tool を使って task を完了する
  • 半端な状態で終わらせない
  • 最後に concise report を返す

5. Agent prompts と built-in agents

5.1 AgentTool/prompt.ts は protocol document

このファイルは multi-agent behavior の model-facing protocol です。

説明されている主な内容:

  • agent list の提示方法
  • 各 agent の description format
  • いつ fork するか
  • いつ subagent_type を指定するか
  • fork と fresh agent の違い
  • どんな時に AgentTool を使わないか
  • sub-agent 向け prompt の書き方
  • foreground / background の違い
  • worktree / remote isolation の意味

5.2 fork semantics が強い理由

fork mode が有効なとき、モデルには次が教えられます。

  • subagent_type を省略すると self-fork になる
  • fork は full conversation context を継承する
  • research tasks は fork に向く
  • implementation tasks も中間出力が多ければ fork に向く
  • fork は prompt cache を共有するため安い
  • model を変えると cache reuse が悪くなる
  • main thread は fork output を覗くべきではない
  • main thread は fork の結果を先回りして決めつけるべきではない

5.3 "How to write the prompt" が重要

agent prompt は delegation の品質も教育します。

  • fresh agents には prior context がない
  • prompts は新しい teammate への briefing のように書く
  • goal と reason を書く
  • すでに除外したものを書く
  • enough context を与える
  • 短い答えが欲しければ明示する
  • task understanding 自体を外注しない
  • lazy delegation をしない
  • file path、line、具体的な change goals を渡す

5.4 built-in agents は specialization を表す

確認できる roles:

  • General Purpose Agent
  • Explore Agent
  • Plan Agent
  • Verification Agent
  • Claude Code Guide Agent
  • Statusline Setup Agent

5.5 Explore Agent は read-only specialist

Explore は create / modify / delete / move / temporary file write / redirection / state-changing commands を行いません。GlobGrepFileRead と read-only Bash commands を使って高速に探索します。

5.6 Plan Agent は pure planner

Plan は read-only のまま requirement understanding、codebase exploration、step-by-step implementation plan、Critical Files for Implementation の列挙を行います。

5.7 Verification Agent は adversarial validator

Verification agent は変更を壊せるか試す役割です。要求される内容:

  • build
  • test suite
  • lint / type-check
  • frontend の browser automation
  • backend の curl / fetch
  • CLI の stdout / stderr / exit code
  • migration up/down
  • public API verification
  • adversarial probes
  • command と observed output
  • VERDICT: PASS / FAIL / PARTIAL

6. Agent orchestration chain

6.1 全体の流れ

流れは次の通りです。

  1. main model が Agent tool を呼ぶ
  2. AgentTool.call() が input を解析
  3. fork / built-in / teammate / background / remote を解決
  4. agent definition を選択
  5. prompt messages を構築
  6. system prompt を構築または継承
  7. tool pool を組み立てる
  8. agent-specific ToolUseContext を作る
  9. hooks / skills / MCP servers を登録
  10. runAgent() を呼ぶ
  11. query() が main loop を回す
  12. transcript、metadata、cleanup を処理

6.2 AgentTool.call() は orchestration controller

Input parsing、team context、background 許可判定、fork path と normal path の分岐、permissions による filtering、MCP checks、prompt construction、task registration、runAgent() 呼び出しを担います。

6.3 fork path vs normal path

fork path は context inheritance と prompt cache reuse を優先します。normal path は fresh agent system prompt を作り、必要な context だけを渡し、agent-specific tool restrictions を適用します。

6.4 cache-identical prefix の重要性

request prefix をできるだけ identical に保ち、prompt cache hit を高めて token cost を下げようとしています。

6.5 foreground / background lifecycle

background agents は独立 abort controller、task registration、notification-based return を持ちます。foreground agents は main thread 側で待機し progress tracking されます。

6.6 runAgent() の役割

runAgent() は MCP servers の初期化、context 準備、permissions / tools 解決、hooks / skills 登録、query() 実行、resource cleanup を担当します。

6.7 agent-specific MCP servers

Agents は自分専用の MCP servers を持ち、runtime に additive capabilities を注入できます。

6.8 frontmatter hooks と frontmatter skills

Hooks や skills を frontmatter 経由で注入できるため、agent は configurable prompt container です。

6.9 query() が最終ループ

役割分担:

  • AgentTool: routing
  • runAgent: runtime / lifecycle construction
  • query: model + tool loop

6.10 transcript / metadata / cleanup

transcript recording、metadata writing、tracking、cleanup の存在は productized runtime を示します。

7. Skills / Plugins / Hooks / MCP

7.1 Skill は workflow package

Skills は first-class primitives です。task が skill に一致したら Skill tool を呼ぶべきで、単に skill を言及するだけでは不十分です。

7.2 Plugin は prompt + metadata + runtime constraints

Plugins は markdown commands、SKILL.md、metadata、allowed tools、model hints、runtime variables を提供でき、モデルの行動を拡張します。

7.3 Hook は runtime governance layer

PreToolUsePostToolUsePostToolUseFailure hooks は message、blocking error、updated input、permission behavior、additional context を返せます。

7.4 Hook と permission model の統合

Hooks は allow / ask / deny を返せても、central safety model は迂回できません。

7.5 MCP は behavior injection layer

MCP は tools だけでなく、その使い方の instructions も system prompt に注入できます。

8. permissions、hooks、tool execution pipeline

8.1 toolExecution.ts

tool lookup、metadata parsing、schema validation、tool-specific validation、hooks、permission decision、tool call、telemetry、post-hooks という pipeline を持ちます。

8.2 input validation

schema parse と tool-specific validation により低レベルエラーを早期に止めます。

8.3 PreToolUse hooks

特に重要なのは updatedInputpermissionBehaviorpreventContinuation です。

8.4 resolveHookPermissionDecision()

このロジックが hook semantics と central permission model を橋渡しします。

8.5 tool call 後も governance は続く

成功後も失敗後も hooks は context injection、continuation blocking、recovery hints を提供できます。

9. なぜ Claude Code は強いのか

9.1 prompt ではなく operating model

本当の moat は prompt architecture、governed runtime、permissions、hooks、specialization、skills、plugins、MCP、cache、lifecycle management の統合です。

9.2 good behavior の制度化

Claude Code は good engineering habits を model の即興に任せず、prompts と runtime rules に書き込みます。

9.3 context scarcity の理解

prompt boundaries、cache reuse、on-demand injection、result clearing、resume mechanisms は token を budget として扱っている証拠です。

9.4 agent specialization の深さ

Explore、Plan、Verification によって research、planning、implementation、validation が分離されています。

9.5 ecosystem が model-aware

Model 自身が skill lists、agent lists、MCP instructions、session-specific guidance を通じて ecosystem を理解している点が大きな差です。

10. key files と次の調査対象

10.1 prompt files

  • src/constants/prompts.ts
  • src/tools/AgentTool/prompt.ts
  • src/tools/SkillTool/prompt.ts
  • src/tools/FileReadTool/prompt.ts
  • src/tools/GlobTool/prompt.ts
  • src/tools/GrepTool/prompt.ts
  • src/tools/BriefTool/prompt.ts

10.2 agent files

  • src/tools/AgentTool/AgentTool.tsx
  • src/tools/AgentTool/runAgent.ts
  • src/tools/AgentTool/resumeAgent.ts
  • src/tools/AgentTool/forkSubagent.ts
  • src/tools/AgentTool/agentMemory.ts
  • src/tools/AgentTool/agentMemorySnapshot.ts
  • src/tools/AgentTool/builtInAgents.ts
  • src/tools/AgentTool/built-in/exploreAgent.ts
  • src/tools/AgentTool/built-in/planAgent.ts
  • src/tools/AgentTool/built-in/verificationAgent.ts
  • src/tools/AgentTool/built-in/generalPurposeAgent.ts
  • src/tools/AgentTool/built-in/claudeCodeGuideAgent.ts
  • src/tools/AgentTool/built-in/statuslineSetup.ts

10.3 skill / plugin / hook / MCP

  • src/tools/SkillTool/constants.ts
  • src/tools/SkillTool/prompt.ts
  • src/commands.ts
  • src/utils/plugins/loadPluginCommands.ts
  • src/services/tools/toolHooks.ts
  • src/utils/hooks.js
  • src/services/tools/toolExecution.ts
  • src/services/mcp/types.ts
  • src/services/mcp/normalization.ts
  • src/services/mcp/mcpStringUtils.ts
  • src/services/mcp/utils.ts
  • src/entrypoints/mcp.ts

10.4 次に深掘りすべき場所

  1. query.ts
  2. resumeAgent.ts
  3. loadSkillsDir
  4. plugin loading
  5. systemPromptSections.ts
  6. coordinator/*
  7. attachments.ts
  8. AgentSummary

結論

このレポートを一文で要約するなら次です。

Claude Code の本当の秘密は system prompt ではない。prompt architecture、tool runtime、permission model、agent orchestration、skill packaging、plugin system、hook governance、MCP integration、context hygiene、product engineering を統合したシステムそのものにある。

だから Claude Code は、tools を呼べる chat interface ではなく、governable で extensible な Agent Operating System に見えるのです。