OpenClaw 工程实战05:-OpenClaw 工程实战05 - variables"
│ │ Discord: MD → Discord Markdown (保持原生) │ │
│ │ WeChat: MD → 纯文本 + XML 卡片 │ │
│ │ 飞书: MD → 飞书富文本 Post JSON │ │
│ │ 钉钉: MD → 钉钉 Markdown 消息 / ActionCard │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
2.4 渠道插件注册机制
所有渠道适配器以 Channel Plugin 的形式存在,位于 extensions/ 目录下。每个渠道有独立的子目录,包含该渠道的全部实现代码。
extensions/
├── telegram/
│ ├── index.ts # 注册入口:defineBundledChannelEntry()
│ ├── monitor.ts # Monitor 模块
│ ├── bot-message-context.session.ts # Context Builder 模块
│ ├── outbound-adapter.ts # Outbound Adapter 模块
│ └── types.ts # 类型定义
├── discord/
│ ├── index.ts
│ ├── monitor.ts
│ ├── context-builder.ts
│ ├── outbound-adapter.ts
│ └── types.ts
├── slack/
│ ├── index.ts
│ ├── ...
├── wechat/
│ ├── index.ts
│ ├── ...
├── feishu/
│ ├── index.ts
│ ├── ...
├── dingtalk/
│ ├── index.ts
│ ├── ...
└── qq-bot/
├── index.ts
└── ...
注册入口示例(Telegram):
// extensions/telegram/index.ts
import { defineBundledChannelEntry } from '../../src/channels/registry';
import { TelegramMonitor } from './monitor';
import { TelegramContextBuilder } from './bot-message-context.session';
import { TelegramOutboundAdapter } from './outbound-adapter';
export default defineBundledChannelEntry({
channelId: 'telegram',
displayName: 'Telegram',
capabilities: {
messageTypes: {
text: true, image: true, audio: true, video: true,
file: true, card: false, richText: false,
markdown: true, embed: false, sticker: true, reaction: true
},
interactions: {
inlineButton: true, inlineKeyboard: true, menu: true,
quickReply: false, thread: true, editMessage: true,
deleteMessage: true, pinMessage: true, typing: true,
readReceipt: false
},
limits: {
maxTextLength: 4096,
maxImageSize: 10240,
maxFileSize: 51200,
maxButtonsPerMessage: 100,
rateLimit: {
requestsPerSecond: 30,
requestsPerMinute: 600,
requestsPerHour: 36000
}
},
connection: {
type: 'long_polling',
requiresPublicEndpoint: false,
supportsReconnect: true,
heartbeatInterval: 30000
}
},
factory: (config, gateway) => ({
monitor: new TelegramMonitor(config),
contextBuilder: new TelegramContextBuilder(config, gateway.sessionStore),
outboundAdapter: new TelegramOutboundAdapter(config)
})
});
3. 消息格式转换组织结构
3.1 消息类型统一抽象
OpenClaw 定义了一套完整的消息类型抽象体系,将各平台的异构消息统一映射为标准化的内部表示。这套抽象体系覆盖文本、图片、文件、卡片、富文本五大类消息。
┌─────────────────────────────────────────────────────────────────────────┐
│ 消息类型统一抽象体系 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ InternalMessage (根类型) │ │
│ │ id: string │ │
│ │ channel: string │ │
│ │ channelGroupId: string │ │
│ │ sender: { id, name, avatar } │ │
│ │ timestamp: Date │ │
│ │ metadata: { replyTo, platformSpecific, ... } │ │
│ └───────────────────────────┬─────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────┼────────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐ │
│ │ TextContent │ │ MediaContent │ │ InteractiveContent │ │
│ │ text: string│ │ type: image │ │ type: card/richText │ │
│ │ │ │ audio │ │ buttons: Button[] │ │
│ │ │ │ video │ │ sections: Section[] │ │
│ │ │ │ file │ │ template: string │ │
│ │ │ │ url: string │ │ │ │
│ │ │ │ data: Buffer│ │ │ │
│ └──────────────┘ └──────────────┘ └──────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
InternalMessage 的完整 TypeScript 定义:
/**
* InternalMessage - 统一内部消息格式
* 所有渠道的入站消息最终都转换为此格式
*/
interface InternalMessage {
/** 消息唯一ID */
id: string;
/** 来源渠道标识 */
channel: 'telegram' | 'discord' | 'slack' | 'wechat' | 'qq' | 'feishu'
| 'dingtalk' | 'whatsapp' | 'signal' | 'teams' | string;
/** 渠道内的群组/会话ID */
channelGroupId: string;
/** 发送者信息 */
sender: {
id: string; // 平台用户ID
name: string; // 显示名称
avatar?: string; // 头像URL
isBot?: boolean; // 是否为机器人
};
/** 消息内容 */
content: TextContent | MediaContent | InteractiveContent;
/** 消息时间戳 */
timestamp: Date;
/** 元数据 */
metadata: {
replyTo?: string; // 回复的目标消息ID
threadId?: string; // 话题/线程ID
isEdited?: boolean; // 是否为编辑消息
mentions?: string[]; // 提及的用户列表
platformSpecific?: Record; // 平台特有字段
};
}
/**
* 文本消息内容
*/
interface TextContent {
type: 'text';
text: string;
/** Markdown 格式标记 */
format?: 'plain' | 'markdown';
}
/**
* 媒体消息内容
*/
interface MediaContent {
type: 'image' | 'audio' | 'video' | 'file' | 'sticker';
/** 媒体文件URL(如果平台已托管) */
url?: string;
/** 媒体文件二进制数据(需要下载的场景) */
data?: Buffer;
/** 文件名 */
filename?: string;
/** MIME类型 */
mimeType?: string;
/** 文件大小(KB) */
size?: number;
/** 附带文本说明 */
caption?: string;
/** 缩略图URL */
thumbnailUrl?: string;
/** 音频时长(秒) */
duration?: number;
/** 图片宽高 */
dimensions?: { width: number; height: number };
}
/**
* 交互式消息内容
*/
interface InteractiveContent {
type: 'card' | 'richText' | 'embed' | 'template';
/** 标题 */
title?: string;
/** 副标题/描述 */
description?: string;
/** 按钮列表 */
buttons?: Button[];
/** 卡片分区 */
sections?: CardSection[];
/** 模板名称 */
template?: string;
/** 模板参数 */
templateData?: Record;
}
/**
* 按钮定义
*/
interface Button {
id: string;
label: string;
type: 'callback' | 'url' | 'share' | 'postback';
data?: string; // callback data / URL
style?: 'default' | 'primary' | 'danger';
}
/**
* 卡片分区
*/
interface CardSection {
title?: string;
fields?: { label: string; value: string }[];
image?: { url: string; alt?: string };
actions?: Button[];
}
3.2 各平台消息格式映射
以下是各主要平台消息格式到统一抽象的映射关系:
入站消息映射(平台 → InternalMessage):
┌─────────────────────────────────────────────────────────────────────────┐
│ 入站消息格式映射矩阵 │
├──────────┬──────────────────────────────────────────────────────────────┤
│ 平台 │ 原始格式 → 统一格式映射 │
├──────────┼──────────────────────────────────────────────────────────────┤
│ │ text 消息: │
│ Telegram │ message.text → TextContent{ type:"text", text:... } │
│ │ photo 消息: │
│ │ message.photo[].file_id → MediaContent{ type:"image" } │
│ │ sticker 消息: │
│ │ message.sticker.file_id → MediaContent{ type:"sticker" } │
│ │ voice 消息: │
│ │ message.voice.file_id → MediaContent{ type:"audio" } │
│ │ document 消息: │
│ │ message.document.file_id → MediaContent{ type:"file" } │
├──────────┼──────────────────────────────────────────────────────────────┤
│ │ text 消息: │
│ Discord │ message.content → TextContent{ type:"text" } │
│ │ embed 消息: │
│ │ message.embeds[] → InteractiveContent{ type:"embed" } │
│ │ 附件: │
│ │ message.attachments[] → MediaContent │
│ │ 反应: │
│ │ message.reactions[] → metadata.platformSpecific │
├──────────┼──────────────────────────────────────────────────────────────┤
│ │ text 消息: │
│ 微信 │ Content → TextContent{ type:"text" } │
│ │ image 消息: │
│ │ PicUrl → MediaContent{ type:"image", url:... } │
│ │ voice 消息: │
│ │ MediaId → MediaContent{ type:"audio" } │
│ │ 事件消息: │
│ │ Event → metadata.platformSpecific │
├──────────┼──────────────────────────────────────────────────────────────┤
│ │ text 消息: │
│ 飞书 │ event.message.content → TextContent │
│ │ image 消息: │
│ │ event.message.message_key → MediaContent │
│ │ post 消息(富文本): │
│ │ event.message.content → InteractiveContent │
│ │ interactive 消息: │
│ │ event.message.content → InteractiveContent{ type:"card" }│
├──────────┼──────────────────────────────────────────────────────────────┤
│ │ text 消息: │
│ 钉钉 │ text.content → TextContent │
│ │ picture 消息: │
│ │ picture.downloadCode → MediaContent │
│ │ richText 消息: │
│ │ richText → InteractiveContent │
│ │ actionCard 消息: │
│ │ actionCard → InteractiveContent{ type:"card" } │
├──────────┼──────────────────────────────────────────────────────────────┤
│ │ text 消息: │
│ Slack │ event.text → TextContent │
│ │ file 分享: │
│ │ event.files[] → MediaContent │
│ │ blocks 消息: │
│ │ event.blocks[] → InteractiveContent │
│ │ reactions: │
│ │ reaction_added → metadata.platformSpecific │
└──────────┴──────────────────────────────────────────────────────────────┘
出站消息映射(ReplyPayload → 平台原生格式):
{
"outboundMapping": {
"telegram": {
"text": "Markdown → Telegram HTML",
"rules": [
"**bold** → bold",
"*italic* → italic",
code
"```block```→
block
",
"[link](url) →link"
],
"image": "sendPhoto API",
"file": "sendDocument API",
"card": "不支持,降级为文本 + inline_keyboard",
"buttons": "inline_keyboard 数组"
},
"discord": {
"text": "保持 Markdown 原生格式",
"rules": ["Discord 原生支持 Markdown"],
"image": "attachment 或 embed.image",
"file": "attachment",
"card": "Embed 对象",
"buttons": "Button Components (v2)"
},
"wechat": {
"text": "Markdown → 纯文本",
"rules": [
"移除所有 Markdown 语法标记",
"保留纯文本内容"
],
"image": "上传素材 → 发送图片消息",
"file": "不支持(降级为文本链接)",
"card": "图文消息 XML",
"buttons": "不支持(降级为文本编号)"
},
"feishu": {
"text": "Markdown → 飞书富文本 Post",
"rules": [
"**bold** → post 中的 bold tag",
"链接 → post 中的 a tag"
],
"image": "上传图片 → image_key → 发送图片消息",
"file": "上传文件 → file_key → 发送文件消息",
"card": "Interactive Card JSON",
"buttons": "Card 中的 button 元素"
},
"dingtalk": {
"text": "Markdown 消息类型",
"rules": ["钉钉原生支持 Markdown"],
"image": "下载图片 → 发送图片消息",
"file": "不支持(降级为链接)",
"card": "ActionCard 消息类型",
"buttons": "ActionCard 中的 btns"
},
"slack": {
"text": "Markdown → Slack mrkdwn",
"rules": [
"**bold** → *bold*",
"*italic* → _italic_",
"`code` → `code`",
"```block```→ ```block```"
],
"image": "files.upload API",
"file": "files.upload API",
"card": "Blocks API",
"buttons": "Block Kit button element"
}
}
}
3.3 富文本降级策略
当目标平台不支持某些消息类型或格式时,适配层采用**优雅降级(Graceful Degradation)**策略,确保消息内容始终能传达给用户,即使格式有所损失。
┌─────────────────────────────────────────────────────────────────────────┐
│ 富文本降级策略决策树 │
│ │
│ ┌─────────────────┐ │
│ │ Agent 输出格式 │ │
│ │ Markdown + 媒体 │ │
│ └────────┬────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ 目标平台支持 MD? │ │
│ └────┬───────┬────┘ │
│ 是 │ │ 否 │
│ ┌────────┘ └────────┐ │
│ ▼ ▼ │
│ ┌────────────────┐ ┌──────────────────┐ │
│ │ 直接发送 MD │ │ 转换为纯文本 │ │
│ │ (Discord/钉钉) │ │ (微信/QQ) │ │
│ └────────────────┘ │ 移除格式标记 │ │
│ │ 保留语义结构 │ │
│ └──────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ 卡片消息降级链 │ │
│ │ Card → RichText → FormattedText → PlainText │ │
│ │ │ │
│ │ Card (飞书/钉钉/Slack/Discord) │ │
│ │ ↓ 不支持时 │ │
│ │ RichText (带格式的文本) │ │
│ │ ↓ 不支持时 │ │
│ │ FormattedText (纯文本 + 编号) │ │
│ │ ↓ 不支持时 │ │
│ │ PlainText (最基本纯文本) │ │
│ └──────────────────────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────┐ │
│ │ 按钮降级链 │ │
│ │ InlineButton → QuickReply → NumberedText │ │
│ │ │ │
│ │ InlineButton (Telegram/Discord/Slack) │ │
│ │ ↓ 不支持时 │ │
│ │ QuickReply (微信/QQ) │ │
│ │ ↓ 不支持时 │ │
│ │ NumberedText: │ │
│ │ "1. 选项A 2. 选项B 3. 选项C" │ │
│ │ 用户回复数字即可 │ │
│ └──────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
降级策略配置示例:
{
"formatDegradation": {
"telegram": {
"card": "degrade_to_inline_keyboard",
"richText": "convert_to_telegram_html",
"buttons": "inline_keyboard"
},
"wechat": {
"card": "degrade_to_text_with_xml",
"richText": "strip_to_plain_text",
"buttons": "degrade_to_numbered_text"
},
"discord": {
"card": "convert_to_embed",
"richText": "keep_markdown",
"buttons": "button_components"
},
"feishu": {
"card": "interactive_card_json",
"richText": "post_rich_text",
"buttons": "card_button_element"
},
"dingtalk": {
"card": "action_card",
"richText": "markdown_message",
"buttons": "action_card_btns"
},
"slack": {
"card": "block_kit",
"richText": "mrkdwn",
"buttons": "block_kit_button"
}
}
}
3.4 媒体文件处理流水线
媒体文件(图片、音频、视频、文件)在各平台间的传输是最复杂的适配场景之一。不同平台对媒体文件的格式、大小、传输方式有不同要求。
┌─────────────────────────────────────────────────────────────────────────┐
│ 媒体文件处理流水线 │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 入站接收 │───▶│ 格式检测 │───▶│ 临时存储 │───▶│ URL生成 │ │
│ │ 从平台下载│ │ MIME/尺寸 │ │ 本地缓存 │ │ 内部引用 │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ 出站发送 │◀───│ 格式转换 │◀───│ 大小检查 │◀───│ 平台上传 │ │
│ │ 调用API │ │ 平台要求 │ │ 限制校验 │ │ CDN/素材 │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
各平台媒体处理差异:
{
"mediaHandling": {
"telegram": {
"inbound": "getFile API + HTTP下载",
"outbound": "multipart/form-data 上传",
"limits": { "photo": "10MB", "other": "50MB" }
},
"discord": {
"inbound": "直接从 CDN URL 下载",
"outbound": "multipart/form-data 附件",
"limits": { "file": "25MB (普通) / 500MB (Boost L3)" }
},
"wechat": {
"inbound": "下载多媒体文件 API",
"outbound": "先上传临时素材获取 media_id 再发送",
"limits": { "image": "2MB", "voice": "2MB/60s", "video": "10MB" }
},
"feishu": {
"inbound": "下载消息资源 API",
"outbound": "上传素材获取 key 再发送",
"limits": { "image": "10MB", "file": "30MB" }
},
"dingtalk": {
"inbound": "下载机器人收到的媒体文件",
"outbound": "通过链接发送或 base64",
"limits": { "image": "1MB" }
},
"slack": {
"inbound": "files.info API + Bearer token",
"outbound": "files.upload API",
"limits": { "file": "1GB" }
}
}
}
3.5 消息分块策略
当 Agent 的回复内容超过目标平台单条消息长度限制时,适配层会自动执行消息分块。
┌─────────────────────────────────────────────────────────────────────────┐
│ 消息分块策略 │
│ │
│ Agent 回复 (可能很长) │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ ## 分析报告 (总计 8000 字符) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────┐ │
│ │ 检查目标平台长度限制 │ │
│ │ Telegram: 4096 字符 │ │
│ │ Discord: 2000 字符 │ │
│ │ WeChat: 2048 字符 │ │
│ │ 飞书: 30000 字符 │ │
│ │ 钉钉: 20000 字符 │ │
│ │ Slack: 40000 字符 │ │
│ └─────────────┬─────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────┐ │
│ │ 智能分块算法 │ │
│ │ 1. 优先在段落边界分块 │ │
│ │ 2. 其次在句子边界分块 │ │
│ │ 3. 最后在词边界分块 │ │
│ │ 4. 确保 Markdown 语法完整 │ │
│ │ 5. 代码块不被截断 │ │
│ └─────────────┬─────────────┘ │
│ │ │
│ ┌─────────────▼─────────────┐ │
│ │ 分块结果 (Telegram 为例) │ │
│ │ 消息1: [1/3] 3500 字符 │ │
│ │ 消息2: [2/3] 3200 字符 │ │
│ │ 消息3: [3/3] 1300 字符 │ │
│ └───────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
分块算法伪代码:
/**
* 智能消息分块算法
* @param text 待分块的文本
* @param maxLength 平台单条消息最大长度
* @returns 分块后的消息数组
*/
function chunkMessage(text: string, maxLength: number): string[] {
const chunks: string[] = [];
let remaining = text;
while (remaining.length > maxLength) {
let splitPoint = maxLength;
// 优先在段落边界分块
const paragraphBreak = remaining.lastIndexOf('\n\n', maxLength);
if (paragraphBreak > maxLength * 0.5) {
splitPoint = paragraphBreak + 2;
} else {
const lineBreak = remaining.lastIndexOf('\n', maxLength);
if (lineBreak > maxLength * 0.5) {
splitPoint = lineBreak + 1;
} else {
const space = remaining.lastIndexOf(' ', maxLength);
if (space > maxLength * 0.5) splitPoint = space + 1;
}
}
// 确保不截断代码块
const beforeChunk = remaining.substring(0, splitPoint);
const codeBlockCount = (beforeChunk.match(/```/g) || []).length;
if (codeBlockCount % 2 !== 0) {
const lastCodeBlockStart = beforeChunk.lastIndexOf('```');
splitPoint = lastCodeBlockStart;
}
chunks.push(remaining.substring(0, splitPoint));
remaining = remaining.substring(splitPoint);
}
if (remaining.length > 0) chunks.push(remaining);
// 添加分块序号
return chunks.map((chunk, index) => {
if (chunks.length > 1) return `[${index + 1}/${chunks.length}] ${chunk}`;
return chunk;
});
}
4. 会话同步组织结构
4.1 跨渠道会话映射
OpenClaw 的会话同步机制是其多渠道能力的核心。它允许用户在不同平台间无缝切换对话——在地铁上用 Telegram 发起的话题,到办公室用 Slack 可以继续讨论,AI 助手记得所有跨平台的历史对话。
会话标识体系:
┌─────────────────────────────────────────────────────────────────────────┐
│ 跨渠道会话标识体系 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 统一会话标识 (sessionKey) │ │
│ │ │ │
│ │ 格式: {渠道}:{平台会话ID}:{用户标识} │ │
│ │ │ │
│ │ 示例: │ │
│ │ telegram:123456789:user_abc → Telegram 私聊会话 │ │
│ │ telegram:-100123456:user_abc → Telegram 群组会话 │ │
│ │ discord:channel_789:user_abc → Discord 频道会话 │ │
│ │ slack:channel_C123:user_abc → Slack 频道会话 │ │
│ │ wechat:wx_id_xyz:user_abc → 微信会话 │ │
│ │ feishu:chat_id_abc:user_abc → 飞书会话 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 会话映射策略 │ │
│ │ │ │
│ │ 策略一:per-channel-peer(渠道+对端隔离) │ │
│ │ Telegram 私聊 → session A | Discord 频道 → session B │ │
│ │ 每个渠道+对端组合 = 独立会话 │ │
│ │ │ │
│ │ 策略二:per-account-channel-peer(账号+渠道+对端隔离) │ │
│ │ 账号1 + Telegram → A | 账号2 + Telegram → C │ │
│ │ 多账号场景下的完全隔离 │ │
│ │ │ │
│ │ 策略三:cross-channel-unified(跨渠道统一会话) │ │
│ │ 用户 Alice 在 Telegram / Discord / Slack → 同一 session X │ │
│ │ 通过统一身份映射实现跨渠道会话合并 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
会话策略配置示例:
{
"sessions": {
"strategy": "per-channel-peer",
"fallbackStrategy": "per-account-channel-peer",
"crossChannelSync": {
"enabled": true,
"identityLinking": {
"method": "pairing_code",
"codeLength": 6,
"expiry": 300
},
"syncInterval": 5000,
"conflictResolution": "last_write_wins"
},
"sessionKey": {
"format": "${channel}:${channelGroupId}:${senderId}",
"customMappings": [
{
"condition": { "channel": "telegram", "channelGroupId": "-100123456" },
"sessionKey": "project-alpha-group"
}
]
},
"persistence": {
"store": "sqlite",
"table": "sessions",
"cleanup": { "maxAge": "30d", "maxInactive": "7d" }
}
}
}
4.2 会话状态同步机制
跨渠道会话状态同步确保用户在任一平台上的对话进展能被其他平台感知。
┌─────────────────────────────────────────────────────────────────────────┐
│ 会话状态同步架构 │
│ │
│ ┌──────────────┐ │
│ │ Telegram │ 用户在 Telegram 发消息 │
│ └──────┬───────┘ │
│ ▼ │
│ ┌───────────────────────┐ ┌──────────────────────┐ │
│ │ Telegram Adapter │────────▶│ Session Store │ │
│ │ 生成 MsgContext │ │ (SQLite) │ │
│ └───────────┬───────────┘ │ - unified_user_id │ │
│ │ │ - channel_bindings │ │
│ ▼ │ - context_summary │ │
│ ┌───────────────────────┐ │ - last_active │ │
│ │ Agent 执行层 │ └──────────┬───────────┘ │
│ │ 处理消息 + 生成回复 │ │ │
│ └───────────┬───────────┘ │ │
│ ▼ │ │
│ ┌───────────────────────┐ │ │
│ │ 回复通过 Telegram │ │ │
│ │ 发送给用户 │ │ │
│ └───────────────────────┘ │ │
│ │ 状态同步 │
│ ┌───────────────────────┐ │ │
│ │ Slack Adapter │◀───────────────────┘ │
│ │ (同一用户在 Slack │ 读取历史上下文 │
│ │ 发消息时读取历史) │ │
│ └───────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
会话同步的 SQLite 数据模型:
-- 统一会话表
CREATE TABLE unified_sessions (
id TEXT PRIMARY KEY,
unified_user_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
last_active_at INTEGER NOT NULL,
context_summary TEXT,
message_count INTEGER DEFAULT 0,
status TEXT DEFAULT 'active',
FOREIGN KEY(unified_user_id) REFERENCES unified_users(id)
);
-- 渠道会话绑定表
CREATE TABLE channel_session_bindings (
id TEXT PRIMARY KEY,
unified_session_id TEXT NOT NULL,
channel TEXT NOT NULL,
channel_session_id TEXT NOT NULL,
channel_user_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
last_active_at INTEGER NOT NULL,
FOREIGN KEY(unified_session_id) REFERENCES unified_sessions(id),
UNIQUE(channel, channel_session_id, channel_user_id)
);
-- 消息记录表
CREATE TABLE messages (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
channel TEXT NOT NULL,
sender_id TEXT NOT NULL,
sender_name TEXT,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp INTEGER NOT NULL,
seq_num INTEGER NOT NULL,
FOREIGN KEY(session_id) REFERENCES unified_sessions(id)
);
4.3 消息顺序保证
在跨渠道、高并发的场景下,消息顺序的保证是一个复杂的工程问题。OpenClaw 采用 Lane/Queue 并发控制模型来解决这个问题。
┌─────────────────────────────────────────────────────────────────────────┐
│ 消息顺序保证机制 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ Lane/Queue 并发控制模型 │ │
│ │ │ │
│ │ 核心规则: │ │
│ │ - 同一 sessionKey 的消息串行处理(保证顺序) │ │
│ │ - 不同 sessionKey 的消息并行处理(提高吞吐) │ │
│ │ │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Lane 1 │ │ Lane 2 │ │ Lane 3 │ │ Lane 4 │ │ │
│ │ │ (串行) │ │ (串行) │ │ (串行) │ │ (串行) │ │ │
│ │ │ msg1 │ │ msgA │ │ msgX │ │ msgP │ │ │
│ │ │ msg2 │ │ msgB │ │ msgY │ │ msgQ │ │ │
│ │ │ msg3 │ │ msgC │ │ msgZ │ │ msgR │ │ │
│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │
│ │ │ │ │ │ │ │
│ │ └────────────┴────────────┴────────────┘ │ │
│ │ 并行执行 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 全局顺序号分配器 │ │
│ │ 每条消息入库时分配全局递增的 seq_num: │ │
│ │ msg1 (Telegram) → seq: 1001 │ │
│ │ msg2 (Slack) → seq: 1002 │ │
│ │ msg3 (Discord) → seq: 1003 │ │
│ │ 查询历史时按 seq_num 排序,保证跨渠道时间线一致 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 流式消息顺序控制 │ │
│ │ Agent 流式输出时: │ │
│ │ chunk_1 → 立即发送(草稿消息) │ │
│ │ chunk_2 → 编辑同一草稿消息(追加内容) │ │
│ │ chunk_3 → 编辑同一草稿消息 │ │
│ │ final → 替换草稿为最终完整消息 │ │
│ │ 支持编辑消息的平台: Telegram, Discord, Slack │ │
│ │ 不支持编辑的平台: 分块发送多条消息 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
4.4 会话隔离与多Agent路由
OpenClaw 支持在同一个 Gateway 实例中运行多个 Agent,每个 Agent 拥有独立的记忆、工具和文件系统。
{
"multiAgentRouting": {
"agents": {
"personal": {
"description": "个人助手 - 处理日常事务",
"channels": ["telegram", "wechat", "whatsapp"],
"bindings": [
{ "channel": "whatsapp", "account": "+1234567890", "agentId": "personal" },
{ "channel": "telegram", "condition": "dm_only", "agentId": "personal" }
]
},
"work": {
"description": "工作助手 - 处理工作相关任务",
"channels": ["slack", "feishu", "dingtalk"],
"bindings": [
{ "channel": "slack", "workspace": "T012345/B012345", "agentId": "work" },
{ "channel": "feishu", "condition": "group_message", "agentId": "work" }
]
},
"coding": {
"description": "编程助手 - 代码审查和技术讨论",
"channels": ["discord", "slack"],
"bindings": [
{ "channel": "discord", "serverId": "987654321", "agentId": "coding" }
]
}
},
"fallbackAgent": "personal",
"routingRules": [
{
"match": { "channel": "telegram", "keywords": ["代码", "bug", "review"] },
"routeTo": "coding"
},
{
"match": { "channel": "slack", "keywords": ["个人", "提醒", "日程"] },
"routeTo": "personal"
}
]
}
}
5. 用户身份映射组织结构
5.1 多平台用户ID关联
OpenClaw 需要将不同平台的用户ID关联为统一身份标识,才能实现跨渠道会话同步和个性化服务。
┌─────────────────────────────────────────────────────────────────────────┐
│ 多平台用户身份映射架构 │
│ │
│ ┌─────────────────┐ │
│ │ 统一用户身份 │ │
│ │ unified_user_id │ │
│ │ (OpenClaw内部) │ │
│ └────────┬────────┘ │
│ │ │
│ ┌──────────────────┼──────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │
│ │ Telegram 身份 │ │ Discord 身份 │ │ Slack 身份 │ │
│ │ tg_user_id │ │ discord_uid │ │ slack_uid │ │
│ │ tg_username │ │ discord_tag │ │ slack_team_id │ │
│ └────────────────┘ └────────────────┘ └────────────────┘ │
│ │
│ ┌──────────────────┼──────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ │
│ │ 微信身份 │ │ 飞书身份 │ │ 钉钉身份 │ │
│ │ wx_openid │ │ feishu_uid │ │ ding_userid │ │
│ │ wx_unionid │ │ feishu_open_id │ │ ding_unionid │ │
│ └────────────────┘ └────────────────┘ └────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
5.2 统一身份管理
统一身份管理的核心是建立一个"身份映射表",将各平台的用户标识关联到一个 OpenClaw 内部的统一用户ID。
-- 统一用户表
CREATE TABLE unified_users (
id TEXT PRIMARY KEY,
display_name TEXT,
avatar TEXT,
created_at INTEGER NOT NULL,
last_seen_at INTEGER NOT NULL,
status TEXT DEFAULT 'active',
metadata TEXT
);
-- 平台身份映射表
CREATE TABLE platform_identities (
id TEXT PRIMARY KEY,
unified_user_id TEXT NOT NULL,
platform TEXT NOT NULL,
platform_user_id TEXT NOT NULL,
platform_username TEXT,
platform_display_name TEXT,
platform_avatar TEXT,
verified BOOLEAN DEFAULT FALSE,
linked_at INTEGER NOT NULL,
last_used_at INTEGER NOT NULL,
FOREIGN KEY(unified_user_id) REFERENCES unified_users(id),
UNIQUE(platform, platform_user_id)
);
-- 身份配对记录表
CREATE TABLE identity_pairings (
id TEXT PRIMARY KEY,
unified_user_id TEXT NOT NULL,
platform TEXT NOT NULL,
platform_user_id TEXT NOT NULL,
pairing_code TEXT NOT NULL,
status TEXT DEFAULT 'pending',
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
completed_at INTEGER,
FOREIGN KEY(unified_user_id) REFERENCES unified_users(id)
);
5.3 跨平台身份配对流程
┌─────────────────────────────────────────────────────────────────────────┐
│ 跨平台身份配对流程 │
│ │
│ 步骤1: 用户在 Telegram 上与 Agent 对话 │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 用户: /link │ │
│ │ Agent: 您的配对码是: 839274 │ │
│ │ 请在目标平台上发送此配对码,有效期 5 分钟 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ 步骤2: 用户在 Slack 上与 Agent 对话 │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 用户: 839274 │ │
│ │ Agent: ✓ 配对成功!Telegram 和 Slack 账号已关联 │ │
│ │ 现在可以在两个平台间无缝切换对话 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ 步骤3: 系统后台处理 │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 1. 验证配对码有效性和未过期 │ │
│ │ 2. 创建 platform_identities 记录 │ │
│ │ 3. 合并两个平台的会话历史到统一会话 │ │
│ │ 4. 更新 unified_users.last_seen_at │ │
│ │ 5. 标记配对码为 completed │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
5.4 权限同步机制
{
"permissionSync": {
"strategy": "unified_role_based",
"roles": {
"owner": {
"description": "Gateway 所有者,拥有全部权限",
"permissions": ["*"]
},
"trusted": {
"description": "受信用户,可使用所有工具和技能",
"permissions": ["chat:*", "tools:read:*", "tools:write:*", "tools:exec:*", "skills:*"]
},
"guest": {
"description": "访客用户,仅可进行基础对话",
"permissions": ["chat:text_only", "tools:read:file", "skills:safe_list"]
}
},
"channelOverrides": {
"wechat": { "defaultRole": "guest", "requireApproval": true },
"telegram": { "defaultRole": "trusted", "allowFrom": ["123456789"] },
"slack": { "defaultRole": "trusted", "workspaceScope": "T012345" }
},
"dmPolicy": {
"default": "pairing",
"strategies": {
"pairing": "首次消息需输入配对码",
"allowlist": "仅允许 allowFrom 列表中的用户",
"open": "允许所有人(不推荐)",
"disabled": "禁止私聊"
}
}
}
}
5.5 用户画像聚合
当用户关联了多个平台身份后,OpenClaw 会从各平台收集用户信息,聚合形成统一的用户画像。
/**
* 用户画像聚合器
* 从多个平台收集用户信息,生成统一画像
*/
interface UserProfile {
unifiedUserId: string;
displayName: string;
avatars: PlatformAvatar[];
preferredLanguage: string;
timezone: string;
activeChannels: string[];
channelPreferences: {
channel: string;
messageCount: number;
lastActive: Date;
avgResponseTime: number;
}[];
derivedTraits: {
isDeveloper: boolean;
preferredFormat: 'markdown' | 'plaintext';
activityPattern: 'morning' | 'afternoon' | 'evening' | 'night';
};
}
6. 消息队列组织结构
6.1 四级队列架构
OpenClaw 的消息队列采用四级队列架构,分别处理消息生命周期的不同阶段。
┌─────────────────────────────────────────────────────────────────────────┐
│ 四级消息队列架构 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ ① 接收队列 (Inbound Queue) │ │
│ │ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │ │
│ │ │ msg │ │ msg │ │ msg │ │ msg │ │ msg │ ← 各渠道原始消息 │ │
│ │ │ 1 │ │ 2 │ │ 3 │ │ 4 │ │ 5 │ │ │
│ │ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ │ │
│ │ ▼ 去重 ▼ 去重 ▼ 去重 ▼ 去重 ▼ 去重 │ │
│ │ ▼ 安检 ▼ 安检 ▼ 安检 ▼ 安检 ▼ 安检 │ │
│ └─────┼───────┼───────┼───────┼───────┼──────────────────────────┘ │
│ ▼ ▼ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ ② 处理队列 (Processing Queue) - 按 sessionKey 分配 Lane │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Lane 1 │ │ Lane 2 │ │ Lane 3 │ │ Lane N │ │ │
│ │ │ session │ │ session │ │ session │ │ session │ │ │
│ │ │ A │ │ B │ │ C │ │ N │ │ │
│ │ │ (串行) │ │ (串行) │ │ (串行) │ │ (串行) │ │ │
│ │ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │ │
│ └───────┼────────────┼────────────┼────────────┼────────────────┘ │
│ ▼ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ ③ 发送队列 (Outbound Queue) - 按目标渠道分组,限流后发送 │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │Telegram │ │ Discord │ │ Slack │ │ WeChat │ │ │
│ │ │ replies │ │ replies │ │ replies │ │ replies │ │ │
│ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │
│ │ ▼ 限流 ▼ 限流 ▼ 限流 ▼ 限流 │ │
│ └───────┼────────────┼────────────┼────────────┼────────────────┘ │
│ ▼ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ ④ 重试队列 (Retry Queue) - 失败消息按退避策略重试 │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ retry 1 │ │ retry 2 │ │ retry 3 │ │ DLQ │ │ │
│ │ │ (1s后) │ │ (4s后) │ │ (16s后) │ │ (死信) │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
6.2 接收队列详解
{
"inboundQueue": {
"description": "接收各渠道的原始消息,执行去重和安全检查",
"implementation": "in-memory priority queue",
"capacity": 10000,
"overflowStrategy": "drop_oldest",
"pipeline": [
{
"stage": "deduplication",
"description": "基于消息ID去重,防止重连导致的重复处理",
"key": "${channel}:${messageId}",
"ttl": 300,
"storage": "lru_cache"
},
{
"stage": "security_filter",
"checks": [
"allowlist_verification",
"dm_policy_check",
"rate_limit_check",
"content_size_limit",
"malicious_content_scan"
]
},
{
"stage": "normalization",
"description": "转换为统一 InternalMessage 格式",
"processor": "ContextBuilder"
},
{
"stage": "routing",
"description": "确定 sessionKey 和目标 Agent",
"processor": "GatewayRouter"
}
],
"metrics": {
"queueDepth": "gauge",
"processingLatency": "histogram",
"dropCount": "counter",
"throughput": "meter"
}
}
}
6.3 处理队列详解
{
"processingQueue": {
"description": "按 sessionKey 分配到 Lane 进行串行处理",
"implementation": "lane-based concurrent queue",
"laneConfig": {
"maxLanes": 64,
"defaultLaneTimeout": 120000,
"laneAllocation": "hash(sessionKey) % maxLanes",
"perLaneBehavior": {
"ordering": "strict_fifo",
"concurrency": 1,
"backpressure": "block_new_messages_when_lane_full",
"maxQueuePerLane": 100
}
},
"sessionKeyStrategies": {
"per-channel-peer": "${channel}:${channelGroupId}:${senderId}",
"per-account-channel-peer": "${account}:${channel}:${channelGroupId}:${senderId}",
"cross-channel-unified": "unified:${unifiedUserId}"
}
}
}
6.4 发送队列与限流
{
"outboundQueue": {
"channelQueues": {
"telegram": {
"maxQueueSize": 500,
"rateLimiter": { "type": "token_bucket", "capacity": 30, "refillRate": 30, "refillInterval": 1000 }
},
"discord": {
"maxQueueSize": 500,
"rateLimiter": { "type": "token_bucket", "capacity": 5, "refillRate": 5, "refillInterval": 1000 },
"globalRateLimit": { "requestsPerSecond": 50, "bucketSize": 10000 }
},
"slack": {
"maxQueueSize": 300,
"rateLimiter": { "type": "token_bucket", "capacity": 1, "refillRate": 1, "refillInterval": 1000 },
"burstAllowance": 3
},
"wechat": {
"maxQueueSize": 200,
"rateLimiter": { "type": "token_bucket", "capacity": 10, "refillRate": 10, "refillInterval": 1000 }
},
"feishu": {
"maxQueueSize": 300,
"rateLimiter": { "type": "token_bucket", "capacity": 5, "refillRate": 5, "refillInterval": 1000 }
},
"dingtalk": {
"maxQueueSize": 300,
"rateLimiter": { "type": "token_bucket", "capacity": 20, "refillRate": 20, "refillInterval": 1000 }
}
}
}
}
6.5 重试队列与死信处理
{
"retryQueue": {
"retryPolicy": {
"maxRetries": 3,
"backoffStrategy": "exponential",
"baseDelay": 1000,
"maxDelay": 60000,
"multiplier": 2,
"jitter": true,
"jitterRange": 0.3
},
"retrySchedule": [
{ "attempt": 1, "delay": "1s ± 0.3s jitter" },
{ "attempt": 2, "delay": "4s ± 1.2s jitter" },
{ "attempt": 3, "delay": "16s ± 4.8s jitter" }
],
"deadLetterQueue": {
"enabled": true,
"maxSize": 1000,
"retention": "7d",
"alertThreshold": 10,
"actions": ["notify_admin", "log_full_payload", "fallback_to_alternate_channel"]
},
"circuitBreaker": {
"enabled": true,
"failureThreshold": 10,
"failureWindow": 60000,
"cooldownPeriod": 30000,
"halfOpenRequests": 3
}
}
}
6.6 队列监控指标
┌─────────────────────────────────────────────────────────────────────────┐
│ 消息队列监控仪表盘 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 接收队列 │ │
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
│ │ │ 队列深度 │ │ 吞吐量 │ │ 去重命中率 │ │ 安全拦截率 │ │ │
│ │ │ 42/10K │ │ 156 msg/s │ │ 3.2% │ │ 0.1% │ │ │
│ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 处理队列 │ │
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
│ │ │ 活跃 Lane │ │ 平均处理时 │ │ 超时数 │ │ 排队等待 │ │ │
│ │ │ 12/64 │ │ 2.3s │ │ 0 │ │ 1.2s │ │ │
│ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 发送队列 │ │
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
│ │ │ 发送成功率 │ │ 平均延迟 │ │ 限流触发 │ │ 重试中 │ │ │
│ │ │ 99.7% │ │ 340ms │ │ 3 │ │ 0 │ │ │
│ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 重试队列 │ │
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
│ │ │ 待重试 │ │ 重试成功率 │ │ 死信队列 │ │ 熔断状态 │ │ │
│ │ │ 2 │ │ 87.5% │ │ 0 │ │ 正常 │ │ │
│ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
7. 状态管理组织结构
7.1 状态管理总览
OpenClaw 的状态管理覆盖四个维度:在线状态、会话状态、消息状态和任务状态。所有状态数据统一存储在 SQLite 数据库中,采用本地优先(local-first)的设计哲学。
┌─────────────────────────────────────────────────────────────────────────┐
│ 状态管理四维架构 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 状态管理总控 (StateManager) │ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ 状态读取 │ │ 状态写入 │ │ │
│ │ │ (读优化) │ │ (写优化) │ │ │
│ │ └─────────────────┘ └─────────────────┘ │ │
│ │ ┌─────────────────┐ ┌─────────────────┐ │ │
│ │ │ 状态同步 │ │ 状态恢复 │ │ │
│ │ │ (跨渠道) │ │ (崩溃恢复) │ │ │
│ │ └─────────────────┘ └─────────────────┘ │ │
│ └───────────┬──────────────────┬──────────────────┬───────────────┘ │
│ │ │ │ │
│ ┌────────▼──────┐ ┌───────▼───────┐ ┌──────▼──────┐ │
│ │ 在线状态 │ │ 会话状态 │ │ 消息状态 │ │
│ │ (OnlineState) │ │ (SessionState)│ │(MsgState) │ │
│ └───────────────┘ └───────────────┘ └─────────────┘ │
│ │ │ │ │
│ │ ┌───────▼───────┐ │ │
│ │ │ 任务状态 │ │ │
│ │ │ (TaskState) │ │ │
│ │ └───────────────┘ │ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ SQLite 持久化层 │ │
│ │ channel_states | sessions | messages | tasks | scheduled_tasks│ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
7.2 在线状态管理
在线状态管理负责追踪各渠道的连接状态和用户的在线/离线状态。
┌─────────────────────────────────────────────────────────────────────────┐
│ 在线状态管理架构 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 渠道连接状态 (ChannelConnectionState) │ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Telegram │ │ Discord │ │ Slack │ │ WeChat │ │ │
│ │ │ ● 在线 │ │ ● 在线 │ │ ● 在线 │ │ ○ 离线 │ │ │
│ │ │ 延迟 45ms│ │ 延迟 80ms│ │ 延迟 120m│ │ 断线重连中│ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ │ │ │
│ │ 状态值: connected | disconnected | reconnecting | error │ │
│ │ 心跳间隔: 30s │ │
│ │ 超时阈值: 90s (3 次心跳未响应) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 用户在线状态 (UserPresenceState) │ │
│ │ │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ 拼多多帮助力入口
│ │ │ Alice │ │ Bob │ │ Charlie │ │ │
│ │ │ Tg: ● 在线 │ │ Tg: ○ 离线 │ │ Tg: ● 在线 │ │ │
│ │ │ Dc: ● 在线 │ │ Dc: ● 在线 │ │ Dc: ○ 离线 │ │ │
│ │ │ Sl: ● 在线 │ │ Sl: ○ 离线 │ │ Sl: ● 在线 │ │ │
│ │ │ 综合: 活跃 │ │ 综合: 仅Dc │ │ 综合: 活跃 │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ │ │ │
│ │ 综合状态: active (任一在线) | inactive (全部离线) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
渠道连接状态的数据模型:
{
"channelStates": {
"telegram": {
"status": "connected",
"connectedSince": "2026-07-06T08:00:00Z",
"lastHeartbeat": "2026-07-06T14:30:00Z",
"latency": 45,
"messagesReceived": 15234,
"messagesSent": 14890,
"errors": 3,
"lastError": "2026-07-06T12:15:00Z - rate_limit_exceeded"
},
"discord": {
"status": "connected",
"connectedSince": "2026-07-06T08:00:00Z",
"lastHeartbeat": "2026-07-06T14:30:00Z",
"latency": 80,
"messagesReceived": 8921,
"messagesSent": 8754,
"errors": 0
},
"wechat": {
"status": "reconnecting",
"connectedSince": null,
"lastHeartbeat": "2026-07-06T14:28:00Z",
"reconnectAttempt": 2,
"nextRetryIn": 4,
"errors": 12,
"lastError": "2026-07-06T14:29:00Z - connection_timeout"
}
}
}
7.3 会话状态管理
会话状态管理负责维护每个对话上下文的生命周期状态。
{
"sessionState": {
"states": {
"active": {
"description": "会话活跃,正在处理消息",
"color": "green",
"transitions": ["idle", "paused", "archived", "error"]
},
"idle": {
"description": "会话空闲,等待新消息",
"color": "blue",
"transitions": ["active", "paused", "archived"]
},
"paused": {
"description": "会话暂停,用户主动暂停",
"color": "yellow",
"transitions": ["active", "archived"]
},
"archived": {
"description": "会话归档,不再活跃",
"color": "gray",
"transitions": ["active"]
},
"error": {
"description": "会话异常,需要干预",
"color": "red",
"transitions": ["active", "archived"]
}
},
"contextManagement": {
"maxContextMessages": 50,
"compactionThreshold": 4000,
"compactionStrategy": "summarize_oldest",
"contextSummaryTTL": "7d",
"contextLayers": [
{
"layer": "system_prompt",
"source": "SOUL.md",
"priority": 1,
"alwaysLoaded": true
},
{
"layer": "task_list",
"source": "HEARTBEAT.md",
"priority": 2,
"alwaysLoaded": true
},
{
"layer": "recent_messages",
"source": "SQLite messages table",
"priority": 3,
"count": 10,
"fullDetail": true
},
{
"layer": "older_messages",
"source": "SQLite messages table",
"priority": 4,
"count": 20,
"fullDetail": false,
"format": "summarized"
},
{
"layer": "semantic_memory",
"source": "SQLite + sqlite-vec",
"priority": 5,
"retrieval": "similarity_search",
"maxResults": 5
}
]
}
}
}
7.4 消息状态管理
每条消息在系统中都有完整的状态追踪,从接收到最终送达的全生命周期。
┌─────────────────────────────────────────────────────────────────────────┐
│ 消息状态流转图 │
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ received │────▶│ queued │────▶│processing│────▶│ sent │ │
│ │ 已接收 │ │ 已入队 │ │ 处理中 │ │ 已发送 │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │ │ │ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ filtered │ │ error │ │delivered │ │
│ │ 已过滤 │ │ 错误 │ │ 已送达 │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ │
│ │ retrying │ │ read │ │
│ │ 重试中 │ │ 已读 │ │
│ └──────────┘ └──────────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ dlq │ │
│ │ 死信 │ │
│ └──────────┘ │
│ │
│ 状态值说明: │
│ received - 渠道适配器接收到原始消息 │
│ queued - 消息进入处理队列,等待 Lane 分配 │
│ filtered - 消息被安全过滤器拦截(allowlist/频率限制等) │
│ processing - Agent 正在处理消息 │
│ error - 处理过程中发生错误 │
│ retrying - 正在按指数退避策略重试 │
│ sent - 回复已通过渠道 API 发送 │
│ delivered - 平台确认消息已送达 │
│ read - 用户已读消息(如果平台支持已读回执) │
│ dlq - 超过最大重试次数,进入死信队列 │
└─────────────────────────────────────────────────────────────────────────┘
7.5 任务状态管理
OpenClaw 支持定时任务(Cron)和异步任务,这些任务同样需要状态管理。
-- 定时任务表
CREATE TABLE scheduled_tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL, -- 关联的会话
channel TEXT NOT NULL, -- 触发渠道
cron_expression TEXT NOT NULL, -- Cron 表达式 如 "0 9 * * 1-5"
task_prompt TEXT NOT NULL, -- 任务提示词
task_type TEXT DEFAULT 'reminder', -- reminder / report / workflow
enabled INTEGER DEFAULT 1, -- 是否启用
last_run INTEGER, -- 上次运行时间
next_run INTEGER, -- 下次运行时间
run_count INTEGER DEFAULT 0, -- 总运行次数
failure_count INTEGER DEFAULT 0, -- 失败次数
max_retries INTEGER DEFAULT 3, -- 最大重试次数
created_at INTEGER NOT NULL,
FOREIGN KEY(session_id) REFERENCES unified_sessions(id)
);
-- 异步任务表
CREATE TABLE async_tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
task_type TEXT NOT NULL, -- tool_call / file_process / api_call
status TEXT DEFAULT 'pending', -- pending / running / completed / failed
input TEXT, -- 输入参数 (JSON)
output TEXT, -- 输出结果 (JSON)
error TEXT, -- 错误信息
started_at INTEGER,
completed_at INTEGER,
timeout_ms INTEGER DEFAULT 30000, -- 超时时间
retry_count INTEGER DEFAULT 0,
FOREIGN KEY(session_id) REFERENCES unified_sessions(id)
);
任务状态配置示例:
{
"taskStateManagement": {
"scheduledTasks": {
"maxConcurrent": 10,
"defaultTimeout": 60000,
"retryPolicy": {
"maxRetries": 3,
"backoffStrategy": "exponential",
"baseDelay": 2000
},
"cleanupPolicy": {
"completedRetention": "24h",
"failedRetention": "7d"
}
},
"asyncTasks": {
"maxConcurrent": 50,
"defaultTimeout": 30000,
"priorityLevels": ["high", "normal", "low"],
"preemption": "high_can_preempt_normal"
}
}
}
8. 各渠道适配器对比
8.1 渠道能力对比矩阵
以下是 OpenClaw 支持的七个主要渠道的能力对比矩阵。矩阵覆盖消息类型、交互能力、限制约束和连接方式四个维度。
消息类型支持矩阵:
能力微信QQ钉钉飞书TelegramSlackDiscord纯文本✅✅✅✅✅✅✅Markdown❌❌✅✅✅✅✅富文本❌⚠️✅✅❌✅✅图片✅✅✅✅✅✅✅音频✅✅❌✅✅✅✅视频❌⚠️❌✅✅✅✅文件❌⚠️⚠️✅✅✅✅卡片消息⚠️❌✅✅❌✅✅表情/贴纸✅✅❌✅✅✅✅消息回应❌❌❌✅✅✅✅位置消息✅❌❌❌✅❌❌
交互能力支持矩阵:
交互能力微信QQ钉钉飞书TelegramSlackDiscord内联按钮❌⚠️✅✅✅✅✅菜单✅⚠️✅✅✅✅✅快速回复✅⚠️✅✅❌✅❌话题/线程❌❌❌✅✅✅✅编辑消息❌❌❌✅✅✅✅删除消息❌❌❌✅✅✅✅置顶消息❌❌✅✅✅✅✅输入状态❌❌❌❌✅✅✅已读回执❌❌❌✅❌✅❌流式编辑❌❌❌⚠️✅✅✅
限制约束对比:
限制项微信QQ钉钉飞书TelegramSlackDiscord单条文本2048字2000字20000字30000字4096字符40000字符2000字符图片大小2MB5MB1MB10MB10MB1GB25MB文件大小不支持10MB不支持30MB50MB1GB25MB频率限制严格中等中等中等宽松宽松中等每秒请求105205301+突发5+全局50按钮数量不支持35101002525
连接方式对比:
连接项微信QQ钉钉飞书TelegramSlackDiscord协议WebSocketWebSocketHTTP WebhookHTTP WebhookHTTP 轮询WebSocketWebSocket认证QR扫码TokenAppKey+SecretAppID+SecretBot TokenBot+App TokenBot Token公网端点否否是是否否否断线重连✅✅N/AN/A✅✅✅心跳间隔30s15sN/AN/A25s30s41s插件类型第三方捆绑插件捆绑插件捆绑插件内置内置内置生产推荐❌⚠️✅✅✅✅✅
8.2 渠道接入复杂度对比
┌─────────────────────────────────────────────────────────────────────────┐
│ 渠道接入复杂度雷达图 (文字版) │
│ │
│ 维度: 配置复杂度 / 认证难度 / 消息格式适配 / 媒体处理 / 群聊支持 │
│ 评分: 1(简单) ~ 5(复杂) │
│ │
│ Telegram: 配置(1) 认证(1) 格式(2) 媒体(2) 群聊(2) 总评: ★☆☆☆☆ │
│ Discord: 配置(2) 认证(2) 格式(1) 媒体(1) 群聊(3) 总评: ★★☆☆☆ │
│ Slack: 配置(3) 认证(3) 格式(3) 媒体(2) 群聊(3) 总评: ★★★☆☆ │
│ 飞书: 配置(3) 认证(3) 格式(4) 媒体(3) 群聊(4) 总评: ★★★☆☆ │
│ 钉钉: 配置(2) 认证(2) 格式(3) 媒体(2) 群聊(3) 总评: ★★☆☆☆ │
│ QQ Bot: 配置(3) 认证(3) 格式(2) 媒体(2) 群聊(2) 总评: ★★★☆☆ │
│ │
│ 结论: │
│ - 最易接入: Telegram (仅需 Bot Token,5分钟完成) │
│ - 最难接入: 微信 (QR扫码授权,非官方API,合规风险) │
│ - 企业首选: 飞书/钉钉 (功能丰富,API完善) │
│ - 开发者首选: Discord/Telegram (文档清晰,限制宽松) │
└─────────────────────────────────────────────────────────────────────────┘
8.3 渠道配置示例集
以下为各渠道的完整配置示例:
{
"channels": {
"telegram": {
"enabled": true,
"token": "1234567890:ABCdefGHIjklMNOpqrsTUVwxyz",
"allowedIds": [123456789, 987654321],
"requireMention": false,
"groups": {
"*": { "requireMention": true }
},
"webhookMode": false,
"pollingTimeout": 30
},
"discord": {
"enabled": true,
"token": "NDI...DSF.sdfl...",
"serverId": "987654321",
"userId": null,
"requireMention": true,
"intents": ["Guilds", "GuildMessages", "MessageContent"],
"forumThreadRouting": true
},
"slack": {
"enabled": true,
"botToken": "xoxb-...",
"appToken": "xapp-...",
"allowedUsers": ["U012345"],
"allowedChannels": ["C012345"],
"socketMode": true
},
"wechat": {
"enabled": true,
"type": "personal",
"autoLogin": true,
"allowedIds": ["wxid_abc123"],
"groups": {
"*": { "requireMention": true, "mentionPatterns": ["@助手"] }
},
"mediaCache": {
"enabled": true,
"maxSize": "500MB",
"ttl": "24h"
}
},
"feishu": {
"enabled": true,
"appId": "cli_abc123",
"appSecret": "secret_abc123",
"verificationToken": "token_abc",
"encryptKey": "key_abc",
"webhookPort": 3000,
"webhookPath": "/feishu/webhook",
"eventTypes": ["im.message.receive_v1"],
"cardSupport": true
},
"dingtalk": {
"enabled": true,
"appKey": "ding_abc123",
"appSecret": "secret_abc",
"robotCode": "robot_abc",
"webhookPort": 3001,
"webhookPath": "/dingtalk/webhook",
"callbackUrl": "https://your-domain/dingtalk/callback",
"actionCardSupport": true
},
"qq-bot": {
"enabled": true,
"connection": "ws://localhost:6700",
"accessToken": "abc123",
"selfId": 123456789,
"groups": {
"*": { "requireMention": true }
}
}
}
}
9. 渠道扩展机制
9.1 自定义渠道接入
OpenClaw 的渠道扩展机制允许开发者通过实现 ChannelPlugin 接口来接入自定义渠道。所有渠道均以插件形式存在,遵循统一的注册和生命周期管理流程。
┌─────────────────────────────────────────────────────────────────────────┐
│ 自定义渠道接入流程 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 步骤1: 创建渠道插件目录 │ │
│ │ extensions/my-channel/ │ │
│ │ ├── index.ts # 注册入口 │ │
│ │ ├── monitor.ts # Monitor 模块 │ │
│ │ ├── context-builder.ts # Context Builder 模块 │ │
│ │ ├── outbound-adapter.ts # Outbound Adapter 模块 │ │
│ │ ├── types.ts # 类型定义 │ │
│ │ └── config.ts # 配置模式定义 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 步骤2: 实现 ChannelPlugin 接口 │ │
│ │ - 定义 channelId 和 displayName │ │
│ │ - 声明 capabilities (消息类型/交互能力/限制约束) │ │
│ │ - 实现 start/stop/send/healthCheck 方法 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 步骤3: 实现三模块 │ │
│ │ Monitor: 建立连接 + 接收事件 + 安全过滤 │ │
│ │ ContextBuilder: 提取信息 + 生成 Envelope + 组装 MsgContext │ │
│ │ OutboundAdapter: 格式转换 + 媒体处理 + 消息分块 + API调用 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 步骤4: 注册插件 │ │
│ │ defineBundledChannelEntry({ │ │
│ │ channelId: 'my-channel', │ │
│ │ displayName: 'My Channel', │ │
│ │ capabilities: { ... }, │ │
│ │ factory: (config, gateway) => ({ ... }) │ │
│ │ }) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 步骤5: 配置和启用 │ │
│ │ 在 openclaw.json 中添加渠道配置 │ │
│ │ 运行 openclaw channels add my-channel ... │ │
│ │ 运行 openclaw channels status 验证连接 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
9.2 协议适配框架
OpenClaw 提供了三种协议适配器基类,开发者可根据目标平台的通信协议选择继承:
/**
* WebSocket 协议适配器基类
* 适用于: Discord, WhatsApp, QQ Bot 等使用 WebSocket 的平台
*/
abstract class WebSocketChannelAdapter extends ChannelPlugin {
protected ws: WebSocket | null = null;
protected reconnectAttempts = 0;
protected maxReconnectAttempts = 10;
async start(config: ChannelConfig): Promise{
this.ws = new WebSocket(config.url, config.options);
this.ws.on('open', this.onConnected.bind(this));
this.ws.on('message', this.onMessage.bind(this));
this.ws.on('close', this.onDisconnected.bind(this));
this.ws.on('error', this.onError.bind(this));
this.startHeartbeat();
}
protected abstract onMessage(data: unknown): void;
protected abstract onConnected(): void;
protected abstract onDisconnected(): void;
protected async reconnect(): Promise{
const delay = Math.min(
1000 * Math.pow(2, this.reconnectAttempts),
30000
);
await this.sleep(delay);
this.reconnectAttempts++;
await this.start(this.config);
}
}
/**
* Webhook 协议适配器基类
* 适用于: 飞书, 钉钉, Microsoft Teams 等使用 Webhook 的平台
*/
abstract class WebhookChannelAdapter extends ChannelPlugin {
protected server: http.Server | null = null;
async start(config: ChannelConfig): Promise{
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 安全验证中间件
app.use(this.verifyRequest.bind(this));
// 注册 Webhook 路由
app.post(config.webhookPath, this.handleWebhook.bind(this));
// 健康检查端点
app.get('/health', (req, res) => res.json({ status: 'ok' }));
this.server = app.listen(config.port, () => {
console.log(`Webhook listening on port ${config.port}`);
});
}
protected abstract verifyRequest(req: Request, res: Response, next: NextFunction): void;
protected abstract handleWebhook(req: Request, res: Response): void;
}
/**
* Long Polling 协议适配器基类
* 适用于: Telegram 等使用长轮询的平台
*/
abstract class LongPollingChannelAdapter extends ChannelPlugin {
protected polling = false;
protected lastUpdateId = 0;
async start(config: ChannelConfig): Promise{
this.polling = true;
while (this.polling) {
try {
const updates = await this.pollUpdates(config.timeout);
for (const update of updates) {
this.lastUpdateId = Math.max(this.lastUpdateId, update.id);
await this.handleUpdate(update);
}
} catch (error) {
console.error('Polling error:', error);
await this.sleep(1000);
}
}
}
protected abstract pollUpdates(timeout: number): Promise;
protected abstract handleUpdate(update: any): Promise;
}
9.3 消息模板机制
OpenClaw 支持消息模板机制,允许开发者预定义消息格式模板,在不同渠道间复用。
{
"messageTemplates": {
"report": {
"description": "分析报告模板",
"variables": ["title", "summary", "details", "conclusion"],
"templates": {
"telegram": {
"format": "html",
"template": "{title}\n\n{summary}\n\n详细分析:\n{details}\n\n结论:{conclusion}"
},
"discord": {
"format": "markdown",
"template": "## {title}\n\n{summary}\n\n### 详细分析\n{details}\n\n### 结论\n{conclusion}"
},
"wechat": {
"format": "plaintext",
"template": "【{title}】\n\n{summary}\n\n详细分析:\n{details}\n\n结论: {conclusion}"
},
"feishu": {
"format": "card",
"template": {
"card": {
"header": { "title": { "content": "{title}" } },
"elements": [
{ "tag": "div", "text": { "content": "{summary}" } },
{ "tag": "div", "text": { "content": "详细分析:\n{details}" } },
{ "tag": "div", "text": { "content": "结论: {conclusion}" } }
]
}
}
},
"dingtalk": {
"format": "actionCard",
"template": {
"actionCard": {
"title": "{title}",
"text": "### {title}\n\n{summary}\n\n#### 详细分析\n{details}\n\n#### 结论\n{conclusion}",
"btnOrientation": "0"
}
}
},
"slack": {
"format": "blocks",
"template": {
"blocks": [
{ "type": "header", "text": { "type": "plain_text", "text": "{title}" } },
{ "type": "section", "text": { "type": "mrkdwn", "text": "{summary}" } },
{ "type": "divider" },
{ "type": "section", "text": { "type": "mrkdwn", "text": "*详细分析*\n{details}" } },
{ "type": "section", "text": { "type": "mrkdwn", "text": "*结论:* {conclusion}" } }
]
}
}
}
},
"error_report": {
"description": "错误报告模板",
"variables": ["errorCode", "errorMessage", "suggestion"],
"templates": {
"default": {
"format": "markdown",
"template": "⚠️ **错误 {errorCode}**\n\n{errorMessage}\n\n **建议:** {suggestion}"
}
}
}
}
}
9.4 渠道插件生命周期
┌─────────────────────────────────────────────────────────────────────────┐
│ 渠道插件生命周期管理 │
│ │
│ ┌──────────┐ │
│ │ Registered│ Gateway 启动时扫描 extensions/ 目录 │
│ │ 已注册 │ 调用 defineBundledChannelEntry() 注册 │
│ └────┬─────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ Configured│ 从 openclaw.json 读取渠道配置 │
│ │ 已配置 │ 执行配置校验 (Zod schema validation) │
│ └────┬─────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ Validated│ 验证认证凭据有效性 │
│ │ 已验证 │ 检查网络连通性 │
│ └────┬─────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Connecting│────▶│ Connected│◀───▶│Reconnect │ │
│ │ 连接中 │ │ 已连接 │ │ 重连中 │ │
│ └──────────┘ └────┬─────┘ └──────────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ Active │ 正常处理消息 │
│ │ 活跃 │ 心跳正常 │
│ └────┬─────┘ │
│ │ │
│ ┌─────────┼─────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌────────┐ ┌────────┐ ┌────────┐ │
│ │ Degraded│ │ Paused │ │ Error │ │
│ │ 降级 │ │ 暂停 │ │ 错误 │ │
│ └────────┘ └────────┘ └────────┘ │
│ │ │ │ │
│ └─────────┼─────────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ Stopped │ Gateway 关闭或手动停止 │
│ │ 已停止 │ 清理资源,保存状态 │
│ └──────────┘ │
│ │
│ 生命周期事件: │
│ channel.registered - 插件注册完成 │
│ channel.configured - 配置加载完成 │
│ channel.connecting - 正在建立连接 │
│ channel.connected - 连接建立成功 │
│ channel.disconnected - 连接断开 │
│ channel.reconnecting - 正在重连 │
│ channel.error - 发生错误 │
│ channel.degraded - 进入降级模式 │
│ channel.stopped - 渠道已停止 │
└─────────────────────────────────────────────────────────────────────────┘
9.5 插件市场与分发
{
"pluginDistribution": {
"officialChannels": {
"description": "内置渠道,随核心包发布",
"channels": ["telegram", "discord", "slack", "whatsapp", "signal", "webchat"],
"location": "src/channels/"
},
"bundledPlugins": {
"description": "随发行版打包的插件,需手动启用",
"channels": ["matrix", "msteams", "qq-bot", "feishu", "dingtalk", "line", "zalo"],
"location": "extensions/",
"enable": "openclaw plugins install @openclaw/"
},
"communityPlugins": {
"description": "社区开发的第三方插件",
"registry": "https://clawhub.dev/plugins",
"install": "openclaw plugins install",
"verify": "openclaw plugins verify",
"securityAudit": "社区插件需通过安全审计"
},
"customPlugins": {
"description": "用户自行开发的插件",
"location": "~/.openclaw/plugins/",
"autoload": true,
"configSchema": "必须提供 Zod 配置模式"
}
}
}
10. 高可用组织结构
10.1 负载均衡架构
OpenClaw 的负载均衡主要体现在三个层面:渠道级负载均衡、会话级负载均衡和 Agent 级负载均衡。
┌─────────────────────────────────────────────────────────────────────────┐
│ 三层负载均衡架构 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 第一层: 渠道级负载均衡 │ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Telegram │ │ Discord │ │ Slack │ │ WeChat │ │ │
│ │ │ Adapter │ │ Adapter │ │ Adapter │ │ Adapter │ │ │
│ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │
│ │ │ │ │ │ │ │
│ │ └────────────┴────────────┴────────────┘ │ │
│ │ 并行处理 (各渠道独立) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 第二层: 会话级负载均衡 (Lane/Queue) │ │
│ │ │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Lane 1 │ │ Lane 2 │ │ Lane 3 │ │ Lane N │ │ │
│ │ │ (串行) │ │ (串行) │ │ (串行) │ │ (串行) │ │ │
│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │
│ │ └────────────┴────────────┴────────────┘ │ │
│ │ 并行处理 (不同会话并行) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 第三层: Agent 级负载均衡 │ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Agent A │ │ Agent B │ │ Agent C │ │ │
│ │ │ (personal)│ │ (work) │ │ (coding) │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
│ │ └────────────┴────────────┘ │ │
│ │ 并行处理 (不同 Agent 独立执行) │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
10.2 故障转移机制
┌─────────────────────────────────────────────────────────────────────────┐
│ 故障转移决策树 │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 检测到渠道故障 │ │
│ │ (心跳超时 / 连续错误 / API 返回 5xx) │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 故障分级 │ │
│ │ Level 1: 瞬时错误 (网络抖动 / 限流) │ │
│ │ Level 2: 持续错误 (认证失败 / API 变更) │ │
│ │ Level 3: 渠道不可用 (平台宕机 / 封禁) │ │
│ └──────────────────────┬──────────────────────────────┘ │
│ │ │
│ ┌─────────────┼─────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Level 1 │ │ Level 2 │ │ Level 3 │ │
│ │ 自动重试 │ │ 隔离+通知 │ │ 故障转移 │ │
│ │ 指数退避 │ │ 尝试修复 │ │ 切换渠道 │ │
│ └──────────┘ └──────────┘ └────┬─────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ 故障转移策略 │ │
│ │ │ │
│ │ 1. 通知用户当前渠道 │ │
│ │ 不可用 │ │
│ │ 2. 查找用户已关联 │ │
│ │ 的其他渠道 │ │
│ │ 3. 通过备用渠道 │ │
│ │ 投递消息 │ │
│ │ 4. 记录故障事件 │ │
│ │ 5. 持续尝试恢复 │ │
│ │ 主渠道 │ │
│ └─────────────────────┘ │
│ │
│ 故障转移配置: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ fallbackChain: │ │
│ │ primary: telegram │ │
│ │ secondary: discord │ │
│ │ tertiary: email │ │
│ │ │ │
│ │ 当 telegram 不可用时 → 尝试 discord │ │
│ │ 当 discord 也不可用时 → 发送邮件通知 │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
故障转移配置示例:
{
"failover": {
"enabled": true,
"strategies": {
"channelFailover": {
"description": "渠道级故障转移",
"fallbackChains": {
"alice": {
"primary": "telegram",
"secondary": "discord",
"tertiary": "slack"
},
"bob": {
"primary": "wechat",
"secondary": "feishu"
}
},
"triggerConditions": {
"consecutiveErrors": 5,
"heartbeatTimeout": 90000,
"apiErrorCodes": [429, 500, 502, 503, 504]
},
"recoveryCheck": {
"interval": 60000,
"method": "send_test_message"
}
},
"agentFailover": {
"description": "Agent 级故障转移",
"enabled": true,
"strategy": "fallback_agent",
"rules": [
{
"primaryAgent": "specialized",
"fallbackAgent": "general",
"trigger": "agent_timeout",
"timeoutThreshold": 120000
}
]
},
"modelFailover": {
"description": "模型级故障转移",
"enabled": true,
"providers": {
"primary": { "name": "claude", "model": "claude-sonnet-4" },
"secondary": { "name": "openai", "model": "gpt-4o" },
"tertiary": { "name": "deepseek", "model": "deepseek-v3" }
},
"triggerConditions": {
"apiTimeout": 30000,
"rateLimitHit": true,
"consecutiveErrors": 3
}
}
}
}
}
10.3 限流降级机制
{
"rateLimiting": {
"globalLimits": {
"totalMessagesPerMinute": 1000,
"totalMessagesPerHour": 30000,
"concurrentProcessing": 64
},
"perChannelLimits": {
"telegram": { "perSecond": 30, "perMinute": 600, "perHour": 36000 },
"discord": { "perSecond": 5, "perMinute": 150, "perHour": 9000 },
"slack": { "perSecond": 1, "perMinute": 60, "perHour": 3600, "burst": 3 },
"wechat": { "perSecond": 10, "perMinute": 200, "perHour": 6000 },
"feishu": { "perSecond": 5, "perMinute": 100, "perHour": 3000 },
"dingtalk": { "perSecond": 20, "perMinute": 400, "perHour": 12000 }
},
"perUserLimits": {
"owner": { "perMinute": 100, "perHour": 2000 },
"trusted": { "perMinute": 30, "perHour": 500 },
"guest": { "perMinute": 5, "perHour": 50 }
}
},
"degradation": {
"strategies": [
{
"trigger": "high_load",
"condition": { "queueDepth": ">500", "cpuUsage": ">80%" },
"actions": [
"reduce_streaming_frequency",
"batch_replies",
"skip_media_processing",
"increase_response_delay"
]
},
{
"trigger": "rate_limit_approaching",
"condition": { "usagePercentage": ">90%" },
"actions": [
"queue_non_urgent_messages",
"notify_user_rate_limit",
"reduce_message_frequency"
]
},
{
"trigger": "memory_pressure",
"condition": { "memoryUsage": ">85%" },
"actions": [
"compact_old_sessions",
"clear_media_cache",
"reduce_context_window"
]
},
{
"trigger": "circuit_breaker_open",
"condition": { "channelCircuitBreaker": "open" },
"actions": [
"route_to_fallback_channel",
"queue_messages_for_retry",
"notify_admin"
]
}
]
}
}
10.4 监控告警体系
┌─────────────────────────────────────────────────────────────────────────┐
│ 监控告警体系架构 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 指标采集层 (Metrics Collection) │ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ 渠道指标 │ │ 队列指标 │ │ 会话指标 │ │ 系统指标 │ │ │
│ │ │ 连接状态 │ │ 队列深度 │ │ 活跃会话 │ │ CPU/Mem │ │ │
│ │ │ 消息计数 │ │ 处理延迟 │ │ 消息数量 │ │ 磁盘IO │ │ │
│ │ │ 错误率 │ │ 重试次数 │ │ 会话时长 │ │ 网络延迟 │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ └───────────────────────────┬─────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 告警规则层 (Alert Rules) │ │
│ │ │ │
│ │ ┌───────────────────────────────────────────────────────┐ │ │
│ │ │ P0 - 紧急 (立即通知) │ │ │
│ │ │ - Gateway 进程崩溃 │ │ │
│ │ │ - 所有渠道断连 │ │ │
│ │ │ - SQLite 数据库损坏 │ │ │
│ │ │ - 死信队列超过阈值 │ │ │
│ │ └───────────────────────────────────────────────────────┘ │ │
│ │ ┌───────────────────────────────────────────────────────┐ │ │
│ │ │ P1 - 重要 (5分钟内通知) │ │ │
│ │ │ - 单个渠道断连超过 3 分钟 │ │ │
│ │ │ - 消息处理延迟超过 30 秒 │ │ │
│ │ │ - 发送队列积压超过 100 条 │ │ │
│ │ │ - 错误率超过 5% │ │ │
│ │ └───────────────────────────────────────────────────────┘ │ │
│ │ ┌───────────────────────────────────────────────────────┐ │ │
│ │ │ P2 - 警告 (1小时内通知) │ │ │
│ │ │ - 某渠道错误率超过 1% │ │ │
│ │ │ - 磁盘使用超过 80% │ │ │
│ │ │ - 内存使用超过 85% │ │ │
│ │ │ - 重试队列积压超过 10 条 │ │ │
│ │ └───────────────────────────────────────────────────────┘ │ │
│ └───────────────────────────┬─────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 通知渠道层 (Notification Channels) │ │
│ │ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Telegram │ │ Email │ │ Webhook │ │ Slack │ │ │
│ │ │ (管理员) │ │ (管理员) │ │ (自定义) │ │ (运维群) │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
监控告警配置示例:
{
"monitoring": {
"metrics": {
"enabled": true,
"interval": 10000,
"retention": "30d",
"export": {
"prometheus": { "enabled": true, "port": 9090, "path": "/metrics" },
"json_logs": { "enabled": true, "path": "~/.openclaw/logs/metrics.jsonl" }
}
},
"alerts": {
"P0": {
"conditions": [
{ "metric": "gateway.status", "operator": "==", "value": "down" },
{ "metric": "channels.all_down", "operator": "==", "value": true },
{ "metric": "dlq.size", "operator": ">", "value": 50 }
],
"actions": ["telegram_notify", "email_notify", "webhook_call"],
"cooldown": 60
},
"P1": {
"conditions": [
{ "metric": "channel.{name}.downtime", "operator": ">", "value": 180000 },
{ "metric": "processing.avg_latency", "operator": ">", "value": 30000 },
{ "metric": "outbound_queue.depth", "operator": ">", "value": 100 },
{ "metric": "error_rate", "operator": ">", "value": 0.05 }
],
"actions": ["telegram_notify", "email_notify"],
"cooldown": 300
},
"P2": {
"conditions": [
{ "metric": "channel.{name}.error_rate", "operator": ">", "value": 0.01 },
{ "metric": "disk.usage", "operator": ">", "value": 0.8 },
{ "metric": "memory.usage", "operator": ">", "value": 0.85 },
{ "metric": "retry_queue.depth", "operator": ">", "value": 10 }
],
"actions": ["telegram_notify"],
"cooldown": 3600
}
},
"healthCheck": {
"enabled": true,
"endpoint": "/health",
"checks": [
"gateway_running",
"sqlite_accessible",
"channels_connected",
"queue_not_overflowed",
"memory_under_limit"
]
}
}
}
10.5 高可用最佳实践
┌─────────────────────────────────────────────────────────────────────────┐
│ 高可用部署最佳实践 │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 部署架构推荐 │ │
│ │ │ │
│ │ 方案一: 单机部署 (个人/小团队) │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ VPS (2C4G+) │ │ │
│ │ │ ├── OpenClaw Gateway (单进程) │ │ │
│ │ │ ├── SQLite (本地文件) │ │ │
│ │ │ ├── LLM Proxy (127.0.0.1:19000) │ │ │
│ │ │ └── Tailscale (远程访问) │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ 适用:<100 用户,<10 渠道, 日均<10000 消息 │ │
│ │ │ │
│ │ 方案二: 容器化部署 (中型团队) │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ Docker Host (4C8G+) │ │ │
│ │ │ ├── OpenClaw Gateway (Docker) │ │ │
│ │ │ ├── Nginx (反向代理 + SSL) │ │ │
│ │ │ ├── Watchtower (自动更新) │ │ │
│ │ │ └── Volume: ~/.openclaw/ (持久化) │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ 适用:<500 用户, 全渠道, 日均<50000 消息 │ │
│ │ │ │
│ │ 方案三: 集群部署 (大型组织) │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ Kubernetes Cluster │ │ │
│ │ │ ├── Gateway Pod (HPA: 2-5 replicas) │ │ │
│ │ │ ├── Redis (共享会话状态) │ │ │
│ │ │ ├── PostgreSQL (替代 SQLite) │ │ │
│ │ │ ├── Ingress Controller (TLS + 路由) │ │ │
│ │ │ └── Prometheus + Grafana (监控) │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ 适用: 500+ 用户, 全渠道, 日均 50000+ 消息 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────┐ │
│ │ 运维检查清单 │ │
│ │ │ │
│ │ □ 配置备份: 定期备份 ~/.openclaw/openclaw.json │ │
│ │ □ 数据备份: 定期备份 SQLite 数据库文件 │ │
│ │ □ 日志轮转: 配置日志轮转策略,避免磁盘写满 │ │
│ │ □ 凭据轮换: 定期更新各渠道的 Token/Secret │ │
│ │ □ 版本更新: 关注 OpenClaw 版本更新,及时升级 │ │
│ │ □ 安全审计: 定期检查 allowlist 和 dmPolicy │ │
│ │ □ 性能监控: 监控 CPU/内存/磁盘使用率 │ │
│ │ □ 渠道健康: 定期检查各渠道连接状态 │ │
│ │ □ 插件安全: 审查第三方插件的安全性 │ │
│ │ □ 灾难恢复: 制定灾难恢复计划并定期演练 │ │
│ └─────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────┘
附录
附录A: 术语对照表
术语英文说明多渠道适配层Multi-Channel Adaptation LayerOpenClaw 四层架构中的第二层,负责渠道差异屏蔽渠道适配器Channel Adapter / ChannelPlugin每个平台的适配实现,以插件形式存在消息归一化Message Normalization将异构消息转换为统一格式的过程会话标识sessionKey唯一标识一个会话的键值统一用户标识unified_user_id跨平台的统一用户身份内部消息InternalMessage统一的内部消息格式消息上下文MsgContext / ctxPayload包含完整上下文的消息对象信封格式Envelope消息正文的统一前缀格式车道Lane串行处理同一 sessionKey 消息的执行单元死信队列Dead Letter Queue (DLQ)超过最大重试次数的消息队列熔断器Circuit Breaker连续失败时暂停发送的保护机制优雅降级Graceful Degradation功能不支持时的逐步降级策略中心辐射式Hub-and-Spoke以 Gateway 为中心的架构模式配对码Pairing Code跨平台身份关联的验证码
附录B: 配置文件结构总览
~/.openclaw/
├── openclaw.json # 主配置文件
├── SOUL.md # Agent 身份与价值观
├── HEARTBEAT.md # 任务清单
├── workspace/ # 工作目录
│ ├── data/
│ │ ├── openclaw.db # SQLite 数据库
│ │ └── media/ # 媒体文件缓存
│ ├── logs/ # 日志目录
│ │ ├── gateway.log
│ │ ├── channels/
│ │ │ ├── telegram.log
│ │ │ ├── discord.log
│ │ │ └── ...
│ │ └── metrics.jsonl # 指标日志
│ ├── memory/ # 持久化记忆
│ │ ├── USER.md
│ │ └── MEMORY.md
│ └── plugins/ # 自定义插件目录
└── extensions/ # 渠道插件源码目录
├── telegram/
├── discord/
├── slack/
├── wechat/
├── feishu/
├── dingtalk/
└── qq-bot/
附录C: 常用运维命令
# 渠道管理
openclaw channels list # 列出所有渠道及状态
openclaw channels status # 检查连通性
openclaw channels add# 添加新渠道
openclaw channels remove# 删除渠道
openclaw channels restart# 重启指定渠道
# Gateway 管理
openclaw gateway start # 启动 Gateway
openclaw gateway stop # 停止 Gateway
openclaw gateway restart # 重启 Gateway
openclaw gateway status # 查看 Gateway 状态
# 诊断与排障
openclaw doctor # 诊断系统问题
openclaw doctor --fix # 诊断并自动修复
openclaw logs --follow # 实时日志监控
openclaw logs --channel telegram # 查看指定渠道日志
# 插件管理
openclaw plugins list # 查看已安装插件
openclaw plugins install# 安装插件
openclaw plugins uninstall# 卸载插件
openclaw plugins verify# 验证插件安全性
# 会话管理
openclaw sessions list # 列出活跃会话
openclaw sessions clear# 清除指定会话
openclaw sessions export# 导出会话历史
# 监控
openclaw dashboard # 打开 Web 控制台
openclaw metrics # 查看性能指标
openclaw health # 健康检查
附录D: 渠道适配器开发检查清单
开发自定义渠道适配器时,请逐项确认:
□ 基础结构
□ 创建 extensions// 目录
□ 实现 index.ts (defineBundledChannelEntry 注册)
□ 实现 Monitor 模块 (连接管理 + 事件接收 + 安全过滤)
□ 实现 Context Builder 模块 (信息提取 + Envelope 生成 + MsgContext 组装)
□ 实现 Outbound Adapter 模块 (格式转换 + 媒体处理 + 消息分块)
□ 接口实现
□ 定义 channelId 和 displayName
□ 声明完整的 capabilities (消息类型/交互能力/限制约束/连接方式)
□ 实现 start() 方法 (建立连接 + 注册回调 + 启动心跳)
□ 实现 stop() 方法 (断开连接 + 清理资源 + 保存状态)
□ 实现 send() 方法 (格式转换 + 媒体上传 + API 调用)
□ 实现 healthCheck() 方法 (连接检测 + 延迟测量)
□ 实现 getStatus() 方法 (运行时状态返回)
□ 协议适配
□ 选择正确的协议基类 (WebSocket / Webhook / Long Polling)
□ 实现断线重连逻辑 (指数退避)
□ 实现心跳保活机制
□ 处理平台特定的认证流程
□ 消息处理
□ 入站: 平台原生格式 → InternalMessage
□ 出站: ReplyPayload → 平台原生格式
□ Markdown 格式转换 (如果平台不支持原生 MD)
□ 消息分块逻辑 (超过平台长度限制时)
□ 媒体文件上传和处理
□ 按钮和交互组件的适配
□ 降级策略实现
□ 安全与健壮性
□ 入站消息安全过滤 (allowlist / dmPolicy)
□ 频率限制适配
□ 错误处理和日志记录
□ 重试和故障转移逻辑
□ 配置校验 (Zod schema)
□ 测试与验证
□ 单元测试覆盖核心逻辑
□ 集成测试验证端到端流程
□ 错误场景测试 (网络断连 / API 限流 / 认证失败)
□ 性能测试 (高并发场景)
□ openclaw doctor 通过