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
chore: files changed crates/openhuman-core/src/threads/ops/usage.rs,crates/openhuman-core/src/thread
Steven Enamakel5996de5aaa7f
diff --git a/crates/openhuman-core/src/threads/ops/usage.rs b/crates/openhuman-core/src/threads/ops/usage.rsindex 0a8f2a5ba2..f4da1026af 100644--- a/crates/openhuman-core/src/threads/ops/usage.rs+++ b/crates/openhuman-core/src/threads/ops/usage.rs@@ -3,11 +3,7 @@use super::support::{counts, envelope, workspace_dir};use crate::core::Outcome;use crate::memory::ApiEnvelope;-use std::collections::BTreeMap;-use std::path::Path;-use tinyagents_session::transcript::{- find_root_transcripts_for_thread, read_transcript, SessionTranscript,-};+use tinyagents_session::transcript::spend::thread_spend;/// Request for [`token_usage`]: the thread whose persisted usage to total.#[derive(Debug, Clone, serde::Deserialize)]@@ -56,202 +52,6 @@ pub struct SubagentUsageDto {pub runs: usize,}-/// One transcript's own spend, summed from the per-turn `turn_usage` records-/// the codec attaches to its assistant rows.-#[derive(Debug, Clone, Default, PartialEq)]-pub(super) struct TranscriptSpend {- pub(super) input_tokens: u64,- pub(super) output_tokens: u64,- pub(super) cached_input_tokens: u64,- pub(super) cost_usd: f64,- /// Turns that recorded usage. The codec emits one record per durable- /// append, and omits an all-zero one, so this is "turns that spent".- pub(super) turns: usize,- /// The newest record's model and window, for the caller's last-turn view.- pub(super) last_input_tokens: u64,- pub(super) last_output_tokens: u64,- pub(super) model: Option<String>,- pub(super) context_window: u64,-}--/// Total one transcript file's own recorded spend.-///-/// The `_meta` header carries denormalised rollups for the same figures, but-/// nothing has written them on the root path since the TinyAgents runtime-/// cutover (`33566d382`) — every root transcript since reads `input_tokens: 0`-/// while its per-turn records hold the real numbers (#6460). The per-turn-/// records are the authoritative copy and the only one that is written on every-/// path, so this reads those and ignores the header.-///-/// `read_transcript` is the reader that applies compaction records and drops-/// interrupted partials, so a compacted or interrupted session is summed over-/// its logical message set rather than its raw append log.-pub(super) fn transcript_spend(transcript: &SessionTranscript) -> TranscriptSpend {- let mut spend = TranscriptSpend::default();- for message in &transcript.messages {- let Some(usage) = message.turn_usage.as_ref() else {- continue;- };- // A text-dialect tool round's issuing row carries a provenance-only- // record (its calls, zero spend); the turn's spend is on its final row.- // It is not a turn that spent, and must not become the "last" one.- if !usage.tool_calls.is_empty()- && usage.usage.input == 0- && usage.usage.output == 0- && usage.usage.cached_input == 0- && usage.usage.cost_usd == 0.0- {- continue;- }- spend.input_tokens = spend.input_tokens.saturating_add(usage.usage.input);- spend.output_tokens = spend.output_tokens.saturating_add(usage.usage.output);- spend.cached_input_tokens = spend- .cached_input_tokens- .saturating_add(usage.usage.cached_input);- spend.cost_usd += usage.usage.cost_usd;- spend.turns += 1;- spend.last_input_tokens = usage.usage.input;- spend.last_output_tokens = usage.usage.output;- if usage.usage.context_window > 0 {- spend.context_window = usage.usage.context_window;- }- if !usage.model.is_empty() {- spend.model = Some(usage.model.clone());- }- }- // A transcript whose model never landed on a usage record still has one in- // its header; prefer the record, fall back to the header.- if spend.model.is_none() {- spend.model = transcript.meta.model.clone();- }- spend-}--/// Read one transcript, logging and skipping an unreadable file rather than-/// failing the whole thread's aggregate for it.-fn read(path: &Path) -> Option<SessionTranscript> {- match read_transcript(path) {- Ok(transcript) => Some(transcript),- Err(err) => {- log::warn!(- "[threads:usage] skipping unreadable transcript {}: {err}",- path.display()- );- None- }- }-}--/// Every descendant transcript of `root`, at any delegation depth.-///-/// Sub-agent transcripts are named `{root_stem}__{child}` (and a grandchild-/// chains another `__`), which is the *only* durable record of the parent→child-/// relation. Selecting them by `_meta.thread_id` instead — as the session-/// crate's own summary helper does — drops the majority of them: a delegation-/// gets its own worker thread, and `inherited_thread_id` lets that worker id win-/// over the parent's, so the child's header names a thread the caller never-/// asked about (#6460).-fn descendant_transcripts(root: &Path) -> Vec<std::path::PathBuf> {- let Some(dir) = root.parent() else {- return Vec::new();- };- let Some(root_stem) = root.file_stem().and_then(|s| s.to_str()) else {- return Vec::new();- };- let prefix = format!("{root_stem}__");- let Ok(entries) = std::fs::read_dir(dir) else {- return Vec::new();- };- let mut matches: Vec<std::path::PathBuf> = entries- .flatten()- .map(|entry| entry.path())- .filter(|path| {- path.extension().and_then(|s| s.to_str()) == Some("jsonl")- && path- .file_stem()- .and_then(|s| s.to_str())- .is_some_and(|stem| stem.starts_with(&prefix))- })- .collect();- matches.sort();- matches-}--/// One thread's spend, split into the orchestrator's own and each sub-agent-/// archetype's, each counted exactly once.-#[derive(Debug, Clone, Default)]-pub(super) struct ThreadSpend {- pub(super) root: TranscriptSpend,- /// Keyed by archetype (`_meta.agent`), with a run count.- pub(super) subagents: BTreeMap<String, (TranscriptSpend, usize)>,- pub(super) updated: Option<String>,- pub(super) found_transcript: bool,-}--/// Walk a thread's root transcripts and their descendants, totalling each file's-/// own recorded spend.-///-/// Correct-by-construction because every transcript records only what the agent-/// that owns it spent (see `session_host::codec::turn_usage`): the walk visits-/// each file once, so no token is counted twice however deep the delegation went,-/// and a child whose usage never reached its parent's in-turn ledger (#6459) is-/// still counted from its own file.-pub(super) fn thread_spend(workspace_dir: &Path, thread_id: &str) -> ThreadSpend {- let mut out = ThreadSpend::default();- let roots = find_root_transcripts_for_thread(workspace_dir, thread_id);- for root in &roots {- out.found_transcript = true;- if let Some(transcript) = read(root) {- let spend = transcript_spend(&transcript);- out.root.input_tokens = out.root.input_tokens.saturating_add(spend.input_tokens);- out.root.output_tokens = out.root.output_tokens.saturating_add(spend.output_tokens);- out.root.cached_input_tokens = out- .root- .cached_input_tokens- .saturating_add(spend.cached_input_tokens);- out.root.cost_usd += spend.cost_usd;- out.root.turns += spend.turns;- // `find_root_transcripts_for_thread` returns oldest first, so the- // last root to report a turn owns the last-turn view.- if spend.turns > 0 {- out.root.last_input_tokens = spend.last_input_tokens;- out.root.last_output_tokens = spend.last_output_tokens;- }- if spend.context_window > 0 {- out.root.context_window = spend.context_window;- }- if spend.model.is_some() {- out.root.model = spend.model;- }- out.updated = Some(transcript.meta.updated);- }- for child in descendant_transcripts(root) {- let Some(child_transcript) = read(&child) else {- continue;- };- let spend = transcript_spend(&child_transcript);- out.found_transcript = true;- let entry = out- .subagents- .entry(child_transcript.meta.agent_name.clone())- .or_default();- entry.0.input_tokens = entry.0.input_tokens.saturating_add(spend.input_tokens);- entry.0.output_tokens = entry.0.output_tokens.saturating_add(spend.output_tokens);- entry.0.cached_input_tokens = entry- .0- .cached_input_tokens- .saturating_add(spend.cached_input_tokens);- entry.0.cost_usd += spend.cost_usd;- entry.0.turns += spend.turns;- if entry.0.model.is_none() {- entry.0.model = spend.model;- }- entry.1 += 1;- }- }- out-}-/// Total a thread's persisted token/cost usage across its root transcripts.pub async fn token_usage(request: ThreadTokenUsageRequest,@@ -384,7 +184,3 @@ fn empty_response(thread_id: &str) -> ThreadTokenUsageResponse {subagents: Vec::new(),}}--#[cfg(test)]-#[path = "usage_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/threads/ops/usage_tests.rs b/crates/openhuman-core/src/threads/ops/usage_tests.rsdeleted file mode 100644index 713102ea57..0000000000--- a/crates/openhuman-core/src/threads/ops/usage_tests.rs+++ /dev/null@@ -1,358 +0,0 @@-//! Aggregation tests for `threads::ops::usage`.-//!-//! Every fixture is written with the session crate's own writer-//! (`append_transcript_turn`), never hand-rolled JSONL, so a wire-format change-//! upstream surfaces here as a failure instead of silently diverging from what-//! the core actually persists.--use super::*;-use tinyagents_session::transcript::{- append_transcript_turn, MessageUsage, TranscriptMessage, TranscriptMeta, TurnUsage,-};--const MODEL: &str = "openrouter/deepseek/deepseek-v4-flash";--fn meta(agent: &str, agent_type: &str, thread_id: Option<&str>) -> TranscriptMeta {- TranscriptMeta {- agent_name: agent.to_string(),- agent_id: Some(agent.to_string()),- agent_type: Some(agent_type.to_string()),- dispatcher: "native".into(),- provider: Some("openhuman".into()),- model: Some(MODEL.into()),- created: "2026-09-22T00:00:00Z".into(),- updated: "2026-09-22T01:00:00Z".into(),- turn_count: 0,- prefix_message_count: None,- // Every fixture leaves the denormalised `_meta` rollups at zero: that is- // exactly what is on disk for every root transcript written since- // `33566d382`, and the aggregate must not depend on them.- input_tokens: 0,- output_tokens: 0,- cached_input_tokens: 0,- charged_amount_usd: 0.0,- thread_id: thread_id.map(str::to_owned),- task_id: None,- session_id: None,- parent_session_id: None,- }-}--fn turn_usage(input: u64, output: u64, cached: u64) -> TurnUsage {- TurnUsage {- provider: "openhuman".into(),- model: MODEL.into(),- usage: MessageUsage {- input,- output,- cached_input: cached,- context_window: 1_000_000,- cost_usd: 0.0,- },- ts: "2026-09-22T01:00:00Z".into(),- reasoning_content: None,- tool_calls: Vec::new(),- iteration: 1,- }-}--/// Append `turns` to `session_raw/{stem}.jsonl`, one durable turn per entry,-/// growing the message set the way the runtime does.-fn write_transcript_turns(- workspace: &Path,- stem: &str,- meta: &TranscriptMeta,- turns: &[(u64, u64, u64)],-) {- let dir = workspace.join("session_raw");- std::fs::create_dir_all(&dir).expect("create session_raw");- let path = dir.join(format!("{stem}.jsonl"));- let mut persisted: Vec<TranscriptMessage> = Vec::new();- for (i, (input, output, cached)) in turns.iter().enumerate() {- let mut next = persisted.clone();- next.push(TranscriptMessage::new("user", format!("q{i}")));- next.push(TranscriptMessage::assistant(format!("a{i}")));- let mut turn_meta = meta.clone();- turn_meta.turn_count = i + 1;- append_transcript_turn(- &path,- &persisted,- &next,- &turn_meta,- Some(&turn_usage(*input, *output, *cached)),- Some(&format!("req-{i}")),- )- .expect("append turn");- persisted = next;- }-}--/// A thread with no sub-agents: the total is the orchestrator's own spend, and-/// the zero `_meta` rollups are ignored.-#[test]-fn totals_a_thread_with_no_subagents_from_its_turn_records() {- let tmp = tempfile::tempdir().expect("tempdir");- let thread = "thread-solo";- write_transcript_turns(- tmp.path(),- "1790000000_orchestrator_solo",- &meta("orchestrator", "root", Some(thread)),- &[(10_000, 100, 4_000), (20_000, 200, 8_000)],- );-- let spend = thread_spend(tmp.path(), thread);-- assert_eq!(spend.root.input_tokens, 30_000);- assert_eq!(spend.root.output_tokens, 300);- assert_eq!(spend.root.cached_input_tokens, 12_000);- assert_eq!(spend.root.turns, 2);- assert!(- spend.subagents.is_empty(),- "no sub-agent transcripts exist, so none may be attributed"- );- // The newest turn owns the last-turn view, not the sum of turns.- assert_eq!(spend.root.last_input_tokens, 20_000);- assert_eq!(spend.root.last_output_tokens, 200);-}--/// The `thread-37dcc15f` shape from the bug report: a root whose children burned-/// far more than it did, and whose child transcripts carry a **worker** thread-/// id rather than the parent's.-///-/// This is the regression. Selecting children by `_meta.thread_id` — what-/// `read_thread_usage_summary` does — attributed 0 of the 397,423 child input-/// tokens to the thread, so ~88% of its spend was invisible (#6460).-#[test]-fn counts_subagents_whose_transcripts_carry_a_worker_thread_id() {- let tmp = tempfile::tempdir().expect("tempdir");- let thread = "thread-37dcc15f";- let root_stem = "1789765020_orchestrator_thread-37dcc";- write_transcript_turns(- tmp.path(),- root_stem,- &meta("orchestrator", "root", Some(thread)),- &[(16_884, 34, 0)],- );- // Both children name their own worker thread, never `thread`.- write_transcript_turns(- tmp.path(),- &format!("{root_stem}__1789766110_researcher_sub-a"),- &meta(- "researcher",- "subagent",- Some("worker-0aa53709-436d-4566-8798-3629beb11723"),- ),- &[(180_295, 8_000, 0)],- );- write_transcript_turns(- tmp.path(),- &format!("{root_stem}__1789766852_researcher_sub-b"),- &meta(- "researcher",- "subagent",- Some("worker-6b2d242f-c1b1-49ef-8b74-0a7ebeda4afc"),- ),- &[(217_128, 8_873, 0)],- );-- let spend = thread_spend(tmp.path(), thread);-- assert_eq!(spend.root.input_tokens, 16_884, "orchestrator's own spend");- let (researcher, runs) = spend- .subagents- .get("researcher")- .expect("both children group under their archetype despite the worker thread ids");- assert_eq!(*runs, 2, "two separate delegations, two runs");- assert_eq!(- researcher.input_tokens, 397_423,- "both children's input must be attributed to the parent thread"- );- assert_eq!(researcher.output_tokens, 16_873);-- // The thread total counts every token exactly ONCE. The pre-fix arithmetic- // would reach 414,307 + 397,423 had the root record also carried its- // children, which is the double count this design removes.- let total = spend.root.input_tokens + researcher.input_tokens;- assert_eq!(total, 414_307);-}--/// A child's spend is counted from the child's own transcript, so a delegation-/// whose usage never reached the parent's in-turn ledger (#6459, the default-/// async path) is still counted — and counted once, not twice.-#[test]-fn counts_each_transcript_once_regardless_of_the_parent_ledger() {- let tmp = tempfile::tempdir().expect("tempdir");- let thread = "thread-ledger";- let root_stem = "1790000001_orchestrator_ledger";- // The root records ONLY its own spend — the contract- // `session_host::codec::turn_usage` now guarantees.- write_transcript_turns(- tmp.path(),- root_stem,- &meta("orchestrator", "root", Some(thread)),- &[(1_000, 10, 0)],- );- write_transcript_turns(- tmp.path(),- &format!("{root_stem}__child_coder"),- &meta("coding_agent", "subagent", Some("worker-xyz")),- &[(5_000, 50, 0)],- );-- let spend = thread_spend(tmp.path(), thread);- let (coder, runs) = spend.subagents.get("coding_agent").expect("child counted");-- assert_eq!(spend.root.input_tokens, 1_000);- assert_eq!(coder.input_tokens, 5_000);- assert_eq!(*runs, 1);- assert_eq!(spend.root.input_tokens + coder.input_tokens, 6_000);-}--/// A grandchild chains another `__`, and must be counted once at its own depth-/// rather than dropped or folded into its parent twice.-#[test]-fn counts_a_grandchild_delegation_once() {- let tmp = tempfile::tempdir().expect("tempdir");- let thread = "thread-deep";- let root_stem = "1790000002_orchestrator_deep";- write_transcript_turns(- tmp.path(),- root_stem,- &meta("orchestrator", "root", Some(thread)),- &[(1_000, 10, 0)],- );- write_transcript_turns(- tmp.path(),- &format!("{root_stem}__child"),- &meta("researcher", "subagent", Some("worker-1")),- &[(2_000, 20, 0)],- );- write_transcript_turns(- tmp.path(),- &format!("{root_stem}__child__grandchild"),- &meta("coding_agent", "subagent", Some("worker-2")),- &[(4_000, 40, 0)],- );-- let spend = thread_spend(tmp.path(), thread);- let total: u64 = spend.root.input_tokens- + spend- .subagents- .values()- .map(|(child, _)| child.input_tokens)- .sum::<u64>();- assert_eq!(- spend.subagents.len(),- 2,- "child and grandchild both counted"- );- assert_eq!(total, 7_000);-}--/// Legacy transcripts already on disk carry zero `_meta` rollups. They must keep-/// working, which they do because the aggregate never reads the header.-#[test]-fn ignores_the_dead_meta_rollup_on_legacy_transcripts() {- let tmp = tempfile::tempdir().expect("tempdir");- let thread = "thread-legacy";- let legacy = meta("orchestrator", "root", Some(thread));- assert_eq!(- legacy.input_tokens, 0,- "fixture must reproduce the on-disk state: a zero header"- );- write_transcript_turns(- tmp.path(),- "1789983533_orchestrator_legacy",- &legacy,- &[(12_495, 23, 12_288)],- );-- let spend = thread_spend(tmp.path(), thread);- assert_eq!(- spend.root.input_tokens, 12_495,- "the per-turn record is authoritative, the zero header is not"- );- assert_eq!(spend.root.cached_input_tokens, 12_288);-}--/// A thread with no transcripts at all reports nothing, and a thread whose-/// transcripts recorded no spend must not claim usage: the UI replaces its live-/// bucket with this payload, so a false `has_usage` zeroes a turn in flight.-#[test]-fn reports_no_usage_for_an_unknown_or_spendless_thread() {- let tmp = tempfile::tempdir().expect("tempdir");- let absent = thread_spend(tmp.path(), "thread-nope");- assert!(!absent.found_transcript);- assert_eq!(absent.root.input_tokens, 0);-- // A transcript that exists but recorded a single all-zero turn. The codec- // omits an all-zero usage record, so this is the shape on disk: rows, no- // usage.- let thread = "thread-empty";- let dir = tmp.path().join("session_raw");- std::fs::create_dir_all(&dir).expect("create session_raw");- let path = dir.join("1790000003_orchestrator_empty.jsonl");- append_transcript_turn(- &path,- &[],- &[TranscriptMessage::new("user", "hi")],- &meta("orchestrator", "root", Some(thread)),- None,- Some("req-0"),- )- .expect("append turn");-- let spend = thread_spend(tmp.path(), thread);- assert!(spend.found_transcript, "the file is there");- assert_eq!(spend.root.turns, 0, "but it recorded no spend");- assert_eq!(spend.root.input_tokens, 0);-}--/// A text-dialect tool round's issuing row carries a provenance-only record —-/// its calls, zero spend — beside the turn's real record on the final row.-/// It is not a turn that spent and must not take over the last-turn view.-#[test]-fn provenance_only_tool_round_records_are_not_counted_as_turns() {- let tmp = tempfile::tempdir().expect("tempdir");- let thread = "thread-text-dialect";- let path = tmp- .path()- .join("session_raw")- .join("1790000001_orchestrator_text.jsonl");- std::fs::create_dir_all(path.parent().unwrap()).expect("create session_raw");-- let mut issuing = TranscriptMessage::assistant("");- issuing.turn_usage = Some(TurnUsage {- tool_calls: vec![tinyagents_session::transcript::TranscriptToolCall {- id: "call-1".into(),- name: "web_search_tool".into(),- arguments: "{}".into(),- extra_content: None,- }],- ..turn_usage(0, 0, 0)- });- let rows = vec![- TranscriptMessage::new("user", "q"),- issuing,- TranscriptMessage::new(- "user",- "[Tool results]\n<tool_result id=\"call-1\">\nok\n</tool_result>\n",- ),- TranscriptMessage::assistant("a"),- ];- append_transcript_turn(- &path,- &[],- &rows,- &meta("orchestrator", "root", Some(thread)),- Some(&turn_usage(5_000, 50, 1_000)),- Some("req-0"),- )- .expect("append turn");-- let spend = thread_spend(tmp.path(), thread);-- assert_eq!(spend.root.turns, 1);- assert_eq!(spend.root.input_tokens, 5_000);- assert_eq!(spend.root.last_input_tokens, 5_000);-}