跳转到正文
莫尔索随笔
返回

OpenClaw 完整配置指南:架构设计、多Agent管理与安全防护

预计 10 分钟

第一时间捕获有价值的信号

介绍OpenClaw架构设计、多Agent协作管理、安全防护三大核心内容,提供从个人使用到企业级部署的全场景完整配置指南与模板。

一、OpenClaw 概述与设计哲学

1.1 项目背景

在AI Agent爆发的2026年,OpenClaw(前身为ClawdBot/Moltbot)以175k+ GitHub星标成为开源个人AI助手领域的标杆项目。由PSPDFKit创始人Peter Steinberger打造,是一套完整的Agent架构范式,支持完全开源可定制。

OpenClaw的设计核心哲学:

  1. 声明式优于命令式:大量使用MD配置文件(AGENTS.md/SOUL.md等)而非硬编码控制行为,易读易维护
  2. 分层与模块化:从System Prompt到工具权限均采用分层设计,各层职责清晰
  3. 用户可控:默认配置合理,同时所有配置均可被用户覆盖定制
  4. 安全优先:多层防御机制,从Prompt护栏到沙箱隔离全方位保障安全
  5. 开放扩展:Skills技能系统与插件机制支持无限扩展能力

1.2 核心架构组件

OpenClaw采用”一个Gateway + 多个Channel + 可扩展Agent系统”架构:

  • Gateway(网关):控制平面,管理所有消息通道连接,提供WebSocket API
  • Agent(代理):独立AI实例,拥有独立上下文、工具集和记忆空间
  • Channel(通道):外部交互接口,支持WhatsApp/Telegram/Slack/Discord等
  • Skill(技能):可扩展功能模块,通过SKILL.md定义能力边界
  • Memory(记忆):持久化存储,支持向量检索和日志记录

1.3 配置文件体系总览

配置文件采用多层级设计:

层级位置说明
项目级配置仓库根目录.eslintrc/.prettierrc/tsconfig.json等构建规则
Gateway核心配置~/.openclaw/openclaw.json运行时核心配置,包含模型、工具、Agent等所有参数
工作空间配置~/.openclaw/workspace/Agent运行时文件系统,包含注入式配置文件
环境配置~/.openclaw/.env存储敏感信息(API Key/Token等),不进入版本控制
注入式配置AGENTS.md/SOUL.md/IDENTITY.md/USER.md直接注入System Prompt,控制Agent行为

二、核心配置模块详解

2.1 身份配置文件

AGENTS.md - 代理行为规范

定义Agent的行为准则、工作流程和编码规范,启动时自动注入System Prompt:

  • 身份定义:明确Agent角色定位
  • 行为准则:交互与任务处理规则
  • 编码规范:技术细节要求
  • 安全边界:禁止行为清单

SOUL.md - 价值观与个性

定义Agent的人格特质,可选配置:

  • 核心价值观:如诚实、专业、友善
  • 沟通风格:正式/随意、简洁/详细
  • 决策原则:模糊需求处理策略
  • 边界意识:人格化的行为边界

IDENTITY.md - 身份档案

存储Agent身份信息:

  • 基本信息:名称、版本、创建时间
  • 形象描述:多模态交互的视觉描述
  • 声音特征:语音交互参数
  • 签名语:标志性问候语

USER.md - 用户画像

存储用户偏好,实现个性化服务:

  • 基本信息:名称、联系方式、时区
  • 技术背景:编程语言偏好、技术栈熟悉度
  • 交互偏好:沟通方式、回复详细程度
  • 隐私设置:数据存储与敏感信息处理规则

2.2 System Prompt 构建机制

采用模块化设计,核心模块包括:

  • Tooling:可用工具列表
  • Safety:安全护栏提示
  • Skills:可用技能列表
  • OpenClaw Self-Update:自更新操作说明
  • Workspace:工作目录路径
  • Documentation:本地文档路径
  • Sandbox:沙箱运行时信息
  • Current Date & Time:时区信息
  • Runtime:主机/OS/模型等运行时信息
  • Reasoning:推理可见性配置

支持三种Prompt模式:

  • full模式:默认,包含所有模块,适用于主Agent
  • minimal模式:子Agent使用,省略非核心模块,节省token
  • none模式:仅返回基础身份行,用于特殊测试场景

2.3 工具系统配置

工具系统是Agent能力的核心载体,通过openclaw.json的tools字段配置:

{
  "tools": {
    "allow": ["*"],
    "deny": ["browser"],
    "profile": "coding",
    "byProvider": {
      "google-antigravity": {
        "profile": "minimal"
      }
    }
  }
}

内置工具Profile:

  • minimal:仅允许session_status,最严格限制
  • coding:允许文件系统、运行时、会话、内存和图像工具
  • messaging:允许消息相关工具和基本会话管理
  • full:无限制

工具组简化配置:

  • group:fs:文件系统工具(read/write/apply_patch等)
  • group:runtime:运行时工具(exec/process等)
  • group:sessions:会话管理工具
  • group:memory:记忆系统工具
  • group:messaging:消息相关工具

2.4 技能(Skills)系统配置

Skills是OpenClaw的扩展机制,每个Skill是独立目录,包含SKILL.md定义文件和可选代码:

skills/my-skill/
  ├── SKILL.md          # 技能定义(必需)
  ├── index.js          # 技能入口(可选)
  └── utils/            # 辅助文件(可选)

SKILL.md规范包含:技能名称、功能描述、使用场景、调用方式、参数说明、示例。

ClawHub技能注册中心:

{
  "clawhub": {
    "enabled": true,
    "registry": "https://clawhub.openclaw.ai"
  }
}

2.5 记忆系统配置

采用分层记忆设计:

  • 短期记忆:会话上下文
  • 长期记忆:持久化存储,包括每日日志(memory/YYYY-MM-DD.md)和精选记忆(MEMORY.md)

向量搜索配置:

{
  "memory": {
    "backend": "memory-core",
    "embedding": {
      "provider": "local",
      "model": "all-MiniLM-L6-v2"
    }
  }
}

2.6 Gateway 配置

Gateway是系统核心枢纽,配置如下:

{
  "gateway": {
    "host": "127.0.0.1",
    "port": 18789,
    "canvasHost": {
      "enabled": true,
      "port": 18793
    },
    "reload": {
      "mode": "hybrid"
    }
  }
}

热重载模式:

  • hybrid(默认):热应用安全变更,关键变更时重启
  • off:禁用热重载
  • restart:任何变更都触发重启

三、多Agent 架构与管理

3.1 多Agent设计思想

单Agent模式存在上下文污染、人格冲突、安全隔离不足、无法按需路由等问题,多Agent架构通过”扁平路由模型”解决这些问题,没有管理者Agent,Gateway直接根据消息来源路由到对应Agent。

每个Agent完全独立:

资源是否共享说明
工作空间独立工作目录
记忆文件独立MEMORY.md和日志
会话历史完全隔离的对话记录
认证凭证独立auth-profiles.json
技能配置可选可配置Agent级技能白名单
AI模型可选可指定不同模型

3.2 Agent配置与角色定义

创建Agent:

openclaw agents add coding
openclaw agents add social
openclaw agents add work

Agent核心配置示例:

{
  "agents": {
    "defaults": {
      "model": "anthropic:claude-opus-4-6",
      "maxTokens": 8192,
      "temperature": 0.7
    },
    "list": [
      {
        "agentId": "main",
        "workspace": "~/.openclaw/workspace",
        "model": "anthropic:claude-opus-4-6"
      },
      {
        "agentId": "coding",
        "workspace": "~/.openclaw/workspace-coding",
        "temperature": 0.3,
        "skills": {
          "enabled": ["coding-agent", "github", "gh-issues", "tmux"]
        },
        "bindings": [
          {
            "channel": "discord",
            "guildId": "123456789",
            "channelId": "987654321"
          }
        ]
      },
      {
        "agentId": "social",
        "workspace": "~/.openclaw/workspace-social",
        "model": "openai:gpt-5.2-mini",
        "temperature": 0.9,
        "skills": {
          "enabled": ["summarize", "weather", "goplaces"]
        },
        "bindings": [
          {
            "channel": "telegram",
            "chatId": "-100123456789"
          }
        ]
      }
    ]
  }
}

每个Agent的工作空间下都有独立的SOUL.md定义其人格、工作规则和沟通风格。

3.3 消息路由与绑定

Gateway路由规则:

  1. 检查bindings配置,匹配到则路由到对应Agent
  2. 未匹配且是私聊,路由到main Agent
  3. 其他情况回退到main Agent

支持的绑定类型:

  • Discord:指定服务器/频道
  • Telegram:指定群组/私聊
  • Slack:指定团队/频道
  • WhatsApp:指定群组

查看路由状态:

openclaw agents list

3.4 Agent间通信机制

直接通信(Sessions工具)

  • sessions_list:发现活跃会话
  • sessions_history:获取会话日志
  • sessions_send:向另一个会话发消息(支持reply-back ping-pong和announce step模式)
  • sessions_spawn:生成新会话

间接通信方式

  • 共享文件:公共目录读写
  • 用户中转:手动传递结果
  • 定时任务串联:Cron按顺序执行
  • Webhook触发:任务完成后调用下一个Agent的Webhook

3.5 任务协作策略

  1. 按职能分工:每个Agent负责一个领域(编程/办公/社交/研究)
  2. 按平台分工:每个Agent负责一个消息平台
  3. 按安全等级分工:按操作风险分配不同权限的Agent
  4. 流水线协作:多Agent按顺序处理任务的不同阶段

3.6 实战案例

客服+技术支持双Agent

  • Community Agent处理#general频道闲聊,用GPT-5.2-mini降低成本
  • Tech Support Agent处理#support频道技术问题,用Claude Sonnet保证专业度
  • 私聊消息由main Agent处理

内容创作流水线

  • Translator Agent翻译中文内容
  • Writer Agent润色英文表达
  • Reviewer Agent审核内容质量
  • 通过定时任务或共享文件串联流程

四、安全配置与防护

4.1 安全架构概述

采用纵深防御五层安全模型:

  1. 网络边界安全:TLS 1.3/防火墙/IP白名单
  2. 认证与授权:Gateway Token/配对系统/用户权限
  3. 输入验证与过滤:提示词护栏/消息过滤/长度限制
  4. 执行隔离:Docker沙箱/文件系统隔离/资源限制
  5. 审计与监控:操作日志/异常检测/告警通知

遵循零信任原则:不信任任何输入、任何网络、任何执行,最小权限,持续验证。

4.2 API Key 安全管理

基本原则:永远不要硬编码,使用环境变量存储:

# 方式一:系统环境变量(服务器推荐)
echo 'export OPENAI_API_KEY="sk-proj-xxxxx"' >> ~/.bashrc
source ~/.bashrc

# 方式二:.env文件(开发推荐)
cat > ~/.openclaw/.env << 'EOF'
OPENAI_API_KEY=sk-proj-xxxxx
ANTHROPIC_API_KEY=sk-ant-xxxxx
EOF
chmod 600 ~/.openclaw/.env

密钥轮换策略:每90天轮换一次,泄露时立即撤销并更换。

4.3 沙箱系统配置

沙箱确保Agent执行的命令被隔离在受控环境中:

{
  "agents": {
    "defaults": {
      "sandbox": {
        "mode": "non-main", // non-main/always/never
        "toolAllowlist": [
          "bash", "process", "read", "write", "edit",
          "sessions_list", "sessions_history",
          "sessions_send", "sessions_spawn"
        ],
        "toolDenylist": [
          "browser", "canvas", "nodes",
          "cron", "discord", "gateway"
        ],
        "securityOpt": ["no-new-privileges:true"],
        "capDrop": ["ALL"],
        "readOnlyRootfs": true,
        "tmpfsSize": "64m",
        "noSetuid": true
      }
    }
  }
}

沙箱模式说明:

  • non-main:非主会话在Docker沙箱中运行(推荐默认值)
  • always:所有会话都在沙箱中运行(高安全要求场景)
  • never:禁用沙箱(仅限开发调试)

4.4 权限控制

Gateway认证(必须设置)

# 生成强随机Token
openssl rand -hex 32
export OPENCLAW_GATEWAY_TOKEN="随机Token"

DM Pairing配对系统(默认启用)

控制谁可以给Agent发私信,默认策略pairing需要手动批准未知发送者:

{
  "channels": {
    "dmPolicy": "pairing" // pairing/open
  }
}

配对操作:

openclaw pairing approve <channel> <code>  # 批准配对
openclaw pairing list                      # 查看待配对请求
openclaw pairing revoke <contact>          # 撤销配对

用户权限分级

{
  "permissions": {
    "roles": {
      "admin": {
        "tools": ["*"],
        "agents": ["*"],
        "maxTokensPerDay": -1,
        "canModifyConfig": true
      },
      "user": {
        "tools": ["search", "calendar", "reminder", "weather"],
        "agents": ["assistant", "researcher"],
        "maxTokensPerDay": 100000,
        "canModifyConfig": false
      },
      "guest": {
        "tools": ["search", "weather"],
        "agents": ["assistant"],
        "maxTokensPerDay": 10000,
        "canModifyConfig": false
      }
    },
    "userRoles": {
      "my-telegram-id": "admin",
      "friend-telegram-id": "user",
      "default": "guest"
    }
  }
}

文件访问权限

{
  "filesystem": {
    "defaultPolicy": "deny",
    "rules": [
      {
        "path": "~/.openclaw/workspace",
        "permissions": ["read", "write", "create", "delete"]
      },
      {
        "path": "~/Documents",
        "permissions": ["read"]
      },
      {
        "path": "~/.openclaw/openclaw.json",
        "permissions": []
      },
      {
        "path": "~/.ssh",
        "permissions": []
      }
    ]
  }
}

4.5 网络安全

TLS 1.3强制启用

{
  "gateway": {
    "tls": {
      "enabled": true,
      "minVersion": "1.3",
      "certFile": "/path/to/cert.pem",
      "keyFile": "/path/to/key.pem"
    }
  }
}

远程访问推荐方案

不要直接暴露Gateway端口,使用:

  • SSH隧道:ssh -L 18789:127.0.0.1:18789 user@your-server
  • Tailscale Serve/Funnel:零配置安全隧道
  • WireGuard VPN

IP白名单与速率限制

{
  "gateway": {
    "security": {
      "ipWhitelist": {
        "enabled": true,
        "allowedIPs": ["127.0.0.1", "::1", "192.168.1.0/24"]
      },
      "rateLimiting": {
        "enabled": true,
        "maxRequestsPerMinute": 60,
        "maxRequestsPerHour": 1000,
        "burstSize": 10
      }
    }
  }
}

4.6 数据隐私保护

静态数据加密

{
  "storage": {
    "encryption": {
      "enabled": true,
      "algorithm": "aes-256-gcm",
      "keyDerivation": "argon2id"
    }
  }
}

本地模型隐私方案

如果不希望数据发送到第三方AI服务商,使用本地模型:

{
  "providers": {
    "ollama": {
      "type": "ollama",
      "baseUrl": "http://127.0.0.1:11434",
      "models": ["llama3.1", "qwen2.5"]
    }
  },
  "agents": {
    "defaults": {
      "provider": "ollama",
      "model": "llama3.1"
    }
  }
}

4.7 日志审计

{
  "logging": {
    "audit": {
      "enabled": true,
      "level": "info",
      "file": "~/.openclaw/logs/audit.log",
      "maxSize": "100m",
      "maxFiles": 30,
      "compress": true,
      "events": [
        "auth.success", "auth.failure", "pairing.request",
        "pairing.approve", "tool.execute", "tool.blocked",
        "config.change", "injection.detected"
      ]
    }
  }
}

4.8 安全最佳实践清单

必须做(CRITICAL)

  • Gateway认证已设置
  • API Key使用环境变量,不硬编码
  • DM配对系统已启用
  • Gateway绑定127.0.0.1
  • 配置文件权限设为600
  • TLS 1.3已启用
  • 沙箱已启用
  • 提示词护栏已启用
  • 运行openclaw doctor确认配置无误

强烈建议(HIGH)

  • 防火墙已配置,端口不对外暴露
  • 使用SSH隧道/VPN远程访问
  • 审计日志已启用
  • 速率限制已配置
  • 文件访问权限defaultPolicy为deny
  • 禁用不需要的工具
  • Webhook签名验证已启用

五、最终完整配置模板

// ~/.openclaw/openclaw.json 最终版完整配置
{
  // Gateway配置
  "gateway": {
    "host": "127.0.0.1",
    "port": 18789,
    "canvasHost": {
      "enabled": true,
      "port": 18793
    },
    "reload": {
      "mode": "hybrid"
    },
    "auth": {
      "mode": "token"
    },
    "tls": {
      "enabled": true,
      "minVersion": "1.3",
      "certFile": "/etc/letsencrypt/live/your-domain.com/fullchain.pem",
      "keyFile": "/etc/letsencrypt/live/your-domain.com/privkey.pem"
    },
    "security": {
      "ipWhitelist": {
        "enabled": true,
        "allowedIPs": ["127.0.0.1", "::1", "192.168.1.0/24"]
      },
      "rateLimiting": {
        "enabled": true,
        "maxRequestsPerMinute": 60,
        "maxRequestsPerHour": 1000,
        "burstSize": 10
      }
    }
  },

  // 模型与Provider配置
  "agents": {
    "defaults": {
      "model": "anthropic:claude-opus-4-6",
      "fallbackModels": ["openai/gpt-4.5", "google/gemini-pro"],
      "maxTokens": 8192,
      "temperature": 0.7,
      "sandbox": {
        "mode": "non-main",
        "toolAllowlist": [
          "bash", "process", "read", "write", "edit",
          "sessions_list", "sessions_history",
          "sessions_send", "sessions_spawn"
        ],
        "toolDenylist": [
          "browser", "canvas", "nodes", "cron", "discord", "gateway"
        ],
        "securityOpt": ["no-new-privileges:true"],
        "capDrop": ["ALL"],
        "readOnlyRootfs": true,
        "tmpfsSize": "64m",
        "noSetuid": true
      },
      "systemPrompt": {
        "guardrails": true,
        "maxLength": 10000,
        "injection": {
          "detection": true,
          "action": "block",
          "logAttempts": true
        }
      }
    },
    "list": [
      {
        "agentId": "main",
        "workspace": "~/.openclaw/workspace",
        "model": "anthropic:claude-opus-4-6"
      },
      {
        "agentId": "coding",
        "workspace": "~/.openclaw/workspace-coding",
        "temperature": 0.3,
        "skills": {
          "enabled": ["coding-agent", "github", "gh-issues", "tmux"]
        },
        "bindings": [
          {
            "channel": "discord",
            "guildId": "123456789",
            "channelId": "987654321"
          }
        ]
      },
      {
        "agentId": "social",
        "workspace": "~/.openclaw/workspace-social",
        "model": "openai:gpt-5.2-mini",
        "temperature": 0.9,
        "skills": {
          "enabled": ["summarize", "weather", "goplaces"]
        },
        "bindings": [
          {
            "channel": "telegram",
            "chatId": "-100123456789"
          }
        ]
      },
      {
        "agentId": "work",
        "workspace": "~/.openclaw/workspace-work",
        "model": "anthropic:claude-sonnet-4-6",
        "skills": {
          "enabled": ["gog", "slack", "notion", "trello", "summarize"]
        },
        "bindings": [
          {
            "channel": "slack",
            "teamId": "T01234567",
            "channelId": "C01234567"
          }
        ]
      }
    ]
  },

  // 工具配置
  "tools": {
    "profile": "coding",
    "deny": ["browser"],
    "byProvider": {
      "google-antigravity": {
        "profile": "minimal"
      }
    },
    "permissions": {
      "shell": {
        "enabled": false,
        "allowedUsers": ["admin"],
        "requireConfirmation": true,
        "blockedCommands": ["rm -rf", "dd if=", "mkfs", "shutdown", "reboot", "curl.*|.*sh", "wget.*|.*sh"]
      },
      "fileWrite": {
        "enabled": true,
        "allowedPaths": ["~/.openclaw/workspace/**"],
        "blockedPaths": ["~/.openclaw/openclaw.json", "~/.ssh/**", "~/.gnupg/**", "/etc/**", "/usr/**"],
        "maxFileSize": "10m"
      },
      "fileRead": {
        "enabled": true,
        "allowedPaths": ["~/.openclaw/workspace/**", "~/Documents/**"],
        "blockedPaths": ["~/.openclaw/.env", "~/.openclaw/credentials", "~/.ssh/**", "~/.gnupg/**", "/etc/shadow", "/etc/passwd"]
      },
      "httpRequest": {
        "enabled": true,
        "allowedDomains": ["api.openai.com", "api.anthropic.com"],
        "blockedDomains": ["*.onion", "localhost", "127.0.0.1"],
        "maxRequestsPerMinute": 30
      }
    }
  },

  // 技能注册中心
  "clawhub": {
    "enabled": true,
    "registry": "https://clawhub.openclaw.ai"
  },

  // 记忆系统
  "memory": {
    "backend": "memory-core",
    "embedding": {
      "provider": "local",
      "model": "all-MiniLM-L6-v2"
    }
  },

  // 通道配置
  "channels": {
    "dmPolicy": "pairing",
    "telegram": {
      "security": {
        "verifyWebhook": true,
        "secretToken": "your-webhook-secret",
        "allowedUpdates": ["message", "callback_query"]
      }
    },
    "discord": {
      "security": {
        "verifySignature": true,
        "publicKey": "your-discord-public-key"
      }
    }
  },

  // 文件系统权限
  "filesystem": {
    "defaultPolicy": "deny",
    "rules": [
      {
        "path": "~/.openclaw/workspace",
        "permissions": ["read", "write", "create", "delete"]
      },
      {
        "path": "~/Documents",
        "permissions": ["read"]
      },
      {
        "path": "~/Downloads",
        "permissions": ["read"]
      },
      {
        "path": "~/.openclaw/openclaw.json",
        "permissions": []
      },
      {
        "path": "~/.openclaw/credentials",
        "permissions": []
      },
      {
        "path": "~/.ssh",
        "permissions": []
      }
    ]
  },

  // 用户权限
  "permissions": {
    "roles": {
      "admin": {
        "tools": ["*"],
        "agents": ["*"],
        "maxTokensPerDay": -1,
        "canModifyConfig": true
      },
      "user": {
        "tools": ["search", "calendar", "reminder", "weather"],
        "agents": ["assistant", "researcher"],
        "maxTokensPerDay": 100000,
        "canModifyConfig": false
      },
      "guest": {
        "tools": ["search", "weather"],
        "agents": ["assistant"],
        "maxTokensPerDay": 10000,
        "canModifyConfig": false
      }
    },
    "userRoles": {
      "my-telegram-id": "admin",
      "friend-telegram-id": "user",
      "default": "guest"
    }
  },

  // 存储与加密
  "storage": {
    "encryption": {
      "enabled": true,
      "algorithm": "aes-256-gcm",
      "keyDerivation": "argon2id"
    },
    "retention": {
      "chatHistory": "90d",
      "auditLogs": "365d",
      "memories": "forever",
      "tempFiles": "7d"
    }
  },

  // 日志审计
  "logging": {
    "audit": {
      "enabled": true,
      "level": "info",
      "file": "~/.openclaw/logs/audit.log",
      "maxSize": "100m",
      "maxFiles": 30,
      "compress": true,
      "events": [
        "auth.success", "auth.failure", "pairing.request",
        "pairing.approve", "tool.execute", "tool.blocked",
        "config.change", "agent.create", "agent.delete",
        "injection.detected"
      ]
    }
  },

  // 定时任务
  "schedules": [
    {
      "name": "health-check",
      "cron": "*/30 * * * *",
      "agentId": "devops",
      "prompt": "执行服务器健康检查,如果发现异常,通过Slack通知#ops频道"
    },
    {
      "name": "daily-report",
      "cron": "0 18 * * *",
      "agentId": "devops",
      "prompt": "生成今日运维日报,发送到Slack #ops频道"
    }
  ]
}

六、总结

OpenClaw的配置体系从设计之初就兼顾了易用性、灵活性和安全性。通过本指南,你可以:

  1. 理解OpenClaw的核心设计思想和架构
  2. 配置多Agent协作系统,实现任务分流和专业分工
  3. 搭建完整的安全防护体系,防范各类安全威胁
  4. 使用最终配置模板快速部署适合自己场景的OpenClaw实例

建议根据实际使用场景裁剪配置,优先保障安全配置项,定期运行openclaw doctor检查配置健康状态。