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
refactor(agent): delegate stop hooks and cost accounting to the harness
Steven Enamakel88725b998c58
diff --git a/crates/openhuman-core/src/agent/cost.rs b/crates/openhuman-core/src/agent/cost.rsindex 3d3d321bf3..5cfdb9dc53 100644--- a/crates/openhuman-core/src/agent/cost.rs+++ b/crates/openhuman-core/src/agent/cost.rs@@ -18,62 +18,35 @@use crate::inference::provider::BilledUsage;-/// Per-million-token rates for a single model.-///-/// All prices are USD per million tokens. `cached_input_per_mtok_usd`-/// applies to the `cached_input_tokens` portion of the usage block (KV-/// prefix cache hits on supporting backends); the remaining-/// `input_tokens - cached_input_tokens` are charged at-/// `input_per_mtok_usd`.-#[derive(Debug, Clone, Copy)]-pub(crate) struct ModelPricing {- /// Model id, e.g. `"claude-sonnet-4-6"`.- pub(crate) model: &'static str,- /// Standard prompt rate, USD per million input tokens.- pub(crate) input_per_mtok_usd: f64,- /// Cached-prefix prompt rate, USD per million cached input tokens.- pub(crate) cached_input_per_mtok_usd: f64,- /// Completion rate, USD per million output tokens.- pub(crate) output_per_mtok_usd: f64,-}--/// Published list rates for `model`, or `None` when the vendor catalog does-/// not know it./// Whether a model names an explicitly free OpenRouter variant.pub(crate) fn is_free_model(model: &str) -> bool {model.trim().to_ascii_lowercase().ends_with(":free")}-pub(crate) fn lookup_pricing(model: &str) -> Option<ModelPricing> {+/// Supply product catalog rates as data to the harness accounting API.+pub(crate) fn lookup_pricing(model: &str) -> Option<tinyagents_harness::cost::ModelPricing> {if is_free_model(model) {- return Some(ModelPricing {- model: "<free>",- input_per_mtok_usd: 0.0,- cached_input_per_mtok_usd: 0.0,- output_per_mtok_usd: 0.0,+ return Some(tinyagents_harness::cost::ModelPricing {+ input_per_token: Some(0.0),+ cache_read_input_per_token: Some(0.0),+ output_per_token: Some(0.0),+ ..Default::default()});}let price = crate::platform::cost::catalog::lookup(model.trim())?;- Some(ModelPricing {- model: price.model_id,- input_per_mtok_usd: price.input_per_mtok_usd,- cached_input_per_mtok_usd: price.cached_input_per_mtok_usd,- output_per_mtok_usd: price.output_per_mtok_usd,- })+ Some(crate::platform::cost::catalog::tinyagents_pricing(price))}-/// List-price estimate of one call, or `None` when the model is not-/// catalogued. Used only when the provider reported no charge.+/// Estimate a call from product list prices when no provider charge was reported.pub fn estimate_call_cost_usd(model: &str, usage: &BilledUsage) -> Option<f64> {let pricing = lookup_pricing(model)?;- let cached = usage.cached_input_tokens().min(usage.input_tokens);- let standard_input = usage.input_tokens.saturating_sub(cached);- let m = 1_000_000.0_f64;- Some(- (standard_input as f64) / m * pricing.input_per_mtok_usd- + (cached as f64) / m * pricing.cached_input_per_mtok_usd- + (usage.output_tokens as f64) / m * pricing.output_per_mtok_usd,- )+ let usage = tinyinference_llm::usage::Usage {+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ cache_read_tokens: usage.cached_input_tokens().min(usage.input_tokens),+ ..Default::default()+ };+ Some(tinyagents_harness::cost::estimate_cost(&pricing, &usage).total_cost)}/// Where a cost figure came from. Ordered from most to least certain, so thediff --git a/crates/openhuman-core/src/agent/cost_tests.rs b/crates/openhuman-core/src/agent/cost_tests.rsindex 970e217b14..56282b666b 100644--- a/crates/openhuman-core/src/agent/cost_tests.rs+++ b/crates/openhuman-core/src/agent/cost_tests.rs@@ -21,7 +21,7 @@ fn an_uncatalogued_model_has_no_price_and_no_estimate() {#[test]fn a_catalogued_model_is_estimated_at_its_list_rates() {let pricing = lookup_pricing(CATALOGUED).expect("catalogued");- assert_eq!(pricing.model, "claude-sonnet-4-6");+ assert_eq!(pricing.input_per_token, Some(3.0 / 1_000_000.0));// 1M uncached input at $3 + 1M cached at $0.30 + 1M output at $15.let usage = counts(2_000_000, 1_000_000, 1_000_000);let estimate = estimate_call_cost_usd(CATALOGUED, &usage).expect("priced");diff --git a/crates/openhuman-core/src/agent/goals/runtime.rs b/crates/openhuman-core/src/agent/goals/runtime.rsindex 78a70f241e..e2448674d3 100644--- a/crates/openhuman-core/src/agent/goals/runtime.rs+++ b/crates/openhuman-core/src/agent/goals/runtime.rs@@ -248,7 +248,7 @@ impl GoalBudgetStopHook {}#[async_trait]-impl StopHook for GoalBudgetStopHook {+impl StopHook<crate::agent::cost::TurnCost> for GoalBudgetStopHook {fn name(&self) -> &str {"thread_goal_budget"}diff --git a/crates/openhuman-core/src/agent/hooks_scope.rs b/crates/openhuman-core/src/agent/hooks_scope.rsindex 7d7a2b32cf..d11afe110e 100644--- a/crates/openhuman-core/src/agent/hooks_scope.rs+++ b/crates/openhuman-core/src/agent/hooks_scope.rs@@ -18,7 +18,7 @@ tokio::task_local! {pub struct HookScope {tools: Vec<Arc<dyn ToolHook>>,post_turn: Vec<Arc<dyn PostTurnHook>>,- stop: Vec<Arc<dyn crate::agent::stop_hooks::StopHook>>,+ stop: Vec<Arc<dyn crate::agent::stop_hooks::StopHook<crate::agent::cost::TurnCost>>>,}impl HookScope {@@ -33,7 +33,10 @@ impl HookScope {}/// Append a usage observer/budget policy checked after each model call.- pub fn push_stop(&mut self, hook: Arc<dyn crate::agent::stop_hooks::StopHook>) {+ pub fn push_stop(+ &mut self,+ hook: Arc<dyn crate::agent::stop_hooks::StopHook<crate::agent::cost::TurnCost>>,+ ) {self.stop.push(hook);}diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rsindex 877911a5f2..0c68fcd4a7 100644--- a/crates/openhuman-core/src/agent/multimodal.rs+++ b/crates/openhuman-core/src/agent/multimodal.rs@@ -158,15 +158,7 @@ impl TextExtractor for DocumentsTextExtractor {// ── Marker helpers over `TranscriptMessage` ────────────────────────────────────-/// Strip every `[IMAGE:…]` marker and return `(cleaned_text, refs_in_order)`.-pub fn parse_image_markers(content: &str) -> (String, Vec<String>) {- markers::parse_image_markers(content)-}--/// Strip every `[FILE:…]` marker and return `(cleaned_text, refs_in_order)`.-pub fn parse_file_markers(content: &str) -> (String, Vec<String>) {- markers::parse_file_markers(content)-}+pub use tinyagents_harness::multimodal::markers::{parse_file_markers, parse_image_markers};/// The base64 payload Ollama's `images` array expects, or `None`.pub fn extract_ollama_image_payload(image_ref: &str) -> Option<String> {diff --git a/crates/openhuman-core/src/agent/stop_hooks.rs b/crates/openhuman-core/src/agent/stop_hooks.rsindex 69a1480d1f..a69ae06660 100644--- a/crates/openhuman-core/src/agent/stop_hooks.rs+++ b/crates/openhuman-core/src/agent/stop_hooks.rs@@ -21,45 +21,17 @@ 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]-pub trait StopHook: Send + Sync {- /// Stable name for tracing / error messages (e.g. `"budget"`).- fn name(&self) -> &str;-- /// Inspect the current turn state and decide whether to continue.- async fn check(&self, ctx: &TurnState<'_>) -> StopDecision;-}+pub use tinyagents_harness::middleware::library::{StopDecision, StopHook};-/// Outcome of a single hook check.-#[derive(Debug, Clone)]-pub enum StopDecision {- /// Keep the loop running.- Continue,- /// Stop the loop. `reason` is propagated to the caller.- Stop { reason: String },-}--/// Snapshot of the turn at the moment a hook fires. References are-/// borrowed from the loop's locals so hooks pay no allocation cost on-/// the hot path; clone fields out if you need to keep them.-pub struct TurnState<'a> {- /// 1-based iteration index that's about to start.- pub iteration: u32,- /// Configured iteration cap for this turn.- pub max_iterations: u32,- /// Cumulative cost / token tally so far.- pub cost: &'a TurnCost,- /// Model name passed to this turn's provider calls.- pub model: &'a str,-}+/// Host accounting snapshot supplied to the harness-owned policy contract.+pub type TurnState<'a> = tinyagents_harness::middleware::library::TurnState<'a, TurnCost>;tokio::task_local! {- static CURRENT_STOP_HOOKS: Vec<Arc<dyn StopHook>>;+ static CURRENT_STOP_HOOKS: Vec<Arc<dyn StopHook<TurnCost>>>;}/// Clone the stop hooks active in the current task, if any.-pub fn current_stop_hooks() -> Vec<Arc<dyn StopHook>> {+pub fn current_stop_hooks() -> Vec<Arc<dyn StopHook<TurnCost>>> {CURRENT_STOP_HOOKS.try_with(Clone::clone).unwrap_or_default()@@ -67,7 +39,7 @@ pub fn current_stop_hooks() -> Vec<Arc<dyn StopHook>> {/// Scope a future with per-turn stop hooks.pub async fn with_stop_hooks<F: std::future::Future>(- hooks: Vec<Arc<dyn StopHook>>,+ hooks: Vec<Arc<dyn StopHook<TurnCost>>>,future: F,) -> F::Output {CURRENT_STOP_HOOKS.scope(hooks, future).await@@ -88,7 +60,7 @@ impl BudgetStopHook {}#[async_trait]-impl StopHook for BudgetStopHook {+impl StopHook<TurnCost> for BudgetStopHook {fn name(&self) -> &str {"budget"}diff --git a/crates/openhuman-core/src/agent/stop_hooks_tests.rs b/crates/openhuman-core/src/agent/stop_hooks_tests.rsindex 3201a4cb64..85f7787720 100644--- a/crates/openhuman-core/src/agent/stop_hooks_tests.rs+++ b/crates/openhuman-core/src/agent/stop_hooks_tests.rs@@ -56,7 +56,7 @@ async fn cancelled_scope_restores_the_callers_tool_limit() {#[tokio::test]async fn scoped_stop_hooks_are_visible_to_run_contexts() {- let hook: Arc<dyn StopHook> = Arc::new(BudgetStopHook::new(1.0));+ let hook: Arc<dyn StopHook<crate::agent::cost::TurnCost>> = 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();diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs b/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rsindex c9d6516212..8af158c0cf 100644--- a/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs@@ -77,7 +77,7 @@ struct RecordingBudgetStopHook {}#[async_trait]-impl StopHook for RecordingBudgetStopHook {+impl StopHook<crate::agent::cost::TurnCost> for RecordingBudgetStopHook {fn name(&self) -> &str {self.inner.name()}diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 0c2d02eccf..65e5ac5f6b 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -59,7 +59,7 @@ pub(super) fn assemble_turn_harness(context_window: Option<u64>,early_exit_tools: &[&str],context_mw: TurnContextMiddleware,- stop_hooks: Vec<Arc<dyn crate::agent::stop_hooks::StopHook>>,+ stop_hooks: Vec<Arc<dyn crate::agent::stop_hooks::StopHook<crate::agent::cost::TurnCost>>>,tool_policy: Option<ToolPolicyEnforcement>,required_capabilities: Option<CapabilitySet>,deterministic_cacheable: bool,@@ -324,7 +324,6 @@ pub(super) fn assemble_turn_harness(&mut harness,handle.as_ref(),model,- max_iterations,stop_hooks,halt_summary.clone(),);diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex 1557889d0f..7f9974823d 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -279,7 +279,7 @@ pub struct OpenHumanRunContext {/// UI/event progress receiver for this turn tree.pub progress: Option<Sender<AgentProgress>>,/// Stop policies evaluated after each model call.- pub stop_hooks: Vec<Arc<dyn StopHook>>,+ pub stop_hooks: Vec<Arc<dyn StopHook<crate::agent::cost::TurnCost>>>,/// Wall-clock deadline of the top-level turn this run belongs to, set/// only by the session turn entry point from the web backstop/// (`agent::turn_deadline`). The harness winds the run down and clampsdiff --git a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rsindex 2886980c13..fe29167870 100644--- a/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs+++ b/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs@@ -1,169 +1,43 @@-//! Mid-turn stop hooks as a `tinyagents` middleware (issue #4249).-//!-//! openhuman's policy-driven [`StopHook`]s (budget cap, thread-goal budget,-//! ad-hoc iteration ceiling) used to fire between iterations of the legacy-//! tool-call loop. That loop is gone — every turn now runs on the `tinyagents`-//! harness — so the firing point moves into a [`Middleware`]:-//!-//! - [`Middleware::after_model`] accumulates each completed model call's usage-//! into a per-turn [`TurnCost`] (the same accounting the hooks read), then-//! evaluates every installed hook with a [`TurnState`] snapshot.-//! - On the first [`StopDecision::Stop`], it sends [`SteeringCommand::Pause`] on-//! the run's steering handle. The agent loop drains steering at the **top** of-//! the next iteration (before the next model call) and `Pause` short-circuits-//! it cleanly — so the run stops before spending another call, returning the-//! partial transcript. This mirrors the [`CapPauser`](super::CapPauser)-//! model-call-cap mechanism.-//!-//! The hook list (the goal-budget hook) is handed to-//! [`StopHookMiddleware::new`]; the middleware is only registered when the list-//! is non-empty.+//! Host accounting and result projection for the harness-owned stop chain.-use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};-use std::sync::{Arc, Mutex};--use async_trait::async_trait;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};+use crate::agent::cost::TurnCost;+use crate::agent::stop_hooks::StopHook;+use std::sync::Arc;+use tinyagents_harness::middleware::library::{StopHookMetrics, StopHookMiddleware};+use tinyagents_harness::steering::SteeringHandle;use tinyinference_llm::model::ModelResponse;-use crate::agent::cost::TurnCost;-use crate::agent::stop_hooks::{StopDecision, StopHook, TurnState};+impl StopHookMetrics for TurnCost {+ fn record_model(&mut self, model: &str, response: &ModelResponse) {+ if let Some(usage) = super::model::usage_info_from_response(response) {+ self.add_call(model, &usage);+ }+ }+}-/// Install after-call usage policies on the assembled turn harness.+/// 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,- max_iterations: usize,- hooks: Vec<Arc<dyn StopHook>>,+ hooks: Vec<Arc<dyn StopHook<TurnCost>>>,halt_summary: super::HaltSummarySlot,) {- if let Some(handle) = handle.filter(|_| !hooks.is_empty()) {- harness.push_middleware(Arc::new(StopHookMiddleware::new(- handle.clone(),- model,- max_iterations,- hooks,- halt_summary,- )));- }-}--/// Fires openhuman [`StopHook`]s after each model call and pauses the run when-/// any hook votes to stop.-pub(super) struct StopHookMiddleware {- /// Steering handle the run was built with; `Pause` is sent here on stop.- handle: SteeringHandle,- /// Model name reported to hooks (and used for cost estimation).- model: String,- /// Configured model-call ceiling for this turn (the hooks' `max_iterations`).- max_iterations: u32,- /// 0-based count of completed model calls; incremented in `after_model`.- iteration: AtomicU32,- /// Per-turn usage tally the hooks read (`TurnState::cost`).- cost: Mutex<TurnCost>,- /// Installed hooks, snapshotted from the task-local at construction.- hooks: Vec<Arc<dyn StopHook>>,- /// Latches once a hook has voted to stop, so we send `Pause` exactly once.- stopped: AtomicBool,- halt_summary: super::HaltSummarySlot,-}--impl StopHookMiddleware {- /// Build a middleware firing `hooks`, pausing `handle` on the first stop.- pub(super) fn new(- handle: SteeringHandle,- model: impl Into<String>,- max_iterations: usize,- hooks: Vec<Arc<dyn StopHook>>,- halt_summary: super::HaltSummarySlot,- ) -> Self {- Self {- handle,- model: model.into(),- max_iterations: max_iterations.min(u32::MAX as usize) as u32,- iteration: AtomicU32::new(0),- cost: Mutex::new(TurnCost::new()),- hooks,- stopped: AtomicBool::new(false),- halt_summary,- }- }-}--#[async_trait]-impl<State, Ctx> Middleware<State, Ctx> for StopHookMiddleware-where- State: Send + Sync,- Ctx: Send + Sync,-{- fn name(&self) -> &str {- "openhuman.stop_hooks"- }-- async fn after_model(- &self,- _ctx: &mut RunContext<Ctx>,- _state: &State,- response: &mut ModelResponse,- ) -> tinyagents_harness::Result<()> {- // Already paused: nothing more to do (Pause is latched once).- if self.stopped.load(Ordering::SeqCst) {- return Ok(());- }-- // Fold this call's usage into the running turn cost (the same tally the- // budget/goal hooks read). Clone it back out so we never hold the mutex- // guard across the async hook checks below.- let iteration = self.iteration.fetch_add(1, Ordering::SeqCst) + 1;- let cost_snapshot = {- let mut cost = self.cost.lock().expect("stop-hook cost mutex poisoned");- if let Some(usage) = super::model::usage_info_from_response(response) {- cost.add_call(&self.model, &usage);- }- cost.clone()- };-- let turn_state = TurnState {- iteration,- max_iterations: self.max_iterations,- cost: &cost_snapshot,- model: &self.model,- };-- // Every observer sees the completed call, including observers installed- // after a budget policy. Preserve the first stop reason for the result.- let mut stop = None;- for hook in &self.hooks {- if let StopDecision::Stop { reason } = hook.check(&turn_state).await {- if stop.is_none() {- stop = Some((hook.name().to_owned(), reason));- }- }- }- if let Some((hook, reason)) = stop {- if self.stopped.swap(true, Ordering::SeqCst) {- return Ok(());- }- tracing::warn!(- target: "stop_hooks",- hook,- iteration,- model = %self.model,- "[stop_hooks] hook voted to stop the turn — pausing run: {reason}"- );- *self- .halt_summary- .lock()- .expect("stop-hook halt mutex poisoned") = Some(format!(- "Stopping after {} model call(s): {reason}",- iteration- ));- self.handle.send(SteeringCommand::Pause);- }-- Ok(())+ if handle.is_some() && !hooks.is_empty() {+ harness.push_middleware(Arc::new(+ StopHookMiddleware::new(model, hooks).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+ );+ *halt_summary.lock().expect("stop-hook halt mutex poisoned") = Some(format!(+ "Stopping after {} model call(s): {}",+ report.iteration, report.reason+ ));+ }),+ ));}}diff --git a/crates/openhuman-core/src/platform/cost/catalog.rs b/crates/openhuman-core/src/platform/cost/catalog.rsindex 5caa812c77..fd3ab4759d 100644--- a/crates/openhuman-core/src/platform/cost/catalog.rs+++ b/crates/openhuman-core/src/platform/cost/catalog.rs@@ -490,6 +490,20 @@ pub fn model_accepts_image_input(model_id: &str) -> bool {VISION_INPUT_MODELS.contains(&normalized.as_str()) || VISION_INPUT_MODELS.contains(&bare)}+/// Supply the product's flat list prices through the harness-owned pricing type.+pub fn tinyagents_pricing(price: &ModelPrice) -> tinyagents_harness::cost::ModelPricing {+ tinyagents_harness::cost::ModelPricing {+ input_per_token: per_token(price.input_per_mtok_usd),+ output_per_token: per_token(price.output_per_mtok_usd),+ cache_read_input_per_token: per_token(price.cached_input_per_mtok_usd),+ cache_creation_input_per_token: None,+ input_audio_per_token: None,+ output_reasoning_per_token: None,+ // The local price table is flat; context-size tiers are not modeled.+ tiers: Vec::new(),+ }+}+/// Project one OpenHuman catalog row into a TinyAgents model-catalog entry.////// This is intentionally a pricing/window projection only. OpenHuman still@@ -506,16 +520,7 @@ pub fn tinyagents_catalog_entry(price: &ModelPrice) -> tinyagents_registry::Modemax_output_tokens: None,deprecation_date: None,release_date: None,- pricing: tinyagents_harness::cost::ModelPricing {- input_per_token: per_token(price.input_per_mtok_usd),- output_per_token: per_token(price.output_per_mtok_usd),- cache_read_input_per_token: per_token(price.cached_input_per_mtok_usd),- cache_creation_input_per_token: None,- input_audio_per_token: None,- output_reasoning_per_token: None,- // The local price table is flat; context-size tiers are not modeled.- tiers: Vec::new(),- },+ pricing: tinyagents_pricing(price),capabilities: tinyagents_registry::ModelCapabilities {prompt_caching: price.cached_input_per_mtok_usd > 0.0,vision: model_accepts_image_input(price.model_id),