Skip to main content

agent_works/
builder.rs

1use std::collections::HashSet;
2use std::sync::Arc;
3
4use agent_base::{AgentResult, AgentRuntime, StreamClient, 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 StreamClient>) -> 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 parent session manager for fork_history support
553    ma_runtime.set_session_manager(Arc::new(runtime.session_manager().clone()));
554
555    // Set up event bridge: child events → parent event bus
556    let (event_tx, mut event_rx) =
557        tokio::sync::mpsc::unbounded_channel::<agent_base::RuntimeEvent>();
558    ma_runtime.set_event_sender(event_tx);
559    let parent_runtime = runtime.clone();
560    tokio::spawn(async move {
561        while let Some(event) = event_rx.recv().await {
562            parent_runtime.emit_event(event);
563        }
564    });
565
566    // Register multi-agent tools if a factory is provided
567    if let Some(factory) = tool_factory {
568        let tools = factory(ma_runtime.clone());
569        let registry = runtime.tools_mut();
570        let mut reg = tokio::task::block_in_place(|| registry.blocking_write());
571        for tool in tools {
572            let tool_name = tool.name().to_string();
573            if !existing_tool_names.contains(&tool_name) {
574                reg.register_arc(tool);
575            }
576        }
577        drop(reg);
578    }
579
580    Ok(ma_runtime)
581}
582
583/// Build the multi-agent system prompt guidance for the main agent.
584pub fn build_multi_agent_system_prompt() -> String {
585    r#"## Multi-Agent Capabilities
586
587You have the ability to spawn sub-agents to execute tasks concurrently. Use these tools to delegate work:
588
589- `spawn_agent`: Create a new sub-agent with a specific role. The agent runs independently.
590- `send_message`: Send a message to a sub-agent without triggering execution.
591- `followup_task`: Assign a task to a sub-agent and trigger its execution. Returns immediately.
592- `wait_agent`: Wait for a sub-agent's result. Blocks until the agent completes or timeout.
593- `list_agents`: List all active sub-agents and their status.
594- `close_agent`: Close a sub-agent and release its resources.
595
596### When to Spawn
597
598- Tasks that can run independently and in parallel (e.g., "research X and Y simultaneously")
599- Long-running tasks where you want to check intermediate results
600- Decomposing complex tasks into sub-tasks for focused execution
601
602### When NOT to Spawn
603
604- Simple lookups or single-tool calls (just use the tool directly)
605- Sequential dependencies where the next step requires the previous result
606- Tasks that need your full context or reasoning
607
608### Communication Pattern
609
6101. `spawn_agent` → create the sub-agent
6112. `followup_task` → assign work (can call multiple times)
6123. `wait_agent` → collect results
6134. `close_agent` → clean up when done"#
614        .to_string()
615}
616
617/// Build the memory system prompt guidance.
618///
619/// Tells the LLM how to use the file-based persistent memory system.
620/// Memory is stored as markdown files — the LLM uses `read_file` / `write_file`
621/// to manage them, following the same convention as Claude Code Memory.
622///
623/// This is prompt-injection only — no dedicated memory tools are registered.
624/// The LLM uses the general-purpose file tools to read/write memory files.
625pub fn build_memory_system_prompt() -> String {
626    r#"## Memory
627
628You have a persistent file-based memory at `.phi/memory/`. Use `read_file` and `write_file` to manage it — there are no dedicated memory tools.
629
630### How Memory Works
631
632- `MEMORY.md` is the index — it lists all memories with one-line descriptions. Read it first when you need to recall something.
633- Each memory is a separate `.md` file with YAML frontmatter:
634  ```yaml
635  ---
636  name: <short-kebab-case-slug>
637  description: <one-line summary — used to decide relevance during recall>
638  metadata:
639    node_type: memory
640    type: user | feedback | project | reference
641  ---
642
643  <the fact or instruction>
644  ```
645- 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.
646- Link related memories with `[[memory-name]]` in the body.
647- `user` type = who the user is (role, expertise, preferences).
648- `feedback` type = guidance the user has given on how you should work.
649- `project` type = ongoing work, goals, or constraints.
650- `reference` type = pointers to external resources (URLs, dashboards, tickets).
651
652### When to Use Memory
653
654- The user explicitly asks you to remember something ("remember this", "save that")
655- You learn something important about the user's preferences or workflow
656- After completing a significant task, save context that would help in future sessions
657- The user gives you feedback on how to work — save it as `feedback` type
658
659### When NOT to Use Memory
660
661- For transient information that won't be useful beyond this session
662- For facts already recorded in the codebase (code structure, git history, config files)
663- For items that only matter to the current conversation
664
665### Pro Tips
666
667- When creating your first memory of a new type, you can read template files for format reference (check `.phi/templates/memory/` if available).
668- Keep the MEMORY.md index concise — it's loaded into context every session.
669- Before writing a new memory, check if an existing file already covers it — update instead of duplicating.
670
671### Workflow
672
673**To recall:** read `MEMORY.md` → find relevant entries by description → read the specific `.md` files you need.
674**To remember:** create a new `.md` file with proper frontmatter → update `MEMORY.md` with a new entry.
675**To update:** edit the existing `.md` file (don't create a duplicate).
676**To forget:** delete the `.md` file → remove its entry from `MEMORY.md`."#
677        .to_string()
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683    use agent_base::{LlmClient, ToolControlFlow};
684    use std::pin::Pin;
685
686    // ── Stub LLM client ──
687
688    struct StubClient;
689
690    #[async_trait::async_trait]
691    impl LlmClient for StubClient {
692        async fn chat(
693            &self,
694            _messages: &[agent_base::ChatMessage],
695            _tools: &[serde_json::Value],
696            _reasoning: Option<&agent_base::ReasoningConfig>,
697            _response_format: Option<&agent_base::ResponseFormat>,
698        ) -> AgentResult<serde_json::Value> {
699            Ok(serde_json::json!({"choices": [{"message": {"content": "ok"}}]}))
700        }
701
702        async fn chat_stream(
703            &self,
704            _messages: &[agent_base::ChatMessage],
705            _tools: &[serde_json::Value],
706            _reasoning: Option<&agent_base::ReasoningConfig>,
707            _response_format: Option<&agent_base::ResponseFormat>,
708        ) -> AgentResult<
709            Pin<Box<dyn futures_core::Stream<Item = AgentResult<agent_base::StreamChunk>> + Send>>,
710        > {
711            let chunks: Vec<AgentResult<agent_base::StreamChunk>> = vec![
712                Ok(agent_base::StreamChunk::Text("ok".to_string())),
713                Ok(agent_base::StreamChunk::Stop {
714                    finish_reason: Some("stop".to_string()),
715                }),
716            ];
717            Ok(Box::pin(futures_util::stream::iter(chunks)))
718        }
719
720        fn capabilities(&self) -> agent_base::LlmCapabilities {
721            agent_base::LlmCapabilities {
722                supports_streaming: true,
723                supports_tools: true,
724                supports_vision: false,
725                supports_thinking: false,
726                max_context_tokens: None,
727                max_output_tokens: None,
728            }
729        }
730    }
731
732    fn make_client() -> Arc<dyn StreamClient> {
733        agent_base::llm::adapt(Arc::new(StubClient))
734    }
735
736    // ── setup_multi_agent tests ──
737
738    #[tokio::test(flavor = "multi_thread")]
739    async fn test_setup_multi_agent_without_factory_registers_no_tools() {
740        let client = make_client();
741        let runtime = agent_base::AgentBuilder::new(client.clone())
742            .build()
743            .unwrap();
744        let config = MultiAgentConfig::enabled();
745
746        let result = setup_multi_agent(
747            &runtime,
748            config,
749            agent_base::Language::En,
750            vec![],
751            None,
752            &HashSet::new(),
753            None, // no factory
754        );
755        assert!(result.is_ok());
756        let ma_runtime = result.unwrap();
757        // Verify no tools were registered (the 6 multi-agent tools are absent)
758        let agents = ma_runtime.list_agents();
759        assert!(agents.is_empty());
760    }
761
762    #[tokio::test(flavor = "multi_thread")]
763    async fn test_setup_multi_agent_with_factory_registers_tools() {
764        let client = make_client();
765        let runtime = agent_base::AgentBuilder::new(client.clone())
766            .build()
767            .unwrap();
768        let config = MultiAgentConfig::enabled();
769
770        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
771            // Minimal factory returning a single fake tool
772            struct FakeTool;
773            #[async_trait::async_trait]
774            impl Tool for FakeTool {
775                fn name(&self) -> &'static str {
776                    "fake_tool"
777                }
778                fn definition(&self) -> serde_json::Value {
779                    serde_json::json!({"type": "function", "function": {"name": "fake_tool"}})
780                }
781                async fn call(
782                    &self,
783                    _args: &serde_json::Value,
784                    _ctx: &agent_base::ToolContext,
785                ) -> AgentResult<agent_base::ToolOutput> {
786                    Ok(agent_base::ToolOutput {
787                        summary: "ok".into(),
788                        raw: None,
789                        control_flow: ToolControlFlow::Continue,
790                        truncation: None,
791                    })
792                }
793            }
794            vec![Arc::new(FakeTool)]
795        });
796
797        let result = setup_multi_agent(
798            &runtime,
799            config,
800            agent_base::Language::En,
801            vec![],
802            None,
803            &HashSet::new(),
804            Some(factory),
805        );
806        assert!(result.is_ok());
807
808        // Check the tool was registered on the runtime
809        let tools: Vec<String> = tokio::task::block_in_place(|| {
810            let tools = runtime.tools_mut();
811            let guard = tools.blocking_read();
812            guard.metadatas().into_iter().map(|m| m.name).collect()
813        });
814        assert!(tools.contains(&"fake_tool".to_string()));
815    }
816
817    #[tokio::test(flavor = "multi_thread")]
818    async fn test_setup_multi_agent_skips_duplicate_tool_names() {
819        let client = make_client();
820        let runtime = agent_base::AgentBuilder::new(client.clone())
821            .build()
822            .unwrap();
823
824        // Pre-register a tool with a conflicting name
825        struct DupTool;
826        #[async_trait::async_trait]
827        impl Tool for DupTool {
828            fn name(&self) -> &'static str {
829                "dup_tool"
830            }
831            fn definition(&self) -> serde_json::Value {
832                serde_json::json!({"type": "function", "function": {"name": "dup_tool"}})
833            }
834            async fn call(
835                &self,
836                _args: &serde_json::Value,
837                _ctx: &agent_base::ToolContext,
838            ) -> AgentResult<agent_base::ToolOutput> {
839                Ok(agent_base::ToolOutput {
840                    summary: "ok".into(),
841                    raw: None,
842                    control_flow: ToolControlFlow::Continue,
843                    truncation: None,
844                })
845            }
846        }
847        {
848            let tools = runtime.tools_mut();
849            let mut reg = tokio::task::block_in_place(|| tools.blocking_write());
850            reg.register(DupTool);
851        }
852
853        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
854            struct FakeTool;
855            #[async_trait::async_trait]
856            impl Tool for FakeTool {
857                fn name(&self) -> &'static str {
858                    "dup_tool"
859                }
860                fn definition(&self) -> serde_json::Value {
861                    serde_json::json!({"type": "function", "function": {"name": "dup_tool"}})
862                }
863                async fn call(
864                    &self,
865                    _args: &serde_json::Value,
866                    _ctx: &agent_base::ToolContext,
867                ) -> AgentResult<agent_base::ToolOutput> {
868                    Ok(agent_base::ToolOutput {
869                        summary: "ok".into(),
870                        raw: None,
871                        control_flow: ToolControlFlow::Continue,
872                        truncation: None,
873                    })
874                }
875            }
876            vec![Arc::new(FakeTool)]
877        });
878
879        let mut existing = HashSet::new();
880        existing.insert("dup_tool".to_string());
881
882        let result = setup_multi_agent(
883            &runtime,
884            MultiAgentConfig::enabled(),
885            agent_base::Language::En,
886            vec![],
887            None,
888            &existing,
889            Some(factory),
890        );
891        assert!(result.is_ok());
892        // dup_tool should NOT have been registered twice
893        let tools = tokio::task::block_in_place(|| {
894            let tools = runtime.tools_mut();
895            let guard = tools.blocking_read();
896            guard
897                .metadatas()
898                .into_iter()
899                .map(|m| m.name)
900                .collect::<Vec<String>>()
901        });
902        let count = tools.iter().filter(|n| n.as_str() == "dup_tool").count();
903        assert_eq!(count, 1);
904    }
905
906    // ── AgentBuilder factory methods ──
907
908    #[tokio::test(flavor = "multi_thread")]
909    async fn test_builder_with_multi_agent_without_factory_builds_ok() {
910        let client = make_client();
911        let runtime = AgentBuilder::new(client)
912            .with_multi_agent(MultiAgentConfig::enabled())
913            .build()
914            .unwrap();
915        // Should succeed even without a factory (no tools registered)
916        let tools = tokio::task::block_in_place(|| {
917            let tools = runtime.tools_mut();
918            let guard = tools.blocking_read();
919            guard
920                .metadatas()
921                .into_iter()
922                .map(|m| m.name)
923                .collect::<Vec<String>>()
924        });
925        // No multi-agent tools registered
926        assert!(!tools.contains(&"spawn_agent".to_string()));
927    }
928
929    #[tokio::test(flavor = "multi_thread")]
930    async fn test_builder_with_factory_registers_tools() {
931        let client = make_client();
932        // Create a simple factory that registers one recognizable tool
933        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
934            struct TestTool;
935            #[async_trait::async_trait]
936            impl Tool for TestTool {
937                fn name(&self) -> &'static str {
938                    "factory_test_tool"
939                }
940                fn definition(&self) -> serde_json::Value {
941                    serde_json::json!({"type": "function", "function": {"name": "factory_test_tool"}})
942                }
943                async fn call(
944                    &self,
945                    _args: &serde_json::Value,
946                    _ctx: &agent_base::ToolContext,
947                ) -> AgentResult<agent_base::ToolOutput> {
948                    Ok(agent_base::ToolOutput {
949                        summary: "ok".into(),
950                        raw: None,
951                        control_flow: ToolControlFlow::Continue,
952                        truncation: None,
953                    })
954                }
955            }
956            vec![Arc::new(TestTool)]
957        });
958
959        let runtime = AgentBuilder::new(client)
960            .with_multi_agent(MultiAgentConfig::enabled())
961            .with_multi_agent_tool_factory(factory)
962            .build()
963            .unwrap();
964
965        let tools = tokio::task::block_in_place(|| {
966            let tools = runtime.tools_mut();
967            let guard = tools.blocking_read();
968            guard
969                .metadatas()
970                .into_iter()
971                .map(|m| m.name)
972                .collect::<Vec<String>>()
973        });
974        assert!(tools.contains(&"factory_test_tool".to_string()));
975    }
976
977    #[test]
978    fn test_builder_disabled_multi_agent_skips_factory() {
979        let client = make_client();
980        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
981            panic!("factory should not be called when multi-agent is not configured");
982        });
983
984        let runtime = AgentBuilder::new(client)
985            .with_multi_agent_tool_factory(factory)
986            // Don't enable multi-agent — default (None) means disabled
987            .build()
988            .unwrap();
989
990        let tools = tokio::task::block_in_place(|| {
991            let tools = runtime.tools_mut();
992            let guard = tools.blocking_read();
993            guard
994                .metadatas()
995                .into_iter()
996                .map(|m| m.name)
997                .collect::<Vec<String>>()
998        });
999        assert!(!tools.contains(&"spawn_agent".to_string()));
1000    }
1001
1002    // ── build_multi_agent_system_prompt ──
1003
1004    #[test]
1005    fn test_system_prompt_contains_tool_names() {
1006        let prompt = build_multi_agent_system_prompt();
1007        assert!(prompt.contains("spawn_agent"));
1008        assert!(prompt.contains("send_message"));
1009        assert!(prompt.contains("followup_task"));
1010        assert!(prompt.contains("wait_agent"));
1011        assert!(prompt.contains("list_agents"));
1012        assert!(prompt.contains("close_agent"));
1013    }
1014
1015    #[test]
1016    fn test_system_prompt_contains_guidance() {
1017        let prompt = build_multi_agent_system_prompt();
1018        assert!(prompt.contains("When to Spawn"));
1019        assert!(prompt.contains("When NOT to Spawn"));
1020        assert!(prompt.contains("Communication Pattern"));
1021    }
1022
1023    // ── without_multi_agent ──
1024
1025    #[tokio::test(flavor = "multi_thread")]
1026    async fn test_without_multi_agent_clears_config_and_factory() {
1027        let client = make_client();
1028
1029        // Set up a factory that would panic if called — without_multi_agent should prevent it
1030        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1031            panic!("factory should not be called when multi-agent is cleared");
1032        });
1033
1034        let runtime = AgentBuilder::new(client)
1035            .with_multi_agent(MultiAgentConfig::enabled())
1036            .with_multi_agent_tool_factory(factory)
1037            .without_multi_agent() // clear both
1038            .build()
1039            .unwrap();
1040
1041        let tools = tokio::task::block_in_place(|| {
1042            let tools = runtime.tools_mut();
1043            let guard = tools.blocking_read();
1044            guard
1045                .metadatas()
1046                .into_iter()
1047                .map(|m| m.name)
1048                .collect::<Vec<String>>()
1049        });
1050        assert!(!tools.contains(&"spawn_agent".to_string()));
1051    }
1052
1053    // ── apply_if ──
1054
1055    #[test]
1056    fn test_apply_if_some_applies_transformation() {
1057        let client = make_client();
1058        let builder = AgentBuilder::new(client)
1059            .apply_if(Some("custom prompt"), |b, prompt| b.system_prompt(prompt));
1060        // system_prompt is stored in self.system_prompt; verify it was set
1061        assert!(builder.system_prompt.unwrap().contains("custom prompt"));
1062    }
1063
1064    #[test]
1065    fn test_apply_if_none_passes_through() {
1066        let client = make_client();
1067        let builder = AgentBuilder::new(client).apply_if(None as Option<&str>, |_b, _prompt| {
1068            panic!("should not be called when value is None");
1069        });
1070        assert!(builder.system_prompt.is_none());
1071    }
1072
1073    // ── build_memory_system_prompt ──
1074
1075    #[test]
1076    fn test_build_memory_system_prompt_non_empty() {
1077        let prompt = build_memory_system_prompt();
1078        assert!(!prompt.is_empty());
1079        assert!(prompt.contains("Memory"));
1080        assert!(prompt.contains("MEMORY.md"));
1081        assert!(prompt.contains("read_file"));
1082        assert!(prompt.contains("write_file"));
1083    }
1084}