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    let tool_policy = runtime.tool_policy().cloned();
543
544    let ma_runtime = Arc::new(MultiAgentRuntime::new(
545        config.clone(),
546        client,
547        business_tools,
548        cancel_token,
549        error_recovery,
550        lang,
551        tool_policy,
552    ));
553
554    // Set parent session manager for fork_history support
555    ma_runtime.set_session_manager(Arc::new(runtime.session_manager().clone()));
556
557    // Set up event bridge: child events → parent event bus
558    let (event_tx, mut event_rx) =
559        tokio::sync::mpsc::unbounded_channel::<agent_base::RuntimeEvent>();
560    ma_runtime.set_event_sender(event_tx);
561    let parent_runtime = runtime.clone();
562    tokio::spawn(async move {
563        while let Some(event) = event_rx.recv().await {
564            parent_runtime.emit_event(event);
565        }
566    });
567
568    // Register multi-agent tools if a factory is provided
569    if let Some(factory) = tool_factory {
570        let tools = factory(ma_runtime.clone());
571        let registry = runtime.tools_mut();
572        let mut reg = tokio::task::block_in_place(|| registry.blocking_write());
573        for tool in tools {
574            let tool_name = tool.name().to_string();
575            if !existing_tool_names.contains(&tool_name) {
576                reg.register_arc(tool);
577            }
578        }
579        drop(reg);
580    }
581
582    Ok(ma_runtime)
583}
584
585/// Build the multi-agent system prompt guidance for the main agent.
586pub fn build_multi_agent_system_prompt() -> String {
587    r#"## Multi-Agent Capabilities
588
589You have the ability to spawn sub-agents to execute tasks concurrently. Use these tools to delegate work:
590
591- `spawn_agent`: Create a new sub-agent with a specific role. The agent runs independently.
592- `send_message`: Send a message to a sub-agent without triggering execution.
593- `followup_task`: Assign a task to a sub-agent and trigger its execution. Returns immediately.
594- `wait_agent`: Wait for a sub-agent's result. Blocks until the agent completes or timeout.
595- `list_agents`: List all active sub-agents and their status.
596- `close_agent`: Close a sub-agent and release its resources.
597
598### When to Spawn
599
600- Tasks that can run independently and in parallel (e.g., "research X and Y simultaneously")
601- Long-running tasks where you want to check intermediate results
602- Decomposing complex tasks into sub-tasks for focused execution
603
604### When NOT to Spawn
605
606- Simple lookups or single-tool calls (just use the tool directly)
607- Sequential dependencies where the next step requires the previous result
608- Tasks that need your full context or reasoning
609
610### Communication Pattern
611
6121. `spawn_agent` → create the sub-agent
6132. `followup_task` → assign work (can call multiple times)
6143. `wait_agent` → collect results
6154. `close_agent` → clean up when done"#
616        .to_string()
617}
618
619/// Build the memory system prompt guidance.
620///
621/// Tells the LLM how to use the file-based persistent memory system.
622/// Memory is stored as markdown files — the LLM uses `read_file` / `write_file`
623/// to manage them, following the same convention as Claude Code Memory.
624///
625/// This is prompt-injection only — no dedicated memory tools are registered.
626/// The LLM uses the general-purpose file tools to read/write memory files.
627pub fn build_memory_system_prompt() -> String {
628    r#"## Memory
629
630You have a persistent file-based memory at `.phi/memory/`. Use `read_file` and `write_file` to manage it — there are no dedicated memory tools.
631
632### How Memory Works
633
634- `MEMORY.md` is the index — it lists all memories with one-line descriptions. Read it first when you need to recall something.
635- Each memory is a separate `.md` file with YAML frontmatter:
636  ```yaml
637  ---
638  name: <short-kebab-case-slug>
639  description: <one-line summary — used to decide relevance during recall>
640  metadata:
641    node_type: memory
642    type: user | feedback | project | reference
643  ---
644
645  <the fact or instruction>
646  ```
647- 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.
648- Link related memories with `[[memory-name]]` in the body.
649- `user` type = who the user is (role, expertise, preferences).
650- `feedback` type = guidance the user has given on how you should work.
651- `project` type = ongoing work, goals, or constraints.
652- `reference` type = pointers to external resources (URLs, dashboards, tickets).
653
654### When to Use Memory
655
656- The user explicitly asks you to remember something ("remember this", "save that")
657- You learn something important about the user's preferences or workflow
658- After completing a significant task, save context that would help in future sessions
659- The user gives you feedback on how to work — save it as `feedback` type
660
661### When NOT to Use Memory
662
663- For transient information that won't be useful beyond this session
664- For facts already recorded in the codebase (code structure, git history, config files)
665- For items that only matter to the current conversation
666
667### Pro Tips
668
669- When creating your first memory of a new type, you can read template files for format reference (check `.phi/templates/memory/` if available).
670- Keep the MEMORY.md index concise — it's loaded into context every session.
671- Before writing a new memory, check if an existing file already covers it — update instead of duplicating.
672
673### Workflow
674
675**To recall:** read `MEMORY.md` → find relevant entries by description → read the specific `.md` files you need.
676**To remember:** create a new `.md` file with proper frontmatter → update `MEMORY.md` with a new entry.
677**To update:** edit the existing `.md` file (don't create a duplicate).
678**To forget:** delete the `.md` file → remove its entry from `MEMORY.md`."#
679        .to_string()
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685    use agent_base::{Content, LlmClient};
686    use std::pin::Pin;
687
688    // ── Stub LLM client ──
689
690    struct StubClient;
691
692    #[async_trait::async_trait]
693    impl LlmClient for StubClient {
694        async fn chat(
695            &self,
696            _messages: &[agent_base::ChatMessage],
697            _tools: &[serde_json::Value],
698            _reasoning: Option<&agent_base::ReasoningConfig>,
699            _response_format: Option<&agent_base::ResponseFormat>,
700        ) -> AgentResult<serde_json::Value> {
701            Ok(serde_json::json!({"choices": [{"message": {"content": "ok"}}]}))
702        }
703
704        async fn chat_stream(
705            &self,
706            _messages: &[agent_base::ChatMessage],
707            _tools: &[serde_json::Value],
708            _reasoning: Option<&agent_base::ReasoningConfig>,
709            _response_format: Option<&agent_base::ResponseFormat>,
710        ) -> AgentResult<
711            Pin<Box<dyn futures_core::Stream<Item = AgentResult<agent_base::StreamChunk>> + Send>>,
712        > {
713            let chunks: Vec<AgentResult<agent_base::StreamChunk>> = vec![
714                Ok(agent_base::StreamChunk::Text("ok".to_string())),
715                Ok(agent_base::StreamChunk::Stop {
716                    finish_reason: Some("stop".to_string()),
717                }),
718            ];
719            Ok(Box::pin(futures_util::stream::iter(chunks)))
720        }
721
722        fn capabilities(&self) -> agent_base::LlmCapabilities {
723            agent_base::LlmCapabilities {
724                supports_streaming: true,
725                supports_tools: true,
726                supports_vision: false,
727                supports_thinking: false,
728                max_context_tokens: None,
729                max_output_tokens: None,
730            }
731        }
732    }
733
734    fn make_client() -> Arc<dyn StreamClient> {
735        agent_base::llm::adapt(Arc::new(StubClient))
736    }
737
738    // ── setup_multi_agent tests ──
739
740    #[tokio::test(flavor = "multi_thread")]
741    async fn test_setup_multi_agent_without_factory_registers_no_tools() {
742        let client = make_client();
743        let runtime = agent_base::AgentBuilder::new(client.clone())
744            .build()
745            .unwrap();
746        let config = MultiAgentConfig::enabled();
747
748        let result = setup_multi_agent(
749            &runtime,
750            config,
751            agent_base::Language::En,
752            vec![],
753            None,
754            &HashSet::new(),
755            None, // no factory
756        );
757        assert!(result.is_ok());
758        let ma_runtime = result.unwrap();
759        // Verify no tools were registered (the 6 multi-agent tools are absent)
760        let agents = ma_runtime.list_agents();
761        assert!(agents.is_empty());
762    }
763
764    #[tokio::test(flavor = "multi_thread")]
765    async fn test_setup_multi_agent_with_factory_registers_tools() {
766        let client = make_client();
767        let runtime = agent_base::AgentBuilder::new(client.clone())
768            .build()
769            .unwrap();
770        let config = MultiAgentConfig::enabled();
771
772        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
773            // Minimal factory returning a single fake tool
774            struct FakeTool;
775            #[async_trait::async_trait]
776            impl Tool for FakeTool {
777                fn name(&self) -> &'static str {
778                    "fake_tool"
779                }
780                fn description(&self) -> &'static str {
781                    ""
782                }
783                fn schema(&self) -> serde_json::Value {
784                    serde_json::json!({})
785                }
786                async fn call(
787                    &self,
788                    _args: &serde_json::Value,
789                    _ctx: &agent_base::ToolContext,
790                ) -> AgentResult<Vec<Content>> {
791                    Ok(vec![Content::text("ok")])
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 description(&self) -> &'static str {
832                ""
833            }
834            fn schema(&self) -> serde_json::Value {
835                serde_json::json!({})
836            }
837            async fn call(
838                &self,
839                _args: &serde_json::Value,
840                _ctx: &agent_base::ToolContext,
841            ) -> AgentResult<Vec<Content>> {
842                Ok(vec![Content::text("ok")])
843            }
844        }
845        {
846            let tools = runtime.tools_mut();
847            let mut reg = tokio::task::block_in_place(|| tools.blocking_write());
848            reg.register(DupTool);
849        }
850
851        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
852            struct FakeTool;
853            #[async_trait::async_trait]
854            impl Tool for FakeTool {
855                fn name(&self) -> &'static str {
856                    "dup_tool"
857                }
858                fn description(&self) -> &'static str {
859                    ""
860                }
861                fn schema(&self) -> serde_json::Value {
862                    serde_json::json!({})
863                }
864                async fn call(
865                    &self,
866                    _args: &serde_json::Value,
867                    _ctx: &agent_base::ToolContext,
868                ) -> AgentResult<Vec<Content>> {
869                    Ok(vec![Content::text("ok")])
870                }
871            }
872            vec![Arc::new(FakeTool)]
873        });
874
875        let mut existing = HashSet::new();
876        existing.insert("dup_tool".to_string());
877
878        let result = setup_multi_agent(
879            &runtime,
880            MultiAgentConfig::enabled(),
881            agent_base::Language::En,
882            vec![],
883            None,
884            &existing,
885            Some(factory),
886        );
887        assert!(result.is_ok());
888        // dup_tool should NOT have been registered twice
889        let tools = tokio::task::block_in_place(|| {
890            let tools = runtime.tools_mut();
891            let guard = tools.blocking_read();
892            guard
893                .metadatas()
894                .into_iter()
895                .map(|m| m.name)
896                .collect::<Vec<String>>()
897        });
898        let count = tools.iter().filter(|n| n.as_str() == "dup_tool").count();
899        assert_eq!(count, 1);
900    }
901
902    // ── AgentBuilder factory methods ──
903
904    #[tokio::test(flavor = "multi_thread")]
905    async fn test_builder_with_multi_agent_without_factory_builds_ok() {
906        let client = make_client();
907        let runtime = AgentBuilder::new(client)
908            .with_multi_agent(MultiAgentConfig::enabled())
909            .build()
910            .unwrap();
911        // Should succeed even without a factory (no tools registered)
912        let tools = tokio::task::block_in_place(|| {
913            let tools = runtime.tools_mut();
914            let guard = tools.blocking_read();
915            guard
916                .metadatas()
917                .into_iter()
918                .map(|m| m.name)
919                .collect::<Vec<String>>()
920        });
921        // No multi-agent tools registered
922        assert!(!tools.contains(&"spawn_agent".to_string()));
923    }
924
925    #[tokio::test(flavor = "multi_thread")]
926    async fn test_builder_with_factory_registers_tools() {
927        let client = make_client();
928        // Create a simple factory that registers one recognizable tool
929        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
930            struct TestTool;
931            #[async_trait::async_trait]
932            impl Tool for TestTool {
933                fn name(&self) -> &'static str {
934                    "factory_test_tool"
935                }
936                fn description(&self) -> &'static str {
937                    ""
938                }
939                fn schema(&self) -> serde_json::Value {
940                    serde_json::json!({})
941                }
942                async fn call(
943                    &self,
944                    _args: &serde_json::Value,
945                    _ctx: &agent_base::ToolContext,
946                ) -> AgentResult<Vec<Content>> {
947                    Ok(vec![Content::text("ok")])
948                }
949            }
950            vec![Arc::new(TestTool)]
951        });
952
953        let runtime = AgentBuilder::new(client)
954            .with_multi_agent(MultiAgentConfig::enabled())
955            .with_multi_agent_tool_factory(factory)
956            .build()
957            .unwrap();
958
959        let tools = tokio::task::block_in_place(|| {
960            let tools = runtime.tools_mut();
961            let guard = tools.blocking_read();
962            guard
963                .metadatas()
964                .into_iter()
965                .map(|m| m.name)
966                .collect::<Vec<String>>()
967        });
968        assert!(tools.contains(&"factory_test_tool".to_string()));
969    }
970
971    #[test]
972    fn test_builder_disabled_multi_agent_skips_factory() {
973        let client = make_client();
974        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
975            panic!("factory should not be called when multi-agent is not configured");
976        });
977
978        let runtime = AgentBuilder::new(client)
979            .with_multi_agent_tool_factory(factory)
980            // Don't enable multi-agent — default (None) means disabled
981            .build()
982            .unwrap();
983
984        let tools = tokio::task::block_in_place(|| {
985            let tools = runtime.tools_mut();
986            let guard = tools.blocking_read();
987            guard
988                .metadatas()
989                .into_iter()
990                .map(|m| m.name)
991                .collect::<Vec<String>>()
992        });
993        assert!(!tools.contains(&"spawn_agent".to_string()));
994    }
995
996    // ── build_multi_agent_system_prompt ──
997
998    #[test]
999    fn test_system_prompt_contains_tool_names() {
1000        let prompt = build_multi_agent_system_prompt();
1001        assert!(prompt.contains("spawn_agent"));
1002        assert!(prompt.contains("send_message"));
1003        assert!(prompt.contains("followup_task"));
1004        assert!(prompt.contains("wait_agent"));
1005        assert!(prompt.contains("list_agents"));
1006        assert!(prompt.contains("close_agent"));
1007    }
1008
1009    #[test]
1010    fn test_system_prompt_contains_guidance() {
1011        let prompt = build_multi_agent_system_prompt();
1012        assert!(prompt.contains("When to Spawn"));
1013        assert!(prompt.contains("When NOT to Spawn"));
1014        assert!(prompt.contains("Communication Pattern"));
1015    }
1016
1017    // ── without_multi_agent ──
1018
1019    #[tokio::test(flavor = "multi_thread")]
1020    async fn test_without_multi_agent_clears_config_and_factory() {
1021        let client = make_client();
1022
1023        // Set up a factory that would panic if called — without_multi_agent should prevent it
1024        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1025            panic!("factory should not be called when multi-agent is cleared");
1026        });
1027
1028        let runtime = AgentBuilder::new(client)
1029            .with_multi_agent(MultiAgentConfig::enabled())
1030            .with_multi_agent_tool_factory(factory)
1031            .without_multi_agent() // clear both
1032            .build()
1033            .unwrap();
1034
1035        let tools = tokio::task::block_in_place(|| {
1036            let tools = runtime.tools_mut();
1037            let guard = tools.blocking_read();
1038            guard
1039                .metadatas()
1040                .into_iter()
1041                .map(|m| m.name)
1042                .collect::<Vec<String>>()
1043        });
1044        assert!(!tools.contains(&"spawn_agent".to_string()));
1045    }
1046
1047    // ── apply_if ──
1048
1049    #[test]
1050    fn test_apply_if_some_applies_transformation() {
1051        let client = make_client();
1052        let builder = AgentBuilder::new(client)
1053            .apply_if(Some("custom prompt"), |b, prompt| b.system_prompt(prompt));
1054        // system_prompt is stored in self.system_prompt; verify it was set
1055        assert!(builder.system_prompt.unwrap().contains("custom prompt"));
1056    }
1057
1058    #[test]
1059    fn test_apply_if_none_passes_through() {
1060        let client = make_client();
1061        let builder = AgentBuilder::new(client).apply_if(None as Option<&str>, |_b, _prompt| {
1062            panic!("should not be called when value is None");
1063        });
1064        assert!(builder.system_prompt.is_none());
1065    }
1066
1067    // ── build_memory_system_prompt ──
1068
1069    #[test]
1070    fn test_build_memory_system_prompt_non_empty() {
1071        let prompt = build_memory_system_prompt();
1072        assert!(!prompt.is_empty());
1073        assert!(prompt.contains("Memory"));
1074        assert!(prompt.contains("MEMORY.md"));
1075        assert!(prompt.contains("read_file"));
1076        assert!(prompt.contains("write_file"));
1077    }
1078
1079    // ── Named tool for register_tool / skill tests ──
1080
1081    struct NamedTool(&'static str);
1082
1083    #[async_trait::async_trait]
1084    impl Tool for NamedTool {
1085        fn name(&self) -> &'static str {
1086            self.0
1087        }
1088
1089        fn description(&self) -> &'static str {
1090            ""
1091        }
1092
1093        fn schema(&self) -> serde_json::Value {
1094            serde_json::json!({})
1095        }
1096
1097        async fn call(
1098            &self,
1099            _args: &serde_json::Value,
1100            _ctx: &agent_base::ToolContext,
1101        ) -> AgentResult<Vec<Content>> {
1102            Ok(vec![Content::text("ok")])
1103        }
1104    }
1105
1106    fn runtime_tool_names(runtime: &AgentRuntime) -> Vec<String> {
1107        tokio::task::block_in_place(|| {
1108            let tools = runtime.tools_mut();
1109            let guard = tools.blocking_read();
1110            guard.metadatas().into_iter().map(|m| m.name).collect()
1111        })
1112    }
1113
1114    #[tokio::test(flavor = "multi_thread")]
1115    async fn test_builder_scalar_passthrough_methods() {
1116        let client = make_client();
1117        let runtime = AgentBuilder::new(client)
1118            .enable_thought(true)
1119            .reasoning(agent_base::ReasoningConfig::default())
1120            .enable_thinking(false)
1121            .thinking_budget(1000)
1122            .tool_timeout(5000)
1123            .max_tool_output_chars(4000)
1124            .max_sessions(16)
1125            .max_turns_per_session(20)
1126            .execution_max_turns(10)
1127            .max_message_tokens(8000)
1128            .context_window(64_000)
1129            .context_window_manager(agent_base::ContextWindowManager::new(64_000))
1130            .response_format(agent_base::ResponseFormat::JsonObject)
1131            .llm_retry(agent_base::RetryConfig::default())
1132            .tool_error_retry_prompt("please retry")
1133            .language(agent_base::Language::En)
1134            .event_bus_capacity(256)
1135            .build()
1136            .unwrap();
1137
1138        assert!(runtime.client().capabilities().supports_streaming);
1139    }
1140
1141    #[tokio::test(flavor = "multi_thread")]
1142    async fn test_register_tool_variants() {
1143        let client = make_client();
1144        let runtime = AgentBuilder::new(client)
1145            .register_tool(NamedTool("tool_by_value"))
1146            .register_tool_arc(Arc::new(NamedTool("tool_by_arc")))
1147            .build()
1148            .unwrap();
1149
1150        let names = runtime_tool_names(&runtime);
1151        assert!(names.contains(&"tool_by_value".to_string()));
1152        assert!(names.contains(&"tool_by_arc".to_string()));
1153    }
1154
1155    #[cfg(feature = "skill")]
1156    mod skill_tests {
1157        use super::*;
1158        use crate::skill::Skill;
1159
1160        struct TestSkill;
1161
1162        impl Skill for TestSkill {
1163            fn name(&self) -> &'static str {
1164                "test_skill"
1165            }
1166
1167            fn brief_description(&self) -> String {
1168                "a test skill".to_string()
1169            }
1170
1171            fn detailed_description(&self) -> String {
1172                "detailed test skill".to_string()
1173            }
1174
1175            fn tools(&self) -> Vec<Arc<dyn Tool>> {
1176                vec![]
1177            }
1178        }
1179
1180        struct ToolSkill;
1181
1182        impl Skill for ToolSkill {
1183            fn name(&self) -> &'static str {
1184                "tool_skill"
1185            }
1186
1187            fn brief_description(&self) -> String {
1188                "skill with a tool".to_string()
1189            }
1190
1191            fn detailed_description(&self) -> String {
1192                "skill that provides a tool".to_string()
1193            }
1194
1195            fn tools(&self) -> Vec<Arc<dyn Tool>> {
1196                vec![Arc::new(NamedTool("skill_provided_tool"))]
1197            }
1198        }
1199
1200        #[tokio::test(flavor = "multi_thread")]
1201        async fn test_register_skill_builds_ok() {
1202            let client = make_client();
1203            let runtime = AgentBuilder::new(client)
1204                .register_skill(TestSkill)
1205                .build()
1206                .unwrap();
1207            // Prompt injection is applied during build; no tools provided.
1208            assert!(runtime_tool_names(&runtime).is_empty());
1209        }
1210
1211        #[tokio::test(flavor = "multi_thread")]
1212        async fn test_register_skill_with_tool_registers_tool() {
1213            let client = make_client();
1214            let runtime = AgentBuilder::new(client)
1215                .register_skill(ToolSkill)
1216                .build()
1217                .unwrap();
1218            assert!(runtime_tool_names(&runtime).contains(&"skill_provided_tool".to_string()));
1219        }
1220
1221        #[tokio::test(flavor = "multi_thread")]
1222        async fn test_register_skill_tool_name_conflict() {
1223            let client = make_client();
1224            let result = AgentBuilder::new(client)
1225                .register_tool(NamedTool("skill_provided_tool"))
1226                .register_skill(ToolSkill)
1227                .build();
1228            let err = result.err().unwrap();
1229            assert!(format!("{err}").contains("Tool name conflict"));
1230        }
1231
1232        #[tokio::test(flavor = "multi_thread")]
1233        async fn test_skill_detail_tool_factory_registers_tool() {
1234            let client = make_client();
1235            let factory: SkillDetailToolFactory = Arc::new(|_skills, name| {
1236                assert_eq!(name, "get_skill_detail");
1237                Arc::new(NamedTool("detail_tool"))
1238            });
1239            let runtime = AgentBuilder::new(client)
1240                .register_skill(TestSkill)
1241                .with_skill_detail_tool_factory(factory)
1242                .build()
1243                .unwrap();
1244            assert!(runtime_tool_names(&runtime).contains(&"detail_tool".to_string()));
1245        }
1246
1247        #[tokio::test(flavor = "multi_thread")]
1248        async fn test_list_skills_tool_factory_registers_tool() {
1249            let client = make_client();
1250            let factory: ListSkillsToolFactory =
1251                Arc::new(|_registry| Arc::new(NamedTool("list_skills_tool")));
1252            let runtime = AgentBuilder::new(client)
1253                .register_skill(TestSkill)
1254                .with_list_skills_tool_factory(factory)
1255                .build()
1256                .unwrap();
1257            assert!(runtime_tool_names(&runtime).contains(&"list_skills_tool".to_string()));
1258        }
1259
1260        #[tokio::test(flavor = "multi_thread")]
1261        async fn test_disable_skill_prompt_injection_builds() {
1262            let client = make_client();
1263            let runtime = AgentBuilder::new(client)
1264                .register_skill(ToolSkill)
1265                .disable_skill_prompt_injection()
1266                .build()
1267                .unwrap();
1268            // Tool still registered; prompt injection skipped.
1269            assert!(runtime_tool_names(&runtime).contains(&"skill_provided_tool".to_string()));
1270        }
1271    }
1272}