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
Merge upstream/main into jev-tool-search
Steven Enamakeld783d305dc02
diff --cc Cargo.lockindex 5d8ba82e31,aabb016144..d42fbeb16e--- a/Cargo.lock+++ b/Cargo.lock@@@ -4104,8 -4104,8 +4104,8 @@@ dependencies ="tinymemory-sources","tinyruntime-bus","tinyskills",-- "tinytools 0.3.0",-- "tinytools-agent 0.3.0",++ "tinytools 0.4.1",++ "tinytools-agent 0.4.1","tinyvoice-bus","tinywallet","tinywallet-bus",@@@ -4173,12 -4173,11 +4173,13 @@@ dependencies ="tinyinference-core","tinyinference-llm","tinyinference-local",++ "tinyjevclient","tinymcp","tinymcp-bus","tinymemory-api",-- "tinytools 0.3.0",-- "tinytools-agent 0.3.0",++ "tinytools 0.4.1",++ "tinytools-agent 0.4.1",+ "tinytools-jev","tokio","tokio-stream","tokio-tungstenite 0.29.0",@@@ -4239,8 -4238,6 +4240,9 @@@ dependencies ="tempfile","thiserror 2.0.20","tinyhumans-sdk",- "tinytools 0.3.0",++ "tinyjevclient",++ "tinytools 0.4.1",+ "tinytools-jev","tokio","url","urlencoding",@@@ -6439,7 -6436,7 +6441,7 @@@ dependencies ="serde_json","tinyagents-harness","tinyinference-llm",-- "tinytools 0.3.0",++ "tinytools 0.4.1","tokio","tracing",]@@@ -6466,8 -6463,8 +6468,8 @@@ dependencies ="tinyagents-definition","tinyinference-embeddings","tinyinference-llm",-- "tinytools 0.3.0",-- "tinytools-agent 0.3.0",++ "tinytools 0.4.1",++ "tinytools-agent 0.4.1","tokio","tracing","uuid",@@@ -6490,7 -6487,7 +6492,7 @@@ dependencies ="tinyagents-runtime","tinyagents-session","tinyinference-llm",-- "tinytools 0.3.0",++ "tinytools 0.4.1","tokio","uuid",]@@@ -6506,7 -6503,7 +6508,7 @@@ dependencies ="tinyagents-definition","tinyagents-harness","tinyinference-llm",-- "tinytools 0.3.0",++ "tinytools 0.4.1",][[package]]@@@ -6519,7 -6516,7 +6521,7 @@@ dependencies ="tinyagents-harness","tinyagents-session","tinyinference-llm",-- "tinytools 0.3.0",++ "tinytools 0.4.1","tokio",]@@@ -6785,7 -6782,7 +6787,7 @@@ dependencies ="sha2 0.11.0","thiserror 2.0.20","tinyinference-core",-- "tinytools-agent 0.3.0 (git+https://github.com/tinyhumansai/tinytools?rev=a5d04a7f3af0abc1dd748f87f94871b36ae9fe71)",++ "tinytools-agent 0.3.0","tokio","tracing",]@@@ -6847,18 -6844,6 +6849,19 @@@ dependencies ="uuid",]+[[package]]+name = "tinyjevclient"+version = "0.2.1"++source = "git+https://github.com/tinyhumansai/tinyjevclient?rev=84b3983c7e1e14f7515658ceafabb6c4e7967c94#84b3983c7e1e14f7515658ceafabb6c4e7967c94"+dependencies = [+ "httpdate",+ "reqwest",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+ "tokio",+]+[[package]]name = "tinyjuice-bus"version = "0.2.5"@@@ -6997,6 -6982,6 +7000,7 @@@ dependencies =[[package]]name = "tinytools"version = "0.3.0"++source = "git+https://github.com/tinyhumansai/tinytools?rev=a5d04a7f3af0abc1dd748f87f94871b36ae9fe71#a5d04a7f3af0abc1dd748f87f94871b36ae9fe71"dependencies = ["anyhow","async-trait",@@@ -7006,8 -6991,8 +7010,7 @@@[[package]]name = "tinytools"--version = "0.3.0"--source = "git+https://github.com/tinyhumansai/tinytools?rev=a5d04a7f3af0abc1dd748f87f94871b36ae9fe71#a5d04a7f3af0abc1dd748f87f94871b36ae9fe71"++version = "0.4.1"dependencies = ["anyhow","async-trait",@@@ -7018,6 -7003,6 +7021,7 @@@[[package]]name = "tinytools-agent"version = "0.3.0"++source = "git+https://github.com/tinyhumansai/tinytools?rev=a5d04a7f3af0abc1dd748f87f94871b36ae9fe71#a5d04a7f3af0abc1dd748f87f94871b36ae9fe71"dependencies = ["regex","serde",@@@ -7027,24 -7012,13 +7031,20 @@@[[package]]name = "tinytools-agent"--version = "0.3.0"--source = "git+https://github.com/tinyhumansai/tinytools?rev=a5d04a7f3af0abc1dd748f87f94871b36ae9fe71#a5d04a7f3af0abc1dd748f87f94871b36ae9fe71"++version = "0.4.1"dependencies = ["regex","serde","serde_json",-- "tinytools 0.3.0 (git+https://github.com/tinyhumansai/tinytools?rev=a5d04a7f3af0abc1dd748f87f94871b36ae9fe71)",++ "tinytools 0.4.1",+]++[[package]]+name = "tinytools-jev"- version = "0.3.0"++version = "0.4.1"+dependencies = [+ "async-trait",- "serde_json",- "tinyjevclient",- "tinytools 0.3.0",- "tokio",++ "tinytools 0.4.1",][[package]]diff --cc crates/openhuman-cli/Cargo.tomlindex f69bb60c41,dd24ca43ae..079680b8cc--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@@ -56,14 -56,13 +56,21 @@@ required-features = ["http-server", "bi# backend. What the feature used to name the engine crates for was two# `library-profile` *scenarios* — see that target's comment below; the binary# itself is still here.+# `tool-search-bench` — the `tool_search` ranker comparison (bm25 / overlap /+# jev) over the real orchestrator registry plus the recorded Composio+# catalogues. Always builds; the `jev` ranker is compiled in with the `jev`+# feature and runs only when a key is in the environment.+[[bin]]+name = "tool-search-bench"+path = "src/bin/tool_search_bench.rs"++ # Manual, network-touching A/B of the text tool-call dialects against a local+ # Ollama model: prompt tokens and call accuracy per `agent.tool_dispatcher`+ # value. Never run by CI; see the file's docs for the invocation.+ [[bin]]+ name = "tool-dialect-bench"+ path = "src/bin/tool_dialect_bench.rs"+[[bin]]name = "rss-bench"path = "src/bin/rss_bench.rs"@@@ -328,9 -334,6 +342,10 @@@ tempfile = "3tinyinference-llm = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }tinytools = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools" }tinytools-agent = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-agent" }+# The Jev ranker `tool-search-bench` measures; gated with the crate's `jev`+# feature so the bin builds without a Jev client.+tinytools-jev = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-jev", optional = true }++tinyjevclient = { git = "https://github.com/tinyhumansai/tinyjevclient", rev = "84b3983c7e1e14f7515658ceafabb6c4e7967c94", optional = true }tokio = { version = "1", features = ["full"] }toml = "1.0"tracing = "0.1"@@@ -376,10 -379,7 +391,10 @@@ wiremock = "0.6# Same contributor set as the core's `default`, forwarded. The product lanes# pass `--features "$(scripts/ci/product-features.sh)"`; every product gate# name resolves here so `cargo test --workspace --features ...` keeps working.-default = ["openhuman-core/default", "openhuman-tinyhumans/default"]+default = ["openhuman-core/default", "openhuman-tinyhumans/default", "jev"]+# The Jev-backed `tool_search` ranker; `openhuman-tinyhumans`'s own gate, plus+# the client `tool-search-bench` measures it with.- jev = ["openhuman-tinyhumans/jev", "dep:tinytools-jev"]++jev = ["openhuman-tinyhumans/jev", "dep:tinytools-jev", "dep:tinyjevclient"]http-server = ["openhuman-core/http-server", "openhuman-tinyhumans/http-server"]inference = ["openhuman-core/inference", "openhuman-tinyhumans/inference"]documents = ["openhuman-core/documents", "openhuman-tinyhumans/documents"]diff --cc crates/openhuman-cli/src/bin/tool_search_bench.rsindex 8862f30ca8,0000000000..ade9375c9emode 100644,000000..100644--- a/crates/openhuman-cli/src/bin/tool_search_bench.rs+++ b/crates/openhuman-cli/src/bin/tool_search_bench.rs@@@ -1,609 -1,0 +1,628 @@@+//! `tool-search-bench` — how well does each `tool_search` ranker pick the+//! right tool for an intent?+//!+//! The catalogue is the real thing: every tool the orchestrator session+//! registers (built exactly as a session builds it, with a temp workspace),+//! plus the recorded Composio catalogues under `tests/fixtures/composio_*.json`+//! (≈1,000 actions across nine toolkits) as the deferred per-action tools a+//! signed-in workspace would synthesise. The intents are+//! `tests/fixtures/tool_search/intents.jsonl`: hand-written requests, each+//! labelled with the tool it should reach (or `none` for a request no tool+//! should answer).+//!+//! Three rankers are measured on the same rows:+//!+//! - `bm25` — `tinytools::Bm25Ranker`, what the harness answers with when+//! nothing else is installed.+//! - `overlap` — `tinyagents_harness::tool::select::rank_tools_by_prompt`,+//! the verb-gated token overlap the Composio sub-agent narrows with today.+//! - `jev` — `tinytools_jev::JevRanker`: BM25 retrieves the top 20, one Jev+//! `Choice` decides. Needs a key: `OPENHUMAN_BACKEND_API_KEY` (through the+//! TinyHumans proxy, `BACKEND_URL` to override the base) or+//! `TYPESAFE_API_KEY` (TypeSafe directly). Skipped without one.+//!+//! Reported per ranker: top-1 and top-3 accuracy over the labelled rows,+//! recall@20 of the BM25 retriever (the ceiling Jev can reach), the needless+//! rate (a `none` row answered with a hit), p50/p95 latency, input tokens and+//! USD from the provider's `usage`, and a per-family confusion table.+//!+//! ```text+//! cargo run -p openhuman-cli --bin tool-search-bench -- --ranker all+//! cargo run -p openhuman-cli --bin tool-search-bench -- --dump-catalogue+//! ```++use std::collections::BTreeMap;+use std::path::PathBuf;+use std::sync::Arc;+use std::time::{Duration, Instant};++use anyhow::{Context, Result};+use serde::{Deserialize, Serialize};+use tinytools::{Bm25Ranker, RankCandidate, RankContext, ToolRanker};++/// jev-1.13 list price for input tokens, USD per million; output is free.+const JEV_USD_PER_MILLION_INPUT: f64 = 0.042;+/// Toolkits with a recorded catalogue under `tests/fixtures/`.+const FIXTURE_TOOLKITS: &[&str] = &[+ "gmail",+ "slack",+ "github",+ "notion",+ "googledrive",+ "googlesheets",+ "reddit",+ "facebook",+ "instagram",+];++#[derive(Debug, Clone, Deserialize)]+struct IntentRow {+ intent: String,+ /// The tool that should answer, or `"none"`.+ expected: String,+ #[serde(default)]+ family: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+struct CatalogueEntry {+ name: String,+ family: Option<String>,+ description: String,+ #[serde(skip)]+ parameters: serde_json::Value,+}++impl CatalogueEntry {+ fn candidate(&self) -> RankCandidate {+ let mut summary = String::with_capacity(self.description.len() + 64);+ summary.push_str(&self.name);+ summary.push(' ');+ summary.push_str(&self.name.replace('_', " "));+ summary.push(' ');+ summary.push_str(&self.description);+ if let Some(props) = self.parameters.get("properties").and_then(|v| v.as_object()) {+ for key in props.keys() {+ summary.push(' ');+ summary.push_str(key);+ }+ }+ RankCandidate {+ key: self.name.clone(),+ family: self.family.clone(),+ summary,+ }+ }+}++#[derive(Debug, Default, Serialize)]+struct RankerReport {+ ranker: String,+ rows: usize,+ labelled: usize,+ top1: usize,+ top3: usize,+ /// Labelled rows whose expected tool BM25 retrieved in its top 20.+ recall_at_20: usize,+ none_rows: usize,+ needless: usize,+ errors: usize,+ latency_ms: Vec<u64>,+ input_tokens: u64,+ usd: f64,+ /// `expected family -> top-1 family -> count`, labelled rows only.+ confusion: BTreeMap<String, BTreeMap<String, usize>>,+ /// `source -> (labelled, top1, top3, recall@k)` where source is `composio`+ /// or `core`; the connector catalogue is the heavy one, so it is read on+ /// its own.+ by_source: BTreeMap<String, (usize, usize, usize, usize)>,+ misses: Vec<Miss>,+}++#[derive(Debug, Clone, Serialize)]+struct Miss {+ intent: String,+ expected: String,+ got: Vec<String>,+}++impl RankerReport {+ fn percentile(&self, p: f64) -> u64 {+ if self.latency_ms.is_empty() {+ return 0;+ }+ let mut sorted = self.latency_ms.clone();+ sorted.sort_unstable();+ let idx = ((sorted.len() as f64 - 1.0) * p).round() as usize;+ sorted[idx.min(sorted.len() - 1)]+ }+}++struct Args {+ ranker: String,+ intents: PathBuf,+ dump_catalogue: bool,+ json_out: Option<PathBuf>,+ top_k: usize,+ retrieval_k: usize,+ misses: bool,+ family: bool,+ embedding: bool,+}++fn parse_args() -> Args {+ let mut args = Args {+ ranker: "all".to_string(),+ intents: repo_root().join("tests/fixtures/tool_search/intents.jsonl"),+ dump_catalogue: false,+ json_out: None,+ top_k: 3,+ retrieval_k: 20,+ misses: false,+ family: false,+ embedding: false,+ };+ let mut it = std::env::args().skip(1);+ while let Some(arg) = it.next() {+ match arg.as_str() {+ "--ranker" => args.ranker = it.next().unwrap_or_default(),+ "--intents" => args.intents = PathBuf::from(it.next().unwrap_or_default()),+ "--dump-catalogue" => args.dump_catalogue = true,+ "--json" => args.json_out = Some(PathBuf::from(it.next().unwrap_or_default())),+ "--top-k" => args.top_k = it.next().and_then(|v| v.parse().ok()).unwrap_or(3),+ "--retrieval-k" => {+ args.retrieval_k = it.next().and_then(|v| v.parse().ok()).unwrap_or(20)+ }+ "--misses" => args.misses = true,+ "--family" => args.family = true,+ "--embedding" => args.embedding = true,+ "-h" | "--help" => {+ eprintln!(+ "usage: tool-search-bench [--ranker all|bm25|overlap|embedding|jev] [--intents FILE] \+ [--dump-catalogue] [--json OUT] [--top-k N] [--retrieval-k N] [--misses] [--family] [--embedding]"+ );+ std::process::exit(0);+ }+ other => {+ eprintln!("unknown argument {other}");+ std::process::exit(2);+ }+ }+ }+ args+}++fn repo_root() -> PathBuf {+ PathBuf::from(env!("OPENHUMAN_REPOSITORY_ROOT"))+}++/// The orchestrator's registered tools, built the way a session builds them.+fn core_catalogue() -> Result<Vec<CatalogueEntry>> {+ use openhuman_core::agent::harness::AgentDefinitionRegistry;+ use openhuman_core::agent::OpenHumanSessionHost;++ let _ = AgentDefinitionRegistry::init_global_builtins();+ let tmp = tempfile::TempDir::new()?;+ let config = openhuman_core::config::Config {+ workspace_dir: tmp.path().join("workspace"),+ action_dir: tmp.path().join("workspace"),+ config_path: tmp.path().join("config.toml"),+ ..openhuman_core::config::Config::default()+ };+ std::fs::create_dir_all(&config.workspace_dir)?;+ let host = OpenHumanSessionHost::from_config_for_agent(&config, "orchestrator")+ .context("build orchestrator session")?;+ let mut out = Vec::new();+ for spec in host.tool_specs() {+ // Pack members carry their pack as the family; everything else is a+ // core tool with no family, like the registry sees it.+ let family = openhuman_core::tools::toolpacks::pack_for_tool(&spec.name)+ .map(|pack| pack.id.to_string());+ out.push(CatalogueEntry {+ name: spec.name.clone(),+ family,+ description: spec.description.clone(),+ parameters: spec.parameters.clone(),+ });+ }+ Ok(out)+}++/// The recorded Composio catalogues, one deferred action per entry.+fn composio_catalogue() -> Result<Vec<CatalogueEntry>> {+ let mut out = Vec::new();+ for toolkit in FIXTURE_TOOLKITS {+ let path = repo_root().join(format!("tests/fixtures/composio_{toolkit}.json"));+ let raw = std::fs::read_to_string(&path).with_context(|| format!("read {path:?}"))?;+ let parsed: serde_json::Value = serde_json::from_str(&raw)?;+ let tools = parsed+ .pointer("/result/result/tools")+ .and_then(|t| t.as_array())+ .with_context(|| format!("missing /result/result/tools in {path:?}"))?;+ for tool in tools {+ let name = tool+ .pointer("/function/name")+ .and_then(|n| n.as_str())+ .unwrap_or_default()+ .to_string();+ if name.is_empty() {+ continue;+ }+ out.push(CatalogueEntry {+ name,+ family: Some((*toolkit).to_string()),+ description: tool+ .pointer("/function/description")+ .and_then(|d| d.as_str())+ .unwrap_or_default()+ .to_string(),+ parameters: tool+ .pointer("/function/parameters")+ .cloned()+ .unwrap_or_else(|| serde_json::json!({"type": "object"})),+ });+ }+ }+ Ok(out)+}++fn load_intents(path: &PathBuf) -> Result<Vec<IntentRow>> {+ let raw = std::fs::read_to_string(path).with_context(|| format!("read {path:?}"))?;+ let mut rows = Vec::new();+ for (i, line) in raw.lines().enumerate() {+ let line = line.trim();+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ let row: IntentRow =+ serde_json::from_str(line).with_context(|| format!("{path:?}:{} bad row", i + 1))?;+ rows.push(row);+ }+ Ok(rows)+}++use openhuman_core::agent::tinyagents::discovery::OverlapRanker;++#[cfg(feature = "jev")]+fn jev_ranker(+ retrieval_k: usize,+ family: bool,+ embedding: bool,+) -> Option<(Arc<dyn ToolRanker>, Arc<tinytools_jev::JevRanker>)> {- use tinytools_jev::{ClientConfig, JevRanker};++ use openhuman_tinyhumans::jev::TinyJevEvaluator;++ use tinyjevclient::{Client, ClientConfig};++ use tinytools_jev::JevRanker;+ let client = if let Ok(key) = std::env::var("OPENHUMAN_BACKEND_API_KEY") {+ let mut client = ClientConfig::tinyhumans_openrouter(key);+ if let Ok(base) = std::env::var("BACKEND_URL") {+ if !base.trim().is_empty() {+ client.base_url = base.trim().trim_end_matches('/').to_string();+ }+ }+ client+ } else if let Ok(key) = std::env::var("TYPESAFE_API_KEY") {+ ClientConfig::new(key)+ } else {+ // No key in the environment: rank exactly as the product does, with+ // the process's signed-in TinyHumans session resolved per search.+ eprintln!("jev: no key in the environment; using the signed-in TinyHumans session");+ return None;+ };- let ranker = JevRanker::from_config(- client,++ let client = Client::new(client).ok()?;++ let evaluator = Arc::new(TinyJevEvaluator::new(client).with_deadline(Duration::from_secs(20)));++ let ranker = Arc::new(JevRanker::new(++ evaluator,+ jev_config(retrieval_k, family, embedding),- )- .ok()?;- let ranker = Arc::new(ranker);++ ));+ Some((ranker.clone() as Arc<dyn ToolRanker>, ranker))+}++#[cfg(feature = "jev")]+fn jev_config(retrieval_k: usize, family: bool, embedding: bool) -> tinytools_jev::JevRankerConfig {+ use tinytools_jev::{JevRankerConfig, JevStrategy};- let mut config = JevRankerConfig::new()- .with_retrieval_k(retrieval_k)- .with_timeout(Duration::from_secs(20));++ let mut config = JevRankerConfig::new().with_retrieval_k(retrieval_k);+ if family {+ config = config.with_strategy(JevStrategy::FamilyThenDecide);+ }+ if embedding {+ config = config.with_retriever(embedding_retriever());+ }+ config+}++#[cfg(not(feature = "jev"))]+fn jev_ranker(+ _retrieval_k: usize,+ _family: bool,+ _embedding: bool,+) -> Option<(Arc<dyn ToolRanker>, Arc<()>)> {+ None+}++/// The process's configured embedding provider as a `ToolRanker`, with its+/// catalogue cache in the scratch workspace so repeated runs embed only the+/// intents.+fn embedding_retriever() -> Arc<dyn ToolRanker> {+ use openhuman_core::agent::tinyagents::discovery::EmbeddingToolRanker;+ let config = tokio::task::block_in_place(|| {+ tokio::runtime::Handle::current().block_on(openhuman_core::config::Config::load_or_init())+ })+ .expect("load config for the embedding provider");+ let provider =+ openhuman_core::inference::embedding_host::default_embedding_provider_with_config(&config);+ if !EmbeddingToolRanker::provider_is_usable(provider.as_ref()) {+ eprintln!(+ "embedding: provider `{}` cannot embed; the bench retriever stays bm25",+ provider.name()+ );+ return Arc::new(Bm25Ranker);+ }+ eprintln!("embedding: {} / {}", provider.name(), provider.model_id());+ Arc::new(+ EmbeddingToolRanker::new(provider).with_disk_cache(+ repo_root().join("target").join("tool_search_bench_embeddings.json"),+ ),+ )+}++fn family_of<'a>(catalogue: &'a [CatalogueEntry], name: &str) -> &'a str {+ catalogue+ .iter()+ .find(|e| e.name == name)+ .and_then(|e| e.family.as_deref())+ .unwrap_or("core")+}++#[tokio::main]+async fn main() -> Result<()> {+ let args = parse_args();+ let mut catalogue = core_catalogue()?;+ let core_count = catalogue.len();+ catalogue.extend(composio_catalogue()?);+ eprintln!(+ "catalogue: {} tools ({} core, {} composio actions)",+ catalogue.len(),+ core_count,+ catalogue.len() - core_count+ );+ if args.dump_catalogue {+ for entry in &catalogue {+ println!(+ "{}\t{}\t{}",+ entry.name,+ entry.family.as_deref().unwrap_or("-"),+ entry.description.chars().take(100).collect::<String>()+ );+ }+ return Ok(());+ }+ let names: std::collections::HashSet<&str> =+ catalogue.iter().map(|e| e.name.as_str()).collect();+ let rows = load_intents(&args.intents)?;+ for row in &rows {+ if row.expected != "none" && !names.contains(row.expected.as_str()) {+ anyhow::bail!(+ "intent {:?} expects `{}`, which is not in the catalogue",+ row.intent,+ row.expected+ );+ }+ }+ let candidates: Vec<RankCandidate> = catalogue.iter().map(CatalogueEntry::candidate).collect();++ let mut rankers: Vec<(String, Arc<dyn ToolRanker>)> = Vec::new();+ let want = |k: &str| args.ranker == "all" || args.ranker == k;+ if want("bm25") {+ rankers.push(("bm25".into(), Arc::new(Bm25Ranker)));+ }+ if want("overlap") {+ rankers.push(("overlap".into(), Arc::new(OverlapRanker)));+ }+ if want("embedding") && args.embedding {+ rankers.push(("embedding".into(), embedding_retriever()));+ }+ if want("jev") {+ match jev_ranker(args.retrieval_k, args.family, args.embedding) {+ Some((ranker, _)) => rankers.push(("jev".into(), ranker)),+ None => {+ #[cfg(feature = "jev")]+ {+ let ranker = openhuman_tinyhumans::jev::TinyHumansJevRanker::with_config(+ jev_config(args.retrieval_k, args.family, args.embedding),+ );+ rankers.push(("jev".into(), Arc::new(ranker)));+ }+ #[cfg(not(feature = "jev"))]+ eprintln!("jev: skipped (build with the `jev` feature)");+ }+ }+ }++ let mut reports = Vec::new();+ for (kind, ranker) in &rankers {+ let mut report = RankerReport {+ ranker: if kind == "jev" {+ format!(+ "jev({}{})",+ if args.family { "family" } else { "retrieve" },+ if args.embedding { "+embedding" } else { "+bm25" }+ )+ } else {+ kind.clone()+ },+ rows: rows.len(),+ ..RankerReport::default()+ };+ for row in &rows {+ let started = Instant::now();+ let result = ranker+ .rank(&row.intent, &RankContext::empty(), &candidates, args.top_k)+ .await;+ report+ .latency_ms+ .push(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX));+ let hits = match result {+ Ok(hits) => hits,+ Err(error) => {+ report.errors += 1;+ eprintln!("{kind}: {:?} -> {error}", row.intent);+ Vec::new()+ }+ };+ let got: Vec<String> = hits.iter().map(|h| h.key.clone()).collect();+ if row.expected == "none" {+ report.none_rows += 1;+ if !got.is_empty() {+ report.needless += 1;+ }+ continue;+ }+ report.labelled += 1;+ let source = if catalogue+ .iter()+ .any(|e| e.name == row.expected && e.family.as_deref().is_some_and(|f| FIXTURE_TOOLKITS.contains(&f)))+ {+ "composio"+ } else {+ "core"+ };+ let bucket = report.by_source.entry(source.to_string()).or_default();+ bucket.0 += 1;+ let hit1 = got.first().map(String::as_str) == Some(row.expected.as_str());+ let hit3 = got.iter().any(|g| g == &row.expected);+ if hit1 {+ report.top1 += 1;+ bucket.1 += 1;+ }+ if hit3 {+ report.top3 += 1;+ bucket.2 += 1;+ } else if args.misses {+ report.misses.push(Miss {+ intent: row.intent.clone(),+ expected: row.expected.clone(),+ got: got.clone(),+ });+ }- let retrieved = Bm25Ranker::rank_sync(&candidates, &row.intent, args.retrieval_k);- if retrieved.iter().any(|h| h.key == row.expected) {++ // Recall of the retriever Jev sits on: the embedding index when++ // `--embedding`, BM25 otherwise. For the standalone rankers it is++ // their own recall at `retrieval_k`.++ let retrieved: Vec<String> = if kind == "jev" && !args.embedding || kind == "bm25" {++ Bm25Ranker::rank_sync(&candidates, &row.intent, args.retrieval_k)++ .into_iter()++ .map(|h| h.key)++ .collect()++ } else {++ let retriever: Arc<dyn ToolRanker> = if kind == "jev" {++ embedding_retriever()++ } else {++ ranker.clone()++ };++ retriever++ .rank(&row.intent, &RankContext::empty(), &candidates, args.retrieval_k)++ .await++ .map(|hits| hits.into_iter().map(|h| h.key).collect())++ .unwrap_or_default()++ };++ if retrieved.iter().any(|h| h == &row.expected) {+ report.recall_at_20 += 1;+ report.by_source.get_mut(source).map(|b| b.3 += 1);+ }+ let expected_family = row+ .family+ .clone()+ .unwrap_or_else(|| family_of(&catalogue, &row.expected).to_string());+ let got_family = got+ .first()+ .map(|g| family_of(&catalogue, g).to_string())+ .unwrap_or_else(|| "(none)".to_string());+ *report+ .confusion+ .entry(expected_family)+ .or_default()+ .entry(got_family)+ .or_default() += 1;+ }+ reports.push(report);+ }++ #[cfg(feature = "jev")]+ if let Some(report) = reports.iter_mut().find(|r| r.ranker == "jev") {+ // Tokens and cost: one detailed pass over the labelled rows so the+ // number is the provider's own `usage`, not an estimate.+ if let Some((_, detailed)) = jev_ranker(args.retrieval_k, args.family, args.embedding) {+ let mut tokens = 0_u64;+ let mut counted = 0_u64;+ for row in rows.iter().take(25) {+ if let Ok(ranking) = detailed+ .rank_detailed(&row.intent, &RankContext::empty(), &candidates, args.top_k)+ .await+ {+ if let Some(t) = ranking.input_tokens {+ tokens += t;+ counted += 1;+ }+ }+ }+ if counted > 0 {+ let per_search = tokens as f64 / counted as f64;+ report.input_tokens = per_search.round() as u64;+ report.usd = per_search * JEV_USD_PER_MILLION_INPUT / 1_000_000.0;+ }+ }+ }+- println!("| ranker | rows | top-1 | top-3 | recall@{} (bm25) | needless (of {}) | errors | p50 ms | p95 ms | tokens/search | USD/search |",++ println!("| ranker | rows | top-1 | top-3 | retriever recall@{} | needless (of {}) | errors | p50 ms | p95 ms | tokens/search | USD/search |",+ args.retrieval_k,+ reports.first().map_or(0, |r| r.none_rows));+ println!("|---|---|---|---|---|---|---|---|---|---|---|");+ for r in &reports {+ let pct = |n: usize, d: usize| {+ if d == 0 {+ "n/a".to_string()+ } else {+ format!("{:.1}%", 100.0 * n as f64 / d as f64)+ }+ };+ println!(+ "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",+ r.ranker,+ r.rows,+ pct(r.top1, r.labelled),+ pct(r.top3, r.labelled),+ pct(r.recall_at_20, r.labelled),+ r.needless,+ r.errors,+ r.percentile(0.5),+ r.percentile(0.95),+ if r.input_tokens == 0 { "-".to_string() } else { r.input_tokens.to_string() },+ if r.usd == 0.0 { "-".to_string() } else { format!("${:.5}", r.usd) },+ );+ }+ println!("\n| ranker | source | labelled | top-1 | top-3 | recall@{} |", args.retrieval_k);+ println!("|---|---|---|---|---|---|");+ for r in &reports {+ for (source, (n, t1, t3, rk)) in &r.by_source {+ let pct = |x: usize| if *n == 0 { "n/a".to_string() } else { format!("{:.1}%", 100.0 * x as f64 / *n as f64) };+ println!("| {} | {} | {} | {} | {} | {} |", r.ranker, source, n, pct(*t1), pct(*t3), pct(*rk));+ }+ }+ for r in &reports {+ println!("\n### {} — top-1 family confusion (expected → got)", r.ranker);+ for (expected, gots) in &r.confusion {+ let line: Vec<String> = gots.iter().map(|(g, n)| format!("{g}:{n}")).collect();+ println!("- {expected}: {}", line.join(", "));+ }+ if args.misses && !r.misses.is_empty() {+ println!("\n### {} — misses", r.ranker);+ for m in &r.misses {+ println!("- {:?} expected `{}` got {:?}", m.intent, m.expected, m.got);+ }+ }+ }+ if let Some(out) = &args.json_out {+ std::fs::write(out, serde_json::to_string_pretty(&reports)?)?;+ eprintln!("wrote {out:?}");+ }+ Ok(())+}diff --cc crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 5a9ac6797e,2718088f54..95a2108ebe--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@@ -144,10 -147,12 +147,16 @@@ pub(super) fn assemble_turn_harnesslet mut policy = run_policy_for(max_iterations, deterministic_cacheable);let route_fallback = routes::route_fallback_policy(model);policy.fallback = route_fallback.clone();+ // Tool discovery: the harness advertises its `tool_search` bridge over the+ // `Deferred` registrations the allowlist admits, ranked by whatever the+ // process installed (`agent::tinyagents::discovery`).+ policy.discovery = super::discovery::discovery_policy();+ policy.tool_dialect = tool_dialect;+ tracing::debug!(+ model,+ ?tool_dialect,+ "[models] turn harness tool dialect pinned from the session"+ );tracing::debug!(model,fallback_chain = ?route_fallback.as_ref().map(|f| &f.models),diff --cc crates/openhuman-tinyhumans/Cargo.tomlindex dc7372aae7,a3e1ff9683..081e79cbda--- a/crates/openhuman-tinyhumans/Cargo.toml+++ b/crates/openhuman-tinyhumans/Cargo.toml@@@ -12,12 -12,7 +12,12 @@@ publish = fals# This crate adds no gates of its own: it is the layer that *connects* an# embed runtime to the TinyHumans backend, not a feature surface.[features]-default = ["openhuman-embed/default"]+# `jev` is this crate's one gate of its own: the Jev-backed `tool_search`+# ranker (`tinytools-jev` over the TinyHumans System One proxy). On by+# 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"]@@@ -50,12 -45,6 +50,16 @@@ openhuman-core = { path = "../openhuman# it. `default-features = false` drops the Socket.IO client; realtime stays# on the core's own `platform::socket` transport.tinyhumans-sdk = { path = "../../vendor/tinyhumans-sdk", default-features = false }+# The `tool_search` ranker backed by TypeSafe's Jev, reached through the+# backend's `/agent-integrations/openrouter/systemone` proxy with the same+# credential every other backend call uses. Same vendored tree as the core's+# `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 transport behind the Jev evaluator; `tinytools-jev` is++# transport-free and this crate owns the wire, the credential and the deadline.++# Consumed by pinned revision, as that crate's README asks.++tinyjevclient = { git = "https://github.com/tinyhumansai/tinyjevclient", rev = "84b3983c7e1e14f7515658ceafabb6c4e7967c94", optional = true }anyhow = "1"async-trait = "0.1"chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }diff --cc crates/openhuman-tinyhumans/src/jev/evaluator.rsindex 0000000000,0000000000..c0e3840812new file mode 100644--- /dev/null+++ b/crates/openhuman-tinyhumans/src/jev/evaluator.rs@@@ -1,0 -1,0 +1,160 @@@++//! [`TinyJevEvaluator`]: the `tinytools_jev::JevEvaluator` over++//! `tinyjevclient`, reaching Jev through the TinyHumans System One proxy.++//!++//! `tinytools-jev` decides *what* to ask — the options, the intent, the++//! family-stage wording — and this evaluator owns the wire: one `Choice`++//! over the options plus a `needs_tool` `Noul`, the credential, the++//! per-attempt timeout and retries the client applies, and a deadline of++//! its own so a slow answer becomes a fallback rather than a stalled turn.++++use std::{collections::BTreeMap, time::Duration};++++use serde_json::{json, Value};++use tinyjevclient::{++ Answer, Choice, Client, Error as JevError, EvaluationFailure, EvaluationRequest, Noul,++ NoulCriteria, Question,++};++use tinytools::RankError;++use tinytools_jev::{JevDecision, JevEvaluator, JevRequest};++++/// Question id of the tool `Choice`.++const TOOL_QUESTION: &str = "tool";++/// Question id of the needs-a-tool `Noul`.++const NEEDS_TOOL_QUESTION: &str = "needs_tool";++/// Default deadline for one evaluation, on top of the client's own++/// per-attempt timeout and retries.++const DEFAULT_DEADLINE: Duration = Duration::from_secs(3);++++/// Evaluates `tinytools_jev` requests against Jev through `tinyjevclient`.++#[derive(Debug, Clone)]++pub struct TinyJevEvaluator {++ client: Client,++ deadline: Duration,++}++++impl TinyJevEvaluator {++ /// An evaluator over `client` with the default 3 s deadline.++ pub fn new(client: Client) -> Self {++ Self {++ client,++ deadline: DEFAULT_DEADLINE,++ }++ }++++ /// Sets the per-evaluation deadline.++ pub fn with_deadline(mut self, deadline: Duration) -> Self {++ self.deadline = deadline;++ self++ }++++ fn build(request: &JevRequest) -> EvaluationRequest {++ let mut state = json!({ "request": request.intent });++ if !request.recent_turns.is_empty() {++ if 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 criteria: BTreeMap<String, Option<Value>> = request++ .options++ .iter()++ .map(|option| (option.key.clone(), Some(json!(option.description))))++ .collect();++ let instructions = request.instructions.clone().unwrap_or_else(|| {++ "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."++ .to_owned()++ });++ EvaluationRequest {++ state,++ model: request.model.clone(),++ 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."++ ),++ }),++ }),++ ),++ ]),++ }++ }++}++++fn map_failure(failure: EvaluationFailure) -> RankError {++ match failure.error {++ JevError::InvalidRequest { reason } | JevError::InvalidConfig { reason } => {++ RankError::invalid_input(reason)++ }++ JevError::Timeout => RankError::Timeout,++ // `Display` on every variant is credential-free by the client's++ // contract; the transport source is dropped, not printed.++ other => RankError::backend(format!("{other} after {} attempt(s)", failure.attempts)),++ }++}++++#[async_trait::async_trait]++impl JevEvaluator for TinyJevEvaluator {++ async fn evaluate(&self, request: &JevRequest) -> Result<JevDecision, RankError> {++ let wire = Self::build(request);++ let result = tokio::time::timeout(self.deadline, self.client.evaluate(&wire))++ .await++ .map_err(|_elapsed| RankError::Timeout)?++ .map_err(map_failure)?;++ let Some(Answer::Choice(choice)) = result.response.answers.get(TOOL_QUESTION) else {++ return Err(RankError::backend(++ "response has no choice answer for `tool`",++ ));++ };++ let needs_tool = match result.response.answers.get(NEEDS_TOOL_QUESTION) {++ Some(Answer::Noul(noul)) => Some(noul.noul),++ _ => None,++ };++ log::debug!(++ "[tool-search] jev evaluated {} option(s) (confidence={:.2} needs_tool={:?} latency_ms={} attempts={} input_tokens={:?})",++ request.options.len(),++ choice.confidence,++ needs_tool,++ result.latency.as_millis(),++ result.attempts,++ result.response.usage.input_tokens,++ );++ Ok(JevDecision {++ probabilities: choice.probabilities.clone(),++ choice_confidence: choice.confidence,++ needs_tool,++ input_tokens: result.response.usage.input_tokens,++ attempts: result.attempts,++ })++ }++}++++#[cfg(test)]++#[path = "evaluator_tests.rs"]++mod tests;diff --cc crates/openhuman-tinyhumans/src/jev/evaluator_tests.rsindex 0000000000,0000000000..dded49826fnew file mode 100644--- /dev/null+++ b/crates/openhuman-tinyhumans/src/jev/evaluator_tests.rs@@@ -1,0 -1,0 +1,73 @@@++use tinytools_jev::JevOption;++++use super::*;++++fn request(instructions: Option<&str>) -> JevRequest {++ JevRequest {++ intent: "ping alex".into(),++ recent_turns: vec!["earlier turn".into()],++ options: vec![++ JevOption {++ key: "SLACK_SEND_MESSAGE".into(),++ description: "send a 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 builds_one_choice_and_one_noul_from_the_request() {++ let wire = TinyJevEvaluator::build(&request(None));++ assert_eq!(wire.model, "jev-latest");++ assert_eq!(wire.state["request"], "ping alex");++ assert_eq!(wire.state["recent_user_turns"][0], "earlier turn");++ assert_eq!(wire.questions.len(), 2);++ match wire.questions.get("tool") {++ Some(Question::Choice(choice)) => {++ assert_eq!(choice.criteria.len(), 2);++ assert!(choice.instructions.as_str().unwrap().starts_with("Which tool"));++ }++ other => panic!("expected a choice, got {other:?}"),++ }++ assert!(matches!(++ wire.questions.get("needs_tool"),++ Some(Question::Noul(_))++ ));++}++++#[test]++fn request_instructions_replace_the_default_wording() {++ let wire = TinyJevEvaluator::build(&request(Some("Which group of tools applies?")));++ match wire.questions.get("tool") {++ Some(Question::Choice(choice)) => {++ assert_eq!(choice.instructions, json!("Which group of tools applies?"));++ }++ other => panic!("expected a choice, got {other:?}"),++ }++}++++#[test]++fn failures_map_without_leaking_the_key() {++ let failure = EvaluationFailure {++ error: JevError::Authentication,++ attempts: 2,++ latency: Duration::from_millis(5),++ };++ let text = map_failure(failure).to_string();++ assert!(text.contains("authentication failed"), "{text}");++ assert!(text.contains("2 attempt(s)"), "{text}");++ assert!(matches!(++ map_failure(EvaluationFailure {++ error: JevError::Timeout,++ attempts: 1,++ latency: Duration::ZERO,++ }),++ RankError::Timeout++ ));++}diff --cc crates/openhuman-tinyhumans/src/jev/mod.rsindex 963df39f6b,0000000000..aca893176bmode 100644,000000..100644--- a/crates/openhuman-tinyhumans/src/jev/mod.rs+++ b/crates/openhuman-tinyhumans/src/jev/mod.rs@@@ -1,33 -1,0 +1,35 @@@+//! The Jev-backed `tool_search` ranker for a TinyHumans-connected core.+//!+//! The core's harness advertises a `tool_search` bridge over every deferred+//! 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+//! `/agent-integrations/openrouter/systemone` proxy with the same credential+//! every other backend call uses.+//!+//! 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+//! current user. A process with no credential answers with an error the+//! harness turns into a BM25 fallback, so `auto` costs nothing when signed+//! 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::TinyJevEvaluator;+pub use ranker::TinyHumansJevRanker;++use std::sync::Arc;++use openhuman_core::agent::tinyagents::discovery::install_tool_ranker;++/// Install the Jev ranker as the process-wide `tool_search` ranker.+///+/// Idempotent; the core replaces the previous ranker in place.+pub fn install_jev_ranker() -> Arc<TinyHumansJevRanker> {+ let ranker = Arc::new(TinyHumansJevRanker::new());+ install_tool_ranker(ranker.clone());+ ranker+}diff --cc crates/openhuman-tinyhumans/src/jev/ranker.rsindex a3ae303661,0000000000..fa76c9e844mode 100644,000000..100644--- a/crates/openhuman-tinyhumans/src/jev/ranker.rs+++ b/crates/openhuman-tinyhumans/src/jev/ranker.rs@@@ -1,214 -1,0 +1,224 @@@+//! [`TinyHumansJevRanker`]: a `ToolRanker` that resolves the process's+//! TinyHumans credential on every search and ranks through Jev.++use std::{+ collections::hash_map::DefaultHasher,+ hash::{Hash, Hasher},+ sync::Mutex,+};++use std::{future::Future, pin::Pin, sync::Arc};++use openhuman_core::agent::tinyagents::discovery::EmbeddingToolRanker;+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::{Client, ClientConfig};++use tinytools_jev::{JevRanker, JevRankerConfig, JevStrategy};++++use super::evaluator::TinyJevEvaluator;++/// 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+/// process-global load); a test hands in a fixed one.+pub type ConfigLoader = Arc<+ dyn Fn() -> Pin<Box<dyn Future<Output = Result<Config, String>> + Send>> + Send + Sync,+>;++/// A [`JevRanker`] bound to whichever credential and backend the process has+/// at search time.+pub struct TinyHumansJevRanker {+ config: JevRankerConfig,+ load_config: ConfigLoader,+ cached: Mutex<Option<Cached>>,+}++struct Cached {+ fingerprint: u64,+ ranker: JevRanker,+ /// The retriever inside `ranker`, kept so its catalogue embeddings+ /// survive a credential change.+ retriever: Arc<dyn ToolRanker>,+}++impl std::fmt::Debug for TinyHumansJevRanker {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("TinyHumansJevRanker")+ .field("config", &self.config)+ .finish_non_exhaustive()+ }+}++impl Default for TinyHumansJevRanker {+ fn default() -> Self {+ Self::new()+ }+}++impl TinyHumansJevRanker {- /// A ranker with `tinytools-jev`'s defaults: BM25 retrieval to 20, one- /// Jev decision, a 3 s deadline.++ /// A ranker with the product defaults: family-then-decide (the++ /// evaluator picks the toolkit or pack, then the tool), the process's++ /// embedding provider as the retriever for any family too large for one++ /// choice, a 3 s deadline per evaluation.+ pub fn new() -> Self {- Self::with_config(JevRankerConfig::new())++ Self::with_config(JevRankerConfig::new().with_strategy(JevStrategy::FamilyThenDecide))+ }++ /// A ranker with an explicit `tinytools-jev` configuration.+ pub fn with_config(config: JevRankerConfig) -> Self {+ Self {+ config,+ load_config: Arc::new(|| {+ Box::pin(openhuman_core::config::ops::load_config_with_timeout())+ }),+ cached: Mutex::new(None),+ }+ }++ /// Reads the config through `loader` instead of the core's read path.+ pub fn with_config_loader(mut self, loader: ConfigLoader) -> Self {+ self.load_config = loader;+ self+ }++ /// The `JevRanker` for the current credential and backend, built or+ /// reused.+ ///+ /// Reads the config and credential fresh each time: the cost is a config+ /// load, which a `tool_search` (one model round trip plus a network call)+ /// dwarfs, and the benefit is that sign-in, sign-out and a backend URL+ /// change are all honoured by the next search.+ async fn current(&self) -> Result<JevRanker, RankError> {+ let config = (self.load_config)()+ .await+ .map_err(|error| RankError::Backend {+ reason: format!("config unavailable: {error}"),+ })?;+ let credential = resolve_backend_credential(&config).map_err(|reason| {+ // The message names what is missing, never a secret.+ RankError::Backend {+ reason: format!("no TinyHumans credential ({reason})"),+ }+ })?;+ let base_url = effective_backend_api_url(&config.api_url);+ let fingerprint = fingerprint(credential.secret(), &base_url);++ let mut cached = self+ .cached+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if let Some(entry) = cached.as_ref().filter(|entry| entry.fingerprint == fingerprint) {+ return Ok(entry.ranker.clone());+ }- let mut client = ClientConfig::tinyhumans_openrouter(credential.into_secret());- client.base_url = base_url.clone();++ let mut client_config = ClientConfig::tinyhumans_openrouter(credential.into_secret());++ client_config.base_url = base_url.clone();++ let client = Client::new(client_config)++ .map_err(|error| RankError::invalid_input(error.to_string()))?;++ let evaluator: Arc<dyn tinytools_jev::JevEvaluator> =++ Arc::new(TinyJevEvaluator::new(client));+ // The retriever is the process's embedding provider when it can+ // embed (the same one memory recall uses), so a family larger than+ // one Jev Choice is cut by meaning, not by shared words. Reused+ // across rebuilds so the catalogue is embedded once per process.+ let retriever: Arc<dyn ToolRanker> = match cached.as_ref() {+ Some(entry) => entry.retriever.clone(),+ None => retriever_for(&config),+ };- let ranker = JevRanker::from_config(- client,++ let ranker = JevRanker::new(++ evaluator,+ self.config.clone().with_retriever(retriever.clone()),- )?;++ );+ log::info!(+ "[tool-search] jev ranker bound to backend {} ({})",+ openhuman_core::util::redact::redact_url_for_log(&base_url),+ if fingerprint_changed(cached.as_ref(), fingerprint) {+ "credential or backend changed"+ } else {+ "first search"+ }+ );+ *cached = Some(Cached {+ fingerprint,+ ranker: ranker.clone(),+ retriever,+ });+ Ok(ranker)+ }+}++/// The semantic retriever for `config`'s embedding provider, or BM25 when+/// the provider cannot embed (`none`, or a managed provider with no route).+fn retriever_for(config: &Config) -> Arc<dyn ToolRanker> {+ let provider = openhuman_core::inference::embedding_host::default_embedding_provider_with_config(+ config,+ );+ if !EmbeddingToolRanker::provider_is_usable(provider.as_ref()) {+ log::info!(+ "[tool-search] embedding provider `{}` cannot embed; retrieving with bm25",+ provider.name()+ );+ return Arc::new(tinytools::Bm25Ranker);+ }+ log::info!(+ "[tool-search] retrieving with embeddings ({} / {})",+ provider.name(),+ provider.model_id()+ );+ Arc::new(+ EmbeddingToolRanker::new(provider).with_disk_cache(+ config+ .workspace_dir+ .join("cache")+ .join("tool_search_embeddings.json"),+ ),+ )+}++fn fingerprint(secret: &str, base_url: &str) -> u64 {+ let mut hasher = DefaultHasher::new();+ secret.hash(&mut hasher);+ base_url.hash(&mut hasher);+ hasher.finish()+}++fn fingerprint_changed(cached: Option<&Cached>, fingerprint: u64) -> bool {+ cached.is_some_and(|entry| entry.fingerprint != fingerprint)+}++#[async_trait::async_trait]+impl ToolRanker for TinyHumansJevRanker {+ fn kind(&self) -> &'static str {+ JevRanker::KIND+ }++ async fn rank(+ &self,+ intent: &str,+ context: &RankContext,+ candidates: &[RankCandidate],+ limit: usize,+ ) -> Result<Vec<RankHit>, RankError> {+ let ranker = self.current().await?;+ let ranking = ranker+ .rank_detailed(intent, context, candidates, limit)+ .await?;+ log::debug!(- "[tool-search] jev ranked {} of {} shortlisted (choice_confidence={:.2} needs_tool={:?} none={:.2} latency_ms={} attempts={} input_tokens={:?})",++ "[tool-search] jev ranked {} of {} shown (families={:?} choice_confidence={:.2} needs_tool={:?} none={:.2} latency_ms={} attempts={} input_tokens={:?})",+ ranking.hits.len(),+ ranking.shortlisted,++ ranking.families,+ ranking.choice_confidence,+ ranking.needs_tool,+ ranking.none_probability,+ ranking.latency.as_millis(),+ ranking.attempts,+ ranking.input_tokens,+ );+ Ok(ranking.hits)+ }+}++#[cfg(test)]+#[path = "ranker_tests.rs"]+mod tests;diff --cc vendor/tinyagentsindex ae48b2c34f,68b0eb0abc..e5c2411b78--- a/vendor/tinyagents+++ b/vendor/tinyagents@@@ -1,1 -1,1 +1,1 @@@- Subproject commit ae48b2c34f7e5e7b84f78ef2693e37ed1ac8c5c8-Subproject commit 68b0eb0abc490541979d9fa2d869f7b4ee0b2189++Subproject commit e5c2411b78c55370a4c295d2c1f49c5b1b3884b1