Skip to content

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

feat(embed): observe whole-turn deadlines and cancellation

Steven Enamakel18e9072346e3
diff --git a/crates/openhuman-embed/src/observe.rs b/crates/openhuman-embed/src/observe.rs
index 3ee5c2b0c0..b9e57b16e2 100644
--- a/crates/openhuman-embed/src/observe.rs
+++ b/crates/openhuman-embed/src/observe.rs
@@ -15,6 +15,14 @@ pub enum TurnFailure {
Provider,
/// Host domain rejected the turn.
Domain,
+ /// Locally refused structured output.
+ Structured,
+ /// Spending admission refused another physical call.
+ Budget,
+ /// Caller requested cancellation.
+ Cancelled,
+ /// Whole-turn deadline elapsed.
+ Deadline,
/// Other facade or configuration failure.
Other,
}
@@ -77,6 +85,10 @@ where
let failure = result.as_ref().err().map(|error| match error {
CoreError::Rpc { .. } => TurnFailure::Provider,
CoreError::Domain { .. } => TurnFailure::Domain,
+ CoreError::StructuredOutput { .. } => TurnFailure::Structured,
+ CoreError::BudgetExceeded { .. } => TurnFailure::Budget,
+ CoreError::Cancelled { .. } | CoreError::TurnCancelled { .. } => TurnFailure::Cancelled,
+ CoreError::DeadlineExceeded { .. } => TurnFailure::Deadline,
_ => TurnFailure::Other,
});
observer.on_turn(&TurnTrace {
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index b7a270d6cd..5117d95c17 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -264,6 +264,8 @@ pub struct Turn {
untrusted_input: bool,
cancellation: Option<crate::TurnCancellation>,
timeout: Option<std::time::Duration>,
+ observer: Option<Arc<dyn crate::observe::TurnObserver>>,
+ trace_content: crate::observe::TraceContent,
}
impl Turn {
@@ -285,6 +287,8 @@ impl Turn {
untrusted_input: false,
cancellation: None,
timeout: None,
+ observer: None,
+ trace_content: crate::observe::TraceContent::MetadataOnly,
}
}
@@ -511,6 +515,30 @@ impl Turn {
/// that is a build/composition fact, not a failure, and a host should hide
/// the surface rather than report an error.
pub async fn send(mut self) -> Result<TurnOutcome, CoreError> {
+ // Keep cancellation acknowledgement behind the terminal callback too.
+ let _observer_guard = self.cancellation.as_ref().map(|handle| handle.enter());
+ let Some(observer) = self.observer.take() else {
+ return self.send_controlled().await;
+ };
+ let capture = self.trace_content;
+ let session_id = self
+ .session_id
+ .clone()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
+ self.session_id = Some(session_id.clone());
+ let message = self.request.message.clone();
+ crate::observe::observe_turn(
+ observer,
+ capture,
+ &session_id,
+ &message,
+ self.send_controlled(),
+ )
+ .await
+ }
+
+ async fn send_controlled(mut self) -> Result<TurnOutcome, CoreError> {
let timeout = self.timeout.take();
let cancellation = match self.cancellation.take() {
Some(cancellation) => cancellation,
@@ -543,6 +571,20 @@ impl Turn {
outcome
}
+ /// Observe completion and, on runtime-owned agents, model and tool events.
+ /// Caller-built core runtimes provide terminal metadata only. Payloads are
+ /// omitted unless [`Self::trace_content`] explicitly enables them.
+ pub fn observer(mut self, observer: Arc<dyn crate::observe::TurnObserver>) -> Self {
+ self.observer = Some(observer);
+ self
+ }
+
+ /// Explicitly consent to model messages and tool payloads in observations.
+ pub fn trace_content(mut self, content: crate::observe::TraceContent) -> Self {
+ self.trace_content = content;
+ self
+ }
+
/// Bound the entire turn, including tool calls and answer repair.
/// Deadline errors are returned only after registered subprocess cleanup.
pub fn timeout(mut self, duration: std::time::Duration) -> Self {
@@ -875,7 +917,7 @@ async fn dispatch(
let turn: futures_box::BoxFuture<'_, Result<AgentReply, CoreError>> =
Box::pin(async move {
use openhuman_core::inference::host_runtime::ops::{
- AgentChatTarget, agent_chat_for,
+ agent_chat_for, AgentChatTarget,
};
let mut config = inner.config.clone();
let route = openhuman_core::config::schema::EphemeralRoute::from_params(
diff --git a/crates/openhuman-embed/tests/turn_cancellation.rs b/crates/openhuman-embed/tests/turn_cancellation.rs
index 56ff32d376..8181a6da4a 100644
--- a/crates/openhuman-embed/tests/turn_cancellation.rs
+++ b/crates/openhuman-embed/tests/turn_cancellation.rs
@@ -2,8 +2,19 @@
mod common;
+use std::sync::{Arc, Mutex};
use std::time::Duration;
+#[derive(Default)]
+struct Outcomes(Mutex<Vec<openhuman_embed::observe::TurnFailure>>);
+impl openhuman_embed::observe::TurnObserver for Outcomes {
+ fn on_turn(&self, trace: &openhuman_embed::observe::TurnTrace<'_>) {
+ assert!(trace.message.is_none());
+ assert!(trace.reply.is_none());
+ self.0.lock().unwrap().push(trace.failure.unwrap());
+ }
+}
+
use common::{offline_config, provider, route, runtime, stub_backend};
use openhuman_embed::{
Access, AgentDefinitionSpec, AgentSpec, CoreError, Runtime, ToolScopeSpec, Workspace,
@@ -88,23 +99,30 @@ async fn scenario() {
));
assert_eq!(agent.run("still usable").await.unwrap().reply, "finished");
+ let observed = Arc::new(Outcomes::default());
// A whole-turn deadline drops inference and leaves the same agent reusable.
assert!(matches!(
blocked
.turn("deadline")
.timeout(Duration::from_millis(100))
+ .observer(observed.clone())
.send()
.await,
Err(CoreError::DeadlineExceeded { .. })
));
assert_eq!(agent.run("after deadline").await.unwrap().reply, "finished");
+ assert_eq!(
+ *observed.0.lock().unwrap(),
+ vec![openhuman_embed::observe::TurnFailure::Deadline]
+ );
// An externally dropped send future also acknowledges cancellation.
+ let prior_requests = common::chat_requests(&slow).await.len();
let mut turn = blocked.turn("drop this inference request");
let cancel = turn.cancellation_handle();
let sent = tokio::spawn(turn.send());
tokio::time::timeout(Duration::from_secs(5), async {
- while common::chat_requests(&slow).await.len() < 3 {
+ while common::chat_requests(&slow).await.len() <= prior_requests {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})