Skip to content

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

refactor(channels): carry relay thread on turn context

Steven Enamakel94d035d1c67a
diff --git a/crates/openhuman-core/src/channels/context.rs b/crates/openhuman-core/src/channels/context.rs
index 1e4c83b8ee..1ff6347ab2 100644
--- a/crates/openhuman-core/src/channels/context.rs
+++ b/crates/openhuman-core/src/channels/context.rs
@@ -30,6 +30,9 @@ pub(crate) type RouteSelectionMap = Arc<Mutex<HashMap<String, ChannelRouteSelect
#[derive(Clone)]
pub(crate) struct ChannelRuntimeContext {
+ /// Explicit durable conversation for a hosted relay; ordinary channels
+ /// use their existing per-sender history and have no relay thread.
+ pub(crate) relay_thread: Option<String>,
pub(crate) channels_by_name: Arc<HashMap<String, Arc<dyn super::Channel>>>,
/// Injected model source used only by tests and bespoke channel hosts.
/// Production contexts carry `config` and construct crate-native sources.
diff --git a/crates/openhuman-core/src/channels/context_tests.rs b/crates/openhuman-core/src/channels/context_tests.rs
index 4273a97214..58cf414ea1 100644
--- a/crates/openhuman-core/src/channels/context_tests.rs
+++ b/crates/openhuman-core/src/channels/context_tests.rs
@@ -25,11 +25,13 @@ impl Tool for DummyTool {
}
fn runtime_context() -> ChannelRuntimeContext {
+ relay_thread: None,
let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![
"ok",
]));
ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(HashMap::new()),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("default".into()),
diff --git a/crates/openhuman-core/src/channels/providers/relay/mod.rs b/crates/openhuman-core/src/channels/providers/relay/mod.rs
index 82cd3e1765..d41517d2b8 100644
--- a/crates/openhuman-core/src/channels/providers/relay/mod.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/mod.rs
@@ -33,14 +33,3 @@ pub use params::{
};
pub use schemas::{all_relay_controller_schemas, all_relay_registered_controllers};
-// The durable conversation key belongs to this inbound relay call, not a
-// process-global last sender. The dispatch future carries it to session build.
-tokio::task_local! { static RELAY_THREAD: String; }
-
-pub(crate) fn current_thread_id() -> Option<String> {
- RELAY_THREAD.try_with(Clone::clone).ok()
-}
-
-pub(crate) async fn with_thread<F: std::future::Future>(thread: String, future: F) -> F::Output {
- RELAY_THREAD.scope(thread, future).await
-}
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 43d5a83279..7deaacc5b2 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -128,7 +128,9 @@ pub(crate) async fn run_relay_turn(
let mut channels_by_name: HashMap<String, Arc<dyn crate::channels::Channel>> = HashMap::new();
channels_by_name.insert(params.channel.clone(), channel.clone());
- let ctx = Arc::new(runtime_context(&config, parts, Arc::new(channels_by_name)));
+ let mut runtime = runtime_context(&config, parts, Arc::new(channels_by_name));
+ runtime.relay_thread = Some(thread_id.clone());
+ let ctx = Arc::new(runtime);
// The thread is the conversation's memory: seed the pipeline's per-chat
// history from it, since this runtime context lives for one message.
@@ -161,7 +163,16 @@ pub(crate) async fn run_relay_turn(
request_id = %request_id,
"[channels::relay] dispatching relayed turn"
);
- super::with_thread(thread_id.clone(), process_channel_message(ctx, message)).await;
+ let turn = process_channel_message(ctx, message);
+ if let Some(context) = crate::core::runtime::CoreContext::scoped() {
+ crate::core::runtime::CoreContext::scope(
+ context.derive_channel_turn(Some(thread_id.clone()), None),
+ Box::pin(turn),
+ )
+ .await;
+ } else {
+ turn.await;
+ }
let replies = channel.sent();
record(&workspace_dir, &params, &thread_id, &replies).await;
diff --git a/crates/openhuman-core/src/channels/routes_tests.rs b/crates/openhuman-core/src/channels/routes_tests.rs
index ee158ecc0d..74deb402b9 100644
--- a/crates/openhuman-core/src/channels/routes_tests.rs
+++ b/crates/openhuman-core/src/channels/routes_tests.rs
@@ -54,11 +54,13 @@ impl Channel for RecordingChannel {
}
fn runtime_context(workspace_dir: PathBuf) -> ChannelRuntimeContext {
+ relay_thread: None,
let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![
"ok",
]));
ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(HashMap::new()),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("openai".into()),
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs
index 6bb1f945a1..4e28b785e7 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs
@@ -42,6 +42,7 @@ impl Channel for Telegram {
fn context(channel: Arc<Telegram>, config: Config) -> Arc<ChannelRuntimeContext> {
let channel: Arc<dyn Channel> = channel;
Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(HashMap::from([("telegram".to_string(), channel)])),
turn_model_source: None,
default_provider: Arc::new("test-provider".to_string()),
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
index b8fc9193fb..8fad6521ab 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
@@ -11,6 +11,8 @@ use tinyagents_session::transcript::TranscriptMessage;
/// One channel message, as a host agent's turn needs it.
pub(crate) struct HostChannelTurn {
+ /// Durable thread supplied explicitly by a hosted relay.
+ pub(crate) relay_thread: Option<String>,
/// The channel the message came in on (`"telegram"`).
pub(crate) channel: String,
/// The chat's history key: the session the host belt is told about and
@@ -35,6 +37,7 @@ pub(crate) async fn run_host_agent_turn(
turn: HostChannelTurn,
) -> anyhow::Result<AgentTurnResponse> {
let HostChannelTurn {
+ relay_thread,
channel,
history_key,
prior_turns,
@@ -68,7 +71,9 @@ pub(crate) async fn run_host_agent_turn(
"[channels::dispatch::host_agent] running channel turn as host agent"
);
- let relay_thread = crate::channels::providers::relay::current_thread_id();
+ host.context = host
+ .context
+ .derive_channel_turn(relay_thread.clone(), Some(origin.clone()));
let mut session = host.session_host(
&config,
Some(relay_thread.as_deref().unwrap_or(&history_key)),
@@ -88,10 +93,7 @@ pub(crate) async fn run_host_agent_turn(
session.set_on_progress(progress);
let text = host
- .scope(crate::agent::turn_origin::with_origin(
- origin.clone(),
- session.run_single_with_origin(&message, Some(origin)),
- ))
+ .scope(session.run_single_with_origin(&message, Some(origin)))
.await?;
Ok(AgentTurnResponse::with_resolved_route(
text,
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
index f6ed313e68..e76f4d3266 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -344,6 +344,7 @@ pub(crate) async fn process_channel_runtime_message(
Some(host) => Box::pin(run_host_agent_turn(
*host,
HostChannelTurn {
+ relay_thread: ctx.relay_thread.clone(),
channel: msg.channel.clone(),
history_key: history_key.clone(),
prior_turns: seed_rows(&history),
diff --git a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
index ea3452e1c2..244f3a54b0 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
@@ -233,7 +233,9 @@ pub(crate) fn runtime_context(
parts: ChannelTurnParts,
channels_by_name: Arc<HashMap<String, Arc<dyn crate::channels::Channel>>>,
) -> ChannelRuntimeContext {
+ relay_thread: None,
ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name,
turn_model_source: None,
default_provider: Arc::new(parts.provider_name),
diff --git a/crates/openhuman-core/src/channels/runtime/test_support.rs b/crates/openhuman-core/src/channels/runtime/test_support.rs
index be2248058c..4248471543 100644
--- a/crates/openhuman-core/src/channels/runtime/test_support.rs
+++ b/crates/openhuman-core/src/channels/runtime/test_support.rs
@@ -413,6 +413,7 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHa
.clone()
.unwrap_or_else(std::env::temp_dir);
let ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("harness-provider".to_string()),
diff --git a/crates/openhuman-core/src/channels/tests/discord_integration.rs b/crates/openhuman-core/src/channels/tests/discord_integration.rs
index ef5f47e3c0..738af9ff53 100644
--- a/crates/openhuman-core/src/channels/tests/discord_integration.rs
+++ b/crates/openhuman-core/src/channels/tests/discord_integration.rs
@@ -105,6 +105,7 @@ fn make_discord_ctx(
channels.insert(channel.name().to_string(), channel);
Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("test-provider".to_string()),
diff --git a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
index b991b62879..e5ba46a1be 100644
--- a/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_dispatch.rs
@@ -115,6 +115,7 @@ async fn message_dispatch_processes_messages_in_parallel() {
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(SlowModel {
@@ -189,6 +190,7 @@ async fn process_channel_message_cancels_scoped_typing_task() {
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(SlowModel {
@@ -277,6 +279,7 @@ async fn dispatch_routes_through_agent_run_turn_bus_handler() {
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
// Still need a model for the context field, but the stubbed bus
// handler never invokes it — so a minimal no-op is fine.
@@ -363,6 +366,7 @@ async fn channel_processed_event_records_resolved_agent_route() {
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(super::common::DummyModel),
@@ -475,6 +479,7 @@ async fn process_channel_message_hardens_multimodal_files_against_smuggled_marke
..Default::default()
};
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(super::common::DummyModel),
@@ -558,6 +563,7 @@ async fn process_channel_message_hardens_against_relative_path_markers() {
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(super::common::DummyModel),
diff --git a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
index 19f9164e8a..2ad327a9da 100644
--- a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
+++ b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs
@@ -24,6 +24,7 @@ async fn process_channel_message_executes_native_tool_calls() {
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(ToolCallingModel),
@@ -95,6 +96,7 @@ async fn process_channel_message_handles_models_command_without_llm_call() {
);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::clone(&default_provider),
@@ -195,6 +197,7 @@ async fn process_channel_message_uses_route_override_provider_and_model() {
);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::clone(&default_provider),
@@ -243,6 +246,7 @@ async fn process_channel_message_respects_configured_max_tool_iterations_above_d
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(IterativeToolModel {
@@ -301,6 +305,7 @@ async fn process_channel_message_reports_configured_max_tool_iterations_limit()
channels_by_name.insert(channel.name().to_string(), channel);
let runtime_ctx = Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels_by_name),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(
Arc::new(IterativeToolModel {
diff --git a/crates/openhuman-core/src/channels/tests/telegram_integration.rs b/crates/openhuman-core/src/channels/tests/telegram_integration.rs
index 9c7c764e32..df1285943b 100644
--- a/crates/openhuman-core/src/channels/tests/telegram_integration.rs
+++ b/crates/openhuman-core/src/channels/tests/telegram_integration.rs
@@ -81,6 +81,7 @@ fn make_test_context(
channels.insert(channel.name().to_string(), channel);
Arc::new(ChannelRuntimeContext {
+ relay_thread: None,
channels_by_name: Arc::new(channels),
turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),
default_provider: Arc::new("test-provider".to_string()),
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 69e668edba..a099b35988 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -103,6 +103,8 @@ pub struct CoreContext {
backend_transport: Option<Arc<dyn crate::backend::transport::BackendTransport>>,
/// Explicit authority on this derived turn context.
turn_origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
+ /// Durable relay conversation carried by the immutable turn context.
+ channel_thread: Option<String>,
/// The agent whose stores a host-installed session store
/// ([`crate::agent::session_store`]) hands out to work under this
/// context. `None` for booted contexts, which use the shared default.
@@ -270,6 +272,7 @@ impl CoreContext {
user_skill_roots: true,
backend_transport,
turn_origin: None,
+ channel_thread: None,
session_agent: None,
profile: None,
agent: Default::default(),
@@ -388,6 +391,7 @@ impl CoreContext {
user_skill_roots: overlay.user_skill_roots,
backend_transport: self.backend_transport.clone(),
turn_origin: self.turn_origin.clone(),
+ channel_thread: self.channel_thread.clone(),
session_agent: overlay.session_agent.or_else(|| self.session_agent.clone()),
profile: overlay.profile.or_else(|| self.profile.clone()),
agent,
@@ -542,6 +546,7 @@ impl CoreContext {
user_skill_roots: true,
backend_transport: None,
turn_origin: None,
+ channel_thread: None,
session_agent: None,
profile: None,
agent: Default::default(),
@@ -574,6 +579,7 @@ impl CoreContext {
user_skill_roots: true,
backend_transport: None,
turn_origin: None,
+ channel_thread: None,
session_agent: None,
profile: None,
agent: Default::default(),
diff --git a/crates/openhuman-core/src/core/runtime/context_for_agent.rs b/crates/openhuman-core/src/core/runtime/context_for_agent.rs
index 6a7f5aa7b4..9594319060 100644
--- a/crates/openhuman-core/src/core/runtime/context_for_agent.rs
+++ b/crates/openhuman-core/src/core/runtime/context_for_agent.rs
@@ -34,6 +34,7 @@ impl CoreContext {
user_skill_roots: self.user_skill_roots,
backend_transport: self.backend_transport.clone(),
turn_origin: self.turn_origin.clone(),
+ channel_thread: self.channel_thread.clone(),
session_agent: Some(agent.to_string()),
profile: self.profile.clone(),
agent: parts,
diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rs
index dc8a0710a3..4f9c57adb8 100644
--- a/crates/openhuman-core/src/core/runtime/context_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs
@@ -13,6 +13,7 @@ fn ctx(dir: &str) -> Arc<CoreContext> {
user_skill_roots: true,
backend_transport: None,
turn_origin: None,
+ channel_thread: None,
session_agent: None,
profile: None,
agent: Default::default(),
@@ -46,6 +47,7 @@ fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {
user_skill_roots: true,
backend_transport: None,
turn_origin: None,
+ channel_thread: None,
session_agent: None,
profile: None,
agent: Default::default(),
@@ -384,6 +386,7 @@ fn degraded_context_rejects_workspace_bound_stores() {
user_skill_roots: true,
backend_transport: None,
turn_origin: None,
+ channel_thread: None,
session_agent: None,
profile: None,
agent: Default::default(),
diff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
index 6428de0355..156e0191d3 100644
--- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
@@ -35,7 +35,25 @@ impl CoreContext {
origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
fut: F,
) -> F::Output {
- let context = Arc::new(CoreContext {
+ CURRENT_CONTEXT
+ .scope(ctx.derive_channel_turn(None, origin), fut)
+ .await
+ }
+
+ /// The relay thread of the current task, without an operator fallback.
+ pub(crate) fn current_channel_thread() -> Option<String> {
+ Self::scoped().and_then(|ctx| ctx.channel_thread.clone())
+ }
+
+ /// Bind channel facts to this agent context, preserving its tenant,
+ /// tools, workspace and capability ceiling. No shared context is mutated.
+ pub(crate) fn derive_channel_turn(
+ &self,
+ thread: Option<String>,
+ origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
+ ) -> Arc<CoreContext> {
+ let ctx = self;
+ Arc::new(CoreContext {
host_kind: ctx.host_kind,
workspace_binding: RwLock::new(
ctx.workspace_binding
@@ -49,10 +67,10 @@ impl CoreContext {
user_skill_roots: ctx.user_skill_roots,
backend_transport: ctx.backend_transport.clone(),
turn_origin: origin.or_else(|| ctx.turn_origin.clone()),
+ channel_thread: thread.or_else(|| ctx.channel_thread.clone()),
session_agent: ctx.session_agent.clone(),
profile: ctx.profile.clone(),
agent: ctx.agent.clone(),
- });
- CURRENT_CONTEXT.scope(context, fut).await
+ })
}
}