1use std::collections::HashMap;
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29
30use adk_core::{Agent, Llm, ToolRegistry};
31use async_trait::async_trait;
32use tokio::sync::RwLock;
33use tracing::{debug, info, warn};
34
35use super::schema::{ToolReference, YamlAgentDefinition};
36
37#[async_trait]
42pub trait ModelFactory: Send + Sync {
43 async fn create_model(&self, provider: &str, model_id: &str) -> adk_core::Result<Arc<dyn Llm>>;
49}
50
51pub struct AgentConfigLoader {
57 tool_registry: Arc<dyn ToolRegistry>,
58 model_factory: Arc<dyn ModelFactory>,
59 loaded_agents: Arc<RwLock<HashMap<String, Arc<dyn Agent>>>>,
60}
61
62impl AgentConfigLoader {
63 pub fn new(tool_registry: Arc<dyn ToolRegistry>, model_factory: Arc<dyn ModelFactory>) -> Self {
65 Self { tool_registry, model_factory, loaded_agents: Arc::new(RwLock::new(HashMap::new())) }
66 }
67
68 pub async fn load_file(&self, path: &Path) -> adk_core::Result<Arc<dyn Agent>> {
81 let path_display = path.display();
82 info!("loading YAML agent definition from {path_display}");
83
84 let content = tokio::fs::read_to_string(path).await.map_err(|e| {
85 adk_core::AdkError::config(format!(
86 "failed to read YAML agent file '{path_display}': {e}"
87 ))
88 })?;
89
90 let definition = self.parse_and_validate(&content, path)?;
91 let agent = self.build_agent(definition, path).await?;
92
93 let name = agent.name().to_string();
95 self.loaded_agents.write().await.insert(name.clone(), agent.clone());
96 debug!("cached agent '{name}' from {path_display}");
97
98 Ok(agent)
99 }
100
101 pub async fn load_directory(&self, dir: &Path) -> adk_core::Result<Vec<Arc<dyn Agent>>> {
111 let dir_display = dir.display();
112 info!("loading YAML agent definitions from directory {dir_display}");
113
114 if !dir.is_dir() {
115 return Err(adk_core::AdkError::config(format!("'{dir_display}' is not a directory")));
116 }
117
118 let yaml_files = collect_yaml_files(dir)?;
120 if yaml_files.is_empty() {
121 warn!("no YAML agent definition files found in {dir_display}");
122 return Ok(vec![]);
123 }
124
125 debug!("found {} YAML files in {dir_display}", yaml_files.len());
126
127 let mut definitions: Vec<(PathBuf, YamlAgentDefinition)> = Vec::new();
129 for file_path in &yaml_files {
130 let content = tokio::fs::read_to_string(file_path).await.map_err(|e| {
131 adk_core::AdkError::config(format!(
132 "failed to read YAML agent file '{}': {e}",
133 file_path.display()
134 ))
135 })?;
136 let def = self.parse_and_validate(&content, file_path)?;
137 definitions.push((file_path.clone(), def));
138 }
139
140 let mut seen_names: HashMap<&str, &Path> = HashMap::new();
142 for (path, def) in &definitions {
143 if let Some(prev_path) = seen_names.insert(&def.name, path) {
144 return Err(adk_core::AdkError::config(format!(
145 "duplicate agent name '{}' found in '{}' and '{}'",
146 def.name,
147 prev_path.display(),
148 path.display()
149 )));
150 }
151 }
152
153 let mut agents: Vec<Arc<dyn Agent>> = Vec::new();
155 let mut remaining: Vec<(PathBuf, YamlAgentDefinition)> = definitions;
156 let mut progress = true;
157
158 while !remaining.is_empty() && progress {
159 progress = false;
160 let mut still_remaining = Vec::new();
161
162 for (path, def) in remaining {
163 let all_resolved = {
165 let loaded = self.loaded_agents.read().await;
166 def.sub_agents.iter().all(|sa| loaded.contains_key(&sa.reference))
167 };
168
169 if all_resolved {
170 let agent = self.build_agent(def, &path).await?;
171 let name = agent.name().to_string();
172 self.loaded_agents.write().await.insert(name, agent.clone());
173 agents.push(agent);
174 progress = true;
175 } else {
176 still_remaining.push((path, def));
177 }
178 }
179
180 remaining = still_remaining;
181 }
182
183 if !remaining.is_empty() {
185 let mut unresolved: Vec<String> = Vec::new();
186 for (path, def) in &remaining {
187 let loaded = self.loaded_agents.read().await;
188 let missing: Vec<&str> = def
189 .sub_agents
190 .iter()
191 .filter(|sa| !loaded.contains_key(&sa.reference))
192 .map(|sa| sa.reference.as_str())
193 .collect();
194 unresolved.push(format!(
195 "'{}' in '{}' (unresolved sub-agents: {})",
196 def.name,
197 path.display(),
198 missing.join(", ")
199 ));
200 }
201 return Err(adk_core::AdkError::config(format!(
202 "circular or unresolvable sub-agent references: {}",
203 unresolved.join("; ")
204 )));
205 }
206
207 info!("loaded {} agents from {dir_display}", agents.len());
208 Ok(agents)
209 }
210
211 pub async fn reload_file(&self, path: &Path) -> adk_core::Result<Arc<dyn Agent>> {
219 debug!("reloading YAML agent definition from {}", path.display());
220 self.load_file(path).await
221 }
222
223 pub async fn get_agent(&self, name: &str) -> Option<Arc<dyn Agent>> {
225 self.loaded_agents.read().await.get(name).cloned()
226 }
227
228 pub async fn all_agents(&self) -> Vec<Arc<dyn Agent>> {
230 self.loaded_agents.read().await.values().cloned().collect()
231 }
232
233 fn parse_and_validate(
235 &self,
236 content: &str,
237 path: &Path,
238 ) -> adk_core::Result<YamlAgentDefinition> {
239 let mut definition: YamlAgentDefinition = serde_saphyr::from_str(content).map_err(|e| {
240 adk_core::AdkError::config(format!("invalid YAML in '{}': {e}", path.display()))
241 })?;
242
243 super::interpolator::EnvInterpolator::interpolate(&mut definition).map_err(|errors| {
245 let messages: Vec<String> = errors
246 .iter()
247 .map(|e| format!("${{{}}} in field '{}'", e.variable_name, e.field_path))
248 .collect();
249 adk_core::AdkError::config(format!(
250 "unresolved environment variables in '{}': {}",
251 path.display(),
252 messages.join(", ")
253 ))
254 })?;
255
256 self.validate_definition(&definition, path)?;
257 Ok(definition)
258 }
259
260 fn validate_definition(&self, def: &YamlAgentDefinition, path: &Path) -> adk_core::Result<()> {
262 let path_display = path.display();
263
264 if def.name.is_empty() {
265 return Err(adk_core::AdkError::config(format!(
266 "field 'name' is required and cannot be empty in '{path_display}'"
267 )));
268 }
269
270 if def.model.provider.is_empty() {
271 return Err(adk_core::AdkError::config(format!(
272 "field 'model.provider' is required and cannot be empty in '{path_display}'"
273 )));
274 }
275
276 if def.model.model_id.is_empty() {
277 return Err(adk_core::AdkError::config(format!(
278 "field 'model.model_id' is required and cannot be empty in '{path_display}'"
279 )));
280 }
281
282 if let Some(temp) = def.model.temperature
284 && !(0.0..=2.0).contains(&temp)
285 {
286 return Err(adk_core::AdkError::config(format!(
287 "field 'model.temperature' must be between 0.0 and 2.0, got {temp} in '{path_display}'"
288 )));
289 }
290
291 Ok(())
292 }
293
294 async fn build_agent(
296 &self,
297 def: YamlAgentDefinition,
298 path: &Path,
299 ) -> adk_core::Result<Arc<dyn Agent>> {
300 let path_display = path.display();
301
302 let model = self
304 .model_factory
305 .create_model(&def.model.provider, &def.model.model_id)
306 .await
307 .map_err(|e| {
308 adk_core::AdkError::config(format!(
309 "failed to create model for provider '{}' with model_id '{}' in '{path_display}': {e}",
310 def.model.provider, def.model.model_id
311 ))
312 })?;
313
314 let mut builder = adk_agent::LlmAgentBuilder::new(&def.name).model(model);
316
317 if let Some(desc) = &def.description {
319 builder = builder.description(desc);
320 }
321
322 if let Some(instructions) = &def.instructions {
324 builder = builder.instruction(instructions);
325 }
326
327 if def.model.temperature.is_some() || def.model.max_tokens.is_some() {
329 let mut config = adk_core::GenerateContentConfig::default();
330 if let Some(temp) = def.model.temperature {
331 config.temperature = Some(temp as f32);
332 }
333 if let Some(max_tokens) = def.model.max_tokens {
334 config.max_output_tokens = Some(max_tokens as i32);
335 }
336 builder = builder.generate_content_config(config);
337 }
338
339 for tool_ref in &def.tools {
341 match tool_ref {
342 ToolReference::Named { name } => {
343 let tool = self.tool_registry.resolve(name).ok_or_else(|| {
344 adk_core::AdkError::config(format!(
345 "unresolved tool reference '{name}' in '{path_display}'. \
346 Available tools: {:?}",
347 self.tool_registry.available_tools()
348 ))
349 })?;
350 builder = builder.tool(tool);
351 }
352 ToolReference::Mcp { mcp } => {
353 debug!(
357 "MCP tool reference in '{path_display}': endpoint='{}', args={:?}",
358 mcp.endpoint, mcp.args
359 );
360 warn!(
361 "MCP tool references in YAML definitions are not yet resolved at load time. \
362 Endpoint '{}' in '{path_display}' will be skipped.",
363 mcp.endpoint
364 );
365 }
366 }
367 }
368
369 for sub_ref in &def.sub_agents {
371 let loaded = self.loaded_agents.read().await;
372 let sub_agent = loaded.get(&sub_ref.reference).cloned().ok_or_else(|| {
373 let available: Vec<String> = loaded.keys().cloned().collect();
374 adk_core::AdkError::config(format!(
375 "unresolved sub-agent reference '{}' in '{path_display}'. \
376 Loaded agents: {available:?}",
377 sub_ref.reference,
378 ))
379 })?;
380 builder = builder.sub_agent(sub_agent);
381 }
382
383 let agent = builder.build().map_err(|e| {
384 adk_core::AdkError::config(format!(
385 "failed to build agent '{}' from '{path_display}': {e}",
386 def.name
387 ))
388 })?;
389
390 info!("built agent '{}' from '{path_display}'", def.name);
391 Ok(Arc::new(agent))
392 }
393}
394
395fn collect_yaml_files(dir: &Path) -> adk_core::Result<Vec<PathBuf>> {
397 let mut files = Vec::new();
398 let entries = std::fs::read_dir(dir).map_err(|e| {
399 adk_core::AdkError::config(format!("failed to read directory '{}': {e}", dir.display()))
400 })?;
401
402 for entry in entries {
403 let entry = entry.map_err(|e| {
404 adk_core::AdkError::config(format!(
405 "failed to read directory entry in '{}': {e}",
406 dir.display()
407 ))
408 })?;
409 let path = entry.path();
410 if path.is_file()
411 && let Some(ext) = path.extension()
412 {
413 let ext = ext.to_string_lossy().to_lowercase();
414 if ext == "yaml" || ext == "yml" {
415 files.push(path);
416 }
417 }
418 }
419
420 files.sort();
422 Ok(files)
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428 use adk_core::{AdkError, Llm, LlmRequest, Tool, ToolContext};
429 use serde_json::Value;
430 use std::io::Write;
431
432 struct MockModelFactory;
435
436 #[async_trait]
437 impl ModelFactory for MockModelFactory {
438 async fn create_model(
439 &self,
440 provider: &str,
441 model_id: &str,
442 ) -> adk_core::Result<Arc<dyn Llm>> {
443 Ok(Arc::new(MockLlm { name: format!("{provider}/{model_id}") }))
444 }
445 }
446
447 struct FailingModelFactory {
448 fail_provider: String,
449 }
450
451 #[async_trait]
452 impl ModelFactory for FailingModelFactory {
453 async fn create_model(
454 &self,
455 provider: &str,
456 _model_id: &str,
457 ) -> adk_core::Result<Arc<dyn Llm>> {
458 if provider == self.fail_provider {
459 Err(AdkError::config(format!("unknown provider '{provider}'")))
460 } else {
461 Ok(Arc::new(MockLlm { name: format!("{provider}/{_model_id}") }))
462 }
463 }
464 }
465
466 struct MockLlm {
469 name: String,
470 }
471
472 #[async_trait]
473 impl Llm for MockLlm {
474 fn name(&self) -> &str {
475 &self.name
476 }
477
478 async fn generate_content(
479 &self,
480 _request: LlmRequest,
481 _stream: bool,
482 ) -> adk_core::Result<adk_core::LlmResponseStream> {
483 unimplemented!("mock LLM")
484 }
485 }
486
487 struct MockToolRegistry {
490 tools: HashMap<String, Arc<dyn Tool>>,
491 }
492
493 impl MockToolRegistry {
494 fn new() -> Self {
495 Self { tools: HashMap::new() }
496 }
497
498 fn with_tool(mut self, name: &str) -> Self {
499 self.tools.insert(name.to_string(), Arc::new(MockTool { name: name.to_string() }));
500 self
501 }
502 }
503
504 impl ToolRegistry for MockToolRegistry {
505 fn resolve(&self, tool_name: &str) -> Option<Arc<dyn Tool>> {
506 self.tools.get(tool_name).cloned()
507 }
508
509 fn available_tools(&self) -> Vec<String> {
510 self.tools.keys().cloned().collect()
511 }
512 }
513
514 struct MockTool {
517 name: String,
518 }
519
520 #[async_trait]
521 impl Tool for MockTool {
522 fn name(&self) -> &str {
523 &self.name
524 }
525
526 fn description(&self) -> &str {
527 "mock tool"
528 }
529
530 async fn execute(
531 &self,
532 _ctx: Arc<dyn ToolContext>,
533 _args: Value,
534 ) -> adk_core::Result<Value> {
535 Ok(Value::Null)
536 }
537 }
538
539 fn write_temp_yaml(dir: &Path, filename: &str, content: &str) -> PathBuf {
542 let path = dir.join(filename);
543 let mut file = std::fs::File::create(&path).unwrap();
544 file.write_all(content.as_bytes()).unwrap();
545 path
546 }
547
548 #[tokio::test]
551 async fn test_load_file_basic() {
552 let dir = tempfile::tempdir().unwrap();
553 let yaml = r#"
554name: test_agent
555description: "A test agent"
556model:
557 provider: gemini
558 model_id: gemini-2.0-flash
559instructions: "You are a helpful assistant."
560"#;
561 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
562
563 let registry = Arc::new(MockToolRegistry::new());
564 let factory = Arc::new(MockModelFactory);
565 let loader = AgentConfigLoader::new(registry, factory);
566
567 let agent = loader.load_file(&path).await.unwrap();
568 assert_eq!(agent.name(), "test_agent");
569 assert_eq!(agent.description(), "A test agent");
570 }
571
572 #[tokio::test]
573 async fn test_load_file_with_tools() {
574 let dir = tempfile::tempdir().unwrap();
575 let yaml = r#"
576name: tool_agent
577model:
578 provider: openai
579 model_id: gpt-4
580tools:
581 - name: get_weather
582 - name: search
583"#;
584 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
585
586 let registry =
587 Arc::new(MockToolRegistry::new().with_tool("get_weather").with_tool("search"));
588 let factory = Arc::new(MockModelFactory);
589 let loader = AgentConfigLoader::new(registry, factory);
590
591 let agent = loader.load_file(&path).await.unwrap();
592 assert_eq!(agent.name(), "tool_agent");
593 }
594
595 #[tokio::test]
596 async fn test_load_file_unresolved_tool() {
597 let dir = tempfile::tempdir().unwrap();
598 let yaml = r#"
599name: bad_agent
600model:
601 provider: gemini
602 model_id: gemini-2.0-flash
603tools:
604 - name: nonexistent_tool
605"#;
606 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
607
608 let registry = Arc::new(MockToolRegistry::new());
609 let factory = Arc::new(MockModelFactory);
610 let loader = AgentConfigLoader::new(registry, factory);
611
612 let err = loader.load_file(&path).await.err().expect("expected error");
613 let msg = err.to_string();
614 assert!(msg.contains("nonexistent_tool"), "error should mention the tool name: {msg}");
615 assert!(msg.contains("unresolved tool reference"), "error should be descriptive: {msg}");
616 }
617
618 #[tokio::test]
619 async fn test_load_file_invalid_yaml() {
620 let dir = tempfile::tempdir().unwrap();
621 let yaml = "name: 123\nmodel: not_a_map\n";
622 let path = write_temp_yaml(dir.path(), "bad.yaml", yaml);
623
624 let registry = Arc::new(MockToolRegistry::new());
625 let factory = Arc::new(MockModelFactory);
626 let loader = AgentConfigLoader::new(registry, factory);
627
628 let err = loader.load_file(&path).await.err().expect("expected error");
629 let msg = err.to_string();
630 assert!(msg.contains("invalid YAML"), "error should mention YAML: {msg}");
631 }
632
633 #[tokio::test]
634 async fn test_load_file_empty_name() {
635 let dir = tempfile::tempdir().unwrap();
636 let yaml = r#"
637name: ""
638model:
639 provider: gemini
640 model_id: gemini-2.0-flash
641"#;
642 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
643
644 let registry = Arc::new(MockToolRegistry::new());
645 let factory = Arc::new(MockModelFactory);
646 let loader = AgentConfigLoader::new(registry, factory);
647
648 let err = loader.load_file(&path).await.err().expect("expected error");
649 let msg = err.to_string();
650 assert!(msg.contains("name"), "error should mention the field: {msg}");
651 }
652
653 #[tokio::test]
654 async fn test_load_directory_basic() {
655 let dir = tempfile::tempdir().unwrap();
656
657 write_temp_yaml(
658 dir.path(),
659 "agent_a.yaml",
660 r#"
661name: agent_a
662model:
663 provider: gemini
664 model_id: gemini-2.0-flash
665instructions: "Agent A"
666"#,
667 );
668
669 write_temp_yaml(
670 dir.path(),
671 "agent_b.yml",
672 r#"
673name: agent_b
674model:
675 provider: openai
676 model_id: gpt-4
677instructions: "Agent B"
678"#,
679 );
680
681 let registry = Arc::new(MockToolRegistry::new());
682 let factory = Arc::new(MockModelFactory);
683 let loader = AgentConfigLoader::new(registry, factory);
684
685 let agents = loader.load_directory(dir.path()).await.unwrap();
686 assert_eq!(agents.len(), 2);
687
688 let names: Vec<&str> = agents.iter().map(|a| a.name()).collect();
689 assert!(names.contains(&"agent_a"));
690 assert!(names.contains(&"agent_b"));
691 }
692
693 #[tokio::test]
694 async fn test_load_directory_with_sub_agents() {
695 let dir = tempfile::tempdir().unwrap();
696
697 write_temp_yaml(
699 dir.path(),
700 "01_agent_a.yaml",
701 r#"
702name: researcher
703model:
704 provider: gemini
705 model_id: gemini-2.0-flash
706instructions: "Research agent"
707"#,
708 );
709
710 write_temp_yaml(
711 dir.path(),
712 "02_agent_b.yaml",
713 r#"
714name: orchestrator
715model:
716 provider: gemini
717 model_id: gemini-2.0-flash
718instructions: "Orchestrator agent"
719sub_agents:
720 - ref: researcher
721"#,
722 );
723
724 let registry = Arc::new(MockToolRegistry::new());
725 let factory = Arc::new(MockModelFactory);
726 let loader = AgentConfigLoader::new(registry, factory);
727
728 let agents = loader.load_directory(dir.path()).await.unwrap();
729 assert_eq!(agents.len(), 2);
730
731 let orchestrator = agents.iter().find(|a| a.name() == "orchestrator").unwrap();
733 assert_eq!(orchestrator.sub_agents().len(), 1);
734 assert_eq!(orchestrator.sub_agents()[0].name(), "researcher");
735 }
736
737 #[tokio::test]
738 async fn test_load_directory_unresolved_sub_agent() {
739 let dir = tempfile::tempdir().unwrap();
740
741 write_temp_yaml(
742 dir.path(),
743 "agent.yaml",
744 r#"
745name: orchestrator
746model:
747 provider: gemini
748 model_id: gemini-2.0-flash
749sub_agents:
750 - ref: nonexistent_agent
751"#,
752 );
753
754 let registry = Arc::new(MockToolRegistry::new());
755 let factory = Arc::new(MockModelFactory);
756 let loader = AgentConfigLoader::new(registry, factory);
757
758 let err = loader.load_directory(dir.path()).await.err().expect("expected error");
759 let msg = err.to_string();
760 assert!(
761 msg.contains("nonexistent_agent"),
762 "error should mention the unresolved agent: {msg}"
763 );
764 }
765
766 #[tokio::test]
767 async fn test_load_directory_duplicate_names() {
768 let dir = tempfile::tempdir().unwrap();
769
770 write_temp_yaml(
771 dir.path(),
772 "agent_a.yaml",
773 r#"
774name: duplicate
775model:
776 provider: gemini
777 model_id: gemini-2.0-flash
778"#,
779 );
780
781 write_temp_yaml(
782 dir.path(),
783 "agent_b.yaml",
784 r#"
785name: duplicate
786model:
787 provider: openai
788 model_id: gpt-4
789"#,
790 );
791
792 let registry = Arc::new(MockToolRegistry::new());
793 let factory = Arc::new(MockModelFactory);
794 let loader = AgentConfigLoader::new(registry, factory);
795
796 let err = loader.load_directory(dir.path()).await.err().expect("expected error");
797 let msg = err.to_string();
798 assert!(msg.contains("duplicate"), "error should mention duplicate name: {msg}");
799 }
800
801 #[tokio::test]
802 async fn test_load_directory_empty() {
803 let dir = tempfile::tempdir().unwrap();
804
805 let registry = Arc::new(MockToolRegistry::new());
806 let factory = Arc::new(MockModelFactory);
807 let loader = AgentConfigLoader::new(registry, factory);
808
809 let agents = loader.load_directory(dir.path()).await.unwrap();
810 assert!(agents.is_empty());
811 }
812
813 #[tokio::test]
814 async fn test_load_directory_not_a_directory() {
815 let dir = tempfile::tempdir().unwrap();
816 let file_path = dir.path().join("not_a_dir.txt");
817 std::fs::write(&file_path, "hello").unwrap();
818
819 let registry = Arc::new(MockToolRegistry::new());
820 let factory = Arc::new(MockModelFactory);
821 let loader = AgentConfigLoader::new(registry, factory);
822
823 let err = loader.load_directory(&file_path).await.err().expect("expected error");
824 let msg = err.to_string();
825 assert!(msg.contains("not a directory"), "error should mention not a directory: {msg}");
826 }
827
828 #[tokio::test]
829 async fn test_reload_file() {
830 let dir = tempfile::tempdir().unwrap();
831 let yaml = r#"
832name: reloadable
833model:
834 provider: gemini
835 model_id: gemini-2.0-flash
836instructions: "Version 1"
837"#;
838 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
839
840 let registry = Arc::new(MockToolRegistry::new());
841 let factory = Arc::new(MockModelFactory);
842 let loader = AgentConfigLoader::new(registry, factory);
843
844 let agent = loader.load_file(&path).await.unwrap();
845 assert_eq!(agent.name(), "reloadable");
846
847 let yaml_v2 = r#"
849name: reloadable
850model:
851 provider: gemini
852 model_id: gemini-2.0-flash
853instructions: "Version 2"
854"#;
855 std::fs::write(&path, yaml_v2).unwrap();
856
857 let agent_v2 = loader.reload_file(&path).await.unwrap();
858 assert_eq!(agent_v2.name(), "reloadable");
859
860 let cached = loader.get_agent("reloadable").await.unwrap();
862 assert!(Arc::ptr_eq(&agent_v2, &cached));
863 }
864
865 #[tokio::test]
866 async fn test_load_file_with_model_config() {
867 let dir = tempfile::tempdir().unwrap();
868 let yaml = r#"
869name: configured_agent
870model:
871 provider: gemini
872 model_id: gemini-2.0-flash
873 temperature: 0.7
874 max_tokens: 4096
875instructions: "You are helpful."
876"#;
877 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
878
879 let registry = Arc::new(MockToolRegistry::new());
880 let factory = Arc::new(MockModelFactory);
881 let loader = AgentConfigLoader::new(registry, factory);
882
883 let agent = loader.load_file(&path).await.unwrap();
884 assert_eq!(agent.name(), "configured_agent");
885 }
886
887 #[tokio::test]
888 async fn test_load_file_model_factory_error() {
889 let dir = tempfile::tempdir().unwrap();
890 let yaml = r#"
891name: bad_model_agent
892model:
893 provider: unknown_provider
894 model_id: some-model
895"#;
896 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
897
898 let registry = Arc::new(MockToolRegistry::new());
899 let factory =
900 Arc::new(FailingModelFactory { fail_provider: "unknown_provider".to_string() });
901 let loader = AgentConfigLoader::new(registry, factory);
902
903 let err = loader.load_file(&path).await.err().expect("expected error");
904 let msg = err.to_string();
905 assert!(msg.contains("unknown_provider"), "error should mention the provider: {msg}");
906 }
907
908 #[tokio::test]
909 async fn test_load_file_with_mcp_tool_reference() {
910 let dir = tempfile::tempdir().unwrap();
911 let yaml = r#"
912name: mcp_agent
913model:
914 provider: gemini
915 model_id: gemini-2.0-flash
916tools:
917 - mcp:
918 endpoint: "npx @modelcontextprotocol/server-filesystem"
919 args: ["/data"]
920"#;
921 let path = write_temp_yaml(dir.path(), "agent.yaml", yaml);
922
923 let registry = Arc::new(MockToolRegistry::new());
924 let factory = Arc::new(MockModelFactory);
925 let loader = AgentConfigLoader::new(registry, factory);
926
927 let agent = loader.load_file(&path).await.unwrap();
929 assert_eq!(agent.name(), "mcp_agent");
930 }
931
932 #[tokio::test]
933 async fn test_load_file_nonexistent() {
934 let registry = Arc::new(MockToolRegistry::new());
935 let factory = Arc::new(MockModelFactory);
936 let loader = AgentConfigLoader::new(registry, factory);
937
938 let err = loader
939 .load_file(Path::new("/nonexistent/agent.yaml"))
940 .await
941 .err()
942 .expect("expected error");
943 let msg = err.to_string();
944 assert!(msg.contains("failed to read"), "error should mention read failure: {msg}");
945 }
946}