12 章分析的核心要点,可视化呈现。515,029 行代码背后每一层设计决策。
Core insights from 12 chapters, visually presented. Every design decision behind 515,029 lines of code.
4 阶段启动流水线,import 阶段就开始并行 I/O。
4-stage boot pipeline. Parallel I/O starts during import evaluation.
核心技巧:在 ~135ms 的 import 求值窗口内,同步启动 MDM 注册表读取、密钥链 OAuth 查询、API Key 查询这三路 I/O。等 import 完成时,数据已经在内存中了。--version 在 <1ms 内返回——零 import 的编译时常量。
Core trick: during the ~135ms import evaluation window, three I/O streams launch in parallel — MDM registry read, Keychain OAuth lookup, API key lookup. By the time imports finish, data is already in memory. --version returns in <1ms — zero-import build-time constant.
没有 DAG,没有规划器。模型自己决定下一步。
No DAGs, no planners. The model decides the next step.
PTL 恢复、MOT 升级、Stop Hook、Token 预算、工具执行……每种有独立状态机
PTL recovery, MOT escalation, stop hooks, token budget, tool execution... each with its own state machine
API 还在流式输出时,工具已经开始执行。只读工具并行,写入工具串行
Tools start executing while API is still streaming. Read-only tools run in parallel, write tools run serially
queryLoop → siblingAbort → toolAbort 层级取消,兄弟错误不影响父级
queryLoop → siblingAbort → toolAbort hierarchy. Sibling errors don't affect parent
把 System Prompt 当缓存系统来设计,每次 API 调用省 90% 的钱。
Design System Prompt as a caching system — save 90% on every API call.
__DYNAMIC_BOUNDARY__ 分界线把它们推到动态区。
4 conditional bits (AskUserQuestion/Agent/Explore/Skill availability) in static zone = 16 prefix hashes = 16 cache entries = hit rate collapse. Fix: __DYNAMIC_BOUNDARY__ pushes them into the dynamic zone.
模型能"想",工具让它能"做"。每个工具默认不安全(fail-closed)。
The model can "think"; tools let it "do". Every tool defaults to unsafe (fail-closed).
读写文件
Read and write files
18 文件 23 项安全检查
18 files, 23 security checks
搜索代码和文件
Search code and files
生成子 Agent 并行工作
Spawn sub-agents in parallel
互联网搜索和抓取
Internet search and fetch
无限外部工具接入
Unlimited external tools
每条命令 metadata 启动时加载,实现懒加载到使用时。
Command metadata loads at startup, but implementations lazy-load on use.
6 个来源按优先级合并——用户/插件命令覆盖内置命令。可用性检查不缓存(因为认证状态会在 /login 后变化)。最大的模块 /insights 有 113KB / 3,200 行,使用双层懒加载 shim。
6 sources merge by priority — user/plugin commands override built-ins. Availability checks are not memoized (auth state changes after /login). The largest module /insights (113KB / 3,200 lines) uses a double-layer lazy shim.
```!``` 和 !`cmd` 语法在发送给模型前执行 shell 命令并替换为输出。安全层检查权限后才执行,且用函数替换(非字符串替换)防止 $$ / $& 腐蚀 shell 输出。
Prompt templates use ```!``` and !`cmd` syntax — shell commands execute and get replaced with output before sending to the model. Security layer checks permissions first, and uses function replacers (not string replacement) to prevent $$ / $& from corrupting shell output.
从免费到昂贵,自动管理 200K-1M Token 上下文窗口。
From free to expensive, auto-managing the 200K-1M token context window.
83.5% (167K) 触发自动压缩。有效窗口 = 总窗口 - min(maxOutput, 20K)
83.5% (167K) triggers auto-compaction. Effective = total - min(maxOutput, 20K)
96.7% (967K) 才触发。更大的窗口意味着更晚的压缩、更低的信息损失
96.7% (967K) to trigger. Larger window = later compression = less info loss
message.id 以包含交错的 tool_results。
Find the latest API usage data (precise), then estimate newer messages at length/4. Parallel tool calls require backtracking to find shared message.id to include interleaved tool_results.
Fail-Closed 哲学:无法证明安全的一律拦截。
Fail-Closed philosophy: anything not provably safe gets blocked.
tree-sitter(主引擎,AST 白名单 4 种结构 + 16 种危险类型)+ shell-quote(备用引擎)。"太复杂"时降级到 shell-quote
tree-sitter (primary, 4 structural + 16 dangerous types) + shell-quote (fallback). "Too complex" downgrades to shell-quote
5 个真实渗透测试发现被修补:IFS 注入、CR 注入、反斜杠双重解析、括号展开混淆、换行符隐藏攻击
5 real pentest findings patched: IFS injection, CR injection, backslash double-parse, brace expansion, quoted newline attacks
可写:cwd + Claude 临时目录 + --add-dir 路径。永远禁止:settings.json(防止沙箱逃逸)
Write: cwd + Claude temp + --add-dir paths. Always denied: settings.json (prevents sandbox escape)
allow/deny 覆盖权限检查。工具 Hook 10 分钟超时,会话结束 Hook 仅 1.5 秒。策略可强制"仅托管 Hook"或禁用所有。
PermissionRequest hooks can output allow/deny to override permission checks. Tool hooks get 10-minute timeout, session end hooks only 1.5s. Policy can enforce "managed hooks only" or disable all.
从简单的子 Agent 到完整的团队协作,按需选择隔离级别。
From simple sub-agents to full team collaboration — choose isolation level as needed.
run_in_background=true 切异步Background async or blocking sync — default sync, run_in_background=true for asyncuseExactTools: true 确保工具池完全一致。父子仅在最后一条 <fork-directive> 处分叉,前缀缓存完全共享。通过 isInForkChild() 禁止嵌套 Fork。
Most elegant design — reuses parent's rendered system prompt bytes (not recompiled), with useExactTools: true for identical tool pools. Parent and child diverge only at the final <fork-directive>, sharing all prefix cache. isInForkChild() prevents nested forks.
.claude/teams/{team}/mailbox/{name}/。4 种寻址:名字、* 广播、UDS 跨会话、Bridge 跨机器。不主动检查收件箱——消息自动投递。
Filesystem-based mailbox at .claude/teams/{team}/mailbox/{name}/. 4 addressing modes: name, * broadcast, UDS cross-session, Bridge cross-machine. No active polling — messages delivered automatically.
统一协议层让 Claude Code 接入任意外部工具和云服务。
A unified protocol layer connects Claude Code to any external tool or cloud service.
本地进程
Local process
服务器推送
Server events
请求响应
Request-response
双向通道
Bidirectional
连接批处理:本地服务器 3 路并发,远程服务器 20 路并发(6.7x 差异,优化网络 vs 子进程开销)。指数退避 1s → 30s。401 自动刷新 Token,403 + WWW-Authenticate 触发 Step-up 认证。
Connection batching: local servers 3-way concurrency, remote 20-way (6.7x difference, optimizing network vs. subprocess overhead). Exponential backoff 1s → 30s. 401 auto-refreshes tokens, 403 + WWW-Authenticate triggers step-up auth.
getAnthropicClient() 根据环境变量透明切换:Anthropic 直连、AWS Bedrock、Azure Foundry、Google Vertex AI
getAnthropicClient() transparently switches by env vars: Anthropic direct, AWS Bedrock, Azure Foundry, Google Vertex AI
跨应用访问:一次登录 IdP → RFC 8693 Token 交换 → 自动认证 N 个 MCP 服务器,无需重复弹窗
Cross-App Access: one IdP login → RFC 8693 Token Exchange → auto-auth N MCP servers, no repeated popups
不是 curses,是一个真正的 React 渲染引擎 + 双缓冲 + 对象池。
Not curses — a real React rendering engine + double buffering + object pools.
_c() 缓存数组对整个函数体做细粒度自动 memoization,即使规模巨大也不会性能崩溃。
"God Component" — 5,005 lines, 280+ imports. Terminals have no routing, so REPL is the sole "page." This is intentional — React Compiler transforms the entire function body with _c() cache arrays for fine-grained auto-memoization, preventing performance collapse despite massive scale.
三层 Flag 架构控制从实验功能到产品形态的一切。
3-tier flag architecture controls everything from experiments to product evolution.
助理模式:7 个子 Flag 联动。SleepTool 无限等待不阻塞、Dreaming 4 阶段记忆整理(定向→收集→合并→修剪)、三重门控防并发
Assistant mode: 7 interlocking sub-flags. SleepTool waits indefinitely without blocking, Dreaming 4-phase memory consolidation (Orient→Gather→Consolidate→Prune), triple-gated concurrency prevention
电子宠物!18 种物种、5 级稀有度(60% 普通 → 1% 传说)、确定性 Hash 生成。一个物种名用 String.fromCharCode() 编码以规避 canary 检测
Virtual pet! 18 species, 5 rarity tiers (60% common → 1% legendary), deterministic hash generation. One species name encoded with String.fromCharCode() to evade canary detection
卧底模式:提交到非内部仓库时自动激活,隐藏模型代号/项目名/AI 身份。无法关闭——安全优先于透明
Stealth mode: auto-activates on non-internal repos, hides model codenames/project names/AI identity. Cannot be disabled — security over transparency
内部版更啰嗦、有主见、挑战假设。tengu_ 前缀证实 "Tengu" 是 Claude Code 内部代号。3 级 GrowthBook SDK Key
Internal version: verbose, opinionated, challenges assumptions. tengu_ prefix confirms "Tengu" is Claude Code's internal codename. 3-tier GrowthBook SDK keys
最小化核心 + 集中式副作用 = 可测试的基础层。
Minimal core + centralized side effects = testable foundation layer.
前缀 b
Prefix b
前缀 a
Prefix a
前缀 r
Prefix r
前缀 t
Prefix t
前缀 w
Prefix w
前缀 m
Prefix m
前缀 d
Prefix d
Task ID = 前缀 + 8 位 base36 随机字符(2.8 万亿种组合,防 symlink 碰撞攻击)。
Task ID = prefix + 8 base36 random chars (2.8 trillion combinations, preventing symlink collision attacks).
比 Redux 更极简:setState(updater) + Object.is 引用比较 + TypeScript DeepImmutable<T> 编译时不可变约束。570 行 AppState 含 100+ 字段跨 13 个功能域
More minimal than Redux: setState(updater) + Object.is reference comparison + TypeScript DeepImmutable<T> compile-time immutability. 570-line AppState with 100+ fields across 13 domains
onChangeAppState:一个函数处理 7 种副作用(权限同步、模型持久化、详细模式、认证缓存清理……),替代 8+ 个分散的通知路径
onChangeAppState: one function handles 7 side effects (permission sync, model persistence, verbose toggle, auth cache cleanup...) replacing 8+ scattered paths
核心是一个 while 循环,但围绕它有 515K 行优化代码
The core is a while loop, but 515K lines of optimization surround it
不预设流程,让 AI 自己判断下一步
No preset workflows — let AI decide the next step
17,885 行安全代码,不确定就拦截
17,885 lines of security code — when in doubt, block it
92% 缓存命中、三层压缩、动态区隔离防缓存击穿
92% cache hit, 3-tier compression, dynamic zone isolation prevents cache busting
Import 期间预取、流式工具执行、Fork Agent 缓存共享
Prefetch during imports, streaming tool execution, Fork Agent cache sharing
每工具限额 + 系统级上限 + 聚合预算,层层兜底
Per-tool limit + system cap + aggregate budget — defense in depth