OpenProgram Docs

Channel subsystem design

Platform user implementations/*.py long poll or event loop; parse into ChannelMessage handle_inbound per-message thread, access gate, attachments, quoted block dispatch_inbound route, session key, per-session lock, run turn, progress, broadcast Script, job, notebook outbound.py one-shot, no worker needed _transport.py the only place that sends bytes: chunk, render, hard-cap split, rate-limit retry Telegram, Discord, Slack, WeChat iLink
  1. Platform user
  2. implementations/*.pylong poll or event loop; parse into ChannelMessage
  3. handle_inboundper-message thread, access gate, attachments, quoted block
  4. dispatch_inboundroute, session key, per-session lock, run turn, progress, broadcast
  5. Script, job, notebook: outbound.py
  6. _transport.pythe only place that sends bytes: chunk, render, hard-cap split, rate-limit retry
  7. 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?"

StageWhat 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_inboundA 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_inboundBindings 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 runstool_use edits the placeholder to ⚙ bash once more than 1 s has passed since the last edit; tool_result swaps it to ✓ bash.
ReplyA forced edit bypasses the throttle and turns message 9001 into the reply. Persists, broadcasts, returns None, so handle_inbound sends nothing.
Degraded pathPlaceholder 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

EntryPurposeStateCaller
outbound.sendOne-shot, no long-running processstatelessJobs, notebooks, Agent methods, Web UI reply
Channel.send_text + edit_textHolds message_id for editsstatefuldispatch_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

LayerOwns
_transport.pyEvery 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.pyMarkdown 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.
AdaptersOnly 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

AspectRule
FileOne 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.
Code8 uppercase characters without 0O1I, valid 1 hour. Same sender not re-prompted in that hour; excess requests silently ignored.
GateRuns before routing; an unpaired sender never reaches dispatch_inbound.
Mutationapprove, 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.

ModuleResponsibilityCalled by
base.pyChannel ABC, MessageHandle, handle_inbound, run_forever, send_text/edit_text(_full), send_fileAdapters, worker, dispatch_inbound
_transport.pySendResult, chunk → render → cap split → retry, 4 platforms' text, edit and file HTTPoutbound, base.send_text/send_file
_format.pyMarkdown to platform wire format_transport
_access.pyAllowlist and pairing gate, access.jsonhandle_inbound (check); CLI, loopback Web UI (mutate)
_room.pyActivation and memory modes (rooms.json), pending history, flood limit, duplicate deliveryhandle_inbound
_active_turns.pyEach session's running turn: chat, speaker, ambient flag_conversation, chat_send, /answer gate
_attachments.pyInbound download; image blocks and [attachment: path] noteshandle_inbound
_message.pyChannelMessage, AttachmentAdapters
_wechat_media.pyiLink media items, CDN keys, AES-128-ECB, outbound itemsWeChat adapter, _attachments, _transport
outbound.pysend, send_full, send_fileJobs, notebooks, Agent methods
_conversation.pydispatch_inbound, per-session lock, progress streaminghandle_inbound
_session_store.pySession path, create, load, savedispatch_inbound
_session_routing.pysession_key, reset policydispatch_inbound
_broadcast.pyWS frames on the event bus (emit_ws_frame → ws.frame); channels never import webuidispatch_inbound
_question_bridge.pyPushes a pending runtime.ask into the chatQuestion path
_question_commands.py/answer, /decline_conversation
_heartbeats.pyAdapter running marks: set when the thread starts, cleared when it endsStatus API
bound_reply.pySends a bound chat's assistant reply to its channel for turns that did not come from the channelopenprogram.runtime.conversation.bound_reply
link_registration.pyImplements openprogram.runtime.channel_link, so core code reaches channels without importing this interfaceCore, on import
__init__.pyCHANNEL_CLASSES, register_channel, entry pointsWeb UI status, worker
accounts.pyCredentials and ACCOUNT_SETTINGS_transport, adapters
bindings.py(channel, account, peer) → agentdispatch_inbound
implementations/*.pyInbound loop and parse; Telegram group settings and mention detection; WeChat QR loginWorker via run_forever

The openprogram channels setup wizard lives in openprogram/interfaces/cli/setup_sections/channels.py.

Platforms

PlatformInboundOutboundProgressAttachments inNotes
TelegramgetUpdates long-poll, no webhooksendMessage (HTML), editMessageText, sendPhoto, sendDocumentyesphoto, document, voice (transcribed), audio, video, animation (file_id → getFile)Bot token, public Bot API; group_sessions, require_mention
Discorddiscord.py GatewayPOST /messages, PATCH /messages/{id}, multipartyesCDN URLsBot token, intents.message_content
SlackSocket Mode (slack_sdk)chat.postMessage (mrkdwn), chat.update, external-uploadyesurl_private with bearerbot_token (xoxb-), app_token (xapp-)
WeChatiLink getupdates long-polliLink sendmessage (plain text); getuploadurl with encrypted CDN uploadno: iLink cannot editimage, voice, file, video, decrypted from the CDNPersonal WeChat QR login, no enterprise verification

All four send files.

User entry points

CLI

openprogram channelsDoes
listStatus per platform and account
setupInteractive wizard
accounts listAll 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 listAll 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

EntryImplementation
/channel: pick a channel, an account, then /attach to bind the conversation to a peerapps/cli/src/commands/handler.ts, apps/cli/src/screens/repl/pickers/channel.tsx
TUI activity feedapps/cli/src/components/ChannelActivityFeed.tsx
TUI channel turnapps/cli/src/screens/repl/wsHandlers/handleChannelTurn.ts
Composer channel chip, always shownapps/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 managementapps/web/components/settings/channels/access-list.tsx, loopback-only /api/channels/access

Extension points

ExtensionHow
New platformChannel subclass and entry point; parse into ChannelMessage and the base pipeline applies
Thread-scoped sessionsthread_id is parsed and carries replies back; the work is folding it into the session key
Reaction approvalAdapter-side listener and a bridge to the approval path
Token-level text streamingEdits happen at tool boundaries; reply-delta edits must weigh rate limits
Last updated · 2026-11-25