The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(embed): validate structured answers with bounded repair
Steven Enamakel4cf198a9b638
diff --git a/Cargo.lock b/Cargo.lockindex aa91c7be64..0ebf8a6377 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -81,6 +81,7 @@ dependencies = ["cfg-if","getrandom 0.3.4","once_cell",+ "serde","version_check","zerocopy",]@@ -173,7 +174,7 @@ version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -184,7 +185,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"dependencies = ["anstyle","once_cell_polyfill",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -629,6 +630,12 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "borrow-or-share"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc0b364ead1874514c8c2855ab558056ebfeb775653e7ae45ff72f28f8f3166c"+[[package]]name = "bs58"version = "0.5.1"@@ -741,6 +748,12 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"+[[package]]+name = "bytecount"+version = "0.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e"+[[package]]name = "bytemuck"version = "1.25.2"@@ -788,7 +801,7 @@ dependencies = ["cap-primitives","cap-std","io-lifetimes 3.0.1",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -805,7 +818,7 @@ dependencies = ["maybe-owned","rustix","rustix-linux-procfs",- "windows-sys 0.60.2",+ "windows-sys 0.61.2","winx",]@@ -1849,7 +1862,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -1982,6 +1995,9 @@ name = "email_address"version = "0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e079f19b08ca6239f47f8ba8509c11cf3ea30095831f7fed61441475edd8c449"+dependencies = [+ "serde",+][[package]]name = "encoding_rs"@@ -2099,7 +2115,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -2174,6 +2190,17 @@ dependencies = ["regex",]+[[package]]+name = "fancy-regex"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d301f5bf187b3c295fce6468d3875037a0bccc5f6b151c63cac2f85babf21912"+dependencies = [+ "bit-set 0.8.0",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "fast-float2"version = "0.2.4"@@ -2270,6 +2297,17 @@ dependencies = ["zlib-rs",]+[[package]]+name = "fluent-uri"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc74ac4d8359ae70623506d512209619e5cf8f347124910440dbc221714b328e"+dependencies = [+ "borrow-or-share",+ "ref-cast",+ "serde",+]+[[package]]name = "fnv"version = "1.0.7"@@ -2339,6 +2377,16 @@ dependencies = ["percent-encoding",]+[[package]]+name = "fraction"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e246562084dde8ebbcc943b261c406ce4f68e5032ec28029a251a47d6a295500"+dependencies = [+ "num",+ "num-bigint",+]+[[package]]name = "fs-set-times"version = "0.20.3"@@ -2930,7 +2978,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.58.0",+ "windows-core 0.62.2",][[package]]@@ -3349,6 +3397,59 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "jsonschema"+version = "0.58.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f622c574a29fb3034a0a90645afee194dfedc75fc124228801b6e77041075bd1"+dependencies = [+ "ahash",+ "bytecount",+ "data-encoding",+ "email_address",+ "fancy-regex 0.19.2",+ "fraction",+ "getrandom 0.3.4",+ "itoa",+ "jsonschema-regex",+ "jsonschema-value",+ "num-cmp",+ "num-traits",+ "percent-encoding",+ "referencing",+ "regex",+ "serde",+ "serde_json",+ "strum",+ "unicode-general-category",+ "uuid-simd",+]++[[package]]+name = "jsonschema-regex"+version = "0.58.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a968fffd387b2ab005bf00c1851f5d26e90df05b6f7ad609ed0d620033cca5e7"+dependencies = [+ "regex-syntax",+]++[[package]]+name = "jsonschema-value"+version = "0.58.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39b7670345e5ce87371339d13705dbb9276b7e3e934bbe1efa2c6734a1f65a96"+dependencies = [+ "ahash",+ "bytecount",+ "fraction",+ "getrandom 0.3.4",+ "num-cmp",+ "num-traits",+ "serde_json",+ "zmij",+]+[[package]]name = "k256"version = "0.13.4"@@ -3755,6 +3856,12 @@ dependencies = ["autocfg",]+[[package]]+name = "micromap"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a86d3146ed3995b5913c414f6664344b9617457320782e64f0bb44afd49d74"+[[package]]name = "mime"version = "0.3.17"@@ -4012,7 +4119,21 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",+]++[[package]]+name = "num"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"+dependencies = [+ "num-bigint",+ "num-complex",+ "num-integer",+ "num-iter",+ "num-rational",+ "num-traits",][[package]]@@ -4025,6 +4146,21 @@ dependencies = ["num-traits",]+[[package]]+name = "num-cmp"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63335b2e2c34fae2fb0aa2cecfd9f0832a1e24b3b32ecec612c3426d46dc8aaa"++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+]+[[package]]name = "num-conv"version = "0.2.2"@@ -4051,6 +4187,27 @@ dependencies = ["num-traits",]+[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+]+[[package]]name = "num-traits"version = "0.2.19"@@ -4668,6 +4825,7 @@ dependencies = ["chrono","dirs 6.0.0","env_logger",+ "jsonschema","log","openhuman","reqwest",@@ -4848,6 +5006,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "outref"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a80800c0488c3a21695ea981a54918fbb37abf04f4d0720c453632255e2ff0e"+[[package]]name = "palette"version = "0.7.7"@@ -5390,7 +5554,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -5683,6 +5847,23 @@ dependencies = ["syn 3.0.6",]+[[package]]+name = "referencing"+version = "0.58.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "558f3855529c0a7e78a48e409fa653456e55f1b167eab4109c16a255b7727e3f"+dependencies = [+ "ahash",+ "fluent-uri",+ "getrandom 0.3.4",+ "hashbrown 0.17.1",+ "itoa",+ "micromap",+ "parking_lot",+ "percent-encoding",+ "serde_json",+]+[[package]]name = "regex"version = "1.13.1"@@ -5879,7 +6060,7 @@ dependencies = ["errno","libc","linux-raw-sys",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -5947,7 +6128,7 @@ dependencies = ["security-framework 3.7.0","security-framework-sys","webpki-root-certs",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6527,7 +6708,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6838,7 +7019,7 @@ dependencies = ["getrandom 0.4.3","once_cell","rustix",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6851,7 +7032,7 @@ dependencies = ["parking_lot","rustix","signal-hook",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6884,7 +7065,7 @@ dependencies = ["anyhow","base64 0.22.1","bitflags 2.13.2",- "fancy-regex",+ "fancy-regex 0.11.0","filedescriptor","finl_unicode","fixedbitset",@@ -8569,6 +8750,12 @@ version = "0.3.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"+[[package]]+name = "unicode-general-category"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f"+[[package]]name = "unicode-ident"version = "1.0.26"@@ -8751,6 +8938,16 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "uuid-simd"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b082222b4f6619906941c17eb2297fff4c2fb96cb60164170522942a200bd8"+dependencies = [+ "outref",+ "vsimd",+]+[[package]]name = "valuable"version = "0.1.1"@@ -8769,6 +8966,12 @@ version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]+name = "vsimd"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64"+[[package]]name = "vtparse"version = "0.6.2"@@ -9276,7 +9479,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape.rsindex 9c866b58e4..c21f5125fd 100644--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs+++ b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs@@ -24,17 +24,44 @@ 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(Debug, Clone, Default, PartialEq)]+#[derive(Clone, Default)]pub struct ResponseShape {+ /// 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>,}+/// 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, Eq)]pub struct FinalResponse {+ /// 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.@@ -94,6 +121,20 @@ pub(super) fn install(harness: &mut AgentHarness<(), OpenHumanRunContext>, root: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;+ 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)));}}@@ -129,8 +170,60 @@ impl Middleware<(), OpenHumanRunContext> for ResponseShapeMiddleware {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;+ }+ }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 reasondiff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.tomlindex d93d0e3b99..08f6674c0d 100644--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@ -47,6 +47,7 @@ anyhow = "1"# `JobSchedule::At` converts to and from the core's `chrono` instants.chrono = "0.4"log = "0.4"+jsonschema = { version = "0.58", default-features = false }serde = { version = "1", features = ["derive"] }serde_json = "1"# `process::sentry` (crash-reporting): the client options and before_senddiff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rsindex 38450dbb24..10ab03663e 100644--- a/crates/openhuman-embed/src/complete.rs+++ b/crates/openhuman-embed/src/complete.rs@@ -173,6 +173,9 @@ impl ResponseFormat {/// One stateless model call.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct CompletionRequest {+ /// Extra structured repair attempts, bounded to three; defaults to zero.+ #[serde(default)]+ pub structured_retries: u8,/// Model id on the route's endpoint. Required and sent verbatim.pub model: String,/// Conversation, in order.@@ -200,6 +203,7 @@ impl CompletionRequest {Self {model: model.into(),messages,+ structured_retries: 0,response_format: None,max_tokens: None,temperature: None,@@ -207,6 +211,12 @@ impl CompletionRequest {}}+ /// Allow at most three extra attempts to repair invalid structured output.+ pub fn structured_retries(mut self, attempts: u8) -> Self {+ self.structured_retries = attempts;+ self+ }+/// Set the output shape.pub fn response_format(mut self, format: ResponseFormat) -> Self {self.response_format = Some(format);@@ -348,7 +358,7 @@ impl CompletionResponse {/// Parse a JSON reply, tolerating one surrounding Markdown code fence — a/// common habit of models without native structured output.-fn parse_json_reply(text: &str) -> Option<Value> {+pub(crate) fn parse_json_reply(text: &str) -> Option<Value> {let trimmed = text.trim();if let Ok(value) = serde_json::from_str(trimmed) {return Some(value);@@ -452,7 +462,7 @@ impl Completer {request: CompletionRequest,) -> Result<CompletionResponse, CoreError> {let started = Instant::now();- let result = self.dispatch(request.clone()).await;+ let result = self.validated_dispatch(request.clone()).await;if let Some(observer) = &self.observer {observer.on_complete(&CompletionTrace {request: &request,@@ -463,6 +473,47 @@ impl Completer {result}+ async fn validated_dispatch(+ &self,+ mut request: CompletionRequest,+ ) -> Result<CompletionResponse, CoreError> {+ use crate::structured::{+ accumulate, StructuredFailureReason, StructuredOutputFailure, Validator,+ };+ let initial_failure = |reason| CoreError::StructuredOutput {+ method: COMPLETE,+ failure: StructuredOutputFailure {+ attempts: 0,+ reason,+ finish_reason: None,+ answered_model: None,+ usage: None,+ },+ };+ if request.structured_retries > 3 {+ return Err(initial_failure(StructuredFailureReason::RetryLimit));+ }+ let validator =+ Validator::new(request.response_format.as_ref()).map_err(initial_failure)?;+ let mut usage = None;+ for attempt in 0..=request.structured_retries {+ let mut response = self.dispatch(request.clone()).await?;+ accumulate(&mut usage, response.usage.as_ref());+ 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 {+ method: COMPLETE, failure: StructuredOutputFailure { attempts: u16::from(attempt)+1,+ reason, finish_reason: response.finish_reason, answered_model: response.answered_model, usage,+ },+ }),+ Err(reason) => request.messages.push(ChatMessage::user(format!(+ "The answer failed structured validation ({reason:?}). Return a complete answer matching the requested schema."+ ))),+ }+ }+ unreachable!("bounded attempt loop always returns")+ }+async fn dispatch(&self, request: CompletionRequest) -> Result<CompletionResponse, CoreError> {let endpoint = self.checked_endpoint(&request)?;let format = request.response_format.clone();diff --git a/crates/openhuman-embed/src/complete_tests.rs b/crates/openhuman-embed/src/complete_tests.rsindex 4aa8fb9ab3..02765d40be 100644--- a/crates/openhuman-embed/src/complete_tests.rs+++ b/crates/openhuman-embed/src/complete_tests.rs@@ -104,10 +104,10 @@ async fn truncated_json_is_reported_not_parsed() {let server = server_replying(body("{\"prime\":", "length")).await;let request = CompletionRequest::new("m", vec![ChatMessage::user("x")]).response_format(ResponseFormat::JsonObject);- let response = completer(&server).complete(request).await.unwrap();- assert_eq!(response.finish_reason.as_deref(), Some("length"));- assert_eq!(response.structured, None);- assert_eq!(response.text, "{\"prime\":");+ let error = completer(&server).complete(request).await.unwrap_err();+ assert!(+ matches!(error, CoreError::StructuredOutput { failure, .. } if failure.reason == crate::structured::StructuredFailureReason::Truncated)+ );}#[tokio::test]@@ -203,9 +203,10 @@ async fn json_object_format_rejects_a_non_object_reply() {let server = server_replying(body("[1,2]", "stop")).await;let request = CompletionRequest::new("m", vec![ChatMessage::user("x")]).response_format(ResponseFormat::JsonObject);- let response = completer(&server).complete(request).await.unwrap();- assert_eq!(response.text, "[1,2]");- assert_eq!(response.structured, None);+ let error = completer(&server).complete(request).await.unwrap_err();+ assert!(+ matches!(error, CoreError::StructuredOutput { failure, .. } if failure.reason == crate::structured::StructuredFailureReason::SchemaMismatch)+ );}#[tokio::test]diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rsindex ad42eb1e55..13c7833789 100644--- a/crates/openhuman-embed/src/error.rs+++ b/crates/openhuman-embed/src/error.rs@@ -26,6 +26,15 @@ use openhuman_core::core::StructuredRpcError;/// Error returned by every typed facade call.#[derive(Debug, thiserror::Error)]pub enum CoreError {+ /// Requested JSON failed strict validation after bounded repair.+ #[error("{method}: {failure}")]+ StructuredOutput {+ /// Operation that refused the answer.+ method: &'static str,+ /// Safe accounting and classification metadata.+ failure: crate::structured::StructuredOutputFailure,+ },+/// The domain returned a structured error envelope.#[error("{method}: {message}")]Domain {@@ -160,7 +169,8 @@ impl CoreError {/// The RPC method this error came from.pub fn method(&self) -> &'static str {match self {- CoreError::Domain { method, .. }+ CoreError::StructuredOutput { method, .. }+ | CoreError::Domain { method, .. }| CoreError::Unavailable { method }| CoreError::Rpc { method, .. }| CoreError::Encode { method, .. }diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex 0ff7d09900..7c7058ddd5 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -285,3 +285,6 @@ impl std::fmt::Debug for Core {f.debug_struct("Core").finish_non_exhaustive()}}++/// Strict structured output failure metadata.+pub mod structured;diff --git a/crates/openhuman-embed/src/structured.rs b/crates/openhuman-embed/src/structured.rsnew file mode 100644index 0000000000..559dee9473--- /dev/null+++ b/crates/openhuman-embed/src/structured.rs@@ -0,0 +1,116 @@+//! Strict host-side JSON validation with no external schema retrieval.++use crate::complete::{CompletionUsage, ResponseFormat};+use serde::{Deserialize, Serialize};+use serde_json::Value;++/// Why a requested structured answer was refused.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub enum StructuredFailureReason {+ /// The host supplied an invalid or externally resolved schema.+ InvalidSchema,+ /// The reply was not complete JSON.+ InvalidJson,+ /// The reply failed the requested schema.+ SchemaMismatch,+ /// The provider exhausted its output ceiling.+ Truncated,+ /// The configured repair allowance exceeded the bounded maximum.+ RetryLimit,+}++/// Safe metadata about a refused answer; never contains the answer itself.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct StructuredOutputFailure {+ /// Physical completion attempts, including repairs.+ pub attempts: u16,+ /// Machine-readable failure classification.+ pub reason: StructuredFailureReason,+ /// Last provider finish reason.+ pub finish_reason: Option<String>,+ /// Last provider-reported answering model.+ pub answered_model: Option<String>,+ /// Usage accumulated across attempts when reported.+ pub usage: Option<CompletionUsage>,+}++impl std::fmt::Display for StructuredOutputFailure {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "structured output {:?} after {} attempts",+ self.reason, self.attempts+ )+ }+}++struct DenyExternal;+impl jsonschema::Retrieve for DenyExternal {+ fn retrieve(+ &self,+ _uri: &jsonschema::Uri<String>,+ ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {+ Err("external schema retrieval is disabled".into())+ }+}++pub(crate) struct Validator(Option<jsonschema::Validator>);+impl Validator {+ pub(crate) fn new(format: Option<&ResponseFormat>) -> Result<Self, StructuredFailureReason> {+ let schema = match format {+ None | Some(ResponseFormat::Text) => return Ok(Self(None)),+ Some(ResponseFormat::JsonObject) => serde_json::json!({"type":"object"}),+ Some(ResponseFormat::JsonSchema { schema, .. }) => schema.clone(),+ };+ jsonschema::options()+ .with_retriever(DenyExternal)+ .should_validate_formats(true)+ .build(&schema)+ .map(|validator| Self(Some(validator)))+ .map_err(|_| StructuredFailureReason::InvalidSchema)+ }++ pub(crate) fn validate(+ &self,+ text: &str,+ finish: Option<&str>,+ ) -> Result<Option<Value>, StructuredFailureReason> {+ let Some(validator) = &self.0 else {+ return Ok(None);+ };+ if matches!(finish, Some("length" | "max_tokens")) {+ return Err(StructuredFailureReason::Truncated);+ }+ let value =+ crate::complete::parse_json_reply(text).ok_or(StructuredFailureReason::InvalidJson)?;+ if !validator.is_valid(&value) {+ return Err(StructuredFailureReason::SchemaMismatch);+ }+ Ok(Some(value))+ }+}++pub(crate) fn accumulate(total: &mut Option<CompletionUsage>, usage: Option<&CompletionUsage>) {+ match (total.as_mut(), usage) {+ (None, Some(usage)) => *total = Some(usage.clone()),+ (Some(total), Some(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.cached_tokens);+ total.reasoning_tokens = total+ .reasoning_tokens+ .saturating_add(usage.reasoning_tokens);+ total.cost_usd = total.cost_usd.zip(usage.cost_usd).map(|(a, b)| a + b);+ }+ (Some(total), None) => total.cost_usd = None,+ (None, None) => (),+ }+}++impl openhuman_core::agent::tinyagents::response_shape::ResponseValidator for Validator {+ fn validate(&self, text: &str, finish_reason: Option<&str>) -> Result<(), String> {+ self.validate(text, finish_reason)+ .map(|_| ())+ .map_err(|reason| format!("{reason:?}"))+ }+}diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 0f453a9b69..ada465101d 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -256,6 +256,7 @@ pub struct Turn {seed: Option<Vec<(String, String)>>,meter: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>,response_format: Option<crate::complete::ResponseFormat>,+ structured_retries: u8,max_tokens: Option<u32>,untrusted_input: bool,}@@ -271,6 +272,7 @@ impl Turn {seed: None,meter: None,response_format: None,+ structured_retries: 0,max_tokens: None,untrusted_input: false,}@@ -375,11 +377,14 @@ impl Turn {////// Applied to each call of the tool loop, so a provider that honours/// structured outputs keeps calling tools and shapes its final answer.- /// With a JSON format the parsed answer comes back in- /// [`TurnOutcome::structured`]. Only a runtime-owned- /// [`Agent`](crate::Agent) can honour it; a caller-built runtime's- /// orchestrator refuses the turn.+ /// Allow up to three extra attempts to repair invalid structured output.#[must_use]+ pub fn structured_retries(mut self, attempts: u8) -> Self {+ self.structured_retries = attempts;+ self+ }++ /// Set the requested structured output shape.pub fn response_format(mut self, format: crate::complete::ResponseFormat) -> Self {self.response_format = Some(format);self@@ -527,6 +532,19 @@ impl Turn {.response_format.as_ref().is_some_and(crate::complete::ResponseFormat::wants_json);+ let validator =+ crate::structured::Validator::new(self.response_format.as_ref()).map_err(|reason| {+ CoreError::StructuredOutput {+ method: AGENT_CHAT,+ failure: crate::structured::StructuredOutputFailure {+ attempts: 0,+ reason,+ finish_reason: None,+ answered_model: None,+ usage: None,+ },+ }+ })?;let options = AgentTurnOptions {shape: openhuman_core::agent::tinyagents::response_shape::ResponseShapeScope::new(openhuman_core::agent::tinyagents::response_shape::ResponseShape {@@ -535,6 +553,8 @@ impl Turn {.take().map(crate::complete::ResponseFormat::into_wire),max_output_tokens: self.max_tokens,+ validator: wants_json.then(|| std::sync::Arc::new(validator) as std::sync::Arc<dyn openhuman_core::agent::tinyagents::response_shape::ResponseValidator>),+ structured_retries: self.structured_retries,},),untrusted_input: self.untrusted_input,@@ -565,6 +585,7 @@ impl Turn {// variant classification are logged; the error itself propagates// to the caller untouched.let tag = match err {+ crate::error::CoreError::StructuredOutput { .. } => "structured_output",crate::error::CoreError::Domain { .. } => "domain",crate::error::CoreError::Unavailable { .. } => "unavailable",crate::error::CoreError::Rpc { .. } => "rpc",@@ -619,6 +640,18 @@ impl Turn {/// Refuse the per-turn options the target cannot honour, before anything/// is dispatched.fn validate_turn_options(&self) -> Result<(), CoreError> {+ if self.structured_retries > 3 {+ return Err(CoreError::StructuredOutput {+ method: AGENT_CHAT,+ failure: crate::structured::StructuredOutputFailure {+ attempts: 0,+ reason: crate::structured::StructuredFailureReason::RetryLimit,+ finish_reason: None,+ answered_model: None,+ usage: None,+ },+ });+ }let refuse = |message: &str, kind: &str| {Err(CoreError::Domain {method: AGENT_CHAT,@@ -631,7 +664,10 @@ impl Turn {let host_only = match &self.target {TurnTarget::Agent(agent) => agent.host_only,TurnTarget::Runtime(_) => {- if self.response_format.is_some() || self.max_tokens.is_some() {+ if self.response_format.is_some()+ || self.max_tokens.is_some()+ || self.structured_retries != 0+ {return refuse("response_format and max_tokens need a runtime-owned Agent","turn_shape_unsupported",@@ -767,6 +803,36 @@ async fn dispatch({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("Truncated") => Reason::Truncated,+ Some("SchemaMismatch") => Reason::SchemaMismatch,+ _ => Reason::InvalidJson,+ };+ return Err(CoreError::StructuredOutput {+ method: AGENT_CHAT,+ failure: StructuredOutputFailure {+ attempts: report.structured_attempts,+ 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,+ }),+ },+ });+ }outcome.map(|outcome| (outcome.value, Some(report))).map_err(|raw| CoreError::from_rpc_string(AGENT_CHAT, raw))diff --git a/crates/openhuman-embed/tests/structured_turns.rs b/crates/openhuman-embed/tests/structured_turns.rsindex 6f97db10c8..e7e6d9ebf6 100644--- a/crates/openhuman-embed/tests/structured_turns.rs+++ b/crates/openhuman-embed/tests/structured_turns.rs@@ -258,3 +258,94 @@ fn untrusted_input_passes_the_prompt_guard_only_on_a_host_only_agent() {.expect("test task");});}++#[test]+fn terminal_schema_validation_retries_without_accepting_a_wrong_type() {+ 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 provider = provider(vec![+ completion(+ json!({"role":"assistant","content":"{\"verdict\":123}"}),+ "stop",+ "fixture",+ 0,+ ),+ completion(+ json!({"role":"assistant","content":"{\"verdict\":\"reject\"}"}),+ "stop",+ "fixture",+ 0,+ ),+ ])+ .await;+ let runtime = build_runtime(&backend).await;+ let agent = runtime+ .agent(reviewer(+ "strict-repair",+ &provider,+ Arc::new(AtomicUsize::new(0)),+ ))+ .unwrap();+ let outcome = agent+ .turn("Review this diff.")+ .response_format(review_schema())+ .structured_retries(1)+ .send()+ .await+ .unwrap();+ assert_eq!(outcome.structured, Some(json!({"verdict":"reject"})));+ assert_eq!(chat_requests(&provider).await.len(), 2);+ })+ .await+ .unwrap();+ });+}++#[test]+fn a_complete_json_value_with_a_length_finish_is_not_a_valid_review() {+ 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 provider = provider(vec![completion(+ json!({"role":"assistant","content":"{\"verdict\":\"approve\"}"}),+ "length",+ "fixture",+ 0,+ )])+ .await;+ let runtime = build_runtime(&backend).await;+ let agent = runtime+ .agent(reviewer(+ "strict-length",+ &provider,+ Arc::new(AtomicUsize::new(0)),+ ))+ .unwrap();+ let error = agent+ .turn("Review this diff.")+ .response_format(review_schema())+ .send()+ .await+ .unwrap_err();+ let CoreError::StructuredOutput { failure, .. } = error else {+ panic!("typed failure");+ };+ assert_eq!(+ failure.reason,+ openhuman_embed::structured::StructuredFailureReason::Truncated+ );+ assert_eq!(failure.attempts, 1);+ assert!(failure.usage.is_some());+ assert_eq!(chat_requests(&provider).await.len(), 1);+ })+ .await+ .unwrap();+ });+}diff --git a/crates/openhuman-embed/tests/structured_validation.rs b/crates/openhuman-embed/tests/structured_validation.rsnew file mode 100644index 0000000000..da6b5873eb--- /dev/null+++ b/crates/openhuman-embed/tests/structured_validation.rs@@ -0,0 +1,87 @@+//! Strict local structured-output validation at the Embed boundary.++mod common;++use openhuman_embed::complete::{ChatMessage, Completer, CompletionRequest, ResponseFormat};+use openhuman_embed::Route;+use serde_json::{json, Value};+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++async fn provider(content: &str) -> 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(content)))+ .mount(&server)+ .await;+ server+}++fn request(schema: Value) -> CompletionRequest {+ CompletionRequest::new("fixture", vec![ChatMessage::user("Review untrusted code.")])+ .response_format(ResponseFormat::JsonSchema {+ name: "review".into(),+ schema,+ })+ .max_tokens(128)+}++fn completer(server: &MockServer) -> Completer {+ Completer::new(Route::openai_compatible(+ format!("{}/v1", server.uri()),+ "fixture",+ ))+}++#[tokio::test]+async fn a_parseable_reply_with_the_wrong_type_is_an_error() {+ let server = provider(r#"{"summary":123}"#).await;+ let error = completer(&server).complete(request(json!({"type":"object","properties":{"summary":{"type":"string"}},"required":["summary"]}))).await.expect_err("schema-invalid JSON must not become an empty successful review");+ assert!(!error.to_string().contains("123"));+ assert_eq!(server.received_requests().await.unwrap().len(), 1);+}++#[tokio::test]+async fn schema_combinators_and_numeric_constraints_are_enforced() {+ let server = provider(r#"{"confidence":1.5}"#).await;+ completer(&server).complete(request(json!({"allOf":[{"type":"object","required":["confidence"]},{"properties":{"confidence":{"type":"number","minimum":0,"maximum":1}}}]})))+ .await.expect_err("a schema subset must not silently ignore bounds or combinators");+}++#[tokio::test]+async fn an_invalid_schema_is_rejected_before_inference() {+ let server = provider("{}").await;+ completer(&server)+ .complete(request(json!({"type":"not-a-json-type"})))+ .await+ .expect_err("invalid schema");+ assert!(server.received_requests().await.unwrap().is_empty());+}++#[tokio::test]+async fn invalid_answers_exhaust_only_the_explicit_repair_allowance() {+ let server = provider(r#"{"summary":123}"#).await;+ let error = completer(&server)+ .complete(+ request(json!({"properties":{"summary":{"type":"string"}}})).structured_retries(2),+ )+ .await+ .unwrap_err();+ let openhuman_embed::CoreError::StructuredOutput { failure, .. } = error else {+ panic!("typed validation error");+ };+ assert_eq!(failure.attempts, 3);+ assert_eq!(failure.usage.unwrap().input_tokens, 3);+ assert_eq!(server.received_requests().await.unwrap().len(), 3);+}++#[tokio::test]+async fn external_schema_retrieval_is_refused_before_inference() {+ let server = provider("{}").await;+ completer(&server)+ .complete(request(json!({"$ref":"https://example.invalid/schema"})))+ .await+ .unwrap_err();+ assert!(server.received_requests().await.unwrap().is_empty());+}