Skip to content

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

refactor(core): replace custom search with bm25 utility

Steven Enamakel32b03cfa2230
diff --git a/crates/openhuman-core/src/skills/search.rs b/crates/openhuman-core/src/skills/search.rs
index 78dfcf5a4f..f3d27a4544 100644
--- a/crates/openhuman-core/src/skills/search.rs
+++ b/crates/openhuman-core/src/skills/search.rs
@@ -39,7 +39,7 @@ use serde_json::{json, Value};
use super::ops_discover::{discover_workflows, is_workspace_trusted};
use super::ops_types::Workflow;
use crate::config::Config;
-use crate::util::bm25::Bm25Index;
+use tinytools::rank::Bm25Index;
use tinytools::{Tool, ToolResult};
/// How many matches a search returns when the caller does not say.
diff --git a/crates/openhuman-core/src/tools/impl/meta/deferred.rs b/crates/openhuman-core/src/tools/impl/meta/deferred.rs
new file mode 100644
index 0000000000..00208f4e33
--- /dev/null
+++ b/crates/openhuman-core/src/tools/impl/meta/deferred.rs
@@ -0,0 +1,88 @@
+//! The host's half of [`ToolExposure::Deferred`](tinytools::ToolExposure):
+//! which registered tools leave the wire, so the harness can advertise
+//! `tool_search` in their place.
+//!
+//! # Why this exists
+//!
+//! Tool schemas are a fixed cost paid on every request. Measured on the
+//! orchestrator with an empty workspace, they were 45,199 bytes against 33,808
+//! bytes of system prompt; on a signed-in workspace with Composio connected
+//! they reached ~112 KB. Most of that is tools the model reaches for on a
+//! handful of turns a week.
+//!
+//! `Deferred` takes such a tool off the wire without removing the capability.
+//! The tinyagents harness owns the other half of that bargain — the intrinsic
+//! `tool_search` / `tool_call` bridge, the BM25 catalogue, and the pluggable
+//! ranker a decision model plugs into (`tool::discover`). This host used to
+//! register a `tool_search` of its own, which the harness honoured over its
+//! intrinsic; that tool could *find* a deferred tool but the turn allowlist
+//! never registered it, so the find was unusable. Now the host only decides
+//! what is deferred and hands the harness both sets: the advertised names as
+//! the wire surface and the deferred names as still-callable registrations.
+//!
+//! # Why not the toolpack mechanism
+//!
+//! Packs answer a different question. A pack is a *group* withheld by a config
+//! posture, recovered through `use_skill`, and its membership is compiled in
+//! precisely so config cannot move a dangerous tool out of the reviewed
+//! surface. That is the right shape for compressing a belt an agent owns.
+//!
+//! Deferral is per-tool and is a property of the tool: `stock_quote` is rarely
+//! needed whoever is running the host. The two compose — a deferred tool inside
+//! a withheld pack is simply absent twice — and neither can widen the surface,
+//! because both only ever subtract from a set the belt and the security policy
+//! already decided.
+
+use std::collections::HashSet;
+
+use tinytools::{Tool, ToolExposure};
+
+/// The name an agent lists in `[tools] named` to opt a hand-written belt into
+/// discovery. It is not a registered tool: the harness advertises its own
+/// intrinsic `tool_search` whenever a run has a deferred tool, so the name in
+/// a belt is a request for that, and the builder strips it from the allowlist.
+pub const TOOL_SEARCH_NAME: &str = "tool_search";
+
+/// Remove every [`ToolExposure::Deferred`] and [`ToolExposure::Hidden`] tool
+/// from an agent's advertised set, returning the names of the deferred ones so
+/// the caller can keep them registered.
+///
+/// Hidden tools are dropped and **not** returned: they are not searchable
+/// either, by definition.
+pub fn strip_deferred_from_visible(
+ visible: &mut HashSet<String>,
+ tools: &[Box<dyn Tool>],
+) -> HashSet<String> {
+ let mut deferred = HashSet::new();
+ for tool in tools {
+ let name = tool.name();
+ if !visible.contains(name) {
+ continue;
+ }
+ match tool.exposure() {
+ ToolExposure::Direct => {}
+ ToolExposure::Deferred => {
+ visible.remove(name);
+ deferred.insert(name.to_string());
+ }
+ ToolExposure::Hidden => {
+ visible.remove(name);
+ }
+ }
+ }
+ deferred
+}
+
+/// Every [`ToolExposure::Deferred`] tool in `tools`, by name — the catalogue a
+/// belt that opted into discovery can reach whether or not it named them.
+pub fn deferred_tool_names(tools: &[Box<dyn Tool>]) -> HashSet<String> {
+ tools
+ .iter()
+ .filter(|tool| tool.exposure() == ToolExposure::Deferred)
+ .map(|tool| tool.name().to_string())
+ .collect()
+}
+
+#[cfg(test)]
+#[path = "deferred_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tools/impl/meta/deferred_tests.rs b/crates/openhuman-core/src/tools/impl/meta/deferred_tests.rs
new file mode 100644
index 0000000000..ce0fb786be
--- /dev/null
+++ b/crates/openhuman-core/src/tools/impl/meta/deferred_tests.rs
@@ -0,0 +1,63 @@
+use std::collections::HashSet;
+
+use serde_json::json;
+use tinytools::{Tool, ToolExposure, ToolResult};
+
+use super::{deferred_tool_names, strip_deferred_from_visible};
+
+struct Fake(&'static str, ToolExposure);
+
+#[async_trait::async_trait]
+impl Tool for Fake {
+ fn name(&self) -> &str {
+ self.0
+ }
+ fn description(&self) -> &str {
+ "fake"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ json!({"type": "object"})
+ }
+ fn exposure(&self) -> ToolExposure {
+ self.1
+ }
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("ok"))
+ }
+}
+
+fn tools() -> Vec<Box<dyn Tool>> {
+ vec![
+ Box::new(Fake("direct", ToolExposure::Direct)),
+ Box::new(Fake("deferred", ToolExposure::Deferred)),
+ Box::new(Fake("hidden", ToolExposure::Hidden)),
+ Box::new(Fake("unlisted_deferred", ToolExposure::Deferred)),
+ ]
+}
+
+#[test]
+fn strip_removes_deferred_and_hidden_but_returns_only_deferred() {
+ let mut visible: HashSet<String> = ["direct", "deferred", "hidden"]
+ .into_iter()
+ .map(String::from)
+ .collect();
+ let deferred = strip_deferred_from_visible(&mut visible, &tools());
+ assert_eq!(visible, HashSet::from(["direct".to_string()]));
+ assert_eq!(deferred, HashSet::from(["deferred".to_string()]));
+}
+
+#[test]
+fn strip_ignores_tools_the_belt_never_named() {
+ let mut visible: HashSet<String> = HashSet::from(["direct".to_string()]);
+ let deferred = strip_deferred_from_visible(&mut visible, &tools());
+ assert!(deferred.is_empty());
+ assert_eq!(visible.len(), 1);
+}
+
+#[test]
+fn deferred_tool_names_lists_every_deferred_registration() {
+ assert_eq!(
+ deferred_tool_names(&tools()),
+ HashSet::from(["deferred".to_string(), "unlisted_deferred".to_string()])
+ );
+}
diff --git a/crates/openhuman-core/src/tools/impl/meta/mod.rs b/crates/openhuman-core/src/tools/impl/meta/mod.rs
index 61c4e020ac..02dfb0e4a2 100644
--- a/crates/openhuman-core/src/tools/impl/meta/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/meta/mod.rs
@@ -1,18 +1,18 @@
//! Tools *about* the tool surface itself.
//!
-//! Two members: [`tool_search`], the lookup half of
-//! [`ToolExposure::Deferred`](tinytools::ToolExposure). It sits
-//! in its own family rather than under `system/` because it is not a capability
-//! the host offers the user — it is the model asking what it is able to do.
+//! Two members: [`collapse`], the shared arithmetic behind a collapsed tool
+//! (`memory`, `todo`, `delegate_to`), and [`deferred`], the host's half of
+//! [`ToolExposure::Deferred`](tinytools::ToolExposure) — which registered tools
+//! leave the wire so the harness can advertise its `tool_search` bridge in
+//! their place. They sit in their own family rather than under `system/`
+//! because neither is a capability the host offers the user — it is the model
+//! asking what it is able to do.
pub mod collapse;
-pub mod tool_search;
+pub mod deferred;
pub use collapse::{
any_external_effect, args_without_action, merge_action_schemas, resolve, strictest_permission,
unknown_action_message, CollapsedAction,
};
-pub use tool_search::{
- bind_tool_search_index, strip_deferred_from_visible, ToolSearchHandle, ToolSearchIndex,
- ToolSearchTool, TOOL_SEARCH_NAME,
-};
+pub use deferred::{deferred_tool_names, strip_deferred_from_visible, TOOL_SEARCH_NAME};
diff --git a/crates/openhuman-core/src/tools/impl/meta/tool_search.rs b/crates/openhuman-core/src/tools/impl/meta/tool_search.rs
deleted file mode 100644
index d37939d3ee..0000000000
--- a/crates/openhuman-core/src/tools/impl/meta/tool_search.rs
+++ /dev/null
@@ -1,329 +0,0 @@
-//! `tool_search` — look up a capability whose schema is not on the wire.
-//!
-//! # Why this exists
-//!
-//! Tool schemas are a fixed cost paid on every request. Measured on the
-//! orchestrator with an empty workspace, they were 45,199 bytes against 33,808
-//! bytes of system prompt; on a signed-in workspace with Composio connected
-//! they reached ~112 KB. Most of that is tools the model reaches for on a
-//! handful of turns a week.
-//!
-//! [`ToolExposure::Deferred`] takes such a tool off the wire without removing
-//! the capability, and this is the other half of that bargain: the model can
-//! find it again. A capability the model can neither see nor look up is simply
-//! gone, which is a far worse regression than the tokens it saves.
-//!
-//! # Why not the toolpack mechanism
-//!
-//! Packs answer a different question. A pack is a *group* withheld by a config
-//! posture, recovered through `load_skill`, and its membership is compiled in
-//! precisely so config cannot move a dangerous tool out of the reviewed
-//! surface. That is the right shape for compressing a belt an agent owns.
-//!
-//! Deferral is per-tool and is a property of the tool: `stock_quote` is rarely
-//! needed whoever is running the host. The two compose — a deferred tool inside
-//! a withheld pack is simply absent twice — and neither can widen the surface,
-//! because both only ever subtract from a set the belt and the security policy
-//! already decided.
-//!
-//! # Ranking
-//!
-//! A hand-rolled BM25. Codex uses the `bm25` crate for the same job; this crate
-//! is kernel surface under a dependency-floor ratchet
-//! (`scripts/kernel-floor.limits`), and ~70 lines of arithmetic is a better
-//! trade than a package on the floor of every embedder's build.
-
-use std::sync::{Arc, RwLock};
-
-use anyhow::Result;
-use serde_json::{json, Value};
-
-use crate::util::bm25::Bm25Index;
-use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult, ToolSpec};
-
-/// How many matches a search returns when the caller does not say.
-const DEFAULT_LIMIT: usize = 5;
-/// Ceiling on `limit`, so one call cannot undo the saving by asking for
-/// everything.
-const MAX_LIMIT: usize = 20;
-
-/// One deferred tool, as the index sees it.
-#[derive(Clone, Debug)]
-pub struct SearchableTool {
- pub name: String,
- pub description: String,
- pub parameters: Value,
- /// `name` + `description`, the text the ranker sees.
- searchable: String,
-}
-
-impl SearchableTool {
- pub fn from_spec(spec: &ToolSpec) -> Self {
- Self {
- name: spec.name.clone(),
- description: spec.description.clone(),
- parameters: spec.parameters.clone(),
- searchable: format!("{} {}", spec.name, spec.description),
- }
- }
-}
-
-/// A BM25 index over the deferred tools.
-///
-/// A thin adapter: the ranking lives in [`crate::util::bm25`], which
-/// knows nothing about tools, and this type owns the part that is about tools —
-/// what text is searchable and what a result looks like.
-#[derive(Default, Debug)]
-pub struct ToolSearchIndex {
- tools: Vec<SearchableTool>,
- index: Bm25Index,
-}
-
-impl ToolSearchIndex {
- pub fn build(specs: &[ToolSpec]) -> Self {
- let tools: Vec<SearchableTool> = specs.iter().map(SearchableTool::from_spec).collect();
- let index = Bm25Index::build(
- tools
- .iter()
- .map(|t| (t.name.as_str(), t.searchable.as_str()))
- .collect::<Vec<_>>(),
- );
- Self { tools, index }
- }
-
- pub fn is_empty(&self) -> bool {
- self.tools.is_empty()
- }
-
- pub fn len(&self) -> usize {
- self.tools.len()
- }
-
- /// Rank the index against `query`, best first.
- ///
- /// Only tools scoring above zero are returned. Padding the list out to
- /// `limit` with unrelated tools would spend exactly the tokens this
- /// mechanism exists to save, and would invite the model to call something
- /// that has nothing to do with what it asked for.
- pub fn search(&self, query: &str, limit: usize) -> Vec<&SearchableTool> {
- self.index
- .search(query, limit)
- .into_iter()
- .map(|i| &self.tools[i])
- .collect()
- }
-}
-
-/// Shared handle to the index.
-///
-/// The tool is constructed during registry assembly, before anything knows
-/// which tools will end up deferred — that depends on the agent's belt, which
-/// is resolved later in the session builder. So the tool owns an empty index
-/// and the builder fills it in through [`bind_tool_search_index`], the same
-/// two-step shape `toolpacks::bind_pack_registry` already uses.
-pub type ToolSearchHandle = Arc<RwLock<ToolSearchIndex>>;
-
-/// Look up a deferred capability by description.
-pub struct ToolSearchTool {
- index: ToolSearchHandle,
-}
-
-impl Default for ToolSearchTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl ToolSearchTool {
- pub fn new() -> Self {
- Self {
- index: Arc::new(RwLock::new(ToolSearchIndex::default())),
- }
- }
-}
-
-#[async_trait::async_trait]
-impl Tool for ToolSearchTool {
- fn name(&self) -> &str {
- TOOL_SEARCH_NAME
- }
-
- fn description(&self) -> &str {
- "Find a tool that is not in your tool list. Not every capability this \
- host has is advertised up front; describe what you need in plain words \
- (\"send a calendar invite\", \"read a PDF\") and this returns the \
- matching tools with their full argument schemas, which you can then \
- call directly. Use it before telling the user something is impossible."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "What you need to do, in plain words."
- },
- "limit": {
- "type": "integer",
- "description": format!(
- "How many matches to return (default {DEFAULT_LIMIT}, max {MAX_LIMIT})."
- ),
- "minimum": 1,
- "maximum": MAX_LIMIT
- }
- },
- "required": ["query"]
- })
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::System
- }
-
- /// Exposes the index so [`bind_tool_search_index`] can populate it after
- /// the agent's belt is resolved.
- ///
- /// Erased for the same reason `PackRegistryHandle` is: a `ToolSearchIndex`
- /// is this host's concept, and a vocabulary shared with other hosts has no
- /// business naming it.
- fn host_extension(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
- Some(&self.index)
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Reads a static in-memory index. Calling it cannot change anything,
- // and gating it would put an approval prompt in front of the model
- // merely asking what it is allowed to do.
- PermissionLevel::None
- }
-
- async fn execute(&self, args: Value) -> Result<ToolResult> {
- let query = args
- .get("query")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .trim()
- .to_string();
- if query.is_empty() {
- return Ok(ToolResult::error(
- "tool_search needs a `query` describing what you want to do.",
- ));
- }
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| (n as usize).clamp(1, MAX_LIMIT))
- .unwrap_or(DEFAULT_LIMIT);
-
- let index = self
- .index
- .read()
- .map_err(|_| anyhow::anyhow!("tool search index lock poisoned"))?;
-
- let matches = index.search(&query, limit);
- if matches.is_empty() {
- return Ok(ToolResult::success(format!(
- "No deferred tool matches \"{query}\". {} tools are searchable; \
- everything else you can use is already in your tool list.",
- index.len()
- )));
- }
- let payload: Vec<Value> = matches
- .iter()
- .map(|tool| {
- json!({
- "name": tool.name,
- "description": tool.description,
- "parameters": tool.parameters,
- })
- })
- .collect();
- Ok(ToolResult::success(format!(
- "{} match(es). Call any of these by name, using the parameters shown.\n{}",
- payload.len(),
- serde_json::to_string_pretty(&payload)?
- )))
- }
-}
-
-#[cfg(test)]
-#[path = "tool_search_tests.rs"]
-mod tests;
-
-/// Remove every [`ToolExposure::Deferred`] and [`ToolExposure::Hidden`] tool
-/// from an agent's advertised set, returning the specs of the deferred ones so
-/// the caller can index them.
-///
-/// Hidden tools are dropped and **not** returned: they are not searchable
-/// either, by definition.
-///
-/// `tool_search` itself is never removed, whatever it declares. A search tool
-/// the model cannot see is the one failure mode this whole mechanism cannot
-/// recover from — every deferred capability would be unreachable, silently.
-pub fn strip_deferred_from_visible(
- visible: &mut std::collections::HashSet<String>,
- tools: &[Box<dyn Tool>],
-) -> Vec<ToolSpec> {
- use tinytools::ToolExposure;
-
- let mut deferred = Vec::new();
- for tool in tools {
- let name = tool.name();
- if name == TOOL_SEARCH_NAME || !visible.contains(name) {
- continue;
- }
- match tool.exposure() {
- ToolExposure::Direct => {}
- ToolExposure::Deferred => {
- visible.remove(name);
- deferred.push(tool.spec());
- }
- ToolExposure::Hidden => {
- visible.remove(name);
- }
- }
- }
- deferred
-}
-
-/// The advertised name of [`ToolSearchTool`], as a constant so the carve-out
-/// above and the registration site cannot disagree about it.
-pub const TOOL_SEARCH_NAME: &str = "tool_search";
-
-/// Populate the registry's `tool_search` index with the deferred specs.
-///
-/// Returns `false` when the registry has no `tool_search` — which is not an
-/// error: an agent whose belt defers nothing does not need one, and a build
-/// with the tool compiled out is a legitimate configuration. It **is** worth a
-/// warning when specs were deferred and there is nowhere to index them, because
-/// that combination makes capabilities unreachable.
-pub fn bind_tool_search_index(tools: &[Box<dyn Tool>], deferred: Vec<ToolSpec>) -> bool {
- let handle = tools.iter().find_map(|tool| {
- if tool.name() != TOOL_SEARCH_NAME {
- return None;
- }
- tool.host_extension()
- .and_then(|any| any.downcast_ref::<ToolSearchHandle>())
- });
- let Some(handle) = handle else {
- if !deferred.is_empty() {
- tracing::warn!(
- deferred = deferred.len(),
- "[tool_search] tools were deferred but no tool_search is registered; \
- they are unreachable this session"
- );
- }
- return false;
- };
- match handle.write() {
- Ok(mut index) => {
- *index = ToolSearchIndex::build(&deferred);
- true
- }
- Err(_) => {
- tracing::error!("[tool_search] index lock poisoned; leaving it empty");
- false
- }
- }
-}
diff --git a/crates/openhuman-core/src/tools/impl/meta/tool_search_tests.rs b/crates/openhuman-core/src/tools/impl/meta/tool_search_tests.rs
deleted file mode 100644
index 5ae6d4ee5a..0000000000
--- a/crates/openhuman-core/src/tools/impl/meta/tool_search_tests.rs
+++ /dev/null
@@ -1,172 +0,0 @@
-// The tokenizer's own tests live with it, in `util::bm25`.
-use super::*;
-
-fn spec(name: &str, description: &str) -> ToolSpec {
- ToolSpec {
- name: name.to_string(),
- description: description.to_string(),
- parameters: json!({"type": "object"}),
- }
-}
-
-fn index() -> ToolSearchIndex {
- ToolSearchIndex::build(&[
- spec("stock_quote", "Get the latest price for a stock ticker"),
- spec("cron_add", "Schedule a recurring job to run later"),
- spec(
- "memory_hybrid_search",
- "Search stored memories semantically",
- ),
- spec(
- "generate_presentation",
- "Build a pptx slide deck from an outline",
- ),
- ])
-}
-
-#[test]
-fn a_plain_language_query_finds_the_right_tool() {
- let index = index();
- let hits = index.search("schedule something to run every morning", 3);
- assert_eq!(hits.first().map(|t| t.name.as_str()), Some("cron_add"));
-}
-
-#[test]
-fn a_query_matching_the_name_rather_than_the_description_still_hits() {
- let index = index();
- let hits = index.search("stock", 3);
- assert_eq!(hits.first().map(|t| t.name.as_str()), Some("stock_quote"));
-}
-
-#[test]
-fn nothing_relevant_returns_nothing_rather_than_padding_to_the_limit() {
- // Padding would spend exactly the tokens deferral saves, and would
- // invite a call to something unrelated to the ask.
- let index = index();
- assert!(index.search("xyzzy quantum flux", 5).is_empty());
-}
-
-#[test]
-fn results_are_capped_at_the_requested_limit() {
- let index = index();
- assert!(index.search("search a stock job memory slide", 2).len() <= 2);
-}
-
-#[test]
-fn an_empty_query_matches_nothing() {
- let index = index();
- assert!(index.search(" ", 5).is_empty());
-}
-
-#[test]
-fn an_empty_index_is_searchable_without_panicking() {
- // `average_length` is 0 here; the length-normalisation term divides by
- // it, so this is the case that would panic or produce NaN if the
- // `.max(1.0)` guard were dropped.
- let empty = ToolSearchIndex::build(&[]);
- assert!(empty.is_empty());
- assert!(empty.search("anything", 5).is_empty());
-}
-
-#[test]
-fn ranking_is_stable_across_identical_queries() {
- let index = index();
- let first: Vec<&str> = index
- .search("search", 4)
- .iter()
- .map(|t| t.name.as_str())
- .collect();
- let second: Vec<&str> = index
- .search("search", 4)
- .iter()
- .map(|t| t.name.as_str())
- .collect();
- assert_eq!(first, second);
-}
-
-// ── strip + bind: a deferred tool leaves the wire and stays findable ─────────
-
-struct ExposureTestTool {
- name: &'static str,
- description: &'static str,
- exposure: tinytools::ToolExposure,
-}
-
-#[async_trait::async_trait]
-impl Tool for ExposureTestTool {
- fn name(&self) -> &str {
- self.name
- }
-
- fn description(&self) -> &str {
- self.description
- }
-
- fn parameters_schema(&self) -> Value {
- json!({"type": "object"})
- }
-
- fn exposure(&self) -> tinytools::ToolExposure {
- self.exposure
- }
-
- async fn execute(&self, _args: Value) -> Result<ToolResult> {
- Ok(ToolResult::success("ok"))
- }
-}
-
-/// The two halves the session builder runs back to back. A Deferred tool must
-/// come off the advertised set AND be findable through `tool_search`; a Hidden
-/// one comes off and is not searchable; `tool_search` itself always stays.
-/// Stripping without the index would make every deferred tool unreachable.
-#[test]
-fn a_deferred_tool_leaves_the_wire_and_is_found_by_tool_search() {
- use tinytools::ToolExposure;
- let tools: Vec<Box<dyn Tool>> = vec![
- Box::new(ToolSearchTool::new()),
- Box::new(ExposureTestTool {
- name: "stock_quote",
- description: "Get the latest price for a stock ticker",
- exposure: ToolExposure::Deferred,
- }),
- Box::new(ExposureTestTool {
- name: "memory_store",
- description: "Store a memory",
- exposure: ToolExposure::Hidden,
- }),
- Box::new(ExposureTestTool {
- name: "memory",
- description: "Store and search memories",
- exposure: ToolExposure::Direct,
- }),
- ];
- let mut visible: std::collections::HashSet<String> =
- tools.iter().map(|t| t.name().to_string()).collect();
-
- let deferred = strip_deferred_from_visible(&mut visible, &tools);
- assert!(bind_tool_search_index(&tools, deferred));
-
- let mut advertised: Vec<&str> = visible.iter().map(String::as_str).collect();
- advertised.sort_unstable();
- assert_eq!(advertised, vec!["memory", TOOL_SEARCH_NAME]);
-
- let handle = tools[0]
- .host_extension()
- .and_then(|any| any.downcast_ref::<ToolSearchHandle>())
- .expect("tool_search exposes its index handle");
- let index = handle.read().unwrap();
- let hits: Vec<&str> = index
- .search("stock price", 5)
- .iter()
- .map(|t| t.name.as_str())
- .collect();
- assert_eq!(
- hits,
- vec!["stock_quote"],
- "the deferred tool must be searchable"
- );
- assert!(
- index.search("store memory", 5).is_empty(),
- "a Hidden tool is not searchable"
- );
-}
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index e5d7787ec7..3a690bdd0d 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -1085,17 +1085,11 @@ pub fn all_tools_with_runtime(
// `orchestrator_tools::collect_orchestrator_tools` — which never pass
// through this function.
crate::tools::toolpacks::append_pack_tools(&mut tools);
-
- // The lookup half of `ToolExposure::Deferred`. Always registered, for the
- // same reason `use_skill` is: whether anything is actually deferred depends
- // on the agent's belt, which is resolved later in the session builder, and
- // a search tool that arrived *after* the tools it searches were hidden
- // would be one release of silently unreachable capabilities. Its index
- // starts empty and costs one small schema; the builder fills it via
- // `bind_tool_search_index`.
- tools.push(Box::new(
- crate::tools::implementations::meta::ToolSearchTool::new(),
- ));
+ // The lookup half of `ToolExposure::Deferred` is not registered here: the
+ // tinyagents harness advertises its intrinsic `tool_search` / `tool_call`
+ // bridge whenever a run has a deferred tool (`tool::discover`), ranked by
+ // whatever `agent::tinyagents::discovery` installed. A host-registered
+ // `tool_search` would shadow that bridge.
tools
}
diff --git a/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs
index 4162d52360..58db7a701b 100644
--- a/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs
+++ b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs
@@ -74,7 +74,9 @@ fn all_tools_registers_collapsed_memory_and_search_tools() {
tool_capability(memory.name()),
Some(tinymemory_api::capabilities::Capability::Core)
);
- assert!(tools
+ // The search half of deferral is the harness's intrinsic bridge, never a
+ // registered tool: a host `tool_search` would shadow it.
+ assert!(!tools
.iter()
.any(|tool| { tool.name() == crate::tools::implementations::meta::TOOL_SEARCH_NAME }));
}
diff --git a/crates/openhuman-core/src/util/bm25.rs b/crates/openhuman-core/src/util/bm25.rs
deleted file mode 100644
index 42c2d6e8fc..0000000000
--- a/crates/openhuman-core/src/util/bm25.rs
+++ /dev/null
@@ -1,243 +0,0 @@
-//! BM25 ranking over short documents — the shared core behind `tool_search`
-//! and `skill_search`.
-//!
-//! # Extraction-ready on purpose
-//!
-//! This module names **nothing** from `crate::`: no config, no `Tool`, no
-//! workspace, no security policy. It takes `(id, text)` pairs and returns
-//! ranked ids. That is not incidental tidiness — a capability that ends up in
-//! a loadable module has to be reachable over a bus, and anything that reaches
-//! back into the host cannot go. Ranking is the half of skill discovery that is
-//! the same for every host; **which** bundles exist, whether the caller may
-//! read one, and what a trust marker means are the half that never leaves.
-//!
-//! Keep it that way. A `use crate::` line here is the edit that makes the move
-//! expensive, and it will look harmless at the time.
-//!
-//! # Why hand-rolled
-//!
-//! Codex uses the `bm25` crate for the same job. This crate is kernel surface
-//! under a dependency-floor ratchet (`scripts/kernel-floor.limits`), and the
-//! arithmetic below is a better trade than a package on the floor of every
-//! embedder's build.
-
-use std::collections::HashMap;
-
-/// Words that carry no capability meaning, dropped from a query before ranking.
-///
-/// A document-frequency threshold alone cannot do this job on a small corpus,
-/// and the failure is not hypothetical: with three skills installed, "a"
-/// appeared in exactly one description, so by frequency it was the *most*
-/// distinguishing term in the query "provision a kubernetes cluster" — and the
-/// changelog skill was returned as the match. The df rule handles a large
-/// corpus; this list handles a small one. Both are needed.
-///
-/// Deliberately short and deliberately English-only. It can only ever *remove*
-/// terms, so a description in another language ranks exactly as it does today
-/// rather than worse. Words that could name a capability are left out on
-/// purpose — "up" stays, because "look up" is a thing a tool does.
-const STOPWORDS: &[&str] = &[
- "a", "an", "and", "are", "as", "at", "be", "but", "by", "can", "do", "for", "from", "how", "i",
- "if", "in", "into", "is", "it", "its", "me", "my", "of", "on", "or", "our", "so", "that",
- "the", "their", "them", "then", "there", "these", "they", "this", "to", "was", "we", "were",
- "what", "when", "which", "who", "will", "with", "would", "you", "your",
-];
-
-/// BM25 term-frequency saturation. The standard default.
-pub const K1: f64 = 1.2;
-/// BM25 length normalisation. The standard default.
-pub const B: f64 = 0.75;
-
-/// Split text into search terms.
-///
-/// Splits on non-alphanumerics **and** on a lower→upper transition, so
-/// `memory_hybrid_search` and `readWorkflowResource` both yield the words a
-/// person would actually type. Without the camelCase rule a query for
-/// "workflow" misses a tool whose only mention of it is inside an identifier.
-pub fn tokenize(text: &str) -> Vec<String> {
- let mut out = Vec::new();
- let mut current = String::new();
- let mut previous_lower = false;
- for ch in text.chars() {
- if ch.is_alphanumeric() {
- if ch.is_uppercase() && previous_lower && !current.is_empty() {
- out.push(std::mem::take(&mut current));
- }
- current.extend(ch.to_lowercase());
- previous_lower = ch.is_lowercase() || ch.is_numeric();
- } else if !current.is_empty() {
- out.push(std::mem::take(&mut current));
- previous_lower = false;
- }
- }
- if !current.is_empty() {
- out.push(current);
- }
- out
-}
-
-/// A ranked corpus of short documents.
-///
-/// Generic over nothing: documents are identified by their index into the slice
-/// the caller built the index from, so the caller keeps its own richer type and
-/// this module never has to know about it.
-#[derive(Default, Debug)]
-pub struct Bm25Index {
- documents: Vec<Document>,
- document_frequency: HashMap<String, usize>,
- average_length: f64,
-}
-
-#[derive(Debug, Clone)]
-struct Document {
- /// Used only to break score ties deterministically.
- sort_key: String,
- tokens: Vec<String>,
-}
-
-impl Bm25Index {
- /// Build from `(sort_key, searchable_text)` pairs, in caller order.
- ///
- /// `sort_key` breaks ties; make it the id the caller would print, so two
- /// identical queries produce identical output. An unstable order would make
- /// a model's transcript non-reproducible for no benefit.
- pub fn build<'a>(documents: impl IntoIterator<Item = (&'a str, &'a str)>) -> Self {
- let documents: Vec<Document> = documents
- .into_iter()
- .map(|(sort_key, text)| Document {
- sort_key: sort_key.to_string(),
- tokens: tokenize(text),
- })
- .collect();
-
- let mut document_frequency: HashMap<String, usize> = HashMap::new();
- for doc in &documents {
- let mut seen: Vec<&str> = Vec::new();
- for token in &doc.tokens {
- if !seen.contains(&token.as_str()) {
- seen.push(token);
- *document_frequency.entry(token.clone()).or_insert(0) += 1;
- }
- }
- }
-
- let total: usize = documents.iter().map(|d| d.tokens.len()).sum();
- let average_length = if documents.is_empty() {
- 0.0
- } else {
- total as f64 / documents.len() as f64
- };
-
- Self {
- documents,
- document_frequency,
- average_length,
- }
- }
-
- pub fn is_empty(&self) -> bool {
- self.documents.is_empty()
- }
-
- pub fn len(&self) -> usize {
- self.documents.len()
- }
-
- /// Rank against `query`, best first, returning **indices** into the corpus.
- ///
- /// Only documents scoring above zero are returned. Padding the list out to
- /// `limit` with unrelated entries would spend exactly the tokens this
- /// mechanism exists to save, and would invite the model to act on something
- /// that has nothing to do with what it asked for.
- pub fn search(&self, query: &str, limit: usize) -> Vec<usize> {
- let terms = self.significant(tokenize(query));
- if terms.is_empty() || self.documents.is_empty() {
- return Vec::new();
- }
- let mut scored: Vec<(f64, usize)> = self
- .documents
- .iter()
- .enumerate()
- .map(|(index, doc)| (self.score(doc, &terms), index))
- .filter(|(score, _)| *score > 0.0)
- .collect();
-
- scored.sort_by(|a, b| {
- b.0.partial_cmp(&a.0)
- .unwrap_or(std::cmp::Ordering::Equal)
- .then_with(|| {
- self.documents[a.1]
- .sort_key
- .cmp(&self.documents[b.1].sort_key)
- })
- });
- scored.into_iter().take(limit).map(|(_, i)| i).collect()
- }
-
- /// Drop query terms that are too common in this corpus to mean anything.
- ///
- /// # Why this is needed, and why the obvious fix is wrong
- ///
- /// The IDF below carries the standard `+ 1`, which keeps a term that
- /// appears in every document at a small **positive** weight rather than a
- /// negative one. That is deliberate — without it, a corpus of one document
- /// scores every term at zero and nothing is ever findable, which is the
- /// common case here (a user with one installed skill).
- ///
- /// The cost is that "a" and "the" score. Measured on a three-skill corpus,
- /// the query "provision a kubernetes cluster" matched a changelog skill,
- /// on the strength of the word "a" alone. A model handed that result has
- /// been told, with a ranking behind it, that a changelog tool provisions
- /// clusters.
- ///
- /// Clamping negative IDF to zero — the usual textbook answer — fixes the
- /// stopwords and breaks the one-document case in the same edit. So the
- /// filter is a document-frequency threshold instead, with a floor of 2 that
- /// makes it inert on a single-document corpus:
- ///
- /// `drop the term when df >= max(2, ceil(0.8 * n))`
- ///
- /// One skill: the threshold is 2 and no term can reach it. Three: a term in
- /// all three goes. Twenty: a term in sixteen or more goes.
- ///
- /// The threshold alone is not enough on a small corpus — see [`STOPWORDS`],
- /// which is the other half and the one that caught the real bug.
- fn significant(&self, terms: Vec<String>) -> Vec<String> {
- let n = self.documents.len();
- if n == 0 {
- return Vec::new();
- }
- let threshold = std::cmp::max(2, (0.8 * n as f64).ceil() as usize);
- terms
- .into_iter()
- .filter(|term| !STOPWORDS.contains(&term.as_str()))
- .filter(|term| *self.document_frequency.get(term).unwrap_or(&0) < threshold)
- .collect()
- }
-
- fn score(&self, doc: &Document, terms: &[String]) -> f64 {
- let length = doc.tokens.len() as f64;
- let count = self.documents.len() as f64;
- terms
- .iter()
- .map(|term| {
- let frequency = doc.tokens.iter().filter(|t| *t == term).count() as f64;
- if frequency == 0.0 {
- return 0.0;
- }
- let df = *self.document_frequency.get(term).unwrap_or(&0) as f64;
- // Standard BM25 IDF with the +1 that keeps a term present in
- // every document at a small positive weight rather than a
- // negative one.
- let idf = (((count - df + 0.5) / (df + 0.5)) + 1.0).ln();
- let denominator =
- frequency + K1 * (1.0 - B + B * length / self.average_length.max(1.0));
- idf * (frequency * (K1 + 1.0)) / denominator
- })
- .sum()
- }
-}
-
-#[cfg(test)]
-#[path = "bm25_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/util/bm25_tests.rs b/crates/openhuman-core/src/util/bm25_tests.rs
deleted file mode 100644
index b347eccce2..0000000000
--- a/crates/openhuman-core/src/util/bm25_tests.rs
+++ /dev/null
@@ -1,108 +0,0 @@
-use super::*;
-
-#[test]
-fn snake_case_and_camel_case_both_split() {
- assert_eq!(
- tokenize("memory_hybrid_search"),
- ["memory", "hybrid", "search"]
- );
- assert_eq!(
- tokenize("readWorkflowResource"),
- ["read", "workflow", "resource"]
- );
- assert_eq!(tokenize("HTTPServer2"), ["httpserver2"]);
-}
-
-fn corpus() -> Bm25Index {
- Bm25Index::build([
- ("alpha", "send an email to a colleague"),
- ("beta", "look up a stock quote by ticker symbol"),
- ("gamma", "read a file from the workspace"),
- ])
-}
-
-#[test]
-fn a_plain_language_query_finds_the_right_document() {
- assert_eq!(corpus().search("stock ticker", 3), vec![1]);
- assert_eq!(corpus().search("email a colleague", 3)[0], 0);
- assert_eq!(corpus().search("read from the workspace", 3)[0], 2);
-}
-
-#[test]
-fn nothing_relevant_returns_nothing_rather_than_padding() {
- // The load-bearing property. A ranker that always returns `limit`
- // results turns a miss into a confident wrong answer.
- assert!(corpus().search("photosynthesis", 3).is_empty());
-}
-
-#[test]
-fn a_query_matching_only_on_stopwords_is_a_miss() {
- // The regression, and it took two attempts to fix. "a" appears in
- // exactly ONE of these three documents, so by document frequency it is
- // the most distinguishing term in the query — the df threshold cannot
- // catch it, and the first fix that only had the threshold still ranked
- // a changelog skill as the match for provisioning a cluster.
- assert!(corpus()
- .search("provision a kubernetes cluster", 3)
- .is_empty());
- assert!(corpus().search("a", 3).is_empty());
- assert!(corpus()
- .search("what is it that you will do for me", 3)
- .is_empty());
-}
-
-#[test]
-fn a_single_document_corpus_stays_searchable() {
- // The reason the threshold has a floor of 2 rather than being a plain
- // ratio. With one document every term is in every document, so a ratio
- // rule would filter the entire query and make the only installed skill
- // permanently unfindable.
- let one = Bm25Index::build([("solo", "post a message to discord")]);
- assert_eq!(one.search("discord", 1), vec![0]);
- assert_eq!(one.search("post a message", 1), vec![0]);
-}
-
-#[test]
-fn a_real_term_still_matches_even_alongside_stopwords() {
- // The filter must drop the noise, not the query.
- assert_eq!(corpus().search("look up a stock", 3), vec![1]);
-}
-
-#[test]
-fn an_empty_query_and_an_empty_index_are_both_safe() {
- assert!(corpus().search("", 3).is_empty());
- assert!(Bm25Index::build([]).search("anything", 3).is_empty());
-}
-
-#[test]
-fn ranking_is_stable_across_identical_queries() {
- let index = corpus();
- let first = index.search("a", 3);
- for _ in 0..5 {
- assert_eq!(index.search("a", 3), first);
- }
-}
-
-#[test]
-fn ties_break_on_the_sort_key_not_on_insertion_order() {
- // Two documents with identical text score identically; the sort key
- // decides. Built in reverse order so insertion order would give the
- // opposite answer.
- // Three documents, two identical: with only two, every term would be
- // in every document and `significant` would filter the query away.
- let index = Bm25Index::build([
- ("zulu", "same words here"),
- ("alpha", "same words here"),
- ("other", "entirely different text"),
- ]);
- assert_eq!(index.search("same words", 2), vec![1, 0]);
-}
-
-#[test]
-fn the_limit_is_honoured() {
- // "read email stock" hits all three documents on a real term each, so
- // the unlimited search returns three — which is what makes this a test
- // of the cap rather than a query that happened to match once.
- assert_eq!(corpus().search("read email stock", 10).len(), 3);
- assert_eq!(corpus().search("read email stock", 1).len(), 1);
-}
diff --git a/crates/openhuman-core/src/util/mod.rs b/crates/openhuman-core/src/util/mod.rs
index a2687f7a56..ddb915948c 100644
--- a/crates/openhuman-core/src/util/mod.rs
+++ b/crates/openhuman-core/src/util/mod.rs
@@ -8,21 +8,17 @@
//! - [`retry`] — retry-with-backoff + transient-filesystem-error classification
//! - [`sanitize`] — LLM-facing text sanitization (control-char stripping,
//! instruction-fence removal, UTF-8-safe byte caps)
-//! - [`bm25`] — BM25 ranking over short documents (tool + skill search)
//! - [`tls`] — platform-conditional `reqwest::ClientBuilder` factory
//! - [`types`] — shared utility types
//!
//! `retry`, `text`, and `types` items are re-exported at the module root, so
//! `crate::util::<fn>` (and `openhuman_core::util::<fn>` from outside, the
//! path the `truncate_with_ellipsis` doctest uses) resolves without naming the
-//! submodule. `bm25`, `redact`, `sanitize`, and `tls` are reached through
+//! submodule. `redact`, `sanitize`, and `tls` are reached through
//! their submodule path.
//!
//! See [`README.md`](README.md) for a per-file breakdown.
-/// BM25 ranking over short documents, shared by `tool_search` and
-/// `skill_search`. Deliberately names nothing from `crate::` — see its docs.
-pub mod bm25;
/// Generic JSON-RPC param deserialisation (`read_required`/`read_optional`),
/// shared across domain `schemas.rs` files.
pub mod params;