use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::types::{AgentError, AgentResult};
use super::{Content, Tool, ToolActivation, ToolContext, ToolExposure};
pub struct ActivateTool {
activation: ToolActivation,
candidates: HashMap<String, (ToolExposure, Value)>,
}
impl ActivateTool {
pub fn new(
activation: ToolActivation,
candidates: Vec<(String, ToolExposure, Value)>,
) -> Arc<Self> {
Arc::new(Self {
activation,
candidates: candidates
.into_iter()
.map(|(name, exposure, def)| (name, (exposure, def)))
.collect(),
})
}
fn candidate_names(&self) -> Vec<&str> {
let mut names: Vec<&str> = self.candidates.keys().map(|s| s.as_str()).collect();
names.sort_unstable();
names
}
}
#[async_trait]
impl Tool for ActivateTool {
fn name(&self) -> &'static str {
"activate_tool"
}
fn description(&self) -> &'static str {
"Mount a tool that the roster names but the session has not opened yet, \
so it can be called from the next turn on. Pass the tool's name exactly \
as the roster spells it; the result is that tool's full description and \
argument schema. Opening is once per session — it stays mounted, do not \
re-open it to use it again. Reach for this when the task needs a \
capability the roster lists as unmounted; do NOT use it for tools that \
are already mounted, and do not open a group on the chance it comes in \
handy — every open tool is sent on every later request."
}
fn schema(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The tool name exactly as the roster spells it."
}
},
"required": ["name"],
"additionalProperties": false,
})
}
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
let name = args
.get("name")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or_else(|| AgentError::ToolArgsInvalid {
name: self.name().to_string(),
raw: "missing field `name` — pass the tool name exactly as the roster spells it"
.to_string(),
})?;
let Some((exposure, definition)) = self.candidates.get(name) else {
return Ok(vec![Content::text(format!(
"No tool named `{name}` is mountable. Mountable names: {}.",
self.candidate_names().join(", ")
))]);
};
match exposure {
ToolExposure::Hidden => Ok(vec![Content::text(format!(
"`{name}` is internal and is not mountable. It is not in the roster."
))]),
ToolExposure::Direct => Ok(vec![Content::text(format!(
"`{name}` is already mounted — call it directly."
))]),
ToolExposure::Deferred => {
let first_open = self.activation.activate(name);
let status = if first_open {
"mounted"
} else {
"already mounted"
};
Ok(vec![Content::text(format!(
"`{name}` {status}. Call it from the next turn on, with these arguments:\n{}",
serde_json::to_string_pretty(definition).unwrap_or_default()
))])
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicBool;
use super::*;
use crate::engine::EventBus;
use crate::tool::ExecClock;
use crate::types::SessionId;
use serde_json::json;
fn test_context() -> ToolContext {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
ToolContext {
session_id: SessionId::new(0),
user_event_tx: tx,
llm_client: None,
session_store: None,
language: crate::types::Language::En,
cancel_token: tokio_util::sync::CancellationToken::new(),
max_output_chars: None,
exec_clock: ExecClock::default(),
waiting_for_human: Arc::new(AtomicBool::new(false)),
event_bus: EventBus::new(1),
}
}
fn registry_free_tool() -> (ActivateTool, ToolActivation) {
let activation = ToolActivation::new();
let tool = ActivateTool::new(
activation.clone(),
vec![
(
"browser_navigate".to_string(),
ToolExposure::Deferred,
json!({
"name": "browser_navigate",
"description": "Open a URL in the browser.",
"parameters": {"type": "object", "properties": {"url": {"type": "string"}}},
}),
),
(
"always_here".to_string(),
ToolExposure::Direct,
json!({"name": "always_here"}),
),
(
"internal".to_string(),
ToolExposure::Hidden,
json!({"name": "internal"}),
),
],
);
let tool = Arc::try_unwrap(tool).ok().expect("single owner in tests");
(tool, activation)
}
async fn call(tool: &ActivateTool, args: Value) -> String {
let ctx = test_context();
let out = tool.call(&args, &ctx).await.expect("call succeeds");
out.iter()
.map(|c| match c {
Content::Text { text } => text.clone(),
_ => String::new(),
})
.collect()
}
#[tokio::test]
async fn opening_a_tool_mounts_it_and_hands_back_its_shape() {
let (tool, activation) = registry_free_tool();
let out = call(&tool, json!({"name": "browser_navigate"})).await;
assert!(
activation.is_active("browser_navigate"),
"opening must stick for the session"
);
assert!(out.contains("mounted"), "say what happened: {out}");
assert!(
out.contains("\"url\""),
"and hand back the real arguments, not just the name: {out}"
);
}
#[tokio::test]
async fn an_unknown_name_is_refused_with_the_real_ones() {
let (tool, _activation) = registry_free_tool();
let out = call(&tool, json!({"name": "browser_nav"})).await;
assert!(out.contains("No tool named `browser_nav`"), "{out}");
assert!(
out.contains("browser_navigate"),
"the answer must name the tool it meant: {out}"
);
}
#[tokio::test]
async fn an_internal_tool_cannot_be_mounted() {
let (tool, activation) = registry_free_tool();
let out = call(&tool, json!({"name": "internal"})).await;
assert!(out.contains("not mountable"), "{out}");
assert!(!activation.is_active("internal"), "and nothing was opened");
}
#[tokio::test]
async fn opening_twice_is_reported_as_already_mounted() {
let (tool, _activation) = registry_free_tool();
call(&tool, json!({"name": "browser_navigate"})).await;
let out = call(&tool, json!({"name": "browser_navigate"})).await;
assert!(out.contains("already mounted"), "{out}");
}
#[tokio::test]
async fn an_already_mounted_tool_is_said_to_be() {
let (tool, activation) = registry_free_tool();
let out = call(&tool, json!({"name": "always_here"})).await;
assert!(out.contains("already mounted"), "{out}");
assert!(
!activation.is_active("always_here"),
"a Direct tool needs no activation entry"
);
}
#[tokio::test]
async fn a_missing_name_says_what_is_missing() {
let (tool, _activation) = registry_free_tool();
let err = tool.call(&json!({}), &test_context()).await;
let msg = format!("{:?}", err.expect_err("no name is an error"));
assert!(
msg.contains("`name`"),
"the error must name the field: {msg}"
);
}
}