The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge the reconciled A3 (oh-embed-cron-resolver) into oh-embed-channels
Steven Enamakel62de5717e0c8
diff --cc crates/openhuman-core/src/channels/README.mdindex fcdea120ba,a60385292a..6cb9b38d04--- a/crates/openhuman-core/src/channels/README.md+++ b/crates/openhuman-core/src/channels/README.md@@@ -1,56 -1,159 +1,161 @@@- # Channels+ # channels- Multi-platform messaging integration. Re-exports the `Channel` trait vocabulary, owns the host glue for every provider (Slack, Discord, Telegram, WhatsApp, WhatsApp Web, IRC, Signal, iMessage, Email, Lark, Mattermost, DingTalk, QQ, Linq, Yuanbao, and the local CLI REPL), the runtime supervisor that brings channels online, inbound dispatch into the agent loop, and proactive outbound delivery. Does NOT own the channel system prompt copy (lives in `agent/context/channels_prompt.rs`; `system_prompt.rs` here owns only when it is re-rendered), per-channel credential storage (delegated to `security/credentials/`), or provider transport implementations (vendored in `tinychannels`; see below).+ 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.- ## Feature gate+ 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.- The domain lives behind the `channels` feature (default-ON, #4801), except two dependency-free carve-outs that always-on code reaches directly: `traits` (the `Channel`/`SendMessage` re-export, named by the always-on agent-harness interactive loop in `agent/session_host/`) and `CliChannel` (the stdin/stdout REPL that loop drives in every build, re-exported from the unconditional `tinychannels-runtime` crate). Everything else (`providers`, `host`, `controllers`, `runtime`, `bus`, `proactive`, `commands`, `context`, `routes`, `system_prompt`, the provider re-exports, `doctor_channels`, `start_channels`, `build_system_prompt` and the `test_support` re-export) is `#[cfg(feature = "channels")]`. The feature owns the optional `tinychannels` crate (`channels = ["dep:tinychannels", "tinychannels/email", "tinychannels/lark"]`); the always-on pins (config schema, the `DomainEvent` inbound envelope, security pairing) resolve through the unconditional `tinychannels-bus` contract crate instead. Measured, the gate sheds no transitive packages: its value is compile surface and binary size. `voice` also re-enables `dep:tinychannels`, for `EmailChannel` alone. The full rationale is the comment above the `channels` feature in `crates/openhuman-core/Cargo.toml`.+ ## How it works- ## Public surface+ There are two inbound paths. They look similar but run in different places.- - `pub use tinychannels_bus::{Channel, ChannelMessage, ChannelSendExt, SendMessage}` (`traits.rs`): the provider contract, sourced from the transport-free `tinychannels-bus` contract crate so it resolves even in `channels`-less builds.- - `ChannelDefinition` / `ChannelAuthMode` (re-exported from `tinychannels::controllers` through `controllers/definitions.rs` and `mod.rs`): declarative provider metadata.- - `pub fn start_channels` (`runtime/startup.rs`, re-exported from `mod.rs`): boots all enabled channels under the supervisor.- - `pub fn doctor_channels` (`commands.rs`): diagnoses connectivity for the doctor CLI.- - `pub fn build_system_prompt`: re-exported from `crate::agent::context::channels_prompt`.- - `pub(crate) enum ChannelSystemPrompt` (`system_prompt.rs`): the prompt a turn is seeded with, `fixed` (tests) or `refreshing` (production), which renders `build_system_prompt_with_identity` for the active agent definition.- - Per-provider channel structs re-exported from `providers/<name>.rs` (all thin `pub use tinychannels::providers::...` shims): `DingTalkChannel`, `DiscordChannel`, `EmailChannel`, `IMessageChannel`, `IrcChannel`, `LarkChannel`, `LinqChannel`, `MattermostChannel`, `QQChannel`, `SignalChannel`, `SlackChannel`, `TelegramChannel`, `WhatsAppChannel`, `YuanbaoChannel`. Cargo-feature-gated: `WhatsAppWebChannel` (`whatsapp-web`). `CliChannel` comes from `tinychannels-runtime` and is ungated.- - Stable `pub use providers::<name>` paths for every provider, in `mod.rs`.- - RPC `channels.{list, describe, connect, disconnect, status, set_default, get_default, test, telegram_login_start, telegram_login_check, discord_link_start, discord_link_check, discord_list_guilds, discord_list_channels, discord_check_permissions, send_message, send_reaction, create_thread, update_thread, list_threads}`, declared in `controllers/schemas.rs`.+ ### Path 1: native listeners (`start_channels`)- ## Submodule map+ 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.- | Path | Purpose |- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |- | `providers/` | Per-provider re-exports from `tinychannels` ([README](providers/README.md)) |- | `host/` | `build_channel_host`, the OpenHuman implementation of `tinychannels::host` that ported providers call back into (adapters in `host/adapters.rs`: `VoiceTranscriber`, `VoiceSynthesizer`, `CoreApprovalGate`, `ConversationHistoryStore`, `OpenHumanEventSink`, `CoreShutdownRegistry`, `ConfigAllowlistStore`); `host/remote_control.rs` (`RemoteControlHost` behind `/status`, `/sessions`, `/new`) and `host/channel_events.rs` (`ChannelApprovalSurfaceSubscriber`, `ChannelTurnStateSubscriber`), which give every capable provider in-chat approvals and remote control |- | `runtime/` | Startup, supervision, and the inbound dispatch loop into the agent ([README](runtime/README.md)) |- | `controllers/` | `channels.*` RPC namespace, `OpenHumanChannelBackend`, provider definitions ([README](controllers/README.md)) |- | `tests/` | Cross-channel integration test suite (`#[cfg(all(feature = "channels", test))]`) |+ [`runtime/startup/start_channels.rs`](./runtime/startup/start_channels.rs) then does the boot work in this order:- Flat files: `bus.rs` (`ChannelInboundSubscriber`, handles `DomainEvent::ChannelInboundMessage` published by the socket transport layer in `platform/socket/event_handlers.rs`; the progressive reply is `tinychannels::delivery::progressive::ProgressiveReply` over `bus/delivery.rs`'s `BackendProgressiveSender`, the REST relay transport; registered by `register_domain_subscribers` in `core/runtime/subscribers.rs`, not here), `commands.rs` (`doctor_channels`, printing `tinychannels::runtime::check_channels_health`), `context.rs` (`ChannelRuntimeContext`, per-sender conversation history, timeouts), `proactive.rs` (`ProactiveMessageSubscriber`, subscribes `DomainEvent::ProactiveMessageRequested` and delivers to the active channel), `routes.rs` (per-sender route overrides and runtime commands, including `tinychannels::remote` commands on providers with the `remote_control` capability), `system_prompt.rs`, `traits.rs` (ungated `Channel`/`SendMessage` re-export).+ 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.- ## Calls into+ ```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+ ```- - `crates/openhuman-core/src/agent/` — the agent turn is dispatched over `BUS.native()` to the `agent.run_turn` handler registered by `agent::bus::register_agent_handlers`, so `runtime/dispatch/` never imports the harness directly. The exception is a channel bound to a host-registered agent (`config.agent.channel_agents`, resolved through `agent::host_agents`): `runtime/dispatch/host_agent/` 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).- - `crates/openhuman-core/src/agent/context/channels_prompt.rs` — channel system prompt rendering, re-exported as `build_system_prompt`.- - `crates/openhuman-core/src/security/credentials/` — `AuthService` lookups for connect/disconnect and for secret hydration at startup (email password, Yuanbao app secret).- - `crates/openhuman-core/src/security/approval/` — `ApprovalGate` for the approval-reply intercept and `ApprovalChatContext` scoping of turns on every provider with the `chat_approvals` capability.- - `crates/openhuman-core/src/config/` — `Config` / `ChannelsConfig` (schema types come from `tinychannels_bus::config` via `config/schema/channels.rs`).- - `crates/openhuman-core/src/memory/conversations/` — memory v2 conversation ingestion (from the session host's `ConversationTurnCommitted` event; channel turns do no per-turn recall or autosave) and `forget_channel`, which `disconnect_channel` with `clear_memory` uses to forget a channel's `channel:<name>`-tagged conversations.- - `crates/openhuman-core/src/backend/client.rs` — `BackendClient` for controller messaging ops and Telegram/Discord link flows.- - `crates/openhuman-core/src/web_chat/` — web-channel event publishing, session invalidation (`/new`), and the web surface subscribers registered at startup.- - `crates/openhuman-core/src/voice/` — STT/TTS behind the `host/` adapters.- - `crates/openhuman-core/src/core/bus.rs` and `core/events.rs` — the process-wide `BUS` and the `DomainEvent::Channel*` variants published from `runtime/dispatch/` and `runtime/supervision.rs`.- - `vendor/tinychannels/` — provider transports, `tinychannels::build_channels` (provider construction), `ChannelManager`/`ChannelBackend`, the `tinychannels::host` capability boundary, progressive delivery (`delivery::progressive`), remote control (`remote`), in-chat approvals (`approvals`), the relay transport registry (`relay::runtime`), connect-form parsing, and per-provider `ChannelCapabilities`; `vendor/tinychannels/crates/tinychannels-bus` — the transport-free trait/type contract.+ 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.- ## Called by++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).+- - `crates/openhuman-core/src/core/all.rs`: registers `controllers::all_channels_registered_controllers()` under the `channels` feature gate.- - `crates/openhuman-core/src/core/runtime/services.rs`: `spawn_channels_service` calls `channels::start_channels(config)` unless `OPENHUMAN_DISABLE_CHANNEL_LISTENERS` is set or `has_listening_integrations()` is false.- - `crates/openhuman-core/src/core/runtime/subscribers.rs`: `bootstrap_core_runtime` subscribes `bus::ChannelInboundSubscriber` and calls `proactive::register_web_only_proactive_subscriber()`.- - `crates/openhuman-core/src/agent/session_host/`: the interactive loop drives the ungated `CliChannel`.- - `crates/openhuman-core/src/cron/bus.rs`: `CronDeliverySubscriber` is handed the started channel map by `runtime/startup.rs`; it names channels only through `tinychannels_bus`.+ 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 derives a thread id from (channel, sender, reply target, thread) with `derive_inbound_thread_id`, starts a turn through `web_chat::start_chat`, and watches the web-channel event stream for that request. The reply is shown progressively with `tinychannels::delivery::progressive::ProgressiveReply`: a draft that is edited as text streams in, typing refreshes, and filler bubbles on slow turns, then a finalize. The transport underneath is `BackendProgressiveSender` ([`bus/delivery.rs`](./bus/delivery.rs)), which sends through `BackendClient` with idempotency keys and maps typed `BackendApiError`s (`ChannelEditUnsupported`, `MessageNotFound`) to the recoveries the progressive driver expects.++ ```text+ backend socket --> DomainEvent::ChannelInboundMessage+ |+ v+ ChannelInboundSubscriber+ | web_chat::start_chat(thread_id, ...)+ v+ web channel events --> ProgressiveReply+ |+ v+ BackendProgressiveSender --> backend REST+ ```++ ### 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.++ ## Layout++ | Path | What it does |+ | --- | --- |+ | [`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 backend progressive sender (`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`.+ - 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 `channels` feature (default on; `channels = ["dep:tinychannels", "tinychannels/email", "tinychannels/lark"]` in [`crates/openhuman-core/Cargo.toml`](../../Cargo.toml)) gates almost everything. Three pieces stay ungated because always-on code names them: `traits` (the agent session host's interactive loop and `cron::bus`), `CliChannel` (re-exported from the unconditional `tinychannels-runtime` crate), and `contract_schema` (used by `openhuman-tinyhumans`). The config schema, the `DomainEvent` inbound envelope and security pairing resolve through `tinychannels-bus`, which is unconditional. The gate sheds no transitive packages; its value is compile surface and binary size. The `voice` feature also enables `dep:tinychannels` (for `EmailChannel` only), so a build without `channels` still links the crate unless `voice` is off too. `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.## Testsdiff --cc crates/openhuman-core/src/channels/runtime/README.mdindex e12dcd1517,b998a59737..12d94f7c86--- a/crates/openhuman-core/src/channels/runtime/README.md+++ b/crates/openhuman-core/src/channels/runtime/README.md@@@ -17,9 -17,9 +17,9 @@@ Model authentication and account lifeti## 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` 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`, 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, and 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 (`resolve_target_agent` + `build_visible_tool_set`) and dispatches the turn over `BUS.native()` to the `agent.run_turn` handler (`agent::bus::register_agent_handlers`, `processor/bus_turn.rs`). It then sends the reply, and publishes `DomainEvent::ChannelMessageProcessed`.+ 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 starts typing, sends the ACK reaction (`select_acknowledgment_reaction`, threaded messages only), opens a streaming draft when the channel supports it, resolves scoping (`resolve_target_agent` + `build_visible_tool_set`), dispatches the turn over `BUS.native()` to the `agent.run_turn` handler (`agent::bus::register_agent_handlers`), sends the reply, and publishes `DomainEvent::ChannelMessageProcessed`.++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`.## `dispatch/`@@@ -33,22 -32,19 +33,28 @@@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.++- **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.+## Called by- `channels::start_channels` is re-exported from `channels/mod.rs` and spawned by `spawn_channels_service` in `crates/openhuman-core/src/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` instead.+ `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.## Tests- - `startup_tests.rs`, `startup_email_secret_tests_tests.rs`, `startup_yuanbao_secret_tests_tests.rs` (secret hydration precedence).- - `supervision_tests.rs`.- - `dispatch_tests.rs` (helpers: ACK reaction categories, context block shape), `dispatch/mod_scoping_tests_tests.rs` (`build_visible_tool_set` / `AgentScoping`), `dispatch/mod_approval_surface_gating_tests_tests.rs` (`channel_has_approval_surface`), `dispatch/routing_connected_fallback_tests_tests.rs` (`connected_with_fallback`: authoritative snapshot vs cached fallback on unavailable/timeout).+ - [`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)diff --cc crates/openhuman-embed/README.mdindex 4e39733bd2,23e44bdc60..ee470bb524--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@@ -285,144 -372,241 +372,256 @@@ and stops it with the runtime; `start_sexplicitly. See [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md#scheduling)and `tests/cron_agents.rs`.+### Channels++`Runtime::channels().telegram(TelegramChannelSpec::new(token, agent_id))`+starts a Telegram listener whose every message is a turn of that runtime+agent: its prompt, its host tools and the chat's history. The agent must+exist first (`ChannelError::UnknownAgent` otherwise), and if it is dropped+later the bot answers that it is unavailable rather than falling back to the+orchestrator. Turns run as `ExternalChannel` and are capped at read-only:+tools that write or reach outside are withheld or refused at once. The+returned `ChannelListener` stops the bot when it is dropped. Behind the+`channels` feature (on by default). See the gitbook's "Channels" section and+`tests/channel_agents.rs`.+- ### Still runtime-wide-- These are read from the runtime's boot config by every agent today. They- are documented rather than hidden; each is a candidate follow-up in the core.+ ## Tools on an agent++ `AgentSpec::tools` gives an agent the host's own in-process tools, each with+ its own schema on the wire. The factory runs once per session build, which+ in practice is once per turn, and receives a `TurnContext` naming the agent+ and the session. `Agent::attach_tools` adds a permanent named tool source to+ an agent that already exists, which is how one library hands a configured+ agent to another. See [`src/agent/README.md`](src/agent/README.md).++ ## Layout++ | Path | What it does |+ | --- | --- |+ | [`src/lib.rs`](src/lib.rs) | Re-exports (core runtime types, `Tool`, `ToolGroups`, the backend port, `session_store`, `agent_progress`) and `Core`, the typed facade over a caller-built `CoreRuntime`. |+ | [`src/runtime/`](src/runtime/README.md) | `Runtime`, `RuntimeBuilder`, `ApiKey`, and the `CoreGuard` that owns process-scoped state until the last handle drops. |+ | [`src/agent/`](src/agent/README.md) | `Agent`, `AgentSpec`, `AgentDefinitionSpec`, `AgentLayout`, `MemoryBinding`, the build step, and permanent tool attachments. |+ | [`src/harness/`](src/harness/README.md) | `Harness` and `HarnessBuilder`, plus the shared input types: `Access`, `Provider`, `Workspace`, `McpServer`, skill copying, `HarnessError`. |+ | [`src/turn.rs`](src/turn.rs) | `Turn`, `TurnRequest`, `TurnOutcome`, `Route`: one turn, its ambient scopes, and its dispatch to an agent or to the orchestrator. |+ | [`src/call.rs`](src/call.rs) | The private typed dispatch helper over `CoreRuntime::invoke` that every facade method uses. |+ | [`src/config.rs`](src/config.rs), [`src/auth.rs`](src/auth.rs), [`src/core_agent.rs`](src/core_agent.rs) | The `Core` sub-facades: runtime flags, credentials (`Session`, `AuthState`), and the orchestrator turn. |+ | [`src/memory.rs`](src/memory.rs) | `Memory`, the per-tenant memory facade returned by `Runtime::memory`. |+ | [`src/process.rs`](src/process.rs), [`src/process_sentry.rs`](src/process_sentry.rs) | Host lifecycle helpers: the agent-sized tokio runtime, logging init, dotenv and launch overrides, the master key, and (`crash-reporting`) the Sentry `ClientOptions` with the single `before_send` chain. |+ | [`src/artifacts.rs`](src/artifacts.rs), [`src/chat_surface.rs`](src/chat_surface.rs), [`src/identity.rs`](src/identity.rs), [`src/modules.rs`](src/modules.rs) | Curated host facades: artifact file resolution, the in-process web-chat event stream, the signed-in identity peek, bundled module releases. `config` also carries `load_or_init`, `load_config_with_timeout`, `default_root_openhuman_dir`, `read_active_user_id`. |+ | [`src/host_internals.rs`](src/host_internals.rs) | `__host` (doc-hidden): an explicit list of core modules for `openhuman-tinyhumans` and `openhuman-rpc` only. |+ | [`src/error.rs`](src/error.rs) | `CoreError`, the error every facade call returns (`Domain`, `Unavailable`, `Rpc`, route refusals). |+ | [`examples/`](examples/README.md) | Runnable programs: one turn on a harness, and two agents on one runtime. |+ | [`tests/`](tests/README.md) | End-to-end suites against `wiremock` providers. |++ ## Key types and entry points++ - `Runtime` and `RuntimeBuilder` ([`src/runtime/`](src/runtime/)): build once per process,+ then call `Runtime::agent`. `Runtime::core()` gives non-turn access+ (config, auth) without exposing a way to start a turn.+ - `AgentSpec` ([`src/agent/spec.rs`](src/agent/spec.rs)): the pure-data description of an agent.+ Ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`.+ - `Agent` ([`src/agent/mod.rs`](src/agent/mod.rs)): a cheap clone handle. `run`, `turn`,+ `attach_tools`, and path accessors (`action_dir`, `home_dir`,+ `skills_dir`, `transcripts_dir`).+ - `Turn` and `TurnOutcome` ([`src/turn.rs`](src/turn.rs)): configure, then `send`.+ - `Access` ([`src/harness/access.rs`](src/harness/access.rs)): the autonomy tier and turn origin,+ always set together. Presets are `readonly`, `supervised` (the default)+ and `full`.+ - `Provider` ([`src/harness/provider.rs`](src/harness/provider.rs)): `openai_compatible(base_url, key)`+ plus `model`, or `inherit()` for the machine's configured inference.+ - `Workspace` ([`src/harness/workspace.rs`](src/harness/workspace.rs)): `Ephemeral` (default), `Dir`,+ `Stateless`, or `Inherit`.+ - `Harness` ([`src/harness/mod.rs`](src/harness/mod.rs)): one runtime, one agent.+ - `Core` ([`src/lib.rs`](src/lib.rs)): the typed facade over a caller-built runtime.++ ## One model call, no runtime: `Completer`++ A host that needs *a completion*, not an agent — a code reviewer asking for a+ JSON verdict, a classifier, an extractor — uses `complete::Completer`. It needs+ no `Runtime`, so none of the one-per-process and worker-stack constraints above+ apply, and any number of calls can run concurrently.- - `autonomy.auto_approve` / `auto_approve_all` and the memory guard's- autonomy tier come from the runtime's boot config (`security::live_policy`),- not the agent's. Path and command policy _do_ use the agent's own tier.- - The approval gate is on or off process-wide; parked approvals are not- labelled with the agent id. A per-agent "no approvals" is `Access::full()`,- whose `TrustedAutomation` origin the gate honours per turn.- - The sub-agent catalogue is runtime-wide (built-ins plus- `<workspace>/agents/*.toml`). Embedded agents cannot be `delegate_*`- targets of one another. Do not reuse built-in ids (`orchestrator`,- `summarizer`, …) for your agents.- - Sub-agents an agent spawns and the experience store re-read the runtime's- on-disk config rather than the agent's overlay. (The turn journal goes to- the agent's own stores under a host session store; without one it uses the- process-default workspace.)- - Sub-agent run-ledger rows, cron jobs and the cost log stay in the- workspace even with a host session store.- - Agents sharing a workspace share the dynamic (`mcp_registry_*`) MCP- registry; `[[mcp_client.servers]]` declared through `AgentSpec::mcp` are- per agent. The host-seeded documentation server is visible to every agent.- - `install_skill` / `create_skill` still write to `~/.openhuman`. With- `include_user_skills(false)` (the default) an agent does not _discover_ the- operator's skills, but an install by the agent lands there.- - One API key (or session) is shared by all agents.- - `IntegrationClient` (backend-proxied Composio/search/media tools) accepts- the runtime's TinyHumans API key or an app-session JWT through- `security::credentials::session_support::resolve_backend_credential`.- API keys use `x-api-key`; session JWTs use `Authorization: Bearer`.- With the backend transport installed and the integration feature and runtime- gates enabled, an API-key-only runtime can register integration tools.-- Other invariants worth knowing before wiring any entry point:+ ```rust,no_run+ # async fn demo() -> Result<(), openhuman_embed::CoreError> {+ use openhuman_embed::complete::{ChatMessage, CompletionRequest, Completer, ResponseFormat};+ use openhuman_embed::Route;++ let completer = Completer::new(Route::openai_compatible("https://openrouter.ai/api/v1", "sk-…"))+ .header("X-Title", "my-app");+ let response = completer+ .complete(+ CompletionRequest::new("openai/gpt-5-mini", vec![ChatMessage::user("Is 7 prime?")])+ .response_format(ResponseFormat::JsonObject)+ .max_tokens(64)+ .provider_options(serde_json::json!({"usage": {"include": true}})),+ )+ .await?;+ println!("{:?} {:?} {:?}", response.structured, response.finish_reason, response.usage);+ # Ok(())+ # }+ ```- - When building a `CoreRuntime` yourself, set `config_path` together with- `workspace_dir` (`CoreBuilder::workspace(dir)` does both). Credentials,- auth profiles and the keyring file resolve beside `config_path`, so a- workspace-only override reads the operator's real credentials. `Runtime`- and `Harness` set both for `Workspace::Ephemeral` and `Workspace::Dir`.- - A turn runs under the access tier _and_ the turn origin. `Access::full()`- sets both (`AutonomyLevel::Full` plus a `TrustedAutomation` origin);- `Access::readonly()` and `Access::supervised()` set no origin and leave the- approval gate on.- - Supply skills through `AgentSpec::skills_dir` / `HarnessBuilder::skills_dir`,- which copy the bundles. Skill discovery rejects symlinked bundles, so- linking them in does not work.+ It differs from an agent turn on purpose: no prompt-injection guard (callers+ pass untrusted text *as data*), no tools (a request declaring tools is+ refused), no session or orchestrator prompt, and no model fallback — the+ requested model is sent verbatim and `answered_model` reports what the+ provider says actually ran. `finish_reason`, token usage (cached and reasoning+ included) and the gateway-reported cost come back on the response; a+ `CompletionObserver` sees every call, success or failure, for trace export.- ## Feature flags+ `openhuman_embed::embeddings` re-exports the embedding models (OpenAI, Voyage,+ Cohere, Ollama, mock) for hosts that keep their own vector index, with the+ signature format unchanged so stored vectors stay in their partition.- Every feature on this crate is a pass-through to the same-named feature on- `openhuman-core` (package `openhuman`); `default` also turns on `channels`,- which core's default already enables: `default`, `http-server`,- `inference`, `documents`, `hosting`, `modules`, `voice`, `web3`,- `runtime-node`, `contacts`, `media`, `flows`, `skills`, `mcp`,- `crash-reporting`, `channels`,- `sandbox-bubblewrap`, `browser-native`, `whatsapp-web`,- `file-logging`, `scheduler-gate`.-- Three of them also gate items on this crate's own public surface:-- - `channels`: `Runtime::channels`, `Channels`, `TelegramChannelSpec`,- `ChannelListener`, `ChannelError` and `StreamMode`.- - `mcp`: `HttpHeader`, `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and- `HarnessBuilder::mcp`.- - `skills`: `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.-- See [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md)- for a measured minimal-footprint feature set, and- [`gitbooks/developing/performance.md`](../../gitbooks/developing/performance.md)- for the resulting binary sizes and per-agent memory numbers.+ ## Locked-down agents: `HostOnly`- ## Examples and tests+ An agent that reads untrusted input (a PR diff) and must never act takes+ `ToolScopeSpec::HostOnly`: the tools it can see and call are the ones the host+ supplies (`AgentSpec::tools`, `Agent::attach_tools`) and nothing else.- ```bash- # Against any OpenAI-compatible endpoint:- OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \- OPENHUMAN_EXAMPLE_API_KEY=sk-… \- OPENHUMAN_EXAMPLE_MODEL=gpt-5 \- cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"-- # Or against the machine's own configured inference, in its real workspace:- OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."+ ```rust,no_run+ use openhuman_embed::{AgentDefinitionSpec, AgentSpec, HostTurnTools, ToolScopeSpec};+ # fn read_only_tools() -> Vec<Box<dyn openhuman_embed::Tool>> { Vec::new() }+ let spec = AgentSpec::new("reviewer")+ .definition(+ AgentDefinitionSpec::new()+ .bare_prompt("You review pull requests.")+ .tools(ToolScopeSpec::HostOnly),+ )+ .tools(|_| HostTurnTools::advertised(read_only_tools()));```- Optional: `OPENHUMAN_EXAMPLE_BACKEND_URL` points non-inference backend calls- somewhere specific, and `OPENHUMAN_EXAMPLE_SKILLS_DIR` supplies skill bundles.+ - No config-derived tool is built and no delegation tool is synthesised, so+ shell, file writes, network, memory, skills, MCP and sub-agents do not exist+ for the model. A deny-by-default gate refuses any other name it calls anyway.+ - Access and sandbox are forced read-only, whatever `Access` was set (even+ after `AgentSpec::config`). Declaring MCP servers or skills is an error.+ - The agent needs its own prompt. `bare_prompt(text)` makes `text` the whole+ system prompt: no identity, safety, tools, workspace or memory section.++ Host tools should themselves be read-only: `HostOnly` bounds which tools+ exist, not what they do.++ Per turn, `Turn::response_format(ResponseFormat)` (the `complete` type) and+ `Turn::max_tokens(n)` apply to every call of the tool loop on any runtime-owned+ agent. `TurnOutcome` then carries `structured` (the reply parsed as JSON),+ `finish_reason`, `answered_model`, and `usage.reasoning_tokens`.+ `Turn::untrusted_input(true)` reads the message as data, so the prompt-injection+ guard and screen are skipped. It is accepted only on a `HostOnly` agent; any+ other agent refuses the turn (`untrusted_input_requires_host_only`).++ ## Feature flags++ Every feature is a pass-through to the same-named feature on+ `openhuman-core` (package `openhuman`): `default`, `http-server`, `inference`,+ `documents`, `hosting`, `modules`, `voice`, `web3`, `runtime-node`, `media`,+ `flows`, `skills`, `mcp`, `crash-reporting`, `channels`, `whatsapp-web`,+ `file-logging` and `scheduler-gate`. A gate added to the core has to be+ forwarded here (and then by `openhuman-tinyhumans` and `openhuman-cli`);+ [`scripts/ci/check-feature-forwarding.mjs`](../../scripts/ci/check-feature-forwarding.mjs) checks the chain.- Two agents on one runtime, either BYOK with the same variables as above, or- managed inference with `OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY`:-Two features also gate this crate's own surface. `mcp` adds `HttpHeader`,++Three features also gate this crate's own surface. `channels` adds `Runtime::channels`, `Channels`, `TelegramChannelSpec`, `ChannelListener`, `ChannelError` and `StreamMode`. `mcp` adds `HttpHeader`,+ `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`.+ `skills` adds `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.++ [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md) has a+ measured minimal feature set, and+ [`gitbooks/developing/performance.md`](../../gitbooks/developing/performance.md)+ has the resulting binary sizes and per-agent memory.++ ## Boundaries++ - The only in-repo dependency is `openhuman-core` with+ `default-features = false`. Every capability comes from a forwarded+ feature.+ - No JSON-RPC here. This crate does not depend on `openhuman-rpc`; `Outcome`+ and `StructuredRpcError` are core types. `openhuman-app` and+ `openhuman-tui` use `openhuman-rpc` and the core directly and do not use+ this crate.+ - No backend client. The hosted transport, product identity, login-token+ exchange and `/auth/me` live in `openhuman-tinyhumans`.+ - The agent loop, transcripts, session identity and tool-call parsing belong+ to [`vendor/tinyagents`](../../vendor/tinyagents/) (repo `tinyhumansai/tinyagents`); the `Tool` trait+ belongs to its nested `tinytools`. Use the `Tool` re-exported here: a+ separately added `tinytools` builds an incompatible type.+ - Memory contracts come from [`vendor/tinymemory`](../../vendor/tinymemory/) (`tinymemory-api`).++ ## Gotchas++ - One runtime per process. The keyring master key, the RPC bearer, the+ event bus and the `Once`-guarded domain subscribers are process-scoped+ (`CoreContext::init`). A second `RuntimeBuilder::build` returns+ `RuntimeError::AlreadyRunning`; a second harness returns+ `HarnessError::AlreadyRunning`. `Core::from_runtime` is not guarded, but+ the same rule applies to the `CoreRuntime` beneath it. The slot is+ released only when the `Runtime` and every `Agent` built on it are+ dropped.+ - Build the tokio runtime yourself. A turn is a deep async state machine,+ and a nested sub-agent overflows tokio's default 2 MiB worker stack, so+ `#[tokio::main]` is not enough. `embed::process` builds one sized for+ turns (`AGENT_WORKER_STACK_BYTES`, `MAX_BLOCKING_THREADS`, both re-exported+ there), so the host needs no core dependency to name them:++ ```rust,no_run+ let runtime = openhuman_embed::process::tokio_runtime().expect("tokio runtime");+ ```++ - Access has two halves. The autonomy tier drives `SecurityPolicy`, and the+ turn origin (a task-local) drives the approval gate. `Access::full()` sets+ both; setting only the tier through `config` gives an agent whose acting+ tools refuse while the transcript looks plausible. `readonly()` and+ `supervised()` set no origin and leave the approval gate on, so an+ unattended supervised agent stalls on approvals until they expire.+ - When building a `CoreRuntime` yourself, set `config_path` together with+ `workspace_dir` (`CoreBuilder::workspace(dir)` does both). Credentials,+ auth profiles and the keyring file resolve beside `config_path`, so a+ workspace-only override reads the operator's real credentials. `Runtime`+ and `Harness` handle this for `Ephemeral`, `Stateless` and `Dir`, and the+ `AgentSpec::config` escape hatch cannot move it.+ - Supply skills through `skills_dir`, which copies bundles. Skill discovery+ rejects symlinked bundles, so linking them in silently does nothing.+ - `Provider::model` is advisory. A model no provider serves falls back to+ the default rather than failing, and a route with no model resolved is+ ignored.+ - A `Route` (or `Provider::openai_compatible`) that pairs a key with a plain+ `http://` endpoint is refused before dispatch with+ `CoreError::InsecureRoute`. A route without a key is allowed.+ - A resumed session keeps its first system prompt and tool list. Prompt+ changes and a tool factory that returns a different belt only reach new+ sessions.++ ## Tests++ The integration suites under [`tests/`](tests/README.md) each build one+ runtime per process against `wiremock` providers; unit tests sit beside+ their modules as `*_tests.rs`.```bash- OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \- OPENHUMAN_EXAMPLE_API_KEY=sk-… \- OPENHUMAN_EXAMPLE_MODEL=gpt-5 \- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."-- # Or managed inference, no BYOK endpoint needed:- OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_… \- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."+ cargo test -p openhuman-embed --features inference,mcp,skills+ cargo test -p openhuman-embed --features inference,mcp,skills --test runtime_agents+ cargo test -p openhuman-embed --features inference,mcp,skills --test cron_agents++cargo test -p openhuman-embed --features inference,mcp,skills --test channel_agents```- The repository-root `examples/embed_headless.rs` (`DomainSet::harness()`,- `ServiceSet::none()`, RPC through `CoreRuntime::invoke`) and- `examples/embed_kernel.rs` (`DomainSet::kernel()`, then opt one family back- in) drive `CoreBuilder` from `openhuman_core` directly, without this crate;- they are `[[example]]` entries of the `openhuman` package, so run them with- `cargo run --example embed_headless`.-- `tests/harness_embed.rs` is the end-to-end proof that `Harness` runs a real- turn against a `wiremock` provider with nothing bound;- `tests/runtime_agents.rs` runs three agents with different providers, access- tiers, skills, MCP servers and working directories on one runtime and shows- the API key reaching a mocked managed backend as a bearer;- `tests/channel_agents.rs` drives a runtime agent from a mocked Telegram Bot- API: the bound agent answers with its prompt and read-only host tool under the- `ExternalChannel` origin, its write tool is withheld and refused, and the reply- is posted back to the chat.- `tests/cron_agents.rs` runs a cron job as a runtime agent with its host tool- under the `TrustedAutomation { Cron }` origin, records a system job handler's- error, and starts and stops the scheduler with the runtime;- `tests/public_api.rs` pins the host-facing embedding contract at compile- time. Run them with `cargo test -p openhuman-embed --features inference,mcp,skills`.++`tests/channel_agents.rs` drives a runtime agent from a mocked Telegram Bot API: the bound agent answers with its prompt and read-only host tool under the `ExternalChannel` origin, its write tool is withheld and refused, and the reply is posted back to the chat.+ `tests/cron_agents.rs` runs a cron job as a runtime agent with its host tool under the+ `TrustedAutomation { Cron }` origin, records a system job handler's error, and starts and+ stops the scheduler with the runtime.++ The repository-root [`examples/embed_headless.rs`](../../examples/embed_headless.rs) and [`examples/embed_kernel.rs`](../../examples/embed_kernel.rs)+ use this crate's `Runtime` (`Runtime::builder()`, then `core_runtime().invoke`+ for raw RPC methods). They are `[[example]]` targets of `openhuman-cli`:+ `cargo run -p openhuman-cli --example embed_headless`.++ ## Further reading++ - [`crates/openhuman-embed/examples/README.md`](examples/README.md): the examples module README.+ - [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md): embedding the core in another product.+ - [`gitbooks/developing/tinyhumans-api-key.md`](../../gitbooks/developing/tinyhumans-api-key.md): running on a TinyHumans API key.+ - [`gitbooks/developing/architecture.md`](../../gitbooks/developing/architecture.md): architecture overview.+ - [`gitbooks/developing/architecture/agent-harness.md`](../../gitbooks/developing/architecture/agent-harness.md): the agent harness.+ - [`gitbooks/developing/loadable-modules.md`](../../gitbooks/developing/loadable-modules.md): loadable modules.+ - [`crates/README.md`](../README.md): crates overview.## Relationship to other cratesdiff --cc crates/openhuman-embed/src/lib.rsindex 1a5d6079b2,b5454a46c3..c98edb4186--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@@ -85,17 -85,33 +85,35 @@@ pub mod agent_progress};}+ /// The skill registry: the host transport an embedder passes to+ /// `tinyskills::SkillRegistry::builder`, and the process registry the core+ /// itself serves catalog RPC and tools from.+ #[cfg(feature = "skills")]+ pub mod skill_registry {+ pub use openhuman_core::skills::catalog::{+ skill_registry, ReqwestTransport, HERMES_REGISTRY_ID,+ };+ }+mod agent;+ pub mod artifacts;mod auth;mod call;+#[cfg(feature = "channels")]+pub mod channels;- mod config;+ pub mod chat_surface;+ pub mod complete;+ pub mod config;mod core_agent;pub mod cron;+ pub mod embeddings;mod error;mod harness;+ pub mod identity;pub mod memory;+ #[cfg(feature = "modules")]+ pub mod modules;+ pub mod process;mod runtime;mod turn;