Skip to content

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

fix(search): stop re-offering search a session cannot use

obchainbc75c6f55f4b
diff --git a/crates/openhuman-core/src/agent/session_host/recorded_tools.rs b/crates/openhuman-core/src/agent/session_host/recorded_tools.rs
index c23aee4106..5343fef64f 100644
--- a/crates/openhuman-core/src/agent/session_host/recorded_tools.rs
+++ b/crates/openhuman-core/src/agent/session_host/recorded_tools.rs
@@ -135,21 +135,24 @@ pub(super) fn rehydrate_search_tools(
.flat_map(|tools| tools.iter().map(|tool| tool.name()))
.collect();
let mut seen = HashSet::new();
- let rebuilt: Vec<Box<dyn Tool>> = recorded
- .iter()
- .filter(|spec| is_search_role_tool(&spec.name))
- .filter(|spec| !live_names.contains(spec.name.as_str()))
- .filter(|spec| seen.insert(spec.name.clone()))
- .map(|spec| {
- Box::new(crate::search::TinySearchTool::recorded(
- tinysearch_bus::ToolSpec {
- name: spec.name.clone(),
- description: spec.description.clone(),
- parameters: spec.parameters.clone(),
- },
- )) as Box<dyn Tool>
- })
- .collect();
+ // One batch, so the rebuilt roles share the "no provider answered" latch
+ // the live surface gives its own search tools (#6991).
+ let rebuilt: Vec<Box<dyn Tool>> = crate::search::TinySearchTool::recorded_batch(
+ recorded
+ .iter()
+ .filter(|spec| is_search_role_tool(&spec.name))
+ .filter(|spec| !live_names.contains(spec.name.as_str()))
+ .filter(|spec| seen.insert(spec.name.clone()))
+ .map(|spec| tinysearch_bus::ToolSpec {
+ name: spec.name.clone(),
+ description: spec.description.clone(),
+ parameters: spec.parameters.clone(),
+ })
+ .collect::<Vec<_>>(),
+ )
+ .into_iter()
+ .map(|tool| Box::new(tool) as Box<dyn Tool>)
+ .collect();
if !rebuilt.is_empty() {
log::info!(
"[session] rebuilt {} recorded search tool(s) the live surface did not supply agent={agent_id}",
diff --git a/crates/openhuman-core/src/search/tools.rs b/crates/openhuman-core/src/search/tools.rs
index c237144fb5..82d4e9d0b9 100644
--- a/crates/openhuman-core/src/search/tools.rs
+++ b/crates/openhuman-core/src/search/tools.rs
@@ -6,6 +6,7 @@
//! through `modules::search::execute_tool`, so a provider or login change is
//! honoured on the next call without rebuilding the session.
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use async_trait::async_trait;
@@ -17,12 +18,29 @@ use crate::config::Config;
/// One TinySearch tool (a role tool such as `web_search_tool`, or a provider
/// tool in `all_tools` presentation).
+/// What a call reports once every provider has already answered
+/// "unavailable" in this session. It tells the model to stop rather than to
+/// wait, because nothing about the session will change the answer (#6991).
+pub const SEARCH_EXHAUSTED_MESSAGE: &str =
+ "Web search is not available in this session. Do not call it again \u{2014} \
+ answer from the material you already have.";
+
pub struct TinySearchTool {
spec: ToolSpec,
/// Spawn-time config. `None` for a deferred instance rebuilt from a
/// recorded transcript, which resolves the live config per call.
config: Option<Arc<Config>>,
exposure: ToolExposure,
+ /// Latched when a call reports that no provider could answer. Shared by
+ /// the search tools built for one session instance, so the model is told
+ /// once and the later calls cost no module round-trip.
+ ///
+ /// A credential alone makes the managed route look reachable
+ /// (`providers::backend_credential_available`), so a deployment that is
+ /// offline, firewalled, out of balance or holding a dead key offers these
+ /// tools on every turn and fails every call. The agent then spends turns
+ /// on a tool that cannot work, at the moment it is least sure what to do.
+ exhausted: Arc<AtomicBool>,
}
impl TinySearchTool {
@@ -31,6 +49,7 @@ impl TinySearchTool {
spec,
config: Some(config),
exposure: ToolExposure::Direct,
+ exhausted: Arc::new(AtomicBool::new(false)),
}
}
@@ -41,9 +60,36 @@ impl TinySearchTool {
spec,
config: None,
exposure: ToolExposure::Direct,
+ exhausted: Arc::new(AtomicBool::new(false)),
}
}
+ /// Recorded tools that share one exhaustion latch, the way the tools of a
+ /// live session do: the roles are three declarations over the same
+ /// providers, so one of them finding nothing settles it for all three.
+ pub fn recorded_batch(specs: impl IntoIterator<Item = ToolSpec>) -> Vec<Self> {
+ let exhausted = Arc::new(AtomicBool::new(false));
+ specs
+ .into_iter()
+ .map(|spec| Self {
+ spec,
+ config: None,
+ exposure: ToolExposure::Direct,
+ exhausted: exhausted.clone(),
+ })
+ .collect()
+ }
+
+ /// Whether this session already learned that no provider can answer.
+ pub(crate) fn is_exhausted(&self) -> bool {
+ self.exhausted.load(Ordering::Relaxed)
+ }
+
+ /// Record that no provider could answer, for the tools sharing this latch.
+ pub(crate) fn mark_exhausted(&self) {
+ self.exhausted.store(true, Ordering::Relaxed);
+ }
+
pub fn spec(&self) -> &ToolSpec {
&self.spec
}
@@ -71,10 +117,7 @@ pub fn user_facing_error(error: &str) -> String {
Some(code) if code == errors::RATE_LIMITED => {
"Web search is rate limited right now. Wait a moment and try again.".to_string()
}
- Some(code) if code == errors::UNAVAILABLE => {
- "Every configured search provider for this request is unavailable right now."
- .to_string()
- }
+ Some(code) if code == errors::UNAVAILABLE => SEARCH_EXHAUSTED_MESSAGE.to_string(),
Some(code) if code == errors::INVALID_ARGUMENTS => {
let marker = format!("{}{code}: ", errors::PREFIX);
let detail = error
@@ -92,6 +135,16 @@ pub fn error_code(error: &str) -> Option<&'static str> {
errors::code_of(error)
}
+/// Whether this failure means no provider can answer for the rest of the
+/// session, rather than something a later call could get past.
+///
+/// Only the "every provider is unavailable" verdict qualifies. A rate limit
+/// clears on its own, and a low balance or a rejected argument has its own
+/// message telling the caller what to change, so neither latches.
+pub(crate) fn exhausts_providers(error: &str) -> bool {
+ error_code(error) == Some(errors::UNAVAILABLE)
+}
+
#[async_trait]
impl Tool for TinySearchTool {
fn name(&self) -> &str {
@@ -132,6 +185,13 @@ impl Tool for TinySearchTool {
args: Value,
options: ToolCallOptions,
) -> anyhow::Result<ToolResult> {
+ if self.is_exhausted() {
+ tracing::debug!(
+ tool = %self.spec.name,
+ "[search][tool] refused: no provider answered earlier in this session"
+ );
+ return Ok(ToolResult::failed(SEARCH_EXHAUSTED_MESSAGE.to_string()));
+ }
let config = self.live_config().await?;
let subject = super::render::subject(&args);
let max_results = args
@@ -169,12 +229,20 @@ impl Tool for TinySearchTool {
))
}
Err(error) => {
+ if exhausts_providers(&error) {
+ self.mark_exhausted();
+ }
tracing::warn!(
tool = %self.spec.name,
code = error_code(&error).unwrap_or("unclassified"),
+ exhausted = self.is_exhausted(),
"[search][tool] failed"
);
- Ok(ToolResult::error(user_facing_error(&error)))
+ Ok(if exhausts_providers(&error) {
+ ToolResult::failed(user_facing_error(&error))
+ } else {
+ ToolResult::error(user_facing_error(&error))
+ })
}
}
}
@@ -199,9 +267,17 @@ pub fn build_search_tools(config: &Config) -> Vec<Box<dyn Tool>> {
"[search][tool] registered search tools"
);
let shared = Arc::new(config.clone());
+ let exhausted = Arc::new(AtomicBool::new(false));
specs
.into_iter()
- .map(|spec| Box::new(TinySearchTool::new(shared.clone(), spec)) as Box<dyn Tool>)
+ .map(|spec| {
+ Box::new(TinySearchTool {
+ spec,
+ config: Some(shared.clone()),
+ exposure: ToolExposure::Direct,
+ exhausted: exhausted.clone(),
+ }) as Box<dyn Tool>
+ })
.collect()
}
diff --git a/crates/openhuman-core/src/search/tools_tests.rs b/crates/openhuman-core/src/search/tools_tests.rs
index 8cdc4e17df..417f71f71a 100644
--- a/crates/openhuman-core/src/search/tools_tests.rs
+++ b/crates/openhuman-core/src/search/tools_tests.rs
@@ -19,7 +19,10 @@ fn classified_errors_become_actionable_messages() {
let balance = user_facing_error("tinysearch.insufficient_balance: 402 from backend");
assert!(balance.contains("balance is too low"));
assert!(user_facing_error("tinysearch.rate_limited: slow down").contains("rate limited"));
- assert!(user_facing_error("tinysearch.provider_unavailable: all down").contains("unavailable"));
+ assert_eq!(
+ user_facing_error("tinysearch.provider_unavailable: all down"),
+ SEARCH_EXHAUSTED_MESSAGE
+ );
assert_eq!(
user_facing_error(
"search ExecuteTool failed: tinysearch.invalid_arguments: urls must not be empty"
@@ -100,3 +103,101 @@ fn standard_privacy_mode_allows_search_tool_dispatch() {
assert!(local_only_search_block("web_search_tool").is_none());
}
+
+// ---------------------------------------------------------------------------
+// #6991: a credential alone makes the managed route look reachable, so a
+// deployment that is offline, firewalled, out of balance or holding a dead key
+// offers these tools on every turn and fails every call. The old message ended
+// "unavailable right now", which reads as "retry later": in the DeepSWE-10 run
+// the agent called search three times on one task, then guessed, and the guess
+// was what the hidden test rejected.
+// ---------------------------------------------------------------------------
+
+fn role_specs() -> Vec<ToolSpec> {
+ ["web_search_tool", "web_answer_tool", "web_contents_tool"]
+ .into_iter()
+ .map(|name| ToolSpec {
+ name: name.to_string(),
+ description: "search".into(),
+ parameters: serde_json::json!({"type": "object"}),
+ })
+ .collect()
+}
+
+#[test]
+fn the_unavailable_verdict_tells_the_model_to_stop_rather_than_wait() {
+ let message = user_facing_error("tinysearch.provider_unavailable: all down");
+
+ assert!(
+ message.contains("Do not call it again"),
+ "the model must be told to stop, got: {message}"
+ );
+ assert!(
+ !message.contains("right now"),
+ "nothing in the session will change the answer, so it must not read as a retry hint: {message}"
+ );
+}
+
+#[test]
+fn only_the_exhaustion_verdict_is_treated_as_final() {
+ // A rate limit clears on its own; a low balance and a rejected argument
+ // each have a message naming what to change. None of them may latch.
+ assert!(exhausts_providers(
+ "tinysearch.provider_unavailable: all down"
+ ));
+ assert!(!exhausts_providers("tinysearch.rate_limited: slow down"));
+ assert!(!exhausts_providers("tinysearch.insufficient_balance: 402"));
+ assert!(!exhausts_providers(
+ "tinysearch.invalid_arguments: urls must not be empty"
+ ));
+ assert!(!exhausts_providers("boom"));
+}
+
+#[test]
+fn a_session_starts_unlatched() {
+ for tool in TinySearchTool::recorded_batch(role_specs()) {
+ assert!(!tool.is_exhausted(), "{} started latched", tool.name());
+ }
+}
+
+#[test]
+fn one_role_finding_nothing_settles_it_for_the_others() {
+ // The three roles are declarations over the same providers, so dropping
+ // only the role that failed would still leave two tools that cannot work.
+ let tools = TinySearchTool::recorded_batch(role_specs());
+
+ tools[0].mark_exhausted();
+
+ for tool in &tools {
+ assert!(
+ tool.is_exhausted(),
+ "{} did not share the latch",
+ tool.name()
+ );
+ }
+}
+
+#[tokio::test]
+async fn a_latched_tool_refuses_before_reaching_the_module() {
+ // The refusal is returned without loading config or calling the module, so
+ // a dead search costs the session one round trip rather than one per call.
+ let tools = TinySearchTool::recorded_batch(role_specs());
+ tools[1].mark_exhausted();
+
+ let result = tools[0]
+ .execute(serde_json::json!({"query": "anything"}))
+ .await
+ .expect("a refusal is a reported failure, not a tool error");
+
+ assert!(result.is_error);
+ assert_eq!(
+ result.error_kind,
+ Some(tinytools::ToolErrorKind::Failed),
+ "the failure is permanent, so it must not be tagged retryable"
+ );
+ assert!(
+ result.text().contains("Do not call it again"),
+ "{:?}",
+ result.text()
+ );
+}