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(telemetry): export readable agent turns through OTLP
Steven Enamakel214b83154ecf
diff --git a/crates/openhuman-core/src/agent/progress_tracing.rs b/crates/openhuman-core/src/agent/progress_tracing.rsindex bf191b101c..298794c1fe 100644--- a/crates/openhuman-core/src/agent/progress_tracing.rs+++ b/crates/openhuman-core/src/agent/progress_tracing.rs@@ -27,7 +27,7 @@//! token/cost figures (model labels are `{provider_id}.{model}`, e.g.//! `managed.hint:chat`). While `observability.agent_tracing.capture_content` is//! on (the default), content is additionally recorded as span `input`/`output` — the turn's-//! prompt/reply, each generation's **truncated** request messages (system+//! prompt/reply, each generation's bounded structured request messages (system//! prompt included) + completion, **truncated** tool arguments/results, and//! each subagent's delegated prompt + final output. With the flag off,//! none of that content ever reaches the in-memory span, so@@ -55,6 +55,7 @@pub(crate) mod journal_projection;/// Langfuse ingestion exporter (remote push through the configured backend).pub(crate) mod langfuse;+mod otlp;/// The [`SpanCollector`] state machine that folds progress events into spans.mod collector;diff --git a/crates/openhuman-core/src/agent/progress_tracing/README.md b/crates/openhuman-core/src/agent/progress_tracing/README.mdindex 5246b0466d..7b46e9d4ee 100644--- a/crates/openhuman-core/src/agent/progress_tracing/README.md+++ b/crates/openhuman-core/src/agent/progress_tracing/README.md@@ -22,21 +22,16 @@ content).`observability.share_usage_data` is on (the default), and local NDJSONexport to `export_path` or the app log when`observability.agent_tracing.enabled` is on (opt-in).-- `langfuse.rs` + `langfuse/` (`environment.rs`, `ingestion_batch.rs`,- `span_export.rs`, `journal_export.rs`) — Langfuse- ingestion exporter: `push_spans` (live spans) and `push_observations`- (journal observations plus the run-ledger `RunTelemetry` aggregate). Both- POST to the backend's `/telemetry/langfuse/ingestion` proxy, derived from- `effective_backend_api_url`, authenticated with the session bearer; the- backend injects the Langfuse project keys and forwards to- `/api/public/ingestion`. `push_spans` builds a bare `reqwest` request and- 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 the canonical production API and `staging`/`development` hosts- (`environment_for_base`, `LANGFUSE_PUSH_ENVIRONMENTS`) and skipped elsewhere- with one `info` log per process. Failures are logged and swallowed so- tracing never breaks a turn.+- `otlp.rs` — the remote agent-turn exporter. It turns completed live spans+ into OTLP/HTTP JSON, preserves the root turn's input/output, maps+ TinyInference messages into role-labeled conversations, puts usage only on+ model generations, and summarizes repeated internal tool discovery.+ It POSTs through the authenticated backend's+ `/telemetry/langfuse/otel/v1/traces` proxy; the backend supplies project+ keys and authoritative user attribution. Export is on by default through+ `observability.share_usage_data`; local NDJSON export remains optional.+- `langfuse.rs` + `langfuse/` retain the legacy batch projection for+ compatibility tests and the flow-run exporter. Agent turns use `otlp.rs`.- `journal_projection.rs` — `spans_from_observations` rebuilds spans from thedurable `AgentObservation` journal instead of the live stream, by foldingjournalled events through the same `SpanCollector`, so a UI/supervisor can@@ -57,9 +52,8 @@ Tests live in this directory as `*_tests.rs` files, e.g.`spans_from_observations` over the run journal, then calls`export_run_trace_from_journal` (journal available) or `export_run_trace`.-`flows/tinyflows/langfuse_export.rs` is the flow-run counterpart: it mirrors-the proxy route, bearer auth, and timeout of `push_spans` but has its own-copy and does not call this module.+`flows/tinyflows/langfuse_export.rs` is the separate flow-run exporter and+currently still uses the legacy batch proxy.## Related docsdiff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/events.rsindex b262611486..13ea7e5612 100644--- a/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs@@ -430,10 +430,16 @@ impl SpanCollector {};if let Some(span) = self.spans.get_mut(index) {if let Some(text) = input {- span.input = Some(serde_json::Value::String(text.clone()));+ span.input = Some(serde_json::Value::String(truncate_chars(+ text,+ MAX_MODEL_CONTENT_CHARS,+ )));}if let Some(text) = output {- span.output = Some(serde_json::Value::String(text.clone()));+ span.output = Some(serde_json::Value::String(truncate_chars(+ text,+ MAX_MODEL_CONTENT_CHARS,+ )));}log::debug!(target: "agent-tracing",diff --git a/crates/openhuman-core/src/agent/progress_tracing/export.rs b/crates/openhuman-core/src/agent/progress_tracing/export.rsindex 9cf849c642..4b001c54ec 100644--- a/crates/openhuman-core/src/agent/progress_tracing/export.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/export.rs@@ -5,6 +5,7 @@ use crate::config::schema::AgentTracingConfig;use crate::config::Config;use super::langfuse;+use super::otlp;use super::serialize::spans_to_ndjson;use super::types::{TraceContext, TraceSpan};@@ -68,11 +69,9 @@ pub(crate) fn export_spans(config: &AgentTracingConfig, spans: &[TraceSpan]) {/// 1. **Usage-data sharing** (`observability.share_usage_data`, on by default):/// push the run's spans to the backend Langfuse proxy — endpoint derived from/// the current backend host, authed with the session bearer (see-/// [`langfuse::push_spans`]). A failure (no live session, network, rejected-/// batch) just logs; there is no local fallback, since sharing and local-/// export are distinct opt-ins. Web-channel turns that successfully read a-/// durable tinyagents journal should call [`export_run_trace_from_journal`]-/// instead, so the remote push uses the crate-owned observation exporter.+/// [`otlp::push_spans`]). A failure (no live session, network, rejected+/// payload) just logs; there is no local fallback, since sharing and local+/// export are distinct opt-ins./// 2. **Local exporter** (`observability.agent_tracing.enabled`, opt-in): append/// OTel/Langfuse-format NDJSON to the configured file or the app log via/// [`export_spans`].@@ -85,7 +84,7 @@ pub(crate) async fn export_run_trace(config: &Config, spans: &[TraceSpan]) {let observability = &config.observability;if observability.share_usage_data {- if let Err(err) = langfuse::push_spans(config, spans).await {+ if let Err(err) = otlp::push_spans(config, spans).await {log::warn!("[agent-tracing] Langfuse usage-data push failed ({err})");}}@@ -96,29 +95,24 @@ pub(crate) async fn export_run_trace(config: &Config, spans: &[TraceSpan]) {}/// Export a completed run when durable tinyagents observations are available.-/// Remote usage-data sharing uses the crate Langfuse exporter over the journal;-/// local tracing still writes the live spans until the migration deletes the-/// legacy span collector/exporter path.+/// Remote usage-data sharing exports the live span tree as OTLP. The journal+/// is still read for local parity checks and future recovery work.pub(crate) async fn export_run_trace_from_journal(config: &Config,- trace_ctx: &TraceContext,- observations: &[tinyagents_harness::observability::AgentObservation],- run_telemetry: Option<&tinyagents_session::run_ledger::RunTelemetry>,+ _trace_ctx: &TraceContext,+ _observations: &[tinyagents_harness::observability::AgentObservation],+ _run_telemetry: Option<&tinyagents_session::run_ledger::RunTelemetry>,live_spans: &[TraceSpan],) {- if observations.is_empty() && live_spans.is_empty() {+ if live_spans.is_empty() {return;}let observability = &config.observability;- if observability.share_usage_data && !observations.is_empty() {- if let Err(err) =- langfuse::push_observations(config, trace_ctx, observations, run_telemetry).await- {- log::warn!("[agent-tracing] Langfuse journal usage-data push failed ({err})");+ if observability.share_usage_data && !live_spans.is_empty() {+ if let Err(err) = otlp::push_spans(config, live_spans).await {+ log::warn!("[agent-tracing] Langfuse OTLP push failed ({err})");}- } else if observability.share_usage_data {- log::debug!("[agent-tracing] no journal observations for Langfuse usage-data push");}if observability.agent_tracing.enabled && !live_spans.is_empty() {@@ -167,7 +161,24 @@ pub(crate) async fn export_subagent_journal_trace(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}");+ let mut spans =+ super::journal_projection::spans_from_observations(trace_ctx.clone(), 0, &rooted);+ if let Some(root) = spans.iter_mut().find(|span| span.parent_span_id.is_none()) {+ for (key, value) in [+ ("run_id", trace_ctx.run_id.as_deref()),+ ("parent_run_id", trace_ctx.parent_run_id.as_deref()),+ ("root_run_id", trace_ctx.root_run_id.as_deref()),+ ] {+ if let Some(value) = value {+ root.attributes+ .insert(key.to_string(), serde_json::json!(value));+ }+ }+ }+ otlp::prepare_subagent_root(&mut spans);+ if let Err(err) = otlp::push_spans(config, &spans).await {+ log::warn!(+ "[agent-tracing] child Langfuse OTLP 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 98ddb58ca7..bddb98e8a5 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse.rs@@ -19,17 +19,21 @@use std::time::Duration;mod environment;+#[allow(dead_code)] // Legacy batch exporter remains for compatibility tests.mod ingestion_batch;+#[allow(dead_code)] // Child-run rooting is still shared with the OTLP path.mod journal_export;+#[allow(dead_code)] // Legacy batch exporter remains for compatibility tests.mod span_export;-pub(crate) use environment::{environment_for_base, ingestion_url};+pub(crate) use environment::{environment_for_base, ingestion_url, skip_push};+#[cfg(test)]pub(crate) use journal_export::push_observations;pub(crate) use journal_export::root_subagent_observations;+#[cfg(test)]pub(crate) use span_export::push_spans;use super::{SpanStatus, TraceContext, TraceSpan};-use environment::skip_push;#[cfg(test)]use crate::config::Config;diff --git a/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs b/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rsindex ebbc4fd351..0c07b4adc4 100644--- a/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/langfuse/environment.rs@@ -133,7 +133,7 @@ static SKIP_LOGGED: std::sync::Once = std::sync::Once::new();/// 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 the/// thing being avoided.-pub(super) fn skip_push(environment: &str) -> bool {+pub(crate) fn skip_push(environment: &str) -> bool {if push_allowed(environment) {return false;}diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp.rsnew file mode 100644index 0000000000..d8df7bebf1--- /dev/null+++ b/crates/openhuman-core/src/agent/progress_tracing/otlp.rs@@ -0,0 +1,499 @@+//! Bounded OTLP/HTTP JSON export through the authenticated backend proxy.++use std::collections::{BTreeMap, HashMap};++use serde_json::{json, Value};+use sha2::{Digest, Sha256};++use super::langfuse::{environment_for_base, ingestion_url, skip_push};+use super::types::{SpanKind, SpanStatus, TraceSpan};+use crate::api::jwt::bearer_authorization_value;+use crate::config::Config;+use crate::security::credentials::session_support::require_live_session_token;++// The backend JSON parser caps requests at 10 MiB. A generation can carry a+// 200 KiB structured prompt, so use a much smaller transport batch.+const MAX_SPANS_PER_REQUEST: usize = 20;+const MAX_REQUEST_BYTES: usize = 8_000_000;++fn hex_id(source: &str, bytes: usize) -> String {+ let digest = Sha256::digest(source.as_bytes());+ digest[..bytes]+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect()+}++fn attribute(key: &str, value: impl Into<String>) -> Value {+ json!({ "key": key, "value": { "stringValue": value.into() } })+}++fn json_attribute(key: &str, value: &Value) -> Value {+ attribute(key, value.to_string())+}++fn string_attr<'a>(span: &'a TraceSpan, key: &str) -> Option<&'a str> {+ span.attributes.get(key).and_then(Value::as_str)+}++fn usage_details(span: &TraceSpan) -> Option<Value> {+ let input = span.attributes.get("gen_ai.usage.input_tokens")?.as_u64()?;+ let output = span+ .attributes+ .get("gen_ai.usage.output_tokens")?+ .as_u64()?;+ let cached = span+ .attributes+ .get("gen_ai.usage.cached_input_tokens")+ .and_then(Value::as_u64)+ .unwrap_or(0);+ Some(json!({+ "input": input.saturating_sub(cached),+ "cache_read_input_tokens": cached,+ "output": output,+ "total": input.saturating_add(output),+ }))+}++fn message_content(payload: &Value) -> String {+ if let Some(content) = payload.get("content").and_then(Value::as_str) {+ return content.to_string();+ }+ payload+ .get("content")+ .and_then(Value::as_array)+ .map(|blocks| {+ blocks+ .iter()+ .filter_map(|block| {+ if let Some(text) = block.as_str() {+ return Some(text.to_string());+ }+ let object = block.as_object()?;+ if let Some(text) = object.get("text").and_then(Value::as_str) {+ return Some(text.to_string());+ }+ if let Some(value) = object.get("json") {+ return Some(value.to_string());+ }+ object.keys().next().map(|kind| format!("[{kind} content]"))+ })+ .collect::<Vec<_>>()+ .join("\n")+ })+ .unwrap_or_default()+}++fn normalize_message(role: &str, payload: &Value) -> Value {+ let mut message = json!({ "role": role, "content": message_content(payload) });+ if role == "tool" {+ if let Some(id) = payload.get("tool_call_id") {+ message["tool_call_id"] = id.clone();+ }+ }+ if role == "assistant" {+ if let Some(calls) = payload.get("tool_calls").and_then(Value::as_array) {+ if !calls.is_empty() {+ message["tool_calls"] = Value::Array(+ calls+ .iter()+ .map(|call| {+ let arguments = call.get("arguments").cloned().unwrap_or(Value::Null);+ json!({+ "id": call.get("id").cloned().unwrap_or(Value::Null),+ "type": "function",+ "function": {+ "name": call.get("name").cloned().unwrap_or(Value::Null),+ "arguments": if let Some(raw) = arguments.as_str() {+ raw.to_string()+ } else {+ arguments.to_string()+ },+ },+ })+ })+ .collect(),+ );+ }+ }+ let reasoning = payload+ .get("content")+ .and_then(Value::as_array)+ .map(|blocks| {+ blocks+ .iter()+ .filter_map(|block| block.get("thinking")?.get("text")?.as_str())+ .collect::<Vec<_>>()+ .join("\n")+ })+ .unwrap_or_default();+ if !reasoning.is_empty() {+ message["reasoning"] = json!(reasoning);+ }+ }+ message+}++fn normalize_generation_io(value: &Value, output: bool) -> Value {+ if let Some(messages) = value.as_array() {+ return Value::Array(+ messages+ .iter()+ .filter_map(|message| {+ let object = message.as_object()?;+ if object.get("role").and_then(Value::as_str).is_some() {+ return Some(message.clone());+ }+ for role in ["system", "user", "assistant", "tool"] {+ if let Some(payload) = object.get(role) {+ return Some(normalize_message(role, payload));+ }+ }+ None+ })+ .collect(),+ );+ }+ if output && value.get("content").is_some() {+ return normalize_message("assistant", value);+ }+ value.clone()+}++/// Journal replay puts serialized model payloads on the child root. Replace+/// those with the delegated user task and last assistant answer for the trace+/// overview; the full per-call messages remain on generation observations.+pub(super) fn prepare_subagent_root(spans: &mut [TraceSpan]) {+ let first_input = spans+ .iter()+ .find(|span| span.kind == SpanKind::Generation)+ .and_then(|span| span.input.as_ref())+ .map(|input| normalize_generation_io(input, false))+ .and_then(|messages| {+ messages.as_array().and_then(|messages| {+ messages+ .iter()+ .rev()+ .find(|message| message["role"] == "user")+ .and_then(|message| message.get("content"))+ .cloned()+ })+ });+ let last_output = spans+ .iter()+ .rev()+ .find(|span| span.kind == SpanKind::Generation)+ .and_then(|span| span.output.as_ref())+ .map(|output| normalize_generation_io(output, true))+ .and_then(|message| message.get("content").cloned());+ if let Some(root) = spans.iter_mut().find(|span| span.parent_span_id.is_none()) {+ if first_input.is_some() {+ root.input = first_input;+ }+ if last_output.is_some() {+ root.output = last_output;+ }+ }+}++fn compact_internal_searches(spans: &[TraceSpan]) -> Vec<TraceSpan> {+ let mut output = Vec::with_capacity(spans.len());+ let mut groups: BTreeMap<String, Vec<&TraceSpan>> = BTreeMap::new();+ for span in spans {+ if span.name == "tool.tool_search" && span.status != SpanStatus::Error {+ groups+ .entry(span.parent_span_id.clone().unwrap_or_default())+ .or_default()+ .push(span);+ } else {+ output.push(span.clone());+ }+ }+ for (parent, group) in groups {+ if group.len() == 1 {+ output.push((*group[0]).clone());+ continue;+ }+ let mut summary = (*group[0]).clone();+ summary.span_id = format!("{}:tool-search-summary", parent);+ summary.name = "tool.search_catalog".to_string();+ summary.start_unix_ms = group+ .iter()+ .map(|span| span.start_unix_ms)+ .min()+ .unwrap_or(0);+ summary.end_unix_ms = group.iter().filter_map(|span| span.end_unix_ms).max();+ summary.input = None;+ summary.output = None;+ summary.attributes.clear();+ summary+ .attributes+ .insert("tool.call_count".to_string(), json!(group.len()));+ output.push(summary);+ }+ output.sort_by_key(|span| span.start_unix_ms);+ output+}++fn without_child_run_details(spans: &[TraceSpan]) -> Vec<TraceSpan> {+ let by_id: HashMap<&str, &TraceSpan> = spans+ .iter()+ .map(|span| (span.span_id.as_str(), span))+ .collect();+ spans+ .iter()+ .filter(|span| {+ let mut parent = span.parent_span_id.as_deref();+ while let Some(id) = parent {+ let Some(ancestor) = by_id.get(id) else {+ break;+ };+ if ancestor.kind == SpanKind::Subagent {+ return false;+ }+ parent = ancestor.parent_span_id.as_deref();+ }+ true+ })+ .cloned()+ .collect()+}++fn span_to_otlp(span: &TraceSpan, root: &TraceSpan, environment: &str) -> Value {+ let mut attrs = vec![+ attribute(+ "langfuse.observation.type",+ match span.kind {+ SpanKind::Turn | SpanKind::Subagent => "agent",+ SpanKind::Tool => "tool",+ SpanKind::Generation => "generation",+ SpanKind::Iteration | SpanKind::SubagentIteration => "span",+ },+ ),+ attribute("langfuse.trace.name", root.name.clone()),+ attribute(+ "langfuse.trace.metadata.openhuman_trace_id",+ root.trace_id.clone(),+ ),+ attribute("langfuse.environment", environment),+ attribute("langfuse.version", env!("CARGO_PKG_VERSION")),+ attribute("langfuse.release", env!("CARGO_PKG_VERSION")),+ attribute(+ "langfuse.session.id",+ string_attr(root, "thread.id")+ .unwrap_or(root.trace_id.as_str())+ .to_string(),+ ),+ ];+ if let Some(run_type) = string_attr(root, "run.type") {+ attrs.push(attribute("langfuse.trace.metadata.run_type", run_type));+ let mut tags = vec![format!("run:{run_type}")];+ if let Some(source) = string_attr(root, "channel.source") {+ tags.push(format!("source:{source}"));+ }+ attrs.push(json!({ "key": "langfuse.trace.tags", "value": {+ "arrayValue": { "values": tags.into_iter().map(|tag| json!({ "stringValue": tag })).collect::<Vec<_>>() }+ } }));+ }+ for key in [+ "agent.id",+ "channel.source",+ "run_id",+ "parent_run_id",+ "root_run_id",+ ] {+ if let Some(value) = string_attr(root, key) {+ attrs.push(attribute(+ &format!("langfuse.trace.metadata.{}", key.replace('.', "_")),+ value,+ ));+ }+ }+ if let Some(input) = &span.input {+ let input = if span.kind == SpanKind::Generation {+ normalize_generation_io(input, false)+ } else {+ input.clone()+ };+ attrs.push(json_attribute("langfuse.observation.input", &input));+ }+ if let Some(output) = &span.output {+ let output = if span.kind == SpanKind::Generation {+ normalize_generation_io(output, true)+ } else {+ output.clone()+ };+ attrs.push(json_attribute("langfuse.observation.output", &output));+ }+ if span.status == SpanStatus::Error {+ attrs.push(attribute("langfuse.observation.level", "ERROR"));+ if let Some(message) = string_attr(span, "error.message") {+ attrs.push(attribute("langfuse.observation.status_message", message));+ }+ }+ for (key, value) in &span.attributes {+ if key.starts_with("gen_ai.usage.") || key == "gen_ai.request.model" {+ continue;+ }+ attrs.push(json_attribute(+ &format!("langfuse.observation.metadata.{}", key.replace('.', "_")),+ value,+ ));+ }+ if span.kind == SpanKind::Generation {+ if let Some(model) = string_attr(span, "gen_ai.request.model") {+ attrs.push(attribute("langfuse.observation.model.name", model));+ }+ if let Some(provider) = string_attr(span, "gen_ai.provider") {+ attrs.push(attribute(+ "langfuse.observation.metadata.provider",+ provider,+ ));+ }+ if provider_is_openrouter(span) {+ attrs.push(attribute(+ "langfuse.observation.metadata.model_route",+ "openrouter",+ ));+ }+ if let Some(usage) = usage_details(span) {+ attrs.push(json_attribute("langfuse.observation.usage_details", &usage));+ }+ if let Some(cost) = span+ .attributes+ .get("gen_ai.usage.cost_usd")+ .and_then(Value::as_f64)+ .filter(|cost| *cost > 0.0)+ {+ attrs.push(json_attribute(+ "langfuse.observation.cost_details",+ &json!({ "total": cost }),+ ));+ }+ } else if span.span_id == root.span_id {+ for key in [+ "gen_ai.usage.input_tokens",+ "gen_ai.usage.output_tokens",+ "gen_ai.usage.cost_usd",+ ] {+ if let Some(value) = span.attributes.get(key) {+ attrs.push(json_attribute(+ &format!(+ "langfuse.observation.metadata.run_total_{}",+ key.rsplit('.').next().unwrap_or(key)+ ),+ value,+ ));+ }+ }+ }+ let mut body = json!({+ "traceId": hex_id(&span.trace_id, 16),+ "spanId": hex_id(&span.span_id, 8),+ "name": span.name,+ "startTimeUnixNano": span.start_unix_ms.saturating_mul(1_000_000).to_string(),+ "endTimeUnixNano": span.end_unix_ms.unwrap_or(span.start_unix_ms).saturating_mul(1_000_000).to_string(),+ "attributes": attrs,+ });+ if let Some(parent) = &span.parent_span_id {+ body["parentSpanId"] = json!(hex_id(parent, 8));+ }+ body+}++fn provider_is_openrouter(span: &TraceSpan) -> bool {+ string_attr(span, "gen_ai.provider") == Some("openrouter")+ || string_attr(span, "gen_ai.request.model")+ .is_some_and(|model| model.contains("openrouter/"))+}++pub(super) fn otlp_requests(spans: &[TraceSpan], environment: &str) -> Vec<Value> {+ let Some(root) = spans.iter().find(|span| span.parent_span_id.is_none()) else {+ return Vec::new();+ };+ // Child runs have their own journal-backed trace under the same session.+ // Keep their parent placeholder here, but export each child model/tool call+ // only once so Langfuse usage metrics do not count it twice.+ let visible = without_child_run_details(spans);+ let compacted = compact_internal_searches(&visible);+ let make_request = |spans: Vec<Value>| {+ json!({ "resourceSpans": [{+ "resource": { "attributes": [attribute("service.name", "openhuman")] },+ "scopeSpans": [{+ "scope": { "name": "openhuman.agent" },+ "spans": spans,+ }],+ }] })+ };+ let mut requests = Vec::new();+ let mut batch = Vec::new();+ let mut bytes = 256;+ for span in &compacted {+ let converted = span_to_otlp(span, root, environment);+ let span_bytes = converted.to_string().len();+ if !batch.is_empty()+ && (batch.len() >= MAX_SPANS_PER_REQUEST || bytes + span_bytes > MAX_REQUEST_BYTES)+ {+ requests.push(make_request(std::mem::take(&mut batch)));+ bytes = 256;+ }+ bytes += span_bytes;+ batch.push(converted);+ }+ if !batch.is_empty() {+ requests.push(make_request(batch));+ }+ requests+}++pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {+ if spans.is_empty() {+ return Ok(());+ }+ let legacy_url = ingestion_url(config);+ let url = legacy_url.replace("/langfuse/ingestion", "/langfuse/otel/v1/traces");+ if !url.starts_with("http") {+ return Err("Langfuse backend proxy URL is unavailable".to_string());+ }+ let environment = environment_for_base(&url);+ if skip_push(environment) {+ return Ok(());+ }+ let token = require_live_session_token(config)?;+ let (product_header, product_value) = crate::api::product::product_identity_header();+ let client = reqwest::Client::new();+ for payload in otlp_requests(spans, environment) {+ let response = client+ .post(&url)+ .header(+ reqwest::header::AUTHORIZATION,+ bearer_authorization_value(&token),+ )+ .header(product_header.clone(), product_value.clone())+ .timeout(std::time::Duration::from_secs(10))+ .json(&payload)+ .send()+ .await+ .map_err(|err| format!("Langfuse OTLP transport failed: {err}"))?;+ let status = response.status();+ if !status.is_success() {+ return Err(format!("Langfuse OTLP proxy returned {status}"));+ }+ let body: Value = response.json().await.unwrap_or(Value::Null);+ if body["partialSuccess"]["rejectedSpans"]+ .as_u64()+ .unwrap_or(0)+ > 0+ || body["partialSuccess"]["errorMessage"]+ .as_str()+ .is_some_and(|message| !message.is_empty())+ {+ return Err("Langfuse OTLP proxy partially rejected spans".to_string());+ }+ }+ Ok(())+}++#[cfg(test)]+#[path = "otlp_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rsnew file mode 100644index 0000000000..ca2ce358e1--- /dev/null+++ b/crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs@@ -0,0 +1,231 @@+use super::*;+use std::collections::BTreeMap;++fn span(id: &str, parent: Option<&str>, kind: SpanKind, name: &str) -> TraceSpan {+ TraceSpan {+ trace_id: "thread-one:turn-one".into(),+ span_id: id.into(),+ parent_span_id: parent.map(str::to_string),+ name: name.into(),+ kind,+ start_unix_ms: 1_000,+ end_unix_ms: Some(2_000),+ status: SpanStatus::Ok,+ attributes: BTreeMap::new(),+ input: None,+ output: None,+ }+}++fn attr<'a>(span: &'a Value, key: &str) -> Option<&'a str> {+ span["attributes"]+ .as_array()?+ .iter()+ .find(|item| item["key"] == key)?["value"]["stringValue"]+ .as_str()+}++#[test]+fn otlp_has_one_root_with_readable_io_and_call_only_usage() {+ let mut root = span("root", None, SpanKind::Turn, "agent.turn:orchestrator");+ root.attributes+ .insert("thread.id".into(), json!("thread-one"));+ root.attributes+ .insert("run.type".into(), json!("interactive_chat"));+ root.attributes+ .insert("gen_ai.usage.input_tokens".into(), json!(20));+ root.attributes+ .insert("gen_ai.usage.output_tokens".into(), json!(5));+ root.input = Some(json!("What is the weather?"));+ root.output = Some(json!("Sunny."));+ let mut generation = span("call", Some("root"), SpanKind::Generation, "llm.reply");+ generation.attributes.insert(+ "gen_ai.request.model".into(),+ json!("managed.openrouter/test"),+ );+ generation+ .attributes+ .insert("gen_ai.usage.input_tokens".into(), json!(20));+ generation+ .attributes+ .insert("gen_ai.usage.cached_input_tokens".into(), json!(8));+ generation+ .attributes+ .insert("gen_ai.usage.output_tokens".into(), json!(5));+ generation.input = Some(json!([{ "role": "user", "content": "What is the weather?" }]));+ generation.output = Some(json!({ "content": "Sunny." }));+ let payloads = otlp_requests(&[root, generation], "production");+ assert_eq!(payloads.len(), 1);+ let spans = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]+ .as_array()+ .unwrap();+ assert_eq!(spans.len(), 2);+ let root = spans+ .iter()+ .find(|item| item["name"] == "agent.turn:orchestrator")+ .unwrap();+ let call = spans+ .iter()+ .find(|item| item["name"] == "llm.reply")+ .unwrap();+ assert_eq!(attr(root, "langfuse.observation.type"), Some("agent"));+ assert_eq!(attr(root, "langfuse.session.id"), Some("thread-one"));+ assert_eq!(+ attr(root, "langfuse.observation.input"),+ Some("\"What is the weather?\"")+ );+ assert_eq!(+ attr(root, "langfuse.observation.output"),+ Some("\"Sunny.\"")+ );+ assert!(attr(root, "langfuse.observation.usage_details").is_none());+ assert_eq!(call["parentSpanId"], root["spanId"]);+ assert_eq!(attr(call, "langfuse.observation.type"), Some("generation"));+ assert_eq!(+ attr(call, "langfuse.observation.model.name"),+ Some("managed.openrouter/test")+ );+ assert_eq!(+ attr(call, "langfuse.observation.usage_details"),+ Some("{\"cache_read_input_tokens\":8,\"input\":12,\"output\":5,\"total\":25}")+ );+}++#[test]+fn repeated_internal_searches_become_one_summary() {+ let root = span("root", None, SpanKind::Turn, "agent.turn");+ let searches: Vec<_> = (0..240)+ .map(|index| {+ span(+ &format!("search-{index}"),+ Some("root"),+ SpanKind::Tool,+ "tool.tool_search",+ )+ })+ .collect();+ let mut all = vec![root];+ all.extend(searches);+ let payloads = otlp_requests(&all, "production");+ let spans = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]+ .as_array()+ .unwrap();+ assert_eq!(spans.len(), 2);+ let summary = spans+ .iter()+ .find(|item| item["name"] == "tool.search_catalog")+ .unwrap();+ assert_eq!(+ attr(summary, "langfuse.observation.metadata.tool_call_count"),+ Some("240")+ );+}++#[test]+fn tinyinference_messages_render_as_role_labeled_conversation() {+ let input = json!([+ { "system": { "content": [{ "text": "instructions" }] } },+ { "user": { "content": [{ "text": "find weather" }] } },+ { "assistant": { "content": [], "tool_calls": [{+ "id": "call-1", "name": "weather", "arguments": { "city": "Paris" }+ }] } },+ { "tool": { "tool_call_id": "call-1", "content": [{ "text": "sunny" }] } },+ { "custom": { "kind": "compaction" } },+ ]);+ let normalized = normalize_generation_io(&input, false);+ let messages = normalized.as_array().unwrap();+ assert_eq!(messages.len(), 4);+ assert_eq!(+ messages[0],+ json!({ "role": "system", "content": "instructions" })+ );+ assert_eq!(+ messages[1],+ json!({ "role": "user", "content": "find weather" })+ );+ assert_eq!(+ messages[2]["tool_calls"][0]["function"]["arguments"],+ "{\"city\":\"Paris\"}"+ );+ assert_eq!(+ messages[3],+ json!({ "role": "tool", "tool_call_id": "call-1", "content": "sunny" })+ );+ let output = normalize_generation_io(&json!({ "content": [{ "text": "It is sunny" }] }), true);+ assert_eq!(+ output,+ json!({ "role": "assistant", "content": "It is sunny" })+ );+}++#[test]+fn subagent_root_shows_task_and_final_answer() {+ let mut root = span("root", None, SpanKind::Turn, "agent.turn:researcher");+ root.input = Some(json!("unreadable serialized model request"));+ let mut first = span("first", Some("root"), SpanKind::Generation, "model");+ first.input = Some(json!([+ { "system": { "content": [{ "text": "instructions" }] } },+ { "user": { "content": [{ "text": "research topic" }] } },+ ]));+ first.output = Some(json!({ "content": [{ "text": "working" }] }));+ let mut last = span("last", Some("root"), SpanKind::Generation, "model");+ last.output = Some(json!({ "content": [{ "text": "final result" }] }));+ let mut spans = vec![root, first, last];+ prepare_subagent_root(&mut spans);+ assert_eq!(spans[0].input, Some(json!("research topic")));+ assert_eq!(spans[0].output, Some(json!("final result")));+}++#[test]+fn child_model_usage_is_exported_only_in_child_trace() {+ let root = span("root", None, SpanKind::Turn, "agent.turn");+ let child = span(+ "child",+ Some("root"),+ SpanKind::Subagent,+ "subagent.researcher",+ );+ let mut generation = span("model", Some("child"), SpanKind::Generation, "model");+ generation+ .attributes+ .insert("gen_ai.usage.input_tokens".into(), json!(100));+ generation+ .attributes+ .insert("gen_ai.usage.output_tokens".into(), json!(10));+ let payloads = otlp_requests(&[root, child, generation], "production");+ let spans = payloads[0]["resourceSpans"][0]["scopeSpans"][0]["spans"]+ .as_array()+ .unwrap();+ assert_eq!(spans.len(), 2);+ assert!(spans+ .iter()+ .all(|span| attr(span, "langfuse.observation.usage_details").is_none()));+}++#[tokio::test]+async fn external_backend_is_skipped_before_session_lookup() {+ let mut config = Config::default();+ config.api_url = Some("https://external.example.invalid/openai/v1".into());+ let spans = [span("root", None, SpanKind::Turn, "agent.turn")];+ assert!(push_spans(&config, &spans).await.is_ok());+}++#[test]+fn large_trace_is_split_under_backend_request_limit() {+ let mut spans = vec![span("root", None, SpanKind::Turn, "agent.turn")];+ for index in 0..18 {+ let mut tool = span(+ &format!("tool-{index}"),+ Some("root"),+ SpanKind::Tool,+ "tool.fetch",+ );+ tool.output = Some(json!("x".repeat(500_000)));+ spans.push(tool);+ }+ let requests = otlp_requests(&spans, "production");+ assert!(requests.len() >= 2);+ assert!(requests+ .iter()+ .all(|request| request.to_string().len() < MAX_REQUEST_BYTES));+}diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rsindex c217269579..a68fe51b0e 100644--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs@@ -29,15 +29,16 @@ fn subagent_content_is_withheld_when_capture_off() {}#[test]-fn oversized_model_content_degrades_to_truncated_string() {+fn oversized_model_content_remains_structured() {let big = "x".repeat(MAX_MODEL_CONTENT_CHARS + 100);- let captured = capture_model_content(&serde_json::json!({ "content": big }));- let rendered = match &captured {- serde_json::Value::String(s) => s.clone(),- other => other.to_string(),- };- assert!(rendered.chars().count() <= MAX_MODEL_CONTENT_CHARS + 64);- assert!(rendered.contains("truncated"));+ let captured = capture_model_content(&serde_json::json!([+ { "role": "system", "content": big },+ { "role": "user", "content": "the latest question" },+ ]));+ let messages = captured.as_array().expect("messages stay structured");+ assert_eq!(messages.last().unwrap()["role"], "user");+ assert_eq!(messages.last().unwrap()["content"], "the latest question");+ assert!(captured.to_string().chars().count() <= MAX_MODEL_CONTENT_CHARS + 128);}#[test]diff --git a/crates/openhuman-core/src/agent/progress_tracing/serialize.rs b/crates/openhuman-core/src/agent/progress_tracing/serialize.rsindex 4f60b9fb41..40c558e8b8 100644--- a/crates/openhuman-core/src/agent/progress_tracing/serialize.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/serialize.rs@@ -18,18 +18,70 @@ pub(super) const MAX_ERROR_MESSAGE_CHARS: usize = 500;/// full message array (system prompt included) — but still bounded so a/// 100k-token context can't push the ingestion batch past Langfuse's event/// size limits.-pub(super) const MAX_MODEL_CONTENT_CHARS: usize = 25_000;+pub(super) const MAX_MODEL_CONTENT_CHARS: usize = 200_000;-/// Capture a model-payload JSON value for a span: kept structured when it-/// serializes within [`MAX_MODEL_CONTENT_CHARS`], else degraded to a truncated-/// string (readable in Langfuse, bounded in size).+/// Keep large model requests as structured messages so Langfuse can render+/// roles and tool calls. Retain the most recent messages within the bound.pub(super) fn capture_model_content(value: &serde_json::Value) -> serde_json::Value {let serialized = value.to_string();if serialized.chars().count() <= MAX_MODEL_CONTENT_CHARS {- value.clone()- } else {- serde_json::Value::String(truncate_chars(&serialized, MAX_MODEL_CONTENT_CHARS))+ return value.clone();+ }+ if let Some(messages) = value.as_array() {+ let mut kept = Vec::new();+ let mut used = 0;+ for message in messages.iter().rev() {+ let mut message = message.clone();+ let size = message.to_string().chars().count();+ if size > MAX_MODEL_CONTENT_CHARS / 2 {+ if let Some(content) = message.get_mut("content") {+ *content = serde_json::Value::String(format!(+ "{}…[message content truncated]",+ truncate_chars(&content.to_string(), MAX_MODEL_CONTENT_CHARS / 2)+ ));+ }+ }+ let size = message.to_string().chars().count();+ if used + size > MAX_MODEL_CONTENT_CHARS.saturating_sub(128) {+ break;+ }+ used += size;+ kept.push(message);+ }+ kept.reverse();+ let omitted = messages.len().saturating_sub(kept.len());+ if omitted > 0 {+ kept.insert(+ 0,+ serde_json::json!({+ "role": "system",+ "content": format!("[{omitted} earlier messages omitted from telemetry]"),+ }),+ );+ }+ return serde_json::Value::Array(kept);+ }+ if let Some(fields) = value.as_object() {+ let mut kept = fields.clone();+ if let Some(content) = kept.get_mut("content") {+ *content = serde_json::Value::String(truncate_chars(+ &content.to_string(),+ MAX_MODEL_CONTENT_CHARS / 2,+ ));+ if serde_json::Value::Object(kept.clone())+ .to_string()+ .chars()+ .count()+ <= MAX_MODEL_CONTENT_CHARS+ {+ return serde_json::Value::Object(kept);+ }+ }}+ serde_json::json!({+ "truncated": true,+ "preview": truncate_chars(&serialized, MAX_MODEL_CONTENT_CHARS / 2),+ })}/// Truncate `text` to `max` characters, appending an explicit truncationdiff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_progress.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_progress.rsindex 6a543b0012..5f45881edd 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session_progress.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_progress.rs@@ -32,11 +32,20 @@ pub(super) async fn send_committed_turn_progress(output: &str,iterations: u32,) -> bool {- let _ = progress.try_send(AgentProgress::TurnContent {+ let content = AgentProgress::TurnContent {input: Some(input.to_string()),output: Some(output.to_string()),- });- match tokio::time::timeout(+ };+ // With two free slots, preserve the usual content-then-completion order.+ // A full channel must reserve its next slot for the terminal fence. Send+ // content after that fence on a short-lived clone so trace IO is still+ // captured when the bridge catches up.+ let delayed_content = if progress.capacity() >= 2 {+ progress.try_send(content).err().map(|err| err.into_inner())+ } else {+ Some(content)+ };+ let completed = match tokio::time::timeout(COMMITTED_TURN_PROGRESS_TIMEOUT,progress.send(AgentProgress::TurnCompleted { iterations }),)@@ -56,5 +65,22 @@ pub(super) async fn send_committed_turn_progress();false}+ };+ if completed {+ if let Some(content) = delayed_content {+ let progress = progress.clone();+ tokio::spawn(async move {+ if !matches!(+ tokio::time::timeout(COMMITTED_TURN_PROGRESS_TIMEOUT, progress.send(content))+ .await,+ Ok(Ok(()))+ ) {+ log::warn!(+ "[agent_session] committed turn content not delivered after completion"+ );+ }+ });+ }}+ completed}diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rsindex db81858a16..68a6bd7589 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs@@ -99,6 +99,15 @@ async fn committed_turn_completion_waits_for_a_full_progress_channel() {.expect("terminal progress event"),Some(AgentProgress::TurnCompleted { iterations: 2 })));+ assert!(matches!(+ tokio::time::timeout(std::time::Duration::from_secs(1), rx.recv())+ .await+ .expect("content after terminal progress event"),+ Some(AgentProgress::TurnContent {+ input: Some(input),+ output: Some(output),+ }) if input == "question" && output == "answer"+ ));}/// A receiver can remain alive while its bridge is stalled. Once the senddiff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rsindex da35e428cc..4e2d008761 100644--- a/crates/openhuman-core/src/web_chat/run_task.rs+++ b/crates/openhuman-core/src/web_chat/run_task.rs@@ -7,6 +7,7 @@use std::sync::Arc;use tinyagents_harness::run_queue::RunQueue;+use crate::agent::progress::AgentProgress;use crate::config::rpc as config_rpc;use crate::threads::turn_state::TurnStateStore;@@ -125,6 +126,12 @@ pub(crate) async fn run_chat_task(// defense-in-depth; extraction of durable state (like a workflow// proposal) must not depend on any single progress event surviving.let (progress_tx, progress_rx) = tokio::sync::mpsc::channel(256);+ // The channel is fresh here. Record the user input even if the turn fails+ // before a committed reply can emit its final TurnContent event.+ let _ = progress_tx.try_send(AgentProgress::TurnContent {+ input: Some(message.to_string()),+ output: None,+ });agent.set_on_progress(Some(progress_tx));agent.set_run_queue(Some(run_queue));agent.set_thread_id(Some(thread_id));diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.mdindex 4abf7fcb6e..12687b6b8d 100644--- a/docs/RELEASE-MANUAL-SMOKE.md+++ b/docs/RELEASE-MANUAL-SMOKE.md@@ -22,6 +22,7 @@ Applies to every release, all platforms.### Conversation resume+- [ ] **Agent traces appear in Langfuse through the backend proxy** — With a signed-in staging test account and default telemetry settings, send a synthetic chat turn that calls a tool and a subagent. Expected: Langfuse shows the user input and final reply on the root observation, role-labeled messages on each model generation, one session across turns, a child-run trace grouped in that session, and no stream-delta or middleware event flood. Confirm a profile with `share_usage_data = false` sends no trace.- [ ] **An existing chat accepts another turn after restart** — Send a message and wait for its reply, fully quit OpenHuman, then reopen that conversation and send a second message. Expected: the second reply streams normally, retains the earlier context, and does not show a generic error. Repeat after the conversation has compacted if a long-running test profile is available (#6608).- [ ] **A failed chat turn does not offer an invalid regenerate action** — Trigger a provider failure in a test profile and inspect its error card. Expected: the diagnostic text remains visible, with no Retry or Refresh button on that failed message. A completed assistant reply still offers Refresh (#6613).diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 48a4ea3282..ac4ad0ac9d 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -230,6 +230,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an| 4.4.15 | Thread goal (`goal_set` / `goal_get` / `goal_complete`) | RI+RU+VU+WD | `tests/agent_harness_e2e.rs`, `crates/openhuman-core/src/agent/goals/{tools_tests.rs,runtime_tests.rs,continuation_tests.rs}`, `vendor/tinyagents/crates/tinyagents-graph/src/goals/test.rs`, `app/src/features/conversations/utils/harnessState.test.ts`, `app/src/features/conversations/components/GoalBanner.test.tsx`, `app/src/features/conversations/hooks/useThreadHarnessState.test.ts`, `app/test/e2e/specs/chat-todos-goals.spec.ts` | ✅ | Objective + token budget set, read back across turns, and completed; structured `{goal, text}` payload drives the chat pane's goal banner. Budget accounting and the budget-limit stop hook are unit-covered (the scripted e2e upstream reports no usage) || 4.4.16 | Builder-supplied session definition (library host) | RU | `crates/openhuman-core/src/agent/session_host/builder/builder_tests_session_definition_tests.rs` | ✅ | `SessionHostBuilder::agent_definition` stamps a caller's own `AgentDefinition` on the session, so a hosted root invocation resolves an id the process registry never held; it outranks a registry entry sharing its id, it carries the turn's tool allow-list, the session is stamped with the definition's own id, a contradicting `agent_definition_name` fails the build, and without it the same id stays unknown || 4.4.17 | Chat failure presentation | RU+VU | `crates/openhuman-core/src/web_chat/web_tests_rate_limit_classification_tests.rs`, `app/src/providers/__tests__/assistantUiMessages.test.ts`, `app/src/features/conversations/aui/ChatErrorNotice.test.tsx`, `app/src/components/assistant-ui/thread.reloadCapability.test.tsx` | ✅ | Failed turns use assistant-ui's error card; old custom link markup is removed from saved errors (#6609); uncommitted failures and guardrail notices hide invalid regenerate controls while completed replies retain Refresh (#6613) |+| 4.4.18 | Agent trace export | RU | `crates/openhuman-core/src/agent/progress_tracing/otlp_tests.rs`, `crates/openhuman-core/src/agent/progress_tracing/progress_tracing_content_gate_tests.rs`, `crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs` | 🟡 | OTLP projection covers turn IO, role-labeled model messages, subagent grouping, tool-search summaries and usage de-duplication; live proxy canary follows backend deployment |---