The reason is that we need to use claude-sdk to do some agent business development. , so it needs to be analyzed, but I am very troubled by their closed source encryption.
Claude Code is a single-file executable program packaged by Bun, with a size of 183MB. All JS code is stuffed in the __BUN Mach-O section, 4945 modules, all obfuscated and compressed. Even if --bytecode is used, Bun still packages the complete JS source code together (bytecode only starts acceleration)
Later it was discovered that this project can be used to decrypt claudecode. Interested experts can decrypt and analyze it by themselves.
Version: 2.1.71
Build time: 2026-03-06T22:45:36Z
package name: @anthropic-ai/claude-code
Analysis date: 2026-03-09
Analysis tools: bun-demincer
Table of contents
Overall architecture overview
Module system principle
Detailed explanation of startup process
Agent cycle architecture
API interaction mechanism
Detailed explanation of tool system
Permissions and security model
Hook system
context management
UI framework and rendering
Authentication system
MCP integration
Plug-ins and Marketplace
telemetry system
Enterprise Strategy Function
Configuring the file system
subagent system
Session management
Git integration
Automatic update mechanism
Key constants and configurations
security features
Performance optimization strategies
Dependency analysis
1. Overall architecture overview
1.1 Packaging structure
cli.js (12.2MB ๅๆไปถ)
โ
โโโ Bun bundler ๆๅ
็ 4,697 ไธชๆจกๅ
โ โโโ 2,894 ไธชๅบ็จๆจกๅ (Claude Code ่ช่บซไปฃ็ )
โ โโโ 1,805 ไธช็ฌฌไธๆนๆจกๅ (vendor)
โ
โโโ ๆจกๅ็ณป็ป่ฟ่กๆถ
โ โโโ C() / k() / m1() / e() / W3()
โ
โโโ ่ตๆบๆไปถ
โโโ resvg.wasm (2.4MB) - SVGๆธฒๆ
โโโ tree-sitter.wasm (201KB) - ไปฃ็ ่งฃๆ
โโโ tree-sitter-bash.wasm (1.3MB) - Bash่งฃๆ1.2 High-level architecture diagram
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLI ๅ
ฅๅฃๅฑ (cli.js) โ
โ Node.js ๅๆไปถๅฏๆง่ก็จๅบ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ 00-runtime.js โ ๆจกๅ็ณป็ป่ฟ่กๆถ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ C() = CommonJS ๆจกๅๅทฅๅ (ๆฐๆงๅ ่ฝฝ) โ โ
โ โ k() = ESM ๆจกๅๅๅงๅๅจ (ๅฏไฝ็จๆง่ก) โ โ
โ โ m1() = ๅฏผๅบ็ปๅฎ็ณป็ป (ๅจๆ getter) โ โ
โ โ e() / W3() = CJSโESM ไบๆไฝๆง่ฝฌๆข โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ 4696.js (Waq) โ ไธปๅ
ฅๅฃๆจกๅ (Commander.js CLI) โ
โ โโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ mcp ๅฝไปค โ auth ๅฝไปค โ plugin ๅฝไปค โ โ
โ โ โโ serve โ โโ login โ โโ validate โ โ
โ โ โโ add-json โ โโ status โ โโ list โ โ
โ โ โโ list โ โโ logout โ โโ install โ โ
โ โ โโ get โ โโ SSO ๆฏๆ โ โโ marketplace โ โ
โ โ โโ remove โ โ โโ skills โ โ
โ โโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ ๆ ธๅฟๆๅกๅฑ โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโ โ
โ โ Auth โ MCP โ Tool โ Agent โ UI โ โ
โ โ OAuth โ Server โ System โ Loop โ React/Ink TUI โ โ
โ โ APIKey โ Stdio โ 15+ๅทฅๅ
ท โ Stream โ ็ปไปถๅๆธฒๆ โ โ
โ โ SSO โ SSE โ ๆ้ๆจกๅ โ ๅญไปฃ็ โ Hooks + Context โ โ
โ โโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ1.3 Module statistics
index | numerical value | illustrate |
|---|---|---|
Total number of modules | 4,697 | Contains vendor |
application module | 2,894 | Claude Code own code |
Vendor module | 1,805 | third party dependencies |
Vendor bag | 127 | Recognized npm packages |
Number of dependent edges | 16,740 | Calling relationships between modules |
average dependency | 3.6 | Average number of dependencies per module |
2. Principle of module system
Claude Code uses Bun bundler to package all source code into a single file and implement module loading through a custom runtime.
2.1 Detailed explanation of core functions
2.1.1 C() - CommonJS module factory
C = (A, q) => () => (
q || A((q = {exports: {}}).exports, q),
q.exports
)Working principle:
1. Receive module functionAand cache variablesq2. Return a lazy-evaluated factory function
3. Execute the module function when called for the first time and cache the results
4. Subsequent calls directly return the cachedexports
Usage scenarios: wraps vendor libraries (axios, semver, etc.) and CJS format modules
Example:
var axios = C((module, exports) => {
// axios ๆจกๅไปฃ็
module.exports = { /* ... */ };
});2.1.2 k() - ESM module initializer
k = (A, q) => () => (A && (q = A(A = 0)), q)Working principle:
1. Receive initialization functionAand cache variablesq2. Executed when called for the first timeA(0)(0 means executed)
3. Cache the return value toq4. Subsequent calls return the cached value
Usage scenarios: Side-effect execution and export binding of ESM module
Example:
var myModule = k(() => {
// ๆจกๅๅๅงๅไปฃ็
Dependency1(); // ่งฆๅไพ่ตๅๅงๅ
Dependency2();
// ็ปๅฎๅฏผๅบ
m1(exports, {
export1: () => value1,
export2: () => value2,
});
return exports;
});
2.1.3 m1() - Export binding system
m1 = (A, q) => {
for (var K in q)
cy6(A, K, {
get: q[K],
enumerable: !0,
configurable: !0,
set: Qtq.bind(q, K)
});
};Working principle:
1. For the target audienceAAdd properties
2. The getter of each attribute points toq[K]function
3. Support dynamic rebinding
4. Configurable and enumerable
use: Implement named export similar to ESM
Example:
var exports = {};
m1(exports, {
mainFunction: () => mainFn,
helperFunction: () => helperFn,
CONST_VALUE: () => 42,
});2.1.4 e() / W3() - Module interoperability
// e() - CommonJS ่ฝฌ ESM
e = (A) => A && A.__esModule ? A : {default: A}// W3() - ESM wrapper
W3 = (A) => ({
__esModule: true,
get default() { return A; },
// ... ๅ
ถไปๅฏผๅบ
})
2.2 Module dependency graph structure
DAG (ๆๅๆ ็ฏๅพ) ไพ่ต็ปๆ:rm1 (ๅ
จๅฑ็ถๆๅ
ฅๅฃ)
โ
yy โ Z46 โ tAA โ G46
โ โ
A7A โ Pf โ M11
โ
K7A โ w7A
โ
$7A (่ๅๆจกๅ)
โ
yo โ iy6 โ J7A โ T7A
โ
ry6, I7A (็ป็ซฏ/ๆธฒๆ)
Features:
- Depth first execution order
- Circular dependencies are resolved through lazy evaluation
- Approximately 4,697 independent module nodes
2.3 Module numbering rules
Number range | type | illustrate |
|---|---|---|
00-runtime.js | runtime | Module system core definition |
0001-289x.js | application module | Claude Code own code |
3000-4697.js | application module | More application modules |
vendor/*.js | third party | npm packages, organized by package name |
3. Detailed explanation of startup process
3.1 Main function execution flow
Node.js ๆง่ก cli.js
โ
ใ้ถๆฎต1ใ็ฏๅขๅๅงๅ (4696.js:288-297)
โโ Uq("main_function_start") - ไบไปถ่ฎฐๅฝ
โโ process.env.NoDefaultCurrentDirectoryInExePath = "1"
โโ txq() - ่ญฆๅๅค็ๅๅงๅ
โโ SIGINT ไฟกๅทๅค็ๅจๆณจๅ
โ
ใ้ถๆฎต2ใๅๆฐๆฃๆต (4696.js:298-322)
โโ -p / --print ๆ ๅฟ (JSON ่พๅบๆจกๅผ)
โโ --init-only ๆ ๅฟ
โโ --sdk-url ๆ ๅฟ (WebSocket ๆจกๅผ)
โโ ็ฆ็จ TTY ๆฃๆต
โโ ้ข่งๆ ผๅผๆฃๆต (markdown/html)
โ
ใ้ถๆฎต3ใๅ
ฅๅฃ็น่ฏๅซ (4696.js:305-318)
โ
โโ GITHUB_ACTIONS โ "github-action"
โโ CLAUDE_CODE_ENTRYPOINT ็ฏๅขๅ้
โ โโ "sdk-typescript" / "sdk-python" / "sdk-cli"
โ โโ "claude-vscode"
โ โโ "claude-desktop"
โ โโ "local-agent"
โ โโ "remote" (SESSION_ACCESS_TOKEN ๆฃๆต)
โโ ้ป่ฎค: "cli"
โ
ใ้ถๆฎต4ใๅฎขๆท็ซฏ็ฑปๅ็กฎๅฎ (4696.js:319)
โโ ig1(_) - ่ฎพ็ฝฎๅ
จๅฑ็ถๆ
โ
ใ้ถๆฎต5ใไธป่ฟ่กๅฝๆฐ่ฐ็จ (4696.js:328)
โโ await Paz() - ๅผๆญฅๅฝไปคๅค็3.2 Command processing function Paz()
Location: 4696.js, line 380
async function Paz() {
// 1. ๅๅปบ Commander.js ๅฎไพ
let q = new Command();// 2. ้
็ฝฎๅ
จๅฑ้้กน
q
.version("2.1.71 (Claude Code)")
.option("-p, --print", "JSON ๆต่พๅบๆจกๅผ")
.option("-w, --worktree [name]", "Git worktree ๆฏๆ")
.option("--tmux", "Tmux ไผ่ฏๅๅปบ")
.option("--enable-auto-mode", "่ชๅจๆจกๅผ๏ผ้่๏ผ")
.option("--agent-id <id>", "ๅค Agent ๆฏๆ๏ผ้่๏ผ")
.option("--team-name <name>", "ๅข้ๅ่ฐ๏ผ้่๏ผ");
// 3. ๆณจๅๅญๅฝไปค
registerMcpCommand(q); // mcp/
registerAuthCommand(q); // auth/
registerPluginCommand(q); // plugin/
registerAgentsCommand(q); // agents
registerDoctorCommand(q); // doctor
registerUpdateCommand(q); // update
// 4. ๅผๆญฅ่งฃๆๅฝไปค่ก
await q.parseAsync(process.argv);
}
3.3 Supported entry point types
entry point | Detection conditions | use |
|---|---|---|
cli | default | Standard command line interface |
github-action | GITHUB_ACTIONS environment variable | GitHub Actions integration |
sdk-typescript | SDK_TYPESCRIPT_MODE | TypeScript SDK calls |
sdk-python | SDK_PYTHON_MODE | Python SDK calls |
sdk-cli | SDK_CLI_MODE | CLI SDK calls |
claude-vscode | VSCODE_EXTENSION | VS Code extension |
claude-desktop | DESKTOP_APP | desktop application |
local-agent | LOCAL_AGENT | local proxy mode |
remote | SESSION_ACCESS_TOKEN | remote session |
4. Agent cycle architecture
4.1 Main cycle flow chart
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ็จๆท่พๅ
ฅ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๆถๆฏ้ขๅค็ + ไธไธๆๆณจๅ
ฅ โ
โ โโ CLAUDE.md ๅ ่ฝฝ โ
โ โโ Git ็ถๆๆณจๅ
ฅ โ
โ โโ ๅฝๅๆฅๆๆณจๅ
ฅ โ
โ โโ ็จๆทๅ
จๅฑๆไปค โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ็ณป็ปๆ็คบๆๅปบ โ
โ โโ ๅทฅๅ
ทๅ่กจ (ๅ
็ฝฎ + MCP) โ
โ โโ ๆ้ๆจกๅผ่ฏดๆ โ
โ โโ ่พๅบๆ ผๅผ่ฆๆฑ โ
โ โโ Beta ๅ่ฝๆ ๅฟ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Agent ไธปๅพช็ฏๅผๅง โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ใๆญฅ้ชค1ใๅพฎ็ดงๅ (microcompact) โ
โ ๆธ
็ๅไฝๆถๆฏๅ
็ด ใๅๅนถ้ๅคๅ
ๅฎน โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ใๆญฅ้ชค2ใ่ชๅจ็ดงๅๆฃๆฅ โ
โ if (tokenCount > threshold) { โ
โ autocompact(messages) โ ็จ LLM ๆ่ฆๅ็ผฉๅๅฒ โ
โ } โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ใๆญฅ้ชค3ใAPI ่ฐ็จ โ
โ messages.create({ โ
โ model, messages, system, tools, โ
โ thinking, betas, stream, ... โ
โ }) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ใๆญฅ้ชค4ใๆตๅผไบไปถๅค็ โ
โ for await (event of stream) { โ
โ switch (event.type) { โ
โ case "message_start": โ ๅๅงๅ, ่ฎฐๅฝ TTFT โ
โ case "content_block_start": โ ๅผๅงๆฐๅ โ
โ case "content_block_delta": โ ๅข้ๅ
ๅฎน โ
โ case "content_block_stop": โ ๅๅฎๆ โ
โ case "message_delta": โ ไฝฟ็จ้ๆดๆฐ โ
โ case "message_stop": โ ๆตๅฎๆ โ
โ } โ
โ } โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ใๆญฅ้ชค5ใๅทฅๅ
ทๆง่กๆฃๆฅ โ
โ if (responseๅ
ๅซ tool_use) { โ
โ for each tool_use { โ
โ โโ ๆ้ๆฃๆฅ (allow/deny/ask) โ
โ โโ Hook ่งฆๅ (PreToolUse) โ
โ โโ ๅทฅๅ
ทๆง่ก โ
โ โโ Hook ่งฆๅ (PostToolUse) โ
โ โโ ็ปๆๆณจๅ
ฅๆถๆฏ โ ็ปง็ปญๅพช็ฏ โ
โ } โ
โ } else { โ
โ ้ๅบๅพช็ฏ โ
โ } โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
(ๅพช็ฏ็ปง็ปญ)4.2 Core loop code location
components | file location | function/module |
|---|---|---|
Main loop entrance | 3549.js |
|
Message processing | 3773.js |
|
API calls | 4286.js |
|
Stream processing | 4286.js | Event loop (lines 621-813) |
tool execution | 3768.js |
|
4.3 Loop control variables
{
maxIterations: 100, // ๆๅคง่ฟญไปฃๆฌกๆฐ
stopOnFirstError: false, // ้่ฏฏๆถๅๆญข
compactThreshold: 0.8, // ๅ็ผฉ้ๅผ (80% ไธไธๆ)
thinkingBudget: 1024, // ๆ่้ข็ฎ (tokens)
streamIdleTimeout: 60000, // ๆต็ฉบ้ฒ่ถ
ๆถ (60็ง)
}5. API interaction mechanism
5.1 API client creation
Location: 4286.js, lines 560-597
async function eb({ maxRetries, model, source }) {
// 1. ็กฎๅฎๅ็ซฏ็ฑปๅ
const backend = D7(); // "firstParty" | "bedrock" | "vertex"// 2. ่ทๅ่ฎค่ฏไฟกๆฏ
const apiKey = await getApiKey();
// 3. ๅๅปบๅฎขๆท็ซฏๅฎไพ
const client = new Anthropic({
apiKey,
maxRetries,
baseURL: getBaseUrl(backend),
defaultHeaders: {
"anthropic-version": "2023-06-01",
...(getBetaHeaders()),
},
});
return client;
}
5.2 API call parameter structure
{
// ๆจกๅ้
็ฝฎ
model: "claude-sonnet-4-6" | "claude-opus-4-6" | "claude-haiku",// ๆถๆฏๅ
ๅฎน
messages: normalizeMessages(rawMessages),
// ็ณป็ปๆ็คบ (ๅธฆ็ผๅญๆงๅถ)
system: [
{ type: "text", text: "...", cache_control: { type: "ephemeral" } },
{ type: "text", text: "..." }
],
// ๅทฅๅ
ทๅฎไน
tools: [
...builtInTools,
...mcpTools,
...customTools
],
// ๅทฅๅ
ท้ๆฉ็ญ็ฅ
tool_choice: "auto" | { type: "tool", name: "..." } | any,
// ่พๅบ้
็ฝฎ
max_tokens: 16384,
// ๆ่ๆจกๅผ้
็ฝฎ
thinking: modelSupportsAdaptive(model)
? { type: "adaptive" }
: { type: "enabled", budget_tokens: N },
// Beta ๅ่ฝ
betas: [
"prompt-caching-2025-07-01", // ๆ็คบ็ผๅญ
"interleaved-thinking-2025-05-14", // ไบค้ๆ่
"token-counting-2025-07-01", // ไปค็่ฎกๆฐ
"server-side-tools-2025-07-01" // ๆๅกๅจ็ซฏๅทฅๅ
ท
],
// ๅ
ๆฐๆฎ
metadata: {
user_id: getUserId()
},
// ๆตๅผๆงๅถ
stream: true,
// ่ฏทๆฑไธญๆญขไฟกๅท
signal: abortController.signal
}
5.3 Detailed explanation of streaming event types
event type | Trigger time | processing action |
|---|---|---|
| stream starts | Initialization state, recording TTFT start time |
| New content block begins | Create block accumulator |
| content increment | Append text/thinking/tool โโinput |
| Think incrementally | Update thought buffer |
| end of block | completion block, added to response |
| Message metadata update | Update usage statistics |
| end of stream | Complete the response and trigger the callback |
5.4 Stream fault tolerance mechanism
// ๆต็ฉบ้ฒ็ๆง
const IDLE_WARNING = 30000; // 30็ง่ญฆๅ
const IDLE_TIMEOUT = 60000; // 60็ง่ถ
ๆถlet lastEventTime = Date.now();
const idleCheck = setInterval(() => {
const idle = Date.now() - lastEventTime;
if (idle > IDLE_TIMEOUT) {
stream.abort();
logError("Stream idle timeout");
} else if (idle > IDLE_WARNING) {
logWarning("Stream idle warning");
}
}, 10000);
stream.on('data', () => {
lastEventTime = Date.now();
});
5.5 Multiple backend support
rear end | detection function | Base URL | special handling |
|---|---|---|---|
First Party |
| api.anthropic.com | Full feature support |
Bedrock |
| bedrock-runtime..amazonaws.com | Inference profile |
Vertex AI |
| -aiplatform.googleapis.com | Beta filtering |
6. Detailed explanation of tool system
6.1 Complete list of built-in tools
6.1.1 File operation tools
Tool name | Module ID | type | Concurrency safety | Function description |
|---|---|---|---|---|
Read | 2545.js | read only | โ | Read files, images, PDFs, Jupyter notebooks |
Write | 3643.js | write | โ | Create or overwrite file contents |
Edit | 4285.js | write | โ | Exact string replacementEdit |
NotebookEdit | 1245.js | write | โ | Edit Jupyter notebook cells |
6.1.2 Search tools
Tool name | Module ID | type | Concurrency safety | Function description |
|---|---|---|---|---|
Glob | 1244.js | read only | โ | File pattern matching (glob syntax) |
Grep | 1244.js | read only | โ | Regular search based on ripgrep |
LSP | 3724.js | read only | โ | Language server protocol code analysis |
ToolSearch | 2545.js | read only | โ | Search available tools |
6.1.3 Network tools
Tool name | Module ID | type | Concurrency safety | Function description |
|---|---|---|---|---|
WebFetch | (condition) | read only | โ | Get web content and process it with AI |
WebSearch | (condition) | read only | โ | web search |
6.1.4 Execution tools
Tool name | Module ID | type | Concurrency safety | Function description |
|---|---|---|---|---|
Bash | (condition) | write | โ | Execute shell command |
PowerShell | (condition) | write | โ | Execute PowerShell commands |
6.1.5 Interactive tools
Tool name | Module ID | type | Function description |
|---|---|---|---|
AskUserQuestion | 2782.js | interaction | Ask user questions/confirm |
EnterPlanMode | (built-in) | interaction | Enter planning mode |
6.1.6 Agent tools
Tool name | Module ID | Function description |
|---|---|---|
Task | 3603.js | Launch subagents to perform complex tasks |
6.1.7 Task management tools
Tool name | Module ID | Function description |
|---|---|---|
TaskCreate | 2548.js | Create new task |
TaskUpdate | 2548.js | Update task status |
TaskGet | 2783.js | Get task details |
TaskList | 2783.js | list all tasks |
TaskStop | 0955.js | Stop task execution |
TaskOutput | 0955.js | Read background task output |
6.1.8 MCP Tools
Tool name | Module ID | Function description |
|---|---|---|
ListMcpResourcesTool | 3727.js | List MCP resources |
ReadMcpResourceTool | 3731.js | Read MCP resources |
TodoWrite | 2410.js | Manage task list |
6.2 Tool definition interface
interface ToolDefinition {
// === ๆ ธๅฟๆ ่ฏ ===
name: string; // ๅทฅๅ
ทๅฏไธๆ ่ฏ็ฌฆ
userFacingName: () => string; // ็จๆทๆพ็คบๅ็งฐ
searchHint: string; // ๆ็ดขๆ็คบๆๆฌ// === ๆ่ฟฐๅๆๆกฃ ===
description: () => Promise<string>; // ่ฏฆ็ปๆ่ฟฐ (ๅผๆญฅ็ๆ)
prompt: () => Promise<string>; // ็ณป็ปๆ็คบไธญ็่ฏดๆ
// === ๆจกๅผๅฎไน ===
inputSchema: () => ZodSchema; // Zod ่พๅ
ฅ้ช่ฏๆจกๅผ
outputSchema: () => ZodSchema; // Zod ่พๅบ้ช่ฏๆจกๅผ
inputParamAliases?: Record<string, string>; // ๅๆฐๅซๅ
// === ๆง่กๆงๅถ ===
isEnabled: () => boolean; // ๆฏๅฆๅฏ็จ
isConcurrencySafe: (input?) => boolean; // ๅนถๅๅฎๅ
จๆง
isReadOnly: () => boolean; // ๅช่ฏปๆ ๅฟ
// === ๆ้ๆฃๆฅ ===
checkPermissions: (
input: unknown,
context: ToolContext
) => Promise<{
behavior: "allow" | "deny" | "ask";
updatedInput?: unknown;
reason?: string;
}>;
// === ๆง่ก ===
call: (
input: unknown,
context: ToolContext,
appState: AppState,
progressCallback?: (progress) => void
) => Promise<{ data: unknown }>;
validateInput?: (
input: unknown,
context: ToolContext
) => Promise<ValidationResult>;
// === ๆธฒๆๅๆพ็คบ ===
renderToolUseMessage?: (input) => string | null;
renderToolUseProgressMessage?: (progress) => JSX.Element;
renderToolResultMessage?: (result, ...) => JSX.Element;
renderToolUseRejectedMessage?: () => JSX.Element;
renderToolUseErrorMessage?: (error) => JSX.Element;
// === ไฝฟ็จๆป็ป ===
getToolUseSummary?: (input) => string;
getActivityDescription?: (input) => string;
// === ๅ็ฑปๅจ่พๅ
ฅ ===
toAutoClassifierInput: (input) => string;
}
6.3 Tool execution process
็จๆท่ฏทๆฑๅทฅๅ
ทไฝฟ็จ
โ
ใๆญฅ้ชค1ใ่พๅ
ฅ้ช่ฏ
โโ inputSchema.safeParse(input)
โโ validateInput(input, context)
โ
ใๆญฅ้ชค2ใๆ้ๆฃๆฅ
โโ checkPermissions(input, context)
โโ "allow" โ ็ปง็ปญ
โโ "deny" โ ๆ็ป๏ผ่ฟๅ้่ฏฏ
โโ "ask" โ ็ญๅพ
็จๆท็กฎ่ฎค
โ
ใๆญฅ้ชค3ใๅนถๅๅฎๅ
จๆฃๆฅ
โโ isConcurrencySafe(input)
โโ ๆฏ โ ๅฏๅนถๅๆง่ก
โโ ๅฆ โ ๅ ๅ
ฅ้ๅ๏ผ้กบๅบๆง่ก
โ
ใๆญฅ้ชค4ใPre Hook ๆง่ก
โโ ่งฆๅ "PreToolUse" hooks
โ
ใๆญฅ้ชค5ใๅทฅๅ
ทๆง่ก
โโ call(input, context, appState, progressCallback)
โโ ่ฟๅบฆๅ่ฐๆดๆฐ UI
โโ ๆฏๆไธญๆญข
โ
ใๆญฅ้ชค6ใ็ปๆๅค็
โโ ่พๅบ้ช่ฏ (outputSchema)
โโ ็ปๆๆ ผๅผๅ
โโ ๆ ๅฐๅฐ tool_result ๆถๆฏ
โ
ใๆญฅ้ชค7ใPost Hook ๆง่ก
โโ ่งฆๅ "PostToolUse" hooks
โ
่ฟๅ็ปๆ็ป Agent6.4 Tool Execution Manager
Location: 3768.js - Da6kind
class ToolExecutionManager {
toolDefinitions: ToolDefinition[];
executionQueue: ToolExecution[];
activeExecutions: Set<string>;// ๆทปๅ ๅทฅๅ
ทๅฐ้ๅ
addTool(toolUseBlock, assistantMessage): void;
// ๆฃๆฅๆฏๅฆๅฏๆง่ก
canExecuteTool(isConcurrencySafe): boolean;
// ๅค็ๆง่ก้ๅ
async processQueue(): Promise<void>;
// ๆง่กๅไธชๅทฅๅ
ท
async executeTool(execution: ToolExecution): Promise<void>;
// ๅๅปบๅๆ้่ฏฏๆถๆฏ
createSyntheticErrorMessage(): ToolResult;
// ่ทๅไธญๆญขๅๅ
getAbortReason(toolId): string;
}
7. Permissions and Security Model
7.1 Three-tier permission rule system
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๆ้่งๅๆฅๆบ (ไผๅ
็บง: ไฝโ้ซ) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ 1. userSettings (~/.claude/settings.json) โ
โ 2. projectSettings (.claude/settings.json) โ
โ 3. localSettings (.claude/settings.json - gitignored) โ
โ 4. session (ไผ่ฏไธดๆถ่ฎพ็ฝฎ) โ
โ 5. cliArg (ๅฝไปค่กๅๆฐ - ๆ้ซไผๅ
็บง) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโๆฏๆก่งๅๅ
ๅซ:
{
toolName: string, // ๅทฅๅ
ทๅ็งฐ
ruleContent?: string, // ่งๅๅ
ๅฎน (ๅฆ่ทฏๅพใๅฝไปคๆจกๅผ)
ruleBehavior: "allow" | "deny" | "ask",
ruleDisplay: string, // ็จๆทๆพ็คบๆ ผๅผ
sourceDisplay: string // ๆฅๆบๆพ็คบๆ ผๅผ
}
7.2 Permission decision-making process
ๅทฅๅ
ท่ฐ็จ่ฏทๆฑ
โ
ใๆญฅ้ชค1ใๅน้
่งๅ
โโ ๆฃๆฅ alwaysDenyRules โ ๆๅน้
โ DENY
โโ ๆฃๆฅ alwaysAllowRules โ ๆๅน้
โ ALLOW
โโ ๆฃๆฅ alwaysAskRules โ ๆๅน้
โ ASK
โ
ใๆญฅ้ชค2ใๅฑ้ฉๆไฝๆฃๆต
โโ Bash ๆ้ๆฃๆฅ
โ โโ ่งๅไธบ "" ๆ ๆ ๆกไปถ โ ๅฑ้ฉ
โ โโ ๅฝไปคๅน้
ๅฑ้ฉๆจกๅผ โ ๅฑ้ฉ
โโ Task ๅ็ฑปๅจๆฃๆฅ
โ โโ classifierType === "TaskType" โ ๅฑ้ฉ
โโ ็ปๅๆฃๆต Phq() = Whq() || Zhq()
โ
ใๆญฅ้ชค3ใๆ้ๆจกๅผๅบ็จ
โโ "bypassPermissions" โ ALLOW (็ป่ฟๆๆๆฃๆฅ)
โโ "acceptEdits" โ ๆไปถ็ผ่พๅทฅๅ
ท ALLOW
โโ "plan" โ ๅทฅๅ
ทไธๆง่ก๏ผไป
่ฟๅ่ฎกๅ
โโ "dontAsk" โ ็จ้ข้
็ฝฎ่งๅๆ้ป่ฎคๆ็ป
โโ "default" โ ๆญฃๅธธๆต็จ
โ
ใๆญฅ้ชค4ใๆฒ็ฎฑๆฃๆฅ
โโ ๆฃๆฅ่ทฏๅพๆฏๅฆๅจๆฒ็ฎฑๅ
โโ ๆฃๆฅๆฏๅฆ่ฎฟ้ฎๅฑ้ฉ่ฎพๅค (/dev/)
โโ ้่ฆๆฒ็ฎฑๅคๆง่ก โ ้ขๅค็กฎ่ฎค
โ
ใๆญฅ้ชค5ใๆ็ปๅณ็ญ
โโ ALLOW โ ๆง่กๅทฅๅ
ท
โโ DENY โ ่ฟๅๆ็ปๆถๆฏ
โโ ASK โ ๆพ็คบ็กฎ่ฎคๅฏน่ฏๆก๏ผ็ญๅพ
็จๆทๅๅบ7.3 Detailed explanation of permission mode
model | Trigger mode | Behavior |
|---|---|---|
default | default | Standard behavior, dangerous operations need to be confirmed |
plan | Enter planning mode | Does not execute the actual tool, only returns the plan |
acceptEdits |
| Automatically accept file edits |
dontAsk | Configuration | No prompts, use preconfigured rules |
bypassPermissions |
| Bypass all permission checks |
7.4 Hazardous operation detection
// ๅฑ้ฉ Bash ๅฝไปคๆจกๅผ
const DANGER_BASH_PATTERNS = [
"rm -rf",
"dd if=",
"mkfs",
"fdisk",
"chmod 000",
"chown -R",
"curl | sh",
"wget | sh",
"eval $(",
// ... ๆดๅค
];// ๅฑ้ฉๅ็ฑปๅจๆฃๆต
function isDangerousClassifier(toolName, ruleContent) {
return classifierType(toolName) === "TaskType";
}
// ็ปๅๆฃๆต
function isDangerousPermission(toolName, ruleContent) {
return isDangerousBash(toolName, ruleContent) ||
isDangerousClassifier(toolName, ruleContent);
}
7.5 Sandbox mechanism
Sandbox type:
1. working directory sandbox- Restrict file access to project directory
2.command sandbox- Limit executable shell commands
3.permission sandbox- Execution control based on permission rules
Forbidden paths:
const FORBIDDEN_PATHS = [
"/dev/zero",
"/dev/random",
"/dev/urandom",
"/dev/full",
"/dev/stdin",
"/dev/stdout",
"/dev/stderr",
"/dev/tty",
"/dev/console",
];8. Hook system
8.1 Hook event type
event name | Trigger time | use |
|---|---|---|
PreToolUse | Before tool execution | Verify, modify input, intercept |
PostToolUse | After successful execution of the tool | Processing results, logs, follow-up actions |
PostToolUseFailure | After tool execution fails | Error handling, cleanup |
SessionStart | Session starts | Initialize resources |
Stop | stop event | Clean up resources |
PermissionRequest | permission request | Custom permission processing |
ConfigChange | Configuration changes | Respond to configuration changes |
Elicitation | elicit events | Custom data collection |
ElicitationResult | elicit results | Process collection results |
InstructionsLoaded | Command loading completed | Verify CLAUDE.md |
SubagentStart | Subagent starts | Initialize subagent environment |
SubagentStop | subagent stopped | Clean up subagent resources |
PreCompact | Before context compression | Back up or analyze conversations |
Notification | notification event | Custom notification handling |
8.2 Hook configuration structure
{
"hooksConfig": {
"enabled": true,
"disabled": [],
"notifications": true
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hookCallbackIds": ["my-validator"],
"timeout": 5000
},
{
"matcher": "Write:path/to/file.js",
"hookCallbackIds": ["my-preprocessor"]
}
],
"PostToolUse": [
{
"matcher": "*",
"hookCallbackIds": ["my-logger"]
}
],
"SessionStart": [
{
"hookCallbackIds": ["init-workspace"]
}
]
}
}8.3 Hook callback interface
interface HookCallback {
id: string;
event: HookEventType;
matcher?: string; // ๅน้
ๅจ (ๅฏ้)
handler: (context: HookContext) => Promise<HookResult>;
timeout?: number; // ่ถ
ๆถๆถ้ด (ๆฏซ็ง)
}interface HookContext {
eventName: string;
toolName?: string;
input?: unknown;
result?: unknown;
error?: Error;
sessionId: string;
timestamp: Date;
}
interface HookResult {
action: "continue" | "modify" | "stop";
modifiedInput?: unknown;
modifiedResult?: unknown;
message?: string;
}
9. Context Management
9.1 Three-stage compression mechanism
level | name | Trigger condition | Processing method | Effect |
|---|---|---|---|---|
L1 | microcompact | Automatically every round | Clean up redundant message elements |
|
L2 | autocompact | exceeds threshold | LLM summary compression | 50-70% reduction |
L3 | reactive compact | API rejection | Emergency compression retry | Make sure the request is successful |
9.2 Detailed explanation of compression process
// ๅพฎ็ดงๅ
function microcompact(messages) {
return messages
.filter(m => !isRedundant(m)) // ็งป้คๅไฝ
.map(m => normalizeContent(m)); // ่ง่ๅๅ
ๅฎน
}// ่ชๅจ็ดงๅ
async function autocompact(messages, options) {
const tokenCount = await countTokens(messages);
const threshold = options.contextWindow * 0.8;
if (tokenCount > threshold) {
// ่ฐ็จ LLM ่ฟ่กๆ่ฆ
const summary = await callLLM({
prompt: COMPACT_PROMPT,
messages: messages,
maxTokens: options.budget
});
return {
messages: createCompactMessages(summary),
stats: {
preCompact: tokenCount,
postCompact: await countTokens(summary),
reduction: 1 - (postCompact / preCompact)
}
};
}
}
// ๅๅบๅผ็ดงๅ
async function reactiveCompact(error) {
if (error.type === "context_too_long") {
const compacted = await autocompact(currentMessages, {
aggressive: true // ๆดๆฟ่ฟ็ๅ็ผฉ
});
return retryWith(compacted.messages);
}
}
9.3 Prompt caching strategy
// ็ผๅญ้
็ฝฎ
const CACHE_CONFIG = {
// REPL ๆจกๅผ๏ผ้ฟ็ผๅญ
repl: {
scope: "ephemeral",
ttl: "1h"
},// ้ป่ฎค๏ผ็ญ็ผๅญ
default: {
scope: "ephemeral",
ttl: "5m"
},
// ๅ
จๅฑ๏ผ็จๆท็บง็ผๅญ
global: {
scope: "global",
ttl: "1h"
}
};
// ๅบ็จ็ผๅญ
function applyCacheControl(blocks, querySource) {
return blocks.map((block, index) => {
const isLast = index === blocks.length - 1;
const config = getCacheConfig(querySource);
return {
...block,
...(isLast ? { cache_control: config } : {})
};
});
}
9.4 Token tracking
Accurate counting:
async function countTokens(messages, tools) {
const response = await client.beta.messages.countTokens({
model: currentModel,
messages,
tools,
betas: ["token-counting-2025-07-01"]
});return {
inputTokens: response.input_tokens,
cacheReadTokens: response.cache_read_input_tokens,
cacheCreationTokens: response.cache_creation_input_tokens
};
}
local estimate(quick prediction):
function estimateTokens(messages) {
return messages.reduce((sum, msg) => {
return sum + estimateMessageTokens(msg);
}, 0);
}function estimateMessageTokens(message) {
// ๆๆฌ: ๅญ็ฌฆๆฐ / 4
// ๅพ็: ๅบๅฎไผฐ็ฎๅผ
// ๅทฅๅ
ท่ฐ็จ: ๅบๅฎไผฐ็ฎๅผ
}
9.5 Context window configuration
Model | context window | Output limits | compression threshold |
|---|---|---|---|
claude-opus-4-6 | 200K | 8192 | 160K (80%) |
claude-sonnet-4-6 | 200K | 8192 | 160K (80%) |
claude-haiku | 200K | 8192 | 160K (80%) |
10. UI framework and rendering
10.1 Technology stack
// ๆ ธๅฟ
React 19.2 // UI ๆกๆถ
Ink 6.x // ็ป็ซฏๆธฒๆๅผๆ// ็ถๆ็ฎก็
React Context API // ๅ
จๅฑ็ถๆ
useState / useEffect // Hooks
// ็ปไปถๅบ (Ink ๅ
็ฝฎ)
<Box> // ๅธๅฑๅฎนๅจ
<Text> // ๆๆฌๆธฒๆ
<Newline> // ๆข่ก
<Static> // ้ๆๅ
ๅฎน
10.2 UI component hierarchy
<AppContainer> (React ่พน็)
โ
โโ <Provider ๅฑ>
โ โโ <SettingsContext.Provider>
โ โโ <SessionContext.Provider>
โ โโ <KeypressContext.Provider>
โ โโ <MouseContext.Provider>
โ โโ <ScrollProvider>
โ โโ <TerminalContext.Provider>
โ โโ <OverflowProvider>
โ โโ <StreamingProvider>
โ
โโ <App> (ไธป็ปไปถ)
โ
โโ <Header> (ๅคด้จ: ็ถๆใๆจกๅผๆ็คบๅจ)
โ
โโ <MessageList> (ๆถๆฏๅๅฒ)
โ โโ <UserMessage>
โ โโ <AssistantMessage>
โ โโ <ToolMessage>
โ โโ <ThinkingMessage>
โ โโ <InfoMessage>
โ
โโ <ToolConfirmationQueue> (ๅทฅๅ
ท็กฎ่ฎค)
โ
โโ <InputDialog> (่พๅ
ฅๅบ)
โ
โโ <StatusBar> (ๅบ้จ็ถๆๆ )10.3 Detailed explanation of core Context
10.3.1 UIStateContext
interface UIState {
// ๆถๆฏๅๅฒ
history: HistoryItem[];
pendingGeminiHistoryItems: HistoryItemWithoutId[];
pendingSlashCommandHistoryItems: HistoryItemWithoutId[];// ๅฏน่ฏๆก็ถๆ
isAuthDialogOpen: boolean;
isSettingsDialogOpen: boolean;
isSessionBrowserOpen: boolean;
isModelDialogOpen: boolean;
isAgentConfigDialogOpen: boolean;
isPermissionsDialogOpen: boolean;
// ๅฝไปค็ณป็ป
slashCommands: SlashCommand[];
commandContext: CommandContext;
commandConfirmationRequest: ConfirmationRequest | null;
// ็กฎ่ฎค่ฏทๆฑ
loopDetectionConfirmationRequest: ConfirmationRequest | null;
permissionConfirmationRequest: PermissionRequest | null;
// ๆตๅๅทฅๅ
ท
streamingState: "idle" | "responding" | "waiting";
pendingToolCalls: TrackedToolCall[];
thought: ThoughtSummary | null;
// ่ๆฏ่ฟ็จ
backgroundShells: Map<number, BackgroundShell>;
activePtyId: number | undefined;
// ไผ่ฏ็ป่ฎก
sessionStats: SessionStatsState;
elapsedTime: number;
// ็ป็ซฏ
terminalWidth: number;
terminalHeight: number;
// UI ๆงๅถ
renderMarkdown: boolean;
copyModeEnabled: boolean;
}
10.3.2 SessionContext
interface SessionContext {
sessionId: string;
sessionStartTime: Date;
metrics: SessionMetrics;
promptCount: number;// ่ฎก็ฎๅฑๆง
totalApiTime: number;
totalToolTime: number;
agentActiveTime: number;
apiTimePercent: number;
toolTimePercent: number;
cacheEfficiency: number;
successRate: number;
totalCachedTokens: number;
}
10.4 Rendering optimization
// ๅข้ๆธฒๆ (damage tracking)
function renderMessages(messages) {
const prevHash = hash(previousMessages);
const currHash = hash(messages);if (prevHash !== currHash) {
// ๅช้ๆฐๆธฒๆๅๅ็้จๅ
const changed = findChangedRegion(prevMessages, messages);
renderRegion(changed);
}
}
// ่ๆๆปๅจ (้ฟๅ่กจ)
function renderLongList(items) {
const visible = calculateVisible(items, scrollPosition);
return visible.map(item => <Item {...item} />);
}
11. Authentication system
11.1 Supported authentication methods
Way | environment variables | Configuration file | illustrate |
|---|---|---|---|
API Key |
| settings.json | Standard certification |
Auth Token |
| settings.json | OAuth token |
Console Login | - | Browser OAuth | Interactive login |
SSO | - | Enterprise configuration | Single sign-on |
11.2 OAuth 2.0 process
็จๆทๆง่ก claude auth login
โ
ๆๅผๆต่งๅจ โ https://platform.claude.com/oauth/authorize
โโ client_id: 9d1c250a-e61b-44d9-88ed-5944d1962f5e
โโ redirect_uri: http://localhost:5454/callback
โโ scope: "openid profile"
โ
็จๆทๆๆ
โ
้ๅฎๅๅฐ localhost ๅ่ฐ
โ
ไบคๆขๆๆ็ โ POST https://platform.claude.com/v1/oauth/token
โ
ๆฅๆถ access_token + refresh_token
โ
ไฟๅญๅฐ ~/.claude/oauth.json
โ
ๅ็ปญ่ฏทๆฑไฝฟ็จ Bearer token11.3 API Key generation
OAuth ็ปๅฝๅ
โ
POST https://api.anthropic.com/api/oauth/claude_cli/create_api_key
โ
โโ Headers:
โ โโ Authorization: Bearer <oauth_token>
โ โโ Content-Type: application/json
โ
โโ Body:
{
"description": "Claude CLI Key",
"expires_after": null
}
โ
่ฟๅ:
{
"api_key": "sk-ant-...",
"created_at": "2026-03-09T00:00:00Z"
}11.4 Token refresh
async function refreshAccessToken() {
const refreshToken = getStoredRefreshToken();const response = await fetch(TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "refresh_token",
refresh_token: refreshToken
})
});
const { access_token, refresh_token: newRefresh } = await response.json();
// ๆดๆฐๅญๅจ
storeTokens({ access_token, refresh_token: newRefresh });
}
12. MCP integration
12.1 MCP transmission method
Way | Implementation class | Applicable scenarios |
|---|---|---|
Stdio |
| local process |
SSE |
| HTTP service |
12.2 MCP server configuration
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed"],
"disabled": false
},
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "${BRAVE_API_KEY}"
}
}
}
}12.3 MCP tool calling process
Agent ๅณๅฎไฝฟ็จ MCP ๅทฅๅ
ท
โ
ๆฅๆพ MCP ๆๅกๅจ่ฟๆฅ
โ
ๆๅปบ tool_use ๆถๆฏ
โ
่ฐ็จ MCP ๆๅกๅจ
โโ stdio: ๅๅ
ฅ stdin, ่ฏปๅ stdout
โโ SSE: ๅ้ HTTP ่ฏทๆฑ
โ
่งฃๆๅๅบ
โโ ๆๅ โ ่ฟๅ tool_result
โโ ๅคฑ่ดฅ โ ่ฟๅ้่ฏฏไฟกๆฏ
โ
็ปง็ปญ Agent ๅพช็ฏ12.4 MCP resource management
// ๅๅบ่ตๆบ
const resources = await mcpClient.listResources();// ่ฏปๅ่ตๆบ
const content = await mcpClient.readResource(uri);
// ่ฎข้
่ตๆบๆดๆฐ
await mcpClient.subscribeResource(uri);
// ่ฐ็จๅทฅๅ
ท
const result = await mcpClient.callTool(name, args);
13. Plug-ins and Marketplace
13.1 Plug-in source types
type | illustrate | Example |
|---|---|---|
github | GitHub repository |
|
git | Git repository URL |
|
git-subdir | Git subdirectory |
|
13.2 Marketplace configuration
{
"marketplaces": [
{
"name": "official",
"source": "github",
"url": "https://github.com/anthropics",
"autoUpdate": true
}
]
}13.3 Plug-in list
{
"name": "my-plugin",
"version": "1.0.0",
"description": "My awesome plugin",
"commands": [
{
"name": "my-command",
"description": "Does something",
"action": "command.js:myHandler"
}
],
"skills": [
{
"name": "my-skill",
"description": "My skill",
"module": "skills/my-skill.js"
}
],
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"handler": "hooks/pre-bash.js"
}
]
}
}13.4 Skills API
// ๆ่ฝๅฎไน
{
name: "my-skill",
description: "Performs a specialized task",
parameters: {
type: "object",
properties: { /* ... */ }
},
handler: async (params, context) => {
// ๆ่ฝ้ป่พ
}
}// ๆ่ฝ่ฐ็จ
const result = await callSkill("my-skill", params);
14. Telemetry system
14.1 Types of data collected
category | event | data |
|---|---|---|
Function usage | tool_executed | Tool name, parameters, duration |
Permissions | permission_request | Tool name, decision, approval type |
cost | cost_threshold_reached | Cost amount, session length |
mistake | error_message | Error type, stack |
renew | update_check | Current version, latest version |
environment | environment_detected | IDE, cloud platform, OS |
14.2 Telemetry event structure
{
eventName: "tengu_tool_executed",
properties: {
tool_name: "Bash",
permission_mode: "default",
approval_type: "ask",
duration_ms: 1234,
success: true
},
userId: "user-uuid",
sessionId: "session-uuid",
timestamp: "2026-03-09T00:00:00Z"
}14.3 GrowthBook Integration
// ๅ่ฝๆ ๅฟ
const features = await growthBook.getFeatures();// A/B ๆต่ฏ
const variant = growthBook.getFeatureValue("experiment-name", "control");
// ่ฟฝ่ธช
growthBook.track("event-name", properties);
14.4 Environmental testing
// IDE ๆฃๆต
const IDES = {
VSCODE: "vscode",
JETBRAINS: ["intellij", "pycharm", "webstorm", /* ... */],
VIM: "vim",
EMACS: "emacs"
};// ไบๅนณๅฐๆฃๆต
const CLOUDS = {
CODESPACES: "codespaces",
GITPOD: "gitpod",
REPLIT: "replit",
AWS: ["aws-lambda", "aws-ec2", "aws-ecs"],
GCP: "gcp-cloud-run",
AZURE: "azure-functions"
};
15. Enterprise Strategy Function
15.1 Hosting setup
{
policySettings: {
// ๆจกๅ้ๅถ
allowedModels: [
"claude-sonnet-4-6",
"claude-haiku"
],// MCP ๆๅกๅจๆงๅถ
allowedMcpServers: ["filesystem", "git"],
deniedMcpServers: ["*"],
// ๅ้ๅถ
allowManagedDomainsOnly: true,
allowedDomains: ["*.company.com"],
// Hook ้ๅถ
allowManagedHooksOnly: true,
// Marketplace ้ๅถ
strictKnownMarketplaces: true,
knownMarketplaces: [
"https://github.com/anthropics"
],
deniedMarketplaces: [],
// ๆ้่งๅ้ๅถ
allowManagedPermissionRulesOnly: true,
// ้ๅฎๆ ๅฟ
managedSettingsLocked: true
}
}
15.2 Policy execution process
็จๆทๆไฝ่ฏทๆฑ
โ
ๆฃๆฅ managedSettingsLocked
โโ true โ ๅชๅบ็จๆ็ฎก่ฎพ็ฝฎ
โโ false โ ๅๅนถ็จๆท่ฎพ็ฝฎ
โ
ๆฃๆฅ allowManagedXOnly
โโ true โ ๅชไฝฟ็จๆ็ฎก้
็ฝฎ
โโ false โ ๅ
่ฎธ็จๆท้
็ฝฎ
โ
้ช่ฏ่ฏทๆฑ็ฌฆๅ็ญ็ฅ
โโ ็ฌฆๅ โ ๆง่ก
โโ ไธ็ฌฆๅ โ ๆ็ป + ่ฎฐๅฝ16. Configuring the file system
16.1 Configuration file location
Scope | path | Git | priority |
|---|---|---|---|
System | /Library/Application Support/Claude Code/ | - | lowest |
User | ~/.claude/settings.json | โ | Low |
Project | .claude/settings.json | โ | middle |
Local | .claude/settings.json (gitignored) | โ | high |
Session | memory (temporary) | - | higher |
CLI | Command line parameters | - | Highest |
16.2 CLAUDE.md system
CLAUDE.md ๅ ่ฝฝ้กบๅบ:
โๅ จๅฑ CLAUDE.md (~/.claude/CLAUDE.md)
โ้กน็ฎ CLAUDE.md (้กน็ฎๆ น/CLAUDE.md)
โๆฌๅฐ CLAUDE.md (.claude/CLAUDE.md)
โๆ็ฎก CLAUDE.md (ไผไธ้ ็ฝฎ)
โ
ๅๅนถๅนถๆณจๅ ฅ็ณป็ปๆ็คบ
16.3 Set Schema
{
// ้็จ่ฎพ็ฝฎ
general: {
vimMode: boolean,
defaultApprovalMode: "default" | "auto_edit" | "yolo" | "plan",
checkpointing: {
enabled: boolean,
interval: number
},
sessionRetention: {
enabled: boolean,
maxDays: number
}
},
// ๆจกๅ่ฎพ็ฝฎ
model: {
name: string,
summarizeToolOutput: { [toolName]: { tokenBudget: number } },
compressionThreshold: 0.5,
disableLoopDetection: false,
skipNextSpeakerCheck: true
},
// ไธไธๆ่ฎพ็ฝฎ
context: {
fileName: "CLAUDE.md",
includeDirectoryTree: true,
includeDirectories: string[],
fileFiltering: {
respectGitIgnore: true,
respectClaudeIgnore: true,
enableRecursiveFileSearch: true,
customIgnoreFilePaths: string[]
}
},
// ๅทฅๅ
ท่ฎพ็ฝฎ
tools: {
sandbox: true,
allowed: { [toolName]: Rule[] },
denied: { [toolName]: Rule[] },
discoveryCommand: "find . -type f -name"*.js""
},
// Hook ่ฎพ็ฝฎ
hooksConfig: {
enabled: true,
disabled: string[],
notifications: true
},
hooks: {
PreToolUse: Hook[],
PostToolUse: Hook[],
// ... ๅ
ถไปไบไปถ
},
// UI ่ฎพ็ฝฎ
ui: {
theme: "dark" | "light",
accessibility: {
highContrast: boolean,
reducedMotion: boolean
},
footer: {
showSessionStats: boolean,
showModelInfo: boolean
}
},
// ๅฎๅ
จ่ฎพ็ฝฎ
security: {
folderTrust: {
enabled: true,
trustedFolders: string[]
},
disableYoloMode: false,
environmentVariableRedaction: true
},
// Agent ่ฎพ็ฝฎ
agents: {
overrides: {
[agentName]: {
enabled: boolean,
modelConfig: {},
runConfig: {
maxTimeMinutes: number,
maxTurns: number
}
}
}
}
}
17. Sub-agent system
17.1 Task tool interface
interface TaskToolParams {
prompt: string; // ไปปๅกๆ่ฟฐ
subagent_type?: string; // ไปฃ็็ฑปๅ
description?: string; // ๆ่ฟฐ
resume?: string; // ๆขๅคๅญไปฃ็ ID
run_in_background?: boolean; // ๅๅฐ่ฟ่ก
name?: string; // ไปปๅกๅ็งฐ
team_name?: string; // ๅข้ๅ็งฐ
mode?: "tmux" | "in-process" | "auto";
isolation?: "shared" | "isolated";
cwd?: string; // ๅทฅไฝ็ฎๅฝ
}17.2 Subagent types
type | illustrate | Start mode |
|---|---|---|
general-purpose | Common tasks | default |
statusline-setup | Status bar configuration | Internal use |
Explore | Code exploration | Internal use |
Plan | Plan generation | Internal use |
ui-ux-designer | UI design | Internal use |
17.3 Subagent life cycle
Task ๅทฅๅ
ท่ฐ็จ
โ
ใๅๅปบใ
โโ ็ๆๅญไปฃ็ ID
โโ ๅๅปบๅญไปฃ็ไผ่ฏ็ฎๅฝ
โโ ๅๅงๅๅญไปฃ็็ถๆ
โ
ใ้
็ฝฎใ
โโ ๅบ็จไปฃ็็ฑปๅ้
็ฝฎ
โโ ่ฎพ็ฝฎๆจกๅๅๅทฅๅ
ท
โโ ็ปงๆฟๆ้็ฆปๆ้
โ
ใๆง่กใ
โโ ๅฏๅจๅญไปฃ็ๅพช็ฏ
โโ ็ฌ็ซไธไธๆ็ฎก็
โโ ไบไปถ้ไฟก
โ
ใๅฎๆใ
โโ ๆถ้็ปๆ
โโ ๆธ
็่ตๆบ
โโ ่ฟๅ็ป็ถไปฃ็17.4 Teamwork
{
team_name: "my-team",
teammates: [
{
agent_id: "agent-1",
agent_name: "Researcher",
agent_type: "general-purpose",
model: "claude-haiku"
},
{
agent_id: "agent-2",
agent_name: "Implementer",
agent_type: "general-purpose",
model: "claude-sonnet-4-6"
}
],
coordination: {
mode: "tmux" | "in-process",
shared_context: boolean
}
}18. Session Management
18.1 Session state
interface SessionState {
sessionId: string;
createdAt: Date;
lastActiveAt: Date;// ๆถๆฏๅๅฒ
messages: Message[];
// ้
็ฝฎๅฟซ็
ง
config: {
model: string;
tools: string[];
permissions: PermissionRules;
};
// ็ป่ฎก
stats: {
turnCount: number;
totalTokens: number;
totalCost: number;
};
// ๅ
ๆฐๆฎ
metadata: {
projectPath: string;
gitBranch?: string;
trustLevel: "trusted" | "untrusted" | "unknown";
};
}
18.2 Session persistence
ไผ่ฏไฟๅญ่งฆๅ:
โโ ๆฏๆฌกๅทฅๅ
ทๆง่กๅ
โโ ๆฏ N ็ง่ชๅจไฟๅญ
โโ ไผ่ฏ็ปๆๆถ
โ
ไฟๅญๅ
ๅฎน:
โโ ๆถๆฏๅๅฒ
โโ ้
็ฝฎๅฟซ็
ง
โโ ไปปๅก็ถๆ
โโ ็ป่ฎกไฟกๆฏ
โ
ๅญๅจไฝ็ฝฎ:
โโ ~/.claude/sessions/<sessionId>/transcript.json18.3 Session recovery
// ๆขๅคๆต็จ
async function resumeSession(sessionId, mode) {
// 1. ๅ ่ฝฝไผ่ฏๆฐๆฎ
const session = await loadSession(sessionId);// 2. ๆขๅค้
็ฝฎ
applyConfig(session.config);
// 3. ๆขๅคๆถๆฏ
restoreMessages(session.messages);
// 4. ๆขๅค็ถๆ
restoreState(session.metadata);
// 5. ๆจกๅผๅค็
if (mode === "fork") {
// ๅๅปบๅๆฏ
sessionId = generateNewId();
copySessionData(sessionId, session);
}
return sessionId;
}
18.4 Session Cleanup
// ่ชๅจๆธ
็
async function cleanupOldSessions() {
const retention = getRetentionDays();
const cutoff = Date.now() - (retention * 86400000);const sessions = await listSessions();
const expired = sessions.filter(s => s.lastActiveAt < cutoff);
for (const session of expired) {
await deleteSession(session.id);
}
}
19. Git integration
19.1 Git command integration
integration point | Function |
|---|---|
state injection | Inject git branch/status into the system prompt |
Worktree | Support creation and management of git worktree |
Submission tracking | Track the number of git commits |
path resolution | Intelligent parsing of git warehouse paths |
19.2 Worktree support
# ๅๅปบ worktree ไผ่ฏ
claude -w feature-branchๆๆๅฎๅ็งฐ
claude -w my-feature
ไธ tmux ็ปๅ
claude -w feature --tmux
19.3 Git state injection
const gitContext = {
branch: await getCurrentBranch(),
status: await getGitStatus(),
recentCommits: await getRecentCommits(5),
root: await getGitRoot()
};// ๆณจๅ
ฅ็ณป็ปๆ็คบ
systemPrompt += `
Current git context:
Branch:${gitContext.branch}Status:${gitContext.status}Recent commits:${gitContext.recentCommits.join('\n')}
`;
20. Automatic update mechanism
20.1 Update check
async function checkForUpdate() {
// 1. ๆฃๆตๅฎ่ฃ
็ฑปๅ
const installType = detectInstallType();// 2. ่ทๅๅฝๅ็ๆฌ
const currentVersion = getVersion();
// 3. ๆฅ่ฏขๆๆฐ็ๆฌ
const latest = await fetchLatestVersion(installType);
// 4. ๆฏ่พ็ๆฌ
if (semver.gt(latest, currentVersion)) {
return {
available: true,
current: currentVersion,
latest: latest,
installType
};
}
return { available: false };
}
20.2 Installation type detection
type | Detection method | Update method |
|---|---|---|
npm-local | package.json exists | npm update |
npm-global | which claude in npm prefix | npm update -g |
native | Binary in specific path | Download new version |
homebrew | brew list claude-code | brew upgrade |
development | .git directory exists | git pull |
20.3 Update channel
{
autoUpdatesChannel: "latest" | "stable" | "beta",channels: {
latest: {
url: "https://registry.npmjs.org/@anthropic-ai/claude-code",
checkInterval: 86400000 // 24ๅฐๆถ
},
stable: {
url: "https://registry.npmjs.org/@anthropic-ai/claude-code",
tag: "latest"
},
beta: {
url: "https://registry.npmjs.org/@anthropic-ai/claude-code",
tag: "beta"
}
}
}
21. Key constants and configurations
21.1 Version information
{
VERSION: "2.1.71",
BUILD_TIME: "2026-03-06T22:45:36Z",
PACKAGE_URL: "@anthropic-ai/claude-code",
FEEDBACK_CHANNEL: "https://github.com/anthropics/claude-code/issues",
README_URL: "https://code.claude.com/docs/en/overview",
ISSUES_EXPLAINER: "report the issue at https://github.com/anthropics/claude-code/issues"
}21.2 Model constants
{
// ้ป่ฎคๆจกๅ
DEFAULT_MODEL: "claude-sonnet-4-6",
DEFAULT_HAIKU: "claude-haiku",
DEFAULT_OPUS: "claude-opus-4-6",// ๆจกๅๆ ๅฐ
MODEL_ALIASES: {
"sonnet": "claude-sonnet-4-6",
"opus": "claude-opus-4-6",
"haiku": "claude-haiku"
}
}
21.3 Timeout configuration
{
// API ่ถ
ๆถ
API_TIMEOUT: 120000, // 2ๅ้
STREAM_IDLE_TIMEOUT: 60000, // 1ๅ้
STREAM_IDLE_WARNING: 30000, // 30็ง่ญฆๅ// ๅทฅๅ
ท่ถ
ๆถ
TOOL_DEFAULT_TIMEOUT: 300000, // 5ๅ้
MCP_TOOL_TIMEOUT: 120000, // 2ๅ้
// Hook ่ถ
ๆถ
HOOK_DEFAULT_TIMEOUT: 5000, // 5็ง
}
21.4 Path constants
{
// ้
็ฝฎ็ฎๅฝ
CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), ".claude"),// ไผ่ฏ็ฎๅฝ
SESSIONS_DIR: path.join(CONFIG_DIR, "sessions"),
// MCP ๆฅๅฟ็ฎๅฝ
MCP_LOGS_DIR: path.join(CONFIG_DIR, "mcp-logs"),
// OAuth ็ผๅญ
OAUTH_CACHE: path.join(CONFIG_DIR, "oauth.json")
}
22. Security features
22.1 Key protection
// ้ฒๆญขๆต่งๅจ็ฏๅข
if (isBrowser() && !dangerouslyAllowBrowser) {
throw new Error("Cannot use API key in browser environment");
}// ็ฏๅขๅ้้ฎ่ฝ
function redactSecrets(str) {
return str
.replace(/sk-ant-[a-zA-Z0-9-]{40,}/g, "sk-ant-***")
.replace(/Bearer[a-zA-Z0-9-]{20,}/g, "Bearer ***");
}
22.2 Folder trust
// ไฟกไปปๆฃๆฅ
function checkFolderTrust(folderPath) {
const trustRecord = getTrustRecord(folderPath);if (!trustRecord) {
return {
trusted: false,
action: "ask",
reason: "Folder not in trust database"
};
}
return {
trusted: trustRecord.trusted,
action: trustRecord.trusted ? "allow" : "deny",
trustDate: trustRecord.date
};
}
22.3 Dangerous path detection
const DANGEROUS_PATHS = [
// ็ณป็ป็ฎๅฝ
"/",
"/System",
"/bin",
"/sbin",
"/etc",// ็จๆทๅ
ณ้ฎ็ฎๅฝ
"/.ssh",
"/.gnupg",
"~/.config",
// ่ฎพๅคๆไปถ
"/dev/*"
];
23. Performance optimization strategies
23.1 Lazy loading
// ๆจกๅๆ้ๅ ่ฝฝ
var heavyModule = k(() => {
// ๅชๅจ้ฆๆฌกไฝฟ็จๆถๆง่ก
return loadHeavyModule();
});23.2 Caching strategy
// ๅค็บง็ผๅญ
interface CacheStrategy {
// ๅ
ๅญ็ผๅญ (ๆๅฟซ)
memory: {
ttl: 60000, // 1ๅ้
maxSize: 1000
},// ๆไปถ็ผๅญ (ไธญ็ญ)
file: {
ttl: 3600000, // 1ๅฐๆถ
location: ".cache/"
},
// API ็ผๅญ (ๆๆ
ขไฝๆไน
)
api: {
ttl: 86400000, // 24ๅฐๆถ
scope: "global"
}
}
23.3 Concurrency control
// ๅนถๅ้ๅถ
class ConcurrencyLimit {
constructor(maxConcurrent) {
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [];
}async run(fn) {
while (this.running >= this.maxConcurrent) {
await new Promise(resolve => this.queue.push(resolve));
}
this.running++;
try {
return await fn();
} finally {
this.running--;
this.queue.shift()?.();
}
}
}
24. Dependency analysis
24.1 Core Vendor Package
package name | Version | use |
|---|---|---|
@anthropic-ai/sdk | latest | Anthropic API Client |
@modelcontextprotocol/sdk | ^1.23.0 | MCP protocol |
react | ^19.2.0 | UI framework |
ink | ^6.x | TUI rendering |
commander | ^12.x | CLI parsing |
zod | ^3.23.8 | Data validation |
chalk | ^5.x | terminal color |
simple-git | ^3.28.0 | Git operations |
24.2 Dependency graph
cli.js
โโ React (UI ๆกๆถ)
โ โโ Ink (TUI)
โโ Commander.js (CLI)
โโ Anthropic SDK (API)
โโ MCP SDK (ๆฉๅฑ)
โโ Zod (้ช่ฏ)
โโ Chalk (ๆ ทๅผ)
โโ simple-git (Git)Appendix A: Key Document Index
File/module | content |
|---|---|
00-runtime.js | module system runtime |
4696.js | CLI entry and command definitions |
3549.js | Agent main loop |
4286.js | API clients and stream processing |
3768.js | Tool Execution Manager |
4300.js | Permission check core |
4441.js | Hook system |
2545.js | Read tools |
4285.js | Edit tool |
3643.js | Write tool |
Appendix B: Environment variables
variable | use |
|---|---|
| API key |
| OAuth token |
| Configure directory override |
| Detect nested runs |
| Node.js parameters |
| GitHub Actions detection |
Appendix C: Glossary
the term | illustrate |
|---|---|
TTFT | Time to First Token, first byte time |
MCP | Model Context Protocol, model context protocol |
Agent | Agent, an abstraction of AI entities |
Tool | Tools, operations that Agent can perform |
Hook | Hooks, event-driven extension points |
Skill | Skills, predefined task processing capabilities |
Compact | Compression, the operation of reducing context length |
REPL | Read-Eval-Print Loop, interactive environment |
TUI | Terminal User Interface, terminal user interface |
End of report
This report is generated based on decompiled source code analysis of Claude Code v2.1.71
Comments (0)
Login to post a comment.