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 pub cost_micros: u64,
102}
103
104impl ToolOutput {
105 pub fn text(text: impl Into<String>) -> Self {
106 Self { text: text.into(), ..Self::default() }
107 }
108
109 pub fn error(text: impl Into<String>) -> Self {
110 Self { text: text.into(), is_error: true, ..Self::default() }
111 }
112
113 pub fn with_image(mut self, image: ToolImage) -> Self {
115 self.images.push(image);
116 self
117 }
118}
119
120pub const MAX_TOOL_IMAGES: usize = 4;
122pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
124pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
126
127#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(untagged)]
133pub enum ToolImage {
134 Base64 { media_type: String, data_base64: String },
136 Url { url: String },
138}
139
140impl ToolImage {
141 pub fn png(data_base64: impl Into<String>) -> Self {
143 Self::Base64 { media_type: "image/png".into(), data_base64: data_base64.into() }
144 }
145
146 pub fn jpeg(data_base64: impl Into<String>) -> Self {
148 Self::Base64 { media_type: "image/jpeg".into(), data_base64: data_base64.into() }
149 }
150
151 pub fn to_url(&self) -> String {
153 match self {
154 ToolImage::Base64 { media_type, data_base64 } => format!("data:{media_type};base64,{data_base64}"),
155 ToolImage::Url { url } => url.clone(),
156 }
157 }
158
159 pub fn check(&self) -> Result<(), ToolImageError> {
161 match self {
162 ToolImage::Url { url } => {
163 if url.len() > 8 && url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://")) {
164 Ok(())
165 } else {
166 Err(ToolImageError::new("image URLs must start with https:// (send inline images as base64)"))
167 }
168 }
169 ToolImage::Base64 { media_type, data_base64 } => {
170 if !TOOL_IMAGE_MEDIA_TYPES.contains(&media_type.as_str()) {
171 return Err(ToolImageError::new(format!(
172 "image media type `{media_type}` is not supported (use {})",
173 TOOL_IMAGE_MEDIA_TYPES.join(", ")
174 )));
175 }
176 let decoded = base64_decoded_len(data_base64)
177 .ok_or_else(|| ToolImageError::new("image data is not valid base64"))?;
178 if decoded == 0 {
179 return Err(ToolImageError::new("image data is empty"));
180 }
181 if decoded > MAX_TOOL_IMAGE_BYTES {
182 return Err(ToolImageError::new(format!(
183 "image is {decoded} bytes, above the {MAX_TOOL_IMAGE_BYTES}-byte limit"
184 )));
185 }
186 Ok(())
187 }
188 }
189 }
190}
191
192#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
194#[error("{0}")]
195pub struct ToolImageError(pub String);
196
197impl ToolImageError {
198 fn new(message: impl Into<String>) -> Self {
199 Self(message.into())
200 }
201}
202
203pub fn check_images(images: &[ToolImage]) -> Result<(), ToolImageError> {
206 if images.len() > MAX_TOOL_IMAGES {
207 return Err(ToolImageError::new(format!(
208 "{} images in one tool result, above the limit of {MAX_TOOL_IMAGES}",
209 images.len()
210 )));
211 }
212 for (index, image) in images.iter().enumerate() {
213 image.check().map_err(|e| ToolImageError::new(format!("image #{index}: {e}")))?;
214 }
215 Ok(())
216}
217
218fn base64_decoded_len(text: &str) -> Option<usize> {
221 let bytes = text.as_bytes();
222 let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(bytes);
223 let alphabet = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/';
224 if !body.iter().all(alphabet) {
225 return None;
226 }
227 let padded = body.len() != bytes.len();
228 if padded && !bytes.len().is_multiple_of(4) {
229 return None;
230 }
231 match body.len() % 4 {
232 1 => None,
233 rest => Some(body.len() / 4 * 3 + rest.saturating_sub(1)),
234 }
235}
236
237pub const MAX_TOOL_FILES: usize = 16;
239const MAX_FILE_SCAN_DEPTH: usize = 3;
241
242pub fn collect_files(data: &Value) -> Vec<Arc<crate::value::File>> {
262 let mut files = Vec::new();
263 collect_files_into(data, 0, &mut files);
264 files
265}
266
267fn collect_files_into(value: &Value, depth: usize, files: &mut Vec<Arc<crate::value::File>>) {
268 if files.len() >= MAX_TOOL_FILES {
269 return;
270 }
271 match value {
272 Value::File(file) => files.push(Arc::clone(file)),
273 Value::Array(items) if depth < MAX_FILE_SCAN_DEPTH => {
274 items.iter().for_each(|item| collect_files_into(item, depth + 1, files));
275 }
276 Value::Object(fields) if depth < MAX_FILE_SCAN_DEPTH => {
277 fields.values().for_each(|field| collect_files_into(field, depth + 1, files));
278 }
279 _ => {}
280 }
281}
282
283#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
285#[error("tool `{tool}`: {message}")]
286pub struct ToolError {
287 pub tool: String,
288 pub message: String,
289}
290
291#[derive(Clone, Default, PartialEq, Eq)]
300pub struct ToolCallContext {
301 pub secrets: BTreeMap<String, String>,
303 pub idempotency_key: Option<String>,
307 pub remaining_cost_micros: Option<u64>,
311}
312
313static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext =
314 ToolCallContext { secrets: BTreeMap::new(), idempotency_key: None, remaining_cost_micros: None };
315
316impl ToolCallContext {
317 pub fn empty() -> &'static ToolCallContext {
319 &EMPTY_TOOL_CALL_CONTEXT
320 }
321
322 pub fn is_empty(&self) -> bool {
324 self.secrets.is_empty()
325 }
326
327 pub fn secret(&self, name: &str) -> Option<&str> {
329 self.secrets.get(name).map(String::as_str)
330 }
331}
332
333impl fmt::Debug for ToolCallContext {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.debug_struct("ToolCallContext")
336 .field("secrets", &self.secrets.keys().collect::<Vec<_>>())
337 .field("idempotency_key", &self.idempotency_key)
338 .field("remaining_cost_micros", &self.remaining_cost_micros)
339 .finish()
340 }
341}
342
343pub trait ToolRuntime: Send + Sync + fmt::Debug {
345 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
347
348 fn call<'a>(
353 &'a self,
354 name: &'a str,
355 arguments: serde_json::Value,
356 context: &'a ToolCallContext,
357 ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
358
359 fn accepts_secrets(&self) -> bool {
364 false
365 }
366}
367
368#[derive(Clone, Default)]
371pub struct ToolRegistry {
372 providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
373}
374
375impl fmt::Debug for ToolRegistry {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.debug_list().entries(self.providers.keys()).finish()
378 }
379}
380
381impl ToolRegistry {
382 pub fn new() -> Self {
383 Self::default()
384 }
385
386 pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
387 self.providers.insert(provider.into(), runtime);
388 self
389 }
390
391 pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
392 self.providers.get(provider)
393 }
394
395 pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
396 self.providers.iter().map(|(k, v)| (k.as_str(), v))
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 #[test]
405 fn call_context_debug_hides_values() {
406 assert!(ToolCallContext::empty().is_empty());
407 let mut context = ToolCallContext::default();
408 context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
409 assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
410 assert_eq!(context.secret("other"), None);
411 let debug = format!("{context:?}");
412 assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
413 }
414
415 #[test]
416 fn files_are_collected_in_order_up_to_the_cap() {
417 let file =
418 |name: &str| Value::from(crate::value::File { marker: true, name: name.into(), ..Default::default() });
419 let names = |data: &Value| collect_files(data).iter().map(|f| f.name.clone()).collect::<Vec<_>>();
420 assert_eq!(names(&file("a")), ["a"]);
421 let nested = Value::object([
422 ("file", file("a")),
423 ("files", Value::array([file("b"), file("c")])),
424 ("text", Value::from("x")),
425 ]);
426 assert_eq!(names(&nested), ["a", "b", "c"]);
427 let deep = Value::array([Value::array([Value::array([Value::array([file("deep")])])])]);
429 assert!(names(&deep).is_empty());
430 let many = Value::array((0..MAX_TOOL_FILES + 5).map(|i| file(&i.to_string())));
431 assert_eq!(collect_files(&many).len(), MAX_TOOL_FILES);
432 assert!(collect_files(&Value::Null).is_empty());
433 }
434
435 #[test]
436 fn constructors_have_no_images() {
437 assert!(ToolOutput::text("a").images.is_empty());
438 let err = ToolOutput::error("b");
439 assert!(err.is_error && err.images.is_empty());
440 let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
441 assert_eq!(out.images.len(), 1);
442 }
443
444 #[test]
445 fn image_urls() {
446 assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
447 assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
448 }
449
450 #[test]
451 fn serde_shapes() {
452 let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
453 {"media_type": "image/png", "data_base64": "AAAA"},
454 {"url": "https://x/a.png"}
455 ]))
456 .unwrap();
457 assert_eq!(images[0], ToolImage::png("AAAA"));
458 assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
459 assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
460 }
461
462 #[test]
463 fn base64_lengths() {
464 assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
465 assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
466 assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
467 assert_eq!(base64_decoded_len("aGVs"), Some(3));
468 assert_eq!(base64_decoded_len("aGVsb"), None);
469 assert_eq!(base64_decoded_len("aGV="), Some(2));
470 assert_eq!(base64_decoded_len("aG V"), None);
471 assert_eq!(base64_decoded_len("aGVsbG8=="), None);
472 assert_eq!(base64_decoded_len(""), Some(0));
473 }
474
475 #[test]
476 fn limits_are_enforced() {
477 assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
478 let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
479 assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
480 let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
481 assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
482 assert!(ToolImage::png("not base64!").check().is_err());
483 assert!(ToolImage::png("").check().is_err());
484 let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
485 assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
486 let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
487 assert!(ToolImage::png(exact).check().is_ok());
488 assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
489 assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
490 assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
491 }
492}