The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(embed): retain refused-call usage and acknowledge completion cancellation
Steven Enamakel8176f147dfe6
diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape.rsindex c42bb4fe86..9b8a21dc27 100644--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs+++ b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs@@ -59,8 +59,12 @@ impl std::fmt::Debug for ResponseShape {}/// What the turn's final model call reported.-#[derive(Debug, Clone, Default, PartialEq, Eq)]+#[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).@@ -75,6 +79,40 @@ pub struct FinalResponse {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>,+}++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 {@@ -210,6 +248,11 @@ impl Middleware<(), OpenHumanRunContext> for ResponseShapeMiddleware {&& !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(@@ -297,6 +340,41 @@ fn record(scope: &ResponseShapeScope, response: &ModelResponse) {.filter(|model| !model.trim().is_empty())});if !response.served_from_cache {+ let raw_cost = response.raw.as_ref().and_then(|raw| {+ raw.pointer("/usage/buyer_cost_micro")+ .and_then(serde_json::Value::as_f64)+ .map(|value| value / 1_000_000.0)+ .or_else(|| {+ raw.pointer("/usage/cost")+ .and_then(serde_json::Value::as_f64)+ })+ });+ let cost = raw_cost+ .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.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;}diff --git a/crates/openhuman-embed/STRUCTURED-OUTPUT.md b/crates/openhuman-embed/STRUCTURED-OUTPUT.mdnew file mode 100644index 0000000000..c20a1cec95--- /dev/null+++ b/crates/openhuman-embed/STRUCTURED-OUTPUT.md@@ -0,0 +1,34 @@+# Structured output for embedding hosts++`Completer` and runtime-owned `Agent::turn` validate requested JSON locally.+Parseable JSON is not sufficient: `JsonSchema` applies the full schema,+including numeric bounds, combinators and local references. External schema+retrieval is disabled even when another dependency enables retrieval features.+Invalid schemas fail before provider dispatch. `JsonObject` requires an object.+A `length` or `max_tokens` finish is refused even if the text happens to parse.++Repair is explicit: `.structured_retries(2)` allows two additional terminal+answer attempts. The default is zero and values above three are rejected before+dispatch. Agent tools can run between attempts; their calls count towards the+ordinary harness limits. The existing TinyAgents output-validator loop owns+agent repair; Embed does not implement a second agent loop. Every model call+still passes through the configured budget and route.++Failures are `CoreError::StructuredOutput { method, failure }`. The failure+contains classification, terminal attempt count, last answering model and finish+reason, and reported usage. It contains no original answer or validation error+that might quote a secret. Repair feedback describes the failure without+feeding the invalid answer back. Completion usage sums all repair attempts;+unknown cost stays unknown rather than treating an unreported call as free.++`Turn::require_tool_call(true)` additionally requires a successful tool execution+before accepting the answer. A proposed, rejected or failed tool call is not a+successful read. Before execution the provider gets `tool_choice: required` and+no final response format; afterwards it receives the requested answer schema.+The host also enforces this requirement when a provider ignores the wire hint.++Use a `HostOnly`, read-only agent and the [repository tools](src/repository/README.md)+for untrusted review input. Validation does not grant tool or write permissions.++Tests: `structured_validation`, `structured_turns`, `tool_required_routing`, and+`completion_routing` use loopback provider fixtures and require no model key.diff --git a/crates/openhuman-embed/src/cancellation.rs b/crates/openhuman-embed/src/cancellation.rsnew file mode 100644index 0000000000..220c54578f--- /dev/null+++ b/crates/openhuman-embed/src/cancellation.rs@@ -0,0 +1,52 @@+//! Cooperative cancellation with acknowledgement of all attached calls stopping.+use std::sync::Arc;+use tokio::sync::watch;++struct State {+ requested: watch::Sender<bool>,+ active: watch::Sender<usize>,+}++/// Cancellation shared by attached completers. Cancellation is permanent;+/// create a fresh handle for a new operation or review.+#[derive(Clone)]+pub struct Cancellation(Arc<State>);+impl Default for Cancellation {+ fn default() -> Self {+ Self(Arc::new(State {+ requested: watch::Sender::new(false),+ active: watch::Sender::new(0),+ }))+ }+}+impl std::fmt::Debug for Cancellation {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Cancellation")+ .field("requested", &*self.0.requested.borrow())+ .finish()+ }+}+impl Cancellation {+ /// Request cancellation and wait for all currently attached call futures+ /// to be dropped, observers notified, and reservations settled. Keep polling+ /// those calls (usually in another Tokio task) while awaiting this method.+ pub async fn cancel(&self) {+ self.0.requested.send_replace(true);+ let mut active = self.0.active.subscribe();+ let _ = active.wait_for(|count| *count == 0).await;+ }+ pub(crate) async fn cancelled(&self) {+ let mut requested = self.0.requested.subscribe();+ let _ = requested.wait_for(|value| *value).await;+ }+ pub(crate) fn enter(&self) -> Guard {+ self.0.active.send_modify(|count| *count += 1);+ Guard(self.clone())+ }+}+pub(crate) struct Guard(Cancellation);+impl Drop for Guard {+ fn drop(&mut self) {+ self.0 .0.active.send_modify(|count| *count -= 1);+ }+}diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rsindex 10ab03663e..3343058dc6 100644--- a/crates/openhuman-embed/src/complete.rs+++ b/crates/openhuman-embed/src/complete.rs@@ -406,6 +406,7 @@ pub struct Completer {headers: Vec<(String, String)>,timeout: Option<Duration>,observer: Option<Arc<dyn CompletionObserver>>,+ cancellation: crate::cancellation::Cancellation,}impl std::fmt::Debug for Completer {@@ -427,6 +428,7 @@ impl Completer {headers: Vec::new(),timeout: None,observer: None,+ cancellation: Default::default(),}}@@ -437,12 +439,18 @@ impl Completer {self}- /// Fail a call that has not settled within `timeout`.+ /// Bound the entire logical call, including structured repair attempts.pub fn timeout(mut self, timeout: Duration) -> Self {self.timeout = Some(timeout);self}+ /// Attach an acknowledged cancellation scope shared with other calls.+ pub fn cancellation(mut self, cancellation: crate::cancellation::Cancellation) -> Self {+ self.cancellation = cancellation;+ self+ }+/// Report every call to `observer`.pub fn observer(mut self, observer: Arc<dyn CompletionObserver>) -> Self {self.observer = Some(observer);@@ -462,7 +470,22 @@ impl Completer {request: CompletionRequest,) -> Result<CompletionResponse, CoreError> {let started = Instant::now();- let result = self.validated_dispatch(request.clone()).await;+ let _guard = self.cancellation.enter();+ let operation = async {+ match self.timeout {+ Some(limit) => {+ tokio::time::timeout(limit, self.validated_dispatch(request.clone()))+ .await+ .unwrap_or(Err(CoreError::DeadlineExceeded { method: COMPLETE }))+ }+ None => self.validated_dispatch(request.clone()).await,+ }+ };+ let result = tokio::select! {+ biased;+ _ = self.cancellation.cancelled() => Err(CoreError::Cancelled { method: COMPLETE }),+ result = operation => result,+ };if let Some(observer) = &self.observer {observer.on_complete(&CompletionTrace {request: &request,@@ -496,9 +519,19 @@ impl Completer {let validator =Validator::new(request.response_format.as_ref()).map_err(initial_failure)?;let mut usage = None;+ let mut unknown_cost = false;for attempt in 0..=request.structured_retries {let mut response = self.dispatch(request.clone()).await?;+ unknown_cost |= response+ .usage+ .as_ref()+ .is_none_or(|usage| usage.cost_usd.is_none());accumulate(&mut usage, response.usage.as_ref());+ if unknown_cost {+ if let Some(usage) = &mut usage {+ usage.cost_usd = None;+ }+ }match validator.validate(&response.text, response.finish_reason.as_deref()) {Ok(value) => { response.structured = value; response.usage = usage; return Ok(response); }Err(reason) if attempt == request.structured_retries => return Err(CoreError::StructuredOutput {@@ -527,25 +560,7 @@ impl Completer {request.into_wire(),);let started = std::time::Instant::now();- let response = match self.timeout {- Some(limit) => match tokio::time::timeout(limit, call).await {- Ok(outcome) => outcome,- Err(_) => {- // Metadata only: method, model and elapsed time, never content.- log::warn!(- "[embed] complete timed out method={COMPLETE} model={model} limit_ms={} elapsed_ms={}",- limit.as_millis(),- started.elapsed().as_millis()- );- return Err(CoreError::Rpc {- method: COMPLETE,- message: format!("timed out after {}ms", limit.as_millis()),- });- }- },- None => call.await,- }- .map_err(|message| {+ let response = call.await.map_err(|message| {log::warn!("[embed] complete failed method={COMPLETE} model={model} elapsed_ms={}",started.elapsed().as_millis()diff --git a/crates/openhuman-embed/src/complete_tests.rs b/crates/openhuman-embed/src/complete_tests.rsindex 02765d40be..24a9950f41 100644--- a/crates/openhuman-embed/src/complete_tests.rs+++ b/crates/openhuman-embed/src/complete_tests.rs@@ -267,10 +267,7 @@ async fn slow_provider_hits_the_timeout_branch() {.await.expect_err("the call must time out before the delayed reply");match err {- CoreError::Rpc { method, message } => {- assert_eq!(method, COMPLETE);- assert_eq!(message, "timed out after 50ms");- }- other => panic!("expected a timeout Rpc error, got {other:?}"),+ CoreError::DeadlineExceeded { method } => assert_eq!(method, COMPLETE),+ other => panic!("expected a typed deadline error, got {other:?}"),}}diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rsindex 13c7833789..e3baa343fc 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -26,6 +26,18 @@ use openhuman_core::core::StructuredRpcError;/// Error returned by every typed facade call.#[derive(Debug, thiserror::Error)]pub enum CoreError {+ /// The host cancelled the call and its provider future has stopped.+ #[error("{method}: cancelled")]+ Cancelled {+ /// Cancelled operation.+ method: &'static str,+ },+ /// The entire logical call exceeded its deadline, including repairs.+ #[error("{method}: deadline exceeded")]+ DeadlineExceeded {+ /// Expired operation.+ method: &'static str,+ },/// Requested JSON failed strict validation after bounded repair.#[error("{method}: {failure}")]StructuredOutput {@@ -169,7 +181,9 @@ impl CoreError {/// The RPC method this error came from.pub fn method(&self) -> &'static str {match self {- CoreError::StructuredOutput { method, .. }+ CoreError::Cancelled { method }+ | CoreError::DeadlineExceeded { method }+ | CoreError::StructuredOutput { method, .. }| CoreError::Domain { method, .. }| CoreError::Unavailable { method }| CoreError::Rpc { method, .. }diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex a9af3d51b4..8f7508e228 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -291,3 +291,6 @@ impl std::fmt::Debug for Core {/// Strict structured output failure metadata.pub mod structured;++/// Acknowledged cancellation for stateless completion operations.+pub mod cancellation;diff --git a/crates/openhuman-embed/src/routing.rs b/crates/openhuman-embed/src/routing.rsindex b26b87d4b0..439c7d6f59 100644--- a/crates/openhuman-embed/src/routing.rs+++ b/crates/openhuman-embed/src/routing.rs@@ -200,6 +200,14 @@ impl CompletionLadder {usage: response.usage.clone(),failed: false,},+ Err(CoreError::StructuredOutput { failure, .. }) => CompletionAttempt {+ requested_model: current.model.clone(),+ max_tokens: current.max_tokens,+ answered_model: failure.answered_model.clone(),+ finish_reason: failure.finish_reason.clone(),+ usage: failure.usage.clone(),+ failed: true,+ },Err(_) => CompletionAttempt {requested_model: current.model.clone(),max_tokens: current.max_tokens,@@ -226,7 +234,18 @@ impl CompletionLadder {}}Err(error) => {- if !matches!(error, CoreError::Rpc { .. }) {+ if !matches!(+ &error,+ CoreError::Rpc { .. } | CoreError::StructuredOutput {+ failure: crate::structured::StructuredOutputFailure {+ reason: crate::structured::StructuredFailureReason::InvalidJson+ | crate::structured::StructuredFailureReason::SchemaMismatch+ | crate::structured::StructuredFailureReason::Truncated,+ ..+ },+ ..+ }+ ) {return Err(ladder_error(error, attempts));}last_error = error;diff --git a/crates/openhuman-embed/src/structured.rs b/crates/openhuman-embed/src/structured.rsindex 559dee9473..85b54f41f7 100644--- a/crates/openhuman-embed/src/structured.rs+++ b/crates/openhuman-embed/src/structured.rs@@ -7,6 +7,8 @@ use serde_json::Value;/// Why a requested structured answer was refused.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub enum StructuredFailureReason {+ /// The host required a successful repository read before the answer.+ RequiredToolCallMissing,/// The host supplied an invalid or externally resolved schema.InvalidSchema,/// The reply was not complete JSON.diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 8a897e4c74..124691b34c 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -607,6 +607,8 @@ impl Turn {// variant classification are logged; the error itself propagates// to the caller untouched.let tag = match err {+ crate::error::CoreError::Cancelled { .. } => "cancelled",+ crate::error::CoreError::DeadlineExceeded { .. } => "deadline",crate::error::CoreError::StructuredOutput { .. } => "structured_output",crate::error::CoreError::Domain { .. } => "domain",crate::error::CoreError::Unavailable { .. } => "unavailable",@@ -820,18 +822,25 @@ async fn dispatch(// report does. Folded in before the meter or the outcome reads// the sink, on success and failure alike.let report = options.shape.report();- if let Some(spent) = usage- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .as_mut(){- spent.reasoning_tokens = report.reasoning_tokens;+ let mut captured = usage+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if captured.is_none() {+ if let Some(spent) = &report.usage {+ *captured = Some(spent.failure_usage());+ }+ }+ if let Some(spent) = captured.as_mut() {+ spent.reasoning_tokens = report.reasoning_tokens;+ }}if outcome.is_err() && report.structured_failed {use crate::structured::{StructuredFailureReason as Reason, StructuredOutputFailure,};let reason = match report.validation_error.as_deref() {+ Some("RequiredToolCallMissing") => Reason::RequiredToolCallMissing,Some("Truncated") => Reason::Truncated,Some("SchemaMismatch") => Reason::SchemaMismatch,_ => Reason::InvalidJson,@@ -843,17 +852,13 @@ async fn dispatch(reason,finish_reason: report.finish_reason,answered_model: report.answered_model,- usage: usage- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .as_ref()- .map(|spent| crate::complete::CompletionUsage {- input_tokens: spent.input_tokens,- output_tokens: spent.output_tokens,- cached_tokens: spent.cached_input_tokens,- reasoning_tokens: spent.reasoning_tokens,- cost_usd: spent.cost_usd,- }),+ usage: report.usage.map(|spent| crate::complete::CompletionUsage {+ input_tokens: spent.input_tokens,+ output_tokens: spent.output_tokens,+ cached_tokens: spent.cached_tokens,+ reasoning_tokens: spent.reasoning_tokens,+ cost_usd: spent.cost_usd,+ }),},});}diff --git a/crates/openhuman-embed/tests/README.md b/crates/openhuman-embed/tests/README.mdindex 2b431cdd3f..87c6da7bb2 100644--- a/crates/openhuman-embed/tests/README.md+++ b/crates/openhuman-embed/tests/README.md@@ -39,6 +39,8 @@ recorded on the wrong server.| [`repository_tools.rs`](repository_tools.rs), [`repository_host_only.rs`](repository_host_only.rs) | Host-backed repository queries validate before dispatch, require redaction, fence and bound output, and remain isolated from shell/write/network under HostOnly, read-only, untrusted-input turns. See [repository contract](../src/repository/README.md). || [`completion_routing.rs`](completion_routing.rs) | Ordered endpoint fallback, bounded 2x/4x truncation retries, final unpinned gateway routing, images and accounting across all attempts. || [`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. || [`public_api.rs`](public_api.rs) | Compile-time check that the host-facing types and signatures stay exported. |## Runningdiff --git a/crates/openhuman-embed/tests/completion_cancellation.rs b/crates/openhuman-embed/tests/completion_cancellation.rsnew file mode 100644index 0000000000..d5aae32e30--- /dev/null+++ b/crates/openhuman-embed/tests/completion_cancellation.rs@@ -0,0 +1,79 @@+//! Stateless completion cancellation drops the provider future and acknowledges it.+mod common;+use openhuman_embed::cancellation::Cancellation;+use openhuman_embed::complete::{ChatMessage, Completer, CompletionRequest};+use openhuman_embed::{CoreError, Route};+use std::time::Duration;+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++fn request() -> CompletionRequest {+ CompletionRequest::new("fixture", vec![ChatMessage::user("Review.")])+}+async fn provider() -> MockServer {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/chat/completions"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(common::chat_completion("ok"))+ .set_delay(Duration::from_secs(5)),+ )+ .mount(&server)+ .await;+ server+}+#[tokio::test]+async fn cancellation_is_acknowledged_after_the_attached_call_stops() {+ let server = provider().await;+ let cancel = Cancellation::default();+ let completer = Completer::new(Route::openai_compatible(+ format!("{}/v1", server.uri()),+ "fixture",+ ))+ .cancellation(cancel.clone());+ let call = tokio::spawn(async move { completer.complete(request()).await });+ tokio::time::timeout(Duration::from_secs(2), async {+ while server.received_requests().await.unwrap().is_empty() {+ tokio::task::yield_now().await;+ }+ })+ .await+ .unwrap();+ tokio::time::timeout(Duration::from_secs(1), cancel.cancel())+ .await+ .unwrap();+ assert!(matches!(+ call.await.unwrap(),+ Err(CoreError::Cancelled { .. })+ ));+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}+#[tokio::test]+async fn a_pre_cancelled_call_makes_no_provider_request() {+ let server = provider().await;+ let cancel = Cancellation::default();+ cancel.cancel().await;+ let result = Completer::new(Route::openai_compatible(+ format!("{}/v1", server.uri()),+ "fixture",+ ))+ .cancellation(cancel)+ .complete(request())+ .await;+ assert!(matches!(result, Err(CoreError::Cancelled { .. })));+ assert!(server.received_requests().await.unwrap().is_empty());+}+#[tokio::test]+async fn deadline_refusal_is_typed_and_stops_the_provider_future() {+ let server = provider().await;+ let result = Completer::new(Route::openai_compatible(+ format!("{}/v1", server.uri()),+ "fixture",+ ))+ .timeout(Duration::from_millis(20))+ .complete(request())+ .await;+ assert!(matches!(result, Err(CoreError::DeadlineExceeded { .. })));+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex a1f342cc96..f3a5c2ff69 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -661,6 +661,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused || 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` || 16.1.14 | Host-backed read-only repository toolset | RI | `crates/openhuman-embed/tests/repository_tools.rs`, `crates/openhuman-embed/tests/repository_host_only.rs` | ✅ | Validated tree/range/search/symbol/git queries delegate only to the host; mandatory redaction, fenced bounded output, sanitized failures, and real HostOnly + readonly + untrusted-input refusal of shell/write/network. |+| 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON. || 16.1.16 | Explicit routing ladders and required exploration | RI | `crates/openhuman-embed/tests/completion_routing.rs`, `crates/openhuman-embed/tests/tool_required_routing.rs`, `crates/openhuman-embed/tests/structured_turns.rs` | ✅ | Ordered fallbacks, bounded truncation retries, unpinned terminal provider selection, image/options preservation, accumulated reported costs, actual answering model and refusal of schema-valid output before successful tool execution |## Summary