1use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7
8use futures::future::BoxFuture;
9use serde::{Deserialize, Serialize};
10
11use crate::value::Value;
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15pub struct ToolSpec {
16 pub name: String,
18 pub description: String,
19 pub parameters: serde_json::Value,
21}
22
23#[derive(Clone, Debug, Default, PartialEq)]
25pub struct ToolOutput {
26 pub text: String,
28 pub data: Value,
30 pub is_error: bool,
32 pub images: Vec<ToolImage>,
34}
35
36impl ToolOutput {
37 pub fn text(text: impl Into<String>) -> Self {
38 Self { text: text.into(), ..Self::default() }
39 }
40
41 pub fn error(text: impl Into<String>) -> Self {
42 Self { text: text.into(), is_error: true, ..Self::default() }
43 }
44
45 pub fn with_image(mut self, image: ToolImage) -> Self {
47 self.images.push(image);
48 self
49 }
50}
51
52pub const MAX_TOOL_IMAGES: usize = 4;
54pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
56pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
58
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(untagged)]
65pub enum ToolImage {
66 Base64 { media_type: String, data_base64: String },
68 Url { url: String },
70}
71
72impl ToolImage {
73 pub fn png(data_base64: impl Into<String>) -> Self {
75 Self::Base64 { media_type: "image/png".into(), data_base64: data_base64.into() }
76 }
77
78 pub fn jpeg(data_base64: impl Into<String>) -> Self {
80 Self::Base64 { media_type: "image/jpeg".into(), data_base64: data_base64.into() }
81 }
82
83 pub fn to_url(&self) -> String {
85 match self {
86 ToolImage::Base64 { media_type, data_base64 } => format!("data:{media_type};base64,{data_base64}"),
87 ToolImage::Url { url } => url.clone(),
88 }
89 }
90
91 pub fn check(&self) -> Result<(), ToolImageError> {
93 match self {
94 ToolImage::Url { url } => {
95 if url.len() > 8 && url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://")) {
96 Ok(())
97 } else {
98 Err(ToolImageError::new("image URLs must start with https:// (send inline images as base64)"))
99 }
100 }
101 ToolImage::Base64 { media_type, data_base64 } => {
102 if !TOOL_IMAGE_MEDIA_TYPES.contains(&media_type.as_str()) {
103 return Err(ToolImageError::new(format!(
104 "image media type `{media_type}` is not supported (use {})",
105 TOOL_IMAGE_MEDIA_TYPES.join(", ")
106 )));
107 }
108 let decoded = base64_decoded_len(data_base64)
109 .ok_or_else(|| ToolImageError::new("image data is not valid base64"))?;
110 if decoded == 0 {
111 return Err(ToolImageError::new("image data is empty"));
112 }
113 if decoded > MAX_TOOL_IMAGE_BYTES {
114 return Err(ToolImageError::new(format!(
115 "image is {decoded} bytes, above the {MAX_TOOL_IMAGE_BYTES}-byte limit"
116 )));
117 }
118 Ok(())
119 }
120 }
121 }
122}
123
124#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
126#[error("{0}")]
127pub struct ToolImageError(pub String);
128
129impl ToolImageError {
130 fn new(message: impl Into<String>) -> Self {
131 Self(message.into())
132 }
133}
134
135pub fn check_images(images: &[ToolImage]) -> Result<(), ToolImageError> {
138 if images.len() > MAX_TOOL_IMAGES {
139 return Err(ToolImageError::new(format!(
140 "{} images in one tool result, above the limit of {MAX_TOOL_IMAGES}",
141 images.len()
142 )));
143 }
144 for (index, image) in images.iter().enumerate() {
145 image.check().map_err(|e| ToolImageError::new(format!("image #{index}: {e}")))?;
146 }
147 Ok(())
148}
149
150fn base64_decoded_len(text: &str) -> Option<usize> {
153 let bytes = text.as_bytes();
154 let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(bytes);
155 let alphabet = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/';
156 if !body.iter().all(alphabet) {
157 return None;
158 }
159 let padded = body.len() != bytes.len();
160 if padded && !bytes.len().is_multiple_of(4) {
161 return None;
162 }
163 match body.len() % 4 {
164 1 => None,
165 rest => Some(body.len() / 4 * 3 + rest.saturating_sub(1)),
166 }
167}
168
169#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
171#[error("tool `{tool}`: {message}")]
172pub struct ToolError {
173 pub tool: String,
174 pub message: String,
175}
176
177#[derive(Clone, Default, PartialEq, Eq)]
186pub struct ToolCallContext {
187 pub secrets: BTreeMap<String, String>,
189}
190
191static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext = ToolCallContext { secrets: BTreeMap::new() };
192
193impl ToolCallContext {
194 pub fn empty() -> &'static ToolCallContext {
196 &EMPTY_TOOL_CALL_CONTEXT
197 }
198
199 pub fn is_empty(&self) -> bool {
201 self.secrets.is_empty()
202 }
203
204 pub fn secret(&self, name: &str) -> Option<&str> {
206 self.secrets.get(name).map(String::as_str)
207 }
208}
209
210impl fmt::Debug for ToolCallContext {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 f.debug_struct("ToolCallContext").field("secrets", &self.secrets.keys().collect::<Vec<_>>()).finish()
213 }
214}
215
216pub trait ToolRuntime: Send + Sync + fmt::Debug {
218 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
220
221 fn call<'a>(
226 &'a self,
227 name: &'a str,
228 arguments: serde_json::Value,
229 context: &'a ToolCallContext,
230 ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
231
232 fn accepts_secrets(&self) -> bool {
237 false
238 }
239}
240
241#[derive(Clone, Default)]
244pub struct ToolRegistry {
245 providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
246}
247
248impl fmt::Debug for ToolRegistry {
249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 f.debug_list().entries(self.providers.keys()).finish()
251 }
252}
253
254impl ToolRegistry {
255 pub fn new() -> Self {
256 Self::default()
257 }
258
259 pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
260 self.providers.insert(provider.into(), runtime);
261 self
262 }
263
264 pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
265 self.providers.get(provider)
266 }
267
268 pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
269 self.providers.iter().map(|(k, v)| (k.as_str(), v))
270 }
271}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 #[test]
278 fn call_context_debug_hides_values() {
279 assert!(ToolCallContext::empty().is_empty());
280 let mut context = ToolCallContext::default();
281 context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
282 assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
283 assert_eq!(context.secret("other"), None);
284 let debug = format!("{context:?}");
285 assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
286 }
287
288 #[test]
289 fn constructors_have_no_images() {
290 assert!(ToolOutput::text("a").images.is_empty());
291 let err = ToolOutput::error("b");
292 assert!(err.is_error && err.images.is_empty());
293 let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
294 assert_eq!(out.images.len(), 1);
295 }
296
297 #[test]
298 fn image_urls() {
299 assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
300 assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
301 }
302
303 #[test]
304 fn serde_shapes() {
305 let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
306 {"media_type": "image/png", "data_base64": "AAAA"},
307 {"url": "https://x/a.png"}
308 ]))
309 .unwrap();
310 assert_eq!(images[0], ToolImage::png("AAAA"));
311 assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
312 assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
313 }
314
315 #[test]
316 fn base64_lengths() {
317 assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
318 assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
319 assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
320 assert_eq!(base64_decoded_len("aGVs"), Some(3));
321 assert_eq!(base64_decoded_len("aGVsb"), None);
322 assert_eq!(base64_decoded_len("aGV="), Some(2));
323 assert_eq!(base64_decoded_len("aG V"), None);
324 assert_eq!(base64_decoded_len("aGVsbG8=="), None);
325 assert_eq!(base64_decoded_len(""), Some(0));
326 }
327
328 #[test]
329 fn limits_are_enforced() {
330 assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
331 let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
332 assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
333 let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
334 assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
335 assert!(ToolImage::png("not base64!").check().is_err());
336 assert!(ToolImage::png("").check().is_err());
337 let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
338 assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
339 let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
340 assert!(ToolImage::png(exact).check().is_ok());
341 assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
342 assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
343 assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
344 }
345}