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
refactor(tinyagents): move response shape into the harness
Steven Enamakel0031a1fa5140
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex 790be38baf..8ad5952a82 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -54,7 +54,6 @@ mod policy_denial;pub(crate) mod reaper;pub(crate) mod reasoning;pub(crate) mod replay;-pub mod response_shape;mod routes;mod steering_forwarder;pub(crate) mod stop_hooks;diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape.rsdeleted file mode 100644index 92339ffb85..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs+++ /dev/null@@ -1,412 +0,0 @@-//! Per-turn response shape for a library host's turn: a response format and-//! an output cap applied to every model call of the turn, and a report of the-//! final call (finish reason, answering model, reasoning tokens).-//!-//! Carried as a task-local rather than through the session, because the-//! session host's turn plumbing is shared by every product path and none of-//! them need this. `inference::host_runtime::ops::agent_chat_reply_for` scopes-//! it around the turn for an `AgentChatTarget::Definition` that asked for it;-//! the turn runner reads it **once**, on the turn's own task, when it builds a-//! root turn's harness ([`install`]), and the middleware holds the `Arc` from-//! then on, so a model call that runs on another task still sees it.-//! Sub-agent turns never install it: the shape is the host's statement about-//! *its* turn's answer.--use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, Mutex};--use async_trait::async_trait;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::runtime::AgentHarness;-use tinyinference_llm::model::{ModelRequest, ModelResponse, ResponseFormat};--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<tinyagents_harness::observability::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.- pub structured_retries: u8,- /// Sent as `response_format` on every call of the turn's tool loop.- pub response_format: Option<ResponseFormat>,- /// Replaces the turn's per-call output cap.- pub max_output_tokens: Option<u32>,- /// Provider routing/reasoning options, applied to every model call.- pub provider_options: serde_json::Value,- /// Require a successful tool execution before accepting terminal output.- pub require_tool_call: bool,- /// Nucleus sampling probability applied to every call of this turn.- pub top_p: Option<f64>,-}--/// Validates terminal provider text without retrieving external resources.-pub trait ResponseValidator: Send + Sync {- /// Returns a safe classification, never response content.- fn validate(&self, text: &str, finish_reason: Option<&str>) -> Result<(), String>;-}--impl std::fmt::Debug for ResponseShape {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("ResponseShape")- .field("response_format", &self.response_format)- .field("max_output_tokens", &self.max_output_tokens)- .field("validator", &self.validator.is_some())- .field("structured_retries", &self.structured_retries)- .finish()- }-}--/// What the turn's final model call reported.-#[derive(Debug, Clone, Default, PartialEq)]-pub struct FinalResponse {- /// Reported accounting captured before the harness can refuse an answer.- pub usage: Option<ResponseUsage>,- /// Whether any call omitted its charged cost.- pub unknown_cost: bool,- /// Strict validation classification of the last terminal answer.- pub validation_error: Option<String>,- /// Number of terminal answer attempts (excluding tool calls).- pub structured_attempts: u16,- /// Whether the harness ended with a structured validation error.- pub structured_failed: bool,- /// The provider's finish reason for the last call (`stop`, `length`, ...).- pub finish_reason: Option<String>,- /// The model the provider says answered the last call.- pub answered_model: Option<String>,- /// Reasoning tokens summed over every call of the turn.- pub reasoning_tokens: u64,-}--/// Usage summed over physical responses, including rejected terminal answers.-#[derive(Debug, Clone, Default, PartialEq)]-pub struct ResponseUsage {- /// Prompt tokens reported by the provider.- pub input_tokens: u64,- /// Generated tokens reported by the provider.- pub output_tokens: u64,- /// Cached prompt tokens.- pub cached_tokens: u64,- /// Reasoning tokens.- pub reasoning_tokens: u64,- /// Charged cost, unknown if any response omitted it.- pub cost_usd: Option<f64>,- /// At least one call supplied a billing receipt, including a malformed one.- /// Distinguishes absent receipts from invalid authoritative billing data.- pub has_cost_receipt: bool,-}--impl ResponseUsage {- /// Build failure accounting when the session has no completed-turn record.- pub fn failure_usage(&self) -> crate::agent::tinyagents::host::LastTurnUsage {- crate::agent::tinyagents::host::LastTurnUsage {- input_tokens: self.input_tokens,- output_tokens: self.output_tokens,- cached_input_tokens: self.cached_tokens,- reasoning_tokens: self.reasoning_tokens,- cost_usd: self.cost_usd,- cost_source: if self.cost_usd.is_some() {- crate::agent::cost::CostSource::Charged- } else {- crate::agent::cost::CostSource::Unknown- },- ..Default::default()- }- }-}--/// A shape and the report slot its turn fills.-#[derive(Debug, Default)]-pub struct ResponseShapeScope {- shape: ResponseShape,- report: Mutex<FinalResponse>,- tool_succeeded: AtomicBool,-}--impl ResponseShapeScope {- /// A scope asking for `shape`.- #[must_use]- pub fn new(shape: ResponseShape) -> Arc<Self> {- Arc::new(Self {- shape,- report: Mutex::default(),- tool_succeeded: AtomicBool::new(false),- })- }-- /// What the turn's calls have reported so far.- #[must_use]- pub fn report(&self) -> FinalResponse {- self.report- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .clone()- }-}--tokio::task_local! {- static RESPONSE_SHAPE: Arc<ResponseShapeScope>;-}--/// Run `fut` with `scope` as its turn's response shape.-pub async fn with_response_shape<F: std::future::Future>(- scope: Arc<ResponseShapeScope>,- fut: F,-) -> F::Output {- let observer = scope.shape.observer.clone();- let run = RESPONSE_SHAPE.scope(scope, Box::pin(fut));- match observer {- Some(observer) => {- tinyagents_harness::observability::turn_observer::with_observer(observer, run).await- }- None => run.await,- }-}--/// Push the shaping middleware onto a root turn's harness, when a shape is-/// scoped around the turn.-pub(super) fn install(harness: &mut AgentHarness<(), OpenHumanRunContext>, root: bool) {- if !root {- return;- }- if let Ok(scope) = RESPONSE_SHAPE.try_with(Arc::clone) {- log::debug!(- "[tinyagents] response shape installed: format={} max_output_tokens={:?}",- scope.shape.response_format.is_some(),- scope.shape.max_output_tokens- );- if scope.shape.validator.is_some() {- let mut policy = harness.policy().clone();- // The generic loop owns bounded repair. Its extraction schema is- // permissive because the host validator applies the complete schema.- policy.default_response_format = Some(ResponseFormat::JsonSchema {- name: "host_answer".into(),- schema: serde_json::json!({}),- });- policy.output_retry.max_attempts = scope.shape.structured_retries;- // Strict output validation owns the complete repair allowance;- // empty-response recovery must not issue additional model calls.- policy.truncated_empty_retries = 0;- policy.truncated_empty_nudges = 0;- policy.output_retry.message_template =- "Return complete JSON matching the requested schema.".into();- harness.with_policy(policy);- harness.with_output_validator(Arc::new(StrictValidator(Arc::clone(&scope))));- }- harness.push_middleware(Arc::new(ResponseShapeMiddleware(scope)));- }-}--struct ResponseShapeMiddleware(Arc<ResponseShapeScope>);--#[async_trait]-impl Middleware<(), OpenHumanRunContext> for ResponseShapeMiddleware {- fn name(&self) -> &str {- "openhuman_response_shape"- }-- async fn before_model(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- request: &mut ModelRequest,- ) -> TaResult<()> {- let shape = &self.0.shape;- if shape.require_tool_call && !self.0.tool_succeeded.load(Ordering::Acquire) {- if request.tools.is_empty() {- return Err(- tinyagents_harness::error::TinyAgentsError::StructuredOutput(- "required_tool_call_has_no_tools".into(),- ),- );- }- // Tool selection must remain free to emit function calls: asking- // for the final JSON shape here can make a model skip exploration.- request.response_format = None;- request.tool_choice = tinyinference_llm::model::ToolChoice::Required;- } else if let Some(format) = &shape.response_format {- request.response_format = Some(format.clone());- }- if !shape.provider_options.is_null() {- request.provider_options = shape.provider_options.clone();- }- if let Some(cap) = shape.max_output_tokens {- request.max_tokens = Some(cap);- }- if let Some(top_p) = shape.top_p {- request.top_p = Some(top_p);- }- Ok(())- }-- async fn after_model(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- response: &mut ModelResponse,- ) -> TaResult<()> {- record(&self.0, response);- if response.tool_calls().is_empty() {- if let Some(validator) = &self.0.shape.validator {- let error = validator- .validate(&response.text(), response.finish_reason.as_deref())- .err();- let mut report = self- .0- .report- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- report.structured_attempts = report.structured_attempts.saturating_add(1);- report.validation_error = error;- }- }- if self.0.shape.require_tool_call- && !self.0.tool_succeeded.load(Ordering::Acquire)- && response.tool_calls().is_empty()- {- self.0- .report- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .validation_error = Some("RequiredToolCallMissing".into());- // tool_choice is advisory on compatible gateways. Enforce the- // host requirement even when a provider ignores that wire hint.- return Err(- tinyagents_harness::error::TinyAgentsError::StructuredOutput(- "required_tool_call_missing".into(),- ),- );- }- Ok(())- }-- async fn after_tool(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- _invocation: &tinyagents_harness::middleware::ToolInvocationIdentity,- result: &mut tinytools::ToolResult,- ) -> TaResult<()> {- if !result.is_error {- self.0.tool_succeeded.store(true, Ordering::Release);- }- Ok(())- }- async fn on_error(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- error: &tinyagents_harness::error::TinyAgentsError,- ) -> TaResult<()> {- if matches!(- error,- tinyagents_harness::error::TinyAgentsError::StructuredOutput(_)- ) {- self.0- .report- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .structured_failed = true;- }- Ok(())- }- fn is_observer(&self) -> bool {- true- }-}--struct StrictValidator(Arc<ResponseShapeScope>);-#[async_trait]-impl tinyagents_harness::structured::OutputValidator<(), OpenHumanRunContext> for StrictValidator {- async fn validate(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- _output: &serde_json::Value,- ) -> TaResult<()> {- match self.0.report().validation_error {- Some(reason) => Err(tinyagents_harness::error::TinyAgentsError::ModelRetry(- reason,- )),- None => Ok(()),- }- }-}--/// Fold one completed call into the report: the last call's finish reason-/// and model win; reasoning tokens add up (a cache replay spent none).-fn record(scope: &ResponseShapeScope, response: &ModelResponse) {- let mut report = scope- .report- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- report.finish_reason = response.finish_reason.clone();- report.answered_model = response- .raw- .as_ref()- .and_then(|raw| raw.get("model"))- .and_then(serde_json::Value::as_str)- .filter(|model| !model.trim().is_empty())- .map(str::to_owned)- .or_else(|| {- response- .resolved_route- .as_ref()- .map(|route| route.model.clone())- .or_else(|| response.resolved_model.as_ref().map(|m| m.name.clone()))- .filter(|model| !model.trim().is_empty())- });- if !response.served_from_cache {- let raw_cost = response.raw.as_ref().and_then(|raw| {- // Presence selects the authoritative source; malformed billing- // must remain unknown rather than fall through to an estimate.- if let Some(buyer) = raw.pointer("/usage/buyer_cost_micro") {- Some(buyer.as_f64().map(|value| value / 1_000_000.0))- } else {- raw.pointer("/usage/cost").map(serde_json::Value::as_f64)- }- });- let cost = raw_cost- .unwrap_or_else(|| {- response- .usage- .and_then(|usage| usage.charged_amount)- .map(|amount| amount.micros as f64 / 1_000_000.0)- })- .filter(|cost| cost.is_finite() && *cost >= 0.0);- report.unknown_cost |= cost.is_none();- let unknown_cost = report.unknown_cost;- if response.usage.is_some() || cost.is_some() {- let total = report.usage.get_or_insert_with(ResponseUsage::default);- total.has_cost_receipt |= raw_cost.is_some()- || response- .usage- .and_then(|usage| usage.charged_amount)- .is_some();- total.cost_usd = if unknown_cost {- None- } else {- Some(total.cost_usd.unwrap_or_default() + cost.unwrap_or_default())- };- if let Some(usage) = &response.usage {- total.input_tokens = total.input_tokens.saturating_add(usage.input_tokens);- total.output_tokens = total.output_tokens.saturating_add(usage.output_tokens);- total.cached_tokens = total.cached_tokens.saturating_add(usage.cache_read_tokens);- total.reasoning_tokens = total- .reasoning_tokens- .saturating_add(usage.reasoning_tokens);- }- }- if let Some(usage) = &response.usage {- report.reasoning_tokens += usage.reasoning_tokens;- }- }-}--#[cfg(test)]-#[path = "response_shape_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape_tests.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape_tests.rsdeleted file mode 100644index 8412e62115..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/response_shape_tests.rs+++ /dev/null@@ -1,40 +0,0 @@-use super::*;-use tinyinference_llm::usage::Usage;--fn response(finish: &str, reasoning: u64, cached: bool) -> ModelResponse {- let mut response = ModelResponse::assistant("{}")- .with_usage(Usage {- reasoning_tokens: reasoning,- ..Default::default()- })- .with_finish_reason(finish);- response.served_from_cache = cached;- response-}--#[test]-fn the_last_call_reports_and_reasoning_adds_up() {- let scope = ResponseShapeScope::new(ResponseShape::default());- record(&scope, &response("tool_calls", 3, false));- record(&scope, &response("stop", 4, false));- record(&scope, &response("stop", 100, true));-- let report = scope.report();- assert_eq!(report.finish_reason.as_deref(), Some("stop"));- assert_eq!(report.reasoning_tokens, 7, "a cache replay spent nothing");-}--#[tokio::test]-async fn install_needs_a_scoped_shape_and_a_root_turn() {- let mut harness: AgentHarness<(), OpenHumanRunContext> = AgentHarness::new();- install(&mut harness, true);- let scope = ResponseShapeScope::new(ResponseShape {- max_output_tokens: Some(64),- ..Default::default()- });- with_response_shape(scope, async {- install(&mut harness, false);- install(&mut harness, true);- })- .await;-}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex 07abc6095a..3c5dc4bd35 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -298,7 +298,11 @@ pub(super) async fn run_turn_via_tinyagents_body(run_context.memory_turn.clone(),run_context.tool_rules.clone(),);- super::response_shape::install(&mut harness, hosted_root.is_some());+ if hosted_root.is_some() {+ if let Some(scope) = run_context.response_shape.clone() {+ tinyagents_harness::middleware::install_response_shape(&mut harness, scope);+ }+ }super::budget::install_depth(&mut harness, &run_context);super::deadline_wind_down::install(&mut harness, &handle, &run_context, &subagent_scope);// Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).diff --git a/crates/openhuman-core/src/agent/turn_projection.rs b/crates/openhuman-core/src/agent/turn_projection.rsindex bcf618d01a..61d96f0e7f 100644--- a/crates/openhuman-core/src/agent/turn_projection.rs+++ b/crates/openhuman-core/src/agent/turn_projection.rs@@ -5,6 +5,9 @@//! mapping of a stop note without a failure class to its stop-reason key//! ([`StopReasonKind`](crate::agent::session_host::stop_summary::StopReasonKind)).+use crate::agent::cost::CostSource;+use crate::agent::tinyagents::host::LastTurnUsage;+use tinyagents_harness::middleware::ResponseUsage;use tinyagents_harness::turn_stop::TurnStop;/// The stop-reason key for a breaker note that names no failure class.@@ -31,6 +34,25 @@ pub fn stop_from_incomplete(reason: &str) -> TurnStop {TurnStop::from_incomplete_reason(reason, stop_fallback_class)}+/// Failure accounting for a turn the session has no completed-turn record+/// for: the harness's reported [`ResponseUsage`] projected onto the product's+/// [`LastTurnUsage`], priced `Charged` only when the provider reported a cost.+pub fn failure_usage(usage: &ResponseUsage) -> LastTurnUsage {+ LastTurnUsage {+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ cached_input_tokens: usage.cached_tokens,+ reasoning_tokens: usage.reasoning_tokens,+ cost_usd: usage.cost_usd,+ cost_source: if usage.cost_usd.is_some() {+ CostSource::Charged+ } else {+ CostSource::Unknown+ },+ ..Default::default()+ }+}+#[cfg(test)]#[path = "turn_projection_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/agent/turn_projection_tests.rs b/crates/openhuman-core/src/agent/turn_projection_tests.rsindex f81b686a4f..7276fe8d6d 100644--- a/crates/openhuman-core/src/agent/turn_projection_tests.rs+++ b/crates/openhuman-core/src/agent/turn_projection_tests.rs@@ -46,3 +46,25 @@ fn an_incomplete_reason_maps_to_cap_or_breaker() {Some("web_answer_tool"));}++#[test]+fn reported_usage_projects_as_charged_only_with_a_cost() {+ let charged = failure_usage(&ResponseUsage {+ input_tokens: 10,+ output_tokens: 5,+ cached_tokens: 3,+ reasoning_tokens: 2,+ cost_usd: Some(0.007),+ has_cost_receipt: true,+ });+ assert_eq!(charged.cost_source, CostSource::Charged);+ assert_eq!(charged.cost_usd, Some(0.007));+ assert_eq!(+ (charged.input_tokens, charged.output_tokens, charged.cached_input_tokens, charged.reasoning_tokens),+ (10, 5, 3, 2)+ );+ assert_eq!(+ failure_usage(&ResponseUsage::default()).cost_source,+ CostSource::Unknown+ );+}diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rsindex f05fe17c3e..9689ac6819 100644--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs@@ -168,8 +168,12 @@ pub enum AgentChatTarget<'a> {untrusted_input: bool,/// A response format and output cap for every model call of the turn,/// and the slot its final call is reported into.- shape: Option<- &'a std::sync::Arc<crate::agent::tinyagents::response_shape::ResponseShapeScope>,+ shape: Option<&'a std::sync::Arc<tinyagents_harness::middleware::ResponseShapeScope>>,+ /// The observer scoped around the caller, re-established around the+ /// turn because the dispatch may run on a worker task that does not+ /// inherit task locals.+ observer: Option<+ &'a std::sync::Arc<tinyagents_harness::observability::turn_observer::ObserverScope>,>,/// Files the host attaches to this turn as bytes, in order.///@@ -501,6 +505,14 @@ pub async fn agent_chat_reply_for(seed.len());}+ // The response shape rides the session explicitly (no task-local): the+ // next turn takes it into its run context.+ if let AgentChatTarget::Definition {+ shape: Some(scope), ..+ } = target+ {+ agent.set_next_turn_response_shape(Some(std::sync::Arc::clone(scope)));+ }// Live progress for in-process embedders. `OpenHumanSessionHost::from_config` never// attaches a sink itself, so there is nothing to clobber here; callers that// set one explicitly (web chat, platform socket, flows, skills) hold their@@ -544,9 +556,14 @@ pub async fn agent_chat_reply_for(};let outcome = match target {AgentChatTarget::Definition {- shape: Some(scope), ..+ observer: Some(observer),+ ..} => {- crate::agent::tinyagents::response_shape::with_response_shape(scope.clone(), run).await+ tinyagents_harness::observability::turn_observer::with_observer(+ std::sync::Arc::clone(observer),+ run,+ )+ .await}_ => run.await,};diff --git a/crates/openhuman-embed/src/structured.rs b/crates/openhuman-embed/src/structured.rsindex cf49d268c8..f89d837b8c 100644--- a/crates/openhuman-embed/src/structured.rs+++ b/crates/openhuman-embed/src/structured.rs@@ -109,7 +109,7 @@ pub(crate) fn accumulate(total: &mut Option<CompletionUsage>, usage: Option<&Com}}-impl openhuman_core::agent::tinyagents::response_shape::ResponseValidator for Validator {+impl tinyagents_harness::middleware::ResponseValidator for Validator {fn validate(&self, text: &str, finish_reason: Option<&str>) -> Result<(), String> {self.validate(text, finish_reason).map(|_| ())diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 6284e1811a..a3c3d7752a 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -481,7 +481,7 @@ use openhuman_core::agent::tinyagents::host::LastTurnUsage;use crate::turn_meter::UsageSink;-use openhuman_core::agent::tinyagents::response_shape::{FinalResponse, ResponseShapeScope};+use tinyagents_harness::middleware::{FinalResponse, ResponseShapeScope};/// A turn's reply text and, for an agent target, its final-response report.type AgentReply = (String, Option<FinalResponse>);@@ -497,6 +497,7 @@ mod futures_box {struct AgentTurnOptions {tools: Option<openhuman_core::agent::HostTools>,shape: std::sync::Arc<ResponseShapeScope>,+ observer: Option<std::sync::Arc<tinyagents_harness::observability::turn_observer::ObserverScope>>,untrusted_input: bool,attachments: Vec<openhuman_core::agent::HostAttachment>,}@@ -580,6 +581,7 @@ async fn dispatch(host_only: inner.host_only,untrusted_input: options.untrusted_input,shape: Some(&options.shape),+ observer: options.observer.as_ref(),attachments: &options.attachments,};let outcome = agent_chat_for(diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rsindex 18fce43b4a..8f5b5098b0 100644--- a/crates/openhuman-embed/src/turn_control.rs+++ b/crates/openhuman-embed/src/turn_control.rs@@ -336,19 +336,22 @@ impl Turn {}})?;let options = AgentTurnOptions {- shape: openhuman_core::agent::tinyagents::response_shape::ResponseShapeScope::new(- openhuman_core::agent::tinyagents::response_shape::ResponseShape {+ // Captured here, before the dispatch can hop to a core worker that+ // does not inherit task locals; the core re-establishes it around+ // the turn.+ observer: tinyagents_harness::observability::turn_observer::current_scope(),+ shape: tinyagents_harness::middleware::ResponseShapeScope::new(+ tinyagents_harness::middleware::ResponseShape {response_format: self.response_format.take().map(crate::complete::ResponseFormat::into_wire),max_output_tokens: self.max_tokens,top_p: self.top_p,- validator: wants_json.then(|| std::sync::Arc::new(validator) as std::sync::Arc<dyn openhuman_core::agent::tinyagents::response_shape::ResponseValidator>),+ validator: wants_json.then(|| std::sync::Arc::new(validator) as std::sync::Arc<dyn tinyagents_harness::middleware::ResponseValidator>),structured_retries: self.structured_retries,provider_options: self.provider_options.clone(),require_tool_call: self.require_tool_call,- observer: tinyagents_harness::observability::turn_observer::current_scope(),},),untrusted_input: self.untrusted_input,diff --git a/crates/openhuman-embed/src/turn_types.rs b/crates/openhuman-embed/src/turn_types.rsindex 816e45ab75..0fc8e52e4c 100644--- a/crates/openhuman-embed/src/turn_types.rs+++ b/crates/openhuman-embed/src/turn_types.rs@@ -8,7 +8,7 @@ mod usage_tests;/// Overlay root provider accounting while retaining session context and children.pub(super) fn overlay_response_usage(captured: &mut Option<openhuman_core::agent::tinyagents::host::LastTurnUsage>,- reported: &openhuman_core::agent::tinyagents::response_shape::ResponseUsage,+ reported: &tinyagents_harness::middleware::ResponseUsage,) {let usage = captured.get_or_insert_with(Default::default);// A session may have a legitimate catalog estimate when every provider@@ -16,7 +16,7 @@ pub(super) fn overlay_response_usage(let preserve_host_cost = reported.cost_usd.is_none() && !reported.has_cost_receipt;let host_cost = usage.cost_usd;let host_source = usage.cost_source;- let root = reported.failure_usage();+ let root = openhuman_core::agent::turn_projection::failure_usage(reported);usage.input_tokens = root.input_tokens;usage.output_tokens = root.output_tokens;usage.cached_input_tokens = root.cached_input_tokens;diff --git a/crates/openhuman-embed/tests/observed_turns.rs b/crates/openhuman-embed/tests/observed_turns.rsindex 2b63b23fd1..f33bc2e89e 100644--- a/crates/openhuman-embed/tests/observed_turns.rs+++ b/crates/openhuman-embed/tests/observed_turns.rs@@ -130,16 +130,13 @@ impl openhuman_embed::observe::TurnObserver for Records {async fn dispatch_on_worker(turn: openhuman_embed::Turn,) -> Result<openhuman_embed::TurnOutcome, openhuman_embed::CoreError> {- use openhuman_core::agent::tinyagents::response_shape::{- with_response_shape, ResponseShape, ResponseShapeScope,- };- let shape = ResponseShapeScope::new(ResponseShape {- observer: tinyagents_harness::observability::turn_observer::current_scope(),- ..ResponseShape::default()- });- tokio::spawn(with_response_shape(shape, turn.send()))- .await- .expect("worker task")+ use tinyagents_harness::observability::turn_observer::{current_scope, with_observer};+ let run = turn.send();+ match current_scope() {+ Some(observer) => tokio::spawn(with_observer(observer, run)).await,+ None => tokio::spawn(run).await,+ }+ .expect("worker task")}#[test]fn model_and_tool_observations_capture_payloads_only_with_consent() {diff --git a/crates/openhuman-embed/tests/unit/turn_usage.rs b/crates/openhuman-embed/tests/unit/turn_usage.rsindex 7a964c4815..98a9c11e2a 100644--- a/crates/openhuman-embed/tests/unit/turn_usage.rs+++ b/crates/openhuman-embed/tests/unit/turn_usage.rs@@ -2,7 +2,7 @@use super::overlay_response_usage;use openhuman_core::agent::subagent_host::SubagentUsage;use openhuman_core::agent::tinyagents::host::{LastTurnUsage, SubagentUsageEntry};-use openhuman_core::agent::tinyagents::response_shape::ResponseUsage;+use tinyagents_harness::middleware::ResponseUsage;#[test]fn reported_root_usage_preserves_children_and_session_context_without_double_counting() {@@ -26,7 +26,7 @@ fn reported_root_usage_preserves_children_and_session_context_without_double_cououtput_tokens: 8,cached_input_tokens: 4,charged_amount_usd: 0.003,- cost_source: report.failure_usage().cost_source,+ cost_source: openhuman_core::agent::turn_projection::failure_usage(&report).cost_source,},}],..Default::default()@@ -48,7 +48,7 @@ fn reported_root_usage_preserves_children_and_session_context_without_double_couassert_eq!(usage.subagents.len(), 1);}captured.as_mut().unwrap().subagents[0].usage.cost_source =- ResponseUsage::default().failure_usage().cost_source;+ openhuman_core::agent::turn_projection::failure_usage(&ResponseUsage::default()).cost_source;overlay_response_usage(&mut captured, &report);assert_eq!(captured.as_ref().unwrap().cost_usd, None);assert_eq!(captured.as_ref().unwrap().input_tokens, 30);