Skip to main content

agent_works/
builder.rs

1use std::collections::HashSet;
2use std::sync::Arc;
3
4use agent_base::{AgentResult, AgentRuntime, LlmClient, Tool};
5
6use crate::multi_agent::{MultiAgentConfig, MultiAgentRuntime};
7
8#[cfg(feature = "skill")]
9use crate::skill::{LazySkillPrompter, Skill, SkillPrompter};
10
11/// Factory type for creating multi-agent tools from a MultiAgentRuntime.
12pub type MultiAgentToolFactory =
13    Arc<dyn Fn(Arc<MultiAgentRuntime>) -> Vec<Arc<dyn Tool>> + Send + Sync>;
14
15/// Factory type for creating a skill detail tool from skills and a tool name.
16#[cfg(feature = "skill")]
17pub type SkillDetailToolFactory =
18    Arc<dyn Fn(Vec<Arc<dyn Skill>>, String) -> Arc<dyn Tool> + Send + Sync>;
19
20/// Factory type for creating a list-skills tool from a SkillRegistry.
21#[cfg(feature = "skill")]
22pub type ListSkillsToolFactory =
23    Arc<dyn Fn(Arc<crate::skill::SkillRegistry>) -> Arc<dyn Tool> + Send + Sync>;
24
25pub struct AgentBuilder {
26    inner: agent_base::AgentBuilder,
27    system_prompt: Option<String>,
28    tool_names: HashSet<String>,
29    /// Business tools to pass to child agents (all registered tools).
30    business_tools: Vec<Arc<dyn Tool>>,
31    /// Multi-agent configuration (None = disabled).
32    multi_agent_config: Option<MultiAgentConfig>,
33    /// Factory to create multi-agent tools (injected by phi-kernel-tools).
34    multi_agent_tool_factory: Option<MultiAgentToolFactory>,
35    /// Error recovery (stored for multi-agent child inheritance).
36    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
37    /// Language preference.
38    language: Option<agent_base::Language>,
39    #[cfg(feature = "skill")]
40    skills: Vec<Arc<dyn Skill>>,
41    #[cfg(feature = "skill")]
42    skill_prompter: Option<Arc<dyn SkillPrompter>>,
43    #[cfg(feature = "skill")]
44    skill_detail_tool_name: String,
45    /// Optional: inject a custom skill-detail tool (old tool-based mode).
46    /// In default prompt-injection mode, the LLM reads `SKILL.md` via
47    /// `read_file` — no dedicated detail tool is needed.
48    #[cfg(feature = "skill")]
49    skill_detail_tool_factory: Option<SkillDetailToolFactory>,
50    #[cfg(feature = "skill")]
51    list_skills_tool_factory: Option<ListSkillsToolFactory>,
52    #[cfg(feature = "skill")]
53    disable_skill_prompt_injection: bool,
54}
55
56impl AgentBuilder {
57    pub fn new(client: Arc<dyn LlmClient>) -> Self {
58        Self {
59            inner: agent_base::AgentBuilder::new(client),
60            system_prompt: None,
61            tool_names: HashSet::new(),
62            business_tools: Vec::new(),
63            multi_agent_config: None,
64            multi_agent_tool_factory: None,
65            error_recovery: None,
66            language: None,
67            #[cfg(feature = "skill")]
68            skills: Vec::new(),
69            #[cfg(feature = "skill")]
70            skill_prompter: None,
71            #[cfg(feature = "skill")]
72            skill_detail_tool_name: "get_skill_detail".to_string(),
73            #[cfg(feature = "skill")]
74            skill_detail_tool_factory: None,
75            #[cfg(feature = "skill")]
76            list_skills_tool_factory: None,
77            #[cfg(feature = "skill")]
78            disable_skill_prompt_injection: false,
79        }
80    }
81
82    /// Enable multi-agent support with the given configuration.
83    ///
84    /// Also sets the tool factory to create the 6 multi-agent tools.
85    /// Callers should use `phi_kernel_tools::multi_agent::create_all_tools` as the factory.
86    pub fn with_multi_agent(mut self, config: MultiAgentConfig) -> Self {
87        self.multi_agent_config = Some(config);
88        self
89    }
90
91    /// Disable multi-agent support.
92    ///
93    /// Removes any previously set multi-agent configuration. No multi-agent tools
94    /// will be registered and the system prompt will not mention multi-agent capabilities.
95    pub fn without_multi_agent(mut self) -> Self {
96        self.multi_agent_config = None;
97        self.multi_agent_tool_factory = None;
98        self
99    }
100
101    /// Set a custom factory for creating multi-agent tools.
102    ///
103    /// The factory receives the `MultiAgentRuntime` and returns the tools to register.
104    /// If not set but multi-agent is enabled, no tools are registered (caller must
105    /// set this for multi-agent to work).
106    pub fn with_multi_agent_tool_factory(mut self, factory: MultiAgentToolFactory) -> Self {
107        self.multi_agent_tool_factory = Some(factory);
108        self
109    }
110
111    /// Set a custom factory for creating the skill detail tool.
112    ///
113    /// The factory receives the skill list and tool name, and returns the tool.
114    /// If not set but skills are registered, no detail tool is added.
115    #[cfg(feature = "skill")]
116    pub fn with_skill_detail_tool_factory(mut self, factory: SkillDetailToolFactory) -> Self {
117        self.skill_detail_tool_factory = Some(factory);
118        self
119    }
120
121    /// Set a custom factory for creating the list-skills tool.
122    ///
123    /// The factory receives the SkillRegistry and returns the tool.
124    #[cfg(feature = "skill")]
125    pub fn with_list_skills_tool_factory(mut self, factory: ListSkillsToolFactory) -> Self {
126        self.list_skills_tool_factory = Some(factory);
127        self
128    }
129
130    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
131        let prompt = prompt.into();
132        self.inner = self.inner.system_prompt(prompt.clone());
133        self.system_prompt = Some(prompt);
134        self
135    }
136
137    pub fn enable_thought(self, enable: bool) -> Self {
138        Self {
139            inner: self.inner.enable_thought(enable),
140            ..self
141        }
142    }
143
144    pub fn reasoning(self, config: agent_base::ReasoningConfig) -> Self {
145        Self {
146            inner: self.inner.reasoning(config),
147            ..self
148        }
149    }
150
151    pub fn enable_thinking(self, enable: bool) -> Self {
152        Self {
153            inner: self.inner.enable_thinking(enable),
154            ..self
155        }
156    }
157
158    pub fn thinking_budget(self, budget: u64) -> Self {
159        Self {
160            inner: self.inner.thinking_budget(budget),
161            ..self
162        }
163    }
164
165    pub fn tool_timeout(self, timeout_ms: u64) -> Self {
166        Self {
167            inner: self.inner.tool_timeout(timeout_ms),
168            ..self
169        }
170    }
171
172    pub fn max_tool_output_chars(self, max_chars: usize) -> Self {
173        Self {
174            inner: self.inner.max_tool_output_chars(max_chars),
175            ..self
176        }
177    }
178
179    pub fn max_sessions(self, max: usize) -> Self {
180        Self {
181            inner: self.inner.max_sessions(max),
182            ..self
183        }
184    }
185
186    pub fn max_turns_per_session(self, max: usize) -> Self {
187        Self {
188            inner: self.inner.max_turns_per_session(max),
189            ..self
190        }
191    }
192
193    pub fn execution_max_turns(self, max: u32) -> Self {
194        Self {
195            inner: self.inner.execution_max_turns(max),
196            ..self
197        }
198    }
199
200    pub fn max_message_tokens(self, max: usize) -> Self {
201        Self {
202            inner: self.inner.max_message_tokens(max),
203            ..self
204        }
205    }
206
207    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
208        let tool_arc: Arc<dyn Tool> = Arc::new(tool);
209        self.tool_names.insert(tool_arc.name().to_string());
210        self.business_tools.push(tool_arc.clone());
211        self.inner = self.inner.register_tool_arc(tool_arc);
212        self
213    }
214
215    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
216        self.tool_names.insert(tool.name().to_string());
217        self.business_tools.push(tool.clone());
218        self.inner = self.inner.register_tool_arc(tool);
219        self
220    }
221
222    pub fn approval_handler(self, handler: Arc<dyn agent_base::ApprovalHandler>) -> Self {
223        Self {
224            inner: self.inner.approval_handler(handler),
225            ..self
226        }
227    }
228
229    pub fn tool_policy(self, policy: Arc<dyn agent_base::ToolPolicy>) -> Self {
230        Self {
231            inner: self.inner.tool_policy(policy),
232            ..self
233        }
234    }
235
236    pub fn middleware(self, mw: impl agent_base::Middleware + 'static) -> Self {
237        Self {
238            inner: self.inner.middleware(mw),
239            ..self
240        }
241    }
242
243    pub fn context_window(self, max_tokens: usize) -> Self {
244        Self {
245            inner: self.inner.context_window(max_tokens),
246            ..self
247        }
248    }
249
250    pub fn context_window_manager(self, manager: agent_base::ContextWindowManager) -> Self {
251        Self {
252            inner: self.inner.context_window_manager(manager),
253            ..self
254        }
255    }
256
257    pub fn response_format(self, format: agent_base::ResponseFormat) -> Self {
258        Self {
259            inner: self.inner.response_format(format),
260            ..self
261        }
262    }
263
264    pub fn llm_retry(self, retry: agent_base::RetryConfig) -> Self {
265        Self {
266            inner: self.inner.llm_retry(retry),
267            ..self
268        }
269    }
270
271    pub fn session_store(self, store: Arc<dyn agent_base::SessionStore>) -> Self {
272        Self {
273            inner: self.inner.session_store(store),
274            ..self
275        }
276    }
277
278    pub fn error_recovery(mut self, recovery: Arc<dyn agent_base::ToolErrorRecovery>) -> Self {
279        self.error_recovery = Some(recovery.clone());
280        self.inner = self.inner.error_recovery(recovery);
281        self
282    }
283
284    pub fn tool_error_retry_prompt(self, prompt: impl Into<String>) -> Self {
285        Self {
286            inner: self.inner.tool_error_retry_prompt(prompt),
287            ..self
288        }
289    }
290
291    pub fn language(mut self, language: agent_base::Language) -> Self {
292        self.language = Some(language.clone());
293        self.inner = self.inner.language(language);
294        self
295    }
296
297    pub fn event_bus_capacity(self, capacity: usize) -> Self {
298        Self {
299            inner: self.inner.event_bus_capacity(capacity),
300            ..self
301        }
302    }
303
304    pub fn session_id_generator(
305        self,
306        generator: Arc<dyn agent_base::types::SessionIdGenerator>,
307    ) -> Self {
308        Self {
309            inner: self.inner.session_id_generator(generator),
310            ..self
311        }
312    }
313
314    /// Conditionally apply a transformation when `value` is `Some`.
315    ///
316    /// This is a convenience for option-chaining builder patterns:
317    ///
318    /// ```ignore
319    /// builder.apply_if(args.thinking_budget, |b, budget| b.thinking_budget(budget))
320    /// ```
321    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
322        match value {
323            Some(v) => f(self, v),
324            None => self,
325        }
326    }
327
328    #[cfg(feature = "skill")]
329    pub fn register_skill(mut self, skill: impl Skill + 'static) -> Self {
330        self.skills.push(Arc::new(skill));
331        self
332    }
333
334    #[cfg(feature = "skill")]
335    pub fn register_skills(mut self, skills: Vec<Arc<dyn Skill>>) -> Self {
336        self.skills.extend(skills);
337        self
338    }
339
340    #[cfg(feature = "skill")]
341    pub fn skill_prompter(mut self, prompter: Arc<dyn SkillPrompter>) -> Self {
342        self.skill_prompter = Some(prompter);
343        self
344    }
345
346    #[cfg(feature = "skill")]
347    pub fn disable_skill_prompt_injection(mut self) -> Self {
348        self.disable_skill_prompt_injection = true;
349        self
350    }
351
352    #[cfg(feature = "skill")]
353    pub fn skill_detail_tool_name(mut self, name: impl Into<String>) -> Self {
354        self.skill_detail_tool_name = name.into();
355        self
356    }
357
358    // ── Build ──
359
360    pub fn build(self) -> AgentResult<AgentRuntime> {
361        #[cfg(feature = "skill")]
362        {
363            self.build_with_skills()
364        }
365        #[cfg(not(feature = "skill"))]
366        {
367            self.build_inner()
368        }
369    }
370
371    #[allow(dead_code)]
372    fn build_inner(mut self) -> AgentResult<AgentRuntime> {
373        let lang = self.language.clone().unwrap_or_default();
374        let ma_config = self.multi_agent_config.clone();
375        let ma_tool_factory = self.multi_agent_tool_factory.take();
376        let business_tools = std::mem::take(&mut self.business_tools);
377        let error_recovery = self.error_recovery.clone();
378        let tool_names = self.tool_names.clone();
379
380        // Inject multi-agent prompt before build
381        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
382            let ma_prompt = build_multi_agent_system_prompt();
383            let new_prompt = match self.system_prompt.take() {
384                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
385                None => ma_prompt,
386            };
387            self.inner = self.inner.system_prompt(new_prompt);
388        }
389
390        let runtime = self.inner.build()?;
391
392        // Post-build: register multi-agent tools if enabled and factory is set
393        if let Some(config) = ma_config
394            && config.enabled
395        {
396            setup_multi_agent(
397                &runtime,
398                config,
399                lang,
400                business_tools,
401                error_recovery,
402                &tool_names,
403                ma_tool_factory,
404            )?;
405        }
406
407        Ok(runtime)
408    }
409
410    /// Build the runtime with skill support.
411    ///
412    /// # Runtime requirement
413    ///
414    /// This method uses [`tokio::task::block_in_place`] to populate the skill
415    /// registry from a synchronous context. It **requires** a multi-threaded
416    /// tokio runtime. Calling it on a `#[tokio::main]` single-threaded
417    /// (`current_thread`) runtime will panic.
418    ///
419    /// The phi-agent CLI and all examples use the default multi-threaded runtime,
420    /// so this is safe in practice.
421    #[cfg(feature = "skill")]
422    fn build_with_skills(mut self) -> AgentResult<AgentRuntime> {
423        let mut ab = self.inner;
424        let lang = self.language.clone().unwrap_or_default();
425        let ma_config = self.multi_agent_config.clone();
426        let ma_tool_factory = self.multi_agent_tool_factory.take();
427        let business_tools = std::mem::take(&mut self.business_tools);
428        let error_recovery = self.error_recovery.clone();
429        let tool_names = self.tool_names.clone();
430
431        // Process skills
432        if !self.skills.is_empty() {
433            let prompter: Arc<dyn SkillPrompter> = self
434                .skill_prompter
435                .take()
436                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));
437
438            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();
439
440            for skill in self.skills {
441                for tool in skill.tools() {
442                    let tool_name = tool.name().to_string();
443                    if self.tool_names.contains(&tool_name) {
444                        return Err(agent_base::AgentError::internal(format!(
445                            "Tool name conflict: `{}` (Skill `{}`)",
446                            tool_name,
447                            skill.name()
448                        )));
449                    }
450                    self.tool_names.insert(tool_name);
451                    ab = ab.register_tool_arc(tool);
452                }
453                skill_refs.push(skill);
454            }
455
456            if !self.disable_skill_prompt_injection {
457                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
458                if !skill_prompt.is_empty() {
459                    let new_prompt = match self.system_prompt.take() {
460                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
461                        None => skill_prompt,
462                    };
463                    self.system_prompt = Some(new_prompt.clone());
464                    ab = ab.system_prompt(new_prompt);
465                }
466            }
467
468            // Use injected factory if available, otherwise skip — prompt-injection
469            // mode uses read_file instead of a dedicated detail tool.
470            if let Some(factory) = self.skill_detail_tool_factory.take() {
471                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
472                ab = ab.register_tool_arc(detail_tool);
473            }
474
475            // Create SkillRegistry and populate it for the list-skills tool
476            if let Some(factory) = self.list_skills_tool_factory.take() {
477                let registry = Arc::new(crate::skill::SkillRegistry::new());
478                for skill in &skill_refs {
479                    tokio::task::block_in_place(|| {
480                        tokio::runtime::Handle::current().block_on(async {
481                            registry.register(skill.clone()).await;
482                        })
483                    });
484                }
485                let list_tool = factory(registry);
486                ab = ab.register_tool_arc(list_tool);
487            }
488        }
489
490        // Inject multi-agent prompt
491        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
492            let ma_prompt = build_multi_agent_system_prompt();
493            let new_prompt = match self.system_prompt.take() {
494                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
495                None => ma_prompt,
496            };
497            ab = ab.system_prompt(new_prompt);
498        }
499
500        let runtime = ab.build()?;
501
502        // Post-build: register multi-agent tools
503        if let Some(config) = ma_config
504            && config.enabled
505        {
506            setup_multi_agent(
507                &runtime,
508                config,
509                lang,
510                business_tools,
511                error_recovery,
512                &tool_names,
513                ma_tool_factory,
514            )?;
515        }
516
517        Ok(runtime)
518    }
519}
520
521/// Set up the MultiAgentRuntime, event bridge, and register tools on an already-built runtime.
522///
523/// # Safety / Runtime Requirement
524///
525/// This function uses [`tokio::task::block_in_place`] to register tools synchronously.
526/// It **requires** a multi-threaded tokio runtime. Calling it on a
527/// `#[tokio::main]` single-threaded (`current_thread`) runtime will panic.
528///
529/// The phi-agent CLI and all examples use the default multi-threaded runtime,
530/// so this is safe in practice.
531pub fn setup_multi_agent(
532    runtime: &AgentRuntime,
533    config: MultiAgentConfig,
534    lang: agent_base::Language,
535    business_tools: Vec<Arc<dyn Tool>>,
536    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
537    existing_tool_names: &HashSet<String>,
538    tool_factory: Option<MultiAgentToolFactory>,
539) -> AgentResult<Arc<MultiAgentRuntime>> {
540    let client = runtime.client();
541    let cancel_token = runtime.cancel_token();
542
543    let ma_runtime = Arc::new(MultiAgentRuntime::new(
544        config.clone(),
545        client,
546        business_tools,
547        cancel_token,
548        error_recovery,
549        lang,
550    ));
551
552    // Set up event bridge: child events → parent event bus
553    let (event_tx, mut event_rx) =
554        tokio::sync::mpsc::unbounded_channel::<agent_base::RuntimeEvent>();
555    ma_runtime.set_event_sender(event_tx);
556    let parent_runtime = runtime.clone();
557    tokio::spawn(async move {
558        while let Some(event) = event_rx.recv().await {
559            parent_runtime.emit_event(event);
560        }
561    });
562
563    // Register multi-agent tools if a factory is provided
564    if let Some(factory) = tool_factory {
565        let tools = factory(ma_runtime.clone());
566        let registry = runtime.tools_mut();
567        let mut reg = tokio::task::block_in_place(|| registry.blocking_write());
568        for tool in tools {
569            let tool_name = tool.name().to_string();
570            if !existing_tool_names.contains(&tool_name) {
571                reg.register_arc(tool);
572            }
573        }
574        drop(reg);
575    }
576
577    Ok(ma_runtime)
578}
579
580/// Build the multi-agent system prompt guidance for the main agent.
581pub fn build_multi_agent_system_prompt() -> String {
582    r#"## Multi-Agent Capabilities
583
584You have the ability to spawn sub-agents to execute tasks concurrently. Use these tools to delegate work:
585
586- `spawn_agent`: Create a new sub-agent with a specific role. The agent runs independently.
587- `send_message`: Send a message to a sub-agent without triggering execution.
588- `followup_task`: Assign a task to a sub-agent and trigger its execution. Returns immediately.
589- `wait_agent`: Wait for a sub-agent's result. Blocks until the agent completes or timeout.
590- `list_agents`: List all active sub-agents and their status.
591- `close_agent`: Close a sub-agent and release its resources.
592
593### When to Spawn
594
595- Tasks that can run independently and in parallel (e.g., "research X and Y simultaneously")
596- Long-running tasks where you want to check intermediate results
597- Decomposing complex tasks into sub-tasks for focused execution
598
599### When NOT to Spawn
600
601- Simple lookups or single-tool calls (just use the tool directly)
602- Sequential dependencies where the next step requires the previous result
603- Tasks that need your full context or reasoning
604
605### Communication Pattern
606
6071. `spawn_agent` → create the sub-agent
6082. `followup_task` → assign work (can call multiple times)
6093. `wait_agent` → collect results
6104. `close_agent` → clean up when done"#
611        .to_string()
612}
613
614/// Build the memory system prompt guidance.
615///
616/// Tells the LLM how to use the file-based persistent memory system.
617/// Memory is stored as markdown files — the LLM uses `read_file` / `write_file`
618/// to manage them, following the same convention as Claude Code Memory.
619///
620/// This is prompt-injection only — no dedicated memory tools are registered.
621/// The LLM uses the general-purpose file tools to read/write memory files.
622pub fn build_memory_system_prompt() -> String {
623    r#"## Memory
624
625You have a persistent file-based memory at `.phi/memory/`. Use `read_file` and `write_file` to manage it — there are no dedicated memory tools.
626
627### How Memory Works
628
629- `MEMORY.md` is the index — it lists all memories with one-line descriptions. Read it first when you need to recall something.
630- Each memory is a separate `.md` file with YAML frontmatter:
631  ```yaml
632  ---
633  name: <short-kebab-case-slug>
634  description: <one-line summary — used to decide relevance during recall>
635  metadata:
636    node_type: memory
637    type: user | feedback | project | reference
638  ---
639
640  <the fact or instruction>
641  ```
642- The `description` field is the key for recall — write it so you can tell at a glance whether this memory is relevant to the current task.
643- Link related memories with `[[memory-name]]` in the body.
644- `user` type = who the user is (role, expertise, preferences).
645- `feedback` type = guidance the user has given on how you should work.
646- `project` type = ongoing work, goals, or constraints.
647- `reference` type = pointers to external resources (URLs, dashboards, tickets).
648
649### When to Use Memory
650
651- The user explicitly asks you to remember something ("remember this", "save that")
652- You learn something important about the user's preferences or workflow
653- After completing a significant task, save context that would help in future sessions
654- The user gives you feedback on how to work — save it as `feedback` type
655
656### When NOT to Use Memory
657
658- For transient information that won't be useful beyond this session
659- For facts already recorded in the codebase (code structure, git history, config files)
660- For items that only matter to the current conversation
661
662### Pro Tips
663
664- When creating your first memory of a new type, you can read template files for format reference (check `.phi/templates/memory/` if available).
665- Keep the MEMORY.md index concise — it's loaded into context every session.
666- Before writing a new memory, check if an existing file already covers it — update instead of duplicating.
667
668### Workflow
669
670**To recall:** read `MEMORY.md` → find relevant entries by description → read the specific `.md` files you need.
671**To remember:** create a new `.md` file with proper frontmatter → update `MEMORY.md` with a new entry.
672**To update:** edit the existing `.md` file (don't create a duplicate).
673**To forget:** delete the `.md` file → remove its entry from `MEMORY.md`."#
674        .to_string()
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680    use agent_base::ToolControlFlow;
681    use std::pin::Pin;
682
683    // ── Stub LLM client ──
684
685    struct StubClient;
686
687    #[async_trait::async_trait]
688    impl LlmClient for StubClient {
689        async fn chat(
690            &self,
691            _messages: &[agent_base::ChatMessage],
692            _tools: &[serde_json::Value],
693            _reasoning: Option<&agent_base::ReasoningConfig>,
694            _response_format: Option<&agent_base::ResponseFormat>,
695        ) -> AgentResult<serde_json::Value> {
696            Ok(serde_json::json!({"choices": [{"message": {"content": "ok"}}]}))
697        }
698
699        async fn chat_stream(
700            &self,
701            _messages: &[agent_base::ChatMessage],
702            _tools: &[serde_json::Value],
703            _reasoning: Option<&agent_base::ReasoningConfig>,
704            _response_format: Option<&agent_base::ResponseFormat>,
705        ) -> AgentResult<
706            Pin<Box<dyn futures_core::Stream<Item = AgentResult<agent_base::StreamChunk>> + Send>>,
707        > {
708            let chunks: Vec<AgentResult<agent_base::StreamChunk>> = vec![
709                Ok(agent_base::StreamChunk::Text("ok".to_string())),
710                Ok(agent_base::StreamChunk::Stop),
711            ];
712            Ok(Box::pin(futures_util::stream::iter(chunks)))
713        }
714
715        fn capabilities(&self) -> agent_base::LlmCapabilities {
716            agent_base::LlmCapabilities {
717                supports_streaming: true,
718                supports_tools: true,
719                supports_vision: false,
720                supports_thinking: false,
721                max_context_tokens: None,
722                max_output_tokens: None,
723            }
724        }
725    }
726
727    fn make_client() -> Arc<dyn LlmClient> {
728        Arc::new(StubClient)
729    }
730
731    // ── setup_multi_agent tests ──
732
733    #[tokio::test(flavor = "multi_thread")]
734    async fn test_setup_multi_agent_without_factory_registers_no_tools() {
735        let client = make_client();
736        let runtime = agent_base::AgentBuilder::new(client.clone())
737            .build()
738            .unwrap();
739        let config = MultiAgentConfig::enabled();
740
741        let result = setup_multi_agent(
742            &runtime,
743            config,
744            agent_base::Language::En,
745            vec![],
746            None,
747            &HashSet::new(),
748            None, // no factory
749        );
750        assert!(result.is_ok());
751        let ma_runtime = result.unwrap();
752        // Verify no tools were registered (the 6 multi-agent tools are absent)
753        let agents = ma_runtime.list_agents();
754        assert!(agents.is_empty());
755    }
756
757    #[tokio::test(flavor = "multi_thread")]
758    async fn test_setup_multi_agent_with_factory_registers_tools() {
759        let client = make_client();
760        let runtime = agent_base::AgentBuilder::new(client.clone())
761            .build()
762            .unwrap();
763        let config = MultiAgentConfig::enabled();
764
765        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
766            // Minimal factory returning a single fake tool
767            struct FakeTool;
768            #[async_trait::async_trait]
769            impl Tool for FakeTool {
770                fn name(&self) -> &'static str {
771                    "fake_tool"
772                }
773                fn definition(&self) -> serde_json::Value {
774                    serde_json::json!({"type": "function", "function": {"name": "fake_tool"}})
775                }
776                async fn call(
777                    &self,
778                    _args: &serde_json::Value,
779                    _ctx: &agent_base::ToolContext,
780                ) -> AgentResult<agent_base::ToolOutput> {
781                    Ok(agent_base::ToolOutput {
782                        summary: "ok".into(),
783                        raw: None,
784                        control_flow: ToolControlFlow::Continue,
785                        truncation: None,
786                    })
787                }
788            }
789            vec![Arc::new(FakeTool)]
790        });
791
792        let result = setup_multi_agent(
793            &runtime,
794            config,
795            agent_base::Language::En,
796            vec![],
797            None,
798            &HashSet::new(),
799            Some(factory),
800        );
801        assert!(result.is_ok());
802
803        // Check the tool was registered on the runtime
804        let tools: Vec<String> = tokio::task::block_in_place(|| {
805            let tools = runtime.tools_mut();
806            let guard = tools.blocking_read();
807            guard.metadatas().into_iter().map(|m| m.name).collect()
808        });
809        assert!(tools.contains(&"fake_tool".to_string()));
810    }
811
812    #[tokio::test(flavor = "multi_thread")]
813    async fn test_setup_multi_agent_skips_duplicate_tool_names() {
814        let client = make_client();
815        let runtime = agent_base::AgentBuilder::new(client.clone())
816            .build()
817            .unwrap();
818
819        // Pre-register a tool with a conflicting name
820        struct DupTool;
821        #[async_trait::async_trait]
822        impl Tool for DupTool {
823            fn name(&self) -> &'static str {
824                "dup_tool"
825            }
826            fn definition(&self) -> serde_json::Value {
827                serde_json::json!({"type": "function", "function": {"name": "dup_tool"}})
828            }
829            async fn call(
830                &self,
831                _args: &serde_json::Value,
832                _ctx: &agent_base::ToolContext,
833            ) -> AgentResult<agent_base::ToolOutput> {
834                Ok(agent_base::ToolOutput {
835                    summary: "ok".into(),
836                    raw: None,
837                    control_flow: ToolControlFlow::Continue,
838                    truncation: None,
839                })
840            }
841        }
842        {
843            let tools = runtime.tools_mut();
844            let mut reg = tokio::task::block_in_place(|| tools.blocking_write());
845            reg.register(DupTool);
846        }
847
848        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
849            struct FakeTool;
850            #[async_trait::async_trait]
851            impl Tool for FakeTool {
852                fn name(&self) -> &'static str {
853                    "dup_tool"
854                }
855                fn definition(&self) -> serde_json::Value {
856                    serde_json::json!({"type": "function", "function": {"name": "dup_tool"}})
857                }
858                async fn call(
859                    &self,
860                    _args: &serde_json::Value,
861                    _ctx: &agent_base::ToolContext,
862                ) -> AgentResult<agent_base::ToolOutput> {
863                    Ok(agent_base::ToolOutput {
864                        summary: "ok".into(),
865                        raw: None,
866                        control_flow: ToolControlFlow::Continue,
867                        truncation: None,
868                    })
869                }
870            }
871            vec![Arc::new(FakeTool)]
872        });
873
874        let mut existing = HashSet::new();
875        existing.insert("dup_tool".to_string());
876
877        let result = setup_multi_agent(
878            &runtime,
879            MultiAgentConfig::enabled(),
880            agent_base::Language::En,
881            vec![],
882            None,
883            &existing,
884            Some(factory),
885        );
886        assert!(result.is_ok());
887        // dup_tool should NOT have been registered twice
888        let tools = tokio::task::block_in_place(|| {
889            let tools = runtime.tools_mut();
890            let guard = tools.blocking_read();
891            guard
892                .metadatas()
893                .into_iter()
894                .map(|m| m.name)
895                .collect::<Vec<String>>()
896        });
897        let count = tools.iter().filter(|n| n.as_str() == "dup_tool").count();
898        assert_eq!(count, 1);
899    }
900
901    // ── AgentBuilder factory methods ──
902
903    #[tokio::test(flavor = "multi_thread")]
904    async fn test_builder_with_multi_agent_without_factory_builds_ok() {
905        let client = make_client();
906        let runtime = AgentBuilder::new(client)
907            .with_multi_agent(MultiAgentConfig::enabled())
908            .build()
909            .unwrap();
910        // Should succeed even without a factory (no tools registered)
911        let tools = tokio::task::block_in_place(|| {
912            let tools = runtime.tools_mut();
913            let guard = tools.blocking_read();
914            guard
915                .metadatas()
916                .into_iter()
917                .map(|m| m.name)
918                .collect::<Vec<String>>()
919        });
920        // No multi-agent tools registered
921        assert!(!tools.contains(&"spawn_agent".to_string()));
922    }
923
924    #[tokio::test(flavor = "multi_thread")]
925    async fn test_builder_with_factory_registers_tools() {
926        let client = make_client();
927        // Create a simple factory that registers one recognizable tool
928        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
929            struct TestTool;
930            #[async_trait::async_trait]
931            impl Tool for TestTool {
932                fn name(&self) -> &'static str {
933                    "factory_test_tool"
934                }
935                fn definition(&self) -> serde_json::Value {
936                    serde_json::json!({"type": "function", "function": {"name": "factory_test_tool"}})
937                }
938                async fn call(
939                    &self,
940                    _args: &serde_json::Value,
941                    _ctx: &agent_base::ToolContext,
942                ) -> AgentResult<agent_base::ToolOutput> {
943                    Ok(agent_base::ToolOutput {
944                        summary: "ok".into(),
945                        raw: None,
946                        control_flow: ToolControlFlow::Continue,
947                        truncation: None,
948                    })
949                }
950            }
951            vec![Arc::new(TestTool)]
952        });
953
954        let runtime = AgentBuilder::new(client)
955            .with_multi_agent(MultiAgentConfig::enabled())
956            .with_multi_agent_tool_factory(factory)
957            .build()
958            .unwrap();
959
960        let tools = tokio::task::block_in_place(|| {
961            let tools = runtime.tools_mut();
962            let guard = tools.blocking_read();
963            guard
964                .metadatas()
965                .into_iter()
966                .map(|m| m.name)
967                .collect::<Vec<String>>()
968        });
969        assert!(tools.contains(&"factory_test_tool".to_string()));
970    }
971
972    #[test]
973    fn test_builder_disabled_multi_agent_skips_factory() {
974        let client = make_client();
975        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
976            panic!("factory should not be called when multi-agent is not configured");
977        });
978
979        let runtime = AgentBuilder::new(client)
980            .with_multi_agent_tool_factory(factory)
981            // Don't enable multi-agent — default (None) means disabled
982            .build()
983            .unwrap();
984
985        let tools = tokio::task::block_in_place(|| {
986            let tools = runtime.tools_mut();
987            let guard = tools.blocking_read();
988            guard
989                .metadatas()
990                .into_iter()
991                .map(|m| m.name)
992                .collect::<Vec<String>>()
993        });
994        assert!(!tools.contains(&"spawn_agent".to_string()));
995    }
996
997    // ── build_multi_agent_system_prompt ──
998
999    #[test]
1000    fn test_system_prompt_contains_tool_names() {
1001        let prompt = build_multi_agent_system_prompt();
1002        assert!(prompt.contains("spawn_agent"));
1003        assert!(prompt.contains("send_message"));
1004        assert!(prompt.contains("followup_task"));
1005        assert!(prompt.contains("wait_agent"));
1006        assert!(prompt.contains("list_agents"));
1007        assert!(prompt.contains("close_agent"));
1008    }
1009
1010    #[test]
1011    fn test_system_prompt_contains_guidance() {
1012        let prompt = build_multi_agent_system_prompt();
1013        assert!(prompt.contains("When to Spawn"));
1014        assert!(prompt.contains("When NOT to Spawn"));
1015        assert!(prompt.contains("Communication Pattern"));
1016    }
1017
1018    // ── without_multi_agent ──
1019
1020    #[tokio::test(flavor = "multi_thread")]
1021    async fn test_without_multi_agent_clears_config_and_factory() {
1022        let client = make_client();
1023
1024        // Set up a factory that would panic if called — without_multi_agent should prevent it
1025        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1026            panic!("factory should not be called when multi-agent is cleared");
1027        });
1028
1029        let runtime = AgentBuilder::new(client)
1030            .with_multi_agent(MultiAgentConfig::enabled())
1031            .with_multi_agent_tool_factory(factory)
1032            .without_multi_agent() // clear both
1033            .build()
1034            .unwrap();
1035
1036        let tools = tokio::task::block_in_place(|| {
1037            let tools = runtime.tools_mut();
1038            let guard = tools.blocking_read();
1039            guard
1040                .metadatas()
1041                .into_iter()
1042                .map(|m| m.name)
1043                .collect::<Vec<String>>()
1044        });
1045        assert!(!tools.contains(&"spawn_agent".to_string()));
1046    }
1047
1048    // ── apply_if ──
1049
1050    #[test]
1051    fn test_apply_if_some_applies_transformation() {
1052        let client = make_client();
1053        let builder = AgentBuilder::new(client)
1054            .apply_if(Some("custom prompt"), |b, prompt| b.system_prompt(prompt));
1055        // system_prompt is stored in self.system_prompt; verify it was set
1056        assert!(builder.system_prompt.unwrap().contains("custom prompt"));
1057    }
1058
1059    #[test]
1060    fn test_apply_if_none_passes_through() {
1061        let client = make_client();
1062        let builder = AgentBuilder::new(client).apply_if(None as Option<&str>, |_b, _prompt| {
1063            panic!("should not be called when value is None");
1064        });
1065        assert!(builder.system_prompt.is_none());
1066    }
1067
1068    // ── build_memory_system_prompt ──
1069
1070    #[test]
1071    fn test_build_memory_system_prompt_non_empty() {
1072        let prompt = build_memory_system_prompt();
1073        assert!(!prompt.is_empty());
1074        assert!(prompt.contains("Memory"));
1075        assert!(prompt.contains("MEMORY.md"));
1076        assert!(prompt.contains("read_file"));
1077        assert!(prompt.contains("write_file"));
1078    }
1079}