Skip to content

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

feat(embed): add explicit routing ladders and required exploration

Steven Enamakelb61c208bd709
diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
index c21f5125fd..c42bb4fe86 100644
--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
@@ -12,6 +12,7 @@
//! 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;
@@ -34,6 +35,10 @@ pub struct ResponseShape {
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,
}
/// Validates terminal provider text without retrieving external resources.
@@ -75,6 +80,7 @@ pub struct FinalResponse {
pub struct ResponseShapeScope {
shape: ResponseShape,
report: Mutex<FinalResponse>,
+ tool_succeeded: AtomicBool,
}
impl ResponseShapeScope {
@@ -84,6 +90,7 @@ impl ResponseShapeScope {
Arc::new(Self {
shape,
report: Mutex::default(),
+ tool_succeeded: AtomicBool::new(false),
})
}
@@ -154,9 +161,24 @@ impl Middleware<(), OpenHumanRunContext> for ResponseShapeMiddleware {
request: &mut ModelRequest,
) -> TaResult<()> {
let shape = &self.0.shape;
- if let Some(format) = &shape.response_format {
+ 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);
}
@@ -184,6 +206,31 @@ impl Middleware<(), OpenHumanRunContext> for ResponseShapeMiddleware {
report.validation_error = error;
}
}
+ if self.0.shape.require_tool_call
+ && !self.0.tool_succeeded.load(Ordering::Acquire)
+ && response.tool_calls().is_empty()
+ {
+ // 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(
@@ -235,11 +282,20 @@ fn record(scope: &ResponseShapeScope, response: &ModelResponse) {
.unwrap_or_else(std::sync::PoisonError::into_inner);
report.finish_reason = response.finish_reason.clone();
report.answered_model = response
- .resolved_route
+ .raw
.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());
+ .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 {
if let Some(usage) = &response.usage {
report.reasoning_tokens += usage.reasoning_tokens;
diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.md
index c342b18199..aa99740da4 100644
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@ -747,3 +747,5 @@ Attachments are shared by clones, always directly advertised, and update only
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).
diff --git a/crates/openhuman-embed/ROUTING.md b/crates/openhuman-embed/ROUTING.md
new file mode 100644
index 0000000000..96f1292376
--- /dev/null
+++ b/crates/openhuman-embed/ROUTING.md
@@ -0,0 +1,66 @@
+# Completion routing
+
+`Completer::complete` remains a single explicit endpoint/model choice. Hosts
+that want fallback use `routing::CompletionLadder`:
+
+```rust,no_run
+use openhuman_embed::{ChatMessage, Completer, CompletionRequest, Route};
+use openhuman_embed::routing::{CompletionLadder, CompletionRung, TruncationRetry};
+
+# async fn run(key: &str) -> Result<(), Box<dyn std::error::Error>> {
+let completer = Completer::new(Route::openrouter(key));
+let ladder = CompletionLadder::new(CompletionRung::new(completer.clone(), "openai/gpt-4.1-mini"))
+ .fallback(CompletionRung::new(completer.clone(), "moonshotai/kimi-k2.5"))
+ .fallback(CompletionRung::new(completer, "minimax/minimax-m3").unpinned())
+ .truncation_retry(TruncationRetry::new(2, 4096));
+let outcome = ladder.complete(
+ CompletionRequest::new("overridden-by-rung", vec![ChatMessage::user("Review the attached image.")
+ .with_image("https://example.org/review.png")])
+ .max_tokens(1024)
+ .provider_options(serde_json::json!({"provider": {"only": ["preferred"]}, "usage": {"include": true}})),
+).await?;
+assert_eq!(outcome.attempts.last().unwrap().answered_model, outcome.response.answered_model);
+# Ok(())
+# }
+```
+
+Each rung starts with the original conversation and cap. A `length` finish
+reason retries the same rung at doubled caps, bounded by both the retry count
+and absolute ceiling; 1024 tokens with the example policy tries 1024, 2048,
+4096. A missing cap never creates an implicit token budget. At the ceiling,
+routing advances. RPC provider/transport failures also advance; local route
+or security errors stop immediately. Error strings are never classified as
+HTTP statuses. A route's own provider compatibility behavior remains owned
+by TinyInference.
+
+An `unpinned()` rung must be last. It removes the gateway's `provider` object,
+while keeping model, reasoning, usage options and images. This lets the final
+gateway route choose its serving provider without changing the requested
+model. Adding a rung after an unpinned rung fails before any dispatch.
+
+`response.usage` describes the winning call. `attempts` records every call,
+including truncated responses. `total_usage` sums reported tokens and costs;
+its cost is unknown (`None`) when any attempt's cost was not reported. The
+ladder error retains this accounting and the last typed error. Completer
+observers run for each call, so hosts can meter failures independently.
+
+`Route::{openrouter, moonshot, minimax}` and matching `Provider` constructors
+use the international API roots. Custom deployments, regional endpoints and
+loopback fixtures use `openai_compatible`.
+
+# Agent exploration
+
+`Turn::provider_options` applies gateway routing/reasoning options to every
+call in a runtime-owned agent turn. `Turn::require_tool_call(true)` requires a
+successful tool execution before accepting a terminal answer. Until then,
+the host sends `tool_choice: "required"` and withholds the final response
+schema so the model can choose a tool. A gateway that ignores the hint and
+returns terminal JSON is refused. A rejected or failed tool does not satisfy
+the requirement. After successful execution the final schema applies again.
+The requirement is per turn, so prior session reads do not satisfy it.
+
+This is an explicit host contract: a prompt saying “read first” alone cannot
+guarantee exploration. The fixtures prove native tool metadata is advertised
+for the tested OpenRouter model IDs and that premature replies fail; they do
+not claim live provider behavioral parity or independently prove a remote
+model's implementation.
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index a19f7f369d..a9af3d51b4 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -117,6 +117,8 @@ pub mod process;
#[cfg(feature = "channels")]
pub mod profiles;
pub mod repository;
+/// Explicit ordered fallback and truncation policies.
+pub mod routing;
mod runtime;
mod turn;
diff --git a/crates/openhuman-embed/src/routing.rs b/crates/openhuman-embed/src/routing.rs
new file mode 100644
index 0000000000..b26b87d4b0
--- /dev/null
+++ b/crates/openhuman-embed/src/routing.rs
@@ -0,0 +1,278 @@
+//! Explicit host-owned completion ladders: ordered endpoints, bounded output
+//! growth and an optional final attempt without gateway provider pins.
+//!
+//! A ladder composes public completers; it does not change the provider's own
+//! retry policy or the single-call contract of `Completer::complete`.
+use crate::{
+ Completer, CompletionRequest, CompletionResponse, CompletionUsage, CoreError, Provider, Route,
+};
+
+impl Route {
+ /// OpenRouter's OpenAI-compatible gateway.
+ pub fn openrouter(api_key: impl Into<String>) -> Self {
+ Self::openai_compatible("https://openrouter.ai/api/v1", api_key)
+ }
+ /// Moonshot's international OpenAI-compatible endpoint.
+ pub fn moonshot(api_key: impl Into<String>) -> Self {
+ Self::openai_compatible("https://api.moonshot.ai/v1", api_key)
+ }
+ /// MiniMax's international OpenAI-compatible endpoint.
+ pub fn minimax(api_key: impl Into<String>) -> Self {
+ Self::openai_compatible("https://api.minimax.io/v1", api_key)
+ }
+}
+impl Provider {
+ /// OpenRouter's gateway; pin a model with `model`.
+ pub fn openrouter(api_key: impl Into<String>) -> Self {
+ Self::openai_compatible("https://openrouter.ai/api/v1", api_key)
+ }
+ /// Moonshot's international endpoint; pin a model with `model`.
+ pub fn moonshot(api_key: impl Into<String>) -> Self {
+ Self::openai_compatible("https://api.moonshot.ai/v1", api_key)
+ }
+ /// MiniMax's international endpoint; pin a model with `model`.
+ pub fn minimax(api_key: impl Into<String>) -> Self {
+ Self::openai_compatible("https://api.minimax.io/v1", api_key)
+ }
+}
+
+/// One endpoint/model choice in an ordered ladder.
+#[derive(Debug, Clone)]
+pub struct CompletionRung {
+ completer: Completer,
+ model: String,
+ unpinned: bool,
+}
+impl CompletionRung {
+ /// Use this completer's endpoint, headers, timeout and observer with `model`.
+ pub fn new(completer: Completer, model: impl Into<String>) -> Self {
+ Self {
+ completer,
+ model: model.into(),
+ unpinned: false,
+ }
+ }
+ /// Remove only the gateway `provider` routing object on this rung. Model,
+ /// reasoning, usage requests, images and every other option are preserved.
+ /// A ladder only accepts an unpinned rung at its end.
+ pub fn unpinned(mut self) -> Self {
+ self.unpinned = true;
+ self
+ }
+}
+
+/// Truncation retry budget; each retry doubles the original output cap.
+#[derive(Debug, Clone, Copy)]
+pub struct TruncationRetry {
+ retries: u8,
+ ceiling: u32,
+}
+impl TruncationRetry {
+ /// At most `retries` additional calls per rung, never exceeding `ceiling`.
+ /// No retry occurs without an explicit request cap, or when doubling
+ /// cannot increase it. `new(2, 4096)` with 1024 tokens tries 1024/2048/4096.
+ pub fn new(retries: u8, ceiling: u32) -> Self {
+ Self { retries, ceiling }
+ }
+}
+
+/// Metadata for one dispatched completion; never includes content or credentials.
+#[derive(Debug, Clone)]
+pub struct CompletionAttempt {
+ /// The rung's requested model.
+ pub requested_model: String,
+ /// The provider's reported answering model.
+ pub answered_model: Option<String>,
+ /// Output token cap used for this attempt.
+ pub max_tokens: Option<u32>,
+ /// Provider finish reason when a response arrived.
+ pub finish_reason: Option<String>,
+ /// Provider-reported usage for this attempt.
+ pub usage: Option<CompletionUsage>,
+ /// Whether the completion returned an error.
+ pub failed: bool,
+}
+
+/// A successful ladder, with accounting for all earlier attempts.
+#[derive(Debug)]
+pub struct LadderResponse {
+ /// The successful rung's response, preserving its original usage and model.
+ pub response: CompletionResponse,
+ /// Attempts in dispatch order, including discarded truncated responses.
+ pub attempts: Vec<CompletionAttempt>,
+ /// Sum of reported tokens. Cost is `None` if any attempt's cost is unknown.
+ pub total_usage: Option<CompletionUsage>,
+}
+
+/// An exhausted or refused ladder; the last error retains its original type.
+#[derive(Debug)]
+pub struct LadderError {
+ /// The error that stopped routing.
+ pub last_error: CoreError,
+ /// Attempts in dispatch order.
+ pub attempts: Vec<CompletionAttempt>,
+ /// Sum of available accounting, with unknown cost preserved as `None`.
+ pub total_usage: Option<CompletionUsage>,
+}
+impl std::fmt::Display for LadderError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "completion ladder stopped after {} attempts: {}",
+ self.attempts.len(),
+ self.last_error
+ )
+ }
+}
+impl std::error::Error for LadderError {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ Some(&self.last_error)
+ }
+}
+
+/// An explicit ordered sequence of completers. RPC dispatch failures advance
+/// to the next rung; local route/security failures stop immediately. No error
+/// text is parsed to infer an HTTP status. Each rung runs its own completer
+/// observer, so a host can trace unsuccessful attempts as well as the winner.
+#[derive(Debug, Clone)]
+pub struct CompletionLadder {
+ rungs: Vec<CompletionRung>,
+ truncation: Option<TruncationRetry>,
+}
+impl CompletionLadder {
+ /// A ladder always has at least one rung.
+ pub fn new(first: CompletionRung) -> Self {
+ Self {
+ rungs: vec![first],
+ truncation: None,
+ }
+ }
+ /// Append a fallback endpoint/model, attempted after earlier choices fail.
+ pub fn fallback(mut self, rung: CompletionRung) -> Self {
+ self.rungs.push(rung);
+ self
+ }
+ /// Enable bounded retries on a provider `length` finish reason.
+ pub fn truncation_retry(mut self, retry: TruncationRetry) -> Self {
+ self.truncation = Some(retry);
+ self
+ }
+ /// Run the ladder. Every rung starts from the original messages and token
+ /// cap; truncated output never becomes trusted conversation history.
+ pub async fn complete(
+ &self,
+ request: CompletionRequest,
+ ) -> Result<LadderResponse, LadderError> {
+ let mut attempts = Vec::new();
+ if self
+ .rungs
+ .iter()
+ .take(self.rungs.len() - 1)
+ .any(|rung| rung.unpinned)
+ {
+ return Err(ladder_error(
+ CoreError::InvalidRoute {
+ method: crate::complete::COMPLETE,
+ },
+ attempts,
+ ));
+ }
+ let mut last_error = CoreError::InvalidRoute {
+ method: crate::complete::COMPLETE,
+ };
+ for rung in &self.rungs {
+ let mut current = request.clone();
+ current.model = rung.model.clone();
+ if rung.unpinned {
+ if let Some(options) = current.provider_options.as_object_mut() {
+ options.remove("provider");
+ }
+ }
+ let mut retries = 0;
+ loop {
+ let response = rung.completer.complete(current.clone()).await;
+ let attempt = match &response {
+ Ok(response) => CompletionAttempt {
+ requested_model: current.model.clone(),
+ max_tokens: current.max_tokens,
+ answered_model: response.answered_model.clone(),
+ finish_reason: response.finish_reason.clone(),
+ usage: response.usage.clone(),
+ failed: false,
+ },
+ Err(_) => CompletionAttempt {
+ requested_model: current.model.clone(),
+ max_tokens: current.max_tokens,
+ answered_model: None,
+ finish_reason: None,
+ usage: None,
+ failed: true,
+ },
+ };
+ let truncated = attempt.finish_reason.as_deref() == Some("length");
+ attempts.push(attempt);
+ match response {
+ Ok(response) if !truncated => {
+ return Ok(LadderResponse {
+ total_usage: total_usage(&attempts),
+ response,
+ attempts,
+ })
+ }
+ Ok(_) => {
+ last_error = CoreError::Rpc {
+ method: crate::complete::COMPLETE,
+ message: "completion truncated after bounded retries".into(),
+ }
+ }
+ Err(error) => {
+ if !matches!(error, CoreError::Rpc { .. }) {
+ return Err(ladder_error(error, attempts));
+ }
+ last_error = error;
+ }
+ }
+ if truncated {
+ if let (Some(policy), Some(cap)) = (self.truncation, current.max_tokens) {
+ let next = cap.saturating_mul(2).min(policy.ceiling);
+ if retries < policy.retries && next > cap {
+ retries += 1;
+ current.max_tokens = Some(next);
+ continue;
+ }
+ }
+ }
+ break;
+ }
+ }
+ Err(ladder_error(last_error, attempts))
+ }
+}
+fn ladder_error(last_error: CoreError, attempts: Vec<CompletionAttempt>) -> LadderError {
+ LadderError {
+ total_usage: total_usage(&attempts),
+ last_error,
+ attempts,
+ }
+}
+fn total_usage(attempts: &[CompletionAttempt]) -> Option<CompletionUsage> {
+ let mut total = CompletionUsage::default();
+ let mut any = false;
+ let mut cost = Some(0.0);
+ for attempt in attempts {
+ if let Some(usage) = &attempt.usage {
+ any = true;
+ 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);
+ cost = cost.zip(usage.cost_usd).map(|(sum, charged)| sum + charged);
+ } else {
+ cost = None;
+ }
+ }
+ total.cost_usd = cost;
+ any.then_some(total)
+}
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index ada465101d..8a897e4c74 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -258,6 +258,8 @@ pub struct Turn {
response_format: Option<crate::complete::ResponseFormat>,
structured_retries: u8,
max_tokens: Option<u32>,
+ provider_options: serde_json::Value,
+ require_tool_call: bool,
untrusted_input: bool,
}
@@ -274,6 +276,8 @@ impl Turn {
response_format: None,
structured_retries: 0,
max_tokens: None,
+ provider_options: serde_json::Value::Null,
+ require_tool_call: false,
untrusted_input: false,
}
}
@@ -390,6 +394,22 @@ impl Turn {
self
}
+ /// Pass gateway routing/reasoning options to every model call in this turn.
+ #[must_use]
+ pub fn provider_options(mut self, options: serde_json::Value) -> Self {
+ self.provider_options = options;
+ self
+ }
+
+ /// Require a successful tool execution before accepting the final answer.
+ /// The first calls advertise required tools and omit the final schema;
+ /// gateways that ignore the tool hint are refused deterministically.
+ #[must_use]
+ pub fn require_tool_call(mut self, required: bool) -> Self {
+ self.require_tool_call = required;
+ self
+ }
+
/// Cap every model call of this turn at `n` output tokens, replacing the
/// agent turn's default cap. Runtime-owned agents only, as
/// [`response_format`](Self::response_format).
@@ -555,6 +575,8 @@ impl Turn {
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,
+ provider_options: self.provider_options.clone(),
+ require_tool_call: self.require_tool_call,
},
),
untrusted_input: self.untrusted_input,
@@ -667,6 +689,8 @@ impl Turn {
if self.response_format.is_some()
|| self.max_tokens.is_some()
|| self.structured_retries != 0
+ || !self.provider_options.is_null()
+ || self.require_tool_call
{
return refuse(
"response_format and max_tokens need a runtime-owned Agent",
diff --git a/crates/openhuman-embed/tests/README.md b/crates/openhuman-embed/tests/README.md
index c8dc8110a3..2b431cdd3f 100644
--- a/crates/openhuman-embed/tests/README.md
+++ b/crates/openhuman-embed/tests/README.md
@@ -37,6 +37,8 @@ recorded on the wrong server.
| [`memory_facade.rs`](memory_facade.rs) | `Runtime::memory` over TinyMemory's in-memory reference engine keeps two tenant roots apart. |
| [`saas_profiles.rs`](saas_profiles.rs) | A `ProfileRuntime` (SaaS mode, in-process): two users on thread `t1` see only their own messages and ride their own credential, a held `ProfileHandle` keeps its profile from release, a relayed Telegram message lands on the user's `channel:` thread with its `channel_outbound` reply on that user's events only, and the process refuses any other core afterwards. Inference is `common::echo_inference` behind `common::PointedTransport`. |
| [`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. |
| [`public_api.rs`](public_api.rs) | Compile-time check that the host-facing types and signatures stay exported. |
## Running
diff --git a/crates/openhuman-embed/tests/completion_routing.rs b/crates/openhuman-embed/tests/completion_routing.rs
new file mode 100644
index 0000000000..c8bc39f6c7
--- /dev/null
+++ b/crates/openhuman-embed/tests/completion_routing.rs
@@ -0,0 +1,169 @@
+//! Ordered routing, capped truncation retries and provider-reported accounting.
+use openhuman_embed::routing::{CompletionLadder, CompletionRung, TruncationRetry};
+use openhuman_embed::{ChatMessage, Completer, CompletionRequest, Route};
+use serde_json::{json, Value};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use wiremock::matchers::{method, path};
+use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
+
+struct Script(Vec<Value>, AtomicUsize);
+impl Respond for Script {
+ fn respond(&self, _: &Request) -> ResponseTemplate {
+ let index = self.1.fetch_add(1, Ordering::SeqCst);
+ ResponseTemplate::new(200).set_body_json(self.0[index.min(self.0.len() - 1)].clone())
+ }
+}
+fn answer(model: &str, finish: &str, cost: f64) -> Value {
+ json!({"model":model,"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":finish}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15,"cost":cost}})
+}
+async fn scripted(bodies: Vec<Value>) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(Script(bodies, AtomicUsize::new(0)))
+ .mount(&server)
+ .await;
+ server
+}
+fn rung(server: &MockServer, model: &str) -> CompletionRung {
+ CompletionRung::new(
+ Completer::new(Route::openai_compatible(
+ format!("{}/v1", server.uri()),
+ "fixture",
+ )),
+ model,
+ )
+}
+#[tokio::test]
+async fn truncation_doubles_the_cap_before_ordered_unpinned_fallback() {
+ let first = scripted(vec![answer("first-actual", "length", 0.01)]).await;
+ let last = scripted(vec![answer("last-actual", "stop", 0.02)]).await;
+ let outcome = CompletionLadder::new(rung(&first,"first"))
+ .fallback(rung(&last,"last").unpinned())
+ .truncation_retry(TruncationRetry::new(2,4096))
+ .complete(CompletionRequest::new("ignored",vec![ChatMessage::user("review").with_image("https://example.org/image.png")])
+ .max_tokens(1024).provider_options(json!({"provider":{"only":["pinned"]},"reasoning":{"effort":"low"},"usage":{"include":true}})))
+ .await.expect("fallback answers");
+ assert_eq!(
+ outcome.response.answered_model.as_deref(),
+ Some("last-actual")
+ );
+ assert_eq!(outcome.attempts.len(), 4);
+ assert_eq!(outcome.total_usage.as_ref().unwrap().input_tokens, 40);
+ assert!((outcome.total_usage.unwrap().cost_usd.unwrap() - 0.05).abs() < 1e-9);
+ let requests = first.received_requests().await.unwrap();
+ let caps: Vec<_> = requests
+ .iter()
+ .map(|r| {
+ serde_json::from_slice::<Value>(&r.body).unwrap()["max_tokens"]
+ .as_u64()
+ .unwrap()
+ })
+ .collect();
+ assert_eq!(caps, vec![1024, 2048, 4096]);
+ let requests = last.received_requests().await.unwrap();
+ let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ assert_eq!(body["model"], "last");
+ assert_eq!(body["max_tokens"], 1024);
+ assert!(body.get("provider").is_none());
+ assert_eq!(body["reasoning"]["effort"], "low");
+ assert_eq!(body["messages"][0]["content"][1]["type"], "image_url");
+}
+#[tokio::test]
+async fn transport_failure_advances_but_invalid_routes_do_not() {
+ let failing = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(
+ ResponseTemplate::new(400)
+ .set_body_json(json!({"error":{"message":"fixture rejection"}})),
+ )
+ .mount(&failing)
+ .await;
+ let last = scripted(vec![answer("actual", "stop", 0.02)]).await;
+ let request = CompletionRequest::new("ignored", vec![ChatMessage::user("review")]);
+ let outcome = CompletionLadder::new(rung(&failing, "first"))
+ .fallback(rung(&last, "last"))
+ .complete(request.clone())
+ .await
+ .expect("next route");
+ assert_eq!(outcome.attempts.len(), 2);
+ assert_eq!(
+ outcome.total_usage.unwrap().cost_usd,
+ None,
+ "failed dispatch spend is unknown"
+ );
+ let unsafe_rung = CompletionRung::new(
+ Completer::new(Route::openai_compatible("http://example.org/v1", "fixture")),
+ "first",
+ );
+ let error = CompletionLadder::new(unsafe_rung)
+ .fallback(rung(&last, "last"))
+ .complete(request)
+ .await
+ .expect_err("unsafe route");
+ assert_eq!(error.attempts.len(), 1);
+ assert_eq!(last.received_requests().await.unwrap().len(), 1);
+}
+#[test]
+fn named_routes_and_providers_share_documented_endpoints() {
+ use openhuman_embed::Provider;
+ for (route, provider, url) in [
+ (
+ Route::openrouter("fixture"),
+ Provider::openrouter("fixture"),
+ "https://openrouter.ai/api/v1",
+ ),
+ (
+ Route::moonshot("fixture"),
+ Provider::moonshot("fixture"),
+ "https://api.moonshot.ai/v1",
+ ),
+ (
+ Route::minimax("fixture"),
+ Provider::minimax("fixture"),
+ "https://api.minimax.io/v1",
+ ),
+ ] {
+ assert_eq!(route.base_url, url);
+ assert_eq!(provider.route(), Some(&route));
+ }
+}
+
+#[tokio::test]
+async fn retries_stop_at_the_ceiling_and_missing_caps_never_expand() {
+ let server = scripted(vec![answer("actual", "length", 0.01)]).await;
+ let ladder = CompletionLadder::new(rung(&server, "requested"))
+ .truncation_retry(TruncationRetry::new(255, 1500));
+ let request = CompletionRequest::new("ignored", vec![ChatMessage::user("review")]);
+ let error = ladder
+ .complete(request.clone().max_tokens(1024))
+ .await
+ .expect_err("bounded exhaustion");
+ assert_eq!(error.attempts.len(), 2);
+ assert_eq!(error.attempts[1].max_tokens, Some(1500));
+ assert_eq!(error.total_usage.unwrap().cost_usd, Some(0.02));
+ let error = ladder
+ .complete(request)
+ .await
+ .expect_err("no growth without explicit cap");
+ assert_eq!(error.attempts.len(), 1);
+}
+#[tokio::test]
+async fn unpinned_rungs_are_terminal_and_success_never_tries_fallback() {
+ let server = scripted(vec![answer("actual", "stop", 0.01)]).await;
+ let request = CompletionRequest::new("ignored", vec![ChatMessage::user("review")]);
+ let error = CompletionLadder::new(rung(&server, "first").unpinned())
+ .fallback(rung(&server, "next"))
+ .complete(request.clone())
+ .await
+ .expect_err("unpinning is a last resort");
+ assert!(error.attempts.is_empty());
+ assert!(server.received_requests().await.unwrap().is_empty());
+ let result = CompletionLadder::new(rung(&server, "first"))
+ .fallback(rung(&server, "next"))
+ .complete(request)
+ .await
+ .expect("first answers");
+ assert_eq!(result.attempts.len(), 1);
+ assert_eq!(server.received_requests().await.unwrap().len(), 1);
+}
diff --git a/crates/openhuman-embed/tests/structured_turns.rs b/crates/openhuman-embed/tests/structured_turns.rs
index e7e6d9ebf6..b876afa4ab 100644
--- a/crates/openhuman-embed/tests/structured_turns.rs
+++ b/crates/openhuman-embed/tests/structured_turns.rs
@@ -179,7 +179,7 @@ fn a_tool_loop_ends_in_a_structured_answer() {
assert_eq!(reads.load(Ordering::SeqCst), 1, "the host tool ran");
assert_eq!(outcome.structured, Some(answer));
assert_eq!(outcome.finish_reason.as_deref(), Some("stop"));
- assert!(outcome.answered_model.is_some());
+ assert_eq!(outcome.answered_model.as_deref(), Some("fixture-answered"));
assert_eq!(outcome.usage.expect("usage").reasoning_tokens, 7);
let requests = chat_requests(&provider).await;
diff --git a/crates/openhuman-embed/tests/tool_required_routing.rs b/crates/openhuman-embed/tests/tool_required_routing.rs
new file mode 100644
index 0000000000..3ca1b1be21
--- /dev/null
+++ b/crates/openhuman-embed/tests/tool_required_routing.rs
@@ -0,0 +1,198 @@
+//! Structured agent turns on a `HostOnly` agent.
+//!
+//! A reviewer reads a diff with host tools and answers in a schema the host
+//! parses. These read the requests the provider received (the response format
+//! and output cap must reach every call of the tool loop) and the outcome the
+//! host gets back (the parsed answer, why the model stopped, which model
+//! answered, and the reasoning it spent). The diff is untrusted data, so a
+//! host-only agent may take it past the prompt guard; no other agent may.
+
+mod common;
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use common::{chat_requests, offline_config, runtime, stub_backend};
+use openhuman_embed::complete::ResponseFormat;
+use openhuman_embed::{
+ Access, AgentDefinitionSpec, AgentSpec, HostTurnTools, Provider, Runtime, Tool, ToolScopeSpec,
+ Workspace,
+};
+use serde_json::{json, Value};
+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()))]))
+}
+
+fn review_schema() -> ResponseFormat {
+ ResponseFormat::JsonSchema {
+ name: "review".to_string(),
+ schema: json!({
+ "type": "object",
+ "properties": { "verdict": { "type": "string" } },
+ "required": ["verdict"]
+ }),
+ }
+}
+
+fn body(request: &Request) -> Value {
+ serde_json::from_slice(&request.body).expect("json body")
+}
+
+#[test]
+fn required_exploration_refuses_premature_answers_and_preserves_gateway_options() {
+ 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, model) in ["openai/gpt-4.1-mini", "moonshotai/kimi-k2.5", "minimax/minimax-m3"].iter().enumerate() {
+ let premature = provider(vec![completion(
+ json!({"role":"assistant","content":"{\"verdict\":\"approve\"}"}),"stop",model,0,
+ )]).await;
+ let reads = Arc::new(AtomicUsize::new(0));
+ let spec = reviewer(&format!("premature-{index}"), &premature, reads.clone())
+ .provider(Provider::openai_compatible(format!("{}/v1",premature.uri()),"fixture").model(*model));
+ let agent = runtime.agent(spec).expect("agent");
+ // Prompt-only exploration accepts premature schema-valid JSON.
+ let advisory = agent.turn("Read src/main.rs before answering.")
+ .response_format(review_schema()).max_tokens(1024).untrusted_input(true)
+ .send().await.expect("advisory prompt accepts provider reply");
+ assert!(advisory.structured.is_some());
+ assert_eq!(reads.load(Ordering::SeqCst),0);
+ let outcome = agent.turn("Read src/main.rs before answering.").response_format(review_schema())
+ .max_tokens(1024).require_tool_call(true).untrusted_input(true)
+ .provider_options(json!({"provider":{"only":["fixture"]},"reasoning":{"effort":"low"}}))
+ .send().await;
+ assert!(outcome.is_err(), "{model} must not accept an unexplored schema-valid answer");
+ assert_eq!(reads.load(Ordering::SeqCst),0);
+ let requests = chat_requests(&premature).await;
+ assert_eq!(requests.len(),2);
+ let wire = body(&requests[1]);
+ assert_eq!(wire["tool_choice"],"required");
+ assert!(wire.get("response_format").is_none());
+ assert!(wire["tools"].as_array().unwrap().iter().any(|tool|tool["function"]["name"]=="read_file"),"native host tools must survive for {model}");
+ assert_eq!(wire["provider"]["only"],json!(["fixture"]));
+ assert_eq!(wire["reasoning"]["effort"],"low");
+ }
+ let rejected = provider(vec![
+ completion(json!({"role":"assistant","content":null,"tool_calls":[{"id":"call-blocked","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"blocked\"}"}}]}),"tool_calls","fixture",0),
+ completion(json!({"role":"assistant","content":"{\"verdict\":\"approve\"}"}),"stop","fixture",0),
+ ]).await;
+ let rejected_reads = Arc::new(AtomicUsize::new(0));
+ let rejected_agent = runtime.agent(reviewer("rejected-read",&rejected,rejected_reads.clone())).expect("agent");
+ assert!(rejected_agent.turn("Read before review.").response_format(review_schema()).require_tool_call(true).send().await.is_err());
+ assert_eq!(rejected_reads.load(Ordering::SeqCst),1);
+ let rejected_requests = chat_requests(&rejected).await;
+ assert_eq!(rejected_requests.len(),2);
+ assert_eq!(body(&rejected_requests[1])["tool_choice"],"required");
+ assert!(body(&rejected_requests[1]).get("response_format").is_none());
+ let served = provider(vec![
+ completion(json!({"role":"assistant","content":null,"tool_calls":[{"id":"call-read","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"src/main.rs\"}"}}]}),"tool_calls","fixture",0),
+ completion(json!({"role":"assistant","content":"{\"verdict\":\"approve\"}"}),"stop","actual-answered",0),
+ ]).await;
+ let reads = Arc::new(AtomicUsize::new(0));
+ let agent = runtime.agent(reviewer("explored",&served,reads.clone())).expect("agent");
+ let outcome = agent.turn("Read before review.").response_format(review_schema())
+ .require_tool_call(true).max_tokens(1024).send().await.expect("explored answer");
+ assert_eq!(reads.load(Ordering::SeqCst),1);
+ assert_eq!(outcome.answered_model.as_deref(),Some("actual-answered"));
+ let requests = chat_requests(&served).await;
+ assert!(body(&requests[0]).get("response_format").is_none());
+ assert_eq!(body(&requests[1])["response_format"]["type"],"json_schema");
+ }).await.expect("test task");
+ });
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 82ba4ec5c3..a1f342cc96 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.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