Skip to content

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

feat(channels): import relay history into the durable agent session

Steven Enamakel10ae9aed8a15
diff --git a/crates/openhuman-core/src/agent/host_agents.rs b/crates/openhuman-core/src/agent/host_agents.rs
index 0b5d0a05f1..20d3ec90f7 100644
--- a/crates/openhuman-core/src/agent/host_agents.rs
+++ b/crates/openhuman-core/src/agent/host_agents.rs
@@ -96,6 +96,7 @@ impl HostAgent {
progress: Option<tokio::sync::mpsc::Sender<tinyagents_harness::progress::AgentProgress>>,
cancellation: tinyagents_harness::CancellationToken,
turn_deadline: Option<std::time::Duration>,
+ imported_history: &[tinyagents_session::transcript::TranscriptMessage],
) -> anyhow::Result<String> {
let config = self.config.clone();
let agent_id = self.definition.id.clone();
@@ -113,6 +114,7 @@ impl HostAgent {
memory_identity: Some(crate::memory::scope::MemoryIdentity::root().child(&agent_id)),
..Default::default()
});
+ session.adopt_imported_history(imported_history)?;
self.scope(session.run_single_with_approval(message, Some(origin), approval))
.await
}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rs
index 13e5445f6f..dec20f8791 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/transcript.rs
@@ -30,7 +30,7 @@ impl OpenHumanSessionHost {
.clone()
}
- pub(super) fn runtime_transcript_meta(&self) -> TranscriptMeta {
+ pub(in crate::agent::session_host) fn runtime_transcript_meta(&self) -> TranscriptMeta {
let now = chrono::Utc::now().to_rfc3339();
TranscriptMeta {
agent_name: self.agent_definition_name.clone(),
diff --git a/crates/openhuman-core/src/agent/session_host/session_api.rs b/crates/openhuman-core/src/agent/session_host/session_api.rs
index 7ddb4b8257..13e631dc63 100644
--- a/crates/openhuman-core/src/agent/session_host/session_api.rs
+++ b/crates/openhuman-core/src/agent/session_host/session_api.rs
@@ -9,12 +9,30 @@
use anyhow::Result;
use tinyagents_runtime::{ResumeMode, TurnOptions};
+use tinyagents_session::transcript::TranscriptMessage;
use crate::agent::tinyagents::host::OpenHumanRunContext;
use super::OpenHumanSessionHost;
impl OpenHumanSessionHost {
+ /// Install imported conversation rows once, before the first turn binds
+ /// this durable session. Empty imports do not reserve a session, and a
+ /// transcript already written by a prior turn always wins unchanged.
+ pub(crate) fn adopt_imported_history(&self, messages: &[TranscriptMessage]) -> Result<bool> {
+ if messages.is_empty() {
+ return Ok(false);
+ }
+ let Some(session) = self.session.as_ref() else {
+ return Ok(false);
+ };
+ self.session_locator().adopt_messages_if_absent(
+ session,
+ self.runtime_transcript_meta(),
+ messages,
+ )
+ }
+
/// Load this session's durable history now, before any turn runs.
///
/// A turn resumes on its own, so this exists for hosts that want the
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index a1bbbf283b..70550794c3 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -3,15 +3,15 @@
use std::collections::HashMap;
use std::sync::Arc;
-use serde_json::{json, Value};
+use serde_json::{Value, json};
use super::channel::RelayChannel;
use super::params::RelayInboundParams;
use super::store::{self, Recorded};
use crate::channels::context::MAX_CHANNEL_HISTORY;
use crate::channels::runtime::{
- build_channel_turn_parts, prepare_runtime_limits, process_channel_runtime_message,
- runtime_context, PromptToolDescs,
+ PromptToolDescs, build_channel_turn_parts, prepare_runtime_limits,
+ process_channel_runtime_message, runtime_context,
};
use crate::config::Config;
use crate::core::Outcome;
@@ -199,8 +199,9 @@ pub(crate) async fn run_relay_turn(
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.
+ // The relay's legacy conversation rows are imported into the selected
+ // agent's durable session on its first resume. Subsequent calls are
+ // idempotent and existing session history remains authoritative.
let message = params.to_channel_message();
let prepared = match crate::modules::channel_controller::prepare_inbound(
&crate::modules::client(config.clone()),
@@ -221,7 +222,7 @@ pub(crate) async fn run_relay_turn(
return channel.sent();
}
};
- match store::prior_turns(
+ let imported_history = match store::prior_turns(
&dispatch_ctx,
&workspace_dir,
&thread_id,
@@ -230,19 +231,22 @@ pub(crate) async fn run_relay_turn(
)
.await
{
- Ok(prior) if !prior.is_empty() => {
- ctx.conversation_histories
- .lock()
- .unwrap_or_else(|e| e.into_inner())
- .insert(prepared.history_key.clone(), prior);
- }
- Ok(_) => {}
+ Ok(prior) => prior
+ .into_iter()
+ .map(|row| match row.role.as_str() {
+ "user" => tinyagents_session::transcript::TranscriptMessage::user(row.content),
+ "assistant" => {
+ tinyagents_session::transcript::TranscriptMessage::assistant(row.content)
+ }
+ _ => unreachable!("prior_turns only returns user and assistant rows"),
+ })
+ .collect(),
Err(error) => tracing::warn!(
thread_id = %thread_id,
%error,
"[channels::relay] could not read the thread's history; running without it"
),
- }
+ };
tracing::debug!(
channel = %params.channel,
@@ -252,6 +256,7 @@ pub(crate) async fn run_relay_turn(
);
let mut runtime_message = crate::channels::runtime::RuntimeChannelMessage::from(message);
runtime_message.prepared_inbound = Some(prepared);
+ runtime_message.imported_history = imported_history;
let turn = process_channel_runtime_message(ctx, runtime_message);
if let Some(context) = dispatch_ctx.core() {
crate::core::runtime::CoreContext::scope(
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 023f23a01c..0a75f76663 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
@@ -31,6 +31,8 @@ pub(crate) struct HostChannelTurn {
pub(crate) approval: crate::security::approval::ApprovalTurnContext,
pub(crate) cancellation: tinyagents_harness::CancellationToken,
pub(crate) turn_deadline: Option<std::time::Duration>,
+ /// Legacy SaaS relay history to adopt into the durable session once.
+ pub(crate) imported_history: Vec<tinyagents_session::transcript::TranscriptMessage>,
}
/// Run `turn` as `host`: its definition and host tools, inside its context,
@@ -50,6 +52,7 @@ pub(crate) async fn run_host_agent_turn(
approval,
cancellation,
turn_deadline,
+ imported_history,
} = turn;
let mut config = host.config.clone();
let profile_ceiling = host
@@ -90,6 +93,7 @@ pub(crate) async fn run_host_agent_turn(
progress,
cancellation,
turn_deadline,
+ &imported_history,
)
.await?;
Ok(AgentTurnResponse::with_resolved_route(
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
index 2f285869af..72185269eb 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor.rs
@@ -31,6 +31,7 @@ pub(crate) struct RuntimeChannelMessage {
pub(crate) inbound_envelope: Option<ChannelInboundEnvelope>,
pub(crate) authenticated_relay: bool,
pub(crate) prepared_inbound: Option<tinychannels_bus::module_inbound::PreparedChannelInbound>,
+ pub(crate) imported_history: Vec<tinyagents_session::transcript::TranscriptMessage>,
}
impl RuntimeChannelMessage {
@@ -43,6 +44,7 @@ impl RuntimeChannelMessage {
inbound_envelope: Some(inbound_envelope),
authenticated_relay: false,
prepared_inbound: None,
+ imported_history: Vec::new(),
}
}
@@ -56,6 +58,7 @@ impl RuntimeChannelMessage {
inbound_envelope: Some(delivery.envelope),
authenticated_relay: delivery.delivered_via_authenticated_relay,
prepared_inbound: None,
+ imported_history: Vec::new(),
}
}
}
@@ -67,6 +70,7 @@ impl From<ChannelMessage> for RuntimeChannelMessage {
inbound_envelope: None,
authenticated_relay: false,
prepared_inbound: None,
+ imported_history: Vec::new(),
}
}
}
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/bus_turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/bus_turn.rs
index dbf254e092..9f0ddb08b4 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/bus_turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/bus_turn.rs
@@ -1,7 +1,7 @@
//! The orchestrator path: an unbound channel's turn goes over the native bus
//! to the `agent.run_turn` handler, with the orchestrator's tool scoping.
-use crate::agent::bus::{AgentTurnRequest, AgentTurnResponse, AGENT_RUN_TURN_METHOD};
+use crate::agent::bus::{AGENT_RUN_TURN_METHOD, AgentTurnRequest, AgentTurnResponse};
use crate::agent::turn_origin::AgentTurnOrigin;
use crate::channels::context::{ChannelRouteSelection, ChannelRuntimeContext};
use crate::core::bus::BUS;
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 f3e3b6d703..c2cb7f1154 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs
@@ -45,6 +45,7 @@ pub(crate) async fn process_channel_runtime_message(
inbound_envelope,
authenticated_relay,
prepared_inbound,
+ imported_history,
} = runtime_msg;
let prepared = match prepared_inbound {
Some(prepared) => prepared,
@@ -454,6 +455,7 @@ pub(crate) async fn process_channel_runtime_message(
approval,
cancellation: cancellation.clone(),
turn_deadline: crate::agent::session_host::turn_backstop::configured_backstop(),
+ imported_history,
},
)),
None if configured_agent_error.is_some() => {
@@ -479,11 +481,9 @@ pub(crate) async fn process_channel_runtime_message(
))
}
#[cfg(not(test))]
- None => Box::pin(async {
- Err(anyhow::anyhow!(
- "channel turn has no configured host agent"
- ))
- }),
+ None => {
+ Box::pin(async { Err(anyhow::anyhow!("channel turn has no configured host agent")) })
+ }
};
let llm_result =
tokio::time::timeout(Duration::from_secs(ctx.message_timeout_secs), agent_call).await;