Skip to content

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

refactor(agent): remove stop hook and hook scope modules

Steven Enamakelf4d09a593e17
diff --git a/crates/openhuman-core/src/agent/goals/runtime_tests.rs b/crates/openhuman-core/src/agent/goals/runtime_tests.rs
index 886e470ff2..1932f18dca 100644
--- a/crates/openhuman-core/src/agent/goals/runtime_tests.rs
+++ b/crates/openhuman-core/src/agent/goals/runtime_tests.rs
@@ -1,16 +1,4 @@
use super::*;
-use crate::inference::provider::BilledUsage;
-use tinyagents_harness::cost::TurnCost;
-
-fn cost_with_tokens(input: u64, output: u64) -> TurnCost {
- let mut tc = crate::agent::cost::turn_cost();
- tc.add_priced_call(
- "agentic-v1",
- &crate::agent::cost::call_usage(&BilledUsage::from_counts(input, output)),
- );
- tc
-}
-
#[tokio::test]
async fn account_turn_charges_active_goal_and_trips_budget() {
let tmp = tempfile::tempdir().unwrap();
@@ -182,91 +170,3 @@ async fn account_turn_clears_suppression_without_losing_usage() {
assert_eq!(updated.time_used_seconds, 3);
}
-#[tokio::test]
-async fn budget_stop_hook_fires_on_crossing() {
- let tmp = tempfile::tempdir().unwrap();
- let dir = tmp.path().to_path_buf();
- let goal = tinyagents_graph::goals::store::set(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "t-hook",
- "obj",
- Some(1000),
- )
- .await
- .unwrap();
- // 600 already used in a prior turn.
- tinyagents_graph::goals::store::account_usage(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "t-hook",
- &goal.goal_id,
- 600,
- 0,
- )
- .await
- .unwrap();
- let goal = tinyagents_graph::goals::store::get(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "t-hook",
- )
- .await
- .unwrap()
- .unwrap();
- let hook = GoalBudgetStopHook::for_goal(&dir, &goal).expect("budgeted active goal");
-
- // This turn so far: 300 in + 200 out = 500. 600 + 500 = 1100 >= 1000.
- let cost = cost_with_tokens(300, 200);
- let ctx = TurnState {
- iteration: 2,
- max_iterations: 10,
- cost: &cost,
- model: "agentic-v1",
- };
- assert!(matches!(hook.check(&ctx).await, StopDecision::Stop { .. }));
-
- // Under the cap continues.
- let small = cost_with_tokens(100, 100); // 600 + 200 = 800 < 1000
- let ctx2 = TurnState {
- iteration: 1,
- max_iterations: 10,
- cost: &small,
- model: "agentic-v1",
- };
- assert!(matches!(hook.check(&ctx2).await, StopDecision::Continue));
-}
-
-#[tokio::test]
-async fn no_hook_without_budget_or_when_inactive() {
- let tmp = tempfile::tempdir().unwrap();
- let dir = tmp.path().to_path_buf();
- let no_budget = tinyagents_graph::goals::store::set(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "a",
- "obj",
- None,
- )
- .await
- .unwrap();
- assert!(GoalBudgetStopHook::for_goal(&dir, &no_budget).is_none());
- tinyagents_graph::goals::store::set(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "b",
- "obj",
- Some(100),
- )
- .await
- .unwrap();
- tinyagents_graph::goals::store::pause(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "b",
- )
- .await
- .unwrap();
- let paused = tinyagents_graph::goals::store::get(
- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,
- "b",
- )
- .await
- .unwrap()
- .unwrap();
- assert!(GoalBudgetStopHook::for_goal(&dir, &paused).is_none());
-}
diff --git a/crates/openhuman-core/src/agent/hooks_scope.rs b/crates/openhuman-core/src/agent/hooks_scope.rs
deleted file mode 100644
index ffc9527e5a..0000000000
--- a/crates/openhuman-core/src/agent/hooks_scope.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-//! Owned hooks carried by one session or turn, never installed process-wide
-//! and never recovered from an ambient scope.
-
-use std::sync::Arc;
-
-use super::{PostTurnHook, ToolHook};
-
-/// Agent/turn callbacks added after the runtime's global callbacks.
-///
-/// A scope is plain data: the entry point that owns the turn hands it to the
-/// session it builds ([`OpenHumanSessionHost::set_host_env`]), which copies the
-/// tool and stop callbacks onto the turn's explicit
-/// [`OpenHumanRunContext`](crate::agent::tinyagents::host::OpenHumanRunContext)
-/// and keeps the post-turn callbacks for the learning sink. A child run
-/// inherits them through `OpenHumanRunContext::child`.
-///
-/// [`OpenHumanSessionHost::set_host_env`]: crate::agent::OpenHumanSessionHost::set_host_env
-#[derive(Clone, Default)]
-pub struct HookScope {
- tools: Vec<Arc<dyn ToolHook>>,
- post_turn: Vec<Arc<dyn PostTurnHook>>,
- stop: Vec<Arc<dyn tinyagents_hooks::stop::StopHook<tinyagents_harness::cost::TurnCost>>>,
-}
-
-impl HookScope {
- /// Append a tool callback, preserving registration order.
- pub fn push_tool(&mut self, hook: Arc<dyn ToolHook>) {
- self.tools.push(hook);
- }
-
- /// Append a completed-turn callback, preserving registration order.
- pub fn push_learning(&mut self, hook: Arc<dyn PostTurnHook>) {
- self.post_turn.push(hook);
- }
-
- /// Append a usage observer/budget policy checked after each model call.
- pub fn push_stop(
- &mut self,
- hook: Arc<dyn tinyagents_hooks::stop::StopHook<tinyagents_harness::cost::TurnCost>>,
- ) {
- self.stop.push(hook);
- }
-
- /// The scope's own tool callbacks, in registration order.
- pub fn tool_hooks(&self) -> &[Arc<dyn ToolHook>] {
- &self.tools
- }
-
- /// The scope's own completed-turn callbacks, in registration order.
- pub fn post_turn_hooks(&self) -> &[Arc<dyn PostTurnHook>] {
- &self.post_turn
- }
-
- /// The scope's own stop policies, in registration order.
- pub fn stop_hooks(
- &self,
- ) -> &[Arc<dyn tinyagents_hooks::stop::StopHook<tinyagents_harness::cost::TurnCost>>] {
- &self.stop
- }
-
- /// Whether the scope carries no callback of any kind.
- pub fn is_empty(&self) -> bool {
- self.tools.is_empty() && self.post_turn.is_empty() && self.stop.is_empty()
- }
-}
diff --git a/crates/openhuman-core/src/agent/stop_hooks.rs b/crates/openhuman-core/src/agent/stop_hooks.rs
deleted file mode 100644
index 4853550991..0000000000
--- a/crates/openhuman-core/src/agent/stop_hooks.rs
+++ /dev/null
@@ -1,76 +0,0 @@
-//! Mid-turn stop hooks — policy-driven halt of an in-flight agent
-//! turn.
-//!
-//! Stop hooks are the policy lever: budget caps, rate limits, custom kill
-//! switches. They run between iterations of the agent loop so a runaway turn can
-//! be cut short before the next provider call rather than after the fact.
-//! (User-driven cancellation — Ctrl+C / `/stop` — is handled separately by the
-//! `tinyagents` steering/cancellation channel.)
-//!
-//! The `tinyagents` adapter installs a `StopHookMiddleware`
-//! ([`crate::agent::tinyagents::stop_hooks`]) that fires each hook after
-//! every model call; a hook returning [`StopDecision::Stop`] pauses the run
-//! gracefully (via the steering handle) before the next provider call. Hooks
-//! arrive on the turn's explicit run context
-//! (`OpenHumanRunContext::stop_hooks`). The
-//! goal-budget hook ([`crate::agent::goals::runtime::GoalBudgetStopHook`]) is
-//! the live implementation.
-//!
-//! The per-turn tool budget ([`tool_call_limit`]) also lives here; a host
-//! narrows it through `HostTurnEnv::tool_call_limit`.
-
-use async_trait::async_trait;
-use tinyagents_harness::cost::TurnCost;
-
-use tinyagents_hooks::stop::{StopDecision, StopHook, TurnState};
-
-/// Stop a turn when its cumulative cost reaches the configured USD cap.
-#[derive(Debug, Clone, Copy)]
-pub struct BudgetStopHook {
- /// Cumulative USD charge at which the turn pauses.
- pub max_usd: f64,
-}
-
-impl BudgetStopHook {
- /// Construct a hook that pauses after a turn reaches `max_usd`.
- pub fn new(max_usd: f64) -> Self {
- Self { max_usd }
- }
-}
-
-#[async_trait]
-impl StopHook<TurnCost> for BudgetStopHook {
- fn name(&self) -> &str {
- "budget"
- }
-
- async fn check(&self, ctx: &TurnState<'_, TurnCost>) -> 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),
- };
- }
- // A cap can only bite on spend it can see: calls of unknown cost add
- // nothing here rather than a made-up rate.
- let spent = ctx.cost.cost.known_usd;
- if spent >= self.max_usd {
- StopDecision::Stop {
- reason: format!("turn cost ${spent:.4} reached cap ${:.4}", self.max_usd),
- }
- } else {
- StopDecision::Continue
- }
- }
-}
-
-/// The real tool invocation budget for one turn: the default derived from the
-/// iteration cap, narrowed by the host's explicit `cap`
-/// (`HostTurnEnv::tool_call_limit`) when it set one. A host can only narrow it.
-pub(crate) fn tool_call_limit(max_iterations: usize, cap: Option<usize>) -> usize {
- let default = max_iterations.saturating_mul(8).max(8);
- cap.map_or(default, |cap| default.min(cap))
-}
-
-#[cfg(test)]
-#[path = "stop_hooks_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/stop_hooks_tests.rs b/crates/openhuman-core/src/agent/stop_hooks_tests.rs
deleted file mode 100644
index c59b88eef5..0000000000
--- a/crates/openhuman-core/src/agent/stop_hooks_tests.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-use super::*;
-use std::sync::Arc;
-
-#[test]
-fn host_tool_cap_only_narrows_the_default_and_keeps_zero() {
- assert_eq!(tool_call_limit(10, None), 80);
- assert_eq!(tool_call_limit(10, Some(4)), 4);
- // A cap wider than the product default never widens it.
- assert_eq!(tool_call_limit(10, Some(1_000)), 80);
- assert_eq!(tool_call_limit(1, Some(100)), 8);
- // Zero is a real cap: no tool may run.
- assert_eq!(tool_call_limit(10, Some(0)), 0);
-}
-
-#[test]
-fn host_tool_cap_and_stop_hooks_flow_into_the_run_context_and_its_children() {
- let hook: Arc<dyn StopHook<tinyagents_harness::cost::TurnCost>> =
- Arc::new(BudgetStopHook::new(1.0));
- let mut hooks = crate::agent::hooks::HookScope::default();
- hooks.push_stop(Arc::clone(&hook));
- let env = crate::agent::turn_env::HostTurnEnv {
- tool_call_limit: Some(3),
- hooks,
- ..Default::default()
- };
- let context = crate::agent::tinyagents::host::OpenHumanRunContext::new().with_host_env(&env);
- assert_eq!(context.tool_call_limit, Some(3));
- assert_eq!(context.stop_hooks.len(), 1);
- assert_eq!(context.stop_hooks[0].name(), "budget");
- // Sub-agents inherit both through the explicit child carrier.
- let child = context.child();
- assert_eq!(child.tool_call_limit, Some(3));
- assert_eq!(child.stop_hooks.len(), 1);
- // A context built without an env carries nothing ambient.
- let bare = crate::agent::tinyagents::host::OpenHumanRunContext::new();
- assert_eq!(bare.tool_call_limit, None);
- assert!(bare.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 {
- cost: tinyagents_harness::cost::CostTally {
- known_usd: 1.0,
- source: tinyagents_harness::cost::CostSource::Charged,
- },
- ..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/stop_hooks.rs b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs
deleted file mode 100644
index f9271b84bf..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-//! Host accounting and result projection for the harness-owned stop chain.
-
-use std::sync::Arc;
-use tinyagents_harness::cost::TurnCost;
-use tinyagents_harness::steering::SteeringHandle;
-use tinyagents_hooks::stop::StopHook;
-use tinyagents_hooks::stop::StopHookMiddleware;
-
-/// Install product policies and preserve the host-facing halt summary.
-pub(super) fn install(
- harness: &mut tinyagents_harness::runtime::AgentHarness<(), super::host::OpenHumanRunContext>,
- handle: Option<&SteeringHandle>,
- model: &str,
- hooks: Vec<Arc<dyn StopHook<TurnCost>>>,
- halt_summary: tinyagents_harness::turn_outcome::HaltSummarySlot,
-) {
- if handle.is_some() && !hooks.is_empty() {
- harness.push_middleware(Arc::new(
- StopHookMiddleware::new(model, hooks)
- .with_metrics_seed(crate::agent::cost::turn_cost())
- .with_stop_observer(move |report| {
- tracing::warn!(
- target: "stop_hooks",
- hook = %report.hook,
- iteration = report.iteration,
- model = %report.model,
- "[stop_hooks] hook voted to stop the turn — pausing run: {}", report.reason
- );
- record_halt_summary(&halt_summary, report);
- }),
- ));
- }
-}
-
-fn record_halt_summary(
- halt_summary: &tinyagents_harness::turn_outcome::HaltSummarySlot,
- report: &tinyagents_hooks::stop::StopReport,
-) {
- *halt_summary
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(format!(
- "Stopping after {} model call(s): {}",
- report.iteration, report.reason
- ));
-}
-
-#[cfg(test)]
-#[path = "stop_hooks_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/stop_hooks_tests.rs b/crates/openhuman-core/src/agent/tinyagents/stop_hooks_tests.rs
deleted file mode 100644
index 20ea335348..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/stop_hooks_tests.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use super::*;
-
-#[test]
-fn a_poisoned_halt_summary_does_not_abort_stop_reporting() {
- let slot: tinyagents_harness::turn_outcome::HaltSummarySlot =
- Arc::new(std::sync::Mutex::new(None));
- let poisoned = Arc::clone(&slot);
- assert!(
- std::thread::spawn(move || {
- let _guard = poisoned.lock().unwrap();
- panic!("synthetic prior writer failure");
- })
- .join()
- .is_err()
- );
- record_halt_summary(
- &slot,
- &tinyagents_hooks::stop::StopReport {
- hook: "budget".into(),
- reason: "limit reached".into(),
- iteration: 2,
- model: "test-model".into(),
- },
- );
- assert_eq!(
- slot.lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .as_deref(),
- Some("Stopping after 2 model call(s): limit reached")
- );
-}