ClaudeCode源碼深度研究報告-260331+資源地址
發(fā)布日期:2026/4/1 7:46:20 瀏覽量:
資源地址:
https://github.com/sanbuphy/claude-code-source-code
https://github.com/instructkr/claude-code
1.1目錄. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 1.研究范圍與結(jié)論總覽4
2.1 1.1這次到底研究了什么. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 1.2關鍵確認事實. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 1.3先給最重要的總判斷. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3 2.源碼結(jié)構全景:它為什么更像AgentOperatingSystem 5
3.1 2.1頂層結(jié)構暴露出的系統(tǒng)復雜度. . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 2.2入口層說明它是平臺,而不是單一界面. . . . . . . . . . . . . . . . . . . . 6
3.3 2.3命令系統(tǒng)是整個產(chǎn)品的操作面板. . . . . . . . . . . . . . . . . . . . . . . . 6
3.4 2.4Tools層才是模型真正“能做事”的根. . . . . . . . . . . . . . . . . . . . . 7
4 3.系統(tǒng)提示詞總裝:prompts.ts的真實地位7
4.1 3.1真正的主入口:src/constants/prompts.ts . . . . . . . . . . . . . . . 7
4.2 3.2getSystemPrompt()不是文本,而是編排器. . . . . . . . . . . . . . . . 8
4.2.1靜態(tài)前綴(更適合cache). . . . . . . . . . . . . . . . . . . . . . . . 8
4.2.2動態(tài)后綴(按會話條件注入). . . . . . . . . . . . . . . . . . . . . . . 8
4.3 3.3Promptcacheboundary:基礎設施級思維. . . . . . . . . . . . . . . . . 8
5 4.Prompt全量提取與模塊級拆解9
5.1 4.1身份與基礎定位:getSimpleIntroSection() . . . . . . . . . . . . . . 9
5.2 4.2基礎系統(tǒng)規(guī)范:getSimpleSystemSection() . . . . . . . . . . . . . . . 9
5.3 4.3做任務哲學:getSimpleDoingTasksSection() . . . . . . . . . . . . . 10
5.4 4.4風險動作規(guī)范:getActionsSection(). . . . . . . . . . . . . . . . . . . 10
5.5 4.5工具使用規(guī)范:getUsingYourToolsSection() . . . . . . . . . . . . . 10
5.6 4.6Session?specificguidance:運行時可變的局部指令. . . . . . . . . . . . . 11
5.7 4.7Outputefficiency:高價值但常被忽視的section . . . . . . . . . . . . . . 11
5.8 4.8Toneandstyle:統(tǒng)一交互感受. . . . . . . . . . . . . . . . . . . . . . . . 11
5.9 4.9DEFAULT_AGENT_PROMPT:子Agent的基礎人格. . . . . . . . . . . . 12
1
6 5.AgentPrompt與built?inagents深挖12
6.1 5.1AgentTool/prompt.ts:Agent協(xié)議說明書. . . . . . . . . . . . . . . . 12
6.2 5.2fork語義為什么很強. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
6.3 5.3“Howtowritetheprompt”一節(jié)非常值錢. . . . . . . . . . . . . . . . . 13
6.4 5.4built?inagents:職責分工而不是萬能worker . . . . . . . . . . . . . . . . 13
6.5 5.5ExploreAgent:純讀模式的代碼探索專家. . . . . . . . . . . . . . . . . . 13
6.5.1絕對只讀. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6.5.2核心能力. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
6.6 5.6PlanAgent:純規(guī)劃,不做編輯. . . . . . . . . . . . . . . . . . . . . . . . 14
6.7 5.7VerificationAgent:為什么它非常值錢. . . . . . . . . . . . . . . . . . . 14
7 6.Agent調(diào)度鏈深挖:從AgentTool到runAgent再到query 15
7.1 6.1總體調(diào)用鏈長什么樣. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
7.2 6.2AgentTool.call():真正的調(diào)度總控. . . . . . . . . . . . . . . . . . . . 15
7.3 6.3forkpathvsnormalpath . . . . . . . . . . . . . . . . . . . . . . . . . . 16
7.3.1 forkpath. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
7.3.2 normalpath. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
7.4 6.4為什么fork會強調(diào)cache?identicalprefix . . . . . . . . . . . . . . . . . 16
7.5 6.5backgroundagent與foregroundagent是兩套生命周期. . . . . . . . . 17
7.5.1 backgroundpath特點. . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.5.2 foregroundpath特點. . . . . . . . . . . . . . . . . . . . . . . . . . . 17
7.6 6.6runAgent():真正的子Agentruntime. . . . . . . . . . . . . . . . . . . 17
7.7 6.7agent?specificMCPservers:真正的additive能力注入. . . . . . . . . . 18
7.8 6.8frontmatterhooks與frontmatterskills . . . . . . . . . . . . . . . . . . 18
7.9 6.9query()才是最終主循環(huán)執(zhí)行器. . . . . . . . . . . . . . . . . . . . . . . 18
7.106.10transcript/metadata/cleanup:產(chǎn)品化runtime的證據(jù). . . . . . . . 18
8 7.Skills/Plugins/Hooks/MCP生態(tài)深挖19
8.1 7.1Skill:不是文檔,而是workflowpackage. . . . . . . . . . . . . . . . . . 19
8.1.1 Skill的本質(zhì). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
8.2 7.2Plugin:Prompt+Metadata+RuntimeConstraints . . . . . . . . . . . 19
8.3 7.3Hook:運行時治理層. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
8.4 7.4Hook與權限的耦合方式非常成熟. . . . . . . . . . . . . . . . . . . . . . . 20
8.5 7.5MCP:不只是工具橋,還是行為說明注入通道. . . . . . . . . . . . . . . . 20
9 8.權限、Hook、工具執(zhí)行鏈深挖21
9.1 8.1toolExecution.ts:真正的工具runtime主線. . . . . . . . . . . . . . 21
9.2 8.2輸入校驗:先擋低級錯誤. . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
9.3 8.3PreToolUsehooks:最關鍵的攔截點. . . . . . . . . . . . . . . . . . . . . 21
9.3.1 updatedInput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
9.3.2 permissionBehavior . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
9.3.3 preventContinuation. . . . . . . . . . . . . . . . . . . . . . . . . . . 22
9.4 8.4resolveHookPermissionDecision():權限語義的關鍵粘合層. . . . . 22
9.5 8.5工具執(zhí)行后也不是結(jié)束. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2
109.為什么ClaudeCode這么強:從源碼看它真正的護城河22
10.19.1它不是一個prompt,而是一個operatingmodel . . . . . . . . . . . . . . 22
10.29.2它把“好行為”制度化了. . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
10.39.3它特別懂“上下文是稀缺資源”. . . . . . . . . . . . . . . . . . . . . . . . 23
10.49.4Agentspecialization是很深的設計優(yōu)勢. . . . . . . . . . . . . . . . . . . 23
10.59.5它的生態(tài)不是“可安裝”,而是“模型可感知” . . . . . . . . . . . . . . . . 24
1110.關鍵文件索引與后續(xù)可繼續(xù)深挖方向24
11.110.1核心Prompt文件. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
11.1.1主系統(tǒng)提示詞. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
11.1.2AgentToolPrompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
11.1.3SkillToolPrompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
11.1.4其他可繼續(xù)挖的tool?specificprompt . . . . . . . . . . . . . . . . . . 24
11.210.2核心Agent文件. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
11.2.1built?inagents. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
11.310.3核心Skill/Plugin/Hook/MCP文件. . . . . . . . . . . . . . . . . . . 25
11.3.1Skill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
11.3.2Plugin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
11.3.3Hook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
11.3.4Toolexecution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
11.3.5MCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
11.410.4如果繼續(xù)做下一輪,還能怎么挖. . . . . . . . . . . . . . . . . . . . . . . 25
11.510.5最終結(jié)論. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3
基于@anthropic-ai/claude-code npm 包的 cli.js.map 還原源碼后完成
的系統(tǒng)性研究。本文是單文件、長篇、研究報告版,重點覆蓋:整體架構、系統(tǒng)提示
詞、Agent提示詞、Skills、Plugins、Hooks、MCP、權限與工具調(diào)用機制,以及
新增的全量Prompt提取框架分析與Agent調(diào)度鏈深挖。
1.1 目錄
1. 研究范圍與結(jié)論總覽
2. 源碼結(jié)構全景:它為什么更像AgentOperatingSystem
3. 系統(tǒng)提示詞總裝:prompts.ts的真實地位
4. Prompt 全量提取與模塊級拆解
5. Agent Prompt 與built?in agents 深挖
6. Agent 調(diào)度鏈深挖:從AgentTool到runAgent再到query
7. Skills / Plugins / Hooks / MCP 生態(tài)深挖
8. 權限、Hook、工具執(zhí)行鏈深挖
9. 為什么ClaudeCode這么強:從源碼看它真正的護城河
10. 關鍵文件索引與后續(xù)可繼續(xù)深挖方向
2.1 1.1這次到底研究了什么
這次不是只看某一個prompt文件,也不是只做“目錄級掃一眼”。這次研究的核心,是把
cli.js.map 中的sourcesContent還原成可讀源碼后,沿著以下主線做系統(tǒng)性拆解:
? ClaudeCode的整體源碼結(jié)構
? 主系統(tǒng)提示詞如何動態(tài)拼裝
? AgentTool/SkillTool 的模型側(cè)協(xié)議
? built?in agents 的角色分工
? Agent調(diào)度鏈路如何跑通
? Plugin/Skill / Hook / MCP如何接入并影響運行時
? Permission / Tool execution / Hook decision 如何協(xié)同
? 它為什么在體驗上比“普通LLM+工具調(diào)用器”強很多
本次已經(jīng)確認:
1. npm包里的cli.js.map包含完整sourcesContent
2. 已從map中提取出4756個源碼文件
3. 主系統(tǒng)提示詞核心文件為:
4
? src/constants/prompts.ts
4. Agent Tool Prompt 核心文件為:
? src/tools/AgentTool/prompt.ts
5. Skill Tool Prompt 核心文件為:
? src/tools/SkillTool/prompt.ts
6. Agent 調(diào)度核心文件至少包括:
? src/tools/AgentTool/AgentTool.tsx
? src/tools/AgentTool/runAgent.ts
7. 工具執(zhí)行鏈核心文件至少包括:
? src/services/tools/toolExecution.ts
? src/services/tools/toolHooks.ts
Claude Code 的強,不是來自某個“神秘systemprompt”,而是來自一個完整的軟件工程系
統(tǒng):
? Prompt不是靜態(tài)文本,而是模塊化runtimeassembly
? Tool 不是直接裸調(diào),而是走permission/hook/analytics / MCP?aware execution
pipeline
? Agent不是一個萬能worker,而是多種built?in/fork/subagent的分工系統(tǒng)
? Skill 不是說明文檔,而是prompt?nativeworkflowpackage
? Plugin不是外掛,而是prompt+metadata+runtimeconstraint的擴展機制
? MCP不是單純工具橋,而是同時能注入工具與行為說明的integrationplane
一句話總結(jié):
ClaudeCode的價值,不是一段prompt,而是一整套把prompt、tool、permission、
agent、skill、plugin、hook、MCP、cache和產(chǎn)品體驗統(tǒng)一起來的AgentOperating
System。
3 2. 源碼結(jié)構全景:它為什么更像AgentOperatingSystem
3.1 2.1頂層結(jié)構暴露出的系統(tǒng)復雜度
從提取出來的src/頂層看,ClaudeCode至少有這些重要模塊:
? src/entrypoints/:入口層
? src/constants/:prompt、系統(tǒng)常量、風險提示、輸出規(guī)范
? src/tools/:工具定義與具體實現(xiàn)
? src/services/:運行時服務,例如tools、mcp、analytics
5
? src/utils/:底層共用能力
? src/commands/:slashcommand與命令系統(tǒng)
? src/components/:TUI/UI組件
? src/coordinator/:協(xié)調(diào)器模式
? src/memdir/:記憶/memoryprompt
? src/plugins/與src/utils/plugins/:插件生態(tài)
? src/hooks/與src/utils/hooks.js:hook系統(tǒng)
? src/bootstrap/:狀態(tài)初始化
? src/tasks/:本地任務、遠程任務、異步agent任務
這已經(jīng)說明它不是簡單CLI包裝器,而是一個完整運行平臺。
可見入口包括:
? src/entrypoints/cli.tsx
? src/entrypoints/init.ts
? src/entrypoints/mcp.ts
? src/entrypoints/sdk/
也就是說它從設計上就考慮了:
? 本地CLI
? 初始化流程
? MCP模式
? SDK消費者
這是一種平臺化思維:同一個agentruntime,可以服務多個入口和多個交互表面。
src/commands.ts 暴露出非常多系統(tǒng)級命令,例如:
? /mcp
? /memory
? /permissions
? /hooks
? /plugin
? /reload-plugins
? /skills
? /tasks
? /plan
? /review
? /status
? /model
? /output-style
? /agents
6
? /sandbox-toggle
這說明命令系統(tǒng)不是“錦上添花”,而是用戶與系統(tǒng)運行時交互的重要控制面。
更關鍵的是,它不僅注冊builtincommands,還統(tǒng)一加載:
? plugincommands
? skill commands
? bundledskills
? 動態(tài)skills
? 可用性過濾后的commands
所以commandsystem本身就是生態(tài)入口。
從prompt和工具名能確認的重要工具包括:
? FileRead
? FileEdit
? FileWrite
? Bash
? Glob
? Grep
? TodoWrite
? TaskCreate
? AskUserQuestion
? Skill
? Agent
? MCPTool
? Sleep
工具層的本質(zhì),是把模型從“回答器”變成“執(zhí)行體”。ClaudeCode的強,很大程度來自
這層做得正式、清晰、可治理。
4.1 3.1真正的主入口:src/constants/prompts.ts
這份文件是整個系統(tǒng)最關鍵的源碼之一。不是因為它寫了一大段神奇文案,而是因為它承擔了:
? 主系統(tǒng)提示詞的總裝配
? 環(huán)境信息注入
? 工具使用規(guī)范注入
? 安全與風險動作規(guī)范
? Session?specific guidance 注入
? language/output style 注入
7
? MCPinstructions 注入
? memoryprompt注入
? scratchpad 說明注入
? function result clearing 提示注入
? brief/ proactive / token budget 等 feature?gated section 注入
Claude Code 的prompt不是靜態(tài)字符串,而是一個systempromptassemblyarchi
tecture。
getSystemPrompt() 里最核心的結(jié)構,是先構造靜態(tài)部分,再加上動態(tài)部分。你可以把它理
解成:
? getSimpleIntroSection()
? getSimpleSystemSection()
? getSimpleDoingTasksSection()
? getActionsSection()
? getUsingYourToolsSection()
? getSimpleToneAndStyleSection()
? getOutputEfficiencySection()
4.2.2 動態(tài)后綴(按會話條件注入)
? session guidance
? memory
? antmodeloverride
? envinfo
? language
? outputstyle
? mcpinstructions
? scratchpad
? function result clearing
? summarizetoolresults
? numericlengthanchors
? tokenbudget
? brief
這個設計非常值錢,因為它不是“把能想到的都寫進systemprompt”,而是把prompt當
作可編排運行時資源來管理。
源碼中明確存在:
? SYSTEM_PROMPT_DYNAMIC_BOUNDARY
8
并且注釋說明:?邊界前盡量可cache?邊界后是用戶/會話特定內(nèi)容?不能亂改,否則會
破壞cache邏輯
這點非常重要。
因為這說明ClaudeCode已經(jīng)不是“會寫prompt”,而是在做:
Prompt assembly with cache economics
也就是說,它連systemprompt的token成本與緩存命中都做了工程化優(yōu)化。
這一節(jié)是本次新增重點:不是只說prompt在哪,而是把主prompt的主要section和行為
價值拆出來。
這一段做的事包括:
? 定義自己是interactiveagent
? 說明是幫助用戶完成軟件工程任務
? 指出輸出風格會受OutputStyle約束
? 注入CYBER_RISK_INSTRUCTION
? 明確禁止隨意生成或猜URL
這段意義不在于“介紹自己”,而在于為后續(xù)行為定基調(diào):
1. 它不是普通聊天機器人
2. 它是工具驅(qū)動的工程協(xié)作者
3. 風險防護從第一屏開始就被注入
5.2 4.2基礎系統(tǒng)規(guī)范:getSimpleSystemSection()
這段本質(zhì)上在定義runtimereality:
? 所有非工具輸出都直接給用戶看
? 工具運行在permissionmode下
? 用戶拒絕后不能原樣重試
? toolresult / user message 里可能有等標簽
? 外部工具結(jié)果可能包含promptinjection
? 有hooks
? 上下文會被自動壓縮,不是硬性上下文窗口
這段極其重要,因為它把模型從“語言模型幻覺世界”拉回了“受控runtime世界”。
9
這部分是ClaudeCode行為穩(wěn)定性的核心之一。它非常明確地約束模型:
? 不要加用戶沒要求的功能
? 不要過度抽象
? 不要瞎重構
? 不要亂加comments/docstrings/typeannotations
? 不要做不必要的errorhandling/fallback/validation
? 不要設計一堆future?proofabstraction
? 先讀代碼再改代碼
? 不要輕易創(chuàng)建新文件
? 不要給時間估計
? 方法失敗時要先診斷再換策略
? 注意安全漏洞
? 刪除確認沒用的東西,不搞compatibility垃圾
? 結(jié)果要如實匯報,不能假裝測試過
這塊本質(zhì)上不是prompt細節(jié),而是:
Anthropic 對 AI 工程師行為規(guī)范的制度化表達
很多codingagent不穩(wěn)定,不是不會寫代碼,而是行為發(fā)散。這一段就是為了解決行為漂
移。
這部分定義了什么叫“需要確認”的風險動作:
? destructive operations
? hard?to?reverse operations
? 修改共享狀態(tài)
? 對外可見動作
? 上傳到第三方工具
并且還強調(diào):?不要用destructiveactions當捷徑?發(fā)現(xiàn)陌生狀態(tài)先調(diào)查?mergeconflict
/ lock file 不要粗暴刪
這一段值錢的點在于:它把blastradius思維編碼進了系統(tǒng)提示詞。
這里面有非常清楚的工具策略:
? 讀文件優(yōu)先FileRead,不要cat/head/tail/sed
? 改文件優(yōu)先FileEdit,不要sed/awk
? 新建文件優(yōu)先FileWrite,不要echo重定向
? 搜文件優(yōu)先Glob
? 搜內(nèi)容優(yōu)先Grep
10
? Bash只保留給真正需要shell的場景
? 有任務管理工具時要用TodoWrite/TaskCreate
? 沒有依賴關系的工具調(diào)用要并行
這非常關鍵,因為它不只是說“你有工具”,而是說:
你要以正確的操作語法使用這些工具
Claude Code 的穩(wěn),和這套toolusagegrammar有很大關系。
getSessionSpecificGuidanceSection() 是個非常關鍵的動態(tài)section。里面會根據(jù)當
前工具集和featuregate拼出一些當下約束,例如:
? 如果有AskUserQuestion,被拒絕后可以問用戶
? 非交互模式下的行為差異
? 是否啟用AgentTool
? Explore/Planagents 是否可用
? slashskill 的使用規(guī)則
? DiscoverSkills 工具的調(diào)用guidance
? Verification agent 的強制驗證合同
這一段說明ClaudeCode的systemprompt不是“總規(guī)則”,而是“總規(guī)則+當前會話的
局部規(guī)則”。
這一段在ant與外部用戶上有分支,但核心目標一致:
? 用戶看的是自然語言,不是日志
? 先說動作或結(jié)論,不要鋪墊
? 該更新時更新,但不要廢話
? 不要過度解釋
? 不要塞無謂表格
? 短句直給
這說明ClaudeCode不只管“能不能完成任務”,還管“完成任務時用戶體驗像不像正式產(chǎn)
品”。
這部分規(guī)定:
? 不要亂用emoji
? 響應要簡潔
? 引用代碼位置時用file_path:line_number
? GitHubissue/PR用owner/repo#123
? toolcall 前不要加冒號
這類細則看起來小,但它們會顯著塑造產(chǎn)品質(zhì)感。
11
在prompts.ts里還定義了:
? DEFAULT_AGENT_PROMPT
核心意思是:
? 你是ClaudeCode的agent
? 用工具完成任務
? 任務要完整,不要半成品
? 完成后給簡潔報告
這說明主線程與子agent在prompt結(jié)構上是有分層的。
6.1 5.1AgentTool/prompt.ts:Agent協(xié)議說明書
這份文件非常值錢。它不是普通說明文,而是AgentTool的模型側(cè)協(xié)議文檔。
它主要說明:
? 如何展示agentlist
? 每個agent的描述格式
? 何時fork自己
? 何時顯式指定subagent_type
? fork與freshagent的區(qū)別
? 什么情況下不要用AgentTool
? 如何寫給子agent的prompt
? foreground / background 的行為差異
? isolation: worktree / remote 的語義
這說明多agent不是暗箱,而是明確寫給模型看的使用協(xié)議。
當fork開啟時,prompt明確告訴模型:
? omitsubagent_type就是fork自己
? fork繼承完整conversationcontext
? 研究任務很適合fork
? 實現(xiàn)任務如果會產(chǎn)生大量中間輸出,也適合fork
? fork很便宜,因為共享promptcache
? 不要給fork單獨設model,否則cache命中會變差
? 不要偷窺fork輸出文件
? 不要預言fork結(jié)果
12
這個設計本質(zhì)上是在解決一個大問題:
怎么讓復雜子任務并行運行,但不污染主上下文
這是多agent系統(tǒng)里非常核心、也非常難做對的一件事。
Agent prompt 里很明確地教育模型:
? freshagent 沒有上下文,要像對新同事briefing一樣寫prompt
? 說明目標和原因
? 說明你已經(jīng)排除了什么
? 提供足夠背景,讓它能做判斷
? 如果要短答,明確說
? 不要把理解任務的工作外包給agent
? 不要寫“基于你的發(fā)現(xiàn)再去修bug”這種偷懶prompt
? 應該給到filepath、line、具體改動要求
這其實是在限制“懶delegation”。也是為什么ClaudeCode的subagent效果會更穩(wěn):主
agent 被prompt強制要求承擔synthesis責任。
從源碼能確認至少有這些內(nèi)建agents:
? GeneralPurposeAgent
? ExploreAgent
? PlanAgent
? Verification Agent
? ClaudeCodeGuideAgent
? Statusline Setup Agent
這說明Anthropic的方向不是讓一個agent什么都做,而是:
? 探索給Explore
? 規(guī)劃給Plan
? 驗證給Verification
? 通用任務給GeneralPurpose
這是典型的specialization 思路。
exploreAgent.ts 的system prompt 很有代表性。它明確規(guī)定:
13
6.5.1 絕對只讀
? 不能創(chuàng)建文件
? 不能修改文件
? 不能刪除文件
? 不能移動文件
? 不能寫臨時文件
? 不能用重定向/heredoc寫文件
? 不能運行任何改變系統(tǒng)狀態(tài)的命令
? 用Glob/Grep/FileRead快速探索代碼庫
? Bash只允許讀操作:ls,git status,git log,git diff,find,grep,cat,head,
tail
? 盡量并行用工具
? 要快,盡快給結(jié)果
這說明Explore不是“會搜索的普通agent”,而是被故意裁成read?onlyspecialist。
planAgent.ts 的systemprompt也非常清晰:
? 只讀
? 不準改文件
? 需要先理解需求
? 需要探索代碼庫、模式、架構
? 需要輸出step?by?stepimplementationplan
? 最后必須列出CriticalFilesforImplementation
這里最關鍵的是:PlanAgent被定義成architect/planner,而不是executor。這樣做的
價值是降低角色混雜。
6.7 5.7Verification Agent:為什么它非常值錢
verificationAgent.ts 是本輪挖掘里非常重要的新增部分。
它的prompt非常強,核心方向不是“確認實現(xiàn)看起來沒問題”,而是:
你的工作是trytobreakit
它甚至在prompt開頭就點出兩類失敗模式:
1. verification avoidance:只看代碼、不跑檢查、寫PASS就走
2. 被前80%迷惑:UI看起來還行、測試也過了,就忽略最后20%的問題
然后prompt強制要求:
? build
14
? testsuite
? linter / type?check
? 根據(jù)變更類型做專項驗證
? frontend要跑瀏覽器自動化/頁面子資源驗證
? backend要curl/fetch 實測響應
? CLI要看stdout/stderr/exit code
? migration 要測up/down和已有數(shù)據(jù)
? refactor 也要測publicAPIsurface
? 必須做adversarialprobes
? 每個check必須帶command和outputobserved
? 最后必須輸出VERDICT: PASS / FAIL / PARTIAL
這說明VerificationAgent 不是“再跑一次測試”,而是一個adversarialvalidator。
這非常強,因為它把很多LLM常見的“差不多就算了”直接用prompt反制掉了。
這是本次新增的第二個重點:Agent調(diào)度鏈深挖。
從AgentTool.tsx與runAgent.ts看,主鏈路可以抽象為:
1. 主模型決定調(diào)用Agent工具
2. AgentTool.call() 解析輸入
3. 解析是否teammate/fork/built?in/ background / worktree / remote
4. 選擇agentdefinition
5. 構造promptmessages
6. 構造/繼承systemprompt
7. 組裝工具池
8. 創(chuàng)建agent?specific ToolUseContext
9. 注冊hooks/skills / MCPservers
10. 調(diào)用runAgent()
11. runAgent() 內(nèi)部再調(diào)用query()
12. query 產(chǎn)出消息流
13. runAgent 記錄transcript、處理lifecycle、清理資源
14. AgentTool 匯總結(jié)果或走異步任務通知
這已經(jīng)是一條非常完整的subagentruntimepipeline。
AgentTool.call() 的職責遠比“轉(zhuǎn)發(fā)到子agent”復雜。它要處理:
? 解析輸入?yún)?shù):description、prompt、subagent_type、model、run_in_background、
name、team_name、mode、isolation、cwd
15
? 判斷是否multi?agentteammatespawn
? 解析teamcontext
? 判斷是否允許background
? 區(qū)分forkpath與normalpath
? 根據(jù)permissionrules過濾agent
? 檢查MCPrequirements
? 計算selectedAgent
? 處理remoteisolation
? 構造systemprompt/promptmessages
? 注冊foreground/asyncagenttask
? 啟動worktreeisolation
? 調(diào)用runAgent()
也就是說,AgentTool本質(zhì)上是agentorchestrationcontroller。
源碼里有非常明顯的分叉:
? subagent_type省略且forkfeature開啟
? 繼承主線程systemprompt
? 用buildForkedMessages()構造promptmessages
? 用父線程完整context
? 工具集盡量與父線程一致,保證promptcache命中
? useExactTools = true
? 明確指定built?in/customagenttype
? 基于agentDefinition生成新的agentsystemprompt
? 只給該agent所需上下文
? 走該agent的toolrestrictions
這里最值錢的地方是:fork不是“再開一個普通agent”,而是為了cache和context繼
承專門優(yōu)化過的執(zhí)行路徑。
在注釋里可以看出,forkpath會盡量繼承父線程的systemprompt和tooldefs,以保持API
request prefix byte?identical,從而提高 prompt cache 命中。
這是非常高級的設計:
? 普通人只想“子任務能跑”
? ClaudeCode想的是“子任務能跑,而且盡量復用主線程cache,不白燒token”
這就是產(chǎn)品級系統(tǒng)思維。
16
AgentTool.call() 會根據(jù)條件決定:
? foreground sync path
? asyncbackgroundpath
? remotelaunchedpath
? teammatespawnedpath
? 注冊asyncagenttask
? 獨立abortcontroller
? 可以在后臺運行
? 完成后通過notification回到主線程
? 可選自動summarization
? 可查看outputFile但prompt里明確不鼓勵偷看
? 主線程等待結(jié)果
? 可以在執(zhí)行中被background化
? 有foregroundtask注冊與progresstracking
這說明ClaudeCode對agentlifecycle的處理是產(chǎn)品化的,而不是“一次函數(shù)調(diào)用”。
runAgent.ts 負責的事情很多:
? 初始化agent?specificMCPservers
? 過濾/克隆contextmessages
? 處理filestatecache
? 獲取system/usercontext
? 對read?onlyagent做claudeMd/gitStatus slimming
? 構造agent?specificpermission mode
? 組裝resolvedtools
? 獲取agentsystemprompt
? 創(chuàng)建abortController
? 執(zhí)行SubagentStarthooks
? 注冊frontmatterhooks
? 預加載frontmatterskills
? 合并agentMCPtools
? 構造subagentToolUseContext
? 調(diào)用query()進入主循環(huán)
? 記錄transcript
? 清理MCP、hooks、perfetto、todo、bashtasks等資源
這說明runAgent不是簡單wrapper,而是子agent的完整runtimeconstructor。
17
initializeAgentMcpServers() 很有意思。
它支持agentDefinition自帶mcpServers,并且可以:
? 從現(xiàn)有配置按名字引用服務器
? 在frontmatter里內(nèi)聯(lián)定義agent?specificMCPserver
? 連接server
? 拉取tools
? 把agent?specific MCPtools 合并進當前agent的tools
? 在agent結(jié)束時做cleanup
這說明agent不只是消費全局MCP,它還可以帶自己的外接能力。這對插件agent/專職
agent 很強。
runAgent() 里還會:
? registerFrontmatterHooks(...)
? 讀取agentDefinition.skills
? 通過getSkillToolCommands()加載技能
? 把skillprompt內(nèi)容預加載成metausermessages注入初始消息
這很關鍵:說明agent本身也是可配置的promptcontainer,而不是固定硬編碼角色。
雖然這次沒有把query.ts全文展開,但從runAgent()能明確看到:
? 真正的模型對話循環(huán)發(fā)生在query({ ... })
? runAgent()只是子agent的上下文準備與生命周期控制器
這就讓整個分層很清楚:
? AgentTool:調(diào)度與模式分流
? runAgent:子agent上下文構造與生命周期管理
? query:真正的模型消息流與tool?calling主循環(huán)
runAgent() 里非常多產(chǎn)品級細節(jié):
? recordSidechainTranscript()
? writeAgentMetadata()
? registerPerfettoAgent()
? cleanupAgentTracking()
? killShellTasksForAgent()
? 清理sessionhooks
18
? 清理clonedfilestate
? 清理todosentry
這說明Anthropic 并不是只讓 subagent “跑起來”,而是把 transcript、telemetry、
cleanup、resume 都納入正式生命周期。
8.1 7.1Skill:不是文檔,而是workflowpackage
源碼里:?SKILL_TOOL_NAME = ’Skill’
在SkillTool/prompt.ts 以及命令系統(tǒng)相關代碼中,它明確要求:
? task匹配skill時必須調(diào)用Skilltool
? 不能只提skill不執(zhí)行
? slashcommand可以視為skill入口
? 如果skill已經(jīng)通過tag注入,則不要重復調(diào)用
這說明Skill是一個first?classprimitive。
可以把它理解成:
? markdownpromptbundle
? 帶frontmattermetadata
? 可聲明allowed?tools
? 可按需注入當前上下文
? 可把重復工作流壓縮成可復用能力包
這比“在systemprompt里塞一堆固定流程”高級很多。
關鍵文件:?src/utils/plugins/loadPluginCommands.ts
插件能提供的能力至少包括:
? markdowncommands
? SKILL.mdskill 目錄
? commandsMetadata
? userConfig
? shellfrontmatter
? allowed?tools
? model/efforthints
? user?invocable
? disable?model?invocation
19
? runtime變量替換
例如支持:?${CLAUDE_PLUGIN_ROOT}?${CLAUDE_PLUGIN_DATA}?${CLAUDE_SKILL_DIR}? ${CLAUDE_SESSION_ID}? ${user_config.X}
所以plugin不是普通CLI插件,而是模型行為層面的擴展單元。
關鍵文件:?src/services/tools/toolHooks.ts
Hook支持:?PreToolUse?PostToolUse?PostToolUseFailure
而且hook結(jié)果不僅僅能“記日志”,還能:
? 返回message
? blockingError
? updatedInput
? permissionBehavior
? preventContinuation
? stopReason
? additionalContexts
? updatedMCPToolOutput
這意味著Hook是runtimepolicylayer。
resolveHookPermissionDecision() 說明:
? hook可以給出allow/ask/deny
? 但hook的allow也不自動突破settingsdeny/askrules
? 如果需要userinteraction或requireCanUseTool,仍然要走統(tǒng)一permissionflow
? hook還能通過updatedInput滿足交互輸入
這說明Hook強,但沒有繞開核心安全模型。
從prompts.ts可以明確看到:
? getMcpInstructionsSection()
? getMcpInstructions(mcpClients)
邏輯是:?如果connectedMCPserver提供instructions? 就把這些instructions 拼進
system prompt
也就是說MCP能同時注入:
1. 新工具
2. 如何使用這些工具的說明
這讓MCP的價值遠高于簡單toolregistry。
20
9.1 8.1toolExecution.ts:真正的工具runtime主線
Claude Code 的工具執(zhí)行并不是“模型決定→直接跑函數(shù)”。實際鏈路大致是:
1. 找tool
2. 解析MCPmetadata
3. 做inputschema校驗
4. 做validateInput
5. 為Bash啟動speculativeclassifier check
6. 運行PreToolUsehooks
7. 解析hookpermissionresult
8. 走permission 決策
9. 再次根據(jù)permissionupdatedInput修正輸入
10. 真正執(zhí)行tool.call()
11. 記錄analytics / tracing / OTel
12. 運行PostToolUse hooks
13. 處理structured output / tool_result block
14. 失敗則走PostToolUseFailure hooks
這是一條標準的runtimepipeline,而不是直連函數(shù)調(diào)用。
工具執(zhí)行前會先做:
? Zodschemaparse
? tool?specific validateInput
如果失?。?直接生成tool_result錯誤消息?記錄tengu_tool_use_error
這保證模型隨便亂生成參數(shù)時不會直接污染執(zhí)行層。
在runPreToolUseHooks() 中,hook可以產(chǎn)出:
? 普通message
? hookPermissionResult
? hookUpdatedInput
? preventContinuation
? stopReason
? additionalContext
? stop
最關鍵的幾個能力是:
hook 可以改寫輸入,但不一定做權限決策。
21
hook 可以直接說:?allow?ask?deny
即使沒deny,也能阻止流程繼續(xù)。
這使得Hook能真正參與控制流。
這段邏輯非常值錢。它定義了:
? hookallow不一定繞過settings規(guī)則
? 如果tool要求userinteraction,而hook沒提供updatedInput,則仍要走canUseTool
? ask類型hook會作為forceDecision傳遞下去
? deny類型直接生效
也就是說,Hook的權限語義是被嚴格嵌進總權限模型里的,不是外掛旁路。
runPostToolUseHooks()與runPostToolUseFailureHooks()說明,ClaudeCode不
把“tool成功返回”當終點。
成功后hook還能:?追加message?注入additionalcontext? 阻斷continuation? 對
MCPtool output 進行更新
失敗后hook還能:?補充失敗上下文?發(fā)阻斷說明?給用戶更多恢復線索
這就是為什么整個系統(tǒng)比“toolcall一把梭”可治理得多。
10.1 9.1 它不是一個prompt,而是一個operatingmodel
很多人復刻codingagent時只會拿走:
? 一個systemprompt? 一個文件編輯工具
? 一個bash工具
? 一個CLI殼
但ClaudeCode真實的護城河是:
? Promptarchitecture
? Toolruntimegovernance
? Permission model
? Hookpolicylayer
? Agentspecialization
22
? Skill workflowpackaging
? Pluginintegration
? MCPinstruction injection
? Promptcacheoptimization
? Async/background/remote lifecycle
? Transcript / telemetry / cleanup / task system
少一個都行,但會顯著掉“手感”。
Claude Code 最大的優(yōu)勢之一,不是模型更聰明,而是:
它不把“好習慣”交給模型即興發(fā)揮,而是寫進prompt和runtime規(guī)則里。
例如:?不要亂加功能?不要過度抽象?不要瞎重試被拒絕的工具?不要未驗證就說成功?不
要隨便做風險操作?不要讓fork輸出污染主上下文?匹配skill時必須執(zhí)行skill?verification
不能只看代碼,必須跑命令
這種制度化,會極大提高系統(tǒng)一致性。
源碼中大量設計都在圍繞上下文做優(yōu)化:
? systemprompt動靜邊界
? promptcacheboundary
? forkpath共享cache
? skill 按需注入
? MCPinstructions 按連接狀態(tài)注入
? function result clearing
? summarizetoolresults
? compact/transcript / resume
這說明他們不是把token當免費空氣,而是當runtime預算來管理。
Explore / Plan / Verification 這套 built?in agents 的價值,不在于“多了三個agent”,而在
于:
? 研究和探索不用污染主線程
? 規(guī)劃和實現(xiàn)分離,降低混亂
? 驗證獨立出來,對抗“實現(xiàn)者bias”
很多系統(tǒng)的問題,就是一個agent既研究、又規(guī)劃、又實現(xiàn)、又驗收,最終哪件事都不夠穩(wěn)
定。
Claude Code 則是明確分工。
23
這是ClaudeCode另一個很強的點。
很多系統(tǒng)也有插件,也有工具,也有外部協(xié)議,但模型本身不知道:?有哪些擴展?什么時
候該用?怎么用
Claude Code 不一樣。它通過:?skills列表?agent列表?MCPinstructions?session
specific guidance? command integration
讓模型“知道自己的擴展能力是什么”。這才是生態(tài)真正能發(fā)揮作用的關鍵。
11.1 10.1 核心Prompt文件
11.1.1 主系統(tǒng)提示詞
? 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
? 以及更多prompt.ts
? 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
24
? 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
11.3.1 Skill
? 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
如果要再往下繼續(xù)深挖,下一輪我建議重點看:
1. query.ts:主會話循環(huán)與模型交互流
2. resumeAgent.ts:agent 恢復機制
3. loadSkillsDir:skills 完整加載鏈
4. pluginLoader:插件加載與內(nèi)建插件生態(tài)
5. systemPromptSections.ts:prompt section registry 細節(jié)
6. coordinator/*:多agent協(xié)調(diào)器模式
7. attachments.ts:skill / agent listing / MCP delta 的消息注入方式
8. AgentSummary:后臺agent進度總結(jié)機制
25
如果只給一句話總結(jié)這份增強版研究報告:
Claude Code的真正秘密,不是一段systemprompt,而是一個把promptarchi
tecture、tool runtime、permission model、agent orchestration、skill pack
aging、pluginsystem、hooksgovernance、MCPintegration、contexthygiene
和productengineering 全部統(tǒng)一起來的系統(tǒng)。
這就是為什么它不像一個“會調(diào)工具的聊天機器人”,而更像一個真正可擴展、可治理、可
產(chǎn)品化的AgentOperatingSystem。
馬上咨詢: 如果您有業(yè)務方面的問題或者需求,歡迎您咨詢!我們帶來的不僅僅是技術,還有行業(yè)經(jīng)驗積累。
QQ: 39764417/308460098 Phone: 13 9800 1 9844 / 135 6887 9550 聯(lián)系人:石先生/雷先生