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: enable production Langfuse traces with per-run grouping
Steven Enamakel0cc7a01af622
diff --git a/crates/openhuman-core/src/agent/progress_tracing.rs b/crates/openhuman-core/src/agent/progress_tracing.rsindex 5e89cc4bc7..bf191b101c 100644--- a/crates/openhuman-core/src/agent/progress_tracing.rs+++ b/crates/openhuman-core/src/agent/progress_tracing.rs@@ -26,11 +26,11 @@//! Spans always carry *metadata* — span names, counts, timings, and//! token/cost figures (model labels are `{provider_id}.{model}`, e.g.//! `managed.hint:chat`). While `observability.agent_tracing.capture_content` is-//! on, content is additionally recorded as span `input`/`output` — the turn's+//! on (the default), content is additionally recorded as span `input`/`output` — the turn's//! prompt/reply, each generation's **truncated** request messages (system//! prompt included) + completion, **truncated** tool arguments/results, and-//! each subagent's delegated prompt + final output. With the flag off (the-//! default — #4454), none of that content ever reaches the in-memory span, so+//! each subagent's delegated prompt + final output. With the flag off,+//! none of that content ever reaches the in-memory span, so//! no exporter (NDJSON file, app log, or Langfuse) can leak it.//! Streamed text/thinking deltas (`TextDelta`, `ThinkingDelta`,//! `ToolCallArgsDelta`), raw error strings, and filesystem paths are **never**@@ -39,9 +39,8 @@//!//! The one exception is the turn's prompt/reply, delivered via//! `AgentProgress::TurnContent`. It is attached to the turn span **only** when-//! the operator opts in via `observability.agent_tracing.capture_content`-//! (default `false`). That gate is enforced at storage time in-//! [`SpanCollector`] — the single choke point — so with the default off, no+//! `observability.agent_tracing.capture_content` is enabled. That gate is+//! enforced at storage time in [`SpanCollector`] — the single choke point — so when off, no//! exporter (NDJSON file, app log, or Langfuse push) can ever serialize it.//!//! ## Wiring@@ -54,7 +53,7 @@/// Journal-backed projection from durable tinyagents observations.pub(crate) mod journal_projection;-/// Langfuse ingestion exporter (remote push to the co-hosted staging server).+/// Langfuse ingestion exporter (remote push through the configured backend).pub(crate) mod langfuse;/// The [`SpanCollector`] state machine that folds progress events into spans.@@ -72,6 +71,7 @@ pub use collector::SpanCollector;pub use types::SpanKind;pub use types::{trace_session_id, RunType, SpanStatus, TraceContext, TraceSpan};+pub(crate) use export::export_subagent_journal_trace;pub(crate) use export::{export_run_trace, export_run_trace_from_journal};#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/progress_tracing/README.md b/crates/openhuman-core/src/agent/progress_tracing/README.mdindex a8cd9a3781..5246b0466d 100644--- a/crates/openhuman-core/src/agent/progress_tracing/README.md+++ b/crates/openhuman-core/src/agent/progress_tracing/README.md@@ -6,7 +6,7 @@ OpenTelemetry/Langfuse-style trace spans (`agent.turn` -> `agent.iteration` ->debugging long multi-agent runs (issue #3886). The module doc on`agent/progress_tracing.rs` has the full span-tree shape and thecontent-capture privacy gate (`observability.agent_tracing.capture_content`,-default off; enforced once, in `SpanCollector`, so no exporter can leak+default on; enforced once, in `SpanCollector`, so no exporter can leakcontent).## Key files@@ -33,7 +33,7 @@ content).stamps `x-sdk-name` via `crate::api::product::product_identity_header`(AGENTS.md "Backend API"); `push_observations` sends through the vendored`tinyagents_harness::LangfuseClient::proxy`, splitting the batch at 500- events. Pushes are allowlisted to `staging`/`development` hosts+ events. Pushes are allowlisted to the canonical production API and `staging`/`development` hosts(`environment_for_base`, `LANGFUSE_PUSH_ENVIRONMENTS`) and skipped elsewherewith one `info` log per process. Failures are logged and swallowed sotracing never breaks a turn.diff --git a/crates/openhuman-core/src/agent/progress_tracing/export.rs b/crates/openhuman-core/src/agent/progress_tracing/export.rsindex a97e547e17..9cf849c642 100644--- a/crates/openhuman-core/src/agent/progress_tracing/export.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/export.rs@@ -125,3 +125,49 @@ pub(crate) async fn export_run_trace_from_journal(export_spans(&observability.agent_tracing, live_spans);}}++/// Export one completed child turn as a separate trace in its conversation.+/// The backend stamps the authenticated user onto the trace, while the child+/// run's original parent/root ids remain in trace metadata for navigation.+pub(crate) async fn export_subagent_journal_trace(+ config: &Config,+ journal_run_id: &str,+ thread_id: Option<&str>,+ agent_id: &str,+ task_id: &str,+) {+ if !config.observability.share_usage_data {+ return;+ }+ let observations = match crate::agent::tinyagents::journal::read_run_events(journal_run_id, 0)+ .await+ {+ Ok(observations) if !observations.is_empty() => observations,+ Ok(_) => return,+ Err(err) => {+ log::warn!("[agent-tracing] child journal read failed run_id={journal_run_id}: {err}");+ return;+ }+ };+ let first = &observations[0];+ let user_id = crate::security::credentials::identity::peek_credential_user_identity()+ .and_then(|identity| identity.id.or(identity.email));+ let trace_ctx = TraceContext::new(format!("subagent:{journal_run_id}"), user_id)+ .with_session_group(thread_id.unwrap_or(task_id).to_string())+ .with_agent_id(agent_id.to_string())+ .with_channel_source("subagent".to_string())+ .with_run_type(super::types::RunType::Subagent)+ .with_capture_content(config.observability.agent_tracing.capture_content)+ .with_run_lineage(+ Some(first.run_id.as_str().to_string()),+ first+ .parent_run_id+ .as_ref()+ .map(|id| id.as_str().to_string()),+ Some(first.root_run_id.as_str().to_string()),+ );+ let rooted = langfuse::root_subagent_observations(&observations);+ if let Err(err) = langfuse::push_observations(config, &trace_ctx, &rooted, None).await {+ log::warn!("[agent-tracing] child Langfuse push failed run_id={journal_run_id}: {err}");+ }+}diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse.rsindex a5dbc06ff1..98ddb58ca7 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse.rs@@ -1,7 +1,6 @@//! Langfuse ingestion exporter for agent trace spans (issue #4249 follow-up).//!-//! When `[observability.agent_tracing]` has `enabled = true` and-//! `backend = "langfuse"`, a completed run's spans are POSTed to the OpenHuman+//! When `observability.share_usage_data` is enabled, a completed run's spans are POSTed to the OpenHuman//! backend's Langfuse **proxy** route, `/telemetry/langfuse/ingestion`, derived//! from the **current backend hostname** (`effective_backend_api_url`). The//! request reuses the OpenHuman **session bearer** — the same auth every other@@ -15,7 +14,7 @@//! and non-PII token/cost figures — the latter promoted into Langfuse's native//! `usageDetails`/`costDetails`). Prompt/reply text and truncated tool I/O//! ride along only while `observability.agent_tracing.capture_content` is on;-//! with the default off, content is withheld and export stays metadata-only.+//! disabling that flag withholds content and leaves metadata-only export.use std::time::Duration;@@ -26,6 +25,7 @@ mod span_export;pub(crate) use environment::{environment_for_base, ingestion_url};pub(crate) use journal_export::push_observations;+pub(crate) use journal_export::root_subagent_observations;pub(crate) use span_export::push_spans;use super::{SpanStatus, TraceContext, TraceSpan};diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rsindex 12bf897db9..ebbc4fd351 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs@@ -33,7 +33,8 @@ const DEPLOYMENT_DOMAIN: &str = "tinyhumans.ai";/// the resolved backend host is the single existing config-driven fact that/// distinguishes deployments (there is no NODE_ENV-style flag in the core/// config) — loopback/local → development, a staging host under-/// [`DEPLOYMENT_DOMAIN`] → staging, anything else → production.+/// [`DEPLOYMENT_DOMAIN`] → staging, the canonical API host → production,+/// anything else → external.////// # Why the host is parsed rather than substring-matched///@@ -47,10 +48,10 @@ const DEPLOYMENT_DOMAIN: &str = "tinyhumans.ai";/// `staging`, so it classified as staging and passed the push gate — a host/// nothing in this tree owns, reached with a live session token. Anchoring/// to [`DEPLOYMENT_DOMAIN`] is what makes the classifier fail *closed*: a-/// host that is not ours is production, and production does not push.+/// host that is not ours is external, and external does not push./// - **Too narrow on local.** An IPv6 loopback backend (`http://[::1]:7788`)/// or a private LAN address matched none of the three literals and-/// classified as production, so a working development setup would have+/// classified as external, so a working development setup would have/// silently stopped exporting the moment the gate landed.////// Host classification is delegated to [`crate::api::config::host_is_local`],@@ -60,20 +61,23 @@ const DEPLOYMENT_DOMAIN: &str = "tinyhumans.ai";/// predicates that disagree is how a gate lets through exactly the case the/// other one blocks.///-/// An unparseable URL is production — the fail-closed default. `ingestion_url`+/// An unparseable URL is external — the fail-closed default. `ingestion_url`/// can return a non-URL placeholder when no backend host resolves, and the/// caller checks `starts_with("http")` separately; classifying that as/// anything pushable would defeat the gate.pub(crate) fn environment_for_base(base: &str) -> &'static str {let Ok(parsed) = url::Url::parse(base) else {- return "production";+ return "external";};if crate::api::config::host_is_local(&parsed) {return "development";}+ if parsed.scheme() != "https" {+ return "external";+ }let Some(url::Host::Domain(host)) = parsed.host() else {// A public IP literal is not a deployment of ours.- return "production";+ return "external";};let host = host.to_ascii_lowercase();let under_deployment_domain =@@ -85,26 +89,25 @@ pub(crate) fn environment_for_base(base: &str) -> &'static str {.split('.').next().is_some_and(|label| label == "staging" || label.starts_with("staging-"));- if under_deployment_domain && leftmost_is_staging {+ if host == "api.tinyhumans.ai" {+ "production"+ } else if under_deployment_domain && leftmost_is_staging {"staging"} else {- "production"+ "external"}}/// The environments this client may push to Langfuse from.///-/// An allowlist, not `!= "production"`, and it mirrors the backend's rule-/// (`backend:src/config/langfuseEnvironment.ts`) deliberately: the two gates-/// have to agree, and two negations drift more easily than two lists. Stating-/// the permitted set also makes the fail-closed property structural — if+/// An allowlist keeps the fail-closed property structural — if/// [`environment_for_base`] ever grows a fourth bucket, that bucket does not/// push until someone adds it here on purpose.////// `test` appears in the backend's list but not here because there is no such/// bucket on this side: [`environment_for_base`] maps loopback hosts to/// `development`, and that is what the Rust suite resolves to.-pub(super) const LANGFUSE_PUSH_ENVIRONMENTS: &[&str] = &["staging", "development"];+pub(super) const LANGFUSE_PUSH_ENVIRONMENTS: &[&str] = &["production", "staging", "development"];/// Whether a push is permitted for a resolved environment.pub(super) fn push_allowed(environment: &str) -> bool {@@ -119,17 +122,13 @@ static SKIP_LOGGED: std::sync::Once = std::sync::Once::new();////// # Why skip at all, when the backend already refuses///-/// Defence in depth, and latency. The backend answers `403 FEATURE_DISABLED`-/// outside staging (backend#1291), so nothing reaches Langfuse either way —-/// but a client that still asks pays a full authenticated round-trip on every-/// agent turn to be told no, and [`PUSH_TIMEOUT`] bounds that at ten seconds-/// when the host is slow. #5602 is that stall. The cheapest request is the one-/// not made.+/// Defence in depth: an unknown backend origin must not receive a session+/// bearer merely because usage sharing is enabled.////// # Why once per process, and at info////// This is on the path of every completed run. A warning per turn would move-/// the noise rather than remove it, and a skip in production is the configured+/// the noise rather than remove it, and a skip for an external host is the configured/// outcome, not a fault — so it is `info`, said once, and then silence. The/// caller receives `Ok(())`: skipping is a successful no-op, and returning/// `Err` would make the caller log the same line on every turn, which is thediff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rsindex c8869c1a86..55601cee89 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/journal_export.rs@@ -33,15 +33,39 @@ pub(super) fn trace_ctx_with_run_lineage(return trace_ctx.clone();};trace_ctx.clone().with_run_lineage(- Some(first.run_id.as_str().to_string()),- first- .parent_run_id- .as_ref()- .map(|id| id.as_str().to_string()),- Some(first.root_run_id.as_str().to_string()),+ trace_ctx+ .run_id+ .clone()+ .or_else(|| Some(first.run_id.as_str().to_string())),+ trace_ctx.parent_run_id.clone().or_else(|| {+ first+ .parent_run_id+ .as_ref()+ .map(|id| id.as_str().to_string())+ }),+ trace_ctx+ .root_run_id+ .clone()+ .or_else(|| Some(first.root_run_id.as_str().to_string())),)}+/// A child is a root observation within its own trace. Preserve its original+/// run lineage on the trace metadata before calling this projection.+pub(crate) fn root_subagent_observations(+ observations: &[AgentObservation],+) -> Vec<AgentObservation> {+ observations+ .iter()+ .cloned()+ .map(|mut observation| {+ observation.parent_run_id = None;+ observation.root_run_id = observation.run_id.clone();+ observation+ })+ .collect()+}+pub(super) fn trace_config_from_context(trace_ctx: &TraceContext,environment: &str,@@ -138,6 +162,14 @@ pub(super) fn insert_run_telemetry_generation(let Some(batch) = payload.get_mut("batch").and_then(Value::as_array_mut) else {return false;};+ // Native per-call charges are already counted by Langfuse. Adding the+ // run aggregate as another generation would double-count the same spend.+ if batch.iter().any(|event| {+ event["type"] == "generation-create"+ && event["body"]["costDetails"]["total"].as_f64().is_some()+ }) {+ return false;+ }let Some(trace_id) = batch.first().and_then(|event| event.get("body"))diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rsindex 1580773178..dd40378eae 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/span_export.rs@@ -248,7 +248,7 @@ pub(crate) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(let url = ingestion_url(config);// Ahead of the URL check, the session lookup and the request: a skipped// environment must cost nothing per turn. An unresolvable URL lands in- // `environment_for_base`'s catch-all, which is `production` — so a garbage+ // `environment_for_base`'s catch-all, which is `external` — so a garbage// host skips rather than erroring, which is the right way round.let environment = environment_for_base(&url);if skip_push(environment) {diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rsindex 28746165ed..e55c537c3e 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse_batch_tests.rs@@ -36,25 +36,22 @@ fn split_ingestion_batch_passes_small_payloads_through() {assert_eq!(split_ingestion_batch(no_batch.clone(), 500), vec![no_batch]);}-// ── production push gate (#5602) ──────────────────────────────-//-// The client already knew which environment it was in — `environment_for_base`-// has returned "production" for a prod host since it was written — and pushed-// anyway, paying an authenticated round-trip per agent turn bounded by the-// 10s `PUSH_TIMEOUT`. These pin that it now skips instead.+// The canonical production and staging APIs accept traces. Unknown origins+// must remain closed before a session bearer is read.#[test]-fn push_is_allowed_only_in_staging_and_development() {+fn push_is_allowed_for_our_backends() {+ assert!(push_allowed("production"));assert!(push_allowed("staging"));assert!(push_allowed("development"));- assert!(!push_allowed("production"));+ assert!(!push_allowed("external"));}#[test]fn an_unrecognised_environment_fails_closed() {// The allowlist, not a `!= "production"` negation, is what makes this// true: a bucket nobody has thought of yet does not push.- for unknown in ["preview", "prod", "PRODUCTION", "", "qa"] {+ for unknown in ["preview", "prod", "PRODUCTION", "", "qa", "external"] {assert!(!push_allowed(unknown),"{unknown:?} must not push — the allowlist is the fail-closed guard"@@ -70,19 +67,19 @@ fn every_environment_for_base_bucket_is_classified_deliberately() {"https://staging-api.tinyhumans.ai")));assert!(push_allowed(environment_for_base("http://localhost:7788")));- assert!(!push_allowed(environment_for_base(+ assert!(push_allowed(environment_for_base("https://api.tinyhumans.ai")));}#[tokio::test]-async fn push_spans_skips_production_without_a_session_or_a_request() {+async fn push_spans_skips_external_without_a_session_or_a_request() {// No live session is seeded here, so reaching `require_live_session_token`// would return `Err`. `Ok(())` therefore proves the gate returned before// it — i.e. before any credential work, and before any network call.let mut config = Config::default();- config.api_url = Some("https://api.tinyhumans.ai/api/v1".to_string());- assert_eq!(environment_for_base(&ingestion_url(&config)), "production");+ config.api_url = Some("https://other.example".to_string());+ assert_eq!(environment_for_base(&ingestion_url(&config)), "external");let spans = vec![span("trace:req-1",@@ -98,15 +95,15 @@ async fn push_spans_skips_production_without_a_session_or_a_request() {assert_eq!(push_spans(&config, &spans).await,Ok(()),- "a production push must be a silent no-op, not an error the caller \+ "an external push must be a silent no-op, not an error the caller \logs on every turn");}#[tokio::test]-async fn push_observations_skips_production_too() {+async fn push_observations_skips_external_too() {let mut config = Config::default();- config.api_url = Some("https://api.tinyhumans.ai/api/v1".to_string());+ config.api_url = Some("https://other.example".to_string());let ctx = TraceContext::new("trace:req-1", Some("user-1".to_string()));let observations = vec![obs(1,@@ -128,7 +125,7 @@ async fn push_observations_skips_production_too() {#[tokio::test]async fn an_unresolvable_host_skips_rather_than_erroring() {// `ingestion_url` on a base it cannot parse lands in the catch-all- // bucket, which is production — so the gate swallows it first. Better+ // bucket, which is external — so the gate swallows it first. Better// than the previous `Err`, which the caller logged every turn.let mut config = Config::default();config.api_url = Some("not a url".to_string());@@ -259,6 +256,51 @@ fn trace_ctx_with_run_lineage_derives_from_subagent_observations() {assert!(untouched.root_run_id.is_none());}+#[test]+fn child_run_roots_its_own_trace_and_preserves_parent_lineage() {+ let child = AgentObservation {+ event_id: EventId::new("child-evt-1"),+ run_id: RunId::new("child-run"),+ parent_run_id: Some(RunId::new("parent-run")),+ root_run_id: RunId::new("root-run"),+ offset: 1,+ ts_ms: 1_000,+ event: AgentEvent::ModelCompleted {+ call_id: CallId::new("model-1"),+ started_at_ms: Some(900),+ usage: Some(Usage::new(10, 3)),+ input: None,+ output: None,+ },+ };+ let ctx = trace_ctx_with_run_lineage(+ &TraceContext::new("subagent:child-run", Some("user-1".into()))+ .with_session_group("thread-1")+ .with_run_lineage(+ Some("child-run".into()),+ Some("parent-run".into()),+ Some("root-run".into()),+ ),+ &root_subagent_observations(&[child.clone()]),+ );+ let trace = trace_config_from_context(&ctx, "production");+ assert_eq!(trace.session_id.as_deref(), Some("thread-1"));+ assert_eq!(trace.metadata["parent_run_id"], "parent-run");+ assert_eq!(trace.metadata["root_run_id"], "root-run");+ let rooted = root_subagent_observations(&[child]);+ assert!(rooted[0].parent_run_id.is_none());+ assert_eq!(rooted[0].root_run_id.as_str(), "child-run");+ let client = LangfuseClient::proxy("https://api.tinyhumans.ai", "token").unwrap();+ let batch = client.build_ingestion_batch(trace, &rooted).unwrap();+ let child_run = batch["batch"]+ .as_array()+ .unwrap()+ .iter()+ .find(|event| event["type"] == "span-create" && event["body"]["name"] == "agent")+ .unwrap();+ assert!(child_run["body"].get("parentObservationId").is_none());+}+#[test]fn journal_observation_content_follows_capture_gate() {let observations = vec![@@ -376,6 +418,20 @@ fn run_telemetry_inserts_aggregate_generation() {assert_eq!(body["metadata"]["run_id"], "req-1");assert_eq!(body["metadata"]["tool_count"], 2);assert_eq!(body["metadata"]["provider"], "managed");++ let mut already_charged = client+ .build_ingestion_batch(+ trace_config_from_context(&TraceContext::new("trace:req-1", None), "production"),+ &observations,+ )+ .unwrap();+ already_charged["batch"][2]["body"]["costDetails"] = json!({ "total": 0.0123 });+ let before = already_charged["batch"].as_array().unwrap().len();+ assert!(!insert_run_telemetry_generation(+ &mut already_charged,+ Some(&telemetry)+ ));+ assert_eq!(already_charged["batch"].as_array().unwrap().len(), before);}#[test]@@ -597,10 +653,10 @@ fn environment_derivation_from_backend_base() {/// A hostname that merely *contains* `staging` is not ours. The classifier/// gates whether a live session token leaves the process, so anything it-/// cannot positively recognise has to land on `production` — which does+/// cannot positively recognise has to land on `external` — which does/// not push.#[test]-fn a_lookalike_staging_host_is_production_not_staging() {+fn a_lookalike_staging_host_is_external_not_staging() {for base in [// The substring match this replaced classified all of these as// staging, and `push_allowed` would then have let them through.@@ -611,11 +667,13 @@ fn a_lookalike_staging_host_is_production_not_staging() {"https://api-staging-mirror.tinyhumans.ai",// A public IP literal is never a deployment of ours."https://93.184.216.34",+ // Never send a session bearer to a public backend over plaintext.+ "http://api.tinyhumans.ai",] {let environment = environment_for_base(base);assert_eq!(- environment, "production",- "{base} must classify as production, got {environment}"+ environment, "external",+ "{base} must classify as external, got {environment}");assert!(!push_allowed(environment), "{base} must not be pushable");}@@ -623,7 +681,7 @@ fn a_lookalike_staging_host_is_production_not_staging() {/// The local buckets the substring form missed. An IPv6 loopback backend/// is an ordinary local setup, and before the parse it classified as-/// production — so turning the push gate on would have silently stopped+/// external — so turning the push gate on would have silently stopped/// exports that had been working.#[test]fn local_backends_are_development_including_ipv6_and_private_ranges() {diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rsindex 0d967b5044..d6e431289c 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse_trace_fields_tests.rs@@ -5,11 +5,11 @@ use crate::agent::progress_tracing::langfuse::span_export::spans_to_langfuse_bat/// pushable bucket. `ingestion_url` returns a non-URL placeholder when no/// backend host resolves.#[test]-fn an_unparseable_base_is_production() {+fn an_unparseable_base_is_external() {for base in ["", "not a url", "/api/v1/ingestion"] {assert_eq!(environment_for_base(base),- "production",+ "external","{base:?} must fail closed");}diff --git a/crates/openhuman-core/src/agent/progress_tracing/types.rs b/crates/openhuman-core/src/agent/progress_tracing/types.rsindex bcf4de2048..1a082b006c 100644--- a/crates/openhuman-core/src/agent/progress_tracing/types.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/types.rs@@ -9,10 +9,9 @@ use serde::Serialize;/// Langfuse trace tags (`run:<type>`) and metadata (`run_type`) so runs can be/// filtered in the UI.///-/// Only kinds actually observable at the collector installation point (the-/// web progress bridge) exist here: orchestration passes, subconscious runs,-/// cron turns, and meeting agents run their turns WITHOUT a progress bridge-/// today, so they never reach the span collector and get no variant.+/// Covers web progress bridge turns and child turns exported from their own+/// durable journals. Other background paths without either export hook do not+/// produce an agent trace yet.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub enum RunType {/// Interactive user chat turn (desktop UI / socket / PTT / dictation).@@ -23,6 +22,8 @@ pub enum RunType {/// Inbound message relayed from an external channel (Telegram, Discord,/// Slack, …) through the channel bus.ChannelInbound,+ /// A delegated child turn, exported as a trace in the parent conversation.+ Subagent,}impl RunType {@@ -32,6 +33,7 @@ impl RunType {RunType::InteractiveChat => "interactive_chat",RunType::AutonomousTask => "autonomous_task",RunType::ChannelInbound => "channel_inbound",+ RunType::Subagent => "subagent",}}diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rsindex 1e093d1e2d..5c733026cc 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs@@ -179,6 +179,7 @@ pub(in super::super) async fn run_subagent_via_graph(// otherwise a child remains in its parent's conversation. Do this before// constructing *any* model so managed requests, transcript metadata, and// the child carrier cannot disagree.+ let trace_session_group = run_context.thread_id.clone().or_else(|| thread_id.clone());let thread_id = inherited_thread_id(run_context.thread_id.clone(), thread_id);tracing::info!(model,@@ -200,10 +201,12 @@ pub(in super::super) async fn run_subagent_via_graph(// seam this is a sub-agent turn, so the unknown-tool recovery uses the// sub-agent wording. With no progress sink the scoped events simply have// nowhere to go, which is harmless.+ let child_journal_run_id = std::sync::Arc::new(std::sync::Mutex::new(None));let subagent_scope = Some(SubagentScope {agent_id: agent_id.to_string(),task_id: task_id.to_string(),extended_policy,+ journal_run_id: Some(child_journal_run_id.clone()),});// A standalone summarizer model for the cap-hit checkpoint call below (the@@ -343,6 +346,29 @@ pub(in super::super) async fn run_subagent_via_graph()).await;+ if let Some(config) = config.filter(|config| config.observability.share_usage_data) {+ let journal_run_id = child_journal_run_id+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone();+ if let Some(journal_run_id) = journal_run_id {+ let config = config.clone();+ let thread_id = trace_session_group.clone();+ let agent_id = agent_id.to_string();+ let task_id = task_id.to_string();+ tokio::spawn(async move {+ crate::agent::progress_tracing::export_subagent_journal_trace(+ &config,+ &journal_run_id,+ thread_id.as_deref(),+ &agent_id,+ &task_id,+ )+ .await;+ });+ }+ }+let mut outcome = match run_result {Ok(outcome) => outcome,Err(err) => {diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rsindex 758e87dd03..c010be6024 100644--- a/crates/openhuman-core/src/agent/tinyagents/model.rs+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs@@ -133,6 +133,14 @@ fn response_to_model_response(usage.cache_read_tokens = u.cached_input_tokens;usage.cache_creation_tokens = u.cache_creation_tokens;usage.reasoning_tokens = u.reasoning_tokens;+ if u.charged_amount_usd.is_finite() && u.charged_amount_usd > 0.0 {+ usage.charged_amount = Some(tinyinference_llm::usage::ChargedAmount::usd_micros(+ (u.charged_amount_usd * 1_000_000.0).round() as i64,+ ));+ }+ if u.context_window > 0 {+ usage.context_window_tokens = Some(u.context_window);+ }usage});let finish_reason = if tool_calls.is_empty() {diff --git a/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs b/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rsindex 4afabca088..892658998b 100644--- a/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/model_g1_usage_tests_tests.rs@@ -33,6 +33,11 @@ fn usage_round_trips_charged_usd_and_all_token_breakdowns() {assert_eq!(usage.cache_read_tokens, 40);assert_eq!(usage.cache_creation_tokens, 10);assert_eq!(usage.reasoning_tokens, 7);+ assert_eq!(+ usage.charged_amount.map(|amount| amount.micros),+ Some(12_300)+ );+ assert_eq!(usage.context_window_tokens, Some(128_000));// Charged USD + context window ride raw and reconstruct exactly.let recovered = usage_info_from_response(&model_response).expect("usage info");diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rsindex 6bd6db2726..2b32ef6b37 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs@@ -22,6 +22,9 @@ pub struct SubagentScope {pub agent_id: String,pub task_id: String,pub extended_policy: bool,+ /// The durable journal stream minted for this child turn. Shared with the+ /// host so it can export the completed child as its own Langfuse trace.+ pub journal_run_id: Option<Arc<Mutex<Option<String>>>>,}/// A shared 1-based model-call (iteration) cursor. The bridge advances it ondiff --git a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rsindex 236a1e3207..a20b35bccd 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs@@ -176,6 +176,7 @@ async fn subagent_model_completed_carries_task_attribution() {agent_id: "context_scout".to_string(),task_id: "ctx-1".to_string(),extended_policy: true,+ journal_run_id: None,}),Arc::default(),Arc::default(),diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex 419a3ab45c..d672bd0ea2 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -441,6 +441,14 @@ async fn run_turn_via_tinyagents_inner(// the restart-stable `{run_id}-evt-{offset}` a late-attach replay// reconstructs the timeline from (05.1). The same id keys the journal + status.let journal_run_id = journal::mint_run_id();+ if let Some(scope) = &subagent_scope {+ if let Some(slot) = &scope.journal_run_id {+ *slot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) =+ Some(journal_run_id.as_str().to_string());+ }+ }let events = Some(EventSink::with_stream_id(journal_run_id.as_str()));// Attach the event bridge for EVERY turn — including an unobserveddiff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rsindex 6f46e197d2..8b0ad3ddef 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/observability.rs@@ -26,8 +26,8 @@ impl Config {}}- // Opt-in: export prompt/reply content on trace spans (default off — a- // deliberate PII reversal). Token/cost export is unaffected by this flag.+ // Prompt/reply content is captured by default; operators can disable+ // it independently of token and cost telemetry.if let Some(flag) = env.get("OPENHUMAN_AGENT_TRACING_CAPTURE_CONTENT") {let normalized = flag.trim().to_ascii_lowercase();match normalized.as_str() {diff --git a/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs b/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rsindex 12815894d8..f9967d63fe 100644--- a/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs+++ b/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs@@ -56,8 +56,9 @@ fn ingestion_url(config: &Config) -> String {/// traces can be correlated with the app build that produced them.const APP_VERSION: &str = env!("CARGO_PKG_VERSION");-/// Builds the [`LangfuseTraceConfig`] for one flow run: the trace id **and**-/// session id are the run's `thread_id` (`flow:{flow_id}:{uuid}`), the trace+/// Builds the [`LangfuseTraceConfig`] for one flow run: the trace id is the+/// run's `thread_id` (`flow:{flow_id}:{uuid}`), while the session id is the+/// stable `flow:{flow_id}` so repeated runs group together. The trace/// is named `flow.run:{flow_name}`, run-type tags (`run:flow` +/// `trigger:<kind>`) mark how the run started, and flow coordinates plus the/// app version ride on the trace metadata. No content — ids, name, status,@@ -72,7 +73,7 @@ fn build_flow_trace_config(LangfuseTraceConfig {trace_id: Some(thread_id.to_string()),name: Some(format!("flow.run:{flow_name}")),- session_id: Some(thread_id.to_string()),+ session_id: Some(format!("flow:{flow_id}")),release: Some(APP_VERSION.to_string()),tags: vec!["run:flow".to_string(),diff --git a/crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rs b/crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rsindex 57ffdc64ab..4ae352ca28 100644--- a/crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rs+++ b/crates/openhuman-core/src/flows/tinyflows/langfuse_export_tests.rs@@ -92,7 +92,7 @@ fn flow_trace_config_uses_thread_id_and_flow_coordinates() {FlowRunTrigger::Schedule,);assert_eq!(trace.trace_id.as_deref(), Some("flow:flow-1:uuid-1"));- assert_eq!(trace.session_id.as_deref(), Some("flow:flow-1:uuid-1"));+ assert_eq!(trace.session_id.as_deref(), Some("flow:flow-1"));assert_eq!(trace.name.as_deref(), Some("flow.run:Daily digest"));assert_eq!(trace.tags, vec!["run:flow", "trigger:schedule"]);assert_eq!(trace.metadata["flow_id"], "flow-1");@@ -129,12 +129,12 @@ fn batch_carries_flow_trace_and_langgraph_keys_on_node_spans() {.expect("batch");let batch = payload["batch"].as_array().expect("batch array");- // Trace: id + sessionId are the run thread id; name and flow+ // Trace id is the run thread id; sessionId groups runs by flow; name and flow// coordinates as configured.let trace_event = &batch[0];assert_eq!(trace_event["type"], "trace-create");assert_eq!(trace_event["body"]["id"], thread_id);- assert_eq!(trace_event["body"]["sessionId"], thread_id);+ assert_eq!(trace_event["body"]["sessionId"], "flow:flow-1");assert_eq!(trace_event["body"]["name"], "flow.run:Daily digest");assert_eq!(trace_event["body"]["metadata"]["flow_id"], "flow-1");assert_eq!(trace_event["body"]["metadata"]["status"], "completed");diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rsindex 0fabecc73b..440206873b 100644--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs@@ -296,8 +296,7 @@ fn subagent_worktree_detail(/// Trace user attribution for a turn whose stored user payload carries no identity/// (headless / autonomous / freshly booted cores): read the on-disk/// app-session profile and return the user's email (preferred) or backend-/// user id. `None` when signed out or the profile is unreadable — the caller-/// then falls back to the transport client id.+/// user id. `None` when signed out or the profile is unreadable.fn session_profile_user_attribution(config: &crate::config::Config) -> Option<String> {let state = crate::security::credentials::session_support::build_session_state(config).ok()?;state@@ -370,10 +369,10 @@ pub(crate) fn spawn_progress_bridge(let mut turn_state =TurnStateMirror::new(turn_state_store, thread_id.clone(), request_id.clone());- // #3886: opt-in structured tracing export. When enabled, fold the same+ // #3886: structured tracing export. When enabled, fold the same// progress stream into OTel/Langfuse-style spans correlated by session// id (falling back to the thread id for headless/autonomous runs).- // `None` (disabled) is zero-cost.+ // `None` (both remote and local exporters disabled) is zero-cost.let mut journal_trace_ctx = None;let mut span_collector = if config.observability.share_usage_data|| config.observability.agent_tracing.enabled@@ -389,15 +388,13 @@ pub(crate) fn spawn_progress_bridge(// Attribute the trace to the *real* authenticated user (cached// stored credential identity: id, else email) — the transport client// id (socket client / "system") is NOT a user; it rides along as- // the separate `client.id` metadata attribute. When no identity is- // cached (signed-out / fresh install), fall back to the client id- // so the trace still carries some attribution.+ // the separate `client.id` metadata attribute. The backend stamps+ // the authenticated JWT user on every accepted trace.let identity = crate::security::credentials::identity::peek_credential_user_identity();- let user_attributed = identity.is_some();let user_id = identity.and_then(|i| i.id.or(i.email))- .or_else(|| session_profile_user_attribution(&config))- .unwrap_or_else(|| client_id.clone());+ .or_else(|| session_profile_user_attribution(&config));+ let user_attributed = user_id.is_some();// Run origin for trace metadata: the request's source tag// ("ptt"/"dictation"/"type"/"autonomous"/…), else a// plain interactive chat turn.@@ -422,7 +419,7 @@ pub(crate) fn spawn_progress_bridge(capture_content,request_id,);- let mut trace_ctx = TraceContext::new(trace_id, Some(user_id))+ let mut trace_ctx = TraceContext::new(trace_id, user_id).with_session_group(thread_id.clone()).with_client_id(client_id.clone()).with_channel_source(channel_source)diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 19cafdace8..5a84a8d5d6 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 19cafdace8fc87a1015f49198984fd1e4c66ddae+Subproject commit 5a84a8d5d66355c054fba9e894cf9c58ea4335a5