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
//! Process-global `CostTracker` singleton.
//!
//! The dashboard RPC handlers and agent-turn telemetry hook share a single
//! tracker instance so cost records are persisted exactly once per provider
//! call and the in-memory daily/monthly aggregates stay coherent.
//!
//! Initialisation is intentionally lazy from the caller's perspective: the
//! `bootstrap_core_runtime` path calls [`init_global`] at startup, and any
//! later call is a no-op. Callers that run before bootstrap (e.g. unit
//! tests) see `None` from [`try_global`] and skip recording — never a panic.
//!
//! The tracker is bound to one workspace. Signing in or out switches the
//! active workspace (`users/local` <-> `users/<id>`), so the credential path
//! calls [`rebind_global`] to move it; otherwise usage recorded after login
//! would keep landing in the pre-login ledger.
use std::path::Path;
use std::sync::Arc;
use parking_lot::RwLock;
use crate::config::CostConfig;
use crate::core::runtime::DispatchCtx;
use tinyinference_llm::usage::BilledUsage;
use super::tracker::CostTracker;
use super::types::{CostSource, TokenUsage, UsageScope};
static GLOBAL_TRACKER: RwLock<Option<Arc<CostTracker>>> = RwLock::new(None);
/// Initialise the global cost tracker. Idempotent — subsequent calls are
/// no-ops and the original tracker is preserved. Logs (but does not panic)
/// when construction fails so a bad workspace path never blocks core boot.
///
/// The agent telemetry path appends to `costs.jsonl` through
/// [`record_provider_usage`] regardless of `cost.enabled`. That flag only
/// affects direct calls to `CostTracker::record_usage`; it does not enforce a
/// spend cap. The local ledger remains available when the flag is false.
///
/// The first-boot `info` log records `enabled` and the resolved
/// workspace so the default-on behaviour shows up in startup logs for
/// existing deployments that omit the `[cost]` block.
pub fn init_global(config: CostConfig, workspace_dir: &Path) {
if GLOBAL_TRACKER.read().is_some() {
return;
}
let cost_enabled = config.enabled;
match CostTracker::new(config, workspace_dir) {
Ok(tracker) => {
let mut slot = GLOBAL_TRACKER.write();
if slot.is_some() {
// Another caller won a concurrent init race; the original
// tracker is kept. Avoid logging a misleading "initialised"
// line — the winner already did so.
log::debug!(
"[cost] global CostTracker already initialised by another caller; \
discarding duplicate instance"
);
return;
}
*slot = Some(Arc::new(tracker));
drop(slot);
log::info!(
"[cost] global CostTracker initialised at workspace {} (cost.enabled={}, \
dashboard telemetry always-on). Set cost.dashboard.enabled=false in \
config.toml to hide the panel.",
workspace_dir.display(),
cost_enabled
);
if !cost_enabled {
log::warn!(
"[cost] cost.enabled=false: dashboard telemetry will still append to \
costs.jsonl. Set cost.dashboard.enabled=false to disable the panel; \
the JSONL is local and never leaves the workspace."
);
}
}
Err(err) => {
log::warn!(
"[cost] failed to initialise global CostTracker at {}: {err} \
— cost dashboard will report empty data until next core start",
workspace_dir.display()
);
}
}
}
/// Point the global tracker at `workspace_dir` when it is bound elsewhere.
///
/// Called when the active workspace changes (sign-in, sign-out). A no-op when
/// the tracker already serves `workspace_dir`. Old ledgers are not migrated:
/// each workspace keeps its own `costs.jsonl`. The session-scoped in-memory
/// figures start over with the new tracker. A failed construction keeps the
/// previous tracker rather than leaving the process with none.
pub fn rebind_global(config: CostConfig, workspace_dir: &Path) {
// In SaaS every profile owns its tracker (see `seed_tenant_tracker`); the
// process-wide slot is never read, so rebinding it would only mislead.
if crate::core::runtime::is_saas() {
log::debug!("[cost] rebind_global ignored in SaaS mode");
return;
}
if let Some(current) = try_global() {
if current.workspace_dir() == workspace_dir {
log::debug!(
"[cost] rebind_global: tracker already bound to workspace {}",
workspace_dir.display()
);
return;
}
}
match CostTracker::new(config, workspace_dir) {
Ok(tracker) => {
let previous = GLOBAL_TRACKER.write().replace(Arc::new(tracker));
log::info!(
"[cost] global CostTracker rebound from workspace {} to {}",
previous
.as_ref()
.map(|t| t.workspace_dir().display().to_string())
.unwrap_or_else(|| "<unbound>".to_string()),
workspace_dir.display()
);
}
Err(err) => {
log::warn!(
"[cost] failed to rebind global CostTracker to {}: {err}; keeping the \
previous tracker",
workspace_dir.display()
);
}
}
}
/// Fetch the global tracker if it has been initialised. Returns `None`
/// before bootstrap or after an init failure — callers must treat the
/// absence as a soft no-op.
///
/// In SaaS this is the calling tenant's own tracker
/// ([`seed_tenant_tracker`]), never the process-wide one: one user's spend
/// must not land in, or be read from, another's ledger. A SaaS task with no
/// scope, or the operator, gets `None`.
pub fn try_global() -> Option<Arc<CostTracker>> {
let saas = crate::core::runtime::is_saas();
if saas {
return tracker_in(crate::core::runtime::tenant::context_in(saas).as_deref());
}
GLOBAL_TRACKER.read().clone()
}
/// A SaaS tenant's cost tracker, held in its context's state slots.
#[derive(Default)]
pub(crate) struct TenantTracker(RwLock<Option<Arc<CostTracker>>>);
/// Give `ctx` (a SaaS profile's context) a cost tracker over the profile's
/// own workspace. Called when the profile opens; a failure leaves it without
/// one (its usage goes unrecorded) rather than borrowing another ledger.
pub fn seed_tenant_tracker(
ctx: &crate::core::runtime::CoreContext,
config: &crate::config::Config,
) {
match CostTracker::new(config.cost.clone(), &config.workspace_dir) {
Ok(tracker) => {
*ctx.agent_state().slot::<TenantTracker>().0.write() = Some(Arc::new(tracker));
log::debug!(
"[cost] tenant tracker seeded workspace={}",
config.workspace_dir.display()
);
}
Err(err) => {
// Never keep a tracker over a previous workspace.
*ctx.agent_state().slot::<TenantTracker>().0.write() = None;
log::warn!(
"[cost] could not seed the tenant tracker at {}: {err}",
config.workspace_dir.display()
);
}
}
}
/// The tracker `ctx` was seeded with; `None` without a context.
pub(crate) fn tracker_in(
ctx: Option<&crate::core::runtime::CoreContext>,
) -> Option<Arc<CostTracker>> {
ctx.and_then(|ctx| ctx.agent_state().slot::<TenantTracker>().0.read().clone())
}
/// Convenience hook used by the agent turn loop: translates a provider
/// [`BilledUsage`] into a [`TokenUsage`] record and persists it via the
/// global tracker. Silently skipped when the tracker is uninitialised.
/// Errors are logged but never propagated — cost tracking must never
/// break a turn.
///
/// Note: this path uses
/// [`crate::platform::cost::tracker::CostTracker::record_usage_unconditional`],
/// so dashboard telemetry is captured even when `cost.enabled = false`.
///
/// `model` is the model identifier the request was routed to (e.g.
/// `"anthropic/claude-sonnet-4-20250514"`) and is used as the bucket key
/// in per-model aggregates.
pub fn record_provider_usage(ctx: &DispatchCtx, model: &str, usage: &BilledUsage) {
record_provider_usage_scoped(model, usage, UsageScope::in_ctx(ctx, None, None));
}
/// [`record_provider_usage`] with the call's attribution. The event bridge
/// passes its provider and, for a delegated child, the sub-agent; everything
/// else comes from the recording task (see [`UsageScope::in_ctx`]).
pub fn record_provider_usage_scoped(model: &str, usage: &BilledUsage, scope: UsageScope) {
let Some(mut token_usage) = build_token_usage(model, usage) else {
return;
};
log::trace!(
"[cost] attributing usage model={model} thread={:?} agent={:?} origin={:?} provider={:?}",
scope.thread_id,
scope.agent_id,
scope.origin,
scope.provider
);
token_usage.scope = scope;
let Some(tracker) = try_global() else {
return;
};
if let Err(err) = tracker.record_usage_unconditional(token_usage) {
log::debug!("[cost] record_provider_usage failed: {err}");
}
}
/// Translate a provider [`BilledUsage`] into a [`TokenUsage`] record.
///
/// Returns `None` for an all-zero payload so the caller can skip the
/// write — providers that don't echo usage produce `BilledUsage::default()`
/// values, and persisting those would inflate the request count with
/// non-events. Non-finite or negative cost is clamped to `0.0`. Extracted
/// from [`record_provider_usage`] so the translation can be unit-tested
/// independently of the process-global tracker singleton.
pub(super) fn build_token_usage(model: &str, usage: &BilledUsage) -> Option<TokenUsage> {
if usage.input_tokens == 0 && usage.output_tokens == 0 && usage.charged_amount_usd == 0.0 {
return None;
}
let total_tokens = usage.input_tokens.saturating_add(usage.output_tokens);
let cost_source = if usage.cost_is_estimate {
CostSource::Estimated
} else if usage.charge_reported {
CostSource::ProviderCharged
} else {
CostSource::Unknown
};
Some(TokenUsage {
model: model.to_string(),
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
total_tokens,
cached_input_tokens: usage.cached_input_tokens().min(usage.input_tokens),
cache_creation_tokens: usage.cache_creation_tokens,
reasoning_tokens: usage.reasoning_tokens,
cost_usd: if usage.charged_amount_usd.is_finite() && usage.charged_amount_usd >= 0.0 {
usage.charged_amount_usd
} else {
0.0
},
cost_source,
// Lineage groundwork (06-cost step 3): the provider-usage build site
// does not yet carry a run_id/root_run_id from the observation stream.
// Leave `None` until the run-tree rollup (06.3, gated) threads run
// lineage through `record_provider_usage` / the observation bridge in
// `tinyagents/observability.rs`.
run_id: None,
root_run_id: None,
scope: UsageScope::default(),
timestamp: chrono::Utc::now(),
})
}
/// Best-effort embedding cost recording (06-cost step 4 / 09-embeddings step 4).
///
/// Emits a [`CostRecord`](super::types::CostRecord) for a successful embedding
/// batch, priced via the unified pricing catalog. The record uses the
/// `"<provider>/<model>"` model key so it matches the embedding `CostRecord`
/// shape used elsewhere (e.g. `voyage/voyage-3`).
///
/// Pricing resolution: [`tinyagents_registry::pricing::estimate_cost_usd`] prices `input_tokens` at
/// the catalogued per-token input rate. Embedding models are frequently **not**
/// in the pricing catalog; in that case `estimate_cost_usd` returns `0.0` and
/// we record the usage with **zero** cost (and log it) rather than fabricating a
/// rate. Output tokens are always zero for embeddings.
///
/// This path is **non-fatal**: it must never fail an embed or a recall turn.
/// A missing global tracker, or a tracker write error, is logged under
/// `[cost][embed]` and swallowed.
///
/// - `provider` — embedding provider slug (e.g. `voyage`, `openai`, `ollama`).
/// - `model` — provider model id (e.g. `voyage-3`).
/// - `input_tokens` — approximate input token count for the batch.
/// - `dimensions` — embedding vector dimensionality (logging context only).
/// - `vector_count` — number of vectors produced (logging context only).
pub fn record_embedding_usage(
ctx: &DispatchCtx,
provider: &str,
model: &str,
input_tokens: u64,
dimensions: usize,
vector_count: u64,
) {
let Some(tracker) = try_global() else {
log::debug!(
"[cost][embed] tracker not initialised; skipping embedding cost record \
provider={provider} model={model} vectors={vector_count}"
);
return;
};
let cost_usd = tinyagents_registry::pricing::estimate_cost_usd(model, input_tokens, 0, 0);
if cost_usd == 0.0 {
log::debug!(
"[cost][embed] no catalog embedding rate for model={model}; recording usage with \
zero cost (provider={provider} dims={dimensions} vectors={vector_count} \
input_tokens={input_tokens})"
);
}
let usage = TokenUsage {
// `<provider>/<model>` bucket key, matching the embedding CostRecord
// shape used in the dashboard/RPC layer (e.g. `voyage/voyage-3`).
model: format!("{provider}/{model}"),
input_tokens,
output_tokens: 0,
total_tokens: input_tokens,
cached_input_tokens: 0,
cache_creation_tokens: 0,
reasoning_tokens: 0,
cost_usd,
cost_source: CostSource::Estimated,
run_id: None,
root_run_id: None,
scope: UsageScope {
origin: Some(super::report::EMBEDDING_ORIGIN.to_string()),
..UsageScope::in_ctx(ctx, Some(provider), None)
},
timestamp: chrono::Utc::now(),
};
log::debug!(
"[cost][embed] recording embedding usage provider={provider} model={model} \
input_tokens={input_tokens} dims={dimensions} vectors={vector_count} cost_usd={cost_usd}"
);
if let Err(err) = tracker.record_usage_unconditional(usage) {
log::debug!(
"[cost][embed] record_embedding_usage failed provider={provider} model={model}: {err}"
);
}
}
#[cfg(test)]
#[path = "global_tests.rs"]
mod tests;