Skip to content

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

feat(embed): bound whole turns with cleanup-aware deadlines

Steven Enamakel0910765e9486
diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rs
index 094fc1dd7f..9f5140d0a0 100644
--- a/crates/openhuman-embed/src/complete.rs
+++ b/crates/openhuman-embed/src/complete.rs
@@ -282,11 +282,10 @@ pub struct CompletionUsage {
pub struct CompletionResponse {
/// The visible reply text (reasoning content excluded).
pub text: String,
- /// `text` parsed as JSON, when a JSON [`ResponseFormat`] was requested and
- /// the reply parses. A [`ResponseFormat::JsonObject`] reply must parse to
- /// an object, otherwise this is `None`. `None` with a JSON format means the
- /// model returned something that is not the requested JSON — check
- /// [`finish_reason`](Self::finish_reason) for `"length"` first.
+ /// Locally validated JSON when a JSON [`ResponseFormat`] was requested.
+ /// JSON objects and complete schemas are enforced before success; invalid
+ /// or truncated replies return [`CoreError::StructuredOutput`]. Text-mode
+ /// completions leave this field unset.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub structured: Option<Value>,
/// Provider finish reason (`stop`, `length`, …).
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 88d5a903ae..b2f50ff756 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -263,6 +263,7 @@ pub struct Turn {
require_tool_call: bool,
untrusted_input: bool,
cancellation: Option<crate::TurnCancellation>,
+ timeout: Option<std::time::Duration>,
}
impl Turn {
@@ -283,6 +284,7 @@ impl Turn {
require_tool_call: false,
untrusted_input: false,
cancellation: None,
+ timeout: None,
}
}
@@ -509,8 +511,11 @@ 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> {
- let Some(cancellation) = self.cancellation.take() else {
- return self.send_inner().await;
+ let timeout = self.timeout.take();
+ let cancellation = match self.cancellation.take() {
+ Some(cancellation) => cancellation,
+ None if timeout.is_some() => crate::TurnCancellation::default(),
+ None => return self.send_inner().await,
};
let _guard = cancellation.enter();
let outcome = cancellation
@@ -522,6 +527,12 @@ impl Turn {
log::debug!("[embed][agent] turn cancelled");
Err(CoreError::TurnCancelled { method: AGENT_CHAT })
}
+ _ = async {
+ match timeout {
+ Some(duration) => tokio::time::sleep(duration).await,
+ None => std::future::pending().await,
+ }
+ } => Err(CoreError::DeadlineExceeded { method: AGENT_CHAT }),
outcome = Box::pin(self.send_inner()) => outcome,
}
})
@@ -532,6 +543,13 @@ impl Turn {
outcome
}
+ /// 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 {
+ self.timeout = Some(duration);
+ self
+ }
+
/// Obtain a cloneable handle that cancels only this turn and awaits its
/// subprocess cleanup. Acquire it before moving the turn to `send()`.
pub fn cancellation_handle(&mut self) -> crate::TurnCancellation {
@@ -675,7 +693,6 @@ impl Turn {
crate::error::CoreError::InsecureRoute { .. } => "insecure_route",
crate::error::CoreError::InvalidRoute { .. } => "invalid_route",
crate::error::CoreError::AgentRemoved { .. } => "agent_removed",
- crate::error::CoreError::TurnCancelled { .. } => "turn_cancelled",
};
log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");
});
diff --git a/crates/openhuman-embed/tests/turn_cancellation.rs b/crates/openhuman-embed/tests/turn_cancellation.rs
index 0973411a3d..56ff32d376 100644
--- a/crates/openhuman-embed/tests/turn_cancellation.rs
+++ b/crates/openhuman-embed/tests/turn_cancellation.rs
@@ -88,12 +88,23 @@ async fn scenario() {
));
assert_eq!(agent.run("still usable").await.unwrap().reply, "finished");
+ // A whole-turn deadline drops inference and leaves the same agent reusable.
+ assert!(matches!(
+ blocked
+ .turn("deadline")
+ .timeout(Duration::from_millis(100))
+ .send()
+ .await,
+ Err(CoreError::DeadlineExceeded { .. })
+ ));
+ assert_eq!(agent.run("after deadline").await.unwrap().reply, "finished");
+
// An externally dropped send future also acknowledges cancellation.
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() < 2 {
+ while common::chat_requests(&slow).await.len() < 3 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})