Files
zclaw_openfang/docs/knowledge-base/openfang-technical-reference.md
iven 0eb30c0531 docs: reorganize documentation structure
- Create docs/README.md as documentation index
- Add WORK_SUMMARY_2026-03-16.md for today's work
- Move test reports to docs/test-reports/
- Move completed plans to docs/archive/completed-plans/
- Move research reports to docs/archive/research-reports/
- Move technical reference to docs/knowledge-base/
- Move all plans from root plans/ to docs/plans/

New structure:
docs/
├── README.md                         # Documentation index
├── DEVELOPMENT.md                    # Development guide
├── OPENVIKING_INTEGRATION.md         # OpenViking integration
├── USER_MANUAL.md                    # User manual
├── ZCLAW_AGENT_INTELLIGENCE_EVOLUTION.md
├── archive/                          # Archived documents
├── knowledge-base/                   # Technical knowledge
├── plans/                            # Execution plans
└── test-reports/                     # Test reports

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 08:21:01 +08:00

969 lines
33 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# OpenFang 技术参考文档
> **文档版本**v1.0
> **更新日期**2026-03-13
> **目标**:为 ZClaw 基于 OpenFang 定制开发提供技术参考
---
## 一、项目概述
### 1.1 基本信息
| 属性 | 值 |
|------|-----|
| **项目名称** | OpenFang |
| **GitHub** | https://github.com/RightNow-AI/openfang |
| **技术栈** | Rust (137,728 行代码) |
| **架构** | 14 个 Crates 模块化设计 |
| **定位** | Agent Operating System |
| **许可** | MIT / Apache 2.0 |
### 1.2 核心特性
```
┌─────────────────────────────────────────────────────────────────┐
│ OpenFang 核心特性 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 🚀 性能优势 │
│ ├── 冷启动180ms (OpenClaw: 5.98s, 33x 提升) │
│ ├── 内存占用40MB (OpenClaw: 394MB, 90% 减少) │
│ └── 安装大小32MB (OpenClaw: 500MB, 94% 减少) │
│ │
│ 🔒 安全架构 (16 层纵深防御) │
│ ├── WASM 双重计量沙箱 │
│ ├── Merkle 哈希链审计 │
│ ├── Ed25519 签名代理清单 │
│ ├── 信息流污染追踪 │
│ ├── SSRF 防护 + 机密零化 │
│ └── ... 共 16 层安全机制 │
│ │
│ 🤖 Hands 自主系统 │
│ ├── 7 个自主能力包 (Clip, Lead, Collector, Predictor, etc.) │
│ └── 可扩展的自主任务框架 │
│ │
│ 📡 通道支持 │
│ └── 40+ 集成通道 (微信、飞书、Telegram、Discord, etc.) │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## 二、项目结构
### 2.1 Crate 架构
OpenFang 采用模块化的 Rust Crate 架构:
```
openfang/
├── crates/
│ ├── openfang-kernel/ # 核心 Kernel - Agent 生命周期管理
│ │ ├── src/
│ │ │ ├── kernel.rs # 主内核实现
│ │ │ ├── approval.rs # 审批系统
│ │ │ ├── auth.rs # 认证模块
│ │ │ ├── capabilities.rs # 能力系统
│ │ │ ├── config.rs # 配置管理
│ │ │ ├── scheduler.rs # 任务调度
│ │ │ ├── supervisor.rs # 进程监控
│ │ │ ├── triggers.rs # 触发器引擎
│ │ │ └── workflow.rs # 工作流引擎
│ │ └── Cargo.toml
│ │
│ ├── openfang-runtime/ # Agent Runtime
│ │ ├── agent.rs # Agent 抽象
│ │ ├── session.rs # 会话管理
│ │ └── context.rs # 上下文处理
│ │
│ ├── openfang-hands/ # Hands 自主系统
│ │ ├── clip/ # 视频处理 Hand
│ │ ├── lead/ # 销售线索 Hand
│ │ ├── collector/ # 数据收集 Hand
│ │ ├── predictor/ # 预测分析 Hand
│ │ ├── researcher/ # 深度研究 Hand
│ │ ├── twitter/ # Twitter Hand
│ │ └── browser/ # 浏览器自动化 Hand
│ │
│ ├── openfang-skills/ # 技能系统
│ │ ├── skill_loader.rs # 技能加载器
│ │ ├── skill_executor.rs # 技能执行器
│ │ └── builtin/ # 内置技能 (60+)
│ │
│ ├── openfang-channels/ # 通道适配器
│ │ ├── wechat/ # 微信
│ │ ├── feishu/ # 飞书
│ │ ├── telegram/ # Telegram
│ │ ├── discord/ # Discord
│ │ └── ... # 40+ 通道
│ │
│ ├── openfang-llm/ # LLM 提供商集成
│ │ ├── providers/ # 27 个提供商
│ │ └── openai_compat.rs # OpenAI 兼容层
│ │
│ ├── openfang-security/ # 安全层
│ │ ├── sandbox/ # WASM 沙箱
│ │ ├── audit/ # 审计链
│ │ └── taint/ # 污染追踪
│ │
│ ├── openfang-api/ # API 层
│ │ ├── rest/ # REST 端点
│ │ ├── websocket/ # WebSocket 处理
│ │ └── sse/ # Server-Sent Events
│ │
│ ├── openfang-cli/ # 命令行工具
│ ├── openfang-config/ # 配置解析
│ ├── openfang-migrate/ # OpenClaw 迁移工具
│ └── openfang-utils/ # 通用工具
├── skills/ # 技能定义文件
│ └── *.md # SKILL.md 格式
├── hands/ # Hand 定义文件
│ └── *.toml # HAND.toml 格式
├── Cargo.toml # Workspace 配置
└── README.md
```
### 2.2 Kernel 核心模块
```rust
// crates/openfang-kernel/src/lib.rs
//! Core kernel for the OpenFang Agent Operating System.
//!
//! The kernel manages agent lifecycles, memory, permissions, scheduling,
//! and inter-agent communication.
pub mod approval; // 审批门控系统
pub mod auth; // 认证与授权
pub mod auto_reply; // 自动回复
pub mod background; // 后台任务
pub mod capabilities; // 能力系统 (RBAC)
pub mod config; // 配置管理
pub mod config_reload; // 热重载配置
pub mod cron; // 定时任务
pub mod error; // 错误处理
pub mod event_bus; // 事件总线
pub mod heartbeat; // 心跳检测
pub mod kernel; // 核心实现
pub mod metering; // 计量系统
pub mod pairing; // 设备配对
pub mod registry; // 服务注册
pub mod scheduler; // 任务调度
pub mod supervisor; // 进程监控
pub mod triggers; // 触发器引擎
pub mod whatsapp_gateway; // WhatsApp 网关
pub mod wizard; // 设置向导
pub mod workflow; // 工作流引擎
pub use kernel::DeliveryTracker;
pub use kernel::OpenFangKernel;
```
---
## 三、API 协议
### 3.1 端点概览
| 协议 | 地址 | 用途 |
|------|------|------|
| **WebSocket** | `ws://127.0.0.1:4200/ws` | 实时聊天、事件流 |
| **REST API** | `http://127.0.0.1:4200` | 资源管理、配置 |
| **SSE** | `http://127.0.0.1:4200/events` | 服务器推送事件 |
| **OpenAI 兼容** | `http://127.0.0.1:4200/v1` | OpenAI API 兼容层 |
### 3.2 WebSocket 协议
#### 连接
```javascript
const ws = new WebSocket('ws://127.0.0.1:4200/ws');
// 认证
ws.send(JSON.stringify({
type: 'auth',
device_id: 'your-device-id',
signature: 'ed25519-signature'
}));
```
#### 消息格式
```typescript
// 发送聊天消息
interface ChatRequest {
type: 'chat';
session_id: string;
message: {
role: 'user';
content: string;
};
options?: {
model?: string;
temperature?: number;
max_tokens?: number;
};
}
// 接收流式响应
interface StreamEvent {
type: 'stream';
session_id: string;
delta: {
content?: string;
tool_call?: ToolCall;
};
done: boolean;
}
// Agent 事件
interface AgentEvent {
type: 'agent_event';
event_type: 'thinking' | 'tool_use' | 'tool_result' | 'hand_trigger';
data: any;
}
```
#### 事件类型
```typescript
// 触发器事件
interface TriggerEvent {
type: 'trigger';
trigger_type: 'webhook' | 'schedule' | 'email' | 'message';
payload: any;
}
// 工作流事件
interface WorkflowEvent {
type: 'workflow';
workflow_id: string;
step: string;
status: 'started' | 'completed' | 'failed';
result?: any;
}
// Hand 事件
interface HandEvent {
type: 'hand';
hand_name: string;
action: string;
status: 'running' | 'completed' | 'needs_approval';
result?: any;
}
```
### 3.3 REST API 端点
#### 核心 API (76 个端点)
```
┌─────────────────────────────────────────────────────────────────┐
│ REST API 端点分类 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Agent 管理 │
│ ├── GET /api/agents # 列出所有 Agent │
│ ├── POST /api/agents # 创建 Agent │
│ ├── GET /api/agents/:id # 获取 Agent 详情 │
│ ├── PUT /api/agents/:id # 更新 Agent │
│ ├── DELETE /api/agents/:id # 删除 Agent │
│ └── POST /api/agents/:id/start # 启动 Agent │
│ │
│ Session 管理 │
│ ├── GET /api/sessions # 列出会话 │
│ ├── POST /api/sessions # 创建会话 │
│ ├── GET /api/sessions/:id # 获取会话 │
│ ├── DELETE /api/sessions/:id # 删除会话 │
│ └── GET /api/sessions/:id/messages # 获取消息历史 │
│ │
│ Skills 管理 │
│ ├── GET /api/skills # 列出技能 │
│ ├── POST /api/skills # 创建技能 │
│ ├── GET /api/skills/:id # 获取技能详情 │
│ ├── PUT /api/skills/:id # 更新技能 │
│ └── DELETE /api/skills/:id # 删除技能 │
│ │
│ Hands 管理 │
│ ├── GET /api/hands # 列出 Hands │
│ ├── GET /api/hands/:name # 获取 Hand 详情 │
│ ├── POST /api/hands/:name/trigger # 触发 Hand │
│ └── GET /api/hands/:name/status # 获取 Hand 状态 │
│ │
│ Channels 管理 │
│ ├── GET /api/channels # 列出通道 │
│ ├── POST /api/channels # 添加通道 │
│ ├── GET /api/channels/:id # 获取通道配置 │
│ ├── PUT /api/channels/:id # 更新通道 │
│ └── DELETE /api/channels/:id # 删除通道 │
│ │
│ Workflow 管理 │
│ ├── GET /api/workflows # 列出工作流 │
│ ├── POST /api/workflows # 创建工作流 │
│ ├── GET /api/workflows/:id # 获取工作流详情 │
│ ├── POST /api/workflows/:id/execute # 执行工作流 │
│ └── GET /api/workflows/:id/runs # 获取执行历史 │
│ │
│ Trigger 管理 │
│ ├── GET /api/triggers # 列出触发器 │
│ ├── POST /api/triggers # 创建触发器 │
│ ├── GET /api/triggers/:id # 获取触发器详情 │
│ └── DELETE /api/triggers/:id # 删除触发器 │
│ │
│ 配置管理 │
│ ├── GET /api/config # 获取配置 │
│ ├── PUT /api/config # 更新配置 │
│ └── POST /api/config/reload # 热重载配置 │
│ │
│ 安全与审计 │
│ ├── GET /api/audit/logs # 审计日志 │
│ ├── GET /api/security/status # 安全状态 │
│ └── GET /api/capabilities # 能力列表 │
│ │
└─────────────────────────────────────────────────────────────────┘
```
### 3.4 OpenAI 兼容 API
```bash
# 聊天补全
curl -X POST http://127.0.0.1:4200/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4",
"messages": [
{"role": "user", "content": "Hello!"}
],
"stream": true
}'
# 模型列表
curl http://127.0.0.1:4200/v1/models
# Embeddings
curl -X POST http://127.0.0.1:4200/v1/embeddings \
-H "Content-Type: application/json" \
-d '{
"model": "text-embedding-ada-002",
"input": "Hello world"
}'
```
---
## 四、配置系统
### 4.1 配置文件位置
```
~/.openfang/
├── config.toml # 主配置文件
├── secrets.toml # 敏感配置 (权限 600)
├── skills/ # 自定义技能
│ └── *.md
├── hands/ # 自定义 Hands
│ └── *.toml
├── data/ # 数据目录
│ ├── sessions/ # 会话数据
│ ├── audit/ # 审计日志
│ └── cache/ # 缓存
└── logs/ # 日志目录
```
### 4.2 配置文件格式
```toml
# ~/.openfang/config.toml
[server]
host = "127.0.0.1"
port = 4200
websocket_port = 4200
[agent]
default_model = "gpt-4"
max_tokens = 4096
temperature = 0.7
timeout = 300
[security]
# 16 层安全配置
sandbox_enabled = true
audit_enabled = true
taint_tracking = true
max_execution_time = 60
rate_limit_rpm = 60
[llm]
# LLM 提供商配置
[[llm.providers]]
name = "openai"
api_key = "${OPENAI_API_KEY}"
models = ["gpt-4", "gpt-3.5-turbo"]
[[llm.providers]]
name = "anthropic"
api_key = "${ANTHROPIC_API_KEY}"
models = ["claude-3-opus", "claude-3-sonnet"]
[[llm.providers]]
name = "deepseek"
api_key = "${DEEPSEEK_API_KEY}"
base_url = "https://api.deepseek.com/v1"
models = ["deepseek-chat", "deepseek-coder"]
[channels]
# 通道配置
wechat_enabled = false
feishu_enabled = true
[channels.feishu]
app_id = "${FEISHU_APP_ID}"
app_secret = "${FEISHU_APP_SECRET}"
[hands]
# Hands 配置
clip_enabled = true
lead_enabled = true
researcher_enabled = true
[workflow]
# 工作流配置
max_concurrent = 5
default_timeout = 300
[triggers]
# 触发器配置
webhook_secret = "${WEBHOOK_SECRET}"
```
### 4.3 环境变量
```bash
# LLM API Keys
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export DEEPSEEK_API_KEY="sk-..."
# 通道凭证
export FEISHU_APP_ID="cli_..."
export FEISHU_APP_SECRET="..."
export WECHAT_CORP_ID="..."
# 安全配置
export WEBHOOK_SECRET="your-secret"
export JWT_SECRET="your-jwt-secret"
# 可选配置
export OPENFANG_LOG_LEVEL="info"
export OPENFANG_DATA_DIR="~/.openfang/data"
```
---
## 五、扩展机制
### 5.1 技能系统 (SKILL.md)
```markdown
# skill-name
## 描述
技能的简短描述
## 触发词
- trigger1
- trigger2
## 示例
用户: 帮我执行 skill-name
助手: [执行技能]
## 参数
| 参数 | 类型 | 必需 | 描述 |
|------|------|------|------|
| param1 | string | 是 | 参数描述 |
## 实现
```skill
action: http_request
method: POST
url: https://api.example.com/endpoint
```
## 权限
- network:outbound
- file:read
```
### 5.2 Hand 系统 (HAND.toml)
```toml
# hands/custom-hand/HAND.toml
name = "custom-hand"
version = "1.0.0"
description = "自定义 Hand 描述"
# 触发条件
[trigger]
type = "schedule" # schedule | webhook | event
cron = "0 9 * * *" # 每天 9:00
# 能力需求
[capabilities]
network = true
filesystem = ["read", "write"]
browser = true
# 执行配置
[execution]
timeout = 300
max_retries = 3
approval_required = true
# 输出配置
[output]
channels = ["wechat", "email"]
format = "markdown"
```
### 5.3 自定义 Channel 适配器
```rust
// src/custom_channel.rs
use openfang_channels::{Channel, ChannelConfig, Message};
pub struct CustomChannel {
config: ChannelConfig,
}
impl Channel for CustomChannel {
async fn connect(&mut self) -> Result<(), ChannelError> {
// 连接逻辑
}
async fn send(&self, message: Message) -> Result<(), ChannelError> {
// 发送消息
}
async fn receive(&mut self) -> Result<Message, ChannelError> {
// 接收消息
}
}
```
### 5.4 自定义 LLM 提供商
```rust
// src/custom_provider.rs
use openfang_llm::{LLMProvider, CompletionRequest, CompletionResponse};
pub struct CustomProvider {
api_key: String,
base_url: String,
}
impl LLMProvider for CustomProvider {
async fn complete(
&self,
request: CompletionRequest,
) -> Result<CompletionResponse, LLMError> {
// 实现补全逻辑
}
async fn stream(
&self,
request: CompletionRequest,
) -> Result<impl Stream<Item = StreamChunk>, LLMError> {
// 实现流式响应
}
}
```
---
## 六、Hands 系统详解
### 6.1 内置 Hands
| Hand | 功能 | 触发方式 | 适用场景 |
|------|------|----------|----------|
| **Clip** | 视频处理、竖屏生成 | 手动/自动 | 内容创作者 |
| **Lead** | 销售线索发现 | 定时 | B2B 销售 |
| **Collector** | 数据收集聚合 | 定时/事件 | 研究人员 |
| **Predictor** | 预测分析 | 手动 | 数据分析 |
| **Researcher** | 深度研究、交叉验证 | 手动 | 知识工作者 |
| **Twitter** | Twitter 自动化 | 定时/事件 | 社媒运营 |
| **Browser** | 浏览器自动化 | 手动/工作流 | 日常办公 |
### 6.2 Hand 工作流程
```
┌─────────────────────────────────────────────────────────────────┐
│ Hand 执行流程 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 触发条件 │
│ ──────── │
│ │ 定时 (Cron) │
│ │ Webhook │
│ │ 事件 (Event) │
│ │ 手动触发 │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ 能力检查 │ ← RBAC 门控 │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ 审批门控 │ ← 如果 approval_required = true │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ 执行 Hand │ ← WASM 沙箱隔离 │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ 结果输出 │ → 通道推送 / 存储 │
│ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## 七、安全架构
### 7.1 16 层纵深防御
```
┌─────────────────────────────────────────────────────────────────┐
│ OpenFang 16 层安全架构 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: WASM 双重计量沙箱 │
│ ├── 指令计数限制 │
│ └── 内存使用限制 │
│ │
│ Layer 2: Merkle 哈希链审计 │
│ ├── 所有操作可追溯 │
│ └── 防篡改日志 │
│ │
│ Layer 3: 信息流污染追踪 │
│ ├── 标记不可信数据 │
│ └── 阻止污染数据进入敏感操作 │
│ │
│ Layer 4: Ed25519 签名代理清单 │
│ ├── 设备身份验证 │
│ └── 请求签名验证 │
│ │
│ Layer 5: SSRF 防护 │
│ ├── 白名单域名 │
│ └── 内网地址阻止 │
│ │
│ Layer 6: 机密零化 │
│ ├── API Key 内存加密 │
│ └── 使用后立即清零 │
│ │
│ Layer 7: OFP 互认证 │
│ ├── 双向 TLS │
│ └── 证书固定 │
│ │
│ Layer 8: 能力门控 (RBAC) │
│ ├── 最小权限原则 │
│ └── 细粒度权限控制 │
│ │
│ Layer 9: 安全头 │
│ ├── Content-Security-Policy │
│ └── X-Frame-Options │
│ │
│ Layer 10: 健康端点编辑 │
│ ├── 输入验证 │
│ └── 输出编码 │
│ │
│ Layer 11: 子进程沙箱 │
│ ├── seccomp 过滤 │
│ └── namespace 隔离 │
│ │
│ Layer 12: 提示注入扫描器 │
│ ├── 检测恶意提示 │
│ └── 阻止注入攻击 │
│ │
│ Layer 13: 循环守卫 │
│ ├── 递归深度限制 │
│ └── 自动断路 │
│ │
│ Layer 14: 会话修复 │
│ ├── 异常检测 │
│ └── 自动恢复 │
│ │
│ Layer 15: 路径遍历防护 │
│ ├── 路径规范化 │
│ └── 访问控制 │
│ │
│ Layer 16: GCRA 速率限制 │
│ ├── 请求速率控制 │
│ └── 突发流量平滑 │
│ │
└─────────────────────────────────────────────────────────────────┘
```
### 7.2 WASM 沙箱
```rust
// 沙箱配置示例
SandboxConfig {
max_instructions: 10_000_000,
max_memory: 64 * 1024 * 1024, // 64MB
timeout: Duration::from_secs(60),
allowed_syscalls: vec![
"read", "write", "close",
// 仅允许安全的系统调用
],
network_access: false,
filesystem_access: SandboxFS::ReadOnly("/data"),
}
```
---
## 八、OpenClaw 迁移
### 8.1 迁移工具
```bash
# 从 OpenClaw 迁移
openfang migrate --from openclaw
# 指定源目录
openfang migrate --from openclaw --source ~/.openclaw
# 干运行(预览)
openfang migrate --from openclaw --dry-run
```
### 8.2 迁移映射
| OpenClaw | OpenFang | 说明 |
|----------|----------|------|
| `~/.openclaw/` | `~/.openfang/` | 配置目录 |
| `config.yaml` | `config.toml` | 配置格式 |
| `plugins/*/index.ts` | `skills/*.md` | 技能格式 |
| `channels/*/` | `channels/*/` | 通道兼容 |
| `agent/*/` | `agents/*/` | Agent 配置 |
### 8.3 技能迁移
```bash
# OpenClaw 插件格式 (TypeScript)
plugins/
└── my-plugin/
├── openclaw.plugin.json
└── index.ts
# OpenFang 技能格式 (Markdown)
skills/
└── my-skill.md
```
**迁移示例**:
```typescript
// OpenClaw 插件 (index.ts)
export default {
name: 'my-plugin',
triggers: ['触发词'],
async handler(ctx) {
return '结果';
}
}
```
```markdown
# OpenFang 技能 (my-skill.md)
## 触发词
- 触发词
## 实现
```skill
action: javascript
code: |
return '结果';
```
```
---
## 九、ZClaw 集成指南
### 9.1 GatewayClient 适配
```typescript
// desktop/src/lib/openfang-client.ts
export class OpenFangClient {
private ws: WebSocket | null = null;
private url = 'ws://127.0.0.1:4200/ws';
async connect(deviceId: string, signature: string): Promise<void> {
return new Promise((resolve, reject) => {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
// 认证
this.ws!.send(JSON.stringify({
type: 'auth',
device_id: deviceId,
signature
}));
resolve();
};
this.ws.onerror = reject;
});
}
async chat(sessionId: string, message: string): Promise<void> {
this.ws?.send(JSON.stringify({
type: 'chat',
session_id: sessionId,
message: { role: 'user', content: message }
}));
}
onStream(callback: (event: StreamEvent) => void): void {
this.ws?.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
if (data.type === 'stream') {
callback(data);
}
});
}
// Hand 触发
async triggerHand(handName: string, params: any): Promise<void> {
this.ws?.send(JSON.stringify({
type: 'hand_trigger',
hand_name: handName,
params
}));
}
// Workflow 执行
async executeWorkflow(workflowId: string, input: any): Promise<void> {
this.ws?.send(JSON.stringify({
type: 'workflow_execute',
workflow_id: workflowId,
input
}));
}
}
```
### 9.2 端口配置
```typescript
// OpenClaw
const OPENCLAW_PORT = 18789;
// OpenFang
const OPENFANG_PORT = 4200;
// 配置切换
const GATEWAY_PORT = process.env.USE_OPENFANG === 'true'
? OPENFANG_PORT
: OPENCLAW_PORT;
```
### 9.3 功能映射
| ZClaw 功能 | OpenClaw API | OpenFang API |
|-----------|-------------|--------------|
| 发送消息 | `chat` | `chat` |
| 获取会话 | `/api/sessions` | `/api/sessions` |
| 触发技能 | 插件系统 | `skill_trigger` |
| Hand 自动化 | ❌ 无 | `hand_trigger` |
| Workflow | ❌ 基础 | `workflow_execute` |
| 审计日志 | ❌ 无 | `/api/audit/logs` |
---
## 十、开发命令
### 10.1 基本命令
```bash
# 安装
cargo install openfang
# 启动服务
openfang start
# 停止服务
openfang stop
# 查看状态
openfang status
# 查看日志
openfang logs
# 配置向导
openfang wizard
# 迁移工具
openfang migrate --from openclaw
```
### 10.2 开发模式
```bash
# 克隆仓库
git clone https://github.com/RightNow-AI/openfang
cd openfang
# 构建
cargo build
# 运行测试
cargo test
# 开发模式运行
cargo run -- start --dev
# 构建 Release
cargo build --release
```
---
## 十一、参考资料
### 11.1 官方资源
- **GitHub**: https://github.com/RightNow-AI/openfang
- **文档**: https://docs.openfang.ai
- **Discord**: https://discord.gg/openfang
### 11.2 相关文档
- [Claw 生态系统深度报告](./claw-ecosystem-deep-dive-report.md)
- [OpenClaw 到 OpenFang 迁移分析](./openclaw-to-openfang-migration-brainstorm.md)
- [ZClaw 项目指南](../CLAUDE.md)
---
*文档版本: v1.0 | 更新日期: 2026-03-13*