use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use crate::context::block::{TextPayload, ToolCallPayload};
use crate::context::ids::BlockId;
use crate::context::tool_data::{ArtifactKind, ArtifactRef, ToolResultPayload};
use crate::context::tools::ToolDefinition;
use crate::ports::control::CallControl;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ToolSurface {
pub definitions: Vec<ToolDefinition>,
}
impl ToolSurface {
pub fn empty() -> Self {
Self {
definitions: Vec::new(),
}
}
pub fn from_definitions(definitions: Vec<ToolDefinition>) -> Self {
Self { definitions }
}
}
#[derive(Clone, Default)]
pub struct ToolMetadata {
entries: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
impl ToolMetadata {
pub fn new() -> Self {
Self::default()
}
pub fn with<T: Any + Send + Sync>(mut self, value: T) -> Self {
self.insert(value);
self
}
pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<Arc<T>> {
self.entries
.insert(TypeId::of::<T>(), Arc::new(value))
.and_then(|prev| prev.downcast::<T>().ok())
}
pub fn get<T: Any>(&self) -> Option<&T> {
self.entries
.get(&TypeId::of::<T>())
.and_then(|arc| (&**arc as &dyn Any).downcast_ref::<T>())
}
pub fn contains<T: Any>(&self) -> bool {
self.entries.contains_key(&TypeId::of::<T>())
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl fmt::Debug for ToolMetadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ToolMetadata")
.field("len", &self.entries.len())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ToolDescription {
pub definition: ToolDefinition,
pub metadata: ToolMetadata,
}
impl ToolDescription {
pub fn new(definition: ToolDefinition) -> Self {
Self {
definition,
metadata: ToolMetadata::default(),
}
}
pub fn with_metadata(mut self, metadata: ToolMetadata) -> Self {
self.metadata = metadata;
self
}
pub fn with_meta<T: Any + Send + Sync>(mut self, value: T) -> Self {
self.metadata.insert(value);
self
}
}
#[derive(Clone, Default)]
pub struct CallAttachments {
entries: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
impl CallAttachments {
pub fn new() -> Self {
Self::default()
}
pub fn with<T: Any + Send + Sync>(mut self, value: T) -> Self {
self.insert(value);
self
}
pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<Arc<T>> {
self.entries
.insert(TypeId::of::<T>(), Arc::new(value))
.and_then(|prev| prev.downcast::<T>().ok())
}
pub fn get<T: Any>(&self) -> Option<&T> {
self.entries
.get(&TypeId::of::<T>())
.and_then(|arc| (&**arc as &dyn Any).downcast_ref::<T>())
}
pub fn contains<T: Any>(&self) -> bool {
self.entries.contains_key(&TypeId::of::<T>())
}
pub fn remove<T: Any + Send + Sync>(&mut self) -> Option<Arc<T>> {
self.entries
.remove(&TypeId::of::<T>())
.and_then(|prev| prev.downcast::<T>().ok())
}
pub fn clear(&mut self) {
self.entries.clear();
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl fmt::Debug for CallAttachments {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CallAttachments")
.field("len", &self.entries.len())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ToolCallContext {
pub call_block_id: BlockId,
pub input: ToolCallPayload,
pub result_notes: Vec<TextPayload>,
pub(crate) attachments: CallAttachments,
}
impl ToolCallContext {
pub fn new(call_block_id: BlockId, input: ToolCallPayload) -> Self {
Self {
call_block_id,
input,
result_notes: Vec::new(),
attachments: CallAttachments::default(),
}
}
pub fn from_declaration(call_block_id: BlockId, declaration: &ToolCallPayload) -> Self {
Self {
call_block_id,
input: declaration.clone(),
result_notes: Vec::new(),
attachments: CallAttachments::default(),
}
}
pub fn attachment<T: Any>(&self) -> Option<&T> {
self.attachments.get::<T>()
}
pub fn attachments(&self) -> &CallAttachments {
&self.attachments
}
pub fn with_attachment<T: Any + Send + Sync>(mut self, value: T) -> Self {
self.attachments.insert(value);
self
}
}
#[non_exhaustive]
pub struct ArtifactHint {
pub tool_name: String,
pub call_block_id: BlockId,
pub kind: ArtifactKind,
}
impl ArtifactHint {
pub fn new(tool_name: impl Into<String>, call_block_id: BlockId, kind: ArtifactKind) -> Self {
Self {
tool_name: tool_name.into(),
call_block_id,
kind,
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum StoreError {
#[error("persist failed: {0}")]
Persist(String),
#[error("read failed: {0}")]
Read(String),
}
#[async_trait]
pub trait ArtifactStore: Send + Sync {
async fn persist(&self, data: &[u8], hint: ArtifactHint) -> Result<ArtifactRef, StoreError>;
async fn read(
&self,
id: &str,
range: Option<std::ops::Range<u64>>,
) -> Result<Vec<u8>, StoreError>;
}
#[async_trait]
pub trait Tool: Send + Sync {
fn definition(&self) -> ToolDefinition;
fn metadata(&self) -> ToolMetadata {
ToolMetadata::default()
}
async fn execute(
&self,
ctx: &ToolCallContext,
control: &CallControl,
store: Option<&dyn ArtifactStore>,
) -> ToolResultPayload;
}