1use std::collections::HashMap;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, Ordering};
4
5use async_trait::async_trait;
6use serde_json::{Value, json};
7use tokio::sync::mpsc;
8
9use crate::engine::SessionStore;
10use crate::types::{AgentError, AgentResult, RuntimeEvent, SessionId, UserEvent};
11
12pub mod auto_continue;
13pub mod policy;
14pub mod update_plan;
15
16pub use auto_continue::AutoContinueTool;
17pub use update_plan::UpdatePlanTool;
18
19pub use policy::{DenyAllToolPolicy, ToolDecision, ToolPolicy};
20
21pub use agent_types::{
23 ActivationContext, Content, ToolExposure, ToolMetadata, content_details, content_images,
24 content_text,
25};
26
27#[derive(Clone, Default)]
36pub struct ExecClock {
37 inner: Arc<ExecClockInner>,
38}
39
40#[derive(Default)]
41struct ExecClockInner {
42 state: std::sync::Mutex<ExecClockState>,
43}
44
45#[derive(Default)]
46struct ExecClockState {
47 live: usize,
49 started: Option<std::time::Instant>,
51 total: std::time::Duration,
53}
54
55impl ExecClock {
56 pub fn pause(&self) -> ExecPauseGuard {
59 let mut state = self.lock();
60 state.live += 1;
61 if state.live == 1 {
62 state.started = Some(std::time::Instant::now());
63 }
64 ExecPauseGuard {
65 clock: self.clone(),
66 }
67 }
68
69 pub fn paused_total(&self) -> std::time::Duration {
73 let state = self.lock();
74 state.total
75 + state
76 .started
77 .map_or(std::time::Duration::ZERO, |s| s.elapsed())
78 }
79
80 fn resume(&self) {
81 let mut state = self.lock();
82 state.live = state.live.saturating_sub(1);
83 if state.live == 0
84 && let Some(started) = state.started.take()
85 {
86 state.total += started.elapsed();
87 }
88 }
89
90 fn lock(&self) -> std::sync::MutexGuard<'_, ExecClockState> {
91 self.inner
94 .state
95 .lock()
96 .unwrap_or_else(std::sync::PoisonError::into_inner)
97 }
98}
99
100pub struct ExecPauseGuard {
102 clock: ExecClock,
103}
104
105impl Drop for ExecPauseGuard {
106 fn drop(&mut self) {
107 self.clock.resume();
108 }
109}
110
111#[derive(Clone)]
112pub struct ToolContext {
113 pub session_id: SessionId,
114 pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
117 pub llm_client: Option<Arc<dyn llm_trait::LlmProvider>>,
118 pub session_store: Option<Arc<dyn SessionStore>>,
119 pub language: crate::types::Language,
122 pub cancel_token: tokio_util::sync::CancellationToken,
124 pub max_output_chars: Option<usize>,
129 pub exec_clock: ExecClock,
132 pub waiting_for_human: Arc<AtomicBool>,
136 pub(crate) event_bus: crate::engine::EventBus,
139}
140
141impl ToolContext {
142 pub fn pause_execution_clock(&self) -> ExecPauseGuard {
147 self.exec_clock.pause()
148 }
149
150 pub fn mark_waiting_for_human(&self) {
155 self.waiting_for_human.store(true, Ordering::Relaxed);
156 }
157
158 pub fn emit_user_event(&self, event: UserEvent) {
166 let _ = self.user_event_tx.send(event.clone());
167 self.event_bus.emit(RuntimeEvent::UserEvent {
168 session_id: self.session_id.clone(),
169 event,
170 agent_id: None,
171 trace_id: None,
172 });
173 }
174
175 pub fn emit_progress(&self, text: impl Into<String>) {
177 self.emit_user_event(UserEvent::Progress { text: text.into() });
178 }
179
180 pub fn emit_partial_result(
183 &self,
184 tool_call_id: &str,
185 content: impl Into<String>,
186 is_partial: bool,
187 ) {
188 self.emit_user_event(UserEvent::ToolPartialResult {
189 tool_call_id: tool_call_id.to_string(),
190 content: content.into(),
191 is_partial,
192 });
193 }
194
195 pub fn for_test() -> Self {
199 let (tx, _rx) = mpsc::unbounded_channel();
200 ToolContext {
201 session_id: SessionId::new(0),
202 user_event_tx: tx,
203 llm_client: None,
204 session_store: None,
205 language: crate::types::Language::En,
206 cancel_token: tokio_util::sync::CancellationToken::new(),
207 max_output_chars: None,
208 exec_clock: ExecClock::default(),
209 waiting_for_human: Arc::new(AtomicBool::new(false)),
210 event_bus: crate::engine::EventBus::new(1),
211 }
212 }
213
214 pub fn new(
219 session_id: SessionId,
220 llm_client: Option<Arc<dyn crate::llm_trait::LlmProvider>>,
221 session_store: Option<Arc<dyn SessionStore>>,
222 cancel_token: tokio_util::sync::CancellationToken,
223 ) -> Self {
224 let (tx, _rx) = mpsc::unbounded_channel();
225 ToolContext {
226 session_id,
227 user_event_tx: tx,
228 llm_client,
229 session_store,
230 language: crate::types::Language::En,
231 cancel_token,
232 max_output_chars: None,
233 exec_clock: ExecClock::default(),
234 waiting_for_human: Arc::new(AtomicBool::new(false)),
235 event_bus: crate::engine::EventBus::new(1),
236 }
237 }
238}
239
240#[async_trait]
241pub trait Tool: Send + Sync {
242 fn name(&self) -> &'static str;
243 fn description(&self) -> &'static str;
245 fn schema(&self) -> Value;
248 async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>>;
249
250 fn timeout_ms(&self) -> Option<u64> {
256 None }
258
259 fn call_timeout_ms(&self, _args: &Value) -> Option<u64> {
272 self.timeout_ms()
273 }
274
275 fn metadata(&self) -> ToolMetadata {
282 ToolMetadata {
283 name: self.name().to_string(),
284 description: self.description().to_string(),
285 origin: "custom".to_string(),
286 version: "unknown".to_string(),
287 requirements: vec![],
288 }
289 }
290
291 fn exposure(&self) -> ToolExposure {
297 ToolExposure::Direct
298 }
299
300 fn should_activate(&self, _ctx: &ActivationContext) -> bool {
306 true
307 }
308}
309
310#[async_trait]
311pub trait TypedTool: Send + Sync {
312 type Args: serde::de::DeserializeOwned + schemars::JsonSchema;
313 type Output: serde::Serialize;
314
315 fn name(&self) -> &'static str;
316 fn description(&self) -> &'static str;
317 async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;
318
319 fn format_output(&self, output: Self::Output) -> Content {
320 match serde_json::to_value(&output) {
325 Ok(serde_json::Value::String(s)) => Content::text(s),
326 Ok(other) => Content::text(other.to_string()),
327 Err(_) => Content::text(String::new()),
328 }
329 }
330
331 fn origin(&self) -> &'static str {
333 "custom"
334 }
335
336 fn version(&self) -> &'static str {
338 "unknown"
339 }
340
341 fn exposure(&self) -> ToolExposure {
343 ToolExposure::Direct
344 }
345
346 fn should_activate(&self, _ctx: &ActivationContext) -> bool {
348 true
349 }
350}
351
352#[async_trait]
353impl<T: TypedTool + Send + Sync + 'static> Tool for T {
354 fn name(&self) -> &'static str {
355 TypedTool::name(self)
356 }
357
358 fn description(&self) -> &'static str {
359 TypedTool::description(self)
360 }
361
362 fn schema(&self) -> Value {
363 let settings = schemars::generate::SchemaSettings::draft07().with(|s| {
369 s.inline_subschemas = true;
370 s.meta_schema = None;
371 });
372 let generator = schemars::SchemaGenerator::new(settings);
373 let schema = generator.into_root_schema_for::<T::Args>();
374 serde_json::to_value(schema).unwrap_or(Value::Null)
375 }
376
377 fn metadata(&self) -> ToolMetadata {
378 ToolMetadata {
379 name: self.name().to_string(),
380 description: self.description().to_string(),
381 origin: self.origin().to_string(),
382 version: self.version().to_string(),
383 requirements: vec![],
384 }
385 }
386
387 fn exposure(&self) -> ToolExposure {
388 TypedTool::exposure(self)
389 }
390
391 fn should_activate(&self, ctx: &ActivationContext) -> bool {
392 TypedTool::should_activate(self, ctx)
393 }
394
395 async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
396 let typed_args: T::Args =
397 serde_json::from_value(args.clone()).map_err(|_| AgentError::ToolArgsInvalid {
398 name: self.name().to_string(),
399 raw: args.to_string(),
400 })?;
401 let output = self.call_typed(typed_args, ctx).await?;
402 Ok(vec![self.format_output(output)])
403 }
404}
405
406pub fn render_tool_definition(tool: &dyn Tool) -> Value {
411 json!({
412 "type": "function",
413 "function": {
414 "name": tool.name(),
415 "description": tool.description(),
416 "parameters": tool.schema(),
417 }
418 })
419}
420
421pub(crate) type ToolRef = Arc<dyn Tool>;
422
423#[derive(Clone, Default)]
424pub struct ToolRegistry {
425 tools: HashMap<String, ToolRef>,
426}
427
428impl ToolRegistry {
429 pub fn register(&mut self, tool: impl Tool + 'static) {
430 self.tools.insert(tool.name().to_string(), Arc::new(tool));
431 }
432
433 pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
434 self.tools.insert(tool.name().to_string(), tool);
435 }
436
437 pub fn remove(&mut self, name: &str) {
439 self.tools.remove(name);
440 }
441
442 pub fn get(&self, name: &str) -> Option<ToolRef> {
443 self.tools.get(name).cloned()
444 }
445
446 pub fn definitions(&self) -> Vec<Value> {
447 let mut tools: Vec<_> = self.tools.values().collect();
448 tools.sort_by_key(|t| t.name());
449 tools
450 .into_iter()
451 .map(|t| render_tool_definition(t.as_ref()))
452 .collect()
453 }
454
455 pub fn definitions_filtered(&self, ctx: &ActivationContext) -> Vec<Value> {
461 let mut tools: Vec<_> = self.tools.values().collect();
462 tools.sort_by_key(|t| t.name());
463
464 let direct_names: Vec<String> = tools
470 .iter()
471 .filter(|t| t.exposure() == ToolExposure::Direct)
472 .map(|t| t.name().to_string())
473 .collect();
474
475 let mut activated_names = direct_names.clone();
476 for t in &tools {
477 if t.exposure() == ToolExposure::Deferred {
478 let mut ctx_with_tools = ctx.clone();
479 ctx_with_tools.current_tools = activated_names.clone();
480 if t.should_activate(&ctx_with_tools) {
481 activated_names.push(t.name().to_string());
482 }
483 }
484 }
485
486 tools
487 .into_iter()
488 .filter(|t| match t.exposure() {
489 ToolExposure::Direct => true,
490 ToolExposure::Deferred => activated_names.contains(&t.name().to_string()),
491 ToolExposure::Hidden => false,
492 })
493 .map(|t| render_tool_definition(t.as_ref()))
494 .collect()
495 }
496
497 pub fn len(&self) -> usize {
498 self.tools.len()
499 }
500
501 pub fn is_empty(&self) -> bool {
502 self.tools.is_empty()
503 }
504
505 pub fn metadatas(&self) -> Vec<ToolMetadata> {
511 let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
512 list.sort_by(|a, b| a.name.cmp(&b.name));
513 list
514 }
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520 use llm_trait::ImageAttachment;
521
522 #[test]
523 fn exec_clock_pause_accounting() {
524 let clock = ExecClock::default();
525 assert_eq!(clock.paused_total(), std::time::Duration::ZERO);
526
527 let guard = clock.pause();
528 std::thread::sleep(std::time::Duration::from_millis(30));
529 assert!(clock.paused_total() >= std::time::Duration::from_millis(30));
531 drop(guard);
532 let banked = clock.paused_total();
533 assert!(banked >= std::time::Duration::from_millis(30));
534
535 std::thread::sleep(std::time::Duration::from_millis(10));
537 assert_eq!(clock.paused_total(), banked);
538 let g2 = clock.pause();
539 std::thread::sleep(std::time::Duration::from_millis(20));
540 assert!(clock.paused_total() >= banked + std::time::Duration::from_millis(20));
541 drop(g2);
542 }
543
544 #[test]
545 fn exec_clock_nested_guards_resume_once() {
546 let clock = ExecClock::default();
547 let outer = clock.pause();
548 let inner = clock.pause();
549 std::thread::sleep(std::time::Duration::from_millis(15));
550 drop(inner);
551 std::thread::sleep(std::time::Duration::from_millis(15));
552 let during = clock.paused_total();
554 assert!(during >= std::time::Duration::from_millis(30));
555 drop(outer);
556 let after = clock.paused_total();
557 assert!(after >= during);
558 std::thread::sleep(std::time::Duration::from_millis(10));
559 assert_eq!(clock.paused_total(), after);
560 }
561
562 #[test]
563 fn exec_clock_guard_drop_unwinds_from_panic() {
564 let clock = ExecClock::default();
566 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
567 let _guard = clock.pause();
568 panic!("boom");
569 }));
570 assert!(caught.is_err());
571 std::thread::sleep(std::time::Duration::from_millis(5));
572 let banked = clock.paused_total();
573 std::thread::sleep(std::time::Duration::from_millis(10));
574 assert_eq!(clock.paused_total(), banked, "clock must be resumed");
575 }
576
577 #[test]
578 fn content_text_ctor_and_into_vec() {
579 let c = Content::text("hello");
580 let v: Vec<Content> = c.clone().into();
581 assert_eq!(v.len(), 1);
582 assert!(matches!(v[0], Content::Text { .. }));
583 assert!(matches!(&c, Content::Text { text } if text == "hello"));
584 }
585
586 #[test]
587 fn content_serializes_with_type_tag() {
588 let c = Content::text("hi");
589 let j = serde_json::to_value(&c).unwrap();
590 assert_eq!(j["type"], "text");
591 assert_eq!(j["text"], "hi");
592 }
593
594 #[test]
595 fn tool_context_for_test_constructs() {
596 let ctx = ToolContext::for_test();
597 assert!(ctx.llm_client.is_none());
598 assert!(ctx.session_store.is_none());
599 assert!(!ctx.cancel_token.is_cancelled());
600 ctx.emit_progress("hello");
601 }
602
603 #[test]
604 fn typed_tool_schema_is_derived_from_args() {
605 #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
606 struct GreetArgs {
607 name: String,
608 #[serde(default)]
609 times: u32,
610 }
611
612 let schema = schemars::schema_for!(GreetArgs);
613 let j = serde_json::to_value(&schema).unwrap();
614 assert!(j["properties"]["name"].is_object());
616 assert!(j["properties"]["times"].is_object());
617 }
618
619 #[test]
620 fn typed_tool_schema_is_provider_safe_for_nested_enum() {
621 #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
622 enum Status {
623 Active,
624 Paused,
625 }
626
627 #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
628 struct Args {
629 name: String,
630 status: Status,
631 }
632
633 #[derive(Default)]
634 struct NestedTool;
635 #[async_trait]
636 impl TypedTool for NestedTool {
637 type Args = Args;
638 type Output = String;
639 fn name(&self) -> &'static str {
640 "nested"
641 }
642 fn description(&self) -> &'static str {
643 ""
644 }
645 async fn call_typed(
646 &self,
647 _args: Args,
648 _ctx: &ToolContext,
649 ) -> crate::types::AgentResult<String> {
650 Ok(String::new())
651 }
652 }
653
654 let schema = Tool::schema(&NestedTool);
655 let raw = schema.to_string();
656 assert!(!raw.contains("$ref"), "schema contains $ref: {raw}");
659 assert!(!raw.contains("$defs"), "schema contains $defs: {raw}");
660 assert!(
661 !raw.contains("definitions"),
662 "schema has definitions: {raw}"
663 );
664 assert!(schema.get("$schema").is_none(), "schema has $schema key");
665
666 let variants: Vec<&str> = schema["properties"]["status"]["enum"]
668 .as_array()
669 .unwrap()
670 .iter()
671 .map(|v| v.as_str().unwrap())
672 .collect();
673 assert!(variants.contains(&"Active"), "missing Active: {variants:?}");
674 assert!(variants.contains(&"Paused"), "missing Paused: {variants:?}");
675 }
676
677 #[test]
678 fn definitions_are_sorted_by_name() {
679 struct NamedTool(&'static str);
680 #[async_trait::async_trait]
681 impl Tool for NamedTool {
682 fn name(&self) -> &'static str {
683 self.0
684 }
685 fn description(&self) -> &'static str {
686 ""
687 }
688 fn schema(&self) -> serde_json::Value {
689 serde_json::Value::Null
690 }
691 async fn call(
692 &self,
693 _args: &serde_json::Value,
694 _ctx: &ToolContext,
695 ) -> crate::types::AgentResult<Vec<Content>> {
696 Ok(vec![])
697 }
698 }
699
700 let mut registry = ToolRegistry::default();
701 registry.register(NamedTool("zeta"));
702 registry.register(NamedTool("alpha"));
703 registry.register(NamedTool("mike"));
704
705 let defs = registry.definitions();
706 let names: Vec<&str> = defs
707 .iter()
708 .map(|d| d["function"]["name"].as_str().unwrap())
709 .collect();
710 assert_eq!(names, vec!["alpha", "mike", "zeta"]);
711 }
712
713 #[test]
716 fn content_image_and_content_text_skips_images() {
717 let img = Content::image("base64data", "image/png");
718 assert!(
719 matches!(&img, Content::Image { data, mime_type } if data == "base64data" && mime_type == "image/png")
720 );
721
722 let text = content_text(&[
723 Content::text("a"),
724 Content::image("b", "image/png"),
725 Content::text("c"),
726 ]);
727 assert_eq!(text, "a\nc");
728 }
729
730 #[test]
735 fn content_images_takes_the_pictures_content_text_drops() {
736 let out = [
737 Content::text("words"),
738 Content::image("Zmlyc3Q=", "image/png"),
739 Content::text("more words"),
740 Content::image("c2Vjb25k", "image/png"),
741 Content::detail(serde_json::json!({"line": 3})),
742 ];
743 let images = content_images(&out);
744 assert_eq!(images.len(), 2);
745 for (img, want) in images.iter().zip(["Zmlyc3Q=", "c2Vjb25k"]) {
746 match img {
747 ImageAttachment::Base64 {
748 data, media_type, ..
749 } => {
750 assert_eq!(data, want);
751 assert_eq!(media_type.as_deref(), Some("image/png"));
752 }
753 other => panic!("expected a base64 attachment, got {other:?}"),
754 }
755 }
756 assert!(content_images(&[Content::text("no pictures")]).is_empty());
757 }
758
759 #[test]
760 fn emit_partial_result_sends_event() {
761 let (tx, mut rx) = mpsc::unbounded_channel();
762 let ctx = ToolContext {
763 session_id: SessionId::new(0),
764 user_event_tx: tx,
765 llm_client: None,
766 session_store: None,
767 language: crate::types::Language::En,
768 cancel_token: tokio_util::sync::CancellationToken::new(),
769 max_output_chars: None,
770 exec_clock: ExecClock::default(),
771 waiting_for_human: Arc::new(AtomicBool::new(false)),
772 event_bus: crate::engine::EventBus::new(1),
773 };
774 ctx.emit_partial_result("tc1", "partial", true);
775 match rx.try_recv().unwrap() {
776 UserEvent::ToolPartialResult {
777 tool_call_id,
778 content,
779 is_partial,
780 } => {
781 assert_eq!(tool_call_id, "tc1");
782 assert_eq!(content, "partial");
783 assert!(is_partial);
784 }
785 other => panic!("unexpected event: {other:?}"),
786 }
787 }
788
789 #[test]
795 fn emit_user_event_dual_writes_to_event_bus() {
796 let (tx, mut rx) = mpsc::unbounded_channel();
797 let ctx = ToolContext {
798 session_id: SessionId::new(7),
799 user_event_tx: tx,
800 llm_client: None,
801 session_store: None,
802 language: crate::types::Language::En,
803 cancel_token: tokio_util::sync::CancellationToken::new(),
804 max_output_chars: None,
805 exec_clock: ExecClock::default(),
806 waiting_for_human: Arc::new(AtomicBool::new(false)),
807 event_bus: crate::engine::EventBus::new(4),
808 };
809 let mut bus_rx = ctx.event_bus.subscribe();
810 ctx.emit_progress("working");
811
812 assert!(
814 matches!(rx.try_recv().unwrap(), UserEvent::Progress { text } if text == "working")
815 );
816
817 match bus_rx.try_recv().unwrap() {
819 crate::types::RuntimeEvent::UserEvent {
820 session_id,
821 event,
822 agent_id,
823 ..
824 } => {
825 assert_eq!(session_id, SessionId::new(7));
826 assert!(matches!(event, UserEvent::Progress { text } if text == "working"));
827 assert!(agent_id.is_none());
828 }
829 other => panic!("unexpected bus event: {other:?}"),
830 }
831 }
832
833 #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
835 struct GreetArgs {
836 name: String,
837 }
838
839 struct GreetTool;
840 #[async_trait]
841 impl TypedTool for GreetTool {
842 type Args = GreetArgs;
843 type Output = String;
844 fn name(&self) -> &'static str {
845 "greet"
846 }
847 fn description(&self) -> &'static str {
848 "greets a name"
849 }
850 fn origin(&self) -> &'static str {
851 "test-crate"
852 }
853 fn version(&self) -> &'static str {
854 "1.0.0"
855 }
856 async fn call_typed(&self, args: GreetArgs, _ctx: &ToolContext) -> AgentResult<String> {
857 Ok(format!("Hello, {}!", args.name))
858 }
859 }
860
861 #[test]
862 fn typed_tool_blanket_delegates_name_description() {
863 let t = GreetTool;
864 assert_eq!(Tool::name(&t), "greet");
865 assert_eq!(Tool::description(&t), "greets a name");
866 }
867
868 #[test]
869 fn typed_tool_metadata_uses_origin_and_version() {
870 let m = Tool::metadata(&GreetTool);
871 assert_eq!(m.name, "greet");
872 assert_eq!(m.description, "greets a name");
873 assert_eq!(m.origin, "test-crate");
874 assert_eq!(m.version, "1.0.0");
875 assert!(m.requirements.is_empty());
876 }
877
878 #[tokio::test]
879 async fn typed_tool_call_deserializes_and_formats() {
880 let ctx = ToolContext::for_test();
881 let out = Tool::call(&GreetTool, &json!({"name": "world"}), &ctx)
882 .await
883 .unwrap();
884 assert_eq!(content_text(&out), "Hello, world!");
886 }
887
888 #[derive(serde::Serialize)]
890 struct GreetResult {
891 message: String,
892 }
893
894 struct GreetStructTool;
895 #[async_trait]
896 impl TypedTool for GreetStructTool {
897 type Args = GreetArgs;
898 type Output = GreetResult;
899 fn name(&self) -> &'static str {
900 "greet_struct"
901 }
902 fn description(&self) -> &'static str {
903 "greets as json"
904 }
905 async fn call_typed(
906 &self,
907 args: GreetArgs,
908 _ctx: &ToolContext,
909 ) -> AgentResult<GreetResult> {
910 Ok(GreetResult {
911 message: format!("Hello, {}!", args.name),
912 })
913 }
914 }
915
916 #[test]
917 fn format_output_json_serializes_struct() {
918 let out = GreetStructTool.format_output(GreetResult {
919 message: "hi".into(),
920 });
921 assert_eq!(content_text(&[out]), r#"{"message":"hi"}"#);
922 }
923
924 #[tokio::test]
925 async fn typed_tool_call_invalid_args_is_tool_args_invalid() {
926 let ctx = ToolContext::for_test();
927 let err = Tool::call(&GreetTool, &json!({"nope": 1}), &ctx)
928 .await
929 .unwrap_err();
930 assert!(matches!(err, AgentError::ToolArgsInvalid { .. }));
931 }
932
933 struct NamedTool(&'static str);
934 #[async_trait]
935 impl Tool for NamedTool {
936 fn name(&self) -> &'static str {
937 self.0
938 }
939 fn description(&self) -> &'static str {
940 ""
941 }
942 fn schema(&self) -> serde_json::Value {
943 serde_json::Value::Null
944 }
945 async fn call(
946 &self,
947 _args: &serde_json::Value,
948 _ctx: &ToolContext,
949 ) -> AgentResult<Vec<Content>> {
950 Ok(vec![])
951 }
952 }
953
954 #[test]
955 fn registry_register_arc_get_remove_len_is_empty() {
956 let mut r = ToolRegistry::default();
957 assert!(r.is_empty());
958 assert_eq!(r.len(), 0);
959
960 let t: Arc<dyn Tool> = Arc::new(NamedTool("x"));
961 r.register_arc(t);
962 assert!(!r.is_empty());
963 assert_eq!(r.len(), 1);
964 assert!(r.get("x").is_some());
965 assert!(r.get("missing").is_none());
966
967 r.remove("x");
968 assert!(r.is_empty());
969 }
970
971 #[test]
972 fn metadatas_are_sorted_by_name() {
973 let mut r = ToolRegistry::default();
974 r.register(NamedTool("zeta"));
975 r.register(NamedTool("alpha"));
976
977 let metas = r.metadatas();
978 let names: Vec<&str> = metas.iter().map(|m| m.name.as_str()).collect();
979 assert_eq!(names, vec!["alpha", "zeta"]);
980 assert_eq!(metas[0].origin, "custom");
981 assert_eq!(metas[0].version, "unknown");
982 }
983
984 struct ExposureTool(&'static str, ToolExposure);
987 #[async_trait]
988 impl Tool for ExposureTool {
989 fn name(&self) -> &'static str {
990 self.0
991 }
992 fn description(&self) -> &'static str {
993 ""
994 }
995 fn schema(&self) -> serde_json::Value {
996 serde_json::Value::Null
997 }
998 async fn call(
999 &self,
1000 _args: &serde_json::Value,
1001 _ctx: &ToolContext,
1002 ) -> AgentResult<Vec<Content>> {
1003 Ok(vec![])
1004 }
1005 fn exposure(&self) -> ToolExposure {
1006 self.1.clone()
1007 }
1008 }
1009
1010 struct ConditionalTool(&'static str, bool);
1011 #[async_trait]
1012 impl Tool for ConditionalTool {
1013 fn name(&self) -> &'static str {
1014 self.0
1015 }
1016 fn description(&self) -> &'static str {
1017 ""
1018 }
1019 fn schema(&self) -> serde_json::Value {
1020 serde_json::Value::Null
1021 }
1022 async fn call(
1023 &self,
1024 _args: &serde_json::Value,
1025 _ctx: &ToolContext,
1026 ) -> AgentResult<Vec<Content>> {
1027 Ok(vec![])
1028 }
1029 fn exposure(&self) -> ToolExposure {
1030 ToolExposure::Deferred
1031 }
1032 fn should_activate(&self, _ctx: &ActivationContext) -> bool {
1033 self.1
1034 }
1035 }
1036
1037 fn default_ctx() -> ActivationContext {
1038 ActivationContext {
1039 session_id: crate::types::SessionId::new(0),
1040 current_tools: vec![],
1041 workspace: std::path::PathBuf::from("/tmp"),
1042 }
1043 }
1044
1045 #[test]
1046 fn tool_exposure_default_is_direct() {
1047 let t = NamedTool("x");
1049 assert_eq!(t.exposure(), ToolExposure::Direct);
1050 }
1051
1052 #[test]
1053 fn tool_should_activate_default_is_true() {
1054 let t = NamedTool("x");
1055 assert!(t.should_activate(&default_ctx()));
1056 }
1057
1058 #[test]
1059 fn definitions_filtered_includes_direct_excludes_hidden() {
1060 let mut r = ToolRegistry::default();
1061 r.register(ExposureTool("direct_a", ToolExposure::Direct));
1062 r.register(ExposureTool("hidden_a", ToolExposure::Hidden));
1063 r.register(ExposureTool("direct_b", ToolExposure::Direct));
1064
1065 let defs = r.definitions_filtered(&default_ctx());
1066 let names: Vec<&str> = defs
1067 .iter()
1068 .map(|d| d["function"]["name"].as_str().unwrap())
1069 .collect();
1070 assert_eq!(names, vec!["direct_a", "direct_b"]);
1071 }
1072
1073 #[test]
1074 fn definitions_filtered_includes_deferred_when_activated() {
1075 let mut r = ToolRegistry::default();
1076 r.register(ExposureTool("always", ToolExposure::Direct));
1077 r.register(ConditionalTool("maybe", true)); r.register(ConditionalTool("never", false)); let defs = r.definitions_filtered(&default_ctx());
1081 let names: Vec<&str> = defs
1082 .iter()
1083 .map(|d| d["function"]["name"].as_str().unwrap())
1084 .collect();
1085 assert_eq!(names, vec!["always", "maybe"]);
1086 }
1087
1088 #[test]
1089 fn definitions_filtered_all_hidden_returns_empty() {
1090 let mut r = ToolRegistry::default();
1091 r.register(ExposureTool("h1", ToolExposure::Hidden));
1092 r.register(ExposureTool("h2", ToolExposure::Hidden));
1093
1094 let defs = r.definitions_filtered(&default_ctx());
1095 assert!(defs.is_empty());
1096 }
1097
1098 #[test]
1099 fn definitions_filtered_empty_registry() {
1100 let r = ToolRegistry::default();
1101 let defs = r.definitions_filtered(&default_ctx());
1102 assert!(defs.is_empty());
1103 }
1104
1105 #[test]
1106 fn definitions_unfiltered_includes_hidden() {
1107 let mut r = ToolRegistry::default();
1109 r.register(ExposureTool("visible", ToolExposure::Direct));
1110 r.register(ExposureTool("secret", ToolExposure::Hidden));
1111
1112 let defs = r.definitions();
1113 assert_eq!(defs.len(), 2);
1114 }
1115}