Channel subsystem design
- Platform user
implementations/*.pylong poll or event loop; parse into ChannelMessagehandle_inboundper-message thread, access gate, attachments, quoted blockdispatch_inboundroute, session key, per-session lock, run turn, progress, broadcast- Script, job, notebook:
outbound.py _transport.pythe only place that sends bytes: chunk, render, hard-cap split, rate-limit retry- Telegram, Discord, Slack, WeChat iLink
Requirements, invariants and the comparison with OpenClaw and Hermes: Requirements and invariants. Protocol details: the docstring at the top of each adapter.
One message, end to end
You send the Telegram bot "what Python files are here?"
| Stage | What happens |
|---|---|
telegram.py | _handle_update receives the update and builds ChannelMessage{text, chat_id="123", user_id="456", chat_type="direct", attachments=()}. An @mention or reply to the bot sets mentioned=True; the mention is stripped. |
handle_inbound | A per-message daemon thread, so a turn paused on runtime.ask does not block polling. decide_inbound_sender, download_inbound, quoted block, then dispatch_inbound(channel="telegram", account_id="default", peer_kind="direct", peer_id="123", progress_stream=True, ...). Messages from one peer take a place in line on arrival and start turns in that order; commands skip the line. |
dispatch_inbound | Bindings pick the agent. session_key = "default_direct_123". Takes the per-session lock: same-session turns queue, different sessions run in parallel; /answer and /decline are handled before the lock; /stop and /help never reach it. Loads the session. Posts ⏳ working..., keeping MessageHandle{message_id="9001"}. Runs process_user_turn. |
| Tool runs | tool_use edits the placeholder to ⚙ bash once more than 1 s has passed since the last edit; tool_result swaps it to ✓ bash. |
| Reply | A forced edit bypasses the throttle and turns message 9001 into the reply. Persists, broadcasts, returns None, so handle_inbound sends nothing. |
| Degraded path | Placeholder failed, the platform cannot edit, or WeChat: dispatch_inbound returns the reply and handle_inbound sends it via Channel.send_text, chunked at MAX_CHARS. |
peer_id is Channel.peer_id_for: chat_id on Telegram and WeChat, or {chat_id}_{user_id} in Telegram groups with group_sessions=per-user; {chat_id}_{user_id} on Discord and Slack.
Sending from code
from openprogram.interfaces.channels.outbound import send
send("telegram", "default", "1234", "Good morning")
Credentials, HTTPS POST, SendResult to True/False. No adapter, worker, session, agent call or broadcast.
Principles
Two entry points, one implementation
| Entry | Purpose | State | Caller |
|---|---|---|---|
outbound.send | One-shot, no long-running process | stateless | Jobs, notebooks, Agent methods, Web UI reply |
Channel.send_text + edit_text | Holds message_id for edits | stateful | dispatch_inbound progress |
Both use _transport.post_message / patch_message: one copy of HTTP, credentials and chunking.
Traffic hub
_conversation.py holds only the flow: route, session key and reset policy, then under the per-session lock load the session, post a placeholder when streaming, run the agent, persist and broadcast. Routing, storage and broadcast live in their own modules.
Platform differences sealed low
| Layer | Owns |
|---|---|
_transport.py | Every outward HTTP call: editMessageText, PATCH /messages/{id}, chat.update, iLink, post_file per platform (sendPhoto/sendDocument, multipart, external-upload, iLink CDN). MAX_CHARS, chunking, HARD_CAPS re-split, rate-limit retry. |
_format.py | Markdown to Telegram HTML (everything escaped; the poster falls back to tag-stripped text if entities are rejected), Slack mrkdwn, Discord passthrough, WeChat plain text. Code is placeholder-protected. |
| Adapters | Only the event loop and parsing into ChannelMessage. They do not send; everything after the parse lives in handle_inbound. |
run_forever(stop) | A raising run() reconnects: 5 s doubling, cap 300 s, reset after surviving 60 s. A clean return means permanently stopped, e.g. invalid WeChat token. |
waiting_for_platform() | Wraps a long poll. A stopping worker waits up to 2 s for adapter threads, but not for one inside a poll: an answer that arrives after the stop is left unread, so the cursor or offset hands it out again after the restart. |
Structured errors
@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 retries inside _transport: Retry-After first, else 1 s then 3 s, sleep capped at 30 s, 3 attempts.
A connection that never opened (connect_failed) retries after 1, 2 and 4 s, 4 attempts; a failure after the request went out does not retry, since a resend could arrive twice.
outbound.send, send_text and edit_text return bool or a handle; _full variants return SendResult, as do both send_files.
Inbound access
| Aspect | Rule |
|---|---|
| File | One access.json per (channel, account): allowlist by stable platform user id, at most three pending. Admission is always pairing; a legacy policy: "open" is ignored. |
| Code | 8 uppercase characters without 0O1I, valid 1 hour. Same sender not re-prompted in that hour; excess requests silently ignored. |
| Gate | Runs before routing; an unpaired sender never reaches dispatch_inbound. |
| Mutation | approve, approve_user, revoke only from the local CLI and loopback Web UI. The inbound path only reads and mints codes, so no channel message can approve anyone. |
Adding a platform
# 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)
Built-ins take priority; a same-named plugin is ignored.
Modules
Under openprogram/interfaces/channels/. Each module deals only with its declared callers; no circular dependencies.
| Module | Responsibility | Called by |
|---|---|---|
base.py | Channel ABC, MessageHandle, handle_inbound, run_forever, send_text/edit_text(_full), send_file | Adapters, worker, dispatch_inbound |
_transport.py | SendResult, chunk → render → cap split → retry, 4 platforms' text, edit and file HTTP | outbound, base.send_text/send_file |
_format.py | Markdown to platform wire format | _transport |
_access.py | Allowlist and pairing gate, access.json | handle_inbound (check); CLI, loopback Web UI (mutate) |
_room.py | Activation and memory modes (rooms.json), pending history, flood limit, duplicate delivery | handle_inbound |
_active_turns.py | Each session's running turn: chat, speaker, ambient flag | _conversation, chat_send, /answer gate |
_attachments.py | Inbound download; image blocks and [attachment: path] notes | handle_inbound |
_message.py | ChannelMessage, Attachment | Adapters |
_wechat_media.py | iLink media items, CDN keys, AES-128-ECB, outbound items | WeChat adapter, _attachments, _transport |
outbound.py | send, send_full, send_file | Jobs, notebooks, Agent methods |
_conversation.py | dispatch_inbound, per-session lock, progress streaming | handle_inbound |
_session_store.py | Session path, create, load, save | dispatch_inbound |
_session_routing.py | session_key, reset policy | dispatch_inbound |
_broadcast.py | WS frames on the event bus (emit_ws_frame → ws.frame); channels never import webui | dispatch_inbound |
_question_bridge.py | Pushes a pending runtime.ask into the chat | Question path |
_question_commands.py | /answer, /decline | _conversation |
_heartbeats.py | Adapter running marks: set when the thread starts, cleared when it ends | Status API |
bound_reply.py | Sends a bound chat's assistant reply to its channel for turns that did not come from the channel | openprogram.runtime.conversation.bound_reply |
link_registration.py | Implements openprogram.runtime.channel_link, so core code reaches channels without importing this interface | Core, on import |
__init__.py | CHANNEL_CLASSES, register_channel, entry points | Web UI status, worker |
accounts.py | Credentials and ACCOUNT_SETTINGS | _transport, adapters |
bindings.py | (channel, account, peer) → agent | dispatch_inbound |
implementations/*.py | Inbound loop and parse; Telegram group settings and mention detection; WeChat QR login | Worker via run_forever |
The openprogram channels setup wizard lives in openprogram/interfaces/cli/setup_sections/channels.py.
Platforms
| Platform | Inbound | Outbound | Progress | Attachments in | Notes |
|---|---|---|---|---|---|
| Telegram | getUpdates long-poll, no webhook | sendMessage (HTML), editMessageText, sendPhoto, sendDocument | yes | photo, document, voice (transcribed), audio, video, animation (file_id → getFile) | Bot token, public Bot API; group_sessions, require_mention |
| Discord | discord.py Gateway | POST /messages, PATCH /messages/{id}, multipart | yes | CDN URLs | Bot token, intents.message_content |
| Slack | Socket Mode (slack_sdk) | chat.postMessage (mrkdwn), chat.update, external-upload | yes | url_private with bearer | bot_token (xoxb-), app_token (xapp-) |
iLink getupdates long-poll | iLink sendmessage (plain text); getuploadurl with encrypted CDN upload | no: iLink cannot edit | image, voice, file, video, decrypted from the CDN | Personal WeChat QR login, no enterprise verification |
All four send files.
User entry points
CLI
openprogram channels | Does |
|---|---|
list | Status per platform and account |
setup | Interactive wizard |
accounts list | All accounts |
accounts add <channel> --id <name> | New account slot |
accounts login <channel> --id <name> | Telegram, Discord, Slack: paste token. WeChat: iLink QR. |
accounts set <channel> <key> <value> --id <name> | Telegram, Discord, Slack: require_mention=on|off, ack_reaction=on|off. Telegram: group_sessions=shared|per-user. All: sender_access=owner|paired. |
accounts group-users list|add|remove|reset <channel> | Who the Agent answers in groups |
accounts rm <channel> <account_id> | Deletes account and its bindings |
access list [<channel>] | Allowlist and pending codes |
access approve <channel> <code> --id <name> | By pairing code |
access allow <channel> <user_id> --id <name> | A user id directly |
access revoke <channel> <user_id> --id <name> | Removes a sender |
bindings list | All routing rules |
bindings add <agent_id> --channel <ch> [--account <acct>] [--peer <peer> --peer-kind <kind>] | Routes to an agent |
bindings rm <binding_id> | Deletes one route |
TUI and Web UI
| Entry | Implementation |
|---|---|
/channel: pick a channel, an account, then /attach to bind the conversation to a peer | apps/cli/src/commands/handler.ts, apps/cli/src/screens/repl/pickers/channel.tsx |
| TUI activity feed | apps/cli/src/components/ChannelActivityFeed.tsx |
| TUI channel turn | apps/cli/src/screens/repl/wsHandlers/handleChannelTurn.ts |
| Composer channel chip, always shown | apps/web/components/chat/composer/environment-row/chips/channel-chip.tsx, apps/web/components/chat/top-bar/menus/channel-choices.ts |
| Health badge | /api/channels/{platform}/{account_id}/status: alive, reconnecting, signed out, failed, unknown |
| Local access management | apps/web/components/settings/channels/access-list.tsx, loopback-only /api/channels/access |
Extension points
| Extension | How |
|---|---|
| New platform | Channel subclass and entry point; parse into ChannelMessage and the base pipeline applies |
| Thread-scoped sessions | thread_id is parsed and carries replies back; the work is folding it into the session key |
| Reaction approval | Adapter-side listener and a bridge to the approval path |
| Token-level text streaming | Edits happen at tool boundaries; reply-delta edits must weigh rate limits |