OpenProgram Docs

渠道子系统设计

平台用户 implementations/*.py 长轮询或事件循环; 解析成 ChannelMessage handle_inbound 每条消息一个线程、访问门禁、 附件、引用块 dispatch_inbound 路由、会话 key、按会话加锁、 运行回合、进度、广播 脚本、定时任务、notebook outbound.py 一次性发送,无需 worker _transport.py 唯一发送字节的地方:分块、渲染、硬上限拆分、限流重试 Telegram、Discord、Slack、微信 iLink
  1. 平台用户
  2. implementations/*.py长轮询或事件循环; 解析成 ChannelMessage
  3. handle_inbound每条消息一个线程、访问门禁、 附件、引用块
  4. dispatch_inbound路由、会话 key、按会话加锁、 运行回合、进度、广播
  5. 脚本、定时任务、notebook: outbound.py
  6. _transport.py唯一发送字节的地方:分块、渲染、硬上限拆分、限流重试
  7. Telegram、Discord、Slack、微信 iLink

要求、约束以及与 OpenClaw、Hermes 的对比:要求与约束。协议细节:各适配器顶部的 docstring。

一条消息的全过程

你给 Telegram 机器人发送“这里有哪些 Python 文件?”

阶段发生什么
telegram.py_handle_update 收到 update,构造 ChannelMessage{text, chat_id="123", user_id="456", chat_type="direct", attachments=()}。@ 机器人或回复机器人时 mentioned=True,并去掉提及。
handle_inbound每条消息一个守护线程,runtime.ask 暂停的回合不会阻塞轮询。decide_inbound_sender、download_inbound、引用块,然后 dispatch_inbound(channel="telegram", account_id="default", peer_kind="direct", peer_id="123", progress_stream=True, ...)。同一 peer 的消息到达时排队,按这个顺序开启轮次;命令不排队。
dispatch_inbound绑定决定 agent。session_key = "default_direct_123"。获取按会话的锁:同会话回合排队,不同会话并行;/answer 和 /decline 在锁之前处理;/stop 和 /help 不经过这里。加载会话。发送 ⏳ working...,保留 MessageHandle{message_id="9001"}。运行 process_user_turn。
工具运行tool_use 在距上次编辑超过 1 秒时把占位改成 ⚙ bash;tool_result 改成 ✓ bash。
回复强制编辑绕过节流,把消息 9001 改成回复。持久化、广播,返回 None,handle_inbound 不再发送。
降级路径占位发送失败、平台不能编辑或微信:dispatch_inbound 返回回复,handle_inbound 经 Channel.send_text 按 MAX_CHARS 分块发送。

peer_id 来自 Channel.peer_id_for:Telegram 和微信为 chat_id;Telegram 群组 group_sessions=per-user 时为 {chat_id}_{user_id};Discord 和 Slack 为 {chat_id}_{user_id}。

从代码发送

from openprogram.interfaces.channels.outbound import send

send("telegram", "default", "1234", "Good morning")

取凭据、HTTPS POST、SendResult 转为 True/False。没有适配器、worker、会话、agent 调用或广播。

设计原则

两个入口,一个实现

入口用途状态调用方
outbound.send一次性,无需常驻进程无状态定时任务、notebook、Agent 方法、Web UI 回复
Channel.send_text + edit_text持有 message_id 用于编辑有状态dispatch_inbound 进度

两者都用 _transport.post_message / patch_message:HTTP、凭据和分块只有一份。

流量枢纽

_conversation.py 只保留流程:路由、会话 key 和重置策略,然后在按会话的锁内加载会话、流式时发占位、运行 agent、持久化和广播。路由、存储和广播各在自己的模块。

平台差异封在底层

层负责
_transport.py所有对外 HTTP:editMessageText、PATCH /messages/{id}、chat.update、iLink,各平台 post_file(sendPhoto/sendDocument、multipart、external-upload、iLink CDN)。MAX_CHARS、分块、HARD_CAPS 再拆分、限流重试。
_format.pyMarkdown 转 Telegram HTML(全部转义;实体被拒时回退为去标签文本)、Slack mrkdwn、Discord 直通、微信纯文本。代码用占位保护。
适配器只负责事件循环和解析成 ChannelMessage。它们不发送;解析之后的一切在 handle_inbound。
run_forever(stop)run() 抛异常时重连:5 秒起翻倍,上限 300 秒,存活 60 秒后重置。正常返回表示永久停止,如微信 token 失效。
waiting_for_platform()包住一次长轮询。worker 停止时最多等适配器线程 2 秒,但不等正在轮询里的线程:停止之后才到的应答不读取,游标或 offset 不动,重启后会再次拿到。

结构化错误

@dataclass(frozen=True)
class SendResult:
    ok: bool
    message_id: str = ""
    error_kind: str = ""     # auth, rate_limit, bad_target, network,
                             # not_supported, format, unknown
    error_detail: str = ""   # one human-readable line
    retryable: bool = False
    retry_after: float = 0.0 # platform-stated wait; 0 = unstated
    connect_failed: bool = False   # connection never opened; safe to resend

rate_limit 在 _transport 内重试:优先 Retry-After,否则 1 秒、3 秒,等待上限 30 秒,共 3 次。

连接没建立(connect_failed)时隔 1、2、4 秒重试,共 4 次;请求发出后的失败不重试,重发可能送达两次。

outbound.send、send_text、edit_text 返回 bool 或句柄;_full 变体和两个 send_file 返回 SendResult。

入站访问控制

方面规则
文件每个(渠道、账号)一个 access.json:按稳定平台用户 id 的 allowlist,最多三个 pending。准入始终是配对;旧的 policy: "open" 被忽略。
配对码8 位大写字符,不含 0O1I,有效 1 小时。这一小时内不再提示同一发送者;超额请求静默忽略。
门禁在路由前运行;未配对发送者到不了 dispatch_inbound。
修改approve、approve_user、revoke 只能在本地 CLI 和回环 Web UI 中使用。入站路径只读取和生成配对码,渠道消息无法批准任何人。

新增平台

# pyproject.toml, scanned at startup
[project.entry-points."openprogram.channels"]
whatsapp = "my_pkg.whatsapp:WhatsAppChannel"

# or, for notebooks and plugin hooks
from openprogram.interfaces.channels import register_channel
register_channel("whatsapp", WhatsAppChannel)

内置平台优先,同名插件被忽略。

模块清单

位于 openprogram/interfaces/channels/。每个模块只面向声明的调用方,没有循环依赖。

模块职责调用方
base.pyChannel ABC、MessageHandle、handle_inbound、run_forever、send_text/edit_text(_full)、send_file适配器、worker、dispatch_inbound
_transport.pySendResult、分块 → 渲染 → 上限拆分 → 重试,4 个平台的文本、编辑和文件 HTTPoutbound、base.send_text/send_file
_format.pyMarkdown 转平台格式_transport
_access.py白名单和配对门禁,access.jsonhandle_inbound(检查);CLI、回环 Web UI(修改)
_room.py激活和记忆模式(rooms.json)、待处理历史、洪泛限制、重复投递handle_inbound
_active_turns.py每个会话运行中的回合:会话、发言者、ambient 标记_conversation、chat_send、/answer 门禁
_attachments.py入站下载;图片块和 [attachment: path] 说明handle_inbound
_message.pyChannelMessage、Attachment适配器
_wechat_media.pyiLink 媒体项、CDN key、AES-128-ECB、出站媒体项微信适配器、_attachments、_transport
outbound.pysend、send_full、send_file定时任务、notebook、Agent 方法
_conversation.pydispatch_inbound、按会话的锁、进度流handle_inbound
_session_store.py会话路径、创建、加载、保存dispatch_inbound
_session_routing.pysession_key、重置策略dispatch_inbound
_broadcast.py事件总线上的 WS 帧(emit_ws_frame → ws.frame);渠道从不导入 webuidispatch_inbound
_question_bridge.py把待回答的 runtime.ask 推送到聊天问题路径
_question_commands.py/answer、/decline_conversation
_heartbeats.py适配器运行标记:线程启动时设置,结束时清除状态 API
bound_reply.py把绑定聊天的助手回复发到渠道,用于不是从渠道发起的回合openprogram.runtime.conversation.bound_reply
link_registration.py实现 openprogram.runtime.channel_link,核心代码无需导入本接口即可访问渠道核心,导入时注册
__init__.pyCHANNEL_CLASSES、register_channel、entry pointsWeb UI 状态、worker
accounts.py凭据和 ACCOUNT_SETTINGS_transport、适配器
bindings.py(渠道、账号、peer)→ agentdispatch_inbound
implementations/*.py入站循环和解析;Telegram 群设置和提及检测;微信二维码登录worker 经 run_forever

openprogram channels setup 向导位于 openprogram/interfaces/cli/setup_sections/channels.py。

支持的平台

平台入站出站进度入站附件说明
TelegramgetUpdates 长轮询,无 webhooksendMessage (HTML), editMessageText, sendPhoto, sendDocument支持照片、文档、语音(转文字)、音频、视频、动图(file_id → getFile)Bot token,公开 Bot API;group_sessions、require_mention
Discorddiscord.py GatewayPOST /messages, PATCH /messages/{id}, multipart支持CDN URLBot token,intents.message_content
SlackSocket Mode (slack_sdk)chat.postMessage (mrkdwn), chat.update, external-upload支持url_private 带 bearerbot_token (xoxb-), app_token (xapp-)
微信iLink getupdates 长轮询iLink sendmessage(纯文本);getuploadurl 加密 CDN 上传不支持:iLink 不能编辑图片、语音、文件、视频,从 CDN 解密个人微信二维码登录,无需企业认证

四个平台都支持发送文件。

用户入口

CLI

openprogram channels作用
list各平台和账号的状态
setup交互向导
accounts list所有账号
accounts add <channel> --id <name>新建账号槽
accounts login <channel> --id <name>Telegram、Discord、Slack:粘贴 token。微信:iLink 二维码。
accounts set <channel> <key> <value> --id <name>Telegram、Discord、Slack:require_mention=on|off、ack_reaction=on|off。Telegram:group_sessions=shared|per-user。全部:sender_access=owner|paired。
accounts group-users list|add|remove|reset <channel>agent 在群里回答谁
accounts rm <channel> <account_id>删除账号及其绑定
access list [<channel>]白名单和待处理配对码
access approve <channel> <code> --id <name>按配对码批准
access allow <channel> <user_id> --id <name>直接加入用户 id
access revoke <channel> <user_id> --id <name>移除发送者
bindings list所有路由规则
bindings add <agent_id> --channel <ch> [--account <acct>] [--peer <peer> --peer-kind <kind>]路由到 agent
bindings rm <binding_id>删除一条路由

TUI 与 Web UI

入口实现
/channel:选渠道、账号,再用 /attach 把对话绑定到 peerapps/cli/src/commands/handler.ts, apps/cli/src/screens/repl/pickers/channel.tsx
TUI 活动流apps/cli/src/components/ChannelActivityFeed.tsx
TUI 渠道回合apps/cli/src/screens/repl/wsHandlers/handleChannelTurn.ts
输入框渠道 chip,始终显示apps/web/components/chat/composer/environment-row/chips/channel-chip.tsx, apps/web/components/chat/top-bar/menus/channel-choices.ts
健康徽标/api/channels/{platform}/{account_id}/status:alive、reconnecting、signed_out、failed、unknown
本地访问管理apps/web/components/settings/channels/access-list.tsx,仅回环的 /api/channels/access

扩展点

扩展做法
新平台Channel 子类加 entry point;解析成 ChannelMessage 后基础管线即可适用
按 thread 隔离会话thread_id 已解析并用于回到原 thread;要做的是把它并入会话 key
表情审批适配器侧监听,加上到审批路径的桥接
按 token 流式目前在工具边界编辑;按回复增量编辑要权衡限流
Last updated · 2026-11-25