Skip to content

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

feat(jev): use host-owned SystemOneEvaluator transport

Steven Enamakel16ca422bf418
diff --git a/Cargo.lock b/Cargo.lock
index 9ff4eeb068..b46dba6848 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4239,6 +4239,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.20",
"tinyhumans-sdk",
+ "tinyjevclient",
"tinytools 0.4.1",
"tinytools-jev",
"tokio",
@@ -6847,6 +6848,19 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "tinyjevclient"
+version = "0.2.1"
+source = "git+https://github.com/tinyhumansai/tinyjevclient?rev=e53d5f088ff03fa38c53bac219dab7697b5016c9#e53d5f088ff03fa38c53bac219dab7697b5016c9"
+dependencies = [
+ "httpdate",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.20",
+ "tokio",
+]
+
[[package]]
name = "tinyjuice-bus"
version = "0.2.5"
diff --git a/crates/openhuman-tinyhumans/Cargo.toml b/crates/openhuman-tinyhumans/Cargo.toml
index dc7372aae7..29f36ff9ce 100644
--- a/crates/openhuman-tinyhumans/Cargo.toml
+++ b/crates/openhuman-tinyhumans/Cargo.toml
@@ -17,7 +17,7 @@ publish = false
# default and forwarded by every shipped host; without it the core ranks
# `tool_search` with BM25 alone.
default = ["openhuman-embed/default", "jev"]
-jev = ["dep:tinytools-jev"]
+jev = ["dep:tinytools-jev", "dep:tinyjevclient"]
http-server = ["openhuman-embed/http-server"]
inference = ["openhuman-embed/inference"]
documents = ["openhuman-embed/documents"]
@@ -56,6 +56,10 @@ tinyhumans-sdk = { path = "../../vendor/tinyhumans-sdk", default-features = fals
# `tinytools`, so the `ToolRanker` types unify.
tinytools = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools" }
tinytools-jev = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-jev", optional = true }
+# The System One HTTP client behind `SystemOneEvaluator`: `tinytools-jev`
+# only defines the `JevEvaluator` seam, the host owns the transport. Same
+# revision `tinytools` pinned while it still carried the client itself.
+tinyjevclient = { git = "https://github.com/tinyhumansai/tinyjevclient", rev = "e53d5f088ff03fa38c53bac219dab7697b5016c9", optional = true }
anyhow = "1"
async-trait = "0.1"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
diff --git a/crates/openhuman-tinyhumans/src/jev/evaluator.rs b/crates/openhuman-tinyhumans/src/jev/evaluator.rs
new file mode 100644
index 0000000000..c87f28e527
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/jev/evaluator.rs
@@ -0,0 +1,194 @@
+//! [`SystemOneEvaluator`]: the `tinytools_jev::JevEvaluator` that carries a
+//! ranking decision over the wire to TypeSafe's System One endpoint through
+//! the TinyHumans backend proxy.
+//!
+//! `tinytools-jev` owns the *decision* (retrieve, shortlist, ask, decode) and
+//! hands the host one provider-neutral [`JevRequest`] per evaluation; this
+//! type owns the *transport*: the `tinyjevclient` HTTP client, the
+//! credential, the deadline and the retry policy. It translates the request
+//! into one System One evaluation — a `Choice` over the options and a `Noul`
+//! asking whether a tool is needed at all — and the answer back into a
+//! [`JevDecision`].
+
+use std::{collections::BTreeMap, time::Duration};
+
+use serde_json::{Value, json};
+use tinyjevclient::{
+ Answer, Choice, Client, ClientConfig, Error as JevError, EvaluationFailure,
+ EvaluationRequest, Noul, NoulCriteria, Question,
+};
+use tinytools::RankError;
+use tinytools_jev::{JevDecision, JevEvaluator, JevRequest};
+
+/// Question id of the option `Choice`.
+const TOOL_QUESTION: &str = "tool";
+/// Question id of the needs-a-tool `Noul`.
+const NEEDS_TOOL_QUESTION: &str = "needs_tool";
+/// The default wording when the ranker does not set
+/// [`JevRequest::instructions`]: which *tool* accomplishes the request.
+const DEFAULT_INSTRUCTIONS: &str = "Which tool accomplishes the user's `request`? Judge by what \
+ each tool does, not by shared words. Pick `none` when no \
+ listed tool does it.";
+
+/// A System One evaluator over one built `tinyjevclient` client.
+#[derive(Clone)]
+pub struct SystemOneEvaluator {
+ client: Client,
+ /// Wall-clock cap on one evaluation, retries included. A tool search sits
+ /// inside a model's turn; a slow decision is worse than a BM25 fallback.
+ timeout: Duration,
+}
+
+impl std::fmt::Debug for SystemOneEvaluator {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SystemOneEvaluator")
+ .field("timeout", &self.timeout)
+ .finish_non_exhaustive()
+ }
+}
+
+impl SystemOneEvaluator {
+ /// The deadline every evaluation runs under unless
+ /// [`with_timeout`](Self::with_timeout) changes it.
+ pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(3);
+
+ /// An evaluator over a client built from `client_config`.
+ ///
+ /// # Errors
+ ///
+ /// Returns the client's configuration error (empty key, bad base URL,
+ /// zero timeout) as [`RankError::InvalidInput`].
+ pub fn from_config(client_config: ClientConfig) -> Result<Self, RankError> {
+ let client = Client::new(client_config).map_err(|error| RankError::InvalidInput {
+ reason: error.to_string(),
+ })?;
+ Ok(Self {
+ client,
+ timeout: Self::DEFAULT_TIMEOUT,
+ })
+ }
+
+ /// Replace the per-evaluation deadline.
+ #[must_use]
+ pub fn with_timeout(mut self, timeout: Duration) -> Self {
+ self.timeout = timeout;
+ self
+ }
+
+ fn build_request(request: &JevRequest) -> Result<EvaluationRequest, RankError> {
+ let mut criteria: BTreeMap<String, Option<Value>> = BTreeMap::new();
+ for option in &request.options {
+ if criteria
+ .insert(option.key.clone(), Some(json!(option.description)))
+ .is_some()
+ {
+ return Err(RankError::InvalidInput {
+ reason: format!("duplicate option key `{}`", option.key),
+ });
+ }
+ }
+ let mut state = json!({ "request": request.intent });
+ if !request.recent_turns.is_empty()
+ && let Some(object) = state.as_object_mut()
+ {
+ object.insert(
+ "recent_user_turns".to_owned(),
+ Value::Array(
+ request
+ .recent_turns
+ .iter()
+ .map(|turn| Value::String(turn.clone()))
+ .collect(),
+ ),
+ );
+ }
+ let instructions = request
+ .instructions
+ .as_deref()
+ .unwrap_or(DEFAULT_INSTRUCTIONS);
+ let questions = BTreeMap::from([
+ (
+ TOOL_QUESTION.to_owned(),
+ Question::Choice(Choice {
+ instructions: json!(instructions),
+ criteria,
+ }),
+ ),
+ (
+ NEEDS_TOOL_QUESTION.to_owned(),
+ Question::Noul(Noul {
+ instructions: json!(
+ "Does fulfilling the user's `request` require calling a tool \
+ — an action or a lookup outside the assistant's own knowledge?"
+ ),
+ criteria: Some(NoulCriteria {
+ r#true: json!(
+ "The request asks for an action or for information that \
+ must be fetched."
+ ),
+ r#false: json!("The request can be answered by replying, with no tool."),
+ }),
+ }),
+ ),
+ ]);
+ Ok(EvaluationRequest {
+ state,
+ model: request.model.clone(),
+ questions,
+ })
+ }
+}
+
+#[async_trait::async_trait]
+impl JevEvaluator for SystemOneEvaluator {
+ async fn evaluate(&self, request: &JevRequest) -> Result<JevDecision, RankError> {
+ let wire = Self::build_request(request)?;
+ let evaluated = tokio::time::timeout(self.timeout, self.client.evaluate(&wire))
+ .await
+ .map_err(|_elapsed| RankError::Timeout)?;
+ let result = evaluated.map_err(map_failure)?;
+ let Some(Answer::Choice(choice)) = result.response.answers.get(TOOL_QUESTION) else {
+ return Err(RankError::Backend {
+ reason: format!("response has no choice answer for `{TOOL_QUESTION}`"),
+ });
+ };
+ let needs_tool = match result.response.answers.get(NEEDS_TOOL_QUESTION) {
+ Some(Answer::Noul(noul)) => Some(noul.noul),
+ _ => None,
+ };
+ log::debug!(
+ "[tool-search] system one answered (options={} confidence={:.2} needs_tool={:?} attempts={} latency_ms={} request_id={:?})",
+ request.options.len(),
+ choice.confidence,
+ needs_tool,
+ result.attempts,
+ result.latency.as_millis(),
+ result.request_id,
+ );
+ Ok(JevDecision {
+ probabilities: choice.probabilities.clone(),
+ choice_confidence: choice.confidence,
+ needs_tool,
+ input_tokens: result.response.usage.input_tokens,
+ attempts: result.attempts,
+ })
+ }
+}
+
+fn map_failure(failure: EvaluationFailure) -> RankError {
+ match failure.error {
+ JevError::InvalidRequest { reason } | JevError::InvalidConfig { reason } => {
+ RankError::InvalidInput { reason }
+ }
+ JevError::Timeout => RankError::Timeout,
+ other => RankError::Backend {
+ // `Display` on every variant is credential-free by the client's
+ // contract; the transport source is dropped, not printed.
+ reason: format!("{other} after {} attempt(s)", failure.attempts),
+ },
+ }
+}
+
+#[cfg(test)]
+#[path = "evaluator_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-tinyhumans/src/jev/evaluator_tests.rs b/crates/openhuman-tinyhumans/src/jev/evaluator_tests.rs
new file mode 100644
index 0000000000..7089b42315
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/jev/evaluator_tests.rs
@@ -0,0 +1,167 @@
+use std::collections::BTreeMap;
+
+use tinyjevclient::{Answer, ChoiceAnswer, ClientConfig, EvaluationResponse, NoulAnswer, Usage};
+use tinytools::RankError;
+use tinytools_jev::{JevEvaluator, JevOption, JevRequest};
+
+use super::*;
+
+fn request(instructions: Option<&str>) -> JevRequest {
+ JevRequest {
+ intent: "ping alex on slack".into(),
+ recent_turns: vec!["hi".into()],
+ options: vec![
+ JevOption {
+ key: "slack_send".into(),
+ description: "Send a Slack message (from slack)".into(),
+ },
+ JevOption {
+ key: "none".into(),
+ description: "No listed tool accomplishes the request.".into(),
+ },
+ ],
+ model: "jev-latest".into(),
+ instructions: instructions.map(str::to_owned),
+ }
+}
+
+#[test]
+fn wire_request_carries_every_option_the_state_and_both_questions() {
+ let wire = SystemOneEvaluator::build_request(&request(None)).expect("valid");
+ assert_eq!(wire.model, "jev-latest");
+ assert_eq!(wire.state["request"], "ping alex on slack");
+ assert_eq!(wire.state["recent_user_turns"][0], "hi");
+ let Some(Question::Choice(choice)) = wire.questions.get(TOOL_QUESTION) else {
+ panic!("tool question is a choice");
+ };
+ assert_eq!(choice.criteria.len(), 2);
+ assert!(choice.criteria.contains_key("none"));
+ assert_eq!(choice.instructions, json!(DEFAULT_INSTRUCTIONS));
+ assert!(matches!(
+ wire.questions.get(NEEDS_TOOL_QUESTION),
+ Some(Question::Noul(_))
+ ));
+}
+
+#[test]
+fn ranker_instructions_replace_the_default_wording() {
+ let wire = SystemOneEvaluator::build_request(&request(Some("Which group applies?")))
+ .expect("valid");
+ let Some(Question::Choice(choice)) = wire.questions.get(TOOL_QUESTION) else {
+ panic!("tool question is a choice");
+ };
+ assert_eq!(choice.instructions, json!("Which group applies?"));
+}
+
+#[test]
+fn duplicate_option_keys_are_invalid_input() {
+ let mut duplicated = request(None);
+ duplicated.options.push(JevOption {
+ key: "slack_send".into(),
+ description: "again".into(),
+ });
+ match SystemOneEvaluator::build_request(&duplicated) {
+ Err(RankError::InvalidInput { reason }) => assert!(reason.contains("slack_send")),
+ other => panic!("expected invalid input, got {other:?}"),
+ }
+}
+
+#[test]
+fn client_config_errors_surface_as_invalid_input() {
+ let err = SystemOneEvaluator::from_config(ClientConfig::new("")).expect_err("empty key");
+ assert!(matches!(err, RankError::InvalidInput { .. }), "{err}");
+}
+
+#[test]
+fn failures_map_without_leaking_the_client_error_source() {
+ let backend = map_failure(EvaluationFailure {
+ error: JevError::RateLimited,
+ attempts: 3,
+ latency: Duration::ZERO,
+ });
+ match backend {
+ RankError::Backend { reason } => assert!(reason.contains("3 attempt(s)"), "{reason}"),
+ other => panic!("expected backend, got {other}"),
+ }
+ assert!(matches!(
+ map_failure(EvaluationFailure {
+ error: JevError::Timeout,
+ attempts: 1,
+ latency: Duration::ZERO,
+ }),
+ RankError::Timeout
+ ));
+}
+
+/// The evaluator answers with exactly the probability table the ranker
+/// decodes; no reshaping happens on the way back.
+#[tokio::test]
+async fn a_choice_answer_becomes_a_decision() {
+ let response = EvaluationResponse {
+ model: "jev-latest".into(),
+ answers: BTreeMap::from([
+ (
+ TOOL_QUESTION.to_owned(),
+ Answer::Choice(ChoiceAnswer {
+ choice: "slack_send".into(),
+ probabilities: BTreeMap::from([
+ ("slack_send".to_owned(), 0.9),
+ ("none".to_owned(), 0.1),
+ ]),
+ confidence: 0.9,
+ }),
+ ),
+ (
+ NEEDS_TOOL_QUESTION.to_owned(),
+ Answer::Noul(NoulAnswer { noul: 0.95 }),
+ ),
+ ]),
+ usage: Usage {
+ input_tokens: Some(1200),
+ output_tokens: None,
+ },
+ };
+ let server = spawn_system_one(response).await;
+ let mut config = ClientConfig::new("test-key");
+ config.base_url = server.url.clone();
+ let evaluator = SystemOneEvaluator::from_config(config).expect("client");
+ let decision = evaluator.evaluate(&request(None)).await.expect("decision");
+ assert_eq!(decision.probabilities["slack_send"], 0.9);
+ assert_eq!(decision.choice_confidence, 0.9);
+ assert_eq!(decision.needs_tool, Some(0.95));
+ assert_eq!(decision.input_tokens, Some(1200));
+ assert_eq!(decision.attempts, 1);
+ server.shutdown.send(()).ok();
+}
+
+struct SystemOneStub {
+ url: String,
+ shutdown: tokio::sync::oneshot::Sender<()>,
+}
+
+/// One-route System One stand-in answering every evaluation with `response`.
+async fn spawn_system_one(response: EvaluationResponse) -> SystemOneStub {
+ use axum::{Router, routing::post};
+ let body = serde_json::to_value(&response).expect("serialise");
+ let app = Router::new().fallback(post(move || {
+ let body = body.clone();
+ async move { axum::Json(body) }
+ }));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind");
+ let addr = listener.local_addr().expect("addr");
+ let (shutdown, rx) = tokio::sync::oneshot::channel::<()>();
+ tokio::spawn(async move {
+ axum::serve(listener, app)
+ .with_graceful_shutdown(async {
+ rx.await.ok();
+ })
+ .await
+ .ok();
+ });
+ SystemOneStub {
+ url: format!("http://{addr}"),
+ shutdown,
+ }
+}
diff --git a/crates/openhuman-tinyhumans/src/jev/mod.rs b/crates/openhuman-tinyhumans/src/jev/mod.rs
index 963df39f6b..5a10d668a4 100644
--- a/crates/openhuman-tinyhumans/src/jev/mod.rs
+++ b/crates/openhuman-tinyhumans/src/jev/mod.rs
@@ -4,9 +4,11 @@
//! tool and ranks searches with whatever ranker the process installed
//! (`openhuman_core::agent::tinyagents::discovery`). This module installs
//! [`TinyHumansJevRanker`]: `tinytools_jev::JevRanker` — BM25 retrieval to a
-//! shortlist, one Jev `Choice` to decide — reached through the backend's
+//! shortlist, one Jev `Choice` to decide — over [`SystemOneEvaluator`], the
+//! host-owned transport that reaches the backend's
//! `/agent-integrations/openrouter/systemone` proxy with the same credential
-//! every other backend call uses.
+//! every other backend call uses (`tinytools-jev` keeps no HTTP client of
+//! its own; the host implements its `JevEvaluator` seam).
//!
//! The credential is resolved **per search**, not at install: a desktop
//! signs in and out while the process runs, and a search must follow the
@@ -15,8 +17,10 @@
//! out. The built client is cached by credential and base URL so a stable
//! session does not rebuild an HTTP client on every search.
+mod evaluator;
mod ranker;
+pub use evaluator::SystemOneEvaluator;
pub use ranker::TinyHumansJevRanker;
use std::sync::Arc;
diff --git a/crates/openhuman-tinyhumans/src/jev/ranker.rs b/crates/openhuman-tinyhumans/src/jev/ranker.rs
index 37a33d8bb5..65a8d07fa8 100644
--- a/crates/openhuman-tinyhumans/src/jev/ranker.rs
+++ b/crates/openhuman-tinyhumans/src/jev/ranker.rs
@@ -13,7 +13,10 @@ use openhuman_core::api::config::effective_backend_api_url;
use openhuman_core::config::Config;
use openhuman_core::security::credentials::session_support::resolve_backend_credential;
use tinytools::{RankCandidate, RankContext, RankError, RankHit, ToolRanker};
-use tinytools_jev::{ClientConfig, JevRanker, JevRankerConfig};
+use tinyjevclient::ClientConfig;
+use tinytools_jev::{JevRanker, JevRankerConfig};
+
+use super::evaluator::SystemOneEvaluator;
/// How the ranker reads the config a search runs under. The default is the
/// core's own read path (the embedder's config when one is bound, else the
@@ -50,8 +53,8 @@ impl Default for TinyHumansJevRanker {
}
impl TinyHumansJevRanker {
- /// A ranker with `tinytools-jev`'s defaults: BM25 retrieval to 20, one
- /// Jev decision, a 3 s deadline.
+ /// A ranker with `tinytools-jev`'s defaults (BM25 retrieval to 20, one
+ /// Jev decision) under the evaluator's 3 s deadline.
pub fn new() -> Self {
Self::with_config(JevRankerConfig::new())
}
@@ -104,7 +107,8 @@ impl TinyHumansJevRanker {
}
let mut client = ClientConfig::tinyhumans_openrouter(credential.into_secret());
client.base_url = base_url.clone();
- let ranker = JevRanker::from_config(client, self.config.clone())?;
+ let evaluator = SystemOneEvaluator::from_config(client)?;
+ let ranker = JevRanker::new(Arc::new(evaluator), self.config.clone());
log::info!(
"[tool-search] jev ranker bound to backend {} ({})",
openhuman_core::util::redact::redact_url_for_log(&base_url),