Skip to content

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

feat(embed): allow per-rung routing options and output caps

Steven Enamakel258ca86b899d
diff --git a/crates/openhuman-embed/ROUTING.md b/crates/openhuman-embed/ROUTING.md
index 96f1292376..9073208a7f 100644
--- a/crates/openhuman-embed/ROUTING.md
+++ b/crates/openhuman-embed/ROUTING.md
@@ -24,7 +24,15 @@ assert_eq!(outcome.attempts.last().unwrap().answered_model, outcome.response.ans
# }
```
-Each rung starts with the original conversation and cap. A `length` finish
+Each rung starts with the original conversation. By default it inherits the
+request cap and provider options. `CompletionRung::provider_options(value)`
+replaces the options for that rung, and `max_tokens(Some(cap))` overrides its
+initial cap. `max_tokens(None)` explicitly removes an inherited cap and disables
+truncation growth; omitting the builder inherits the request cap. Options are
+replaced before `unpinned()` removes the provider routing object. Rung debug
+output omits option values. Each fallback retries from its own initial 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,
diff --git a/crates/openhuman-embed/src/routing.rs b/crates/openhuman-embed/src/routing.rs
index 439c7d6f59..f2514bdb60 100644
--- a/crates/openhuman-embed/src/routing.rs
+++ b/crates/openhuman-embed/src/routing.rs
@@ -37,10 +37,12 @@ impl Provider {
}
/// One endpoint/model choice in an ordered ladder.
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct CompletionRung {
completer: Completer,
model: String,
+ provider_options: Option<serde_json::Value>,
+ max_tokens: Option<Option<u32>>,
unpinned: bool,
}
impl CompletionRung {
@@ -49,9 +51,24 @@ impl CompletionRung {
Self {
completer,
model: model.into(),
+ provider_options: None,
+ max_tokens: None,
unpinned: false,
}
}
+ /// Replace the request's provider options on this rung. Applied before
+ /// `unpinned` removes gateway routing pins; other request fields survive.
+ pub fn provider_options(mut self, options: serde_json::Value) -> Self {
+ self.provider_options = Some(options);
+ self
+ }
+ /// Override this rung's initial output cap. `None` explicitly removes an
+ /// inherited cap and disables truncation growth; omitting this builder
+ /// inherits the request cap. Each rung retries from its own initial cap.
+ pub fn max_tokens(mut self, cap: Option<u32>) -> Self {
+ self.max_tokens = Some(cap);
+ self
+ }
/// 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.
@@ -61,6 +78,18 @@ impl CompletionRung {
}
}
+impl std::fmt::Debug for CompletionRung {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("CompletionRung")
+ .field("completer", &self.completer)
+ .field("model", &self.model)
+ .field("has_provider_options", &self.provider_options.is_some())
+ .field("max_tokens", &self.max_tokens)
+ .field("unpinned", &self.unpinned)
+ .finish()
+ }
+}
+
/// Truncation retry budget; each retry doubles the original output cap.
#[derive(Debug, Clone, Copy)]
pub struct TruncationRetry {
@@ -157,7 +186,7 @@ impl CompletionLadder {
self.truncation = Some(retry);
self
}
- /// Run the ladder. Every rung starts from the original messages and token
+ /// Run the ladder. Every rung starts from the original messages and its own or inherited
/// cap; truncated output never becomes trusted conversation history.
pub async fn complete(
&self,
@@ -183,6 +212,12 @@ impl CompletionLadder {
for rung in &self.rungs {
let mut current = request.clone();
current.model = rung.model.clone();
+ if let Some(options) = &rung.provider_options {
+ current.provider_options = options.clone();
+ }
+ if let Some(cap) = rung.max_tokens {
+ current.max_tokens = cap;
+ }
if rung.unpinned {
if let Some(options) = current.provider_options.as_object_mut() {
options.remove("provider");
@@ -225,7 +260,7 @@ impl CompletionLadder {
total_usage: total_usage(&attempts),
response,
attempts,
- })
+ });
}
Ok(_) => {
last_error = CoreError::Rpc {
diff --git a/crates/openhuman-embed/tests/completion_routing.rs b/crates/openhuman-embed/tests/completion_routing.rs
index c8bc39f6c7..ae98f0e18e 100644
--- a/crates/openhuman-embed/tests/completion_routing.rs
+++ b/crates/openhuman-embed/tests/completion_routing.rs
@@ -1,7 +1,7 @@
//! 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 serde_json::{Value, json};
use std::sync::atomic::{AtomicUsize, Ordering};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
@@ -167,3 +167,85 @@ async fn unpinned_rungs_are_terminal_and_success_never_tries_fallback() {
assert_eq!(result.attempts.len(), 1);
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
+
+#[tokio::test]
+async fn fallback_uses_its_own_provider_pin_and_retries_from_its_own_cap() {
+ let first = MockServer::start().await;
+ Mock::given(method("POST"))
+ .respond_with(
+ ResponseTemplate::new(400)
+ .set_body_json(json!({"error":{"message":"fixture rejection"}})),
+ )
+ .mount(&first)
+ .await;
+ let fallback = scripted(vec![
+ answer("actual", "length", 0.01),
+ answer("actual", "stop", 0.02),
+ ])
+ .await;
+ let outcome = CompletionLadder::new(
+ rung(&first, "primary")
+ .provider_options(
+ json!({"provider":{"only":["primary-pin"]},"reasoning":{"effort":"low"}}),
+ )
+ .max_tokens(Some(16)),
+ )
+ .fallback(
+ rung(&fallback, "fallback")
+ .provider_options(
+ json!({"provider":{"only":["fallback-pin"]},"reasoning":{"effort":"high"}}),
+ )
+ .max_tokens(Some(32)),
+ )
+ .truncation_retry(TruncationRetry::new(1, 128))
+ .complete(
+ CompletionRequest::new("ignored", vec![ChatMessage::user("review")])
+ .max_tokens(8)
+ .provider_options(json!({"provider":{"only":["request-pin"]}})),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ outcome
+ .attempts
+ .iter()
+ .map(|attempt| attempt.max_tokens)
+ .collect::<Vec<_>>(),
+ vec![Some(16), Some(32), Some(64)]
+ );
+ let requests = first.received_requests().await.unwrap();
+ let primary: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ assert_eq!(primary["provider"]["only"][0], "primary-pin");
+ assert_eq!(primary["max_tokens"], 16);
+ let requests = fallback.received_requests().await.unwrap();
+ assert_eq!(requests.len(), 2);
+ for (request, cap) in requests.iter().zip([32, 64]) {
+ let body: Value = serde_json::from_slice(&request.body).unwrap();
+ assert_eq!(body["provider"]["only"][0], "fallback-pin");
+ assert_eq!(body["reasoning"]["effort"], "high");
+ assert_eq!(body["max_tokens"], cap);
+ }
+}
+
+#[tokio::test]
+async fn unpinned_rung_removes_its_own_pin_and_can_explicitly_clear_the_cap() {
+ let provider = scripted(vec![answer("actual", "length", 0.01)]).await;
+ let choice = rung(&provider,"model")
+ .provider_options(json!({"provider":{"only":["own-pin"]},"reasoning":{"effort":"high"},"host-private":"SECRET-OPTION"}))
+ .max_tokens(None).unpinned();
+ assert!(!format!("{choice:?}").contains("SECRET-OPTION"));
+ let error = CompletionLadder::new(choice)
+ .truncation_retry(TruncationRetry::new(2, 128))
+ .complete(
+ CompletionRequest::new("ignored", vec![ChatMessage::user("review")]).max_tokens(8),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.attempts.len(), 1);
+ assert_eq!(error.attempts[0].max_tokens, None);
+ let requests = provider.received_requests().await.unwrap();
+ let body: Value = serde_json::from_slice(&requests[0].body).unwrap();
+ assert!(body.get("provider").is_none());
+ assert!(body.get("max_tokens").is_none());
+ assert_eq!(body["reasoning"]["effort"], "high");
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 2be4015d16..0dd3d3d6e0 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -662,7 +662,8 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 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 |
+| 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, per-rung option/cap overrides, 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 |
+
| 16.1.19 | Pinned standalone Embed source consumer | Script+RI | `scripts/__tests__/embed-consumer-bootstrap.test.mjs` | ✅ | Exact SHA verification, inherited workspace edition, generated active patches, stable locked offline builds with optional Embed enabled/disabled, default dependency tree without HTTP, no untracked secrets or Git metadata, refused malformed/escaping patches and existing destinations |
| 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
| 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |