Skip to content

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

Merge upstream/main into saas-channel-relay

Steven Enamakel9dcc2be6c679
diff --cc crates/openhuman-core/src/channels/providers/relay/README.md
index fe4cc4c609,0000000000..9fda6b42fb
mode 100644,000000..100644
--- a/crates/openhuman-core/src/channels/providers/relay/README.md
+++ b/crates/openhuman-core/src/channels/providers/relay/README.md
@@@ -1,76 -1,0 +1,76 @@@
+# Relay
+
+The hosted-channel relay. A gateway that owns a chat platform's webhook and account link relays each message into the core as the user it belongs to, and delivers the replies back to the platform. The core never talks to the platform itself.
+
+In SaaS the cloud gateway owns the hosted Telegram, iMessage and Discord webhooks and the account links (`openhuman_tinyhumans::hosted::channel_link`). The relay also works in a single-user core, for an embedder or a local relay: there the caller's config is the process's.
+
+## Contract
+
- `openhuman.channel_relay_inbound` (namespace `channel`, beside `channel_web_chat`), on the SaaS user surface (`user_agents::surface::USER_METHODS`):
++`openhuman.channel_relay_inbound` (namespace `channel`, beside `channel_web_chat`), on the SaaS user surface (`profiles::surface::USER_METHODS`):
+
+| Param | Rule |
+| --- | --- |
+| `channel` | Platform name, 1–32 chars of `[a-z0-9_-]`, starting with a letter. `web`, `cli` and `relay` are reserved. Any name in the charset is accepted, not only a fixed list of hosted platforms, so a gateway can add a platform without a core release; the name picks the platform's capabilities (`tinychannels_bus::capabilities_for`). |
+| `chat_id`, `sender_id`, `message_id` | 1–128 chars of printable ASCII, without spaces, `/`, `#` or `\`. Those characters structure the thread id, so refusing them keeps two chats from deriving the same thread. |
+| `sender_name` | Optional, at most 128 characters, no control characters. |
+| `text` | Not blank, at most 32 KiB. |
+| `client_id` | Optional `/events` client id for the replies, same rule as the ids; default `channel-relay`. |
+| `attachments` | Reserved. A non-empty list is refused, never silently dropped. |
+
+The answer comes at once: `{ accepted: true, thread_id, request_id, client_id }`. A `message_id` already recorded on its thread answers `{ accepted: false, duplicate: true, thread_id }` and runs nothing, so a gateway may retry a delivery.
+
+Each reply arrives on the caller's `GET /events?client_id=<client_id>` stream as:
+
+```json
+{
+ "event": "channel_outbound",
+ "client_id": "channel-relay",
+ "thread_id": "channel:telegram/555/777",
+ "request_id": "<from the ack>",
+ "full_response": "<reply text>",
+ "structured": {
+ "kind": "channel_outbound",
+ "channel": "telegram",
+ "chat_id": "777",
+ "thread_ts": null,
+ "reply_to_message_id": "tg-1",
+ "idempotency_key": "<per send>"
+ }
+}
+```
+
+Replies are final messages only: the relay sink takes no streaming drafts or reactions.
+
+## How a message runs
+
+1. `params.rs` validates the message and derives its thread with `channels::bus::derive_inbound_thread_id`: `channel:<channel>/<sender>/<chat>`, the same id as the backend-relayed inbound path. A user cannot create such a thread through `threads_upsert`, which reserves `channel:`.
+2. `store.rs` creates the thread in the workspace of the caller's config and appends the message (`user:<message_id>`). In a single-user core the process-wide channel persistence subscriber is told to skip this turn (`threads::store::claim_channel_turn`), so it is not mirrored under a second id; in SaaS that subscriber is not registered and the claim is a no-op.
+3. `ops.rs` builds a one-message `ChannelRuntimeContext` from the caller's config and policy (`channels::runtime::build_channel_turn_parts` with `PromptToolDescs::Registered`, then `runtime_context`): the caller's tools, model and workspace, never the process's channel runtime. The pipeline's per-chat history is seeded from the thread's earlier rows. The turn runs in the background under the caller's scope (`spawn_scoped`).
+4. `process_channel_message` runs it like any channel message: slash commands, approval replies, then the orchestrator over `agent.run_turn` under the `ExternalChannel` origin.
+5. `channel.rs`'s `RelayChannel` turns each send into a `channel_outbound` event. `publish_web_channel_event` stamps the publishing context's tenant (`profile`, `agent`), and `/events` filters on it, so only the caller's stream carries it.
+6. The texts sent are appended to the thread as one reply (`assistant:<message_id>`).
+
+## Files
+
+| File | Purpose |
+| --- | --- |
+| `mod.rs` | Module docs and re-exports |
+| `params.rs` | `RelayInboundParams`, limits, validation, thread id and title |
+| `channel.rs` | `RelayChannel`, the `Channel` sink that publishes `channel_outbound` |
+| `store.rs` | Recording the inbound message and the reply; history from the thread |
+| `ops.rs` | `channel_relay_inbound` and the turn runner |
+| `schemas.rs` | The `channel.relay_inbound` controller |
+
+Tests sit beside each file (`*_tests.rs`). `tests/saas_mode_e2e.rs::a_profile_holds_web_and_relayed_channel_threads` covers the SaaS path end to end.
+
+## Limits
+
+- Per-chat `/models` overrides set from a relayed chat last for that message only: the runtime context is rebuilt per message.
+- The tool registry and prompt are built per message.
+- In a single-user core with in-chat approvals, a parked approval is announced through the started channel runtime, which has no relay sink. In SaaS the gate never parks.
+- Native per-profile listeners (a user's own bot token) are not served here; see the SaaS profiles plan.
+
+## Further reading
+
+- [Providers](../README.md)
+- [Channels](../../README.md)
diff --cc crates/openhuman-core/src/channels/providers/relay/params_tests.rs
index 7ad215132c,0000000000..de0f68e8e1
mode 100644,000000..100644
--- a/crates/openhuman-core/src/channels/providers/relay/params_tests.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/params_tests.rs
@@@ -1,146 -1,0 +1,146 @@@
+use super::*;
+use serde_json::json;
+
+fn params() -> RelayInboundParams {
+ serde_json::from_value(json!({
+ "channel": "telegram",
+ "chat_id": "-100123",
+ "sender_id": "42",
+ "sender_name": "Ada",
+ "message_id": "m-1",
+ "text": "hello",
+ }))
+ .expect("params")
+}
+
+#[test]
+fn a_well_formed_message_is_accepted() {
+ let p = params();
+ p.validate().expect("valid");
+ assert_eq!(p.client_id(), DEFAULT_RELAY_CLIENT_ID);
+ assert_eq!(p.thread_title(), "telegram · Ada · -100123");
+}
+
+#[test]
+fn the_thread_id_is_a_reserved_channel_id() {
+ let p = params();
+ let id = p.thread_id();
+ assert_eq!(id, "channel:telegram/42/-100123");
+ assert_eq!(
+ id,
+ crate::channels::bus::derive_inbound_thread_id(
+ "telegram",
+ Some("42"),
+ Some("-100123"),
+ None
+ ),
+ "the backend-relayed inbound path's derivation"
+ );
+ assert!(
- crate::user_agents::surface::validate_user_thread_id(&id).is_err(),
++ crate::profiles::surface::validate_user_thread_id(&id).is_err(),
+ "a user cannot choose it"
+ );
+}
+
+#[test]
+fn distinct_chats_and_senders_get_distinct_threads() {
+ let base = params();
+ let mut other_chat = params();
+ other_chat.chat_id = "-100124".into();
+ let mut other_sender = params();
+ other_sender.sender_id = "43".into();
+ assert_ne!(base.thread_id(), other_chat.thread_id());
+ assert_ne!(base.thread_id(), other_sender.thread_id());
+}
+
+#[test]
+fn channel_names_are_lowercase_tokens() {
+ for ok in ["telegram", "imessage", "discord", "x", "a_b-1"] {
+ validate_channel(ok).unwrap_or_else(|e| panic!("{ok}: {e}"));
+ }
+ for bad in [
+ "",
+ "Telegram",
+ "1telegram",
+ "tele gram",
+ "telegram:bot",
+ "telegram/1",
+ "tg#1",
+ "télégram",
+ &"a".repeat(MAX_CHANNEL_LEN + 1),
+ ] {
+ assert!(validate_channel(bad).is_err(), "{bad:?}");
+ }
+ for reserved in RESERVED_CHANNELS {
+ assert!(validate_channel(reserved).is_err(), "{reserved}");
+ }
+}
+
+#[test]
+fn ids_cannot_forge_another_chats_thread() {
+ // `a/b` + `c` and `a` + `b/c` would derive the same thread id.
+ for bad in ["a/b", "a#thread:1", "a\\b", "has space", "", "tab\t"] {
+ assert!(validate_id("chat_id", bad).is_err(), "{bad:?}");
+ }
+ assert!(validate_id("chat_id", &"9".repeat(MAX_ID_LEN + 1)).is_err());
+ for ok in [
+ "-100123",
+ "+15551234567",
+ "iMessage;+;chat1",
+ ] {
+ validate_id("chat_id", ok).unwrap_or_else(|e| panic!("{ok}: {e}"));
+ }
+}
+
+/// A change that breaks one field of a valid message.
+type Mutation = Box<dyn Fn(&mut RelayInboundParams)>;
+
+#[test]
+fn every_field_is_checked() {
+ let cases: Vec<(&str, Mutation)> = vec![
+ ("channel", Box::new(|p| p.channel = "Web".into())),
+ ("chat_id", Box::new(|p| p.chat_id = "a/b".into())),
+ ("sender_id", Box::new(|p| p.sender_id = String::new())),
+ ("message_id", Box::new(|p| p.message_id = "x y".into())),
+ ("client_id", Box::new(|p| p.client_id = Some("c/1".into()))),
+ (
+ "sender_name",
+ Box::new(|p| p.sender_name = Some("a".repeat(MAX_SENDER_NAME_CHARS + 1))),
+ ),
+ (
+ "sender_name",
+ Box::new(|p| p.sender_name = Some("a\nb".into())),
+ ),
+ ("text", Box::new(|p| p.text = " ".into())),
+ (
+ "text",
+ Box::new(|p| p.text = "x".repeat(MAX_TEXT_BYTES + 1)),
+ ),
+ (
+ "attachments",
+ Box::new(|p| p.attachments = Some(vec![json!({"url": "https://x"})])),
+ ),
+ ];
+ for (field, mutate) in cases {
+ let mut p = params();
+ mutate(&mut p);
+ let err = p.validate().expect_err(field);
+ assert!(err.contains(field), "{field}: {err}");
+ }
+ let mut p = params();
+ p.attachments = Some(vec![]);
+ p.validate().expect("an empty attachment list is fine");
+}
+
+#[test]
+fn the_channel_message_carries_the_relayed_facts() {
+ let msg = params().to_channel_message();
+ assert_eq!(msg.channel, "telegram");
+ assert_eq!(msg.id, "m-1");
+ assert_eq!(msg.sender, "42");
+ assert_eq!(msg.reply_target, "-100123");
+ assert_eq!(msg.content, "hello");
+ assert_eq!(msg.sender_name.as_deref(), Some("Ada"));
+ assert!(msg.thread_ts.is_none());
+}
diff --cc crates/openhuman-core/src/core/runtime/saas.rs
index 1092f3bc4d,5a6a3a4c37..c1b100e6cd
--- a/crates/openhuman-core/src/core/runtime/saas.rs
+++ b/crates/openhuman-core/src/core/runtime/saas.rs
@@@ -289,15 -297,7 +297,15 @@@ pub async fn build
// Whoever initialised first won; refuse to serve users from a registry
// that holds anything but the built-ins.
verify_builtin_definitions(crate::agent::harness::AgentDefinitionRegistry::global())?;
+ // A relayed platform message (`channel_relay_inbound`) runs through the
+ // channel dispatch pipeline, which asks the native bus for an
+ // `agent.run_turn`. The `Agent` family stays off in SaaS (no agent RPCs
+ // on any surface), so its subscriber plan never registers that handler;
+ // register it alone. The request carries the caller's own turn parts, and
+ // the handler runs in the caller's (profile's) scope.
+ crate::agent::bus::register_agent_handlers();
+ log::debug!("[saas] registered the native agent.run_turn handler for relayed channel turns");
- let host = Arc::new(crate::user_agents::AgentHost::new(
+ let host = Arc::new(crate::profiles::ProfileHost::new(
config,
runtime.context().clone(),
));