The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(agent): add stop hooks for runtime session lifecycle
Steven Enamakelf098bb09d6af
diff --git a/crates/openhuman-core/src/agent/README.md b/crates/openhuman-core/src/agent/README.mdindex f0032412e4..f578400266 100644--- a/crates/openhuman-core/src/agent/README.md+++ b/crates/openhuman-core/src/agent/README.md@@ -92,7 +92,7 @@ Flat files: `bus.rs` (`agent.run_turn` native request handler), `context_breakdoinvocation budget for one awaited turn without changing the agent's persistentconfiguration. Zero permits no tool invocations. The adapter applies the limitto both run policy and run configuration, including parallel calls counted by-TinyAgents. `with_stop_hooks_and_tool_limit` combines it with stop hooks.+TinyAgents.Nested scopes take the smaller limit; `None` preserves an enclosing limit.Exiting or dropping the future restores the caller's scope, and concurrentdiff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 1e0392e3cd..8e33a1cf1f 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -743,9 +743,6 @@ impl OpenHumanTurnPrelude {self.tool_dispatcher.tool_call_format(),).harness_dispatcher();- run_context- .stop_hooks- .extend(crate::agent::stop_hooks::current_stop_hooks());self.context.lock().unwrap_or_else(std::sync::PoisonError::into_inner)diff --git a/crates/openhuman-core/src/agent/stop_hooks.rs b/crates/openhuman-core/src/agent/stop_hooks.rsindex b28463f04f..f24c3bb873 100644--- a/crates/openhuman-core/src/agent/stop_hooks.rs+++ b/crates/openhuman-core/src/agent/stop_hooks.rs@@ -7,30 +7,18 @@//! (User-driven cancellation — Ctrl+C / `/stop` — is handled separately by the//! `tinyagents` steering/cancellation channel.)//!-//! ## Wiring-//!-//! Hooks ride on a task-local rather than a parameter threaded through the turn,-//! mirroring how [`super::harness::fork_context::PARENT_CONTEXT`] and-//! [`super::harness::sandbox_context::CURRENT_AGENT_SANDBOX_MODE`] are threaded.-//!-//! Callers register hooks via [`with_stop_hooks`] around their turn invocation.-//! The `tinyagents` adapter snapshots them via [`current_stop_hooks`] and-//! installs a `StopHookMiddleware`+//! 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.-//!-//! ## Built-in hooks+//! gracefully (via the steering handle) before the next provider call. The+//! goal-budget hook ([`crate::agent::goals::runtime::GoalBudgetStopHook`]) is+//! the live implementation.//!-//! - [`BudgetStopHook`] — caps cumulative turn cost in USD using the-//! [`super::cost::TurnCost`] accumulator.-//! - [`MaxIterationsStopHook`] — caps iteration count from outside the-//! `max_tool_iterations` config (useful for ad-hoc per-call limits-//! without mutating the agent's persistent config).+//! The per-turn tool budget ([`with_tool_call_limit`]) also lives here, on a+//! task-local.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]@@ -65,28 +53,6 @@ pub struct TurnState<'a> {pub model: &'a str,}-tokio::task_local! {- /// Active stop hooks. `None` (the task-local-not-set state) is- /// treated as "no hooks" — see [`current_stop_hooks`].- static CURRENT_STOP_HOOKS: Vec<Arc<dyn StopHook>>;-}--/// Returns a clone of the currently-installed hook list, or an empty-/// vec when no scope has been entered.-pub fn current_stop_hooks() -> Vec<Arc<dyn StopHook>> {- CURRENT_STOP_HOOKS- .try_with(|hooks| hooks.clone())- .unwrap_or_default()-}--/// Run `future` with `hooks` installed as the active stop-hook list.-pub async fn with_stop_hooks<F, R>(hooks: Vec<Arc<dyn StopHook>>, future: F) -> R-where- F: std::future::Future<Output = R>,-{- CURRENT_STOP_HOOKS.scope(hooks, future).await-}-tokio::task_local! {static CURRENT_TOOL_CALL_LIMIT: usize;}@@ -110,15 +76,6 @@ pub async fn with_tool_call_limit<F: std::future::Future>(}}-/// Install hook policy and a tool budget around the same turn.-pub async fn with_stop_hooks_and_tool_limit<F: std::future::Future>(- hooks: Vec<Arc<dyn StopHook>>,- limit: Option<usize>,- future: F,-) -> F::Output {- with_tool_call_limit(limit, with_stop_hooks(hooks, future)).await-}-pub(crate) fn tool_call_limit(max_iterations: usize) -> usize {let default = max_iterations.saturating_mul(8).max(8);CURRENT_TOOL_CALL_LIMIT@@ -126,91 +83,6 @@ pub(crate) fn tool_call_limit(max_iterations: usize) -> usize {.unwrap_or(default)}-// ─────────────────────────────────────────────────────────────────────────────-// Built-in hooks-// ─────────────────────────────────────────────────────────────────────────────--/// Stop the turn once cumulative cost reaches `max_usd`.-///-/// Uses [`TurnCost::total_usd`] which prefers the backend's-/// `charged_amount_usd` and falls back to a tier-keyed estimate.-#[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 {- // Fail closed on a malformed cap: NaN, non-finite, or- // non-positive `max_usd` should *stop* rather than silently- // disable the guard (NaN comparisons always return false, so- // `spent >= NaN` would otherwise let the loop run forever).- 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 ${cap:.4}",- cap = self.max_usd- ),- }- } else {- StopDecision::Continue- }- }-}--/// Stop the turn at a hard iteration ceiling.-///-/// Sibling of `max_tool_iterations` on `AgentConfig`; this hook is-/// useful when callers want to lower the limit for one specific turn-/// without mutating the agent's persistent config.-#[derive(Debug, Clone, Copy)]-pub struct MaxIterationsStopHook {- pub cap: u32,-}--impl MaxIterationsStopHook {- pub fn new(cap: u32) -> Self {- Self { cap }- }-}--#[async_trait]-impl StopHook for MaxIterationsStopHook {- fn name(&self) -> &str {- "max_iterations"- }-- async fn check(&self, ctx: &TurnState<'_>) -> StopDecision {- if ctx.iteration > self.cap {- StopDecision::Stop {- reason: format!(- "turn reached iteration cap {} (about to start iteration {})",- self.cap, ctx.iteration- ),- }- } else {- StopDecision::Continue- }- }-}-#[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.rsindex e389f7b4f8..45c68d35e0 100644--- a/crates/openhuman-core/src/agent/stop_hooks_tests.rs+++ b/crates/openhuman-core/src/agent/stop_hooks_tests.rs@@ -1,116 +1,6 @@use super::*;use crate::inference::provider::UsageInfo;-fn cost_with_usd(usd: f64) -> TurnCost {- let mut tc = TurnCost::new();- tc.add_call(- "agentic-v1",- &UsageInfo {- charged_amount_usd: usd,- ..Default::default()- },- );- tc-}--#[tokio::test]-async fn budget_hook_continues_under_cap() {- let cost = cost_with_usd(0.10);- let hook = BudgetStopHook::new(1.00);- let ctx = TurnState {- iteration: 1,- max_iterations: 10,- cost: &cost,- model: "agentic-v1",- };- assert!(matches!(hook.check(&ctx).await, StopDecision::Continue));-}--#[tokio::test]-async fn budget_hook_stops_at_cap() {- let cost = cost_with_usd(1.50);- let hook = BudgetStopHook::new(1.00);- let ctx = TurnState {- iteration: 2,- max_iterations: 10,- cost: &cost,- model: "agentic-v1",- };- match hook.check(&ctx).await {- StopDecision::Stop { reason } => {- assert!(reason.contains("$1.5000"));- assert!(reason.contains("$1.0000"));- }- other => panic!("expected Stop, got {other:?}"),- }-}--#[tokio::test]-async fn budget_hook_fails_closed_on_nan_cap() {- // NaN comparisons always return false, so without the guard- // `spent >= NaN` would silently disable the cap forever.- let cost = cost_with_usd(1.0);- let hook = BudgetStopHook::new(f64::NAN);- let ctx = TurnState {- iteration: 1,- max_iterations: 10,- cost: &cost,- model: "agentic-v1",- };- match hook.check(&ctx).await {- StopDecision::Stop { reason } => assert!(reason.contains("invalid budget cap")),- other => panic!("expected Stop on NaN cap, got {other:?}"),- }-}--#[tokio::test]-async fn budget_hook_fails_closed_on_non_positive_cap() {- let cost = TurnCost::new();- let ctx = TurnState {- iteration: 1,- max_iterations: 10,- cost: &cost,- model: "agentic-v1",- };- for bad in [0.0, -1.0, f64::NEG_INFINITY, f64::INFINITY] {- let hook = BudgetStopHook::new(bad);- assert!(- matches!(hook.check(&ctx).await, StopDecision::Stop { .. }),- "cap {bad} should stop"- );- }-}--#[tokio::test]-async fn max_iterations_hook_stops_when_exceeded() {- let cost = TurnCost::new();- let hook = MaxIterationsStopHook::new(3);- let ctx = TurnState {- iteration: 4,- max_iterations: 10,- cost: &cost,- model: "agentic-v1",- };- assert!(matches!(hook.check(&ctx).await, StopDecision::Stop { .. }));-}--#[tokio::test]-async fn current_stop_hooks_returns_empty_outside_scope() {- assert!(current_stop_hooks().is_empty());-}--#[tokio::test]-async fn with_stop_hooks_installs_visible_within_scope() {- let hooks: Vec<Arc<dyn StopHook>> = vec![Arc::new(BudgetStopHook::new(0.5))];- with_stop_hooks(hooks, async {- let visible = current_stop_hooks();- assert_eq!(visible.len(), 1);- assert_eq!(visible[0].name(), "budget");- })- .await;- assert!(current_stop_hooks().is_empty());-}-#[tokio::test]async fn scoped_tool_limits_narrow_restore_and_keep_zero() {assert_eq!(tool_call_limit(10), 80);diff --git a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rsindex 0340bc8b8b..4460824ffb 100644--- a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs+++ b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs@@ -15,9 +15,7 @@//! partial transcript. This mirrors the [`CapPauser`](super::CapPauser)//! model-call-cap mechanism.//!-//! The hook list is captured by the caller via-//! [`current_stop_hooks`](crate::agent::stop_hooks::current_stop_hooks)-//! while the `CURRENT_STOP_HOOKS` task-local is in scope and handed to+//! The hook list (the goal-budget hook) is handed to//! [`StopHookMiddleware::new`]; the middleware is only registered when the list//! is non-empty.