Skip to content

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

chore: files changed crates/openhuman-core/src/agent/cost.rs,crates/openhuman-core/src/agent/tinyage

Steven Enamakel5237177a3cca
diff --git a/crates/openhuman-core/src/agent/cost.rs b/crates/openhuman-core/src/agent/cost.rs
index 24bb95870a..949d25c96b 100644
--- a/crates/openhuman-core/src/agent/cost.rs
+++ b/crates/openhuman-core/src/agent/cost.rs
@@ -70,39 +70,64 @@ const PRICING_TABLE: &[ModelPricing] = &[
/// managed default's rate so an old cost record still estimates sanely.
const LEGACY_TIER_ROWS: &[&str] = &crate::config::LEGACY_TIER_MODELS;
-/// Look up pricing for a model name, falling back to [`FALLBACK_PRICING`].
+/// Zero-rate pricing for free model variants (OpenRouter's `…:free` ids).
+const FREE_PRICING: ModelPricing = ModelPricing {
+ model: "<free>",
+ input_per_mtok_usd: 0.0,
+ cached_input_per_mtok_usd: 0.0,
+ output_per_mtok_usd: 0.0,
+};
+
+/// Whether `model` names a free variant: OpenRouter's `vendor/model:free`
+/// suffix (case-insensitive, optionally behind a provider prefix such as
+/// `openrouter.` or `openrouter/`).
+pub(crate) fn is_free_model(model: &str) -> bool {
+ model.trim().to_ascii_lowercase().ends_with(":free")
+}
+
+/// Look up pricing for a model name when it is actually known, or `None`.
///
/// Resolution order:
-/// 1. Exact match on the managed default model (or a retired tier slug /
+/// 1. A free variant (`…:free`) is priced at zero.
+/// 2. Exact match on the managed default model (or a retired tier slug /
/// `hint:*` alias, which ran on it).
-/// 2. The concrete-vendor-model pricing catalog
+/// 3. The concrete-vendor-model pricing catalog
/// ([`crate::platform::cost::catalog`]) — accurate per-model rates for
/// `claude-*`, `gpt-*`, `gemini-*`, `deepseek-*`, `kimi-*`, `qwen-*`,
/// `mistral-*`, including OpenRouter-style `vendor/model` ids.
-/// 3. [`FALLBACK_PRICING`].
-pub(crate) fn lookup_pricing(model: &str) -> ModelPricing {
+///
+/// Reporting surfaces (trace export, journal roll-ups) use this so an unknown
+/// model records no cost rather than a made-up one.
+pub(crate) fn lookup_known_pricing(model: &str) -> Option<ModelPricing> {
let trimmed = model.trim();
+ if is_free_model(trimmed) {
+ return Some(FREE_PRICING);
+ }
if let Some(row) = PRICING_TABLE.iter().find(|row| row.model == trimmed) {
- return *row;
+ return Some(*row);
}
if trimmed.starts_with("hint:") || LEGACY_TIER_ROWS.contains(&trimmed) {
- return PRICING_TABLE[0];
- }
- if let Some(price) = crate::platform::cost::catalog::lookup(model) {
- return 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,
- };
+ return Some(PRICING_TABLE[0]);
}
- FALLBACK_PRICING
+ crate::platform::cost::catalog::lookup(model).map(|price| 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,
+ })
}
-/// Estimate the USD cost of a single provider call from its token
-/// usage. Used as a fallback when `charged_amount_usd` is missing.
-pub fn estimate_call_cost_usd(model: &str, usage: &BilledUsage) -> f64 {
- let pricing = lookup_pricing(model);
+/// Look up pricing for a model name, falling back to [`FALLBACK_PRICING`].
+///
+/// Same resolution as [`lookup_known_pricing`], plus the conservative
+/// fallback so budget caps still bite on an unknown model. Use it for budget
+/// enforcement only; reporting a cost should go through
+/// [`estimate_known_call_cost_usd`].
+pub(crate) fn lookup_pricing(model: &str) -> ModelPricing {
+ lookup_known_pricing(model).unwrap_or(FALLBACK_PRICING)
+}
+
+fn estimate_with(pricing: &ModelPricing, usage: &BilledUsage) -> f64 {
let cached = usage.cached_input_tokens();
let standard_input = usage.input_tokens.saturating_sub(cached);
let m = 1_000_000.0_f64;
@@ -111,6 +136,18 @@ pub fn estimate_call_cost_usd(model: &str, usage: &BilledUsage) -> f64 {
+ (usage.output_tokens as f64) / m * pricing.output_per_mtok_usd
}
+/// Estimate a call's USD cost from a known price, or `None` when the model's
+/// price is unknown (no fabricated fallback rate). Free variants cost `0`.
+pub fn estimate_known_call_cost_usd(model: &str, usage: &BilledUsage) -> Option<f64> {
+ lookup_known_pricing(model).map(|pricing| estimate_with(&pricing, usage))
+}
+
+/// Estimate the USD cost of a single provider call from its token
+/// usage. Used as a fallback when `charged_amount_usd` is missing.
+pub fn estimate_call_cost_usd(model: &str, usage: &BilledUsage) -> f64 {
+ estimate_with(&lookup_pricing(model), usage)
+}
+
/// Pick the most authoritative USD figure for a single provider call.
///
/// Backend-reported `charged_amount_usd` wins whenever it's > 0;
diff --git a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rs b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rs
new file mode 100644
index 0000000000..814affbb32
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rs
@@ -0,0 +1,147 @@
+//! Wind a top-level turn down before the outer backstop drops it.
+//!
+//! [`TurnDeadline`] puts the wind-down point at 780s under the default 900s
+//! web backstop. Once that point has passed, [`DeadlineWindDownMiddleware`]
+//! sends [`SteeringCommand::Pause`] at the next safe checkpoint: after a model
+//! call (that call's tool round still runs) or after a tool result (so a long
+//! sub-agent call is not followed by yet another model call). The loop drains
+//! the pause at the top of its next iteration, before any provider call. That
+//! is the same mechanism as the goal-budget and cap pauses
+//! ([`super::stop_hooks`]).
+//!
+//! A paused run has no final response, so the session driver's grounded close
+//! (`session_host::driver::grounded_close`) writes the user's answer from the
+//! completed tool results. The turn then commits like any other, and the user
+//! gets an answer instead of a dropped turn.
+//!
+//! [`install`] also clamps the harness `max_wall_clock_ms` to the deadline's
+//! hard stop. A single tool call that runs past the wind-down point is then
+//! ended by the harness's own typed `Timeout`, before the backstop drops the
+//! turn with nothing recorded.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Instant;
+
+use async_trait::async_trait;
+use tinyagents_harness::context::RunContext;
+use tinyagents_harness::middleware::Middleware;
+use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};
+use tinyagents_harness::AgentHarness;
+use tinyinference_llm::model::ModelResponse;
+use tinytools::ToolResult;
+
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+use crate::agent::turn_deadline::TurnDeadline;
+
+/// Pauses the run once its turn deadline's wind-down point has passed.
+pub(crate) struct DeadlineWindDownMiddleware {
+ handle: SteeringHandle,
+ deadline: TurnDeadline,
+ /// Latched on the first pause, so `Pause` is sent exactly once.
+ fired: Arc<AtomicBool>,
+}
+
+impl DeadlineWindDownMiddleware {
+ pub(crate) fn new(handle: SteeringHandle, deadline: TurnDeadline) -> Self {
+ Self {
+ handle,
+ deadline,
+ fired: Arc::new(AtomicBool::new(false)),
+ }
+ }
+
+ /// Whether this middleware has paused the run.
+ pub(crate) fn fired(&self) -> bool {
+ self.fired.load(Ordering::SeqCst)
+ }
+
+ /// Pause the run if the wind-down point has passed as of `now`. Returns
+ /// whether this call sent the pause.
+ pub(crate) fn maybe_pause(&self, checkpoint: &'static str, now: Instant) -> bool {
+ if !self.deadline.should_wind_down(now) || self.fired.swap(true, Ordering::SeqCst) {
+ return false;
+ }
+ tracing::warn!(
+ target: "turn_deadline",
+ checkpoint,
+ elapsed_ms = self.deadline.elapsed_at(now).as_millis() as u64,
+ wind_down_ms = self.deadline.wind_down_after().as_millis() as u64,
+ backstop_ms = self.deadline.backstop().as_millis() as u64,
+ "[turn_deadline] wind-down point passed; pausing the run so the turn closes with an answer before the backstop"
+ );
+ self.handle.send(SteeringCommand::Pause);
+ true
+ }
+}
+
+#[async_trait]
+impl<State, Ctx> Middleware<State, Ctx> for DeadlineWindDownMiddleware
+where
+ State: Send + Sync,
+ Ctx: Send + Sync,
+{
+ fn name(&self) -> &str {
+ "openhuman.deadline_wind_down"
+ }
+
+ async fn after_model(
+ &self,
+ _ctx: &mut RunContext<Ctx>,
+ _state: &State,
+ _response: &mut ModelResponse,
+ ) -> tinyagents_harness::Result<()> {
+ self.maybe_pause("after_model", Instant::now());
+ Ok(())
+ }
+
+ async fn after_tool(
+ &self,
+ _ctx: &mut RunContext<Ctx>,
+ _state: &State,
+ _invocation: &tinyagents_harness::middleware::ToolInvocationIdentity,
+ _result: &mut ToolResult,
+ ) -> tinyagents_harness::Result<()> {
+ self.maybe_pause("after_tool", Instant::now());
+ Ok(())
+ }
+}
+
+/// Install the wind-down for a run that carries a turn deadline, and clamp the
+/// harness wall-clock ceiling to its hard stop.
+///
+/// Children and runs without a deadline are left untouched. A synchronous
+/// child is bounded by its parent's tool-call budget, which the clamp already
+/// ends at the hard stop. Detached children must not inherit the deadline of
+/// the turn that spawned them.
+pub(super) fn install(
+ harness: &mut AgentHarness<(), OpenHumanRunContext>,
+ handle: Option<&SteeringHandle>,
+ deadline: Option<TurnDeadline>,
+ is_subagent: bool,
+) -> Option<Arc<DeadlineWindDownMiddleware>> {
+ let deadline = deadline.filter(|_| !is_subagent)?;
+ let now = Instant::now();
+ let mut policy = harness.policy().clone();
+ let configured = policy.limits.max_wall_clock_ms;
+ policy.limits.max_wall_clock_ms = deadline.clamp_wall_clock_ms(configured, now);
+ tracing::debug!(
+ target: "turn_deadline",
+ configured_ms = ?configured,
+ clamped_ms = ?policy.limits.max_wall_clock_ms,
+ elapsed_ms = deadline.elapsed_at(now).as_millis() as u64,
+ wind_down_ms = deadline.wind_down_after().as_millis() as u64,
+ hard_stop_ms = deadline.hard_stop_after().as_millis() as u64,
+ backstop_ms = deadline.backstop().as_millis() as u64,
+ "[turn_deadline] clamped harness wall clock to the turn's hard stop"
+ );
+ harness.with_policy(policy);
+ let handle = handle?;
+ let middleware = Arc::new(DeadlineWindDownMiddleware::new(handle.clone(), deadline));
+ harness.push_middleware(middleware.clone());
+ Some(middleware)
+}
+
+#[cfg(test)]
+#[path = "deadline_wind_down_tests.rs"]
+mod tests;