OpenProgram Docs

Channel requirements and invariants

Structure and message flow: Channel subsystem design.

The contract

@dataclass(frozen=True)
class MessageHandle:
    platform: str
    account_id: str
    target: str
    message_id: str

    @property
    def editable(self) -> bool: ...


class Channel(abc.ABC):
    platform_id: str = ""

    @abc.abstractmethod
    def run(self, stop: threading.Event) -> None: ...

    def send_text(self, target, text) -> Optional[MessageHandle]: ...
    def send_text_full(self, target, text, thread_id=None) -> SendResult: ...
    def send_file(self, target, path, caption="", thread_id=None) -> SendResult: ...
    def edit_text(self, handle, new_text) -> bool: ...
    def edit_text_full(self, handle, new_text) -> SendResult: ...
InvariantReason
run is the only abstract methodInbound loops have no common shape. Outbound does, so send and edit are concrete over _transport. An adapter implementing only run can fully send and edit; overrides exist only when an SDK adds something, such as mention parsing or upload. Mandating send/edit/react would force capabilities a platform may lack.
MessageHandle is all stringsSurvives serialization: one process sends, another edits
Two entry points, one implementationoutbound.send works with no adapter in the process; adapter.send_text keeps the id to edit. _transport alone owns HTTP, credentials and chunking, so a new operation is one implementation, not eight.
Sends return SendResultA bool cannot separate a transient failure from a permanent one. error_kind (auth, rate_limit, bad_target, network, not_supported, format, unknown) comes from _classify_http_status, _telegram_kind_from_description, _slack_kind_from_error. Bool forms remain.
Edit capability is a handle propertyiLink cannot edit. WeChat handles report editable == False; edit_text_full returns SendResult.fail("not_supported", ...), never faking it by deleting and reposting. No caller special-cases a platform name.
Cross-platform edits are refusedhandle.platform != self.platform_id returns SendResult.fail("bad_target", ...). Coordinating adapters is the caller's concern.
Built-ins win registration_BUILTIN_CHANNEL_CLASSES over _PLUGIN_CHANNEL_CLASSES. Plugins use [project.entry-points."openprogram.channels"] or register_channel(name, cls). CHANNEL_CLASSES is a dict-like proxy over both.

Neutral inbound message

_message.py:ChannelMessage, frozen: text, chat_id, user_id, user_display, message_id, chat_type, ts, reply_to_id, quoted_text, thread_id, parent_chat_id, attachments (tuple of Attachment), mentioned, from_bot.

The pipeline prepends quoted_text as a > block and downloads attachments, forwarding small images as vision input. thread_id sends placeholders, replies and files back to the thread; it does not join session routing.

Inbound dispatch

StepDoes
1. Routesession_aliases and bindings decide agent_id
2. Keysession_key per agent.session_scope
3. Resetdaily_reset or idle_minutes
4. Store_load_or_init_session writes the session store
5. Turnbuild_turn_request makes the TurnRequest; CanonicalAgentAdapter admits and runs it
6. ReplyAppended
7. BroadcastA channel_turn envelope to the Web UI

progress_stream=False returns the reply for the adapter to send. True drives send_text/edit_text, so tool events reach the user mid-turn; the dispatcher already emits them, so streaming is wiring over MessageHandle and patch_message. Routing, storage and broadcast are split into _session_routing.py, _session_store.py, _broadcast.py.

Why the stateless entry point exists

ParadigmWho drivesEntry
A: agentic programmingPython control flow; Agent method makes a Context node; Runtime.exec asks the LLM only when calledCode written by the programmer
B: agent loop (channels, Web UI chat)The LLM picks tools: process_user_turn → agent_loop → tool streamingAn external message
DeploymentAdapter instance
openprogram worker runningin the worker
Script importing an Agent method; job in a separate process; notebook; pytestnowhere
  • Channels attach to B, but A still sends. A is library mode: no worker assumed. OpenClaw's and Hermes's adapter-only sends fit their single daemon, where a job can get adapters by injection.
  • Any async-first base must keep a synchronous module-level wrapper, so an Agent method can send without asyncio.
  • Streaming edit stays reachable from A: an Agent method can hold a MessageHandle and edit it.

Comparison

OpenClaw is the TypeScript source OpenProgram forked from; Hermes is a Python chat-bot project. Opencode and Claude Code have no channel subsystem.

AspectOpenProgramOpenClawHermes
Abstract methods1 (run), concrete send and edit5+ (SendAdapter, LiveAdapter, ApprovalAdapter...)5+ (send, edit, draft, typing, handoff)
Neutral messageChannelMessageChannelMeta with media, richtext, componentsMessageEvent, SessionSource
Send resultSendResult (ok, message_id, error_kind, retryable, retry_after)DurableMessageSendResult (message_id, edited_ids, retry policy)SendResult (message_id, retryable)
Dispatchsync → str, or progress_stream=Trueasync pipeline: draft → live → finalasync streaming events
Session isolationsession_scope, 4 valuesdmScope, thread-bindings-policychat × user × thread
Progressdispatcher drives send and editthree stages, throttlededit_message, automatic overflow split
Approvaltext bridge (_question_commands.py)reaction ✓/✗, onApprove, onDecline, onTimeout/approve text command
Debouncenoneunknown0.35 s delay, 1 s cap
Health checknone at startup; heartbeats feed statushealth-check-adapter.tsunknown
Receiptsnoneyesunknown
Structured repliestext onlyembed, button, menupartial
Attachmentsstate dir, vision inputcachedUUID prefix, 24 h cleanup
Outbound APIoutbound.send shares _transportthrough adaptersDeliveryRouter(adapters: dict)
Process modellib, worker, scriptsingle daemonsingle gateway
Chunking_transport._chunkin the platform plugintruncate_message
Registrationbuilt-in dict, entry pointsPlugin SDK: manifest, dynamic loaderbuilt-in plus registry
LanguagePythonTypeScriptPython
What OpenClaw does
MechanismDetail
Layoutreferences/openclaw/src/channels/ holds fine-grained files; each platform has extensions/{name}/ (discord 70+ files, slack 40+, telegram 35+)
Plugin SDKsrc/plugin-sdk/channel-*.ts, 50+ contract files: ChannelMessageSendAdapter, ChannelMessageLiveAdapterShape, ChannelApprovalAdapter, ChannelMessageActionAdapter, ChannelOutboundAdapter
Streaming editdraft → live-preview (throttled) → final; throttling in the pipeline
Reaction approval✓/✗ reactions on dangerous tools, with timeout, retry, cancel (ack-reactions.ts, approval-native.ts)
Health checkStartup probe; one dead platform does not take down the worker
Registrationopenclaw.plugin.json manifests, core loader scans extensions/*/ or npm, lazy instantiation
What Hermes does
MechanismDetail
BaseBasePlatformAdapter (1500 lines), 14+ platforms, one file per adapter, async send, edit_message, send_draft, send_typing, create_handoff_thread
Session keyDM agent:main:{platform}:dm:{chat_id}[:{thread_id}]; group agent:main:{platform}:group:{chat_id}[:{thread_id}][:{user_id}]. Threads shared, groups per user, per-channel override.
Progress_edit_progress_message; _roll_progress_overflow_if_needed starts new bubbles past the platform limit
Debounce_queue_text_debounce merges consecutive texts into one turn: 0.35 s, cap 1.0 s
Quick commands/stop, /new, /reset, /approve bypass the session queue
Attachment cachedoc_{uuid12}_{name}; Telegram URLs downloaded before their one-hour expiry; cleanup after 24 h
DeliveryDeliveryRouter with DeliveryTarget (origin, local, telegram:123...), through adapters
Approval/approve sets an Event the tool thread waits on; reactions exist but are off the approval path
RegistrationPlatformEntry in platform_registry; built-ins take a hardcoded fast path

What is borrowed

TopicFrom OpenClawFrom Hermes
Method signatures, lifecycles, return structuresYes, more completeYes
StreamingThree-stateSingle edit
Approval lifecycleComplete/approve command
Health probeYes—
Code organizationNo: 50+ contracts and 70+ files per platform are overkillYes: one base file, one per platform
Why OpenClaw is not copied, and what is deferred
  • No Python to copy: OpenClaw is entirely TypeScript; its only .py files are CI and skill tooling. Reuse means re-implementing the design; TS interfaces map to Protocol/abc.ABC, dataclasses and plugin manifests carry across.
  • Static typing is what makes 50+ contract files pay off. Python Protocols are not enforced at runtime, and mypy is not on by default. So one file per interface is not worth it; the interface shapes are.
  • OpenClaw and Hermes are async-first; this layer is synchronous with one thread per adapter. Going async means turning dispatch_inbound into an async generator and rewiring four event loops.
  • Hermes's debounce merging, quick-command bypass and attachment caching came from production traffic and are deferred until those problems appear.

Implementation status

StateItems
In placeChannel ABC, MessageHandle, concrete send and edit; _transport shared by both entries and the only chunker; SendResult classification; ChannelMessage; entry-point registration; progress_stream=True; the _conversation.py split
Session isolationOne-dimensional: peer_id joins chat and user; session_scope is main, per-peer, per-channel-peer or per-account-channel-peer. Hermes's thread-shared mode is not expressible.
account_id passed twiceTo the adapter constructor and dispatch_inbound, which blocks one adapter serving several accounts in a process
Thread-scoped sessionsthread_id routes replies only
Startup probe, receiptsNot implemented
Last updated · 2026-11-25