Skip to content

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

fix(embed): restore scoped stop hook compatibility

Steven Enamakel18919f03cf2b
diff --git a/crates/openhuman-core/src/agent/stop_hooks.rs b/crates/openhuman-core/src/agent/stop_hooks.rs
index f24c3bb873..b76f7984bc 100644
--- a/crates/openhuman-core/src/agent/stop_hooks.rs
+++ b/crates/openhuman-core/src/agent/stop_hooks.rs
@@ -19,6 +19,7 @@
use crate::agent::cost::TurnCost;
use async_trait::async_trait;
+use std::sync::Arc;
/// A policy hook fired between iterations of the tool-call loop.
#[async_trait]
@@ -53,6 +54,60 @@ pub struct TurnState<'a> {
pub model: &'a str,
}
+tokio::task_local! {
+ static CURRENT_STOP_HOOKS: Vec<Arc<dyn StopHook>>;
+}
+
+/// Clone the stop hooks active in the current task, if any.
+pub fn current_stop_hooks() -> Vec<Arc<dyn StopHook>> {
+ CURRENT_STOP_HOOKS
+ .try_with(Clone::clone)
+ .unwrap_or_default()
+}
+
+/// Scope a future with per-turn stop hooks.
+pub async fn with_stop_hooks<F: std::future::Future>(
+ hooks: Vec<Arc<dyn StopHook>>,
+ future: F,
+) -> F::Output {
+ CURRENT_STOP_HOOKS.scope(hooks, future).await
+}
+
+/// Stop a turn when its cumulative cost reaches the configured USD cap.
+#[derive(Debug, Clone, Copy)]
+pub struct BudgetStopHook {
+ pub max_usd: f64,
+}
+
+impl BudgetStopHook {
+ pub fn new(max_usd: f64) -> Self {
+ Self { max_usd }
+ }
+}
+
+#[async_trait]
+impl StopHook for BudgetStopHook {
+ fn name(&self) -> &str {
+ "budget"
+ }
+
+ async fn check(&self, ctx: &TurnState<'_>) -> StopDecision {
+ if !self.max_usd.is_finite() || self.max_usd <= 0.0 {
+ return StopDecision::Stop {
+ reason: format!("invalid budget cap configured: max_usd={}", self.max_usd),
+ };
+ }
+ let spent = ctx.cost.total_usd();
+ if spent >= self.max_usd {
+ StopDecision::Stop {
+ reason: format!("turn cost ${spent:.4} reached cap ${:.4}", self.max_usd),
+ }
+ } else {
+ StopDecision::Continue
+ }
+ }
+}
+
tokio::task_local! {
static CURRENT_TOOL_CALL_LIMIT: usize;
}
diff --git a/crates/openhuman-core/src/agent/stop_hooks_tests.rs b/crates/openhuman-core/src/agent/stop_hooks_tests.rs
index 8481c152ac..0a2334b27d 100644
--- a/crates/openhuman-core/src/agent/stop_hooks_tests.rs
+++ b/crates/openhuman-core/src/agent/stop_hooks_tests.rs
@@ -53,3 +53,45 @@ async fn cancelled_scope_restores_the_callers_tool_limit() {
drop(scoped);
assert_eq!(tool_call_limit(10), 80);
}
+
+#[tokio::test]
+async fn scoped_stop_hooks_are_visible_to_run_contexts() {
+ let hook: Arc<dyn StopHook> = Arc::new(BudgetStopHook::new(1.0));
+ assert!(current_stop_hooks().is_empty());
+ with_stop_hooks(vec![Arc::clone(&hook)], async {
+ let active = current_stop_hooks();
+ assert_eq!(active.len(), 1);
+ assert_eq!(active[0].name(), "budget");
+ assert_eq!(
+ crate::agent::tinyagents::host::OpenHumanRunContext::new()
+ .stop_hooks
+ .len(),
+ 1
+ );
+ })
+ .await;
+ assert!(current_stop_hooks().is_empty());
+}
+
+#[tokio::test]
+async fn budget_stop_hook_fails_closed_and_stops_at_cap() {
+ let hook = BudgetStopHook::new(1.0);
+ let cost = TurnCost {
+ charged_usd: 1.0,
+ ..TurnCost::default()
+ };
+ let state = TurnState {
+ iteration: 1,
+ max_iterations: 10,
+ cost: &cost,
+ model: "test",
+ };
+ assert!(matches!(
+ hook.check(&state).await,
+ StopDecision::Stop { .. }
+ ));
+ assert!(matches!(
+ BudgetStopHook::new(f64::NAN).check(&state).await,
+ StopDecision::Stop { .. }
+ ));
+}
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 aab9227362..1fb5a62815 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -23,7 +23,7 @@ use crate::agent::stop_hooks::StopHook;
use crate::agent::subagent_host::SubagentUsage;
use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;
use crate::agent::tinyagents::{
- turn_outcome::ToolCallOutcome, turn_policy::ToolPolicyEnforcement, TurnContextMiddleware,
+ TurnContextMiddleware, turn_outcome::ToolCallOutcome, turn_policy::ToolPolicyEnforcement,
};
use crate::agent::turn_origin::AgentTurnOrigin;
use tinyagents_harness::store::InMemoryStore as ToolResultArtifactIndexStore;
@@ -322,7 +322,7 @@ impl OpenHumanRunContext {
Self {
origin: None,
progress: None,
- stop_hooks: Vec::new(),
+ stop_hooks: crate::agent::stop_hooks::current_stop_hooks(),
parent: None,
prepared_context_sources: Arc::new(Vec::new()),
file_state_agent_id: None,
diff --git a/crates/openhuman-core/src/backend/classify.rs b/crates/openhuman-core/src/backend/classify.rs
new file mode 100644
index 0000000000..c2e9e63d2c
--- /dev/null
+++ b/crates/openhuman-core/src/backend/classify.rs
@@ -0,0 +1,3 @@
+//! Shared provider error classification helpers.
+
+pub use tinyinference_providers::is_budget_exhausted_message;
diff --git a/crates/openhuman-core/src/backend/mod.rs b/crates/openhuman-core/src/backend/mod.rs
index e3c7cc2a28..02b00cc5aa 100644
--- a/crates/openhuman-core/src/backend/mod.rs
+++ b/crates/openhuman-core/src/backend/mod.rs
@@ -21,14 +21,15 @@
//! [`BackendApiError::BackendUnavailable`] / `BACKEND_UNAVAILABLE:`, and the
//! URL helpers here return [`BackendTransportError::Unavailable`].
+pub mod classify;
pub mod client;
pub mod transport;
-pub use client::{flatten_authed_error, BackendApiError, BackendClient};
+pub use client::{BackendApiError, BackendClient, flatten_authed_error};
pub use transport::{
+ BackendRequest, BackendTransport, BackendTransportError, BaseUrlPurpose, TransportProfile,
install_backend_transport, installed_backend_transport, is_installed,
- resolve_backend_transport, BackendRequest, BackendTransport, BackendTransportError,
- BaseUrlPurpose, TransportProfile,
+ resolve_backend_transport,
};
/// The operator's override, trimmed; `None` when unset or blank.
diff --git a/crates/openhuman-core/src/tools/toolpacks/groups.rs b/crates/openhuman-core/src/tools/toolpacks/groups.rs
index 3d4c6fdc36..709593d41c 100644
--- a/crates/openhuman-core/src/tools/toolpacks/groups.rs
+++ b/crates/openhuman-core/src/tools/toolpacks/groups.rs
@@ -165,6 +165,11 @@ impl ToolGroups {
/// [`CoreContext`]: crate::core::runtime::context::CoreContext
static PROCESS_GROUPS: std::sync::OnceLock<ToolGroups> = std::sync::OnceLock::new();
+/// Set the process-wide group posture for hosts that do not establish a core context.
+pub fn set_process_default(groups: ToolGroups) {
+ let _ = PROCESS_GROUPS.set(groups);
+}
+
/// The ambient groups for the running core.
///
/// Resolution order: the scoped [`CoreContext`], then the process default from
diff --git a/crates/openhuman-core/src/tools/toolpacks/mod.rs b/crates/openhuman-core/src/tools/toolpacks/mod.rs
index 8c5f7e9eb0..a62b54d2d0 100644
--- a/crates/openhuman-core/src/tools/toolpacks/mod.rs
+++ b/crates/openhuman-core/src/tools/toolpacks/mod.rs
@@ -26,14 +26,14 @@ pub mod groups;
pub mod ops;
pub mod registry;
-pub use groups::{GroupMode, ToolGroups, GROUP_COUNT};
+pub use groups::{GROUP_COUNT, GroupMode, ToolGroups, set_process_default};
pub use ops::{
append_pack_tools, bind_pack_registry, bind_synthesized_pack_registry, close_handed_off_packs,
closed_by_direct_handoff, strip_packed_from_visible,
};
pub use registry::{
- all_packed_tool_names, callable_pack_ids, pack, pack_for_tool, pack_index_markdown_filtered,
- CATALOG, PACKS,
+ CATALOG, PACKS, all_packed_tool_names, callable_pack_ids, pack, pack_for_tool,
+ pack_index_markdown_filtered,
};
#[cfg(test)]