Xpersona
C

Claude Code Architecture

CLAWHUB · Unverified

基于 Claude Code 源码分析提炼的 AI Agent 架构设计模式。当你需要设计/重构 Agent 工具系统、安全门控、上下文压缩、任务编排时使用。 Skill: Claude Code Architecture Owner: wudi488 Summary: 基于 Claude Code 源码分析提炼的 AI Agent 架构设计模式。当你需要设计/重构 Agent 工具系统、安全门控、上下文压缩、任务编排时使用。 Tags: agent:1.0.0, architecture:1.0.0, design-patterns:1.0.0, latest:2.0.3 Version history: v2.0.3 | 2026-05-02T15:11:19.401Z | user 修复: 权限门控未注册工具默认拒绝; execute()加入审批检查; 摘要role从system改assistant v2.0.2 | 2026-05-01T23:14:22.694Z | user 修复: 补全 references/ 5个缺失文件; 移除争议性来源描述; 添加代码写入安全规则 v

62
Rank
84
Safety
1.1k
Downloads

About

What it does, and when to use it.

Capability contract not published. No trust telemetry is available yet. 1.1K downloads reported by the source. Last updated 10/11/2026.

Avoid when

  • Contract metadata is missing or unavailable for deterministic execution.

Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing

Install and run

Setup complexity: low.

clawhub skill install s17adk7beyrksqxwmwvwhhe5an83gzyp:claude-code-architecture
  1. Setup complexity is classified as HIGH. You must provision dedicated cloud infrastructure or an isolated VM. Do not run this directly on your local workstation.
  2. Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.

Contract: missing

curl -s "https://www.xpersona.co/api/v1/agents/clawhub-wudi488-claude-code-architecture/snapshot"

Run-check

$0.02 USD

1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.

Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.

Documentation

CLAWHUB

37,589 characters of source documentation, loaded on request.

Extracted files

4 files captured from the source.

SKILL.md

---
name: claude-code-architecture
description: 基于 Claude Code 源码分析提炼的 AI Agent 架构设计模式。当你需要设计/重构 Agent 工具系统、安全门控、上下文压缩、任务编排时使用。
version: 2.0.3
author: di
tags: [agent, architecture, harness, safety, tool-system]
---

# AI Agent 架构设计模式

> 从公开的 Agent 架构讨论和主流框架设计中提炼的实战设计模式
> 触发:设计Agent工具系统 / 实现安全门控 / 优化上下文管理 / 搭建多Agent编排

---

## ⚡ 快速使用

当 agent 需要进行架构设计时,按场景选择模板:

| 场景 | 对应模板 | 触发词 |
|------|----------|--------|
| 需要工具权限控制 | 模板 A:权限门控 | "生成权限门控代码" |
| Token 消耗太大 | 模板 B:工具按需加载 | "实现工具按需加载" |
| 上下文快满了 | 模板 C:上下文压缩 | "生成上下文压缩方案" |
| 多工具并发 | 模板 D:读写分离 | "实现读写分离调度" |

Agent 应按当前任务选择模板并生成定制代码。

⚠️ **安全规则**:
- 生成代码前须告知用户目标路径,**等待确认再写入**
- 不可直接覆盖已有文件(先备份或询问)
- 建议用户在新分支或沙箱环境中测试生成代码
- 模板代码为设计参考,需要根据实际项目调整

---

## 🏛️ 核心原则

**护城河不是模型,是 harness(框架)** — 任务编排、工具系统、上下文管理、安全机制

### 七大设计模式

| # | 模式 | 一句话 |
|---|------|--------|
| 1 | Initiative/Execution 分离 | 规划层与执行层解耦 |
| 2 | 读写分离并发 | 只读并行,写入排队 |
| 3 | 工具按需加载 | 先给轻量索引,选中后再加载完整参数 |
| 4 | 记忆不记代码 | 代码事实实时从源码读取 |
| 5 | 五级上下文压缩 | 剪裁→精简→折叠→AI总结→强制保留 |
| 6 | 插件式工具架构 | 每个工具独立权限+验证+格式化 |
| 7 | Fail-closed 安全 | 默认拒绝,显式授权 |

---

## 模板 A:权限门控

```python
class ToolPermissionGate:
    """Fail-closed 权限门控。默认拒绝,显式授权。"""
    def __init__(self):
        self.permissions = {}
        self.default = "none"
    
    def can_execute(self, tool_name: str, user: str) -> bool:
        if not self._is_declared_readonly(tool_name):
            return self.permissions.get(user, self.default) >= self._required_level(tool_name)
        return True
    
    def request(self, tool_name: str) -> str:
        return f"⚠️ 需要授权执行 {tool_name}。确认吗?"
```

参考具体实现:`references/permission_gate_full.py`

---

## 模板 B:工具按需加载

```python
class ToolRegistry:
    """轻量索引 → 选中 → 加载完整参数"""
    def __init__(self):
        self.index = {}      # 轻量:名称+用途
        self.loaders = {}    # 完整参数加载器
    
    def list_tools(self) -> list:
        return [{"name": k, "purpose": v} for k, v in self.index.items()]
    
    def get_full(self, name: str) -> dict:
        return self.loaders[name]() if name in self.loaders else None
```

参考具体实现:`references/tool_lazy_loading_full.py`

---

## 模板 C:五级上下文压缩

| 级别 | 方法 | 适用 |
|------|------|------|
| 1 Prune | 删除低价值消息 | 日常清理 |
| 2 Micro | 精简长消息 | 接近限制 |
| 3 Fold | 折叠摘要 | 上下文紧张 |
| 4 Auto | AI 自动总结 | 严重溢出 |
| 5 Hard | 强制保留关键信息 | 最后手段 |

```python
class ContextCompressor:
    LEVELS = {1: "prune", 2: "micro", 3: "fold", 4: "auto", 5: "hard"}
    
    def compress(self, messages: list, level: int, max_tokens: int) -> list:
        # 按级别执行对应压缩策略
        ...
```

参考具体实现:`references/context_compressor_full.py`

---

## 模板 D:读写分离调度

```python
class ReadWriteScheduler:
    """只读操作并发,写操作排队"""
    async def execute(self, ops: list) -> list:
        reads = [op for op in ops if op.is_readonly]
        writes = [op for op in ops if not op.is_readonly]
        
        results = await asyncio.gather(*[self._read(op) for op in reads])
        for op in writes:
            results.append(await self._write(op))
        return results
```

参考具体实现:

_meta.json

{
  "ownerId": "kn764er6cp7n2yqb0wch6zx1dn83h07f",
  "slug": "claude-code-architecture",
  "version": "2.0.3",
  "publishedAt": 1777734679401
}

references/framework_comparison.md

# Agent 框架架构对比

> 从公开资料分析的主流 Agent 框架设计模式对比

---

## 对比矩阵

| 维度 | Claude Code 风格 | OpenAI Agents SDK | LangChain/LangGraph | 本模板 |
|------|-----------------|-------------------|---------------------|--------|
| **工具权限** | Fail-closed 门控 | 声明式 guardrails | 回调链 | 五级权限门控 |
| **工具加载** | 按需索引+完整加载 | 全量注册 | 全量注册 | 两阶段懒加载 |
| **上下文管理** | 五级压缩 | 自动摘要 | 记忆组件 | 五级可配置压缩 |
| **并发模型** | 读写分离 | 异步图执行 | 图状态机 | ReadWriteScheduler |
| **安全边界** | 沙箱+权限 | 输入/输出 guard | 中间件 | 钩子+审计 |

---

## 各框架详析

### Claude Code 风格
- **核心思想**: Harness > Model,框架层承担安全与编排
- **权限模型**: 工具级权限 + 用户确认门控 + sandbox
- **特点**: 激进压缩(五级)、工具 system prompt 动态注入

### OpenAI Agents SDK
- **核心思想**: Agent = LLM + tools + handoffs
- **权限模型**: Input/output guardrails + 声明式 safety checks
- **特点**: Agent 间 handoff、tracing 内建、轻量级

### LangChain/LangGraph
- **核心思想**: Chain/Graph 作为编排原语
- **权限模型**: Callback middleware + 自定义检查
- **特点**: 生态丰富、学习曲线陡峭、状态管理强

---

## 选择建议

| 场景 | 推荐 |
|------|------|
| 需要严格控制工具权限 | 本模板 A + Claude Code 风格 |
| 多 Agent 协作 + handoff | OpenAI Agents SDK |
| 复杂工作流 + 状态管理 | LangGraph |
| Token 敏感 + 大量工具 | 本模板 B:工具按需加载 |
| 高并发工具调用 | 本模板 D:读写分离 |

skill-card.md

## Description:

Provides Chinese-language AI agent architecture patterns for designing or refactoring tool systems, safety gates, context compression, and task orchestration.

This skill is ready for commercial/non-commercial use.

## Publisher:

[wudi488](https://clawhub.ai/user/wudi488)

### License/Terms of Use:

MIT-0

## Use Case:

Developers and agent framework engineers use this skill as a reference template pack when designing permission gates, lazy tool loading, context compression, and read/write scheduling for agent harnesses.

### Deployment Geography for Use:

Global

## Known Risks and Mitigations:

Risk: Safety-critical templates may lead to unsafe authorization behavior if copied directly into a production agent.

Mitigation: Review and adapt generated permission-gate code, including authorization state and approval binding, before use.

Risk: Context compression templates may remove or weaken important safety messages if implemented without safeguards.

Mitigation: Preserve all system and developer safety messages when adapting context-compression logic.

Risk: Template code may not match a target project's security, concurrency, or deployment requirements.

Mitigation: Test adapted code in a branch or sandbox and avoid overwriting existing files without explicit user confirmation.

## Reference(s):

- [ClawHub skill page](https://clawhub.ai/wudi488/skills/claude-code-architecture)
- [SKILL.md](SKILL.md)
- [Permission gate implementation](references/permission_gate_full.py)
- [Tool lazy loading implementation](references/tool_lazy_loading_full.py)
- [Context compressor implementation](references/context_compressor_full.py)
- [Read/write scheduler implementation](references/rw_scheduler_full.py)
- [Framework comparison](references/framework_comparison.md)

## Skill Output:

**Output Type(s):** [guidance, markdown, code, shell commands, configuration]

**Output Format:** [Markdown with inline code examples and reference implementations]

**Output Parameters:** [1D]

**Other Properties Related to Output:** [Chinese-language architecture guidance; generated code should be reviewed and adapted before use.]

## Skill Version(s):

2.0.3 (source: frontmatter and server release evidence)

## Ethical Considerations:

Users should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.

Sponsored

Ads related to Claude Code Architecture and adjacent AI workflows.