1#[cfg(feature = "derive")]
208pub use aither_derive::tool;
209use alloc::borrow::Cow;
210use serde_json::Value;
211
212use crate::Result;
213use alloc::format;
214use alloc::string::{String, ToString};
215use alloc::vec::Vec;
216use alloc::{boxed::Box, collections::BTreeMap};
217use core::any::Any;
218use core::fmt::{Debug, Display};
219use core::{future::Future, pin::Pin};
220pub use mime::Mime;
221use schemars::{JsonSchema, Schema, schema_for};
222use serde::de::DeserializeOwned;
223
224mod approval;
225mod cancel;
226mod command;
227mod context;
228mod identity;
229
230pub use approval::{
231 AnyApprover, Approval, ApprovalError, ApprovalKind, ApprovalRequest, Approver, ApproverFailure,
232};
233pub use cancel::{CancelSignal, Canceller};
234pub use command::{
235 CommandOutcome, CommandResult, CommandStream, Interruption, InterruptionCause, StoredFile,
236 render_interruptions,
237};
238pub use context::{Progress, ProgressError, ProgressSink, ToolContext};
239pub use identity::{AgentIdentity, AgentPath, CallIdentity, SubagentIdentity, ToolCallId};
240
241#[derive(Debug, Clone, PartialEq, Eq)]
260#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
261#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
262pub enum ToolResult {
263 Done,
265
266 Text {
268 text: String,
270 },
271
272 Tsv {
274 text: String,
276 },
277
278 Binary {
280 mime: String,
282 content: Vec<u8>,
284 },
285
286 Error {
288 message: String,
290 },
291
292 Command(Box<CommandResult>),
298
299 Parts {
306 parts: Vec<ToolResultPart>,
308 },
309}
310
311#[derive(Debug, Clone, PartialEq, Eq)]
316#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
317#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
318pub enum ToolResultPart {
319 Text {
321 text: String,
323 },
324
325 Tsv {
327 text: String,
329 },
330
331 Binary {
333 mime: String,
335 content: Vec<u8>,
337 },
338}
339
340impl ToolResult {
341 #[must_use]
343 pub fn text(s: impl Into<String>) -> Self {
344 Self::Text { text: s.into() }
345 }
346
347 #[must_use]
349 pub fn tsv(s: impl Into<String>) -> Self {
350 Self::Tsv { text: s.into() }
351 }
352
353 #[must_use]
355 pub fn image(data: Vec<u8>, media_type: &str) -> Self {
356 Self::Binary {
357 mime: parse_media_type_or_octet_stream(media_type),
358 content: data,
359 }
360 }
361
362 #[must_use]
364 pub fn binary(data: Vec<u8>) -> Self {
365 Self::Binary {
366 mime: mime::APPLICATION_OCTET_STREAM.essence_str().to_string(),
367 content: data,
368 }
369 }
370
371 #[must_use]
373 pub fn error(message: impl Into<String>) -> Self {
374 Self::Error {
375 message: message.into(),
376 }
377 }
378
379 #[must_use]
385 pub fn parts(parts: Vec<ToolResultPart>) -> Self {
386 match <[ToolResultPart; 1]>::try_from(parts) {
387 Ok([part]) => part.into_result(),
388 Err(parts) if parts.is_empty() => Self::Done,
389 Err(parts) => Self::Parts { parts },
390 }
391 }
392
393 #[must_use]
395 pub const fn is_done(&self) -> bool {
396 matches!(self, Self::Done)
397 }
398
399 #[must_use]
401 pub const fn is_error(&self) -> bool {
402 matches!(self, Self::Error { .. })
403 }
404
405 #[must_use]
407 pub fn as_text(&self) -> Option<&str> {
408 match self {
409 Self::Text { text } | Self::Tsv { text } => Some(text),
410 Self::Error { message } => Some(message),
411 Self::Done | Self::Binary { .. } | Self::Command(_) | Self::Parts { .. } => None,
412 }
413 }
414
415 #[must_use]
417 pub fn command(&self) -> Option<&CommandResult> {
418 match self {
419 Self::Command(command) => Some(command.as_ref()),
420 _ => None,
421 }
422 }
423
424 #[must_use]
426 pub fn error_message(&self) -> Option<&str> {
427 match self {
428 Self::Error { message } => Some(message),
429 Self::Done
430 | Self::Text { .. }
431 | Self::Tsv { .. }
432 | Self::Binary { .. }
433 | Self::Command(_)
434 | Self::Parts { .. } => None,
435 }
436 }
437
438 #[must_use]
440 pub fn render_for_model(&self) -> String {
441 match self {
442 Self::Done => String::new(),
443 Self::Text { text } | Self::Tsv { text } => text.clone(),
444 Self::Command(command) => command.render_for_model(),
445 Self::Binary { mime, content } => render_binary_placeholder(mime, content),
446 Self::Error { message } => message.clone(),
447 Self::Parts { parts } => join_part_renders(parts),
448 }
449 }
450
451 #[must_use]
456 pub fn mime(&self) -> Option<Mime> {
457 match self {
458 Self::Binary { mime, .. } => mime.parse().ok(),
459 Self::Parts { parts } => match parts.as_slice() {
460 [ToolResultPart::Binary { mime, .. }] => mime.parse().ok(),
461 _ => None,
462 },
463 Self::Done
464 | Self::Text { .. }
465 | Self::Tsv { .. }
466 | Self::Command(_)
467 | Self::Error { .. } => None,
468 }
469 }
470
471 #[must_use]
475 pub fn content(&self) -> Option<&[u8]> {
476 match self {
477 Self::Binary { content, .. } => Some(content),
478 Self::Parts { parts } => match parts.as_slice() {
479 [ToolResultPart::Binary { content, .. }] => Some(content),
480 _ => None,
481 },
482 Self::Done
483 | Self::Text { .. }
484 | Self::Tsv { .. }
485 | Self::Command(_)
486 | Self::Error { .. } => None,
487 }
488 }
489}
490
491impl ToolResultPart {
492 #[must_use]
494 pub fn text(s: impl Into<String>) -> Self {
495 Self::Text { text: s.into() }
496 }
497
498 #[must_use]
500 pub fn tsv(s: impl Into<String>) -> Self {
501 Self::Tsv { text: s.into() }
502 }
503
504 #[must_use]
506 pub fn image(data: Vec<u8>, media_type: &str) -> Self {
507 Self::Binary {
508 mime: parse_media_type_or_octet_stream(media_type),
509 content: data,
510 }
511 }
512
513 #[must_use]
515 pub fn binary(data: Vec<u8>) -> Self {
516 Self::Binary {
517 mime: mime::APPLICATION_OCTET_STREAM.essence_str().to_string(),
518 content: data,
519 }
520 }
521
522 #[must_use]
524 pub fn as_text(&self) -> Option<&str> {
525 match self {
526 Self::Text { text } | Self::Tsv { text } => Some(text),
527 Self::Binary { .. } => None,
528 }
529 }
530
531 #[must_use]
533 pub fn render_for_model(&self) -> String {
534 match self {
535 Self::Text { text } | Self::Tsv { text } => text.clone(),
536 Self::Binary { mime, content } => render_binary_placeholder(mime, content),
537 }
538 }
539
540 #[must_use]
542 pub fn mime(&self) -> Option<Mime> {
543 match self {
544 Self::Binary { mime, .. } => mime.parse().ok(),
545 Self::Text { .. } | Self::Tsv { .. } => None,
546 }
547 }
548
549 #[must_use]
551 pub fn content(&self) -> Option<&[u8]> {
552 match self {
553 Self::Binary { content, .. } => Some(content),
554 Self::Text { .. } | Self::Tsv { .. } => None,
555 }
556 }
557
558 #[must_use]
560 pub fn into_result(self) -> ToolResult {
561 match self {
562 Self::Text { text } | Self::Tsv { text } => ToolResult::Text { text },
563 Self::Binary { mime, content } => ToolResult::Binary { mime, content },
564 }
565 }
566}
567
568fn render_binary_placeholder(mime: &str, content: &[u8]) -> String {
569 let mut rendered = String::new();
570 rendered.push_str("[binary tool result: ");
571 rendered.push_str(mime);
572 rendered.push_str(", ");
573 rendered.push_str(content.len().to_string().as_str());
574 rendered.push_str(" bytes]");
575 rendered
576}
577
578fn join_part_renders(parts: &[ToolResultPart]) -> String {
579 let mut rendered = String::new();
580 for part in parts {
581 let text = part.render_for_model();
582 if text.is_empty() {
583 continue;
584 }
585 if !rendered.is_empty() {
586 rendered.push('\n');
587 }
588 rendered.push_str(&text);
589 }
590 rendered
591}
592
593pub trait IntoToolResult {
599 fn into_tool_result(self) -> Result<ToolResult>;
605}
606
607impl IntoToolResult for ToolResult {
608 fn into_tool_result(self) -> Result<ToolResult> {
609 Ok(self)
610 }
611}
612
613impl IntoToolResult for CommandResult {
614 fn into_tool_result(self) -> Result<ToolResult> {
615 Ok(ToolResult::Command(Box::new(self)))
616 }
617}
618
619impl IntoToolResult for () {
620 fn into_tool_result(self) -> Result<ToolResult> {
621 Ok(ToolResult::Done)
622 }
623}
624
625impl IntoToolResult for String {
626 fn into_tool_result(self) -> Result<ToolResult> {
627 Ok(ToolResult::text(self))
628 }
629}
630
631impl IntoToolResult for &str {
632 fn into_tool_result(self) -> Result<ToolResult> {
633 Ok(ToolResult::text(self))
634 }
635}
636
637impl IntoToolResult for Cow<'_, str> {
638 fn into_tool_result(self) -> Result<ToolResult> {
639 Ok(ToolResult::text(self.into_owned()))
640 }
641}
642
643impl<T> IntoToolResult for Option<T>
644where
645 T: IntoToolResult,
646{
647 fn into_tool_result(self) -> Result<ToolResult> {
648 self.map_or_else(|| Ok(ToolResult::Done), IntoToolResult::into_tool_result)
649 }
650}
651
652impl IntoToolResult for Vec<ToolResultPart> {
653 fn into_tool_result(self) -> Result<ToolResult> {
654 Ok(ToolResult::parts(self))
655 }
656}
657
658impl<T, E> IntoToolResult for core::result::Result<T, E>
659where
660 T: IntoToolResult,
661 E: Display,
662{
663 fn into_tool_result(self) -> Result<ToolResult> {
664 match self {
665 Ok(value) => value.into_tool_result(),
666 Err(error) => Ok(ToolResult::error(error.to_string())),
667 }
668 }
669}
670
671fn parse_media_type_or_octet_stream(media_type: &str) -> String {
672 media_type
673 .parse::<Mime>()
674 .unwrap_or(mime::APPLICATION_OCTET_STREAM)
675 .essence_str()
676 .to_string()
677}
678
679pub trait Tool: Send + Sync {
719 fn name(&self) -> Cow<'static, str>;
721
722 fn description(&self) -> Cow<'static, str> {
732 description_from_schema::<Self::Arguments>().unwrap_or_default()
733 }
734
735 fn arguments_schema(&self) -> Schema {
746 derived_arguments_schema::<Self::Arguments>()
747 }
748
749 type Arguments: Send + JsonSchema + DeserializeOwned;
752
753 type Res: IntoToolResult + Send;
755
756 fn call(
767 &self,
768 arguments: Self::Arguments,
769 cx: ToolContext,
770 ) -> impl Future<Output = Result<Self::Res>> + Send;
771}
772
773trait ToolImpl: Send + Sync + Any {
774 fn call(
775 &self,
776 args: &str,
777 cx: ToolContext,
778 ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + '_>>;
779
780 fn definition(&self) -> &ToolDefinition;
783
784 fn as_any(&self) -> &dyn Any;
789
790 fn as_any_mut(&mut self) -> &mut dyn Any;
792}
793
794struct DynToolImpl<F>
796where
797 F: Fn(&str, ToolContext) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send>>
798 + Send
799 + Sync,
800{
801 definition: ToolDefinition,
802 handler: F,
803}
804
805impl<F> ToolImpl for DynToolImpl<F>
806where
807 F: Fn(&str, ToolContext) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send>>
808 + Send
809 + Sync
810 + 'static,
811{
812 fn call(
813 &self,
814 args: &str,
815 cx: ToolContext,
816 ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + '_>> {
817 (self.handler)(args, cx)
818 }
819
820 fn definition(&self) -> &ToolDefinition {
821 &self.definition
822 }
823
824 fn as_any(&self) -> &dyn Any {
825 self
826 }
827
828 fn as_any_mut(&mut self) -> &mut dyn Any {
829 self
830 }
831}
832
833fn schema_is_object(value: &Value) -> bool {
836 matches!(value.get("type").and_then(Value::as_str), Some("object"))
837 || value.get("properties").is_some()
838 || value.get("oneOf").is_some()
839 || value.get("anyOf").is_some()
840 || value.get("$defs").is_some()
841}
842
843fn is_object<T: JsonSchema>() -> bool {
844 schema_is_object(&schema_for!(T).to_value())
845}
846
847fn derived_arguments_schema<T: JsonSchema>() -> Schema {
850 if is_object::<T>() {
851 schema_for!(T)
852 } else {
853 schema_for!(ToolArgument<T>)
854 }
855}
856
857fn description_from_schema<T: JsonSchema>() -> Option<Cow<'static, str>> {
859 schema_for!(T)
860 .to_value()
861 .get("description")
862 .and_then(Value::as_str)
863 .filter(|text| !text.trim().is_empty())
864 .map(|text| Cow::Owned(text.to_string()))
865}
866
867struct RegisteredTool<T: Tool> {
873 tool: T,
874 definition: ToolDefinition,
875 args_are_object: bool,
876}
877
878impl<T: Tool> RegisteredTool<T> {
879 fn new(tool: T) -> Self {
880 let definition = ToolDefinition::new(&tool);
881 let args_are_object = is_object::<T::Arguments>();
882 Self {
883 tool,
884 definition,
885 args_are_object,
886 }
887 }
888}
889
890#[derive(askama::Template)]
892#[template(path = "invalid_arguments.txt", escape = "none")]
893struct InvalidArguments<'a> {
894 tool: &'a str,
895 error: &'a serde_json::Error,
896}
897
898impl<T: Tool + 'static> ToolImpl for RegisteredTool<T> {
899 fn call(
900 &self,
901 args: &str,
902 cx: ToolContext,
903 ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + '_>> {
904 let result = if self.args_are_object {
905 serde_json::from_str::<T::Arguments>(args)
906 } else {
907 serde_json::from_str::<ToolArgument<T::Arguments>>(args).map(|wrapper| wrapper.value)
908 };
909
910 let arguments = match result {
911 Ok(arguments) => arguments,
912 Err(error) => {
913 let message = InvalidArguments {
914 tool: self.definition.name(),
915 error: &error,
916 }
917 .to_string();
918 return Box::pin(async move { Err(anyhow::Error::msg(message)) });
919 }
920 };
921
922 Box::pin(async move {
923 Tool::call(&self.tool, arguments, cx)
924 .await?
925 .into_tool_result()
926 })
927 }
928
929 fn definition(&self) -> &ToolDefinition {
930 &self.definition
931 }
932
933 fn as_any(&self) -> &dyn Any {
934 &self.tool
935 }
936
937 fn as_any_mut(&mut self) -> &mut dyn Any {
938 &mut self.tool
939 }
940}
941
942#[derive(Debug, Clone, PartialEq, Eq)]
947pub struct InvalidSchema {
948 name: Cow<'static, str>,
950}
951
952impl InvalidSchema {
953 #[must_use]
955 pub fn name(&self) -> &str {
956 &self.name
957 }
958}
959
960impl Display for InvalidSchema {
961 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
962 write!(
963 f,
964 "tool '{}' has an argument schema that is neither an object nor a boolean",
965 self.name
966 )
967 }
968}
969
970impl core::error::Error for InvalidSchema {}
971
972#[derive(Debug, Clone, PartialEq, Eq)]
974pub enum RegisterError {
975 DuplicateName(Cow<'static, str>),
979
980 EmptyDescription(Cow<'static, str>),
985}
986
987impl Display for RegisterError {
988 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
989 match self {
990 Self::DuplicateName(name) => {
991 write!(f, "a tool named '{name}' is already registered")
992 }
993 Self::EmptyDescription(name) => write!(
994 f,
995 "tool '{name}' has an empty description; add a rustdoc comment to its \
996 Arguments type or implement Tool::description"
997 ),
998 }
999 }
1000}
1001
1002impl core::error::Error for RegisterError {}
1003
1004pub struct Tools {
1020 tools: BTreeMap<Cow<'static, str>, Box<dyn ToolImpl>>,
1021}
1022
1023impl Debug for Tools {
1024 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1025 f.debug_struct("Tools")
1026 .field("tools", &self.tools.keys().collect::<Vec<_>>())
1027 .finish()
1028 }
1029}
1030
1031#[derive(Debug, Clone, PartialEq)]
1035#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1036pub struct ToolDefinition {
1037 name: Cow<'static, str>,
1039 description: Cow<'static, str>,
1041 arguments: Schema,
1043}
1044
1045impl ToolDefinition {
1046 #[must_use]
1051 pub fn new<T: Tool>(tool: &T) -> Self {
1052 Self {
1053 name: tool.name(),
1054 description: tool.description(),
1055 arguments: tool.arguments_schema(),
1056 }
1057 }
1058
1059 pub fn from_parts(
1070 name: Cow<'static, str>,
1071 description: Cow<'static, str>,
1072 schema: Value,
1073 ) -> core::result::Result<Self, InvalidSchema> {
1074 let arguments: Schema = schema
1075 .try_into()
1076 .map_err(|_| InvalidSchema { name: name.clone() })?;
1077
1078 Ok(Self {
1079 name,
1080 description,
1081 arguments,
1082 })
1083 }
1084
1085 #[must_use]
1087 pub fn name(&self) -> &str {
1088 &self.name
1089 }
1090
1091 #[must_use]
1093 pub fn description(&self) -> &str {
1094 &self.description
1095 }
1096
1097 #[must_use]
1101 pub fn arguments_openai_schema(&self) -> serde_json::Value {
1102 let mut inner = self.arguments.clone().to_value();
1103 clean_schema(&mut inner);
1104
1105 inner
1106 }
1107}
1108
1109#[derive(Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
1110struct ToolArgument<T> {
1111 value: T,
1112}
1113
1114fn clean_schema(value: &mut Value) {
1115 let defs = extract_defs(value);
1117
1118 resolve_and_clean(value, &defs);
1120
1121 if let Value::Object(map) = value {
1123 map.remove("description");
1126
1127 if map.contains_key("properties") && !map.contains_key("type") {
1129 map.insert("type".to_string(), Value::String("object".to_string()));
1130 }
1131 }
1132}
1133
1134fn extract_defs(value: &Value) -> serde_json::Map<String, Value> {
1136 if let Value::Object(map) = value
1137 && let Some(Value::Object(defs)) = map.get("$defs").or_else(|| map.get("definitions"))
1138 {
1139 return defs.clone();
1140 }
1141 serde_json::Map::new()
1142}
1143
1144#[allow(clippy::too_many_lines)]
1146fn resolve_and_clean(value: &mut Value, defs: &serde_json::Map<String, Value>) {
1147 resolve_and_clean_inner(value, defs, false);
1148}
1149
1150#[allow(clippy::too_many_lines)]
1152fn resolve_and_clean_inner(
1153 value: &mut Value,
1154 defs: &serde_json::Map<String, Value>,
1155 inside_properties: bool,
1156) {
1157 match value {
1158 Value::Object(map) => {
1159 if let Some(Value::String(ref_path)) = map.remove("$ref")
1161 && let Some(Value::Object(resolved_map)) = resolve_ref(&ref_path, defs)
1162 {
1163 let existing_description = map.remove("description");
1166 for (k, v) in resolved_map {
1167 map.entry(k).or_insert(v);
1168 }
1169 if let Some(desc) = existing_description {
1171 map.insert("description".to_string(), desc);
1172 }
1173 }
1174
1175 if let Some(const_val) = map.remove("const") {
1177 map.insert("enum".to_string(), Value::Array(alloc::vec![const_val]));
1178 }
1179
1180 if let Some(Value::Array(variants)) =
1182 map.remove("oneOf").or_else(|| map.remove("anyOf"))
1183 {
1184 let is_simple_enum = variants.iter().all(|v| {
1186 if let Value::Object(vm) = v {
1187 (vm.contains_key("const") || vm.contains_key("enum"))
1188 && !vm.contains_key("properties")
1189 } else {
1190 false
1191 }
1192 });
1193
1194 if is_simple_enum {
1195 let mut enum_values: alloc::vec::Vec<Value> = alloc::vec::Vec::new();
1197 let mut variant_type: Option<String> = None;
1198
1199 for variant in &variants {
1200 if let Value::Object(vm) = variant {
1201 if let Some(const_val) = vm.get("const")
1202 && !enum_values.contains(const_val)
1203 {
1204 enum_values.push(const_val.clone());
1205 }
1206 if let Some(Value::Array(arr)) = vm.get("enum") {
1207 for val in arr {
1208 if !enum_values.contains(val) {
1209 enum_values.push(val.clone());
1210 }
1211 }
1212 }
1213 if variant_type.is_none()
1214 && let Some(Value::String(t)) = vm.get("type")
1215 {
1216 variant_type = Some(t.clone());
1217 }
1218 }
1219 }
1220
1221 if !enum_values.is_empty() {
1222 map.insert("enum".to_string(), Value::Array(enum_values));
1223 if let Some(t) = variant_type {
1224 map.insert("type".to_string(), Value::String(t));
1225 }
1226 }
1227 } else {
1228 let mut all_properties = serde_json::Map::new();
1230
1231 for variant in variants {
1232 if let Value::Object(variant_map) = variant
1233 && let Some(Value::Object(props)) = variant_map.get("properties")
1234 {
1235 for (key, val) in props {
1236 let new_values: Option<alloc::vec::Vec<Value>> =
1238 if let Value::Object(val_obj) = val {
1239 if let Some(Value::Array(arr)) = val_obj.get("enum") {
1240 Some(arr.clone())
1241 } else {
1242 val_obj
1243 .get("const")
1244 .map(|const_val| alloc::vec![const_val.clone()])
1245 }
1246 } else {
1247 None
1248 };
1249
1250 if all_properties.contains_key(key) {
1251 if let Some(values) = new_values
1253 && let Some(Value::Object(existing_obj)) =
1254 all_properties.get_mut(key)
1255 && let Some(Value::Array(existing_enum)) =
1256 existing_obj.get_mut("enum")
1257 {
1258 for e in values {
1259 if !existing_enum.contains(&e) {
1260 existing_enum.push(e);
1261 }
1262 }
1263 }
1264 } else {
1265 let mut val_clone = val.clone();
1267 if let Value::Object(obj) = &mut val_clone
1268 && let Some(const_val) = obj.remove("const")
1269 {
1270 obj.insert(
1271 "enum".to_string(),
1272 Value::Array(alloc::vec![const_val]),
1273 );
1274 }
1275 all_properties.insert(key.clone(), val_clone);
1276 }
1277 }
1278 }
1279 }
1280
1281 if !all_properties.is_empty() {
1283 map.insert("type".to_string(), Value::String("object".to_string()));
1284 map.insert("properties".to_string(), Value::Object(all_properties));
1285 }
1286 }
1287 }
1288
1289 if !inside_properties {
1292 let allowed = [
1293 "type",
1294 "description",
1295 "properties",
1296 "required",
1297 "items",
1298 "enum",
1299 "nullable",
1300 ];
1301 map.retain(|k, _| allowed.contains(&k.as_str()));
1302 }
1303
1304 if let Some(Value::Array(types)) = map.get("type") {
1306 let non_null: Vec<&Value> = types
1308 .iter()
1309 .filter(|t| !matches!(t, Value::String(s) if s == "null"))
1310 .collect();
1311 if non_null.len() == 1 {
1312 map.insert("type".to_string(), non_null[0].clone());
1313 }
1314 }
1315
1316 for (key, v) in map.iter_mut() {
1318 let child_inside_props = key == "properties";
1320 resolve_and_clean_inner(v, defs, child_inside_props);
1321 }
1322 }
1323 Value::Array(arr) => {
1324 for v in arr {
1325 resolve_and_clean_inner(v, defs, false);
1326 }
1327 }
1328 _ => {}
1329 }
1330}
1331
1332fn resolve_ref(ref_path: &str, defs: &serde_json::Map<String, Value>) -> Option<Value> {
1334 let name = ref_path
1336 .strip_prefix("#/$defs/")
1337 .or_else(|| ref_path.strip_prefix("#/definitions/"))?;
1338
1339 defs.get(name).cloned()
1340}
1341
1342impl Default for Tools {
1343 fn default() -> Self {
1344 Self::new()
1345 }
1346}
1347
1348impl Tools {
1349 #[must_use]
1351 pub const fn new() -> Self {
1352 Self {
1353 tools: BTreeMap::new(),
1354 }
1355 }
1356
1357 #[must_use]
1361 pub fn get<T>(&self) -> Option<&T>
1362 where
1363 T: Tool + 'static,
1364 {
1365 self.tools
1366 .values()
1367 .find_map(|tool| tool.as_any().downcast_ref::<T>())
1368 }
1369
1370 #[must_use]
1374 pub fn get_mut<T>(&mut self) -> Option<&mut T>
1375 where
1376 T: Tool + 'static,
1377 {
1378 self.tools
1379 .values_mut()
1380 .find_map(|tool| tool.as_any_mut().downcast_mut::<T>())
1381 }
1382
1383 #[must_use]
1385 pub fn definitions(&self) -> Vec<ToolDefinition> {
1386 self.tools
1387 .values()
1388 .map(|tool| tool.definition().clone())
1389 .collect()
1390 }
1391
1392 pub fn register<T: Tool + 'static>(
1403 &mut self,
1404 tool: T,
1405 ) -> core::result::Result<(), RegisterError> {
1406 self.insert(Box::new(RegisteredTool::new(tool)))
1407 }
1408
1409 pub fn register_dyn<F>(
1419 &mut self,
1420 definition: ToolDefinition,
1421 handler: F,
1422 ) -> core::result::Result<(), RegisterError>
1423 where
1424 F: Fn(&str, ToolContext) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send>>
1425 + Send
1426 + Sync
1427 + 'static,
1428 {
1429 self.insert(Box::new(DynToolImpl {
1430 definition,
1431 handler,
1432 }))
1433 }
1434
1435 fn insert(&mut self, tool: Box<dyn ToolImpl>) -> core::result::Result<(), RegisterError> {
1436 let name = tool.definition().name.clone();
1437 if self.tools.contains_key(&name) {
1438 return Err(RegisterError::DuplicateName(name));
1439 }
1440 if tool.definition().description().trim().is_empty() {
1441 return Err(RegisterError::EmptyDescription(name));
1442 }
1443 self.tools.insert(name, tool);
1444 Ok(())
1445 }
1446
1447 pub fn unregister(&mut self, name: &str) {
1449 self.tools.remove(name);
1450 }
1451
1452 pub async fn call(&self, name: &str, args: &str, cx: ToolContext) -> Result<ToolResult> {
1460 if let Some(tool) = self.tools.get(name) {
1461 tool.call(args, cx).await
1462 } else {
1463 Err(anyhow::Error::msg(format!("Tool '{name}' not found")))
1464 }
1465 }
1466}
1467
1468#[cfg(test)]
1469mod tests {
1470 use super::*;
1471 use alloc::{format, string::ToString, vec};
1472 use schemars::JsonSchema;
1473 use serde::Deserialize;
1474
1475 #[derive(JsonSchema, Deserialize, Debug, PartialEq)]
1477 struct CalculatorArgs {
1478 operation: String,
1479 a: f64,
1480 b: f64,
1481 }
1482
1483 struct Calculator;
1484
1485 impl Tool for Calculator {
1486 fn name(&self) -> Cow<'static, str> {
1487 "calculator".into()
1488 }
1489 type Arguments = CalculatorArgs;
1490 type Res = ToolResult;
1491
1492 fn call(
1493 &self,
1494 args: Self::Arguments,
1495 _cx: ToolContext,
1496 ) -> impl Future<Output = Result<Self::Res>> + Send {
1497 core::future::ready(match args.operation.as_str() {
1498 "add" => Ok(ToolResult::text((args.a + args.b).to_string())),
1499 "subtract" => Ok(ToolResult::text((args.a - args.b).to_string())),
1500 "multiply" => Ok(ToolResult::text((args.a * args.b).to_string())),
1501 "divide" => {
1502 if args.b == 0.0 {
1503 Err(anyhow::Error::msg("Division by zero"))
1504 } else {
1505 Ok(ToolResult::text((args.a / args.b).to_string()))
1506 }
1507 }
1508 _ => Err(anyhow::Error::msg(format!(
1509 "Unknown operation: {}",
1510 args.operation
1511 ))),
1512 })
1513 }
1514 }
1515
1516 #[derive(JsonSchema, Deserialize)]
1518 struct GreetArgs {
1519 name: String,
1520 }
1521
1522 struct Greeter;
1523
1524 impl Tool for Greeter {
1525 fn name(&self) -> Cow<'static, str> {
1526 "greeter".into()
1527 }
1528 type Arguments = GreetArgs;
1529 type Res = ToolResult;
1530
1531 fn call(
1532 &self,
1533 args: Self::Arguments,
1534 _cx: ToolContext,
1535 ) -> impl Future<Output = Result<Self::Res>> + Send {
1536 core::future::ready(Ok(ToolResult::text(format!("Hello, {}!", args.name))))
1537 }
1538 }
1539
1540 #[test]
1541 fn from_parts_accepts_object_and_boolean_schemas() {
1542 for schema in [
1544 serde_json::json!({"type": "object"}),
1545 serde_json::json!(true),
1546 ] {
1547 assert!(
1548 ToolDefinition::from_parts("t".into(), "does a thing".into(), schema.clone())
1549 .is_ok(),
1550 "{schema} should be accepted"
1551 );
1552 }
1553 }
1554
1555 #[test]
1556 fn from_parts_rejects_non_schema_values() {
1557 for schema in [
1560 serde_json::json!("a string"),
1561 serde_json::json!([1, 2, 3]),
1562 serde_json::json!(7),
1563 serde_json::json!(null),
1564 ] {
1565 let result = ToolDefinition::from_parts("weird".into(), "d".into(), schema.clone());
1566 let Err(err) = result else {
1567 panic!("{schema} should be rejected");
1568 };
1569 assert_eq!(err.name(), "weird");
1570 }
1571 }
1572
1573 #[test]
1574 fn tool_definition_creation() {
1575 let calculator = Calculator;
1576 let definition = ToolDefinition::new(&calculator);
1577
1578 assert_eq!(definition.name, "calculator");
1579 assert_eq!(
1580 definition.description,
1581 "Performs basic mathematical operations."
1582 );
1583 }
1586
1587 #[test]
1588 fn tools_creation() {
1589 let tools = Tools::new();
1590 assert_eq!(tools.definitions().len(), 0);
1591 }
1592
1593 #[test]
1594 fn tools_default() {
1595 let tools = Tools::default();
1596 assert_eq!(tools.definitions().len(), 0);
1597 }
1598
1599 #[tokio::test]
1600 async fn tools_register_and_call() {
1601 let mut tools = Tools::new();
1602 tools.register(Calculator).expect("calculator registers");
1603
1604 let definitions = tools.definitions();
1605 assert_eq!(definitions.len(), 1);
1606 assert_eq!(definitions[0].name, "calculator");
1607
1608 let result = tools
1609 .call(
1610 "calculator",
1611 r#"{"operation": "add", "a": 5, "b": 3}"#,
1612 ToolContext::new(),
1613 )
1614 .await;
1615 assert!(result.is_ok());
1616 assert_eq!(result.unwrap().as_text(), Some("8"));
1617 }
1618
1619 #[tokio::test]
1620 async fn invalid_arguments_report_the_parse_error_without_schema() {
1621 let mut tools = Tools::new();
1622 tools.register(Calculator).expect("calculator registers");
1623
1624 let error = tools
1625 .call("calculator", r#"{"operation": "add"}"#, ToolContext::new())
1626 .await
1627 .unwrap_err()
1628 .to_string();
1629 assert_eq!(
1630 error,
1631 "Invalid arguments for tool 'calculator': missing field `a` at line 1 column 20"
1632 );
1633 }
1634
1635 #[test]
1636 fn command_result_renders_its_text() {
1637 let result = ToolResult::Command(Box::new(CommandResult {
1638 stdout: CommandStream::Inline {
1639 text: "hi\n".to_string(),
1640 },
1641 stderr: None,
1642 outcome: CommandOutcome::Exited { code: 3 },
1643 interruptions: Vec::new(),
1644 }));
1645 assert_eq!(result.render_for_model(), "hi\nExit code: 3.\n");
1646 assert_eq!(
1647 result.command().map(|command| &command.outcome),
1648 Some(&CommandOutcome::Exited { code: 3 })
1649 );
1650 }
1651
1652 #[cfg(feature = "serde")]
1653 #[test]
1654 fn command_result_round_trips_through_serde() {
1655 let file = || crate::llm::StoredFile {
1656 url: "outputs/x.txt".to_string(),
1657 path: "/sandbox/outputs/x.txt".to_string(),
1658 };
1659 let results = [
1660 CommandResult {
1661 stdout: CommandStream::Inline {
1662 text: "hi\n".to_string(),
1663 },
1664 stderr: Some(CommandStream::Inline {
1665 text: "oops".to_string(),
1666 }),
1667 outcome: CommandOutcome::Exited { code: 1 },
1668 interruptions: Vec::new(),
1669 },
1670 CommandResult {
1671 stdout: CommandStream::Stored {
1672 file: file(),
1673 preview: "head".to_string(),
1674 truncated: true,
1675 },
1676 stderr: None,
1677 outcome: CommandOutcome::Exited { code: 0 },
1678 interruptions: Vec::new(),
1679 },
1680 CommandResult {
1681 stdout: CommandStream::Image {
1682 media_type: "image/png".to_string(),
1683 file: file(),
1684 },
1685 stderr: None,
1686 outcome: CommandOutcome::Running {
1687 task_id: "t1".to_string(),
1688 output: file(),
1689 },
1690 interruptions: Vec::new(),
1691 },
1692 ];
1693 for command in results {
1694 let result = ToolResult::Command(Box::new(command));
1695 let json = serde_json::to_string(&result).expect("a command result serializes");
1696 let back: ToolResult = serde_json::from_str(&json).expect("it deserializes back");
1697 assert_eq!(back, result, "{json}");
1698 }
1699 }
1700
1701 #[tokio::test]
1702 async fn calculator_operations() {
1703 let mut tools = Tools::new();
1704 tools.register(Calculator).expect("calculator registers");
1705
1706 let result = tools
1708 .call(
1709 "calculator",
1710 r#"{"operation": "add", "a": 10, "b": 5}"#,
1711 ToolContext::new(),
1712 )
1713 .await;
1714 assert_eq!(result.unwrap().as_text(), Some("15"));
1715
1716 let result = tools
1718 .call(
1719 "calculator",
1720 r#"{"operation": "subtract", "a": 10, "b": 3}"#,
1721 ToolContext::new(),
1722 )
1723 .await;
1724 assert_eq!(result.unwrap().as_text(), Some("7"));
1725
1726 let result = tools
1728 .call(
1729 "calculator",
1730 r#"{"operation": "multiply", "a": 4, "b": 3}"#,
1731 ToolContext::new(),
1732 )
1733 .await;
1734 assert_eq!(result.unwrap().as_text(), Some("12"));
1735
1736 let result = tools
1738 .call(
1739 "calculator",
1740 r#"{"operation": "divide", "a": 15, "b": 3}"#,
1741 ToolContext::new(),
1742 )
1743 .await;
1744 assert_eq!(result.unwrap().as_text(), Some("5"));
1745 }
1746
1747 #[tokio::test]
1748 async fn calculator_division_by_zero() {
1749 let mut tools = Tools::new();
1750 tools.register(Calculator).expect("calculator registers");
1751
1752 let result = tools
1753 .call(
1754 "calculator",
1755 r#"{"operation": "divide", "a": 10, "b": 0}"#,
1756 ToolContext::new(),
1757 )
1758 .await;
1759 assert!(result.is_err());
1760 assert!(result.unwrap_err().to_string().contains("Division by zero"));
1761 }
1762
1763 #[tokio::test]
1764 async fn calculator_unknown_operation() {
1765 let mut tools = Tools::new();
1766 tools.register(Calculator).expect("calculator registers");
1767
1768 let result = tools
1769 .call(
1770 "calculator",
1771 r#"{"operation": "modulo", "a": 10, "b": 3}"#,
1772 ToolContext::new(),
1773 )
1774 .await;
1775 assert!(result.is_err());
1776 assert!(
1777 result
1778 .unwrap_err()
1779 .to_string()
1780 .contains("Unknown operation")
1781 );
1782 }
1783
1784 #[tokio::test]
1785 async fn multiple_tools() {
1786 let mut tools = Tools::new();
1787 tools.register(Calculator).expect("calculator registers");
1788 tools.register(Greeter).expect("greeter registers");
1789
1790 let definitions = tools.definitions();
1791 assert_eq!(definitions.len(), 2);
1792
1793 let calc_def = definitions.iter().find(|d| d.name == "calculator").unwrap();
1795 let greet_def = definitions.iter().find(|d| d.name == "greeter").unwrap();
1796
1797 assert_eq!(
1798 calc_def.description,
1799 "Performs basic mathematical operations."
1800 );
1801 assert_eq!(greet_def.description, "Greets a person by name.");
1802
1803 let calc_result = tools
1805 .call(
1806 "calculator",
1807 r#"{"operation": "add", "a": 2, "b": 3}"#,
1808 ToolContext::new(),
1809 )
1810 .await;
1811 assert_eq!(calc_result.unwrap().as_text(), Some("5"));
1812
1813 let greet_result = tools
1814 .call("greeter", r#"{"name": "Alice"}"#, ToolContext::new())
1815 .await;
1816 assert_eq!(greet_result.unwrap().as_text(), Some("Hello, Alice!"));
1817 }
1818
1819 #[derive(Debug)]
1820 struct ToolFailure(&'static str);
1821
1822 impl core::fmt::Display for ToolFailure {
1823 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1824 f.write_str(self.0)
1825 }
1826 }
1827
1828 impl core::error::Error for ToolFailure {}
1829
1830 #[test]
1831 fn into_tool_result_string_is_plain_text() {
1832 assert_eq!(
1833 String::from("hello").into_tool_result().unwrap(),
1834 ToolResult::text("hello")
1835 );
1836 }
1837
1838 #[test]
1839 fn into_tool_result_str_is_plain_text() {
1840 assert_eq!(
1841 "hello".into_tool_result().unwrap(),
1842 ToolResult::text("hello")
1843 );
1844 }
1845
1846 #[test]
1847 fn into_tool_result_option_none_is_done() {
1848 let result = Option::<String>::None.into_tool_result().unwrap();
1849 assert_eq!(result, ToolResult::Done);
1850 }
1851
1852 #[test]
1853 fn into_tool_result_option_some_delegates() {
1854 let result = Some("hello").into_tool_result().unwrap();
1855 assert_eq!(result, ToolResult::text("hello"));
1856 }
1857
1858 #[test]
1859 fn into_tool_result_result_ok_string_is_text() {
1860 let result = core::result::Result::<String, ToolFailure>::Ok(String::from("hello"))
1861 .into_tool_result()
1862 .unwrap();
1863 assert_eq!(result, ToolResult::text("hello"));
1864 }
1865
1866 #[test]
1867 fn into_tool_result_result_err_is_typed_error() {
1868 let result = core::result::Result::<String, ToolFailure>::Err(ToolFailure("boom"))
1869 .into_tool_result()
1870 .unwrap();
1871 assert_eq!(result, ToolResult::error("boom"));
1872 assert!(result.is_error());
1873 assert_eq!(result.error_message(), Some("boom"));
1874 }
1875
1876 #[tokio::test]
1877 async fn tool_not_found() {
1878 let tools = Tools::new();
1879
1880 let result = tools.call("nonexistent", "{}", ToolContext::new()).await;
1881 assert!(result.is_err());
1882 assert!(
1883 result
1884 .unwrap_err()
1885 .to_string()
1886 .contains("Tool 'nonexistent' not found")
1887 );
1888 }
1889
1890 #[tokio::test]
1891 async fn invalid_json() {
1892 let mut tools = Tools::new();
1893 tools.register(Calculator).expect("calculator registers");
1894
1895 let result = tools
1896 .call("calculator", "invalid json", ToolContext::new())
1897 .await;
1898 assert!(result.is_err());
1899 }
1900
1901 #[test]
1902 fn tools_unregister() {
1903 let mut tools = Tools::new();
1904 tools.register(Calculator).expect("calculator registers");
1905 tools.register(Greeter).expect("greeter registers");
1906
1907 assert_eq!(tools.definitions().len(), 2);
1908
1909 tools.unregister("calculator");
1910 assert_eq!(tools.definitions().len(), 1);
1911
1912 let remaining = &tools.definitions()[0];
1913 assert_eq!(remaining.name, "greeter");
1914
1915 tools.unregister("greeter");
1916 assert_eq!(tools.definitions().len(), 0);
1917 }
1918
1919 #[test]
1920 fn tools_debug() {
1921 let mut tools = Tools::new();
1922 tools.register(Calculator).expect("calculator registers");
1923 tools.register(Greeter).expect("greeter registers");
1924
1925 let debug_str = format!("{tools:?}");
1926 assert!(debug_str.contains("Tools"));
1927 assert!(debug_str.contains("calculator"));
1928 assert!(debug_str.contains("greeter"));
1929 }
1930
1931 #[test]
1932 fn tool_definition_debug() {
1933 let calculator = Calculator;
1934 let definition = ToolDefinition::new(&calculator);
1935 let debug_str = format!("{definition:?}");
1936
1937 assert!(debug_str.contains("ToolDefinition"));
1938 assert!(debug_str.contains("calculator"));
1939 assert!(debug_str.contains("Performs basic mathematical operations"));
1940 }
1941
1942 #[derive(JsonSchema, Deserialize)]
1943 #[expect(dead_code, reason = "only the schema is read")]
1944 struct PickArgs {
1945 interpreter: String,
1947 }
1948
1949 struct Pick {
1951 interpreters: Vec<String>,
1952 }
1953
1954 impl Tool for Pick {
1955 fn name(&self) -> Cow<'static, str> {
1956 "pick".into()
1957 }
1958 fn description(&self) -> Cow<'static, str> {
1959 "Picks an interpreter.".into()
1960 }
1961 fn arguments_schema(&self) -> Schema {
1962 let mut schema = derived_arguments_schema::<PickArgs>();
1963 schema.ensure_object();
1964 let property = schema
1965 .get_mut("properties")
1966 .and_then(Value::as_object_mut)
1967 .and_then(|properties| properties.get_mut("interpreter"))
1968 .and_then(Value::as_object_mut)
1969 .expect("interpreter property");
1970 property.insert("enum".into(), self.interpreters.clone().into());
1971 schema
1972 }
1973 type Arguments = PickArgs;
1974 type Res = ToolResult;
1975
1976 fn call(
1977 &self,
1978 _args: Self::Arguments,
1979 _cx: ToolContext,
1980 ) -> impl Future<Output = Result<Self::Res>> + Send {
1981 core::future::ready(Ok(ToolResult::text("ok")))
1982 }
1983 }
1984
1985 #[test]
1986 fn runtime_schema_reaches_the_definition_and_the_registry() {
1987 let tool = Pick {
1988 interpreters: vec!["bash".to_string(), "python".to_string()],
1989 };
1990 let expected = serde_json::json!(["bash", "python"]);
1991
1992 let schema = ToolDefinition::new(&tool).arguments_openai_schema();
1993 assert_eq!(schema["properties"]["interpreter"]["enum"], expected);
1994
1995 let mut tools = Tools::new();
1996 tools.register(tool).expect("registers");
1997 let listed = tools.definitions();
1998 assert_eq!(
1999 listed[0].arguments_openai_schema()["properties"]["interpreter"]["enum"],
2000 expected
2001 );
2002 }
2003
2004 #[test]
2005 fn tool_without_override_sends_the_derived_schema() {
2006 let schema = ToolDefinition::new(&Calculator).arguments_openai_schema();
2007 let mut derived = schema_for!(<Calculator as Tool>::Arguments).to_value();
2008 clean_schema(&mut derived);
2009 assert_eq!(schema, derived);
2010 assert!(schema["properties"]["interpreter"].is_null());
2011 }
2012
2013 #[test]
2014 fn tool_definition_clone() {
2015 let calculator = Calculator;
2016 let original = ToolDefinition::new(&calculator);
2017 let cloned = original.clone();
2018
2019 assert_eq!(original.name, cloned.name);
2020 assert_eq!(original.description, cloned.description);
2021 }
2022
2023 #[test]
2024 fn schema_preserves_enum() {
2025 #[derive(JsonSchema, Deserialize)]
2026 #[serde(rename_all = "snake_case")]
2027 enum Status {
2028 Pending,
2029 InProgress,
2030 Completed,
2031 }
2032
2033 #[allow(dead_code)]
2034 #[derive(JsonSchema, Deserialize)]
2035 struct Item {
2036 status: Status,
2037 }
2038
2039 #[allow(dead_code)]
2040 #[derive(JsonSchema, Deserialize)]
2041 struct Args {
2042 items: Vec<Item>,
2043 }
2044
2045 struct TestTool;
2046
2047 impl Tool for TestTool {
2048 fn name(&self) -> Cow<'static, str> {
2049 "test".into()
2050 }
2051 type Arguments = Args;
2052 type Res = ToolResult;
2053
2054 fn call(
2055 &self,
2056 _args: Self::Arguments,
2057 _cx: ToolContext,
2058 ) -> impl Future<Output = Result<Self::Res>> + Send {
2059 core::future::ready(Ok(ToolResult::text("ok")))
2060 }
2061 }
2062
2063 let tool = TestTool;
2064 let def = ToolDefinition::new(&tool);
2065 let schema = def.arguments_openai_schema();
2066
2067 let schema_obj = schema.as_object().expect("schema should be object");
2069 let properties = schema_obj
2070 .get("properties")
2071 .expect("should have properties")
2072 .as_object()
2073 .unwrap();
2074 let items = properties
2075 .get("items")
2076 .expect("should have items")
2077 .as_object()
2078 .unwrap();
2079 let item_props = items
2080 .get("items")
2081 .expect("items should have items schema")
2082 .as_object()
2083 .unwrap();
2084 let item_properties = item_props
2085 .get("properties")
2086 .expect("item should have properties")
2087 .as_object()
2088 .unwrap();
2089 let status = item_properties
2090 .get("status")
2091 .expect("should have status")
2092 .as_object()
2093 .unwrap();
2094
2095 assert!(
2097 status.contains_key("enum"),
2098 "Status should have enum field. Full schema: {}",
2099 serde_json::to_string_pretty(&schema).unwrap()
2100 );
2101 }
2102
2103 #[test]
2104 fn schema_ref_resolution() {
2105 let raw_schema = serde_json::json!({
2107 "type": "object",
2108 "properties": {
2109 "status": {
2110 "$ref": "#/$defs/Status"
2111 }
2112 },
2113 "$defs": {
2114 "Status": {
2115 "type": "string",
2116 "enum": ["pending", "in_progress", "completed"]
2117 }
2118 }
2119 });
2120
2121 let mut schema = raw_schema;
2122 clean_schema(&mut schema);
2123
2124 let props = schema.get("properties").unwrap().as_object().unwrap();
2125 let status = props.get("status").unwrap().as_object().unwrap();
2126
2127 assert!(
2128 status.contains_key("enum"),
2129 "Status should have enum after ref resolution. Got: {}",
2130 serde_json::to_string_pretty(&schema).unwrap()
2131 );
2132 }
2133
2134 #[test]
2135 fn schema_nested_ref_in_array() {
2136 let raw_schema = serde_json::json!({
2138 "type": "object",
2139 "properties": {
2140 "entries": {
2141 "type": "array",
2142 "items": {
2143 "$ref": "#/$defs/BatchItem"
2144 }
2145 }
2146 },
2147 "$defs": {
2148 "BatchItem": {
2149 "type": "object",
2150 "properties": {
2151 "content": { "type": "string" },
2152 "status": { "$ref": "#/$defs/BatchStatus" }
2153 },
2154 "required": ["content", "status"]
2155 },
2156 "BatchStatus": {
2157 "type": "string",
2158 "enum": ["pending", "in_progress", "completed"]
2159 }
2160 }
2161 });
2162
2163 let mut schema = raw_schema;
2164 clean_schema(&mut schema);
2165
2166 let props = schema.get("properties").unwrap().as_object().unwrap();
2168 let todos = props.get("entries").unwrap().as_object().unwrap();
2169 let items = todos.get("items").unwrap().as_object().unwrap();
2170 let item_props = items.get("properties").unwrap().as_object().unwrap();
2171 let status = item_props.get("status").unwrap().as_object().unwrap();
2172
2173 assert!(
2174 status.contains_key("enum"),
2175 "Nested status should have enum. Full schema: {}",
2176 serde_json::to_string_pretty(&schema).unwrap()
2177 );
2178 }
2179
2180 #[test]
2181 fn parts_collapses_degenerate_inputs() {
2182 assert_eq!(ToolResult::parts(vec![]), ToolResult::Done);
2183 assert_eq!(
2184 ToolResult::parts(vec![ToolResultPart::text("only")]),
2185 ToolResult::text("only")
2186 );
2187 let multi = ToolResult::parts(vec![
2188 ToolResultPart::text("a"),
2189 ToolResultPart::image(vec![1, 2], "image/png"),
2190 ]);
2191 let ToolResult::Parts { parts } = &multi else {
2192 panic!("two parts must stay a Parts result");
2193 };
2194 assert_eq!(parts.len(), 2);
2195 }
2196
2197 #[test]
2198 fn parts_render_joins_text_and_marks_binary() {
2199 let result = ToolResult::parts(vec![
2200 ToolResultPart::text("header"),
2201 ToolResultPart::tsv("n\n1\n"),
2202 ToolResultPart::image(vec![0x89], "image/png"),
2203 ]);
2204 assert_eq!(
2205 result.render_for_model(),
2206 "header\nn\n1\n\n[binary tool result: image/png, 1 bytes]"
2207 );
2208 assert!(result.mime().is_none() && result.content().is_none());
2209 }
2210
2211 #[test]
2212 fn parts_with_one_binary_expose_mime_and_content() {
2213 let result = ToolResult::Parts {
2214 parts: vec![ToolResultPart::image(vec![9, 9], "image/png")],
2215 };
2216 assert_eq!(result.mime().unwrap().essence_str(), "image/png");
2217 assert_eq!(result.content().unwrap(), &[9, 9]);
2218 }
2219
2220 #[cfg(feature = "serde")]
2221 #[test]
2222 fn parts_serde_roundtrip_uses_kind_tag() {
2223 let result = ToolResult::parts(vec![
2224 ToolResultPart::text("note"),
2225 ToolResultPart::tsv("k\ntrue\n"),
2226 ]);
2227 let value = serde_json::to_value(&result).unwrap();
2228 assert_eq!(value["kind"], "parts");
2229 assert_eq!(value["parts"][0]["kind"], "text");
2230 let back: ToolResult = serde_json::from_value(value).unwrap();
2231 assert_eq!(back, result);
2232 }
2233}