Skip to main content

agent_works/builder/
build.rs

1// `Arc` is needed by every path that hands out a shared runtime, registry or
2// prompter: the memory store, the skill registry/prompter, and the
3// multi-agent runtime. Gate on all three, not on a subset — a feature set
4// with `multi_agent` alone must still compile.
5#[cfg(any(feature = "memory", feature = "skill", feature = "multi_agent"))]
6use std::sync::Arc;
7
8use agent_base::{AgentResult, AgentRuntime};
9
10use super::AgentBuilder;
11use super::build_agent_instructions_prompt;
12#[cfg(feature = "memory")]
13use super::build_memory_system_prompt_with_config;
14#[cfg(feature = "multi_agent")]
15use super::build_multi_agent_system_prompt;
16#[cfg(feature = "multi_agent")]
17use super::setup_multi_agent;
18
19#[cfg(feature = "memory")]
20use crate::memory::MemoryStore;
21#[cfg(feature = "multi_agent")]
22use crate::multi_agent::MultiAgentRuntime;
23#[cfg(feature = "skill")]
24use crate::skill::{LazySkillPrompter, Skill, SkillPrompter};
25
26impl AgentBuilder {
27    /// Register the four memory tools and append the memory prompt (index
28    /// snapshot + tool guidance) to the system prompt. No-op when no memory
29    /// configuration was set. Called from every `build_*` path right after
30    /// the agent-instructions (CLAUDE.md) injection.
31    #[cfg(feature = "memory")]
32    fn apply_memory_config(mut self) -> Self {
33        let Some(config) = self.memory_config.take() else {
34            return self;
35        };
36
37        let store = Arc::new(MemoryStore::new(
38            config.memory_root.clone(),
39            config.index_filename.clone(),
40        ));
41
42        // Register the memory tools unless the consumer already took the name.
43        for tool in crate::tools::create_memory_tools(Arc::clone(&store)) {
44            let tool_name = tool.name().to_string();
45            if self.tool_names.contains(&tool_name) {
46                tracing::warn!(tool = %tool_name, "memory tool name conflict; skipping registration");
47                continue;
48            }
49            self.tool_names.insert(tool_name);
50            self.inner = self.inner.register_tool_arc(tool);
51        }
52
53        // Inject the index snapshot + tool guidance into the system prompt.
54        let index = store.read_index();
55        if index.len() > 10_240 {
56            tracing::warn!(
57                index_bytes = index.len(),
58                root = %config.memory_root.display(),
59                "memory index is unusually large (>10KB); consider cleaning up stale memories"
60            );
61        }
62        let mem_prompt = build_memory_system_prompt_with_config(&config, &index);
63        tracing::info!(
64            memory_root = %config.memory_root.display(),
65            index_bytes = index.len(),
66            tools = 4,
67            "injecting memory prompt + tools into system prompt"
68        );
69        let new_prompt = match self.system_prompt.take() {
70            Some(existing) => format!("{existing}\n\n---\n\n{mem_prompt}"),
71            None => mem_prompt,
72        };
73        tracing::info!(
74            prompt_len = new_prompt.len(),
75            "system prompt after memory injection (full text logged at DEBUG level)"
76        );
77        tracing::debug!(system_prompt = %new_prompt, "full system prompt after memory injection");
78        self.system_prompt = Some(new_prompt.clone());
79        self.inner = self.inner.system_prompt(new_prompt);
80        self
81    }
82
83    // ── Build ──
84
85    pub fn build(self) -> AgentResult<AgentRuntime> {
86        #[cfg(feature = "skill")]
87        {
88            self.build_with_skills()
89        }
90        #[cfg(not(feature = "skill"))]
91        {
92            self.build_inner()
93        }
94    }
95
96    /// Build the runtime and return the multi-agent runtime (if enabled).
97    ///
98    /// Same as [`build`](Self::build) but also returns the `MultiAgentRuntime`
99    /// created during setup. Callers that need to start the watcher task or
100    /// access the mailbox should use this method.
101    #[cfg(feature = "multi_agent")]
102    pub fn build_with_ma(self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
103        #[cfg(feature = "skill")]
104        {
105            self.build_with_skills_ma()
106        }
107        #[cfg(not(feature = "skill"))]
108        {
109            self.build_inner_ma()
110        }
111    }
112
113    #[allow(dead_code, unused_mut)]
114    fn build_inner(mut self) -> AgentResult<AgentRuntime> {
115        // Inject default guard if none was set by the consumer.
116        // Uses the same LLM client for the judge (enabled by default).
117        if self.inner.get_guard().is_none() {
118            self.inner = self
119                .inner
120                .guard(crate::guard::DefaultGuard::with_llm_client(
121                    crate::guard::DefaultGuardConfig::default(),
122                    self.client.clone(),
123                ));
124        }
125
126        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
127        if !self.agent_instructions_paths.is_empty()
128            && let Some(instructions) =
129                build_agent_instructions_prompt(&self.agent_instructions_paths)
130        {
131            tracing::info!(
132                paths = ?self.agent_instructions_paths,
133                instructions_len = instructions.len(),
134                "injecting agent instructions into system prompt"
135            );
136            let new_prompt = match self.system_prompt.take() {
137                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
138                None => instructions,
139            };
140            self.system_prompt = Some(new_prompt.clone());
141            self.inner = self.inner.system_prompt(new_prompt);
142        }
143
144        // Register memory tools + inject memory prompt (Phase 9b)
145        #[cfg(feature = "memory")]
146        {
147            self = self.apply_memory_config();
148        }
149
150        #[cfg(feature = "multi_agent")]
151        let lang = self.language.clone().unwrap_or_default();
152        #[cfg(feature = "multi_agent")]
153        let business_tools = std::mem::take(&mut self.business_tools);
154        #[cfg(feature = "multi_agent")]
155        let error_recovery = self.error_recovery.clone();
156        #[cfg(feature = "multi_agent")]
157        let tool_names = self.tool_names.clone();
158
159        #[cfg(feature = "multi_agent")]
160        let ma_config = self.multi_agent_config.clone();
161        #[cfg(feature = "multi_agent")]
162        let ma_tool_factory = self.multi_agent_tool_factory.take();
163
164        // Inject multi-agent prompt before build
165        #[cfg(feature = "multi_agent")]
166        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
167            let ma_prompt = build_multi_agent_system_prompt();
168            let new_prompt = match self.system_prompt.take() {
169                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
170                None => ma_prompt,
171            };
172            self.inner = self.inner.system_prompt(new_prompt);
173        }
174
175        // Inject inline context compactor if set
176        if let Some(compactor) = self.context_compactor.take() {
177            self.inner = self.inner.context_compactor(compactor);
178        }
179
180        let runtime = self.inner.build()?;
181
182        // Post-build: register multi-agent tools if enabled and factory is set
183        #[cfg(feature = "multi_agent")]
184        if let Some(config) = ma_config
185            && config.enabled
186        {
187            setup_multi_agent(
188                &runtime,
189                config,
190                lang,
191                business_tools,
192                error_recovery,
193                &tool_names,
194                ma_tool_factory,
195            )?;
196        }
197
198        Ok(runtime)
199    }
200
201    /// Like `build_inner` but also returns the `MultiAgentRuntime`.
202    #[cfg(feature = "multi_agent")]
203    #[allow(dead_code, unused_mut)]
204    fn build_inner_ma(mut self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
205        if self.inner.get_guard().is_none() {
206            self.inner = self
207                .inner
208                .guard(crate::guard::DefaultGuard::with_llm_client(
209                    crate::guard::DefaultGuardConfig::default(),
210                    self.client.clone(),
211                ));
212        }
213
214        // Register memory tools + inject memory prompt (Phase 9b)
215        #[cfg(feature = "memory")]
216        {
217            self = self.apply_memory_config();
218        }
219
220        let lang = self.language.clone().unwrap_or_default();
221        let business_tools = std::mem::take(&mut self.business_tools);
222        let error_recovery = self.error_recovery.clone();
223        let tool_names = self.tool_names.clone();
224        let ma_config = self.multi_agent_config.clone();
225        let ma_tool_factory = self.multi_agent_tool_factory.take();
226
227        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
228            let ma_prompt = build_multi_agent_system_prompt();
229            let new_prompt = match self.system_prompt.take() {
230                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
231                None => ma_prompt,
232            };
233            self.inner = self.inner.system_prompt(new_prompt);
234        }
235
236        if let Some(compactor) = self.context_compactor.take() {
237            self.inner = self.inner.context_compactor(compactor);
238        }
239
240        let runtime = self.inner.build()?;
241
242        let ma_runtime_out = if let Some(config) = ma_config
243            && config.enabled
244        {
245            Some(setup_multi_agent(
246                &runtime,
247                config,
248                lang,
249                business_tools,
250                error_recovery,
251                &tool_names,
252                ma_tool_factory,
253            )?)
254        } else {
255            None
256        };
257
258        Ok((runtime, ma_runtime_out))
259    }
260
261    /// Build the runtime with skill support.
262    ///
263    /// # Runtime requirement
264    ///
265    /// This method uses [`tokio::task::block_in_place`] to populate the skill
266    /// registry from a synchronous context. It **requires** a multi-threaded
267    /// tokio runtime. Calling it on a `#[tokio::main]` single-threaded
268    /// (`current_thread`) runtime will panic.
269    ///
270    /// The phi-agent CLI and all examples use the default multi-threaded runtime,
271    /// so this is safe in practice.
272    #[cfg(feature = "skill")]
273    fn build_with_skills(mut self) -> AgentResult<AgentRuntime> {
274        // Inject default guard if none was set by the consumer.
275        // Uses the same LLM client for the judge (enabled by default).
276        if self.inner.get_guard().is_none() {
277            self.inner = self
278                .inner
279                .guard(crate::guard::DefaultGuard::with_llm_client(
280                    crate::guard::DefaultGuardConfig::default(),
281                    self.client.clone(),
282                ));
283        }
284
285        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
286        if !self.agent_instructions_paths.is_empty()
287            && let Some(instructions) =
288                build_agent_instructions_prompt(&self.agent_instructions_paths)
289        {
290            tracing::info!(
291                paths = ?self.agent_instructions_paths,
292                instructions_len = instructions.len(),
293                "injecting agent instructions into system prompt"
294            );
295            let new_prompt = match self.system_prompt.take() {
296                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
297                None => instructions,
298            };
299            self.system_prompt = Some(new_prompt.clone());
300            self.inner = self.inner.system_prompt(new_prompt);
301        }
302
303        // Register memory tools + inject memory prompt (Phase 9b)
304        #[cfg(feature = "memory")]
305        {
306            self = self.apply_memory_config();
307        }
308
309        let mut ab = self.inner;
310        #[cfg(feature = "multi_agent")]
311        let lang = self.language.clone().unwrap_or_default();
312        #[cfg(feature = "multi_agent")]
313        let business_tools = std::mem::take(&mut self.business_tools);
314        #[cfg(feature = "multi_agent")]
315        let error_recovery = self.error_recovery.clone();
316        #[cfg(feature = "multi_agent")]
317        let tool_names = self.tool_names.clone();
318
319        #[cfg(feature = "multi_agent")]
320        let ma_config = self.multi_agent_config.clone();
321        #[cfg(feature = "multi_agent")]
322        let ma_tool_factory = self.multi_agent_tool_factory.take();
323
324        // Process skills
325        if !self.skills.is_empty() {
326            let prompter: Arc<dyn SkillPrompter> = self
327                .skill_prompter
328                .take()
329                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));
330
331            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();
332
333            for skill in self.skills {
334                for tool in skill.tools() {
335                    let tool_name = tool.name().to_string();
336                    if self.tool_names.contains(&tool_name) {
337                        return Err(agent_base::AgentError::internal(format!(
338                            "Tool name conflict: `{}` (Skill `{}`)",
339                            tool_name,
340                            skill.name()
341                        )));
342                    }
343                    self.tool_names.insert(tool_name);
344                    ab = ab.register_tool_arc(tool);
345                }
346                skill_refs.push(skill);
347            }
348
349            if !self.disable_skill_prompt_injection {
350                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
351                if !skill_prompt.is_empty() {
352                    let new_prompt = match self.system_prompt.take() {
353                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
354                        None => skill_prompt,
355                    };
356                    self.system_prompt = Some(new_prompt.clone());
357                    ab = ab.system_prompt(new_prompt);
358                }
359            }
360
361            // Use injected factory if available, otherwise skip — prompt-injection
362            // mode uses read_file instead of a dedicated detail tool.
363            if let Some(factory) = self.skill_detail_tool_factory.take() {
364                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
365                ab = ab.register_tool_arc(detail_tool);
366            }
367
368            // Create SkillRegistry and populate it for the list-skills tool
369            if let Some(factory) = self.list_skills_tool_factory.take() {
370                let registry = Arc::new(crate::skill::SkillRegistry::new());
371                for skill in &skill_refs {
372                    tokio::task::block_in_place(|| {
373                        tokio::runtime::Handle::current().block_on(async {
374                            registry.register(skill.clone()).await;
375                        })
376                    });
377                }
378                let list_tool = factory(registry);
379                ab = ab.register_tool_arc(list_tool);
380            }
381        }
382
383        // Inject multi-agent prompt
384        #[cfg(feature = "multi_agent")]
385        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
386            let ma_prompt = build_multi_agent_system_prompt();
387            let new_prompt = match self.system_prompt.take() {
388                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
389                None => ma_prompt,
390            };
391            ab = ab.system_prompt(new_prompt);
392        }
393
394        // Inject inline context compactor if set
395        if let Some(compactor) = self.context_compactor.take() {
396            ab = ab.context_compactor(compactor);
397        }
398
399        let runtime = ab.build()?;
400
401        // Post-build: register multi-agent tools
402        #[cfg(feature = "multi_agent")]
403        if let Some(config) = ma_config
404            && config.enabled
405        {
406            setup_multi_agent(
407                &runtime,
408                config,
409                lang,
410                business_tools,
411                error_recovery,
412                &tool_names,
413                ma_tool_factory,
414            )?;
415        }
416
417        Ok(runtime)
418    }
419
420    /// Like `build_with_skills` but also returns the `MultiAgentRuntime`.
421    #[cfg(all(feature = "skill", feature = "multi_agent"))]
422    fn build_with_skills_ma(
423        mut self,
424    ) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
425        if self.inner.get_guard().is_none() {
426            self.inner = self
427                .inner
428                .guard(crate::guard::DefaultGuard::with_llm_client(
429                    crate::guard::DefaultGuardConfig::default(),
430                    self.client.clone(),
431                ));
432        }
433
434        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
435        if !self.agent_instructions_paths.is_empty()
436            && let Some(instructions) =
437                build_agent_instructions_prompt(&self.agent_instructions_paths)
438        {
439            tracing::info!(
440                paths = ?self.agent_instructions_paths,
441                instructions_len = instructions.len(),
442                "injecting agent instructions into system prompt"
443            );
444            let new_prompt = match self.system_prompt.take() {
445                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
446                None => instructions,
447            };
448            self.system_prompt = Some(new_prompt.clone());
449            self.inner = self.inner.system_prompt(new_prompt);
450        }
451
452        // Register memory tools + inject memory prompt (Phase 9b)
453        #[cfg(feature = "memory")]
454        {
455            self = self.apply_memory_config();
456        }
457
458        let mut ab = self.inner;
459        let lang = self.language.clone().unwrap_or_default();
460        let business_tools = std::mem::take(&mut self.business_tools);
461        let error_recovery = self.error_recovery.clone();
462        let tool_names = self.tool_names.clone();
463        let ma_config = self.multi_agent_config.clone();
464        let ma_tool_factory = self.multi_agent_tool_factory.take();
465
466        // Process skills
467        if !self.skills.is_empty() {
468            let prompter: Arc<dyn SkillPrompter> = self
469                .skill_prompter
470                .take()
471                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));
472
473            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();
474
475            for skill in self.skills {
476                for tool in skill.tools() {
477                    let tool_name = tool.name().to_string();
478                    if self.tool_names.contains(&tool_name) {
479                        return Err(agent_base::AgentError::internal(format!(
480                            "Tool name conflict: `{}` (Skill `{}`)",
481                            tool_name,
482                            skill.name()
483                        )));
484                    }
485                    self.tool_names.insert(tool_name);
486                    ab = ab.register_tool_arc(tool);
487                }
488                skill_refs.push(skill);
489            }
490
491            if !self.disable_skill_prompt_injection {
492                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
493                if !skill_prompt.is_empty() {
494                    let new_prompt = match self.system_prompt.take() {
495                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
496                        None => skill_prompt,
497                    };
498                    self.system_prompt = Some(new_prompt.clone());
499                    ab = ab.system_prompt(new_prompt);
500                }
501            }
502
503            if let Some(factory) = self.skill_detail_tool_factory.take() {
504                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
505                ab = ab.register_tool_arc(detail_tool);
506            }
507
508            if let Some(factory) = self.list_skills_tool_factory.take() {
509                let registry = Arc::new(crate::skill::SkillRegistry::new());
510                for skill in &skill_refs {
511                    tokio::task::block_in_place(|| {
512                        tokio::runtime::Handle::current().block_on(async {
513                            registry.register(skill.clone()).await;
514                        })
515                    });
516                }
517                let list_tool = factory(registry);
518                ab = ab.register_tool_arc(list_tool);
519            }
520        }
521
522        // Inject multi-agent prompt
523        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
524            let ma_prompt = build_multi_agent_system_prompt();
525            let new_prompt = match self.system_prompt.take() {
526                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
527                None => ma_prompt,
528            };
529            ab = ab.system_prompt(new_prompt);
530        }
531
532        if let Some(compactor) = self.context_compactor.take() {
533            ab = ab.context_compactor(compactor);
534        }
535
536        let runtime = ab.build()?;
537
538        let ma_runtime_out = if let Some(config) = ma_config
539            && config.enabled
540        {
541            Some(setup_multi_agent(
542                &runtime,
543                config,
544                lang,
545                business_tools,
546                error_recovery,
547                &tool_names,
548                ma_tool_factory,
549            )?)
550        } else {
551            None
552        };
553
554        Ok((runtime, ma_runtime_out))
555    }
556}