{"schemaVersion":"1.0","type":"TechArticle","types":["Article","TechArticle"],"slug":"claude-code-v2-1-71-complete-architecture-analysis-report-nnlh5","url":"https://zyvop.com/claude-code-v2-1-71-complete-architecture-analysis-report-nnlh5","title":"Claude Code v2.1.71: Complete Architecture Analysis Report","subtitle":null,"tldr":"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 ...","keywords":[],"entities":["I0veD","cyber security researcher","ZyVOP"],"keyTakeaways":["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."],"headings":["Table of contents","1. Overall architecture overview","1.1 Packaging structure","1.2 High-level architecture diagram","1.3 Module statistics","2. Principle of module system","2.1 Detailed explanation of core functions","2.1.1 C() - CommonJS module factory","2.1.2 k() - ESM module initializer","2.1.3 m1() - Export binding system","2.1.4 e() / W3() - Module interoperability","2.2 Module dependency graph structure","2.3 Module numbering rules","3. Detailed explanation of startup process","3.1 Main function execution flow","3.2 Command processing function Paz()","3.3 Supported entry point types","4. Agent cycle architecture","4.1 Main cycle flow chart","4.2 Core loop code location","4.3 Loop control variables","5. API interaction mechanism","5.1 API client creation","5.2 API call parameter structure"],"outboundLinks":[],"contentText":"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) =&gt; () =&gt; ( 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) =&gt; { // axios 模块代码 module.exports = { /* ... */ }; });2.1.2 k() - ESM module initializer k = (A, q) =&gt; () =&gt; (A &amp;&amp; (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(() =&gt; { // 模块初始化代码 Dependency1(); // 触发依赖初始化 Dependency2(); // 绑定导出 m1(exports, { export1: () =&gt; value1, export2: () =&gt; value2, }); return exports; }); 2.1.3 m1() - Export binding system m1 = (A, q) =&gt; { 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: () =&gt; mainFn, helperFunction: () =&gt; helperFn, CONST_VALUE: () =&gt; 42, });2.1.4 e() / W3() - Module interoperability // e() - CommonJS 转 ESM e = (A) =&gt; A &amp;&amp; A.__esModule ? A : {default: A} // W3() - ESM wrapper W3 = (A) =&gt; ({ __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 &lt;id&gt;\", \"多 Agent 支持（隐藏）\") .option(\"--team-name &lt;name&gt;\", \"团队协调（隐藏）\"); // 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 &gt; 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 xC() Message processing 3773.js gzz() API calls 4286.js iSq(), nS() Stream processing 4286.js Event loop (lines 621-813) tool execution 3768.js Da6kind 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 message_start stream starts Initialization state, recording TTFT start time content_block_start New content block begins Create block accumulator content_block_delta content increment Append text/thinking/tool ​​input thinking_delta Think incrementally Update thought buffer content_block_stop end of block completion block, added to response message_delta Message metadata update Update usage statistics message_stop 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(() =&gt; { const idle = Date.now() - lastEventTime; if (idle &gt; IDLE_TIMEOUT) { stream.abort(); logError(\"Stream idle timeout\"); } else if (idle &gt; IDLE_WARNING) { logWarning(\"Stream idle warning\"); } }, 10000); stream.on('data', () =&gt; { lastEventTime = Date.now(); }); 5.5 Multiple backend support rear end detection function Base URL special handling First Party isFirstParty() api.anthropic.com Full feature support Bedrock isBedrock() bedrock-runtime..amazonaws.com Inference profile Vertex AI isVertex() -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: () =&gt; string; // 用户显示名称 searchHint: string; // 搜索提示文本 // === 描述和文档 === description: () =&gt; Promise&lt;string&gt;; // 详细描述 (异步生成) prompt: () =&gt; Promise&lt;string&gt;; // 系统提示中的说明 // === 模式定义 === inputSchema: () =&gt; ZodSchema; // Zod 输入验证模式 outputSchema: () =&gt; ZodSchema; // Zod 输出验证模式 inputParamAliases?: Record&lt;string, string&gt;; // 参数别名 // === 执行控制 === isEnabled: () =&gt; boolean; // 是否启用 isConcurrencySafe: (input?) =&gt; boolean; // 并发安全性 isReadOnly: () =&gt; boolean; // 只读标志 // === 权限检查 === checkPermissions: ( input: unknown, context: ToolContext ) =&gt; Promise&lt;{ behavior: \"allow\" | \"deny\" | \"ask\"; updatedInput?: unknown; reason?: string; }&gt;; // === 执行 === call: ( input: unknown, context: ToolContext, appState: AppState, progressCallback?: (progress) =&gt; void ) =&gt; Promise&lt;{ data: unknown }&gt;; validateInput?: ( input: unknown, context: ToolContext ) =&gt; Promise&lt;ValidationResult&gt;; // === 渲染和显示 === renderToolUseMessage?: (input) =&gt; string | null; renderToolUseProgressMessage?: (progress) =&gt; JSX.Element; renderToolResultMessage?: (result, ...) =&gt; JSX.Element; renderToolUseRejectedMessage?: () =&gt; JSX.Element; renderToolUseErrorMessage?: (error) =&gt; JSX.Element; // === 使用总结 === getToolUseSummary?: (input) =&gt; string; getActivityDescription?: (input) =&gt; string; // === 分类器输入 === toAutoClassifierInput: (input) =&gt; 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&lt;string&gt;; // 添加工具到队列 addTool(toolUseBlock, assistantMessage): void; // 检查是否可执行 canExecuteTool(isConcurrencySafe): boolean; // 处理执行队列 async processQueue(): Promise&lt;void&gt;; // 执行单个工具 async executeTool(execution: ToolExecution): Promise&lt;void&gt;; // 创建合成错误消息 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 -aor configure Automatically accept file edits dontAsk Configuration No prompts, use preconfigured rules bypassPermissions --dangerously-skip-permissions 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) =&gt; Promise&lt;HookResult&gt;; 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 5-10% reduction 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 =&gt; !isRedundant(m)) // 移除冗余 .map(m =&gt; normalizeContent(m)); // 规范化内容 } // 自动紧凑 async function autocompact(messages, options) { const tokenCount = await countTokens(messages); const threshold = options.contextWindow * 0.8; if (tokenCount &gt; 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) =&gt; { 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) =&gt; { 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 内置) &lt;Box&gt; // 布局容器 &lt;Text&gt; // 文本渲染 &lt;Newline&gt; // 换行 &lt;Static&gt; // 静态内容 10.2 UI component hierarchy &lt;AppContainer&gt; (React 边界) │ ├─ &lt;Provider 层&gt; │ ├─ &lt;SettingsContext.Provider&gt; │ ├─ &lt;SessionContext.Provider&gt; │ ├─ &lt;KeypressContext.Provider&gt; │ ├─ &lt;MouseContext.Provider&gt; │ ├─ &lt;ScrollProvider&gt; │ ├─ &lt;TerminalContext.Provider&gt; │ ├─ &lt;OverflowProvider&gt; │ └─ &lt;StreamingProvider&gt; │ └─ &lt;App&gt; (主组件) │ ├─ &lt;Header&gt; (头部: 状态、模式指示器) │ ├─ &lt;MessageList&gt; (消息历史) │ ├─ &lt;UserMessage&gt; │ ├─ &lt;AssistantMessage&gt; │ ├─ &lt;ToolMessage&gt; │ ├─ &lt;ThinkingMessage&gt; │ └─ &lt;InfoMessage&gt; │ ├─ &lt;ToolConfirmationQueue&gt; (工具确认) │ ├─ &lt;InputDialog&gt; (输入区) │ └─ &lt;StatusBar&gt; (底部状态栏)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&lt;number, BackgroundShell&gt;; 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 =&gt; &lt;Item {...item} /&gt;); } 11. Authentication system 11.1 Supported authentication methods Way environment variables Configuration file illustrate API Key ANTHROPIC_API_KEY settings.json Standard certification Auth Token ANTHROPIC_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 &lt;oauth_token&gt; │ └─ 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 StdioClientTransport local process SSE SSEClientTransport 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 anthropics/official-plugin git Git repository URL https://example.com/repo.git git-subdir Git subdirectory https://example.com/repo.git#subdir 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) =&gt; { // 技能逻辑 } } // 技能调用 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: [&amp;quot;filesystem&amp;quot;, &amp;quot;git&amp;quot;], deniedMcpServers: [&amp;quot;*&amp;quot;], // 域限制 allowManagedDomainsOnly: true, allowedDomains: [&amp;quot;*.company.com&amp;quot;], // Hook 限制 allowManagedHooksOnly: true, // Marketplace 限制 strictKnownMarketplaces: true, knownMarketplaces: [ &amp;quot;https://github.com/anthropics&amp;quot; ], 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&amp;quot;*.js&amp;quot;\" }, // 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/&lt;sessionId&gt;/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 =&gt; s.lastActiveAt &lt; 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() &amp;&amp; !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(() =&gt; { // 只在首次使用时执行 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 &gt;= this.maxConcurrent) { await new Promise(resolve =&gt; 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 ANTHROPIC_API_KEY API key ANTHROPIC_AUTH_TOKEN OAuth token CLAUDE_CONFIG_DIR Configure directory override CLAUDECODE Detect nested runs NODE_OPTIONS Node.js parameters GITHUB_ACTIONS 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","contentHash":"sha256:3e9b4740c83f412e449339ac1be83e08bd00a22c94a7b92f5a9987bacac26f6f","authorName":"I0veD","authorUrl":"https://zyvop.com/author/i0ved","authorSameAs":["https://www.cdxiaodong.life/","https://github.com/cdxiaodong","https://www.linkedin.com/in/%E6%A0%8B-%E7%A8%8B-167b89391/"],"category":null,"tags":[],"audience":"Senior software engineers, systems architects, and technical leads working with software development","tone":"Instructional, practical, code-first","readingTimeMinutes":17,"wordCount":4442,"faqs":null,"primaryTopic":null,"publishedAt":"2026-08-12T05:45:03.941Z","updatedAt":"2026-08-12T05:50:00.203Z","canonicalUrl":"https://www.cdxiaodong.life/article/31d0f0c5-b87c-8043-84a2-d47565f6f9e5"}