# Channel requirements and invariants

Structure and message flow: [Channel subsystem design](https://fzkuji.github.io/OpenProgram/docs/reference/design/channels/design.html).

## 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: ...
```

| Invariant | Reason |
| --- | --- |
| `run` is the only abstract method | Inbound 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 strings | Survives serialization: one process sends, another edits |
| Two entry points, one implementation | `outbound.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 `SendResult` | A 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 property | iLink 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 refused | `handle.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

| Step | Does |
| --- | --- |
| 1. Route | `session_aliases` and `bindings` decide `agent_id` |
| 2. Key | `session_key` per `agent.session_scope` |
| 3. Reset | `daily_reset` or `idle_minutes` |
| 4. Store | `_load_or_init_session` writes the session store |
| 5. Turn | `build_turn_request` makes the `TurnRequest`; `CanonicalAgentAdapter` admits and runs it |
| 6. Reply | Appended |
| 7. Broadcast | A `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

| Paradigm | Who drives | Entry |
| --- | --- | --- |
| A: agentic programming | Python control flow; `Agent` method makes a Context node; `Runtime.exec` asks the LLM only when called | Code written by the programmer |
| B: agent loop (channels, Web UI chat) | The LLM picks tools: `process_user_turn` → `agent_loop` → tool streaming | An external message |

| Deployment | Adapter instance |
| --- | --- |
| `openprogram` worker running | in the worker |
| Script importing an Agent method; job in a separate process; notebook; pytest | nowhere |

- 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.

| Aspect | OpenProgram | OpenClaw | Hermes |
| --- | --- | --- | --- |
| Abstract methods | 1 (`run`), concrete send and edit | 5+ (SendAdapter, LiveAdapter, ApprovalAdapter...) | 5+ (`send`, `edit`, `draft`, `typing`, `handoff`) |
| Neutral message | `ChannelMessage` | `ChannelMeta` with media, richtext, components | `MessageEvent`, `SessionSource` |
| Send result | `SendResult` (ok, message_id, error_kind, retryable, retry_after) | `DurableMessageSendResult` (message_id, edited_ids, retry policy) | `SendResult` (message_id, retryable) |
| Dispatch | sync → str, or `progress_stream=True` | async pipeline: draft → live → final | async streaming events |
| Session isolation | `session_scope`, 4 values | `dmScope`, thread-bindings-policy | chat × user × thread |
| Progress | dispatcher drives send and edit | three stages, throttled | `edit_message`, automatic overflow split |
| Approval | text bridge (`_question_commands.py`) | reaction ✓/✗, onApprove, onDecline, onTimeout | `/approve` text command |
| Debounce | none | unknown | 0.35 s delay, 1 s cap |
| Health check | none at startup; heartbeats feed status | `health-check-adapter.ts` | unknown |
| Receipts | none | yes | unknown |
| Structured replies | text only | embed, button, menu | partial |
| Attachments | state dir, vision input | cached | UUID prefix, 24 h cleanup |
| Outbound API | `outbound.send` shares `_transport` | through adapters | `DeliveryRouter(adapters: dict)` |
| Process model | lib, worker, script | single daemon | single gateway |
| Chunking | `_transport._chunk` | in the platform plugin | `truncate_message` |
| Registration | built-in dict, entry points | Plugin SDK: manifest, dynamic loader | built-in plus registry |
| Language | Python | TypeScript | Python |

**What OpenClaw does**

| Mechanism | Detail |
| --- | --- |
| Layout | `references/openclaw/src/channels/` holds fine-grained files; each platform has `extensions/{name}/` (discord 70+ files, slack 40+, telegram 35+) |
| Plugin SDK | `src/plugin-sdk/channel-*.ts`, 50+ contract files: `ChannelMessageSendAdapter`, `ChannelMessageLiveAdapterShape`, `ChannelApprovalAdapter`, `ChannelMessageActionAdapter`, `ChannelOutboundAdapter` |
| Streaming edit | draft → 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 check | Startup probe; one dead platform does not take down the worker |
| Registration | `openclaw.plugin.json` manifests, core loader scans `extensions/*/` or npm, lazy instantiation |

**What Hermes does**

| Mechanism | Detail |
| --- | --- |
| Base | `BasePlatformAdapter` (1500 lines), 14+ platforms, one file per adapter, async `send`, `edit_message`, `send_draft`, `send_typing`, `create_handoff_thread` |
| Session key | DM `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 cache | `doc_{uuid12}_{name}`; Telegram URLs downloaded before their one-hour expiry; cleanup after 24 h |
| Delivery | `DeliveryRouter` 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 |
| Registration | `PlatformEntry` in `platform_registry`; built-ins take a hardcoded fast path |

## What is borrowed

| Topic | From OpenClaw | From Hermes |
| --- | --- | --- |
| Method signatures, lifecycles, return structures | Yes, more complete | Yes |
| Streaming | Three-state | Single edit |
| Approval lifecycle | Complete | `/approve` command |
| Health probe | Yes | — |
| Code organization | No: 50+ contracts and 70+ files per platform are overkill | Yes: 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 `Protocol`s 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

| State | Items |
| --- | --- |
| In place | `Channel` 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 isolation | One-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 twice | To the adapter constructor and `dispatch_inbound`, which blocks one adapter serving several accounts in a process |
| Thread-scoped sessions | `thread_id` routes replies only |
| Startup probe, receipts | Not implemented |
