Skip to content

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

feat(embed): enforce host dispatch admission on model calls

Steven Enamakel6ddf39abd1da
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget.rs b/crates/openhuman-core/src/agent/tinyagents/budget.rs
index 73444f2ee8..179b66daab 100644
--- a/crates/openhuman-core/src/agent/tinyagents/budget.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs
@@ -11,7 +11,8 @@ pub use tinyinference_llm::model::budget::{
Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits,
};
pub use tinyagents_harness::cost::{
- DispatchRefusal, DispatchRefusalReason, PhysicalDispatchAdmission, PhysicalDispatchPermit,
+ ControlledDispatchError, DispatchModelOptions, DispatchRefusal, DispatchRefusalReason,
+ PhysicalDispatchAdmission, PhysicalDispatchPermit,
};
/// OpenHuman's source-compatible carrier for the shared ledger and physical
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 1fd2144368..61ac12cfd3 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -269,6 +269,9 @@ impl TurnDispatchState {
pub struct OpenHumanRunContext {
/// Explicit shared model-call budget inherited by synchronous children.
pub model_budget: Option<super::super::budget::ModelBudget>,
+ /// Host admission policy shared by this run and its synchronous descendants.
+ pub dispatch_admission:
+ Option<Arc<super::super::budget::PhysicalDispatchAdmission>>,
/// The response format and output cap this root turn asks of every model
/// call, and the slot its final call is reported into. Carried explicitly
/// from the caller (`agent_chat`) through the session; children never
@@ -435,6 +438,7 @@ impl OpenHumanRunContext {
pub fn new() -> Self {
Self {
model_budget: None,
+ dispatch_admission: None,
response_shape: None,
max_spawn_depth: None,
origin: None,
@@ -583,6 +587,7 @@ impl OpenHumanRunContext {
#[must_use]
pub(crate) fn with_host_env(mut self, env: &crate::agent::turn_env::HostTurnEnv) -> Self {
self.model_budget = env.model_budget.clone().or(self.model_budget);
+ self.dispatch_admission = env.dispatch_admission.clone().or(self.dispatch_admission);
self.max_spawn_depth = env.spawn_depth_limit.or(self.max_spawn_depth);
if let Some(cancellation) = &env.cancellation {
self.cancellation = cancellation.clone();
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
index a82d0fbc6b..eab9b629cd 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs
@@ -428,6 +428,38 @@ fn child_inherits_shared_model_budget_and_narrowed_depth_limit() {
);
}
+#[test]
+fn child_inherits_the_same_physical_dispatch_admission() {
+ let admission: Arc<dyn super::super::budget::PhysicalDispatchAdmission> =
+ Arc::new(TestAdmission);
+ let env = crate::agent::turn_env::HostTurnEnv {
+ dispatch_admission: Some(admission.clone()),
+ ..Default::default()
+ };
+
+ let parent = OpenHumanRunContext::new().with_host_env(&env);
+ let child = parent.child();
+
+ assert!(Arc::ptr_eq(
+ parent.dispatch_admission.as_ref().unwrap(),
+ child.dispatch_admission.as_ref().unwrap()
+ ));
+}
+
+struct TestAdmission;
+
+#[async_trait::async_trait]
+impl super::super::budget::PhysicalDispatchAdmission for TestAdmission {
+ async fn acquire(
+ &self,
+ ) -> Result<
+ Arc<dyn super::super::budget::PhysicalDispatchPermit>,
+ super::super::budget::DispatchRefusal,
+ > {
+ unreachable!("this context inheritance test never acquires a permit")
+ }
+}
+
#[test]
fn task_recency_window_reaches_tools_as_a_host_extension_not_a_task_local() {
let mut host = OpenHumanRunContext::new();
diff --git a/crates/openhuman-core/src/agent/turn_env.rs b/crates/openhuman-core/src/agent/turn_env.rs
index 086514edd0..5205e033ed 100644
--- a/crates/openhuman-core/src/agent/turn_env.rs
+++ b/crates/openhuman-core/src/agent/turn_env.rs
@@ -35,6 +35,8 @@ pub struct HostTurnEnv {
/// Shared model-spend ledger and per-call bounds every model call of the
/// turn tree is charged against.
pub model_budget: Option<ModelBudget>,
+ /// Shared physical-dispatch policy for this turn and its synchronous children.
+ pub dispatch_admission: Option<Arc<dyn super::tinyagents::budget::PhysicalDispatchAdmission>>,
/// A narrower model-directed delegation depth than the product ceiling.
pub spawn_depth_limit: Option<usize>,
/// The caller's cancellation, shared with every child run. `None` runs the
@@ -79,6 +81,7 @@ impl std::fmt::Debug for HostTurnEnv {
f.debug_struct("HostTurnEnv")
.field("command_environment", &self.command_environment.is_some())
.field("model_budget", &self.model_budget.is_some())
+ .field("dispatch_admission", &self.dispatch_admission.is_some())
.field("spawn_depth_limit", &self.spawn_depth_limit)
.field("cancellation", &self.cancellation.is_some())
.field("turn_deadline", &self.turn_deadline.is_some())
diff --git a/crates/openhuman-embed/src/budget.rs b/crates/openhuman-embed/src/budget.rs
index 0d1ecd1c98..089b59c16b 100644
--- a/crates/openhuman-embed/src/budget.rs
+++ b/crates/openhuman-embed/src/budget.rs
@@ -20,7 +20,8 @@
//! bounds that include model framing and the maximum price on allowed routes.
pub use openhuman_core::agent::tinyagents::budget::ModelBudget;
pub use openhuman_core::agent::tinyagents::budget::{
- DispatchRefusal, DispatchRefusalReason, PhysicalDispatchAdmission, PhysicalDispatchPermit,
+ ControlledDispatchError, DispatchModelOptions, DispatchRefusal, DispatchRefusalReason,
+ PhysicalDispatchAdmission, PhysicalDispatchPermit,
};
pub use tinyinference_llm::model::budget::{
Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits,
diff --git a/crates/openhuman-embed/src/complete_tests.rs b/crates/openhuman-embed/src/complete_tests.rs
index 119d6bd149..5a0b0f57eb 100644
--- a/crates/openhuman-embed/src/complete_tests.rs
+++ b/crates/openhuman-embed/src/complete_tests.rs
@@ -533,6 +533,142 @@ async fn repair_cannot_exceed_dispatch_limit() {
assert!(result.is_err(), "the refused repair must be terminal");
}
+#[tokio::test]
+async fn admission_only_completion_refuses_before_provider_and_observer() {
+ let server = MockServer::start().await;
+ let observer = Arc::new(PhysicalRecorder::default());
+ let admission = Arc::new(RefuseAdmission);
+
+ let error = completer(&server)
+ .dispatch_admission(admission)
+ .physical_observer(observer.clone())
+ .complete(CompletionRequest::new(
+ "admission-only",
+ vec![ChatMessage::user("private")],
+ ))
+ .await
+ .expect_err("the host policy refuses the first call");
+
+ assert!(matches!(error, CoreError::DispatchAdmission { .. }));
+ assert!(server.received_requests().await.unwrap().is_empty());
+ assert!(observer.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn scoped_monetary_budget_keeps_the_shared_dispatch_admission() {
+ let server = server_replying(body("{\"ok\":true}", "stop")).await;
+ let admission = Arc::new(OneCallAdmission(std::sync::atomic::AtomicUsize::new(0)));
+ let budget = crate::budget::ModelBudget {
+ ledger: crate::budget::Budget::new(crate::budget::SpendLimits {
+ tokens: Some(1_000),
+ cost_micros: Some(100_000),
+ }),
+ call: crate::budget::CallBudget {
+ input_tokens: 500,
+ output_tokens: 100,
+ cost_micros: 100_000,
+ },
+ };
+
+ completer(&server)
+ .budget(budget)
+ .dispatch_admission(admission)
+ .complete(CompletionRequest::new(
+ "budgeted-admission",
+ vec![ChatMessage::user("private")],
+ ))
+ .await
+ .expect("the first call is admitted");
+
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn truncation_retry_consumes_a_dispatch_slot() {
+ let server = MockServer::start().await;
+ let replies = Arc::new(Mutex::new(0));
+ let replies_for_handler = Arc::clone(&replies);
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(move |_request: &wiremock::Request| {
+ let mut replies = replies_for_handler.lock().unwrap();
+ let (text, finish) = if *replies == 0 {
+ ("{", "length")
+ } else {
+ ("{\"ok\":true}", "stop")
+ };
+ *replies += 1;
+ ResponseTemplate::new(200).set_body_json(body(text, finish))
+ })
+ .mount(&server)
+ .await;
+ let admission = Arc::new(OneCallAdmission(std::sync::atomic::AtomicUsize::new(0)));
+ let request = CompletionRequest::new("truncated-model", vec![ChatMessage::user("private")])
+ .response_format(ResponseFormat::JsonObject)
+ .structured_retries(1);
+
+ let error = completer(&server)
+ .dispatch_admission(admission)
+ .complete(request)
+ .await
+ .expect_err("the truncation repair is refused");
+
+ assert!(matches!(error, CoreError::DispatchAdmission { .. }));
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn refusal_preserves_paid_usage_without_a_phantom_observer_event() {
+ let server = MockServer::start().await;
+ let replies = Arc::new(Mutex::new(0));
+ let replies_for_handler = Arc::clone(&replies);
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(move |_request: &wiremock::Request| {
+ let mut replies = replies_for_handler.lock().unwrap();
+ let text = if *replies == 0 { "invalid" } else { "{\"ok\":true}" };
+ *replies += 1;
+ ResponseTemplate::new(200).set_body_json(body(text, "stop"))
+ })
+ .mount(&server)
+ .await;
+ let admission = Arc::new(OneCallAdmission(std::sync::atomic::AtomicUsize::new(0)));
+ let observer = Arc::new(PhysicalRecorder::default());
+ let request = CompletionRequest::new("paid-repair", vec![ChatMessage::user("private")])
+ .response_format(ResponseFormat::JsonObject)
+ .structured_retries(1);
+
+ let error = completer(&server)
+ .dispatch_admission(admission)
+ .physical_observer(observer.clone())
+ .complete(request)
+ .await
+ .expect_err("the second physical call is refused");
+
+ match error {
+ CoreError::DispatchAdmission { usage, .. } => {
+ assert_eq!(usage.expect("first call usage is retained").cost_usd, Some(0.0125));
+ }
+ other => panic!("expected typed admission refusal, got {other:?}"),
+ }
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+ assert_eq!(observer.0.lock().unwrap().len(), 1);
+}
+
+struct RefuseAdmission;
+
+#[async_trait::async_trait]
+impl crate::budget::PhysicalDispatchAdmission for RefuseAdmission {
+ async fn acquire(
+ &self,
+ ) -> Result<Arc<dyn crate::budget::PhysicalDispatchPermit>, crate::budget::DispatchRefusal>
+ {
+ Err(crate::budget::DispatchRefusal::new(
+ crate::budget::DispatchRefusalReason::CallLimit,
+ ))
+ }
+}
+
#[test]
fn json_reply_tolerates_one_code_fence() {
assert_eq!(
diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rs
index 387d1944c5..46ad40b8d3 100644
--- a/crates/openhuman-embed/src/error.rs
+++ b/crates/openhuman-embed/src/error.rs
@@ -55,6 +55,17 @@ pub enum CoreError {
/// Refusal including spend so far and outstanding reservations.
source: crate::budget::BudgetExceeded,
},
+ /// Physical model dispatch refused by the host before provider invocation.
+ #[error("{method}: {source}")]
+ DispatchAdmission {
+ /// Method that attempted the call.
+ method: &'static str,
+ /// Typed host policy refusal.
+ #[source]
+ source: crate::budget::DispatchRefusal,
+ /// Usage from completed calls in this logical completion, if any.
+ usage: Option<crate::complete::CompletionUsage>,
+ },
/// The host cancelled this turn through its cancellation handle.
#[error("{method}: turn cancelled")]
TurnCancelled {
diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rs
index 3f5bcfee9c..d60f77dbd0 100644
--- a/crates/openhuman-embed/src/turn_control.rs
+++ b/crates/openhuman-embed/src/turn_control.rs
@@ -366,6 +366,7 @@ impl Turn {
host: openhuman_core::agent::turn_env::HostTurnEnv {
command_environment: self.tool_env.take(),
model_budget: budget.clone(),
+ dispatch_admission: self.dispatch_admission.take(),
spawn_depth_limit: self.spawn_depth_limit,
cancellation: self.native_cancellation.clone(),
hooks: std::mem::take(&mut self.hooks),