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