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(tinyagents): add cost budget and memory pack middleware
Steven Enamakel6ccdd930e254
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex edb933ea90..ed9004b72a 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -647,7 +647,7 @@ pub(super) fn assemble_turn_harness(// `ArgRecoveryMiddleware` so it wraps recovered arguments; before the// embedder hooks so they observe the call that actually runs.let registered_tools = harness.tools().names();- harness.push_middleware(Arc::new(middleware::PackedToolRouteMiddleware::new(+ harness.push_middleware(Arc::new(middleware::packed_tool_route_middleware(registered_tools,route_session,)));@@ -684,7 +684,7 @@ pub(super) fn assemble_turn_harness(// The turn's memory pack rides every request of the turn, after every// reduction step and after the transcript snapshot, so it is never// compacted, trimmed or persisted (`memory::lifecycle::hooks::pre_turn`).- harness.push_middleware(Arc::new(middleware::MemoryPackMiddleware));+ harness.push_middleware(Arc::new(middleware::memory_pack_middleware()));AssembledTurnHarness {harness,diff --git a/crates/openhuman-core/src/agent/tinyagents/live_harness.rs b/crates/openhuman-core/src/agent/tinyagents/live_harness.rsindex 92f3e715a6..efa119d78e 100644--- a/crates/openhuman-core/src/agent/tinyagents/live_harness.rs+++ b/crates/openhuman-core/src/agent/tinyagents/live_harness.rs@@ -117,7 +117,7 @@ pub(crate) fn assemble_live_tool_harness(harness.push_tool_middleware(Arc::new(middleware::credential_scrub_middleware()));harness.push_middleware(Arc::new(ArgRecoveryMiddleware::new(tool_sets.clone())));let registered_tools = harness.tools().names();- harness.push_middleware(Arc::new(middleware::PackedToolRouteMiddleware::new(+ harness.push_middleware(Arc::new(middleware::packed_tool_route_middleware(registered_tools,route_session,)));diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rsindex 8dcc296f81..bc54e8d391 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs@@ -26,7 +26,6 @@mod approval;mod cli_rpc_only;-mod cost_budget;mod credential_scrub;mod embedder_hooks;mod failure_policy;@@ -42,11 +41,10 @@ mod turn_context;pub(crate) use approval::ApprovalSecurityMiddleware;pub(crate) use cli_rpc_only::CliRpcOnlyMiddleware;-pub(crate) use cost_budget::CostBudgetMiddleware;pub(crate) use credential_scrub::credential_scrub_middleware;pub(crate) use embedder_hooks::EmbedderToolHooksMiddleware;-pub(crate) use memory_pack::MemoryPackMiddleware;-pub(crate) use packed_tool_route::PackedToolRouteMiddleware;+pub(crate) use memory_pack::memory_pack_middleware;+pub(crate) use packed_tool_route::packed_tool_route_middleware;pub(crate) use repeated_failure::RepeatedToolFailureMiddleware;pub(crate) use tool_exposure::OpenHumanToolExposureShadowMiddleware;pub(crate) use tool_outcome_capture::ToolOutcomeCaptureMiddleware;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rsdeleted file mode 100644index 8361fdb737..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/cost_budget.rs+++ /dev/null@@ -1,121 +0,0 @@-//! [`CostBudgetMiddleware`]: token-accounting parity observer. It used to-//! enforce daily/monthly cost budgets before a model-//! call spends, and shadow-compare token accounting against the crate-//! `BudgetMiddleware`.--use async_trait::async_trait;--use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::{AgentRun, BudgetTracker, Middleware};--/// Token-accounting parity observer. It once enforced OpenHuman's-/// daily/monthly cost budgets before a model call spent (issue #4249, Phase 5),-/// failing the run before the provider call when a budget was already-/// exceeded. That cap is gone and nothing here refuses any more; a warning-/// threshold logs but proceeds. This enforcement path stays **authoritative**.-///-/// Self-gating: a no-op unless a global tracker exists and `config.enabled` with-/// a limit is set (`check_budget` returns `Allowed` otherwise). Complements the-/// post-call `StopHookMiddleware` per-turn USD cap. Projecting the *next* call's-/// cost pre-spend (vs the already-exceeded check here) needs an input-token-/// estimate — a follow-up.-///-/// # Shadow role (W2-budget-dedupe)-///-/// When built with [`with_shadow`](Self::with_shadow), this middleware is ALSO a-/// divergence-logging shadow over the observe-only crate-/// [`BudgetMiddleware`](tinyagents_harness::middleware::BudgetMiddleware). It-/// keeps enforcing exactly as before, but at `after_agent` it compares the-/// crate `BudgetMiddleware`'s shared [`BudgetTracker`] accumulation against the-/// authoritative runtime [`AgentRun::usage`] and logs `[budget_shadow]` parity-/// or divergence (compact numeric summary; no PII). Both accumulate the same-/// per-call `response.usage`, so token totals must match once the crate-/// middleware is on the path — this is the parity signal that must be clean-/// before enforcement can flip to the crate owner (see the flip-criteria comment-/// at the registration site in `tinyagents/mod.rs`). Cost is intentionally NOT-/// compared: the observe-only crate middleware has no pricing table, so its cost-/// stays zero while the local path prices via `cost::catalog` — cost parity is a-/// flip-criteria follow-up.-pub(crate) struct CostBudgetMiddleware {- /// Observe-only crate `BudgetMiddleware`'s shared tracker handle, for the- /// end-of-run `[budget_shadow]` comparison. `None` when the shadow is not- /// installed (isolated unit tests of the enforcement gate).- shadow_tracker: Option<BudgetTracker>,-}--impl CostBudgetMiddleware {- /// Enforcement-only gate with no shadow comparison (isolated unit tests).- pub(crate) fn new() -> Self {- Self {- shadow_tracker: None,- }- }-- /// Enforcement gate that ALSO compares its per-run token accounting against- /// the observe-only crate `BudgetMiddleware`'s shared `tracker` at end of run- /// and logs `[budget_shadow]` parity/divergence.- pub(crate) fn with_shadow(tracker: BudgetTracker) -> Self {- Self {- shadow_tracker: Some(tracker),- }- }-}--#[async_trait]-impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for CostBudgetMiddleware {- fn name(&self) -> &str {- "cost_budget"- }-- /// Shadow parity check (W2-budget-dedupe). This middleware no longer- /// enforces anything — the spend cap is gone — so observing is all it- /// does. Compares the observe-only- /// crate `BudgetMiddleware`'s accumulated token spend against the runtime's- /// authoritative `AgentRun::usage` and logs `[budget_shadow]` divergence.- /// Never fails the run.- async fn after_agent(- &self,- _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- _state: &(),- run: &mut AgentRun,- ) -> TaResult<()> {- let Some(tracker) = &self.shadow_tracker else {- return Ok(());- };- let crate_usage = tracker.snapshot().usage; // UsageTotals (crate shadow)- let local = run.usage; // UsageTotals (runtime authoritative)- let l = &local.usage;- let c = &crate_usage.usage;- let diverged = l.input_tokens != c.input_tokens- || l.output_tokens != c.output_tokens- || l.cache_read_tokens != c.cache_read_tokens- || l.total_tokens != c.total_tokens- || local.calls != crate_usage.calls;- if diverged {- tracing::warn!(- local_calls = local.calls,- crate_calls = crate_usage.calls,- local_in = l.input_tokens,- crate_in = c.input_tokens,- local_out = l.output_tokens,- crate_out = c.output_tokens,- local_cached = l.cache_read_tokens,- crate_cached = c.cache_read_tokens,- local_total = l.total_tokens,- crate_total = c.total_tokens,- "[budget_shadow] divergence: crate BudgetMiddleware token accounting differs from authoritative AgentRun.usage"- );- } else {- tracing::debug!(- calls = local.calls,- input = l.input_tokens,- output = l.output_tokens,- cached = l.cache_read_tokens,- total = l.total_tokens,- "[budget_shadow] parity: crate BudgetMiddleware token accounting matches AgentRun.usage"- );- }- Ok(())- }-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rsindex b3c7951e2f..08d241f8a9 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs@@ -1,62 +1,37 @@-//! Request-scoped delivery of the turn's memory pack.+//! Host source for the harness `MemoryPackMiddleware`.//!//! The session host recalls one pack per turn before the model runs//! (`memory::lifecycle::hooks::pre_turn`) and parks it on the run context-//! (`OpenHumanRunContext::memory_turn`). This middleware adds it to every model-//! request of that turn with [`push_ephemeral_instruction`]: a tail system-//! message, or on a model that hoists system turns (DeepSeek, native-//! Anthropic) a note on the tail user or tool message. The request is built-//! from a copy of the working transcript, so the pack is never committed —-//! the thread's persisted history and the provider's cached prefix stay-//! exactly as they were.+//! (`OpenHumanRunContext::memory_turn`). The harness middleware adds+//! [`TurnMemoryPack`]'s text to every model request of that turn as an+//! ephemeral instruction, so the pack is never committed to the thread's+//! history or the provider's cached prefix.-use async_trait::async_trait;--use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::{push_ephemeral_instruction, Middleware};-use tinyinference_llm::model::ModelRequest;+use tinyagents_harness::middleware::MemoryPackSource;use crate::agent::tinyagents::host::OpenHumanRunContext;-/// Adds the turn's memory pack to each of its model requests.-pub(crate) struct MemoryPackMiddleware;--#[async_trait]-impl Middleware<(), OpenHumanRunContext> for MemoryPackMiddleware {- fn name(&self) -> &str {- "memory_pack"- }+/// Reads the turn's memory pack off the OpenHuman run context.+pub(crate) struct TurnMemoryPack;- fn is_observer(&self) -> bool {- true- }-- async fn before_model(- &self,- ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- request: &mut ModelRequest,- ) -> TaResult<()> {- let Some(pack) = ctx- .data- .memory_turn- .as_ref()- .and_then(|turn| turn.pack.as_ref())- else {- return Ok(());- };- let injection = pack.injection();+impl MemoryPackSource<OpenHumanRunContext> for TurnMemoryPack {+ fn injection(&self, data: &OpenHumanRunContext) -> Option<String> {+ let pack = data.memory_turn.as_ref()?.pack.as_ref()?;tracing::trace!(tokens = pack.tokens,refs = pack.refs.len(),"[tinyagents::mw] memory pack added to the model request");- push_ephemeral_instruction(request, injection, ctx.model_profile.as_ref());- Ok(())+ Some(pack.injection())}}+/// The harness middleware over [`TurnMemoryPack`].+pub(crate) fn memory_pack_middleware(+) -> tinyagents_harness::middleware::MemoryPackMiddleware<OpenHumanRunContext, TurnMemoryPack> {+ tinyagents_harness::middleware::MemoryPackMiddleware::new(TurnMemoryPack)+}+#[cfg(test)]#[path = "memory_pack_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rsindex a327583cbe..3af3b61c40 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs@@ -41,7 +41,7 @@ async fn the_pack_rides_every_request_of_the_turn() {for _ in 0..2 {let mut request = ModelRequest::new(history.clone());- MemoryPackMiddleware+ memory_pack_middleware().before_model(&mut ctx, &(), &mut request).await.unwrap();@@ -61,7 +61,7 @@ async fn the_pack_rides_every_request_of_the_turn() {async fn a_turn_without_a_pack_is_left_alone() {let mut ctx = context(None);let mut request = ModelRequest::new(vec![Message::user("hi")]);- MemoryPackMiddleware+ memory_pack_middleware().before_model(&mut ctx, &(), &mut request).await.unwrap();@@ -91,7 +91,7 @@ async fn request_for(let mut ctx = context(Some(pack));ctx.model_profile = profile;let mut request = ModelRequest::new(history.to_vec());- MemoryPackMiddleware+ memory_pack_middleware().before_model(&mut ctx, &(), &mut request).await.unwrap();diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rsindex da3fef0a99..77125b0c18 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs@@ -1,135 +1,46 @@-//! [`PackedToolRouteMiddleware`]: route a call that names a withheld packed tool-//! by its bare name through `use_skill`, instead of answering "unknown tool".--use std::collections::HashSet;--use async_trait::async_trait;-use serde_json::{json, Value};--use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::Middleware;-use tinyinference_llm::tool::ToolCall as TaToolCall;--use crate::tools::toolpacks::{self, GroupMode};+//! Host router for the harness `PackedToolRouteMiddleware`: route a call that+//! names a withheld packed tool by its bare name through `use_skill`, instead+//! of answering "unknown tool" (#6276).+//!+//! The rewrite mechanism lives in the harness. This file keeps the policy+//! only: a tool is routed where the turn's tool-policy session lets it run+//! (`session.decision_for(name).blocks_execution()` is false), a pack owns it,+//! and that pack's group is `Withheld`. No session (sub-agent, channel/CLI+//! turns) means no routing, so the registration allowlist stays the boundary.++use tinyagents_harness::middleware::{PackedToolRouteMiddleware, PackedToolRouter};use tinyagents_harness::tool::packs::USE_SKILL;use tinytools::ToolPolicySession;-/// `before_tool`: rewrite `name(args)` into-/// `use_skill { "skill": <pack>, "tool": name, "args": args }` when `name` is a-/// withheld packed tool this turn did not register (#6276).-///-/// A pack withholds a tool's schema, not its name. The pack listing documents-/// every tool under its bare name, and sibling descriptions and prompts refer to-/// it the same way, so a model calls that name as a top-level tool. The crate's-/// unknown-tool answer lists only the registered tools and never says the tool-/// exists behind a pack: live turns re-read the listing and repeated the bare-/// call until the turn ran out, and nothing was ever run.-///-/// **Only where the session says the tool may run.** Routing is gated on the-/// same predicate `ToolPolicyMiddleware` applies to `use_skill`'s inner tool and-/// the pack listing applies to what it shows:-/// `session.decision_for(name).blocks_execution()`. That decision is `Deny` for a-/// name the session does not have, so a tool outside this agent's registry, over-/// the channel ceiling, or refused by policy is never routed. The gate lives here-/// rather than relying on the gate downstream, so a blocked tool keeps the-/// crate's `unknown tool` answer instead of being rewritten at all.-///-/// **No session, no routing.** Sub-agent and channel/CLI turns carry no-/// tool-policy session: they bound their tools with the registration allowlist,-/// they never withhold packs, and nothing on those paths checks `use_skill`'s-/// inner tool. There an unregistered packed name was excluded by the allowlist,-/// so rewriting it into `use_skill` would walk around that boundary.-///-/// When it does route, the rewrite happens ahead of admission, so the call then-/// goes through what an explicit `use_skill` call goes through: schema-/// validation, the approval gate, the CLI-only gate, `ToolPolicyMiddleware`, and-/// permission forwarding. Routing rather than an error because the intent is-/// unambiguous (the name is in the compiled pack table), and an error would spend-/// a round trip telling the model to make this same call.-///-/// Left alone, so the crate's own recovery answers:-/// * a name no pack owns (a hallucinated tool),-/// * a registered name (a pack owner keeps its belt advertised),-/// * a turn without `use_skill`, where the tool has no route at all,-/// * a turn without a tool-policy session (sub-agent, channel/CLI),-/// * a tool the session blocks,-/// * a group that is not `Withheld` (`Off` is not registered anywhere),-/// * arguments that failed to parse or are not an object.-pub(crate) struct PackedToolRouteMiddleware {- /// Tool names registered on this turn's harness.- registered: HashSet<String>,- /// This turn's tool-policy snapshot; `None` disables routing.+use crate::agent::tinyagents::host::OpenHumanRunContext;+use crate::tools::toolpacks::{self, GroupMode};++/// This turn's tool-policy snapshot; `None` disables routing.+pub(crate) struct SessionPackRouter {session: Option<ToolPolicySession>,}-impl PackedToolRouteMiddleware {- /// Build the middleware over the names this turn registered and the turn's- /// tool-policy session, if it has one.- pub(crate) fn new(- registered: impl IntoIterator<Item = String>,- session: Option<ToolPolicySession>,- ) -> Self {- Self {- registered: registered.into_iter().collect(),- session,+impl PackedToolRouter<OpenHumanRunContext> for SessionPackRouter {+ fn pack_for(&self, _data: &OpenHumanRunContext, tool: &str) -> Option<String> {+ let session = self.session.as_ref()?;+ if session.decision_for(tool).blocks_execution() {+ return None;}- }-- /// Rewrite `call` in place when it should be routed; `true` if it was.- fn route(&self, call: &mut TaToolCall) -> bool {- if call.invalid.is_some()- || self.registered.contains(&call.name)- || !self.registered.contains(USE_SKILL)- {- return false;- }- let Some(session) = &self.session else {- return false;- };- if session.decision_for(&call.name).blocks_execution() {- return false;+ let pack = toolpacks::pack_for_tool(tool)?;+ if toolpacks::groups::current().mode_for_tool(tool) != GroupMode::Withheld {+ return None;}- let Some(pack) = toolpacks::pack_for_tool(&call.name) else {- return false;- };- if toolpacks::groups::current().mode_for_tool(&call.name) != GroupMode::Withheld {- return false;- }- let args = match call.arguments {- Value::Object(_) => call.arguments.take(),- Value::Null => json!({}),- _ => return false,- };- let tool = std::mem::replace(&mut call.name, USE_SKILL.to_string());- tracing::info!(- tool = %tool,- skill = pack.id,- call_id = %call.id,- "[toolpacks] routed bare packed tool call through use_skill"- );- call.arguments = json!({ "skill": pack.id, "tool": tool, "args": args });- true+ Some(pack.id.to_string())}}-#[async_trait]-impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>- for PackedToolRouteMiddleware-{- fn name(&self) -> &str {- "packed_tool_route"- }-- async fn before_tool(- &self,- _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- _state: &(),- call: &mut TaToolCall,- ) -> TaResult<()> {- self.route(call);- Ok(())- }+/// Build the harness middleware over the names this turn registered and the+/// turn's tool-policy session, if it has one.+pub(crate) fn packed_tool_route_middleware(+ registered: impl IntoIterator<Item = String>,+ session: Option<ToolPolicySession>,+) -> PackedToolRouteMiddleware<OpenHumanRunContext, SessionPackRouter> {+ PackedToolRouteMiddleware::new(registered, USE_SKILL, SessionPackRouter { session })}#[cfg(test)]