use super::{ToolCatalogError, registry::ToolExecutor};
use crate::composition::ToolBridge;
use causa_kernel::{CallControl, InvocationId, ProcessorData, Tool, ToolDescription, ToolSurface};
use std::collections::HashMap;
use std::sync::Arc;
pub struct BoundTools<'a> {
pub(super) executor: &'a ToolExecutor,
pub(super) surface: ToolSurface,
pub(super) tools: Vec<ToolDescription>,
pub(super) targets: HashMap<String, Arc<dyn Tool>>,
pub(super) invocation_id: InvocationId,
pub(super) control: CallControl,
pub(super) data: Option<ProcessorData>,
}
impl ToolExecutor {
pub async fn bind(
&self,
invocation_id: InvocationId,
control: CallControl,
) -> Result<BoundTools<'_>, ToolCatalogError> {
control.check().map_err(ToolCatalogError::Control)?;
let registrations = self.dynamic.read().expect("dynamic registry lock").clone();
let mut tools = Vec::new();
let mut targets = HashMap::new();
for entry in &self.tools {
control.check().map_err(ToolCatalogError::Control)?;
let definition = entry.tool.definition();
if definition.name != entry.name {
return Err(ToolCatalogError::StaticNameChanged {
registered: entry.name.clone(),
actual: definition.name,
});
}
targets.insert(entry.name.clone(), entry.tool.clone());
tools.push(ToolDescription::new(definition).with_hints(entry.tool.hints()));
}
for entry in registrations {
control.check().map_err(ToolCatalogError::Control)?;
for description in entry.describe(&control).await? {
let name = description.definition.name.clone();
if targets.contains_key(&name) {
return Err(ToolCatalogError::DuplicateTool { name });
}
let bridge = ToolBridge::new(entry.source.clone(), description.definition.clone())
.with_hints(description.hints.clone());
targets.insert(name, Arc::new(bridge) as Arc<dyn Tool>);
tools.push(description);
}
}
control.check().map_err(ToolCatalogError::Control)?;
let surface = ToolSurface::from_definitions(
tools.iter().map(|tool| tool.definition.clone()).collect(),
);
Ok(BoundTools {
executor: self,
surface,
tools,
targets,
invocation_id,
control,
data: None,
})
}
}
impl BoundTools<'_> {
pub fn surface(&self) -> &ToolSurface {
&self.surface
}
pub fn with_processor_data(mut self, data: ProcessorData) -> Self {
self.data = Some(data);
self
}
}