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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
27 pub effects: Vec<ToolEffect>,
28}
29
30impl ToolSpec {
31 pub fn new(name: impl Into<String>, description: impl Into<String>, parameters: serde_json::Value) -> Self {
33 Self { name: name.into(), description: description.into(), parameters, effects: Vec::new() }
34 }
35
36 #[must_use]
38 pub fn with_effects(mut self, effects: Vec<ToolEffect>) -> Self {
39 self.effects = effects;
40 self
41 }
42
43 pub fn needs_approval(&self) -> bool {
46 self.effects.iter().any(|effect| effect.needs_approval())
47 }
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum ToolEffect {
55 Read,
57 Write,
59 Send,
62 Pay,
64}
65
66impl ToolEffect {
67 pub const ALL: [ToolEffect; 4] = [ToolEffect::Read, ToolEffect::Write, ToolEffect::Send, ToolEffect::Pay];
69
70 pub fn as_str(self) -> &'static str {
72 match self {
73 Self::Read => "read",
74 Self::Write => "write",
75 Self::Send => "send",
76 Self::Pay => "pay",
77 }
78 }
79
80 pub fn needs_approval(self) -> bool {
83 matches!(self, Self::Send | Self::Pay)
84 }
85}
86
87#[derive(Clone, Debug, Default, PartialEq)]
89pub struct ToolOutput {
90 pub text: String,
92 pub data: Value,
94 pub is_error: bool,
96 pub images: Vec<ToolImage>,
98}
99
100impl ToolOutput {
101 pub fn text(text: impl Into<String>) -> Self {
102 Self { text: text.into(), ..Self::default() }
103 }
104
105 pub fn error(text: impl Into<String>) -> Self {
106 Self { text: text.into(), is_error: true, ..Self::default() }
107 }
108
109 pub fn with_image(mut self, image: ToolImage) -> Self {
111 self.images.push(image);
112 self
113 }
114}
115
116pub const MAX_TOOL_IMAGES: usize = 4;
118pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
120pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
122
123#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(untagged)]
129pub enum ToolImage {
130 Base64 { media_type: String, data_base64: String },
132 Url { url: String },
134}
135
136impl ToolImage {
137 pub fn png(data_base64: impl Into<String>) -> Self {
139 Self::Base64 { media_type: "image/png".into(), data_base64: data_base64.into() }
140 }
141
142 pub fn jpeg(data_base64: impl Into<String>) -> Self {
144 Self::Base64 { media_type: "image/jpeg".into(), data_base64: data_base64.into() }
145 }
146
147 pub fn to_url(&self) -> String {
149 match self {
150 ToolImage::Base64 { media_type, data_base64 } => format!("data:{media_type};base64,{data_base64}"),
151 ToolImage::Url { url } => url.clone(),
152 }
153 }
154
155 pub fn check(&self) -> Result<(), ToolImageError> {
157 match self {
158 ToolImage::Url { url } => {
159 if url.len() > 8 && url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://")) {
160 Ok(())
161 } else {
162 Err(ToolImageError::new("image URLs must start with https:// (send inline images as base64)"))
163 }
164 }
165 ToolImage::Base64 { media_type, data_base64 } => {
166 if !TOOL_IMAGE_MEDIA_TYPES.contains(&media_type.as_str()) {
167 return Err(ToolImageError::new(format!(
168 "image media type `{media_type}` is not supported (use {})",
169 TOOL_IMAGE_MEDIA_TYPES.join(", ")
170 )));
171 }
172 let decoded = base64_decoded_len(data_base64)
173 .ok_or_else(|| ToolImageError::new("image data is not valid base64"))?;
174 if decoded == 0 {
175 return Err(ToolImageError::new("image data is empty"));
176 }
177 if decoded > MAX_TOOL_IMAGE_BYTES {
178 return Err(ToolImageError::new(format!(
179 "image is {decoded} bytes, above the {MAX_TOOL_IMAGE_BYTES}-byte limit"
180 )));
181 }
182 Ok(())
183 }
184 }
185 }
186}
187
188#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
190#[error("{0}")]
191pub struct ToolImageError(pub String);
192
193impl ToolImageError {
194 fn new(message: impl Into<String>) -> Self {
195 Self(message.into())
196 }
197}
198
199pub fn check_images(images: &[ToolImage]) -> Result<(), ToolImageError> {
202 if images.len() > MAX_TOOL_IMAGES {
203 return Err(ToolImageError::new(format!(
204 "{} images in one tool result, above the limit of {MAX_TOOL_IMAGES}",
205 images.len()
206 )));
207 }
208 for (index, image) in images.iter().enumerate() {
209 image.check().map_err(|e| ToolImageError::new(format!("image #{index}: {e}")))?;
210 }
211 Ok(())
212}
213
214fn base64_decoded_len(text: &str) -> Option<usize> {
217 let bytes = text.as_bytes();
218 let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(bytes);
219 let alphabet = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/';
220 if !body.iter().all(alphabet) {
221 return None;
222 }
223 let padded = body.len() != bytes.len();
224 if padded && !bytes.len().is_multiple_of(4) {
225 return None;
226 }
227 match body.len() % 4 {
228 1 => None,
229 rest => Some(body.len() / 4 * 3 + rest.saturating_sub(1)),
230 }
231}
232
233pub const MAX_TOOL_FILES: usize = 16;
235const MAX_FILE_SCAN_DEPTH: usize = 3;
237
238pub fn collect_files(data: &Value) -> Vec<Arc<crate::value::File>> {
258 let mut files = Vec::new();
259 collect_files_into(data, 0, &mut files);
260 files
261}
262
263fn collect_files_into(value: &Value, depth: usize, files: &mut Vec<Arc<crate::value::File>>) {
264 if files.len() >= MAX_TOOL_FILES {
265 return;
266 }
267 match value {
268 Value::File(file) => files.push(Arc::clone(file)),
269 Value::Array(items) if depth < MAX_FILE_SCAN_DEPTH => {
270 items.iter().for_each(|item| collect_files_into(item, depth + 1, files));
271 }
272 Value::Object(fields) if depth < MAX_FILE_SCAN_DEPTH => {
273 fields.values().for_each(|field| collect_files_into(field, depth + 1, files));
274 }
275 _ => {}
276 }
277}
278
279#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
281#[error("tool `{tool}`: {message}")]
282pub struct ToolError {
283 pub tool: String,
284 pub message: String,
285}
286
287#[derive(Clone, Default, PartialEq, Eq)]
296pub struct ToolCallContext {
297 pub secrets: BTreeMap<String, String>,
299 pub idempotency_key: Option<String>,
303}
304
305static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext = ToolCallContext { secrets: BTreeMap::new(), idempotency_key: None };
306
307impl ToolCallContext {
308 pub fn empty() -> &'static ToolCallContext {
310 &EMPTY_TOOL_CALL_CONTEXT
311 }
312
313 pub fn is_empty(&self) -> bool {
315 self.secrets.is_empty()
316 }
317
318 pub fn secret(&self, name: &str) -> Option<&str> {
320 self.secrets.get(name).map(String::as_str)
321 }
322}
323
324impl fmt::Debug for ToolCallContext {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 f.debug_struct("ToolCallContext")
327 .field("secrets", &self.secrets.keys().collect::<Vec<_>>())
328 .field("idempotency_key", &self.idempotency_key)
329 .finish()
330 }
331}
332
333pub trait ToolRuntime: Send + Sync + fmt::Debug {
335 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
337
338 fn call<'a>(
343 &'a self,
344 name: &'a str,
345 arguments: serde_json::Value,
346 context: &'a ToolCallContext,
347 ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
348
349 fn accepts_secrets(&self) -> bool {
354 false
355 }
356}
357
358#[derive(Clone, Default)]
361pub struct ToolRegistry {
362 providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
363}
364
365impl fmt::Debug for ToolRegistry {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 f.debug_list().entries(self.providers.keys()).finish()
368 }
369}
370
371impl ToolRegistry {
372 pub fn new() -> Self {
373 Self::default()
374 }
375
376 pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
377 self.providers.insert(provider.into(), runtime);
378 self
379 }
380
381 pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
382 self.providers.get(provider)
383 }
384
385 pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
386 self.providers.iter().map(|(k, v)| (k.as_str(), v))
387 }
388}
389
390#[cfg(test)]
391mod tests {
392 use super::*;
393
394 #[test]
395 fn call_context_debug_hides_values() {
396 assert!(ToolCallContext::empty().is_empty());
397 let mut context = ToolCallContext::default();
398 context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
399 assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
400 assert_eq!(context.secret("other"), None);
401 let debug = format!("{context:?}");
402 assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
403 }
404
405 #[test]
406 fn files_are_collected_in_order_up_to_the_cap() {
407 let file =
408 |name: &str| Value::from(crate::value::File { marker: true, name: name.into(), ..Default::default() });
409 let names = |data: &Value| collect_files(data).iter().map(|f| f.name.clone()).collect::<Vec<_>>();
410 assert_eq!(names(&file("a")), ["a"]);
411 let nested = Value::object([
412 ("file", file("a")),
413 ("files", Value::array([file("b"), file("c")])),
414 ("text", Value::from("x")),
415 ]);
416 assert_eq!(names(&nested), ["a", "b", "c"]);
417 let deep = Value::array([Value::array([Value::array([Value::array([file("deep")])])])]);
419 assert!(names(&deep).is_empty());
420 let many = Value::array((0..MAX_TOOL_FILES + 5).map(|i| file(&i.to_string())));
421 assert_eq!(collect_files(&many).len(), MAX_TOOL_FILES);
422 assert!(collect_files(&Value::Null).is_empty());
423 }
424
425 #[test]
426 fn constructors_have_no_images() {
427 assert!(ToolOutput::text("a").images.is_empty());
428 let err = ToolOutput::error("b");
429 assert!(err.is_error && err.images.is_empty());
430 let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
431 assert_eq!(out.images.len(), 1);
432 }
433
434 #[test]
435 fn image_urls() {
436 assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
437 assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
438 }
439
440 #[test]
441 fn serde_shapes() {
442 let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
443 {"media_type": "image/png", "data_base64": "AAAA"},
444 {"url": "https://x/a.png"}
445 ]))
446 .unwrap();
447 assert_eq!(images[0], ToolImage::png("AAAA"));
448 assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
449 assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
450 }
451
452 #[test]
453 fn base64_lengths() {
454 assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
455 assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
456 assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
457 assert_eq!(base64_decoded_len("aGVs"), Some(3));
458 assert_eq!(base64_decoded_len("aGVsb"), None);
459 assert_eq!(base64_decoded_len("aGV="), Some(2));
460 assert_eq!(base64_decoded_len("aG V"), None);
461 assert_eq!(base64_decoded_len("aGVsbG8=="), None);
462 assert_eq!(base64_decoded_len(""), Some(0));
463 }
464
465 #[test]
466 fn limits_are_enforced() {
467 assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
468 let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
469 assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
470 let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
471 assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
472 assert!(ToolImage::png("not base64!").check().is_err());
473 assert!(ToolImage::png("").check().is_err());
474 let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
475 assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
476 let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
477 assert!(ToolImage::png(exact).check().is_ok());
478 assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
479 assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
480 assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
481 }
482}