Skip to content

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

feat(channels): add native runner dispatch for channel runtime

Steven Enamakele0aead761df2
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs b/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs
new file mode 100644
index 0000000000..ebe57024dd
--- /dev/null
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/native_runner.rs
@@ -0,0 +1,322 @@
+//! Native channel adapter for TinyAgents' shared turn lifecycle.
+
+use std::{collections::HashMap, sync::{Arc, Mutex}};
+
+use async_trait::async_trait;
+use tinyagents_harness::{
+ run_queue::RunQueue,
+ turn_runner::{
+ EventSink, FailureClassifier, IngressDecision, IngressPolicy, IngressStage,
+ QueueDisposition, ReplyStore, ScopeKey, Summarizer, TerminalEvent, TurnHost,
+ TurnRequest, TurnResult, TurnRunner, TurnRunnerConfig, TurnSession, TurnSignal,
+ },
+ CancellationToken,
+};
+use tokio::sync::mpsc;
+
+use crate::{
+ agent::{host_agents::HostAgent, queued_turn::QueuedPayload, session_lease::SessionLease},
+ channels::bus::NativeProgressiveReply,
+ core::runtime::DispatchCtx,
+};
+
+type Runner = TurnRunner<NativeHost, NativeIngress, NativeReplies, NativeEvents, NativeFailures, NativeSummarizer, QueuedPayload>;
+
+#[derive(Default)]
+struct NativeSlot {
+ lease: Option<SessionLease>,
+ reply: Option<String>,
+ progress_failed: bool,
+}
+
+#[derive(Default)]
+struct NativeShared {
+ slots: Mutex<HashMap<String, NativeSlot>>,
+}
+
+impl NativeShared {
+ fn with<R>(&self, request_id: &str, f: impl FnOnce(&mut NativeSlot) -> R) -> R {
+ let mut slots = self
+ .slots
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ f(slots.entry(request_id.to_owned()).or_default())
+ }
+
+ fn take_lease(&self, request_id: &str) -> Option<SessionLease> {
+ self.slots
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .get_mut(request_id)
+ .and_then(|slot| slot.lease.take())
+ }
+}
+
+struct NativeHost {
+ shared: Arc<NativeShared>,
+}
+
+#[async_trait]
+impl TurnHost<QueuedPayload> for NativeHost {
+ async fn checkout(&self, request: &TurnRequest<QueuedPayload>) -> Result<TurnSession, String> {
+ self.checkout_session(request, false).await
+ }
+
+ async fn checkout_fork(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ ) -> Result<TurnSession, String> {
+ self.checkout_session(request, true).await
+ }
+
+ fn run_origin(&self, request: &TurnRequest<QueuedPayload>) -> serde_json::Value {
+ let Some(trusted) = request.payload.trusted_turn.as_ref() else {
+ return serde_json::Value::Null;
+ };
+ match &trusted.origin {
+ crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ channel,
+ sender,
+ reply_target,
+ message_id,
+ ..
+ } => serde_json::json!({
+ "kind": "external_channel",
+ "channel": channel,
+ "sender": sender,
+ "reply_target": reply_target,
+ "message_id": message_id,
+ }),
+ _ => serde_json::json!({"kind": "trusted_host_turn"}),
+ }
+ }
+
+ async fn run(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ session: &TurnSession,
+ _origin: &serde_json::Value,
+ cancellation: CancellationToken,
+ queue: Arc<RunQueue<TurnRequest<QueuedPayload>>>,
+ progress: mpsc::Sender<TurnSignal>,
+ ) -> Result<TurnResult, String> {
+ let trusted = request
+ .payload
+ .trusted_turn
+ .as_ref()
+ .ok_or_else(|| "channel turn has no trusted host context".to_owned())?;
+ let (agent_progress, mut progress_rx) = mpsc::channel(64);
+ let progress_forwarder = tokio::spawn(async move {
+ while let Some(event) = progress_rx.recv().await {
+ if progress
+ .send(TurnSignal::Progress(Box::new(event)))
+ .await
+ .is_err()
+ {
+ break;
+ }
+ }
+ });
+ let response = crate::channels::runtime::dispatch::host_agent::run_host_agent_turn(
+ trusted.host_agent.clone(),
+ crate::channels::runtime::dispatch::host_agent::HostChannelTurn {
+ relay_thread: trusted.relay_thread.clone(),
+ channel: trusted.channel.clone(),
+ session_key: session.session_id.clone(),
+ event_session_id: trusted.event_session_id.clone(),
+ message: request.text.clone(),
+ origin: trusted.origin.clone(),
+ progress: Some(agent_progress),
+ run_queue: Some(queue),
+ approval: trusted.approval.clone(),
+ cancellation,
+ turn_deadline: None,
+ imported_history: trusted.imported_history.clone(),
+ },
+ )
+ .await
+ .map_err(|error| error.to_string());
+ let _ = progress_forwarder.await;
+ response.map(|response| TurnResult {
+ reply: response.text,
+ data: serde_json::json!({
+ "provider": response.resolved_provider,
+ "model": response.resolved_model,
+ }),
+ })
+ }
+
+ async fn checkin(&self, _request: &TurnRequest<QueuedPayload>) {}
+
+ async fn cancel_children(&self, _request: &TurnRequest<QueuedPayload>) {}
+}
+
+impl NativeHost {
+ async fn checkout_session(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ fork: bool,
+ ) -> Result<TurnSession, String> {
+ let trusted = request
+ .payload
+ .trusted_turn
+ .as_ref()
+ .ok_or_else(|| "channel turn has no trusted host context".to_owned())?;
+ let dispatch = request
+ .payload
+ .ctx
+ .as_ref()
+ .ok_or_else(|| "channel turn has no core context".to_owned())?;
+ let tenant = dispatch.tenant().map_err(|error| error.to_string())?;
+ let tenant_scope = crate::core::runtime::tenant::tenant_key(&tenant, "");
+ let session_id = if fork {
+ format!("{}:parallel:{}", trusted.session_key, request.request_id)
+ } else {
+ trusted.session_key.clone()
+ };
+ let lease = SessionLease::acquire(
+ crate::agent::session_lease::SessionLeaseKey::new(
+ tenant_scope,
+ trusted.host_agent.definition.id.clone(),
+ session_id.clone(),
+ ),
+ None,
+ )
+ .await
+ .map_err(|()| "channel session lease was cancelled".to_owned())?;
+ self.shared.with(&request.request_id, |slot| slot.lease = Some(lease));
+ Ok(TurnSession {
+ session_id,
+ fingerprint: None,
+ })
+ }
+}
+
+struct NativeIngress;
+
+#[async_trait]
+impl IngressPolicy<QueuedPayload> for NativeIngress {
+ async fn apply(
+ &self,
+ _stage: IngressStage,
+ _request: &mut TurnRequest<QueuedPayload>,
+ ) -> Result<IngressDecision, String> {
+ Ok(IngressDecision::Continue)
+ }
+}
+
+struct NativeReplies {
+ shared: Arc<NativeShared>,
+}
+
+#[async_trait]
+impl ReplyStore<QueuedPayload> for NativeReplies {
+ async fn persist(
+ &self,
+ request: &TurnRequest<QueuedPayload>,
+ _reply_id: &str,
+ result: &TurnResult,
+ ) -> Result<(), String> {
+ self.shared
+ .with(&request.request_id, |slot| slot.reply = Some(result.reply.clone()));
+ Ok(())
+ }
+}
+
+struct NativeEvents {
+ shared: Arc<NativeShared>,
+}
+
+#[async_trait]
+impl EventSink<QueuedPayload> for NativeEvents {
+ async fn progress(&self, request: &TurnRequest<QueuedPayload>, event: tinyagents_harness::progress::AgentProgress) {
+ let Some(reply) = request
+ .payload
+ .trusted_turn
+ .as_ref()
+ .and_then(|trusted| trusted.native_reply.as_ref())
+ else {
+ return;
+ };
+ let Some(event) = super::processor::progressive::output_event(event) else {
+ return;
+ };
+ match reply.feed(vec![event]).await {
+ Ok(result) if super::processor::progressive::delivery_succeeded(&result) => {}
+ Ok(_) | Err(_) => self.shared.with(&request.request_id, |slot| slot.progress_failed = true),
+ }
+ }
+
+ async fn terminal(&self, _request: &TurnRequest<QueuedPayload>, _event: TerminalEvent) {}
+}
+
+struct NativeFailures;
+
+impl FailureClassifier for NativeFailures {
+ fn classify(&self, error: &str) -> (String, String) {
+ let classified = crate::web_chat::classify_inference_error(error);
+ (classified.error_type.to_owned(), classified.message)
+ }
+}
+
+struct NativeSummarizer;
+
+#[async_trait]
+impl Summarizer<QueuedPayload> for NativeSummarizer {}
+
+struct NativeRuntime {
+ shared: Arc<NativeShared>,
+ runner: Arc<Runner>,
+}
+
+impl Default for NativeRuntime {
+ fn default() -> Self {
+ let shared = Arc::new(NativeShared::default());
+ let runner = Arc::new(TurnRunner::new(
+ Arc::new(NativeHost {
+ shared: shared.clone(),
+ }),
+ Arc::new(NativeIngress),
+ Arc::new(NativeReplies {
+ shared: shared.clone(),
+ }),
+ Arc::new(NativeEvents {
+ shared: shared.clone(),
+ }),
+ Arc::new(NativeFailures),
+ Arc::new(NativeSummarizer),
+ TurnRunnerConfig::default(),
+ ));
+ Self { shared, runner }
+ }
+}
+
+pub(crate) struct NativeTurnExecution {
+ pub(crate) result: Result<TurnResult, String>,
+ pub(crate) lease: Option<SessionLease>,
+ pub(crate) progress_failed: bool,
+}
+
+pub(crate) async fn run(
+ dispatch: &DispatchCtx,
+ mut request: TurnRequest<QueuedPayload>,
+) -> NativeTurnExecution {
+ let runtime = crate::core::runtime::slot_for::<NativeRuntime>(dispatch);
+ let request_id = request.request_id.clone();
+ if request.payload.ctx.is_none() {
+ request.payload.ctx = Some(dispatch.clone());
+ }
+ let result = runtime.runner.run(request).await.map_err(|error| error.to_string());
+ let slot = runtime
+ .shared
+ .slots
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .remove(&request_id)
+ .unwrap_or_default();
+ NativeTurnExecution {
+ result,
+ lease: slot.lease,
+ progress_failed: slot.progress_failed,
+ }
+}