Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore: files changed crates/openhuman-core/src/channels/README.md,crates/openhuman-core/src/channels

Steven Enamakel53c01fb9a5c4
diff --git a/crates/openhuman-core/src/channels/README.md b/crates/openhuman-core/src/channels/README.md
index 0b2fadf169..b5b1791615 100644
--- a/crates/openhuman-core/src/channels/README.md
+++ b/crates/openhuman-core/src/channels/README.md
@@ -1,177 +1,56 @@
-# channels
-
-This domain connects OpenHuman to external messaging platforms: Slack, Discord, Telegram, WhatsApp (Cloud API and, behind a feature, WhatsApp Web), IRC, Signal, iMessage, Email, Lark, Mattermost, DingTalk, QQ, Linq, Yuanbao, and the local CLI REPL. A message that arrives on one of those platforms is turned into an agent turn, and the agent's reply is sent back to the same chat. The domain also owns the `channels.*` RPC namespace the settings UI uses to connect and test providers, and the subscriber that delivers proactive messages (briefings, cron output) to the user's chosen channel.
-
-Most provider code is not here. Transports, provider construction, capability flags, remote-control commands, in-chat approval rendering and progressive reply choreography live in the vendored `tinychannels` crate ([`vendor/tinychannels/`](../../../../vendor/tinychannels/)). This folder is the host side: it supplies credentials, the agent, approvals, voice, persistence and events, and decides policy.
-
-## How it works
-
-There are two inbound paths. They look similar but run in different places.
-
-### Path 1: native listeners (`start_channels`)
-
-When the user has connected at least one listening integration, the core spawns the channel runtime. `spawn_channels_service` in [`core/runtime/services.rs`](../core/runtime/services.rs) captures the current channel session token, loads the config, checks `channels_config.has_listening_integrations()`, and calls `start_channels_with_session`. Setting `OPENHUMAN_DISABLE_CHANNEL_LISTENERS=1` skips the whole thing.
-
-[`runtime/startup/start_channels.rs`](./runtime/startup/start_channels.rs) then does the boot work in this order:
-
-1. Initialises the event bus and registers the subscribers a messaging core needs (health, thread persistence, Composio triggers, the web-chat surface subscribers, task sources) plus the native `agent.run_turn` handler. That handler must exist before the dispatch loop starts, because every inbound message is answered through it.
-2. Resolves the chat model (`resolve_chat_workload` in `startup/chat_workload.rs` picks the managed cloud model or the user's per-workload provider), installs the live `SecurityPolicy`, builds the tool registry, and loads skills.
-3. Builds the system prompt as a `ChannelSystemPrompt::refreshing` (see "System prompt" below). The fixed suffix is the XML tool-instruction block plus an advisory "Host access" section rendered by `startup/prompt.rs`.
-4. Builds the `ChannelHost` capability surface (`host::build_channel_host`) and calls `tinychannels::build_channels` with a credential-hydrated config (`hydrate_channel_credentials` in `startup/credentials.rs` fills the email password and Yuanbao app secret from the keyring) and `RuntimeProxyClients` (the configured HTTP proxy).
-5. Optionally connects the relay WebSocket runtime (`startup/relay.rs`) when `channels_config.relay` is configured.
-6. Spawns one supervised listener per provider ([`runtime/supervision.rs`](./runtime/supervision.rs)), registers the cron delivery subscriber, the cron channel bridge, the proactive subscriber, and the turn-state and approval-surface subscribers from [`host/channel_events.rs`](./host/channel_events.rs).
-7. Runs the dispatch loop until the session is cancelled.
-
-```text
- provider listener (one per channel, supervised, backoff + jitter)
- | ChannelMessage relay websocket (optional)
- v | RuntimeChannelMessage
- mpsc(100) --> bridge task --> mpsc(100) <+
- |
- v
- run_message_dispatch_loop
- (bounded by compute_max_in_flight_messages)
- |
- v one worker per message
- process_channel_runtime_message (processor/turn.rs)
- 1. publish ChannelMessageReceived
- 2. slash command? --> routes.rs, stop
- 3. yes/no for a parked approval? --> ApprovalGate, stop
- 4. typing indicator, ACK reaction
- 5. history = system prompt + per-sender history + msg
- 6. resolve_target_agent ("orchestrator") + tool scope
- 7. BUS.native().request("agent.run_turn", ...)
- inside ApprovalChatContext when chat_approvals
- 8. draft updates / final reply on the channel
- 9. publish ChannelMessageProcessed
-```
-
-Per-sender history is kept in memory in `ChannelRuntimeContext` ([`context.rs`](./context.rs)), keyed by `conversation_history_key` (channel, sender, reply target, thread). When a turn fails with a context-window overflow, the processor compacts that sender's history and asks the user to resend. Turns have a timeout (`message_timeout_secs`). Channel turns do no per-turn memory recall or autosave: memory reaches a session through `context.md`, injected by the session host, and committed turns are ingested from the `ConversationTurnCommitted` event.
-
-A channel can instead be bound to a host-registered agent with `config.agent.channel_agents` (channel name to agent id): `runtime/dispatch/host_agent/` then builds that agent's session and runs the turn as it, under the channel's `ExternalChannel` origin capped at read-only, and refuses the message when the bound agent is missing. See [runtime/README.md](runtime/README.md#channels-bound-to-a-host-agent).
-
-The listener supervisor reports through `OpenHumanListenerObserver`, which publishes `DomainEvent::ChannelConnected`, `ChannelDisconnected` and `HealthRestarted`. The full runtime walk-through, including account lifetime and logout, is in [runtime/README.md](runtime/README.md).
-
-### Path 2: backend-relayed inbound (`ChannelInboundSubscriber`)
-
-The desktop app usually has no native listeners. Messages for hosted bots arrive over the backend socket instead: [`platform/socket/event_handlers.rs`](../platform/socket/event_handlers.rs) publishes `DomainEvent::ChannelInboundMessage`. `bus::ChannelInboundSubscriber` ([`bus/subscriber.rs`](./bus/subscriber.rs)) handles it. It is registered on the always-on boot path by `register_domain_subscribers` in [`core/runtime/subscribers.rs`](../core/runtime/subscribers.rs), not by `start_channels`, so it works on a core that never starts listeners.
-
-The subscriber obtains the existing thread and client identifiers through confidential `PrepareChannelIdentity`, opens a private module runtime, starts a turn through `web_chat::start_chat`, and projects ordered turn events in bounded batches. `ExecuteProgressive` owns drafts, typing refreshes, filler bubbles, idempotency and final delivery inside the module. The callback in [`bus/delivery.rs`](./bus/delivery.rs) supplies managed REST transport with the credential and channel captured for that turn. Typed backend errors become transport facts that the module uses for recovery. Sign-out cancels the captured transport; close retains the callback until the module acknowledges shutdown.
-
-```text
- backend socket --> DomainEvent::ChannelInboundMessage
- |
- PrepareChannelIdentity --> web_chat::start_chat
- |
- ordered turn event batches --> ExecuteProgressive(handle)
- |
- captured managed callback --> backend REST
-```
-
-### Path 3: gateway-relayed inbound (`channel_relay_inbound`)
-
-A gateway that owns a hosted platform's webhook (the SaaS cloud gateway for Telegram, iMessage and Discord) relays each message in as its user with `openhuman.channel_relay_inbound` ([`providers/relay/`](./providers/relay/README.md)). The message is recorded on the caller's `channel:<channel>/<sender>/<chat>` thread (`derive_inbound_thread_id`), then runs through the Path 1 pipeline (`process_channel_message`, `ExternalChannel` origin) with a runtime context built from the caller's own config. Replies go to `RelayChannel`, which publishes them as `channel_outbound` events on the caller's `/events` stream for the gateway to deliver, and are recorded on the thread.
-
-### Outbound: proactive messages
-
-[`proactive.rs`](./proactive.rs) subscribes to `DomainEvent::ProactiveMessageRequested`. Every proactive message goes to the web channel (`web_chat::publish_web_channel_event`). If the user has set an active external channel and that channel is in the started channel map, it is sent there too. The always-on boot registers a web-only variant (`register_web_only_proactive_subscriber`); the full runtime registers one with the real channel map and publishes its active-channel handle, so `channels.set_default` (through `set_runtime_active_channel`) takes effect without a restart.
-
-### Slash commands and remote control
-
-[`routes.rs`](./routes.rs) intercepts messages starting with `/` before any turn runs. Portable commands (`/models`, `/providers` and the per-sender route override they set) come from `tinychannels::routes`. On providers with the `remote_control` capability, `/status`, `/sessions`, `/new` and `/help` are parsed and executed by `tinychannels::remote`, with [`host/remote_control.rs`](./host/remote_control.rs) (`RuntimeRemoteControl`) answering from the runtime context, the thread store and the web-chat session cache.
-
-### In-chat approvals
-
-When a tool call needs approval on a channel whose provider has `chat_approvals`, three pieces cooperate. The dispatch loop runs the turn inside an `ApprovalChatContext` whose thread id is the history key. `ChannelApprovalSurfaceSubscriber` (`host/channel_events.rs`) turns `ApprovalRequested` events into a prompt in that chat through `tinychannels::approvals::ApprovalSurface`. When the user replies yes or no, `try_route_approval_reply` ([`runtime/dispatch/processor/approval.rs`](./runtime/dispatch/processor/approval.rs)) hands it to `ApprovalGate::decide` instead of starting a new turn. Any other text runs as a fresh turn, which cancels the parked call. Providers without the capability (email, CLI, webhooks) keep the "no chat context, allow" behaviour, since a prompt there would only time out.
-
-### System prompt
-
-[`system_prompt.rs`](./system_prompt.rs) owns when the prompt is rendered, not its text. `ChannelSystemPrompt` has two variants. `Fixed` is a literal used by tests. `Refreshing` keeps the render inputs (`ChannelPromptInputs`: tool descriptions, skills, model, the fixed suffix) and re-renders only when the identity fingerprint changes. The fingerprint is a hash of `(mtime, len)` for the workspace-root `SOUL.md` and `IDENTITY.md`, so a steady-state message costs two `stat` calls and gets the same `Arc<String>` back, which keeps the provider prefix cache warm. The render itself is `build_system_prompt_with_identity` from [`agent/context/channels_prompt.rs`](../agent/context/channels_prompt.rs), with the project context (identity files) placed after the tool schemas and access block.
+# Channels
+
+This domain owns OpenHuman's channel configuration, RPC surface, account
+policy, and agent-turn integration. Provider transports and construction live
+in the TinyChannels module, which OpenHuman loads through TinyBus. The host
+does not build provider implementations or fall back to local listeners when
+the module is unavailable.
+
+## Native runtime
+
+[`runtime/`](./runtime/README.md) opens an identity-scoped module lease for
+configured native listeners and an optional gateway relay. Before dispatch,
+the host asks the module to prepare effective timeout and concurrency limits.
+The host supplies typed callbacks for host-owned operations such as voice,
+allowlist persistence, event publication, and remote-control access. The
+module owns provider-specific startup, supervision, transport, and interaction
+behavior; OpenHuman owns routing, approvals, agent execution, and the session
+cancellation lifetime.
+
+The normal provider type and provider re-exports are available only to tests
+that retain legacy compatibility fixtures. Production code uses the portable
+TinyChannels bus contracts from `tinychannels-bus` and the module client.
+
+## Hosted and relay paths
+
+Hosted-channel messages arrive through the backend socket and are handled by
+[`bus/subscriber.rs`](./bus/subscriber.rs). The host prepares the caller identity and opens a
+private module runtime for progressive delivery. The module owns drafts,
+typing, retries, and idempotent final delivery; the host callback provides the
+captured managed REST transport.
+
+Gateway-relayed inbound messages use [`providers/relay/`](./providers/relay/README.md).
+The host preserves authenticated relay provenance outside serialized message
+metadata, then runs the message through the same routing and agent policy as a
+native listener. Channel operations and relay delivery use typed module
+requests rather than a local provider implementation.
+
+## Host policy
+
+OpenHuman remains responsible for selecting the target agent, enforcing
+channel permissions, handling chat approvals, and applying the captured
+account/session lifetime. A missing module or malformed module response fails
+the affected operation with a sanitized error. There is no host-side provider
+or shell-based substitute.
## Layout
-| Path | What it does |
+| Path | Purpose |
| --- | --- |
-| [`mod.rs`](./mod.rs) | Module declarations, the feature-gate split, stable `channels::<provider>` paths and the public re-exports. |
-| [`traits.rs`](./traits.rs) | Ungated re-export of `Channel`, `ChannelMessage`, `ChannelSendExt`, `SendMessage` from `tinychannels-bus`. |
-| [`contract_schema.rs`](./contract_schema.rs) | Ungated conversion of `tinychannels-bus` controller schemas into core `ControllerSchema`s; shared with `openhuman-tinyhumans`. |
-| `providers/` | One-line re-exports of each provider module from `tinychannels::providers`. See [providers/README.md](providers/README.md) for the provider table and how to add one. |
-| `host/` | The OpenHuman implementation of the `tinychannels::host` boundary: `build_channel_host` and its adapters (`adapters.rs`), the approval-surface and turn-state subscribers (`channel_events.rs`), and the remote-control host (`remote_control.rs`). |
-| `runtime/` | Startup, listener supervision, the account-lifetime session, and the dispatch pipeline. See [runtime/README.md](runtime/README.md). |
-| `controllers/` | The `channels.*` RPC namespace and `OpenHumanChannelBackend`. See [controllers/README.md](controllers/README.md). |
-| [`bus.rs`](./bus.rs), `bus/` | `ChannelInboundSubscriber` (`subscriber.rs`), the captured managed transport (`delivery.rs`), and the inbound thread-id re-export (`thread_id.rs`). |
-| `context.rs` | `ChannelRuntimeContext`, per-sender history maps, history compaction, and timeout/backoff constants re-exported from `tinychannels::context`. |
-| `routes.rs` | Slash-command parsing and per-sender route selection (provider and model overrides). |
-| `proactive.rs` | `ProactiveMessageSubscriber` and the active-channel handle. |
-| `system_prompt.rs` | `ChannelSystemPrompt`, `ChannelPromptInputs`, identity fingerprinting. |
-| [`commands.rs`](./commands.rs) | `doctor_channels`: builds channels from the hydrated config and prints `tinychannels::runtime::check_channels_health` results. |
-| `tests/` | Cross-channel integration suite (see Tests). |
-
-## Key types and entry points
-
-- `start_channels` / `start_channels_with_session` (`runtime/startup/start_channels.rs`) boot the native runtime. The `_with_session` form takes a `CancellationToken` captured before config loading, which is what `spawn_channels_service` uses.
-- `session::channel_session` and `session::invalidate_channel_session` ([`runtime/session.rs`](./runtime/session.rs)) hold the process's single `tinychannels::runtime::ChannelSession`. Logout calls `invalidate_channel_session` from [`security/credentials/ops/credential.rs`](../security/credentials/ops/credential.rs), which cancels the running runtime and everything it owns.
-- `ChannelRuntimeContext` (`context.rs`) is the shared state every dispatch worker reads: channel map, tools, prompt, model, histories, route overrides, timeouts, and the full `Config` in production.
-- `process_channel_runtime_message` and `run_message_dispatch_loop` ([`runtime/dispatch/processor/`](./runtime/dispatch/processor/)) are the per-message pipeline and its bounded loop.
-- `resolve_target_agent` ([`runtime/dispatch/routing.rs`](./runtime/dispatch/routing.rs)) routes every channel turn to the `orchestrator` agent and builds its visible tool set, falling back to `AgentScoping::unscoped()` when the registry or definition is missing.
-- `build_channel_host` ([`host/mod.rs`](./host/mod.rs)) assembles the `ChannelHost` from `CoreShutdownRegistry`, `VoiceTranscriber`, `VoiceSynthesizer`, `CoreApprovalGate`, `ConversationHistoryStore`, `OpenHumanEventSink` and `ConfigAllowlistStore`. Reactions, turn dispatch, the run ledger and pairing are left unset.
-- `ChannelInboundSubscriber` (`bus/subscriber.rs`) is the backend-relayed inbound path.
-- `ProactiveMessageSubscriber` (`proactive.rs`) is outbound proactive delivery.
-- `ChannelSystemPrompt` (`system_prompt.rs`) is the seed prompt for every turn.
-- `OpenHumanChannelBackend` ([`controllers/backend.rs`](./controllers/backend.rs)) implements `tinychannels::ChannelBackend` for the RPC handlers.
-- `ChannelDefinition` and `ChannelAuthMode` are re-exported from `tinychannels::controllers` (through [`controllers/definitions.rs`](./controllers/definitions.rs)) for declarative provider metadata.
-- `build_system_prompt` is a re-export of `agent::context::channels_prompt::build_system_prompt`.
-
-## RPC / CLI surface
-
-The `channels` namespace is registered from `controllers::all_channels_registered_controllers()` in [`core/all.rs`](../core/all.rs), under `DomainGroup::Channels` and behind the `channels` feature. Schemas come from the `tinychannels-bus` contract.
-
-- Provider metadata: `channels.list`, `channels.describe`.
-- Connection lifecycle: `channels.connect`, `channels.disconnect` (optionally forgetting the channel's stored conversations), `channels.status`, `channels.test`.
-- Default channel for proactive delivery: `channels.set_default`, `channels.get_default`.
-- Discord: `channels.discord_list_guilds`, `channels.discord_list_channels`, `channels.discord_check_permissions`.
-- Messaging through the backend: `channels.send_message`, `channels.send_reaction`, `channels.create_thread`, `channels.update_thread`, `channels.list_threads`.
-
-The managed-bot link methods `channels.telegram_login_start`, `telegram_login_check`, `discord_link_start` and `discord_link_check` are part of the contract but are not registered here. They are listed in `HOSTED_CHANNEL_FUNCTIONS` ([`controllers/schemas.rs`](./controllers/schemas.rs)) and served by `openhuman-tinyhumans` (`hosted/channel_link/`), which converts their schemas with `channels::contract_schema::contract_controller_schema`.
-
-The in-app web chat (RPC namespace `channel`, singular) is a separate domain in `web_chat/`.
-
-## Boundaries
-
-- Provider transports, provider construction (`tinychannels::build_channels`), `ChannelManager`/`ChannelBackend`, per-provider `ChannelCapabilities`, remote-control commands (`tinychannels::remote`), approval prompts (`tinychannels::approvals`), progressive delivery, the relay transport, connect-form parsing and health checks all belong to `tinychannels` (`vendor/tinychannels/`, repo `tinyhumansai/tinychannels`). The transport-free trait and type contract is [`vendor/tinychannels/crates/tinychannels-bus`](../../../../vendor/tinychannels/crates/tinychannels-bus/). Fix provider bugs there, not with a host-side branch on a channel name; add a capability flag upstream instead.
-- The channel system prompt text is in `agent/context/channels_prompt.rs`.
-- The agent turn itself is run by the `agent.run_turn` native handler registered by `agent::bus::register_agent_handlers`. The dispatch code never imports the harness directly.
-- Credential storage is [`security/credentials/`](../security/credentials/) (`AuthService`); the approval gate and `ApprovalChatContext` are [`security/approval/`](../security/approval/).
-- Config schema types come from `tinychannels_bus::config` through [`config/schema/channels.rs`](../config/schema/channels.rs).
-- Conversation memory ingestion and `forget_channel` are in `memory/conversations/`.
-- Backend REST calls go through `backend::BackendClient`; Telegram and Discord link flows that need a TinyHumans account live in `openhuman-tinyhumans`.
-- Discord bot guild/channel discovery and permission checks call the released TinyChannels module through the confidential `ChannelController` member. The host resolves stored credentials and proxy scope, and the bus contract preserves the existing RPC response fields.
-- `channels.test` delegates field validation and email IMAP verification to the same confidential controller member. It never persists credentials or configuration, and an unavailable module fails the test instead of reporting local validation as success.
-- Speech-to-text and text-to-speech are the `voice/` domain, reached through the `host/` adapters.
-- Web-chat turns, the web-channel event stream, and the surface subscribers are `web_chat/`.
-- Cron delivery is [`cron/bus.rs`](../cron/bus.rs) (`CronDeliverySubscriber`) and [`cron/channel_bridge.rs`](../cron/channel_bridge.rs); `start_channels` hands them the started channel map.
-
-## Gotchas
-
-- The default `channels` feature gates provider orchestration and enables the module loader. Serialized config, messages, and controller declarations use the unconditional `tinychannels-bus` contract. Legacy provider traits and runtime helpers remain linked as explicit migration exceptions. The CLI REPL is host-owned orchestration. `WhatsAppWebChannel` additionally needs the `whatsapp-web` feature.
-- `start_channels` is skipped on cores with no listening integrations, which includes most desktop installs. Anything every core needs (the `ChannelInboundSubscriber`, the web-only proactive subscriber, tool-timeout seeding, self-improvement subscribers, the flows trigger subscriber) is registered in `core/runtime/subscribers.rs`, not in `start_channels`. Put new always-needed wiring there.
-- Several registrations in `start_channels` overlap with `bootstrap_core_runtime` (agent handlers, the agent definition registry). They are written to be idempotent; keep them that way.
-- The channel session token must be captured before the first `await` on config loading. Otherwise a logout during startup leaves a listener running for the old account.
-- The system prompt is frozen for the process except for the identity files. Tools, skills, model and security posture still need a restart to reach channel turns.
-- History keys include the sender and thread, not only the channel. Keying on the channel alone would merge different participants of a shared Slack or Discord channel into one session.
-
-## Tests
-
-Unit tests sit beside their modules as `*_tests.rs` files (for example [`bus_tests.rs`](./bus_tests.rs), [`routes_tests.rs`](./routes_tests.rs), [`host/host_tests.rs`](./host/host_tests.rs), [`controllers/ops_tests.rs`](./controllers/ops_tests.rs), [`runtime/startup_tests.rs`](./runtime/startup_tests.rs)). The cross-channel integration suite in `tests/` (declared as `#[cfg(all(feature = "channels", test))] mod tests` in `mod.rs`) covers end-to-end dispatch, tool calls, health restarts, prompt assembly, and the Discord and Telegram flows; its `mod.rs` describes each file. Behaviour owned by `tinychannels` is tested upstream.
-
-```bash
-cargo test -p openhuman channels::
-pnpm debug rust channels::
-```
-
-## Further reading
-
-- [Parent module README](../../README.md)
-- [Messaging channels](../../../../gitbooks/features/channels.md)
-- [Deep architecture reference](../../../../gitbooks/developing/architecture.md)
-- [tinychannels](../../../../vendor/tinychannels/README.md)
+| [`mod.rs`](./mod.rs) | Feature gates and the public channel contract exports. Concrete provider exports are test-only. |
+| [`traits.rs`](./traits.rs) | Portable message and send contracts re-exported from `tinychannels-bus`. |
+| [`controllers/`](./controllers/) | OpenHuman `channels.*` operations and host-side backend transport adaptation. |
+| [`host/`](./host/) | Typed module callbacks, event subscribers, and remote-control host operations. |
+| [`runtime/`](./runtime/README.md) | Module lease startup, account lifetime, and the OpenHuman dispatch pipeline. |
+| [`bus/`](./bus/) | Hosted-channel inbound and durable progressive delivery integration. |
+| [`providers/relay/`](./providers/relay/README.md) | Gateway relay RPC surface and host-side relay orchestration. |
diff --git a/crates/openhuman-core/src/channels/runtime/README.md b/crates/openhuman-core/src/channels/runtime/README.md
index b480cecb42..e9c017293c 100644
--- a/crates/openhuman-core/src/channels/runtime/README.md
+++ b/crates/openhuman-core/src/channels/runtime/README.md
@@ -1,60 +1,65 @@
-# Runtime
-
-Boots every enabled channel, keeps their listeners alive, and dispatches inbound messages into the agent loop. [`mod.rs`](./mod.rs) exports `start_channels` and a crate-internal startup entry with a captured session lifetime; `dispatch` and `supervision` internals are `pub(crate)` for [`channels/tests/`](../tests/) under `#[cfg(test)]`.
-
-## Files
-
-| Path | Purpose |
-| --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| [`startup.rs`](./startup.rs) (+ `startup/`: `start_channels.rs`, `credentials.rs`, `chat_workload.rs`, `prompt.rs`, `relay.rs`, `turn_parts.rs`) | `start_channels` builds the `channels::host` capability surface, hydrates secrets that live outside `config.toml` (`hydrate_channel_credentials`: email password, Yuanbao app secret, via `security::credentials::AuthService`), calls `tinychannels::build_channels`, registers the startup bus subscribers, spawns a supervised listener per channel and the optional relay runtime, then runs the dispatch loop. `turn_parts.rs` (`build_channel_turn_parts`, `runtime_context`) builds the model, tools, prompt and `ChannelRuntimeContext` from a config without installing any process-global state; `start_channels` and the hosted-channel relay (`providers/relay/`) share it |
-| [`supervision.rs`](./supervision.rs) | `spawn_supervised_listener` re-runs `Channel::listen` in a loop with exponential backoff plus full jitter, publishing `DomainEvent::ChannelConnected` / `ChannelDisconnected` / `HealthRestarted`; re-exports `tinychannels::runtime::compute_max_in_flight_messages` |
-| `dispatch/` | The inbound pipeline that turns a `RuntimeChannelMessage` into an agent turn and a reply |
-| [`test_support.rs`](./test_support.rs) | `#[cfg(any(test, debug_assertions))]` dispatch harness (`run_dispatch_harness`, `DispatchHarnessOptions`) used by `channels/tests/` and raw coverage |
-
-## Account lifetime
-
-Model authentication and account lifetime are separate. A local or CLI model can run without an OpenHuman backend session, but explicit logout cancels the old account's channel runtime. `spawn_channels_service` captures the channel lifetime before awaiting config loading, so logout also cancels a partially started runtime. [`session.rs`](./session.rs) holds the process's `tinychannels::runtime::ChannelSession` and stops the runtime on invalidation; owned listener/bridge tasks, dispatch workers, draft updaters, typing tasks, and relay reconnect supervision terminate when their owners drop. A runtime explicitly started again obtains a fresh lifetime; logout does not automatically start listeners for another account.
+# Channel runtime
+
+OpenHuman owns channel configuration, account lifetime, host policy, and the
+agent-turn pipeline. The TinyChannels module owns provider construction,
+listener supervision, relay transport, and channel-side interaction behavior.
+This directory adapts those two sides through the typed TinyBus contract.
+
+## Startup and ownership
+
+[`startup/start_channels.rs`](./startup/start_channels.rs) captures the
+session cancellation token, prepares the module runtime limits, hydrates
+credentials from the host credential store, and opens a private
+`ChannelRuntimeLease`. The module describes configured providers and starts
+listeners and the optional relay using the captured configuration. The host
+serves typed callbacks for operations it owns, including voice transcription,
+allowlist persistence, event publication, and remote-control access. A
+malformed or unavailable module response fails closed; there is no local
+provider-construction fallback.
+
+Startup registers host event subscribers before accepting inbound work. The
+dispatch queue is bounded, and its concurrency limit comes from the module's
+`PrepareChannelControl::RuntimeLimits` response. Session cancellation closes
+the lease, which asks the module to stop its resources before the host drops
+the captured callbacks.
## Inbound path
-1. Each provider listener (`spawn_supervised_listener`, one per channel from `tinychannels::build_channels`) sends `traits::ChannelMessage`s on a bounded `mpsc` (capacity 100). A bridge task in [`startup/start_channels.rs`](./startup/start_channels.rs) wraps each into `RuntimeChannelMessage` and forwards it to the dispatch queue (also capacity 100). The relay runtime (`start_relay_runtime`) writes `RuntimeChannelMessage`s to that queue directly so relay inbound keeps its original TinyChannels envelope.
-2. `run_message_dispatch_loop` ([`dispatch/processor.rs`](./dispatch/processor.rs), over `tinychannels::runtime::run_dispatch_loop`) drains the queue under a semaphore sized by `compute_max_in_flight_messages(listener_count)` and spawns a worker per message that calls `process_channel_runtime_message` (`processor/turn.rs`). `process_channel_message` is the `traits::ChannelMessage` wrapper for the same pipeline.
-3. `process_channel_runtime_message` publishes `DomainEvent::ChannelMessageReceived`, then: if `channel_has_approval_surface` and `try_route_approval_reply` claims the message as a yes/no answer to a parked approval, stops there; otherwise, when the channel is bound to a host agent (`agent.channel_agents`) whose agent no host answers for, replies `AGENT_UNAVAILABLE_REPLY` and stops there; otherwise starts typing, sends the ACK reaction (`select_acknowledgment_reaction`, threaded messages only), opens a streaming draft when the channel supports it, runs the turn (a channel bound to a host agent runs as that agent, `host_agent::run_host_agent_turn`, below; any other channel resolves scoping with `resolve_target_agent` + `build_visible_tool_set` and dispatches over `BUS.native()` to the `agent.run_turn` handler, `agent::bus::register_agent_handlers`, in `processor/bus_turn.rs`), sends the reply, and publishes `DomainEvent::ChannelMessageProcessed`.
+Native listener and gateway-relayed messages enter the same host dispatch
+pipeline. The host preserves authenticated relay provenance separately from
+serialized message data. It prepares inbound identity and policy facts through
+the module, then applies OpenHuman's routing, approval, and agent-turn policy.
+Replies and interactions are sent through the module's typed channel objects;
+the host does not reconstruct provider-specific outbound behavior.
-## `dispatch/`
+The always-on `ChannelInboundSubscriber` handles hosted-channel messages
+published by the backend socket. It prepares the caller's identity, opens a
+private module runtime, and executes progressive delivery against the captured
+backend callback. Drafts, typing refreshes, idempotency, and final delivery are
+owned by the module. The host callback supplies only the managed REST transport
+and credential captured for that turn.
-| Path | Purpose |
-| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `helpers.rs` | Stateless helpers: per-turn context block for non-web channels, deterministic ACK-emoji picker, worker join logging, scoped typing task |
-| `routing.rs` | `AgentScoping`, `resolve_target_agent`, `build_visible_tool_set`, `connected_with_fallback`: picks the active agent for the channel and its visible/delegation tool surface from `Config`, `AgentDefinitionRegistry`, and the connected-integrations snapshot |
-| `processor.rs` (+ `processor/`: `approval.rs`, `turn.rs`, `bus_turn.rs`) | `RuntimeChannelMessage` (re-exported from `tinychannels::runtime`), `channel_has_approval_surface`, `try_route_approval_reply`, `process_channel_message`, `process_channel_runtime_message`, `run_message_dispatch_loop`; `bus_turn.rs` is the orchestrator path over the bus |
-| `host_agent/` (`mod.rs`, `turn.rs`, `posture.rs`, `guard_tool.rs`) | Channels bound to a host-registered agent: `bound_agent_id`, `route` (`HostRoute::{Unbound, Agent, Missing}`), `refuse_missing_agent`, `run_host_agent_turn`, `seed_rows`, and the external-channel posture (`tool_ceiling`, `cap_channel`, `guard_host_tools`, `CeilingGuard`) |
-| `mod.rs` | Declares the three submodules and the `#[cfg(test)]` / `#[cfg(any(test, debug_assertions))]` re-exports the test modules reach through `super::*` |
-
-Two policy points here: `channel_has_approval_surface` follows the provider's `chat_approvals` capability (every chat provider; not email, the CLI or webhooks, which keep the "no chat context, silently allow" behaviour); and scoping is per channel (`resolve_target_agent(&msg.channel)`), falling back to `AgentScoping::unscoped()` (every registered tool visible) when the registry is not initialised or the target agent is unknown.
-
-## Channels bound to a host agent
-
-`config.agent.channel_agents` maps a channel name to an agent id (`telegram = "teeny-chat"`). It is keyed by channel name rather than set on each provider's config because those structs belong to `tinychannels`; which agent answers a channel is host policy. A message on a bound channel is resolved through `agent::host_agents` and runs as that `HostAgent`: its definition (system prompt, tool scope, iteration cap), its host tools, its config (provider model and route) and its `CoreContext` (`HostAgent::scope`). The channel keeps what it owns: the per-chat history in `conversation_histories` seeds the session (`seed_resume_from_messages`, transcript autoload suppressed, so no other chat's transcript is resumed), and typing, drafts (progress is wired with `set_on_progress`), the reply, history compaction on overflow and `ChannelMessageProcessed` work as for the orchestrator. The channel's `/models` route does not apply: the agent's own provider answers.
+## Account lifetime
-- **A missing agent is refused, never widened.** When the binding names an agent no host answers for (not created yet, or dropped), the message gets `AGENT_UNAVAILABLE_REPLY`, `ChannelMessageProcessed` records `success: false`, and an error is logged. It is not sent to the orchestrator, which holds the operator's full tool belt.
-- **The turn runs as `ExternalChannel`, capped at read-only.** The origin is passed down as a parameter (`run_single_with_origin`), not read from a task-local. `posture::tool_ceiling` maps it to `PermissionLevel::ReadOnly`, and the turn applies it twice. `cap_channel` sets `agent.channel_permissions[<channel>] = "readonly"` in the turn's config clone (never widening an operator's `none`), so the session's tool policy withholds every tool above read-only, built-in or host, and a call by name is refused at once. `guard_host_tools` wraps each host tool in a `CeilingGuard` that refuses, with a tool error, any call whose `permission_level_with_args` exceeds the ceiling or that has an external effect. It reports no external effect itself, so the approval gate never parks an approval that only the outside sender could answer.
-- An unbound channel takes the orchestrator path unchanged.
+Model authentication and channel account lifetime are separate. A local model
+can run without a backend session, while logout cancels the channel runtime
+captured for the old account. The session owner explicitly closes the runtime
+even when shared channel handles remain alive. Provider listeners, dispatch
+workers, typing refreshes, and relay tasks stop with their owning module
+resources.
-## Called by
+## Files
-`channels::start_channels` is re-exported from [`channels/mod.rs`](../mod.rs) and spawned by `spawn_channels_service` in [`crates/openhuman-core/src/core/runtime/services.rs`](../../core/runtime/services.rs), unless `OPENHUMAN_DISABLE_CHANNEL_LISTENERS` is set or `channels_config.has_listening_integrations()` is false. Web-chat-only desktop cores therefore never run it; `bus::ChannelInboundSubscriber` and the web-only proactive subscriber are registered on the always-on boot path in [`core/runtime/subscribers.rs`](../../core/runtime/subscribers.rs) instead.
+| Path | Purpose |
+| --- | --- |
+| [`startup.rs`](./startup.rs) and `startup/` | Captures configuration and callbacks, opens the module lease, prepares runtime limits, registers subscribers, and starts the dispatch loop. |
+| [`dispatch/`](./dispatch/) | Applies OpenHuman's inbound routing, approval, agent, and reply policy. |
+| [`session.rs`](./session.rs) | Tracks the process channel-session cancellation lifetime. |
+| [`test_support.rs`](./test_support.rs) | Test/debug dispatch harness; it does not provide a production provider fallback. |
## Tests
-- [`startup_tests.rs`](./startup_tests.rs), [`startup_email_secret_tests_tests.rs`](./startup_email_secret_tests_tests.rs), [`startup_yuanbao_secret_tests_tests.rs`](./startup_yuanbao_secret_tests_tests.rs) (secret hydration precedence).
-- [`supervision_tests.rs`](./supervision_tests.rs).
-- [`dispatch_tests.rs`](./dispatch_tests.rs) (helpers: ACK reaction categories, context block shape), [`dispatch/mod_scoping_tests_tests.rs`](./dispatch/mod_scoping_tests_tests.rs) (`build_visible_tool_set` / `AgentScoping`), [`dispatch/mod_approval_surface_gating_tests_tests.rs`](./dispatch/mod_approval_surface_gating_tests_tests.rs) (`channel_has_approval_surface`), [`dispatch/routing_connected_fallback_tests_tests.rs`](./dispatch/routing_connected_fallback_tests_tests.rs) (`connected_with_fallback`: authoritative snapshot vs cached fallback on unavailable/timeout).
-- `dispatch/host_agent/mod_tests.rs` (binding lookup, `seed_rows`), `posture_tests.rs` (ceiling, `cap_channel`, `CeilingGuard`), `dispatch_tests.rs` (a missing agent is refused without reaching the bus; an unbound channel still reaches the orchestrator; a bound channel runs its host agent against a mock provider with its prompt and read-only host tool, under the channel's origin, with the write tool withheld and refused). The embed crate's `tests/channel_agents.rs` covers the same path end to end through a mocked Telegram Bot API.
-- End-to-end dispatch coverage lives in `channels/tests/` (`runtime_dispatch`, `runtime_tool_calls`, `discord_integration`, `telegram_integration`, `health`).
-
-## Further reading
-
-- [Parent module README](../README.md)
-- [Messaging channels](../../../../../gitbooks/features/channels.md)
-- [tinychannels](../../../../../vendor/tinychannels/README.md)
+Startup and dispatch tests live beside their modules. `module_fixture_tests.rs`
+exercises the typed bus callbacks against an in-process TinyChannels module
+fixture. The separately maintained released-artifact fixture verifies the
+same public bus contract through the pinned module loader.