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(tokenjuice): move savings accounting into the tinyjuice module
Steven Enamakel8942ae8f45fa
diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/mod.rsindex f26836452e..d2c70cd49d 100644--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs@@ -120,12 +120,14 @@ pub(crate) fn install_request(config: &crate::config::Config) -> InstallRequestpub async fn install_from_config(config: &crate::config::Config) -> Result<(), String> {savings::configure(+ &client(config),config.default_model.clone().unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string()),&config.workspace_dir,- );+ )+ .await?;let request = install_request(config);let fingerprint = serde_json::to_vec(&request).map_err(|error| error.to_string())?;static INSTALLED: std::sync::OnceLock<tokio::sync::Mutex<Option<Vec<u8>>>> =diff --git a/crates/openhuman-core/src/inference/tokenjuice/savings.rs b/crates/openhuman-core/src/inference/tokenjuice/savings.rsindex 6ac67758b8..1a07411427 100644--- a/crates/openhuman-core/src/inference/tokenjuice/savings.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/savings.rs@@ -1,202 +1,120 @@-//! Compaction savings accounting — how many tokens (and $$) the content router-//! has saved.+//! Host adapter for compaction savings accounting.//!-//! Every time the router compacts a tool result it records the estimated tokens-//! before/after and the cost that would have been paid to send the dropped-//! tokens as **input** to the LLM the result is being compressed for. Cost uses-//! the per-model input price from [`crate::agent::cost`].+//! The aggregate math, the per-model and per-compressor buckets and the+//! snapshot at `workspace_dir/state/tokenjuice_savings.json` live in the+//! tinyjuice module (`ConfigureSavings` / `RecordSavings` / `SavingsStats` /+//! `ResetSavings`). OpenHuman keeps only what is policy: which model the+//! saving is attributed to and the USD price per input token from+//! [`crate::agent::cost`].//!-//! Deliberately local, not on the storage port: the aggregate is one-//! process-global counter (not per user) that is cheap to lose, so a per-agent-//! scoped document would not mean what the number means. Allowlisted in+//! The snapshot is deliberately local, not on the storage port: it is one+//! process-global counter that is cheap to lose. Allowlisted in//! `scripts/ci/check-storage-bypass.mjs`.-//!-//! Aggregates are kept process-global and snapshotted to-//! `workspace_dir/state/tokenjuice_savings.json` so the dashboard survives-//! restarts. The configured default model and snapshot path are installed via-//! [`configure`].-use std::collections::HashMap;-use std::path::PathBuf;use std::sync::{Mutex, OnceLock};-use serde::{Deserialize, Serialize};--use {tinyjuice_bus::types::CompressorKind, tinyjuice_bus::types::ContentKind};--/// Per-key (model / compressor) rolled-up savings.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SavingsBucket {- pub events: u64,- pub original_tokens: u64,- pub compacted_tokens: u64,- pub tokens_saved: u64,- pub cost_saved_usd: f64,-}+use tinyjuice_bus::names::methods;+pub use tinyjuice_bus::savings::{RecordSavingsRequest, SavingsAggregate, SavingsBucket};+use tinyjuice_bus::types::CompressorKind;-impl SavingsBucket {- fn add(&mut self, original: u64, compacted: u64, cost: f64) {- self.events += 1;- self.original_tokens += original;- self.compacted_tokens += compacted;- self.tokens_saved += original.saturating_sub(compacted);- self.cost_saved_usd += cost;- }-}+const MODULE: &str = "tinyjuice";-/// The full savings snapshot returned to callers / the dashboard.-#[derive(Debug, Clone, Default, Serialize, Deserialize)]-#[serde(rename_all = "camelCase")]-pub struct SavingsAggregate {- /// Overall totals across every compaction.- pub total: SavingsBucket,- /// Breakdown by the model the savings were attributed to.- pub by_model: HashMap<String, SavingsBucket>,- /// Breakdown by which compressor produced the saving.- pub by_compressor: HashMap<String, SavingsBucket>,+/// Model used to price the saved input tokens (the configured default).+fn model_slot() -> &'static Mutex<String> {+ static SLOT: OnceLock<Mutex<String>> = OnceLock::new();+ SLOT.get_or_init(|| Mutex::new(crate::config::DEFAULT_MODEL.to_string()))}-impl SavingsAggregate {- /// Fold one compaction's savings into the aggregate, attributed to `model`.- /// Caller guarantees `original > compacted`. Pure (no global state) so it is- /// unit-testable without touching the process-global aggregate.- fn record_saving(&mut self, model: &str, compressor: &str, original: u64, compacted: u64) {- let cost = cost_saved_usd(model, original.saturating_sub(compacted));- self.total.add(original, compacted, cost);- self.by_model- .entry(model.to_string())- .or_default()- .add(original, compacted, cost);- self.by_compressor- .entry(compressor.to_string())- .or_default()- .add(original, compacted, cost);- }-}--struct State {- aggregate: SavingsAggregate,- /// Model used to price the saved input tokens (the configured default).+/// Install the attribution model (host policy) and point the module at the+/// snapshot location; the module loads a prior snapshot once per path.+pub async fn configure(+ client: &crate::modules::client::ModuleClient,attribution_model: String,- /// Where the snapshot is persisted; `None` ⇒ in-memory only.- snapshot_path: Option<PathBuf>,-}--impl Default for State {- fn default() -> Self {- Self {- aggregate: SavingsAggregate::default(),- attribution_model: crate::config::DEFAULT_MODEL.to_string(),- snapshot_path: None,- }+ workspace_dir: &std::path::Path,+) -> Result<(), String> {+ if !attribution_model.trim().is_empty() {+ *model_slot().lock().unwrap_or_else(|p| p.into_inner()) = attribution_model;}+ let path = workspace_dir.join("state").join("tokenjuice_savings.json");+ client+ .call::<()>(+ MODULE,+ methods::CONFIGURE_SAVINGS,+ (path.to_string_lossy().into_owned(),),+ )+ .await+ .map_err(|e| e.to_string())}-fn state() -> &'static Mutex<State> {- static STATE: OnceLock<Mutex<State>> = OnceLock::new();- STATE.get_or_init(|| Mutex::new(State::default()))+/// The model savings are currently attributed to.+pub fn attribution_model() -> String {+ model_slot()+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .clone()}-/// Install the configured-default attribution model and snapshot location,-/// loading a prior snapshot once per workspace.-pub fn configure(attribution_model: String, workspace_dir: &std::path::Path) {- let path = workspace_dir.join("state").join("tokenjuice_savings.json");- let mut st = state().lock().unwrap_or_else(|p| p.into_inner());- if !attribution_model.trim().is_empty() {- st.attribution_model = attribution_model;- }- // Module calls apply host configuration lazily. Do not reload the snapshot- // on every tool result: besides needless I/O, a concurrent call could have- // read the file just before another call persisted a saving and then replace- // the newer in-memory aggregate with that stale copy.- if st.snapshot_path.as_ref() == Some(&path) {- return;- }- let loaded = std::fs::read_to_string(&path)- .ok()- .and_then(|s| serde_json::from_str::<SavingsAggregate>(&s).ok());- st.snapshot_path = Some(path);- if let Some(agg) = loaded {- st.aggregate = agg;- }+/// USD per million input tokens for `model`; `None` for a model the catalog+/// does not price, so the saving is counted in tokens only, never guessed.+fn input_per_mtok_usd(model: &str) -> Option<f64> {+ crate::agent::cost::lookup_pricing(model)+ .and_then(|pricing| pricing.input_per_token)+ .map(|per_token| per_token * 1_000_000.0)}-/// Record one compaction's savings. `original_tokens`/`compacted_tokens` are the-/// pre/post estimates; the cost saved prices the dropped tokens as input to the-/// attribution model.-pub fn record(- content_kind: ContentKind,+/// Build the module request for one compaction, or `None` when nothing shrank.+fn request(compressor: CompressorKind,original_tokens: u64,compacted_tokens: u64,-) {+) -> Option<RecordSavingsRequest> {if original_tokens <= compacted_tokens {- return;+ return None;}- let mut st = state().lock().unwrap_or_else(|p| p.into_inner());- let attribution_model = st.attribution_model.clone();- st.aggregate.record_saving(- &attribution_model,- compressor.as_str(),+ let model = attribution_model();+ Some(RecordSavingsRequest {+ input_per_mtok_usd: input_per_mtok_usd(&model),+ model,+ compressor: compressor.as_str().to_string(),original_tokens,compacted_tokens,- );-- let _ = content_kind; // reserved for a future by-kind breakdown- persist(&st);-}--/// Cost (USD) of sending `tokens_saved` as input to `model`, using the per-model-/// input price. Tool results enter the next turn's context as input tokens, so-/// the input price is the relevant rate. `0.0` for a model the catalog does-/// not price: the saving is then counted in tokens only, not guessed in USD.-fn cost_saved_usd(model: &str, tokens_saved: u64) -> f64 {- crate::agent::cost::lookup_pricing(model).map_or(0.0, |pricing| {- (tokens_saved as f64) * pricing.input_per_token.unwrap_or(0.0)})}-fn persist(st: &State) {- let Some(path) = st.snapshot_path.as_ref() else {+/// Record one compaction's savings through the module.+pub async fn record(+ client: &crate::modules::client::ModuleClient,+ compressor: CompressorKind,+ original_tokens: u64,+ compacted_tokens: u64,+) {+ let Some(req) = request(compressor, original_tokens, compacted_tokens) else {return;};- if let Some(parent) = path.parent() {- let _ = std::fs::create_dir_all(parent);+ if let Err(e) = client+ .call::<()>(MODULE, methods::RECORD_SAVINGS, (req,))+ .await+ {+ log::debug!("[tokenjuice][savings] record failed: {e}");}- match serde_json::to_string(&st.aggregate) {- Ok(json) => {- if let Err(e) = std::fs::write(path, json) {- log::debug!("[tokenjuice][savings] snapshot write failed: {e}");- }- }- Err(e) => log::debug!("[tokenjuice][savings] snapshot serialize failed: {e}"),- }-}--/// Snapshot the current savings aggregate.-pub fn stats() -> SavingsAggregate {- state()- .lock()- .unwrap_or_else(|p| p.into_inner())- .aggregate- .clone()}-/// The model savings are currently attributed to.-pub fn attribution_model() -> String {- state()- .lock()- .unwrap_or_else(|p| p.into_inner())- .attribution_model- .clone()+/// Snapshot the module's savings aggregate.+pub async fn stats(+ client: &crate::modules::client::ModuleClient,+) -> Result<SavingsAggregate, String> {+ client+ .call(MODULE, methods::SAVINGS_STATS, ())+ .await+ .map_err(|e| e.to_string())}/// Clear all recorded savings (and the persisted snapshot).-pub fn reset() {- let mut st = state().lock().unwrap_or_else(|p| p.into_inner());- st.aggregate = SavingsAggregate::default();- persist(&st);+pub async fn reset(client: &crate::modules::client::ModuleClient) -> Result<(), String> {+ client+ .call::<()>(MODULE, methods::RESET_SAVINGS, ())+ .await+ .map_err(|e| e.to_string())}#[cfg(test)]diff --git a/crates/openhuman-core/src/inference/tokenjuice/savings_tests.rs b/crates/openhuman-core/src/inference/tokenjuice/savings_tests.rsindex ae498d9bd2..953a9842c7 100644--- a/crates/openhuman-core/src/inference/tokenjuice/savings_tests.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/savings_tests.rs@@ -1,48 +1,26 @@use super::*;#[test]-fn records_and_aggregates() {- // Use a fresh local state to avoid clobbering the process-global one.- let mut agg = SavingsAggregate::default();- let cost = cost_saved_usd("claude-sonnet-4-6", 1000);- agg.total.add(2000, 1000, cost);- agg.by_compressor- .entry("smartcrusher".into())- .or_default()- .add(2000, 1000, cost);- assert_eq!(agg.total.tokens_saved, 1000);- assert!(agg.total.cost_saved_usd > 0.0);- assert_eq!(agg.by_compressor["smartcrusher"].events, 1);+fn input_price_is_per_million_tokens() {+ let p = input_per_mtok_usd("claude-sonnet-4-6").expect("catalogued model");+ assert!((p - 3.0).abs() < 1e-6, "got {p}");}#[test]-fn cost_uses_input_price() {- // Catalogued model input pricing is used for saved-token cost estimates.- let c = cost_saved_usd("claude-sonnet-4-6", 1_000_000);- assert!((c - 3.0).abs() < 1e-6, "got {c}");+fn unpriced_model_has_no_price() {+ assert_eq!(input_per_mtok_usd("no-such-model-xyz"), None);}#[test]-fn no_record_when_not_smaller() {- let before = stats().total.events;- record(ContentKind::Json, CompressorKind::SmartCrusher, 100, 100);- record(ContentKind::Json, CompressorKind::SmartCrusher, 50, 100);- assert_eq!(stats().total.events, before, "no-op when not smaller");+fn no_request_when_not_smaller() {+ assert!(request(CompressorKind::SmartCrusher, 100, 100).is_none());+ assert!(request(CompressorKind::SmartCrusher, 50, 100).is_none());}#[test]-fn record_saving_attributes_to_given_model() {- // Pure aggregation on a LOCAL aggregate — no process-global state, so it- // cannot race the other tests in this module.- let mut agg = SavingsAggregate::default();- agg.record_saving("turn-model-x", "smartcrusher", 2000, 1000);- assert_eq!(agg.total.tokens_saved, 1000);- assert!(- agg.by_model.contains_key("turn-model-x"),- "saving must be attributed to the supplied model"- );- assert_eq!(- agg.by_model["turn-model-x"].cost_saved_usd, 0.0,- "an unknown model has no estimated monetary saving"- );+fn request_carries_attribution_and_token_counts() {+ let req = request(CompressorKind::SmartCrusher, 2000, 1000).unwrap();+ assert_eq!(req.model, attribution_model());+ assert_eq!(req.compressor, CompressorKind::SmartCrusher.as_str());+ assert_eq!((req.original_tokens, req.compacted_tokens), (2000, 1000));}