Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(embed): expose private-by-default turn observers

Steven Enamakel22cec6c21051
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml
index 5e7df5e55b..95cc9cd352 100644
--- a/crates/openhuman-cli/Cargo.toml
+++ b/crates/openhuman-cli/Cargo.toml
@@ -344,6 +344,7 @@ urlencoding = "2.1"
wiremock = "0.6"
[features]
+langfuse = ["openhuman-rpc/langfuse"]
# The contributor set: the core's `[features] default` gates (listed, because
# `openhuman-rpc`'s own default carries only its server and client) plus the
# Jev ranker. The product lanes pass `--features
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index e45e2eda7b..26a372ded5 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -686,6 +686,8 @@ tokio = { version = "1", features = ["test-util"] }
proptest = "1"
[features]
+# Curated forwarding of the existing TinyAgents telemetry exporter.
+langfuse = ["tinyagents-harness/langfuse"]
# Storage drivers for `[storage] url` / `OPENHUMAN_STORAGE_URL` (see the
# `storage` domain). Memory is always available. Off in the product until a
# desktop domain moves onto the ports; a cloud build turns on `storage-mongodb`.
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index 0b17e6d78d..6b13dc8902 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -62,6 +62,7 @@ pub(crate) mod stop_hooks;
pub mod todos;
pub(crate) mod tools;
mod topology;
+pub mod turn_observer;
mod turn_models;
mod turn_outcome;
mod turn_policy;
diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
index 9b8a21dc27..7badb7fe57 100644
--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
@@ -27,6 +27,8 @@ use crate::agent::tinyagents::host::OpenHumanRunContext;
/// What a host asks of every model call in one turn.
#[derive(Clone, Default)]
pub struct ResponseShape {
+ /// Observer captured before the host dispatches to the core worker.
+ pub observer: Option<Arc<super::turn_observer::ObserverScope>>,
/// Host validation of the original terminal text, before any repair.
pub validator: Option<Arc<dyn ResponseValidator>>,
/// Bounded number of output repair attempts.
@@ -151,7 +153,12 @@ pub async fn with_response_shape<F: std::future::Future>(
scope: Arc<ResponseShapeScope>,
fut: F,
) -> F::Output {
- RESPONSE_SHAPE.scope(scope, Box::pin(fut)).await
+ let observer = scope.shape.observer.clone();
+ let run = RESPONSE_SHAPE.scope(scope, Box::pin(fut));
+ match observer {
+ Some(observer) => super::turn_observer::with_observer(observer, run).await,
+ None => run.await,
+ }
}
/// Push the shaping middleware onto a root turn's harness, when a shape is
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_observer.rs b/crates/openhuman-core/src/agent/tinyagents/turn_observer.rs
new file mode 100644
index 0000000000..d8db6cf3eb
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_observer.rs
@@ -0,0 +1,295 @@
+//! Root-turn observer hooks. Scopes attach once during harness construction;
+//! payload capture is opt-in and raw errors/provider options are never exposed.
+use super::host::OpenHumanRunContext;
+use async_trait::async_trait;
+use serde_json::Value;
+use std::sync::{Arc, Mutex};
+use std::time::Instant;
+use tinyagents_harness::context::RunContext;
+use tinyagents_harness::events::{AgentEvent, EventListener, EventRecord, EventSink};
+use tinyagents_harness::middleware::{MiddlewareModelOutcome, ModelHandler, ModelMiddleware};
+use tinyagents_harness::runtime::AgentHarness;
+use tinyinference_llm::model::ModelRequest;
+
+/// Explicit consent for capturing model messages and tool input/output.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum TraceContent {
+ /// Only identifiers, durations, token counts, costs, and success/failure.
+ #[default]
+ MetadataOnly,
+ /// Include messages and tool payloads. Hosts own their retention policy.
+ Include,
+}
+/// Provider-reported usage; absent costs remain unknown.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct ObservedUsage {
+ /// Prompt tokens.
+ pub input_tokens: u64,
+ /// Output tokens.
+ pub output_tokens: u64,
+ /// Cached prompt tokens.
+ pub cached_tokens: u64,
+ /// Reasoning tokens.
+ pub reasoning_tokens: u64,
+ /// Provider charge in USD, never a local estimate.
+ pub cost_usd: Option<f64>,
+}
+/// A curated model/tool observation. No raw errors or arbitrary metadata.
+#[derive(Clone, Debug, PartialEq)]
+pub enum TurnObservation {
+ /// One model pipeline returned, even if later answer validation rejects it.
+ Model {
+ /// Harness run identifier.
+ run_id: String,
+ /// Model call identifier when supplied by the harness.
+ call_id: Option<String>,
+ /// Requested model identifier.
+ requested_model: Option<String>,
+ /// Provider-reported actual answering model.
+ answered_model: Option<String>,
+ /// Provider finish reason.
+ finish_reason: Option<String>,
+ /// Wall-clock time in milliseconds.
+ duration_ms: u64,
+ /// Whether the pipeline failed.
+ failed: bool,
+ /// Provider usage.
+ usage: Option<ObservedUsage>,
+ /// Conversation messages, only with explicit capture consent.
+ input: Option<Value>,
+ /// Assistant message, only with explicit capture consent.
+ output: Option<Value>,
+ },
+ /// A tool started or returned; `failed=None` denotes its start.
+ Tool {
+ /// Harness run identifier, once its start was observed.
+ run_id: Option<String>,
+ /// Call identifier, pairs start with completion.
+ call_id: String,
+ /// Tool name.
+ name: String,
+ /// Terminal failure status, never the raw error text.
+ failed: Option<bool>,
+ /// Terminal duration if available.
+ duration_ms: Option<u64>,
+ /// Arguments, only with explicit capture consent.
+ input: Option<Value>,
+ /// Result, only with explicit capture consent.
+ output: Option<Value>,
+ },
+}
+/// Synchronous, nonblocking host callback. Queue export work in the host.
+pub trait Observer: Send + Sync {
+ /// Called once per observed model outcome or tool event.
+ fn on_event(&self, event: &TurnObservation);
+}
+/// Observer and capture consent shared by one turn's harness.
+pub struct ObserverScope {
+ observer: Arc<dyn Observer>,
+ capture: TraceContent,
+ run_id: Mutex<Option<String>>,
+}
+impl ObserverScope {
+ /// Construct a turn-local observer scope.
+ pub fn new(observer: Arc<dyn Observer>, capture: TraceContent) -> Arc<Self> {
+ Arc::new(Self {
+ observer,
+ capture,
+ run_id: Mutex::default(),
+ })
+ }
+ /// Harness run identifier observed during this scope's dispatch.
+ pub fn run_id(&self) -> Option<String> {
+ self.run_id
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ }
+ fn payload(&self, value: &Option<Value>) -> Option<Value> {
+ (self.capture == TraceContent::Include)
+ .then(|| value.clone())
+ .flatten()
+ }
+}
+tokio::task_local! { static OBSERVER: Arc<ObserverScope>; }
+/// Capture the current scope before dispatch crosses a runtime/task boundary.
+pub fn current_scope() -> Option<Arc<ObserverScope>> {
+ OBSERVER.try_with(Arc::clone).ok()
+}
+
+impl std::fmt::Debug for ObserverScope {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ObserverScope")
+ .field("capture", &self.capture)
+ .finish_non_exhaustive()
+ }
+}
+
+/// Scope an observation context around turn dispatch.
+pub async fn with_observer<F: std::future::Future>(
+ scope: Arc<ObserverScope>,
+ future: F,
+) -> F::Output {
+ OBSERVER.scope(scope, Box::pin(future)).await
+}
+/// Attach to a root harness and its event stream if a host scoped an observer.
+pub(super) fn install(
+ harness: &mut AgentHarness<(), OpenHumanRunContext>,
+ events: &EventSink,
+ root: bool,
+) {
+ if !root {
+ return;
+ }
+ if let Ok(scope) = OBSERVER.try_with(Arc::clone) {
+ if scope.capture == TraceContent::Include {
+ let mut policy = harness.policy().clone();
+ policy.capture.tool_io = true;
+ harness.with_policy(policy);
+ }
+ harness.push_model_middleware(scope.clone());
+ events.subscribe(scope);
+ }
+}
+impl EventListener for ObserverScope {
+ fn on_event(&self, record: &EventRecord) {
+ if let AgentEvent::RunStarted { run_id, .. } = &record.event {
+ *self
+ .run_id
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(run_id.to_string());
+ }
+ let (call_id, name, failed, duration_ms, input, output) = match &record.event {
+ AgentEvent::ToolStarted {
+ call_id,
+ tool_name,
+ input,
+ ..
+ } => (call_id, tool_name, None, None, self.payload(input), None),
+ AgentEvent::ToolCompleted {
+ call_id,
+ tool_name,
+ error,
+ duration_ms,
+ input,
+ output,
+ ..
+ } => (
+ call_id,
+ tool_name,
+ Some(error.is_some()),
+ *duration_ms,
+ self.payload(input),
+ self.payload(output),
+ ),
+ AgentEvent::ToolFailed {
+ call_id,
+ tool_name,
+ duration_ms,
+ ..
+ } => (call_id, tool_name, Some(true), *duration_ms, None, None),
+ // Deltas, errors, metadata, and custom events can contain payloads.
+ _ => return,
+ };
+ self.observer.on_event(&TurnObservation::Tool {
+ run_id: self.run_id(),
+ call_id: call_id.to_string(),
+ name: name.clone(),
+ failed,
+ duration_ms,
+ input,
+ output,
+ });
+ }
+}
+#[async_trait]
+impl ModelMiddleware<(), OpenHumanRunContext> for ObserverScope {
+ fn name(&self) -> &str {
+ "host_turn_observer"
+ }
+ async fn wrap_model(
+ &self,
+ ctx: &mut RunContext<OpenHumanRunContext>,
+ state: &(),
+ request: ModelRequest,
+ next: ModelHandler<'_, (), OpenHumanRunContext>,
+ ) -> tinyagents_harness::error::Result<MiddlewareModelOutcome> {
+ let run_id = ctx.run_id().to_string();
+ let call_id = request
+ .correlation
+ .as_ref()
+ .map(|correlation| correlation.call_id.clone());
+ let requested_model = request.model.clone();
+ // Serialize messages only: provider_options may contain credentials.
+ let input = (self.capture == TraceContent::Include)
+ .then(|| serde_json::to_value(&request.messages).ok())
+ .flatten();
+ let started = Instant::now();
+ let result = next.run(ctx, state, request).await;
+ let response = match &result {
+ Ok(MiddlewareModelOutcome::Response(response)) => Some(response),
+ _ => None,
+ };
+ let raw = response.and_then(|response| response.raw.as_ref());
+ let answered_model = raw
+ .and_then(|raw| raw.get("model"))
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or_else(|| {
+ response
+ .and_then(|response| response.resolved_model.as_ref())
+ .map(|model| model.name.clone())
+ });
+ let raw_cost = raw
+ .and_then(|raw| raw.pointer("/usage/cost"))
+ .and_then(Value::as_f64);
+ let usage = response
+ .and_then(|response| response.usage.as_ref())
+ .map(|usage| ObservedUsage {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ cached_tokens: usage.cache_read_tokens,
+ reasoning_tokens: usage.reasoning_tokens,
+ cost_usd: usage
+ .charged_amount
+ .as_ref()
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ .or(raw_cost),
+ })
+ .or_else(|| {
+ raw_cost.map(|cost_usd| ObservedUsage {
+ cost_usd: Some(cost_usd),
+ ..ObservedUsage::default()
+ })
+ });
+ let output = if self.capture == TraceContent::Include {
+ response.and_then(|response| serde_json::to_value(&response.message).ok())
+ } else {
+ None
+ };
+ self.observer.on_event(&TurnObservation::Model {
+ run_id,
+ call_id,
+ requested_model,
+ answered_model,
+ finish_reason: response.and_then(|response| response.finish_reason.clone()),
+ duration_ms: started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64,
+ failed: result.is_err(),
+ usage,
+ input,
+ output,
+ });
+ result
+ }
+}
+/// Existing TinyAgents exporter; this module adds no transport implementation.
+#[cfg(feature = "langfuse")]
+pub mod langfuse {
+ pub use tinyagents_harness::events::AgentEvent;
+ pub use tinyagents_harness::ids::{CallId, EventId, RunId};
+ pub use tinyagents_harness::observability::AgentObservation;
+ pub use tinyagents_harness::observability::{
+ LangfuseAuth, LangfuseClient, LangfuseScore, LangfuseScoreValue, LangfuseTraceConfig,
+ };
+ pub use tinyinference_llm::usage::Usage;
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
index 70bf02f4f8..c00da12401 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs
@@ -462,8 +462,9 @@ pub(super) async fn run_turn_via_tinyagents_body(
Some(journal_run_id.as_str().to_string());
}
}
- let events = Some(EventSink::with_stream_id(journal_run_id.as_str()));
-
+ let sink = EventSink::with_stream_id(journal_run_id.as_str());
+ super::turn_observer::install(&mut harness, &sink, hosted_root.is_some());
+ let events = Some(sink);
// Attach the event bridge for EVERY turn — including an unobserved
// (`on_progress = None`) background/cron turn (#4467, item 3). The bridge's
// `record_usage` feeds the global cost tracker on each `UsageRecorded` event
@@ -472,8 +473,7 @@ pub(super) async fn run_turn_via_tinyagents_body(
// `record_unobserved_turn_usage` fallback below only runs on the success path
// and never sees a failed run's usage. With `on_progress = None` the bridge
// still records cost but its progress `send`s are inert no-ops, so there is
- // no spurious streaming. `events` is created unconditionally above, so the
- // bridge is always present.
+ // no spurious streaming; every turn has an event sink.
let bridge = events.as_ref().map(|events| {
let bridge = OpenhumanEventBridge::with_scope(
on_progress,
diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml
index 08f6674c0d..27602fe7c6 100644
--- a/crates/openhuman-embed/Cargo.toml
+++ b/crates/openhuman-embed/Cargo.toml
@@ -9,6 +9,7 @@ readme = "README.md"
publish = false
[features]
+langfuse = ["openhuman-core/langfuse"]
# `channels` is in core's default set already; enabling it here too compiles
# the `Runtime::channels` facade in a default build.
default = ["openhuman-core/default", "channels"]
diff --git a/crates/openhuman-embed/OBSERVERS.md b/crates/openhuman-embed/OBSERVERS.md
new file mode 100644
index 0000000000..8aaecfcb13
--- /dev/null
+++ b/crates/openhuman-embed/OBSERVERS.md
@@ -0,0 +1,66 @@
+# Turn observers
+
+Hosts implement `observe::TurnObserver` to receive model and tool observations
+and a terminal `TurnTrace`. Callbacks run synchronously: enqueue export work in
+the host and return promptly. Model observations contain the answering model,
+finish reason, duration, and provider-reported usage/cost. Tool observations
+pair starts and completions by call ID and report failure without an error body.
+The terminal trace reports dispatch success, latency and final metadata.
+
+`TraceContent::MetadataOnly` is the default. It excludes model messages, replies,
+tool arguments/results, arbitrary tool metadata, raw error strings, streamed
+deltas, and provider options. `TraceContent::Include` opts into messages and tool
+payloads; it still excludes raw errors, arbitrary metadata and provider options.
+Hosts own consent, redaction, retention, and export destinations for captured
+content. Metadata such as session IDs, tool names and model IDs also needs an
+appropriate retention policy.
+
+```rust,no_run
+use std::sync::Arc;
+use openhuman_embed::observe::{TurnObserver, TurnObservation, TurnTrace};
+
+struct Metrics;
+impl TurnObserver for Metrics {
+ fn on_event(&self, event: &TurnObservation) {
+ // Enqueue metadata to your process's metrics collector.
+ }
+ fn on_turn(&self, trace: &TurnTrace<'_>) {
+ // Record latency and success/failure without formatting payloads.
+ }
+}
+```
+
+An observer scope is captured before dispatch crosses to the owned core runtime
+and restored inside its worker. A task-local alone would silently lose model and
+tool observations across that boundary. Each root harness captures its own
+scope; spawned child harnesses require their own observer scopes.
+
+Model callbacks run around the model pipeline, before terminal schema/tool
+validation. A premature answer rejected after a successful model response still
+reports that response's model, finish reason and spend. Pipeline callbacks cover
+logical model invocations; internal provider retry attempts are not separate
+callback records. Failed pipeline invocations report `failed=true`, without
+including raw provider errors. Unknown per-model charges stay `None`. Terminal
+`LastTurnUsage` retains the core cost-source classification, which can distinguish
+provider charges from catalogue estimates.
+
+The terminal callback runs after the supplied dispatch future completes,
+including its cleanup, and handles failures that have no `TurnOutcome`. Dropping
+the entire future cannot promise a terminal callback; use the turn cancellation
+API and await its cleanup when completion telemetry is required.
+
+## Existing Langfuse exporter
+
+The optional `langfuse` feature forwards TinyAgents' existing exporter through
+`observe::langfuse`, including `LangfuseClient`, `LangfuseAuth`,
+`LangfuseTraceConfig`, and its durable `AgentObservation` contract. It adds no
+second HTTP transport. The host supplies export credentials and batches durable
+observations with `LangfuseClient::build_ingestion_batch` /
+`send_observations`; do that work outside synchronous callbacks. This is a
+separate durable-journal contract, not an implicit export of captured turn data.
+See [CONSUMERS.md](CONSUMERS.md) for the current dependency footprint: gating the
+public exporter does not make enabled Embed an HTTP-free build.
+
+Loopback regressions live in `tests/turn_observers.rs` and
+`tests/observed_turns.rs`, covering sanitized terminal errors and actual model /
+host-tool events with metadata-only and explicit content capture.
diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.md
index ac8c942d46..74a7018a7a 100644
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@ -781,4 +781,4 @@ their managed system catalogue when a continuing conversation gains tools.
See [agent attachment semantics and example](src/agent/README.md#attach-tools-to-an-existing-agent)
for source identity, collision errors, policy composition, and runtime identity.
-Ordered fallback ladders and required agent exploration: [routing](ROUTING.md).
+Ordered fallbacks and required exploration: [routing](ROUTING.md). Host telemetry and the existing exporter: [observers](OBSERVERS.md).
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index ce783fc8f3..21c989c0f0 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -113,6 +113,7 @@ pub mod fanout;
mod harness;
pub mod identity;
pub mod memory;
+pub mod observe;
#[cfg(feature = "modules")]
pub mod modules;
pub mod process;
diff --git a/crates/openhuman-embed/src/observe.rs b/crates/openhuman-embed/src/observe.rs
new file mode 100644
index 0000000000..3ee5c2b0c0
--- /dev/null
+++ b/crates/openhuman-embed/src/observe.rs
@@ -0,0 +1,105 @@
+//! Host turn callbacks with explicit payload consent. Callbacks should enqueue
+//! telemetry work; transport and retention belong to the embedding application.
+use crate::{CoreError, LastTurnUsage, TurnOutcome};
+use openhuman_core::agent::tinyagents::turn_observer::{self, Observer, ObserverScope};
+pub use openhuman_core::agent::tinyagents::turn_observer::{
+ ObservedUsage, TraceContent, TurnObservation,
+};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+/// Sanitized failure classification; no controller or provider error text.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TurnFailure {
+ /// Provider/RPC execution failed.
+ Provider,
+ /// Host domain rejected the turn.
+ Domain,
+ /// Other facade or configuration failure.
+ Other,
+}
+/// Terminal turn metadata, borrowed for the duration of the callback.
+#[derive(Debug)]
+pub struct TurnTrace<'a> {
+ /// Harness run identifier for correlating model/tool observations.
+ pub run_id: Option<String>,
+ /// Conversation identifier.
+ pub session_id: &'a str,
+ /// Whether dispatch and answer validation succeeded.
+ pub success: bool,
+ /// Wall-clock duration.
+ pub latency: Duration,
+ /// Final provider finish reason.
+ pub finish_reason: Option<&'a str>,
+ /// Actual model that answered, when reported.
+ pub answered_model: Option<&'a str>,
+ /// Turn usage, if the session supplied it.
+ pub usage: Option<&'a LastTurnUsage>,
+ /// Sanitized failure category.
+ pub failure: Option<TurnFailure>,
+ /// User message only with explicit capture consent.
+ pub message: Option<&'a str>,
+ /// Final reply only with explicit capture consent.
+ pub reply: Option<&'a str>,
+}
+/// Per-turn synchronous callbacks. Implementations must be fast and nonblocking.
+pub trait TurnObserver: Send + Sync {
+ /// A model pipeline completed or a tool started/completed.
+ fn on_event(&self, _event: &TurnObservation) {}
+ /// Dispatch completed, including failures with no outcome.
+ fn on_turn(&self, _trace: &TurnTrace<'_>) {}
+}
+struct Adapter(Arc<dyn TurnObserver>);
+impl Observer for Adapter {
+ fn on_event(&self, event: &TurnObservation) {
+ self.0.on_event(event);
+ }
+}
+/// Scope model/tool callbacks and report one terminal outcome around dispatch.
+///
+/// Primarily the integration seam used by `Turn`; also supports hosts wrapping
+/// an existing turn future. Child harnesses have independent observer scopes.
+#[doc(hidden)]
+pub async fn observe_turn<F>(
+ observer: Arc<dyn TurnObserver>,
+ capture: TraceContent,
+ session_id: &str,
+ message: &str,
+ future: F,
+) -> Result<TurnOutcome, CoreError>
+where
+ F: std::future::Future<Output = Result<TurnOutcome, CoreError>>,
+{
+ let started = Instant::now();
+ let scope = ObserverScope::new(Arc::new(Adapter(observer.clone())), capture);
+ let result = turn_observer::with_observer(scope.clone(), future).await;
+ let outcome = result.as_ref().ok();
+ let failure = result.as_ref().err().map(|error| match error {
+ CoreError::Rpc { .. } => TurnFailure::Provider,
+ CoreError::Domain { .. } => TurnFailure::Domain,
+ _ => TurnFailure::Other,
+ });
+ observer.on_turn(&TurnTrace {
+ run_id: scope.run_id(),
+ session_id: outcome.map_or(session_id, |outcome| outcome.session_id.as_str()),
+ success: result.is_ok(),
+ latency: started.elapsed(),
+ finish_reason: outcome.and_then(|outcome| outcome.finish_reason.as_deref()),
+ answered_model: outcome.and_then(|outcome| outcome.answered_model.as_deref()),
+ usage: outcome.and_then(|outcome| outcome.usage.as_ref()),
+ failure,
+ message: (capture == TraceContent::Include).then_some(message),
+ reply: if capture == TraceContent::Include {
+ outcome.map(|outcome| outcome.reply.as_str())
+ } else {
+ None
+ },
+ });
+ result
+}
+/// Existing TinyAgents Langfuse client and durable observation contract.
+/// Enable the `langfuse` feature. Export requires explicit host credentials.
+#[cfg(feature = "langfuse")]
+pub mod langfuse {
+ pub use openhuman_core::agent::tinyagents::turn_observer::langfuse::*;
+}
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index b2f50ff756..b7a270d6cd 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -637,6 +637,7 @@ impl Turn {
structured_retries: self.structured_retries,
provider_options: self.provider_options.clone(),
require_tool_call: self.require_tool_call,
+ observer: openhuman_core::agent::tinyagents::turn_observer::current_scope(),
},
),
untrusted_input: self.untrusted_input,
@@ -874,7 +875,7 @@ async fn dispatch(
let turn: futures_box::BoxFuture<'_, Result<AgentReply, CoreError>> =
Box::pin(async move {
use openhuman_core::inference::host_runtime::ops::{
- agent_chat_for, AgentChatTarget,
+ AgentChatTarget, agent_chat_for,
};
let mut config = inner.config.clone();
let route = openhuman_core::config::schema::EphemeralRoute::from_params(
diff --git a/crates/openhuman-embed/tests/README.md b/crates/openhuman-embed/tests/README.md
index 51a55aadf4..e36b5afa00 100644
--- a/crates/openhuman-embed/tests/README.md
+++ b/crates/openhuman-embed/tests/README.md
@@ -41,6 +41,8 @@ recorded on the wrong server.
| [`tool_required_routing.rs`](tool_required_routing.rs) | Native host tool metadata for GPT, Kimi and MiniMax model IDs; premature JSON refusal; required successful execution before final schema; gateway options survive. |
| [`completion_cancellation.rs`](completion_cancellation.rs) | Cancellation acknowledged after the provider future stops, pre-cancelled calls make no request, and deadlines are typed. |
| [`structured_validation.rs`](structured_validation.rs) | Full schema constraints, invalid/external schema refusal before dispatch, typed failures and bounded repair usage. |
+| [`turn_observers.rs`](turn_observers.rs) | Terminal error privacy, explicit input capture, and exactly one terminal callback on dispatch failure. |
+| [`observed_turns.rs`](observed_turns.rs) | Actual model and host-tool observations survive the core runtime task hop; payloads require consent; actual model, finish reason and reasoning usage. |
| [`public_api.rs`](public_api.rs) | Compile-time check that the host-facing types and signatures stay exported. |
| [`turn_cancellation.rs`](turn_cancellation.rs) | Cancellation before send, during inference and during a builtin shell command; repeated requests and agent reuse. |
| [`process_cancellation.rs`](process_cancellation.rs) | On Linux, dropping a command future kills its shell descendants. |
diff --git a/crates/openhuman-embed/tests/observed_turns.rs b/crates/openhuman-embed/tests/observed_turns.rs
new file mode 100644
index 0000000000..85a5d13541
--- /dev/null
+++ b/crates/openhuman-embed/tests/observed_turns.rs
@@ -0,0 +1,197 @@
+//! Actual model/tool observations survive owned runtime dispatch. All model
+//! traffic uses loopback fixtures; content capture requires explicit consent.
+
+mod common;
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use common::{offline_config, runtime, stub_backend};
+use openhuman_embed::{
+ Access, AgentDefinitionSpec, AgentSpec, HostTurnTools, Provider, Runtime, Tool, ToolScopeSpec,
+ Workspace,
+};
+use serde_json::{Value, json};
+use wiremock::matchers::{method, path};
+use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
+
+static RUNTIME_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+struct ReadFile(Arc<AtomicUsize>);
+
+#[async_trait::async_trait]
+impl Tool for ReadFile {
+ fn name(&self) -> &str {
+ "read_file"
+ }
+ fn description(&self) -> &str {
+ "Read a file from the pull request's checkout"
+ }
+ fn parameters_schema(&self) -> Value {
+ json!({"type": "object", "properties": {"path": {"type": "string"}}})
+ }
+ async fn execute(&self, args: Value) -> anyhow::Result<openhuman_core::tools::ToolResult> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ if args["path"] == "blocked" {
+ return Ok(openhuman_core::tools::ToolResult::error("read denied"));
+ }
+ Ok(openhuman_core::tools::ToolResult::success("fn main() {}"))
+ }
+}
+
+struct Script {
+ bodies: Vec<Value>,
+ next: AtomicUsize,
+}
+
+impl Respond for Script {
+ fn respond(&self, _: &Request) -> ResponseTemplate {
+ let index = self.next.fetch_add(1, Ordering::SeqCst);
+ ResponseTemplate::new(200)
+ .set_body_json(self.bodies[index.min(self.bodies.len() - 1)].clone())
+ }
+}
+
+fn completion(message: Value, finish_reason: &str, model: &str, reasoning: u64) -> Value {
+ json!({
+ "id": "chatcmpl-structured",
+ "object": "chat.completion",
+ "created": 1_700_000_000_u64,
+ "model": model,
+ "choices": [{ "index": 0, "message": message, "finish_reason": finish_reason }],
+ "usage": {
+ "prompt_tokens": 10,
+ "completion_tokens": 5,
+ "total_tokens": 15,
+ "completion_tokens_details": { "reasoning_tokens": reasoning }
+ }
+ })
+}
+
+async fn provider(bodies: Vec<Value>) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(Script {
+ bodies,
+ next: AtomicUsize::new(0),
+ })
+ .mount(&server)
+ .await;
+ server
+}
+
+async fn build_runtime(backend: &MockServer) -> Runtime {
+ Runtime::builder()
+ .config(offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .build()
+ .await
+ .expect("runtime")
+}
+
+fn routed(spec: AgentSpec, provider: &MockServer) -> AgentSpec {
+ spec.provider(
+ Provider::openai_compatible(format!("{}/v1", provider.uri()), "fixture").model("fixture"),
+ )
+}
+
+fn reviewer(id: &str, provider: &MockServer, reads: Arc<AtomicUsize>) -> AgentSpec {
+ routed(AgentSpec::new(id), provider)
+ .access(Access::readonly())
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("You must call read_file on src/main.rs before reviewing the diff. Answer with the review JSON.")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| HostTurnTools::advertised(vec![Box::new(ReadFile(reads.clone()))]))
+}
+
+#[derive(Default)]
+struct Records {
+ events: std::sync::Mutex<Vec<openhuman_embed::observe::TurnObservation>>,
+ terminal: std::sync::Mutex<Vec<(bool, Option<String>)>>,
+}
+impl openhuman_embed::observe::TurnObserver for Records {
+ fn on_event(&self, event: &openhuman_embed::observe::TurnObservation) {
+ self.events.lock().unwrap().push(event.clone());
+ }
+ fn on_turn(&self, trace: &openhuman_embed::observe::TurnTrace<'_>) {
+ self.terminal
+ .lock()
+ .unwrap()
+ .push((trace.success, trace.run_id.clone()));
+ }
+}
+// Native dispatch must survive a worker task that does not inherit task locals.
+async fn dispatch_on_worker(
+ turn: openhuman_embed::Turn,
+) -> Result<openhuman_embed::TurnOutcome, openhuman_embed::CoreError> {
+ use openhuman_core::agent::tinyagents::response_shape::{
+ ResponseShape, ResponseShapeScope, with_response_shape,
+ };
+ let shape = ResponseShapeScope::new(ResponseShape {
+ observer: openhuman_core::agent::tinyagents::turn_observer::current_scope(),
+ ..ResponseShape::default()
+ });
+ tokio::spawn(with_response_shape(shape, turn.send()))
+ .await
+ .expect("worker task")
+}
+#[test]
+fn model_and_tool_observations_capture_payloads_only_with_consent() {
+ use openhuman_embed::observe::{TraceContent, TurnObservation, observe_turn};
+ let _guard = RUNTIME_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ runtime().block_on(async { tokio::spawn(async {
+ let backend = stub_backend().await;
+ let runtime = build_runtime(&backend).await;
+ for (index,capture) in [TraceContent::MetadataOnly, TraceContent::Include].into_iter().enumerate() {
+ let provider = provider(vec![
+ completion(json!({"role":"assistant","content":null,"tool_calls":[{"id":"read-1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"SECRET-PATH\"}"}}]}),"tool_calls","actual-model",0),
+ completion(json!({"role":"assistant","content":"SECRET-REPLY"}),"stop","actual-model",3),
+ ]).await;
+ let reads = Arc::new(AtomicUsize::new(0));
+ let agent = runtime.agent(reviewer(&format!("observed-{index}"),&provider,reads.clone())).unwrap();
+ let records = Arc::new(Records::default());
+ let result = observe_turn(records.clone(),capture,"session","SECRET-PROMPT",dispatch_on_worker(agent.turn("Read the file. SECRET-PROMPT"))).await.unwrap();
+ assert_eq!(result.reply,"SECRET-REPLY");
+ let terminal = records.terminal.lock().unwrap();
+ assert_eq!(terminal.len(),1);
+ assert!(terminal[0].0);
+ let events = records.events.lock().unwrap();
+ let models: Vec<_> = events.iter().filter_map(|event| match event {
+ TurnObservation::Model {answered_model,finish_reason,usage,input,output,failed,..} => Some((answered_model,finish_reason,usage,input,output,failed)), _ => None,
+ }).collect();
+ assert_eq!(models.len(),2);
+ assert!(terminal[0].1.is_some());
+ assert!(events.iter().all(|event| match event {
+ TurnObservation::Model {run_id,..} => Some(run_id) == terminal[0].1.as_ref(),
+ TurnObservation::Tool {run_id,..} => run_id == &terminal[0].1,
+ }));
+ assert_eq!(models[1].0.as_deref(),Some("actual-model"));
+ assert_eq!(models[1].1.as_deref(),Some("stop"));
+ assert_eq!(models[1].2.as_ref().unwrap().reasoning_tokens,3);
+ assert!(!models[1].5);
+ let tools: Vec<_> = events.iter().filter(|event| matches!(event,TurnObservation::Tool {..})).collect();
+ assert_eq!(tools.len(),2);
+ assert!(matches!(tools[1],TurnObservation::Tool {failed:Some(false),..}));
+ let debug = format!("{events:?}");
+ assert_eq!(debug.contains("SECRET-PATH"),capture==TraceContent::Include);
+ assert_eq!(debug.contains("SECRET-PROMPT"),capture==TraceContent::Include);
+ assert_eq!(debug.contains("SECRET-REPLY"),capture==TraceContent::Include);
+ }
+ let provider = provider(vec![completion(json!({"role":"assistant","content":"SECRET-PREMATURE"}),"stop","refused-model",7)]).await;
+ let agent = runtime.agent(reviewer("refused-observed", &provider, Arc::new(AtomicUsize::new(0)))).unwrap();
+ let records = Arc::new(Records::default());
+ observe_turn(records.clone(), TraceContent::default(), "session", "prompt", dispatch_on_worker(agent.turn("Read before replying").require_tool_call(true))).await.unwrap_err();
+ let terminal = records.terminal.lock().unwrap();
+ assert_eq!(terminal.len(),1);
+ assert!(!terminal[0].0);
+ let events = records.events.lock().unwrap();
+ assert!(events.iter().any(|event| matches!(event, TurnObservation::Model { answered_model:Some(model), usage:Some(usage), failed:false, .. } if model == "refused-model" && usage.reasoning_tokens == 7)));
+ assert!(!format!("{events:?}").contains("SECRET-PREMATURE"));
+ }).await.unwrap(); });
+}
diff --git a/crates/openhuman-embed/tests/turn_observers.rs b/crates/openhuman-embed/tests/turn_observers.rs
new file mode 100644
index 0000000000..0f3d225622
--- /dev/null
+++ b/crates/openhuman-embed/tests/turn_observers.rs
@@ -0,0 +1,88 @@
+//! Turn observers never receive payloads or raw errors by default.
+mod common;
+use openhuman_embed::CoreError;
+use openhuman_embed::observe::{
+ TraceContent, TurnObservation, TurnObserver, TurnTrace, observe_turn,
+};
+use std::sync::{Arc, Mutex};
+#[derive(Default)]
+struct Recorder(Mutex<Vec<String>>);
+impl TurnObserver for Recorder {
+ fn on_event(&self, event: &TurnObservation) {
+ self.0.lock().unwrap().push(format!("{event:?}"));
+ }
+ fn on_turn(&self, trace: &TurnTrace<'_>) {
+ self.0.lock().unwrap().push(format!("{trace:?}"));
+ }
+}
+#[test]
+fn terminal_errors_and_inputs_are_private_unless_content_is_requested() {
+ common::runtime().block_on(async {
+ let observer = Arc::new(Recorder::default());
+ let result = observe_turn(
+ observer.clone(),
+ TraceContent::default(),
+ "session",
+ "SECRET-PROMPT",
+ async {
+ Err(CoreError::Rpc {
+ method: "test",
+ message: "SECRET-ERROR".into(),
+ })
+ },
+ )
+ .await;
+ assert!(result.is_err());
+ let records = observer.0.lock().unwrap();
+ assert_eq!(records.len(), 1);
+ assert!(!records[0].contains("SECRET"));
+ assert!(records[0].contains("Provider"));
+ drop(records);
+ observe_turn(
+ observer.clone(),
+ TraceContent::Include,
+ "session",
+ "SECRET-PROMPT",
+ async {
+ Err(CoreError::Rpc {
+ method: "test",
+ message: "SECRET-ERROR".into(),
+ })
+ },
+ )
+ .await
+ .unwrap_err();
+ let records = observer.0.lock().unwrap();
+ assert!(records[1].contains("SECRET-PROMPT"));
+ assert!(!records[1].contains("SECRET-ERROR"));
+ });
+}
+
+#[cfg(feature = "langfuse")]
+#[test]
+fn existing_langfuse_exporter_builds_a_host_owned_batch_without_network() {
+ use openhuman_embed::observe::langfuse::{
+ AgentEvent, AgentObservation, EventId, LangfuseClient, LangfuseTraceConfig, RunId,
+ };
+ let client = LangfuseClient::proxy("http://127.0.0.1:1", "fixture-token").unwrap();
+ let batch = client
+ .build_ingestion_batch(
+ LangfuseTraceConfig::default(),
+ &[AgentObservation {
+ event_id: EventId::new("event"),
+ run_id: RunId::new("run"),
+ root_run_id: RunId::new("run"),
+ parent_run_id: None,
+ offset: 0,
+ ts_ms: 1_704_067_200_000,
+ event: AgentEvent::RunStarted {
+ run_id: RunId::new("run"),
+ thread_id: None,
+ },
+ }],
+ )
+ .unwrap();
+ assert_eq!(batch["batch"][0]["type"], "trace-create");
+ assert_eq!(batch["batch"][0]["body"]["id"], "run");
+ assert!(!batch.to_string().contains("fixture-token"));
+}
diff --git a/crates/openhuman-rpc/Cargo.toml b/crates/openhuman-rpc/Cargo.toml
index 6de903e389..c96550044f 100644
--- a/crates/openhuman-rpc/Cargo.toml
+++ b/crates/openhuman-rpc/Cargo.toml
@@ -11,6 +11,7 @@ publish = false
# to embed and then the core (chain: core -> embed -> tinyhumans -> rpc ->
# hosts). `http-client`, `server` and `session-store` are this crate's own.
[features]
+langfuse = ["openhuman-tinyhumans/langfuse"]
default = ["http-client", "server"]
# Authenticated HTTP client for reaching a core's `/rpc` endpoint.
http-client = ["dep:reqwest"]
diff --git a/crates/openhuman-tinyhumans/Cargo.toml b/crates/openhuman-tinyhumans/Cargo.toml
index c1f71fc9d9..bf2334c372 100644
--- a/crates/openhuman-tinyhumans/Cargo.toml
+++ b/crates/openhuman-tinyhumans/Cargo.toml
@@ -12,6 +12,7 @@ publish = false
# This crate adds no gates of its own: it is the layer that *connects* an
# embed runtime to the TinyHumans backend, not a feature surface.
[features]
+langfuse = ["openhuman-embed/langfuse"]
# `jev` is this crate's one gate of its own: the Jev-backed `tool_search`
# ranker (`tinytools-jev` over the TinyHumans System One proxy). On by
# default and forwarded by every shipped host; without it the core ranks
diff --git a/crates/openhuman-tui/Cargo.toml b/crates/openhuman-tui/Cargo.toml
index 56f4dddbee..376d61edda 100644
--- a/crates/openhuman-tui/Cargo.toml
+++ b/crates/openhuman-tui/Cargo.toml
@@ -15,6 +15,7 @@ publish = false
# through a bare workspace `openhuman-core` dependency, which turned on the
# core's whole `default`.
[features]
+langfuse = ["openhuman-rpc/langfuse"]
default = [
"crash-reporting",
"media",
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index f4de2aec6c..2be4015d16 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -667,6 +667,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
| 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |
| 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux |
+| 16.1.20 | Host turn observer privacy and runtime propagation | RI | `crates/openhuman-embed/tests/turn_observers.rs`, `crates/openhuman-embed/tests/observed_turns.rs` | ✅ | Sanitized terminal failures, opt-in payloads, root runtime scope propagation, real model/tool callbacks and answering-model usage |
## Summary