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
fix(agent): handle missing event bridge in usage tracking
Steven Enamakelc454c0b12c72
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rsindex ed20da4486..050991a3ce 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_bridge.rs@@ -20,19 +20,19 @@ use super::cap_pauser::{};#[derive(Default)]-struct BridgeState {- input_tokens: u64,- output_tokens: u64,- cached_input_tokens: u64,- charged_amount_usd: f64,+pub(super) struct BridgeState {+ pub(super) input_tokens: u64,+ pub(super) output_tokens: u64,+ pub(super) cached_input_tokens: u64,+ pub(super) charged_amount_usd: f64,/// Local response-cache hits observed on this turn (issue #4249, 03.2). A hit/// means the harness served a model call from its [`ResponseCache`] without/// invoking the provider. Additive counters — a follow-up (coordinated with/// workstream 06) wires these into the cost-footer DTO; today they are logged/// with a grep-friendly `[cache]` prefix and exposed via [`OpenhumanEventBridge::cache_counts`].- cache_hits: u64,+ pub(super) cache_hits: u64,/// Local response-cache misses observed on this turn (provider *was* invoked).- cache_misses: u64,+ pub(super) cache_misses: u64,}/// Per-model-call figures `record_usage` resolved from the provider-usagediff --git a/crates/openhuman-core/src/threads/ops/usage.rs b/crates/openhuman-core/src/threads/ops/usage.rsnew file mode 100644index 0000000000..169fb1169a--- /dev/null+++ b/crates/openhuman-core/src/threads/ops/usage.rs@@ -0,0 +1,163 @@+//! Aggregated token/cost usage for a thread, re-audited at current pricing.++use super::support::{counts, envelope, workspace_dir};+use crate::memory::ApiEnvelope;+use crate::rpc::RpcOutcome;++/// Request for [`token_usage`]: the thread whose persisted usage to total.+#[derive(Debug, Clone, serde::Deserialize)]+pub struct ThreadTokenUsageRequest {+ pub thread_id: String,+}++/// Aggregated token/cost usage for one thread, read back from its persisted+/// session transcripts. Seeds the UI footer when the user selects a thread so+/// the totals reflect prior turns instead of starting at zero.+#[derive(Debug, Clone, serde::Serialize)]+pub struct ThreadTokenUsageResponse {+ pub thread_id: String,+ pub input_tokens: u64,+ pub output_tokens: u64,+ pub cached_input_tokens: u64,+ pub cost_usd: f64,+ pub turn_count: usize,+ /// Tokens of the most recent turn — numerator for the context-window gauge.+ pub last_turn_input_tokens: u64,+ pub last_turn_output_tokens: u64,+ /// Context window (tokens) inferred from the last model; `0` when unknown.+ pub context_window: u64,+ pub model: Option<String>,+ pub updated: Option<String>,+ /// `false` when the thread has no persisted turns yet (all zeros).+ pub has_usage: bool,+ /// Per-archetype sub-agent spend (re-audited at current pricing). The+ /// top-level totals already include this; it's broken out for the UI's+ /// per-agent footer rows.+ pub subagents: Vec<SubagentUsageDto>,+}++/// One sub-agent archetype's contribution within a thread.+#[derive(Debug, Clone, serde::Serialize)]+pub struct SubagentUsageDto {+ pub agent_id: String,+ pub input_tokens: u64,+ pub output_tokens: u64,+ pub cost_usd: f64,+ pub runs: usize,+}++/// Total a thread's persisted token/cost usage across its root transcripts.+pub async fn token_usage(+ request: ThreadTokenUsageRequest,+) -> Result<RpcOutcome<ApiEnvelope<ThreadTokenUsageResponse>>, String> {+ let dir = workspace_dir().await?;+ let summary = crate::agent::harness::session::transcript::read_thread_usage_summary(+ &dir,+ &request.thread_id,+ );++ // Re-audit cost at CURRENT pricing rather than trusting the+ // `charged_amount_usd` persisted in the transcript: those values were+ // stamped at turn time and don't reflect later tier-pricing corrections.+ // Recompute from the persisted token counts using the last-known model's+ // rates; falls back to `fallback` only when the model is unknown.+ let audit_cost =+ |model: Option<&str>, input: u64, output: u64, cached: u64, fallback: f64| match model {+ Some(m) => crate::agent::cost::estimate_call_cost_usd(+ m,+ &crate::inference::provider::UsageInfo {+ input_tokens: input,+ output_tokens: output,+ cached_input_tokens: cached,+ ..Default::default()+ },+ ),+ None => fallback,+ };++ let response = match summary {+ Some(s) => {+ let context_window = s+ .model+ .as_deref()+ .and_then(crate::inference::model_context::context_window_for_model)+ .unwrap_or(0);++ // Orchestrator (root) spend, re-audited.+ let orchestrator_cost = audit_cost(+ s.model.as_deref(),+ s.input_tokens,+ s.output_tokens,+ s.cached_input_tokens,+ s.cost_usd,+ );++ // Sub-agent archetypes, each re-audited with its own model. Older+ // sub-agent transcripts didn't persist a model on their messages, so+ // fall back to the thread's (root) model rather than pricing them at+ // $0 — sub-agents usually run on the same managed tier as the parent.+ let mut subagents = Vec::with_capacity(s.subagents.len());+ let (mut sub_in, mut sub_out, mut sub_cached, mut sub_cost) = (0u64, 0u64, 0u64, 0.0);+ for g in &s.subagents {+ let sub_model = g.model.as_deref().or(s.model.as_deref());+ let cost = audit_cost(+ sub_model,+ g.input_tokens,+ g.output_tokens,+ g.cached_input_tokens,+ 0.0,+ );+ sub_in = sub_in.saturating_add(g.input_tokens);+ sub_out = sub_out.saturating_add(g.output_tokens);+ sub_cached = sub_cached.saturating_add(g.cached_input_tokens);+ sub_cost += cost;+ subagents.push(SubagentUsageDto {+ agent_id: g.agent_id.clone(),+ input_tokens: g.input_tokens,+ output_tokens: g.output_tokens,+ cost_usd: cost,+ runs: g.runs,+ });+ }++ // Top-level totals = orchestrator + all sub-agents.+ ThreadTokenUsageResponse {+ thread_id: request.thread_id.clone(),+ input_tokens: s.input_tokens.saturating_add(sub_in),+ output_tokens: s.output_tokens.saturating_add(sub_out),+ cached_input_tokens: s.cached_input_tokens.saturating_add(sub_cached),+ cost_usd: orchestrator_cost + sub_cost,+ turn_count: s.turn_count,+ last_turn_input_tokens: s.last_turn_input_tokens,+ last_turn_output_tokens: s.last_turn_output_tokens,+ context_window,+ model: s.model,+ updated: Some(s.updated),+ has_usage: true,+ subagents,+ }+ }+ None => ThreadTokenUsageResponse {+ thread_id: request.thread_id.clone(),+ input_tokens: 0,+ output_tokens: 0,+ cached_input_tokens: 0,+ cost_usd: 0.0,+ turn_count: 0,+ last_turn_input_tokens: 0,+ last_turn_output_tokens: 0,+ context_window: 0,+ model: None,+ updated: None,+ has_usage: false,+ subagents: Vec::new(),+ },+ };++ let has_usage = response.has_usage;+ Ok(envelope(+ response,+ Some(counts([("has_usage", usize::from(has_usage))])),+ None,+ ))+}diff --git a/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs b/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rsnew file mode 100644index 0000000000..7518e33e01--- /dev/null+++ b/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs@@ -0,0 +1,125 @@+//! Delivery of a voice turn's result (or failure) into the user's in-app chat,+//! plus the raw socket emit helpers the turn handler uses to talk back to the+//! relay.++use log::{info, warn};+use serde_json::{json, Value};++use crate::platform::socket::manager::global_socket_manager;++/// Chat thread + client id the voice turn scopes as its approval / routing+/// surface, mirroring `deliver_voice_result_to_chat`. Setting these around the+/// turn (via `APPROVAL_CHAT_CONTEXT` + `with_thread_id`) is what makes the voice+/// orchestrator behave like the chat path for tools that need a *routable*+/// approval surface:+///+/// - `composio_connect` fails closed with a `[policy-denied] … needs an+/// interactive chat turn` message whenever `APPROVAL_CHAT_CONTEXT` is absent+/// (see `integrations/composio/tools.rs`). On voice that message got+/// paraphrased back to the user as "your Gmail connection is throwing an auth+/// error, reconnect it" — the exact voice-only Gmail-summary failure — even+/// though the same request works in tap-and-speak (a `WebChat` turn, which+/// installs this context). With the context set, the tool reaches its+/// already-connected short-circuit and returns success instead.+/// - external_effect tool approvals raised on the `ExternalChannel` turn now+/// have a thread card to route to (the same `proactive:voice` thread where+/// deferred voice answers land) rather than silently TTL-denying.+/// - `with_thread_id` gives async delegation (`spawn_async_subagent`) the+/// `parent_thread_id` it requires and aligns inference logs / KV-cache with+/// the voice thread.+pub(super) const VOICE_CHAT_THREAD_ID: &str = "proactive:voice";+pub(super) const VOICE_CHAT_CLIENT_ID: &str = "system";++/// Deliver a deferred voice turn's answer into the user's in-app chat. Publishes+/// a `proactive_message` on the web-channel event bus — the same seam cron and the+/// subconscious use — which the frontend renders as an assistant message in a+/// visible thread. Web-only: it does not fan out to external channels (#5399).+pub(super) fn deliver_voice_result_to_chat(+ correlation_id: &str,+ reply: String,+ allow_speak_back: bool,+) {+ let spoken = reply.trim();+ if spoken.is_empty() {+ warn!("[voice-harness] deferred turn produced no text correlation={correlation_id}");+ // The spoken ack already promised a chat follow-up, so an empty deferred+ // reply must still surface a message rather than leave the user waiting.+ deliver_voice_failure_to_chat(correlation_id);+ return;+ }+ info!(+ "[voice-harness] delivering deferred result to chat correlation={correlation_id} chars={} speak_back={allow_speak_back}",+ spoken.chars().count()+ );+ crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {+ event: "proactive_message".to_string(),+ client_id: VOICE_CHAT_CLIENT_ID.to_string(),+ thread_id: VOICE_CHAT_THREAD_ID.to_string(),+ full_response: Some(spoken.to_string()),+ success: Some(true),+ ..Default::default()+ });++ // Speak-back: push the finished answer to the renderer's LIVE voice session so+ // the agent can read it aloud. The frontend voice hook listens for `voice_speak`+ // and, only while the call is still open, sends it back into the ElevenLabs+ // session (a fast read-back turn). Skipped for read-back turns themselves to+ // avoid a loop; harmless if the call already ended (nobody is subscribed).+ if allow_speak_back {+ crate::web_chat::publish_web_channel_event(+ crate::core::socketio::WebChannelEvent {+ event: "voice_speak".to_string(),+ client_id: VOICE_CHAT_CLIENT_ID.to_string(),+ full_response: Some(spoken.to_string()),+ success: Some(true),+ ..Default::default()+ },+ );+ }+}++/// Deliver a short "couldn't complete" notice to the voice chat thread for a+/// deferred turn that produced no answer the user can see — either it errored,+/// or it completed past the ack deadline with empty text (on this path+/// `run_single`'s returned text is the sole answer channel: the orchestrator+/// folds any tool/subagent output into its final reply, so an empty reply means+/// nothing was produced for the user, not that the answer went elsewhere).+/// Because the caller was told the answer was still coming, staying silent would+/// leave them waiting on a message that never arrives —+/// this makes the promised message always appear. Delivered as a normal+/// assistant message (not spoken) on the same `proactive:voice` surface as a+/// successful deferred answer.+pub(super) fn deliver_voice_failure_to_chat(correlation_id: &str) {+ info!(+ "[voice-harness] delivering deferred failure notice to chat correlation={correlation_id}"+ );+ crate::web_chat::publish_web_channel_event(crate::core::socketio::WebChannelEvent {+ event: "proactive_message".to_string(),+ client_id: VOICE_CHAT_CLIENT_ID.to_string(),+ thread_id: VOICE_CHAT_THREAD_ID.to_string(),+ full_response: Some(+ "Sorry — I couldn't finish that request just now. Please try again.".to_string(),+ ),+ success: Some(false),+ ..Default::default()+ });+}++pub(super) async fn emit_event(event: &str, payload: Value) {+ match global_socket_manager() {+ Some(mgr) => {+ if let Err(e) = mgr.emit(event, payload).await {+ warn!("[voice-harness] emit {event} failed: {e}");+ }+ }+ None => warn!("[voice-harness] no socket manager; dropping {event}"),+ }+}++pub(super) async fn emit_error(correlation_id: &str, message: &str) {+ emit_event(+ "voice:harness:error",+ json!({ "correlationId": correlation_id, "message": message }),+ )+ .await;+}