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