Dive into Claude Code: The Design Space of Today's and Future AI Agent Systems

agent 2604.14228
agent-architecturesafetycontext-managementextensibilitymulti-agent

Dive into Claude Code: The Design Space of Today's and Future AI Agent Systems #

Jiacheng Liu, Xiaohan Zhao, Xinyi Shang, Zhiqiang Shen | 2026-04 | Category: agent | Tags: agent-architecture, safety, context-management, extensibility, multi-agent

§1 TL;DR #

首次基于源码 (TypeScript v2.1.88) 解剖生产级 coding agent 完整架构——揭示 "1.6% 决策逻辑 + 98.4% 确定性基础设施" 范式, 追踪 5 values → 13 principles → 实现, 通过 OpenClaw 对比展示部署上下文如何塑造 agent 设计空间。


§2 Q1 / Q2 / Q3 #

Q1 痛点 #

Production coding agents (如 Claude Code) 已广泛使用, 但 Anthropic 只发布用户文档不发布架构描述。学术界缺乏源码级系统分析: 现有工作聚焦 benchmark 评测或 framework API 设计, 没有人追踪 "价值观 → 设计原则 → 实现选择" 的完整链条。27% 的 Claude Code 辅助任务属于 "无此工具就不会尝试" 的质变工作, 说明架构赋能了全新工作流, 但其内部机制对外部开发者是黑盒。

Q2 方法 #

对 Claude Code v2.1.88 源码 (~1,884 文件, ~512K 行 TypeScript) 进行逆向工程的设计空间分析:

  1. 识别 5 个驱动架构的人类价值观 (Human Decision Authority, Safety, Reliable Execution, Capability Amplification, Contextual Adaptability)
  2. 追踪至 13 条设计原则 (deny-first, graduated trust, defense-in-depth, context-as-scarce-resource, minimal scaffolding 等)
  3. 按 6 个重复性设计问题组织分析 (reasoning location, execution engine, safety posture, binding constraint, extensibility, delegation)
  4. 与 OpenClaw (开源多通道 AI 助理网关) 在 6 维度对比
  5. 三级证据体系: Tier A (产品文档) / Tier B (源码验证) / Tier C (重构推理)。

    核心技术壁垒: 五层渐进式上下文压缩管道 (budget reduction → snip → microcompact → context collapse → auto-compact)。5 层之间的交互复杂性是最难复现的工程: snip 的 token savings 对 auto-compact 不可见需要显式传递; microcompact 的 boundary messages 必须 defer 到 API 响应后获得实际 cache_deleted_input_tokens; context collapse 是 read-time virtual projection 不修改存储, 需与 persist/resume 协调。重现此管道需要深刻理解 prompt caching 经济学和 append-only transcript 不变量。

    Q3 结果 #

    • 核心范式: agent 系统由极简 while-loop (queryLoop AsyncGenerator) + 庞大确定性基础设施构成
    • 权限: 7 modes + 7 层独立安全机制, 93% approval rate 暴露 approval fatigue
    • 扩展: 4 种按 context cost 分层的机制 (hooks 零 → skills 低 → plugins 中 → MCP 高)
    • 上下文: 5 层渐进 compaction pipeline
    • 委派: summary-only return + sidechain transcript + worktree isolation, teams 约 7× token 消耗
    • 通过 OpenClaw 对比证明: 设计问题是稳定的, 答案取决于部署上下文
    • 提出 6 个未来方向 (observability gap, cross-session persistence, harness evolution, horizon scaling, governance, human capability preservation)

    §3 架构 / 方法图 #

    系统总体架构 #

    Figure 1: High-level system structure of Claude Code

    Paper's Figure 1 (caption: "High-level system structure of Claude Code. Seven functional components: user, interfaces, agent loop, permission system, tools, state & persistence, execution environment. All entry surfaces converge on the same agent loop.")

    Claude Code 的核心架构是 7 组件结构: 所有入口 (Interactive CLI, Headless CLI, Agent SDK, IDE) 汇聚到统一的 agent loop, loop 向 permission system 提议动作, 批准后触达 tools, tools 与 execution environment 交互返回结果。这个设计的关键特征是入口多态但执行路径单一——无论从哪个 interface 进入, 核心 queryLoop() 函数完全相同。

    单轮执行流程 #

    Figure 2: Runtime turn flow

    Paper's Figure 2 (caption: "Runtime turn flow showing end-to-end execution of a single agentic turn: user prompt → context assembly → model call → permission gate → tool execution → result feedback → compaction.")

    每个 agentic turn 的 9 步固定序列: settings resolution → mutable state init → context assembly → 5 pre-model shapers → model call → tool-use dispatch → permission gate → tool execution & result collection → stop condition check。核心洞察: loop 自身极简 (while-true + stop check), 所有复杂性在 surrounding subsystems。

    五层子系统分解 #

    Figure 3: Expanded layered architecture

    Paper's Figure 3 (caption: "Expanded layered architecture: Surface, Core, Safety/Action, State, Backend.")

    五层架构将 7 组件进一步展开: Surface 层 (入口面) → Core 层 (agent loop + compaction) → Safety/Action 层 (permission + hooks + tools + sandbox + subagent) → State 层 (context assembly + persistence + memory) → Backend 层 (execution environments + external resources)。Safety/Action 层最复杂, 包含 7 种独立安全机制。

    Agent Loop 状态机 (Mermaid) #

    stateDiagram-v2 [*] --> ContextAssembly: user prompt ContextAssembly --> PreModelShapers: messages ready PreModelShapers --> ModelCall: shaped context ModelCall --> StopCheck: response received StopCheck --> ToolDispatch: has tool_use blocks StopCheck --> [*]: no tool_use (turn complete) ToolDispatch --> PermissionGate: tool request PermissionGate --> ToolExecution: allowed PermissionGate --> ModelCall: denied (reason fed back) PermissionGate --> UserPrompt: ask (await approval) UserPrompt --> ToolExecution: approved UserPrompt --> ModelCall: rejected (reason fed back) ToolExecution --> ResultCollection: tool_result ResultCollection --> ModelCall: append & loop ModelCall --> Recovery: context overflow Recovery --> ModelCall: reactive compact / fallback Recovery --> [*]: unrecoverable

    Agent loop 是 ReAct 模式的 AsyncGenerator 实现。没有显式规划图、树搜索或 backtracking。当 permission 被拒绝时, denial reason 反馈给模型, 模型在下一轮修正方法——这是 recovery-oriented 设计而非 hard-stop。

    Permission Gate 流程 #

    Figure 4: Permission gate overview

    Paper's Figure 4 (caption: "Permission gate overview and design principles.")

    Permission pipeline 的 4 阶段: Pre-filtering → PreToolUse hook → Rule evaluation (deny-first) → Permission handler (4 分支: Coordinator / Swarm worker / Speculative classifier / Interactive fallback)。关键设计: hook allow 不绕过后续检查, denial 是 routing signal 而非 hard stop。

    Context Compaction Pipeline (Mermaid) #

    stateDiagram-v2 [*] --> BudgetReduction: per-message size limits BudgetReduction --> Snip: lightweight trim Snip --> Microcompact: time-based + cache-aware Microcompact --> ContextCollapse: read-time projection ContextCollapse --> Check: still over threshold? Check --> AutoCompact: yes Check --> [*]: no (proceed to model call) AutoCompact --> [*]: model-generated summary

    5 层按 aggressiveness 递增: budget reduction (always active, 只裁 per-message) → snip (lightweight, 旧历史) → microcompact (time-based + cache-aware, deferred boundaries) → context collapse (virtual projection, 不修改存储) → auto-compact (full model summarization, 仅最后手段)。


    §4 作者证明 #

    无形式化作者证明 — 仅实证 (架构分析论文)

    本文不提出新算法或数学模型, 而是对已部署系统的源码级逆向工程分析。其 "证明" 方法:

    符号/术语含义
    Tier A产品文档直接引用
    Tier B源码验证 (文件名+行号)
    Tier C重构推理 (社区分析/推断)
    Values (5)Authority, Safety, Reliability, Capability, Adaptability
    Principles (13)Table 1 中的设计原则
    Components (7)user, interfaces, agent loop, permission, tools, state, execution
    Layers (5)surface, core, safety/action, state, backend

    6 项验证检查 #

    1. Source traceability: 所有架构 claim 引用具体 TypeScript 源文件 (query.ts, permissions.ts, tools.ts, sessionStorage.ts 等) — ✓ 通过
    2. Design-space completeness: 6 个 recurring design questions 覆盖 agent 系统设计空间的主要维度 — ✓ 通过 (reasoning, engine, safety, constraint, extensibility, delegation)
    3. Contrastive validation: OpenClaw 对比在 6 维度上展示了替代设计选择的可行性 — ✓ 通过
    4. External empirical support: 引用 4 个独立研究 (807-repo Cursor analysis, 304K commits audit, 16-developer RCT, EEG study) — ✓ 通过
    5. Internal consistency: 5 values → 13 principles → implementation 的映射无矛盾 (Table 1 双向可追踪) — ✓ 通过
    6. Limitation acknowledgment: 显式声明逆向工程的认识论限制 (无法确认意图, 静态快照, feature flags) — ✓ 通过
    7. Agent-specific 验证 #

      • Success-rate model: 无。论文不评测 agent 任务成功率, 仅引用 "27% 新工作" 和 "93% approval rate" 作为使用模式佐证
      • Latency budget per turn: 未量化。提及 streaming execution 和 speculative classifier 减少交互延迟, 但无 end-to-end latency 数据
      • Failure mode classification: 引用外部研究识别 14 种 agent failure modes (system-design, inter-agent misalignment, task verification), 78% AI failures invisible; 非本文原创分析
      • 可能被 bounded 的指标: task completion rate as $f(\text{context length}, \text{permission mode}, \text{compaction strategy}, \text{tool set size})$——论文未做此 sweep, 但数据结构已支撑

      §5 实验与数据 #

      本文为架构分析论文, 不含传统意义的实验。以下是其关键数据支撑:

      5.1 使用模式数据 #

      数据点来源
      工程师/研究者调查样本132 人Anthropic 内部调查
      "无此工具不会尝试"的任务比例27%同上
      Permission prompt 批准率~93%Claude Code auto-mode 分析
      Auto-approve 率 (新用户 <50 sessions)~20%纵向使用数据
      Auto-approve 率 (老用户 >750 sessions)>40%同上
      Sandboxing 减少 permission prompts~84%架构分析推算

      93% 批准率是关键发现: 它证明交互式确认在行为上不可靠 (approval fatigue), 倒逼架构必须独立于人类警觉性维持安全——这直接驱动了 deny-first + auto-mode classifier + sandboxing 的三重独立机制。

      5.2 代码规模数据 #

      指标
      分析版本v2.1.88
      源文件数~1,884
      代码行数~512K
      AI 决策逻辑占比~1.6%
      操作基础设施占比~98.4%
      Built-in tools54 (19 unconditional + 35 conditional)
      Tool subdirectories42
      Hook event types27 (5 safety + 22 lifecycle)
      Permission modes7
      Slash commands86
      MCP transports6 (stdio, SSE, HTTP, WebSocket, SDK, IDE)

      1.6% vs 98.4% 比例 (Tier C evidence) 是论文最有力的架构论断: 模型推理, harness 执行。大量代码投资在 "让模型做出好决策的条件" 而非 "替代模型做决策"。

      5.3 外部验证研究 #

      研究发现与架构的关联
      Cursor 807-repo 因果分析代码复杂度 +40.7%, 初始速度飙升后三月归基线支持 "skill atrophy" 评估透镜
      304K AI-authored commits 审计~1/4 AI 引入问题持续到最新版本验证需要 verification/reflection 机制
      16 开发者 RCTAI 工具使实际速度 -19% (尽管 perceived +20%)挑战 "capability amplification" 的普适性
      EEG 研究LLM 用户显示持续 neural connectivity 弱化支持 §2.4 "paradox of supervision" 论点

      5.4 OpenClaw 对比数据 (Table 3) #

      DimensionClaude CodeOpenClaw
      System scopeCLI/IDE ephemeral per-sessionPersistent WS gateway daemon, multi-channel
      Trust modelDeny-first per-action + ML classifier + 7 modesSingle trusted operator + perimeter access control
      Agent runtimequeryLoop AsyncGenerator as system centerPi-agent runner embedded in gateway RPC
      Extension4 mechanisms at graduated context costsManifest-first plugin + 12 capability types
      Memory/contextCLAUDE.md 4-level + 5-layer compactionBootstrap files + hybrid search + MEMORY.md/DREAMS.md
      Multi-agentTask-delegating subagents + worktree isolationMulti-agent routing + depth-limited sub-delegation

      对比揭示: 同一设计问题在不同部署上下文 (CLI coding harness vs multi-channel gateway) 下产生根本不同的答案, 证明 agent 设计空间是分层可组合的而非扁平分类。


      §6 论证链 #

      StepPremiseConclusionEvidence Tier
      1AI coding tools 从 autocomplete 进化到 agentic systems (自主规划+执行+迭代), 但内部架构从未被系统分析需要源码级架构分析填补知识缺口A (Anthropic docs) + B (code exists)
      25 个 human values (authority, safety, reliability, capability, adaptability) 驱动 Anthropic 的 agent 设计决策架构是 value-driven 的, 不是随机或纯功能性的A (Constitution + safe-agent framework)
      313 条设计原则可从 5 values 推导且双向可追踪 (Table 1)存在系统化的 value→principle→implementation 映射B (每条原则追踪到具体实现 section)
      4源码验证: queryLoop() 占 ~1.6% 决策逻辑, 其余 98.4% 是确定性操作基础设施Claude Code 实现 "minimal scaffolding + maximal harness" 范式B (query.ts) + C (社区分析比例)
      57 层独立安全机制各自可独立失败而不导致系统性突破Defense-in-depth 优于 single-boundary 设计B (permissions.ts, sandbox, hooks 独立实现)
      64 种扩展机制按 context cost 分层 (零/低/中/高), 对应 3 个注入点分层扩展性解决 "extensibility vs context budget" 矛盾B (Table 2, tools.ts assembleToolPool)
      7OpenClaw 在同样 6 个设计问题上给出不同答案 (perimeter vs per-action, embedded vs central loop)设计问题是稳定的, 答案取决于部署上下文B (OpenClaw source) + 对比分析

      Load-bearing step: Step 4。如果 "minimal scaffolding + maximal harness" 不成立 (例如 Claude Code 实际有大量 hidden scaffolding 在 proprietary server-side), 整个架构范式结论需要修正。


      §7 实现 cross-reference #

      源码引用 (论文中的 Tier B 证据) #

      组件文件关键函数/结构
      Agent loopsrc/query.tsqueryLoop() AsyncGenerator, 9-step pipeline
      Permission systemsrc/permissions.tstoolMatchesRule(), deny-first evaluation
      Auto-mode classifiersrc/yoloClassifier.tstwo-stage ML classification, 3 prompt resources
      Tool poolsrc/tools.tsassembleToolPool() 5-step pipeline, getAllBaseTools()
      Context assemblysrc/context.tsgetSystemContext(), getUserContext()
      Compactionsrc/compact.tscompactConversation(), 5 shapers in query.ts:365-453
      Session persistencesrc/sessionStorage.tsappend-only JSONL transcripts
      CLAUDE.mdsrc/claudemd.ts4-level hierarchy (managed → user → project → local)
      Sandboxsrc/shouldUseSandbox.tsfilesystem/network isolation check
      Subagentsrc/AgentTool.tsx, src/runAgent.ts21-parameter lifecycle, worktree isolation
      Entry pointsrc/main.tsxmain()
      State managementsrc/state/single State object, 7 continue sites
      MCP clientsrc/services/mcp/client.tsmultiple transports (stdio, SSE, HTTP, WS, SDK, IDE)
      Hook pipelinehook events (27 types)PreToolUse, PostToolUse, PermissionRequest etc.
      Streaming executorStreamingToolExecutorsibling abort controller, concurrent-safe classification
      Historysrc/history.tsglobal prompt history

      关键实现细节 (易遗漏) #

      1. Microcompact deferred boundary: CACHED_MICROCOMPACT 路径的 boundary messages 必须在 API 响应之后才能确定 (依赖 actual cache_deleted_input_tokens 而非预估), 这意味着 compaction 决策和 API 调用之间存在 temporal coupling——任何试图 purely pre-compute compaction 的实现都会产生次优结果。
        1. Context collapse 是 read-time projection: CONTEXT_COLLAPSE "nothing is yielded; the collapsed view is a read-time projection over the REPL's full history"——存储层不变, 只有视图层变化。这保持了 append-only invariant 但引入了 view-storage divergence, resume 时必须重建视图。
          1. Permission 不跨 session 恢复: not-restoring-permissions-on-resume 是有意设计——trust state 是 ephemeral, 每次 resume 从 permission mode baseline 重新开始。这防止了 trust state 被序列化攻击, 但增加了用户 re-approval friction。

          2. Agent-Specific Analysis #

            A1. Agent Scope #

            维度特征
            Task classOpen-ended coding (file editing, shell execution, web search, multi-file refactoring)
            Interaction patternMulti-turn within session, ephemeral across sessions
            AutonomyGraduated: plan (human-in-loop) → default → auto (supervised autonomous) → bypassPermissions (fully autonomous)
            BackboneClaude (Anthropic API), 200K-1M context window

            A2. Planning & Reasoning #

            • Planning style: Pure ReAct (think-then-act loop)。Plan permission mode 提供显式规划但被观察为 "基本上是 no-op"——其价值在于保持 agent on-track 而非外部计算
            • Decomposition: 无显式 task decomposition。Model 自行决定是否使用 AgentTool 委派子任务
            • Budget: configurable max turns, context window 隐式限制 step count
            • Backtracking: 无显式 backtracking。Denial → reason fed back → model revises approach。Recovery-oriented, not rollback-oriented

            A3. Tool & Environment Interface #

            • Tool catalog: 54 built-in (JSON schema format) + MCP-provided (dynamic)。命名: built-in 直接名, MCP 为 mcp__server__tool
            • Side effects: Read-only tools 并行执行, state-modifying tools 串行化。StreamingToolExecutor 做 concurrent-safety classification
            • Error surface: Bash tool 错误触发 sibling abort controller 终止并行工具。Tool results 按请求顺序缓冲发出。Model 看到错误 output 作为 tool_result
            • Environment contract: Non-deterministic (文件系统/网络/shell 均有外部副作用), partially observable (只通过 tool_result 看环境)

            A4. LLM Backbone Requirements #

            • Minimum model: 论文未做弱模型消融。整个 values-over-rules 哲学假设模型有 "good judgment", 暗示需要 frontier-class 模型
            • Required capabilities: Long context (200K-1M), structured tool_use format, chain-of-thought, extended thinking (configurable)
            • Backbone sensitivity: 设计假设 Claude; 换模型可能需要更多 scaffolding (minimal scaffolding 范式可能是 Claude-specific)
            • Serving cost: 未量化。Agent teams 约 7× standard token consumption; auto-mode classifier 每次 tool invocation 额外一次 LLM 调用

            A5. Evaluation #

            • Benchmarks: 无。论文不做 benchmark 评测, 是架构分析论文
            • Metrics: 间接——27% 新任务比例, 93% approval rate, auto-approve 纵向增长曲线
            • Baselines: 对比 3 种替代设计族 (LangGraph rule-based, SWE-Agent container-isolated, Aider git-rollback)
            • External evidence: 4 独立研究佐证 (见 §5.3)

            A6. Multi-Agent #

            • Topology: Hierarchical parent-child (非 peer mesh)
            • Coordination: Summary-only return + file locking (agent teams 从 shared list 认领 tasks)
            • Role specialization: 6 种 built-in subagent types (Explore, Plan, General, Guide, Verification, Statusline) + custom agents
            • Failure isolation: Subagent crash 不影响 parent (sidechain transcript 独立, 只有 summary text 返回)
            • Isolation modes: Worktree (git worktree, 文件系统级隔离) / Remote (internal-only) / In-process (共享 FS, 隔离 context)

            A7. Production Readiness #

            • Sandboxing: Shell sandbox (filesystem/network isolation) 独立于 permission system 操作。shouldUseSandbox() runtime check
            • Secrets & auth: 未详述。Permission system 阻止未授权 tool 访问, 但 blast radius 分析不在论文范围内
            • Observability: Append-only JSONL transcript (完整审计轨迹) + 27 hook events。但 context compaction 对用户不可见 (无法检查什么被丢失)
            • Cost/concurrency: Agent teams 7× token consumption。Multi-instance 通过 file locking 协调, 无 distributed coordination service
            • Known vulnerabilities: 2 个 pre-trust initialization ordering CVE (hooks/MCP 在 trust dialog 前执行); >50 subcommands 时安全检查退化为单一 generic approval

            核心技术壁垒 #

            五层渐进式上下文压缩管道 (5-layer context compaction pipeline)。

            此管道的壁垒不在单层算法复杂度, 而在 5 层之间的交互耦合:

            • Snip 的 snipTokensFreed 必须显式传递给 auto-compact 触发条件 (因为 usage field 不幸存 snip 操作)
            • Microcompact 的 CACHED_MICROCOMPACT boundary 必须 defer 到 API response 后才能获得 actual cache metrics
            • Context collapse 是 read-time projection (不修改底层 append-only 存储), 与 session resume 的 state reconstruction 存在视图一致性挑战
            • Auto-compact 依赖 model 生成 summary, 但 summary 质量影响后续所有 turn 的 reasoning——是 irreversible operation

            重现需要: prompt caching 经济学理解 + append-only transcript invariant 维护 + streaming API 的 temporal coupling 处理。


            关键实现细节 #

            1. CLAUDE.md 以 user message 而非 system instruction 传递: 这意味着模型对 project-level 指令的遵从是 probabilistic (可被 adversarial prompt override), 但 permission rules 提供 deterministic enforcement 作为 safety net——两层协作覆盖不同失败模式。
              1. StreamingToolExecutor 的 sibling abort: 当任何 Bash tool 产生错误, abort controller 立即终止所有并行运行的 sibling tools。这是 fail-fast 语义——防止后续 tools 在已知错误基础上继续执行产生级联副作用。