Skip to main content

agent_works/builder/
mod.rs

1use std::collections::HashSet;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use agent_base::Tool;
6
7#[cfg(feature = "multi_agent")]
8use crate::multi_agent::{MultiAgentConfig, MultiAgentRuntime};
9
10#[cfg(feature = "memory")]
11use crate::memory::MemoryConfig;
12
13#[cfg(feature = "skill")]
14use crate::skill::{Skill, SkillPrompter};
15
16/// Read agent instruction files and build a combined prompt section.
17///
18/// Files are read in order; later entries have higher priority and appear
19/// first in the output. Missing files are silently skipped.
20fn build_agent_instructions_prompt(paths: &[PathBuf]) -> Option<String> {
21    let mut sections = Vec::new();
22
23    for path in paths {
24        if let Ok(content) = std::fs::read_to_string(path) {
25            let trimmed = content.trim();
26            if !trimmed.is_empty() {
27                sections.push(trimmed.to_string());
28            }
29        }
30    }
31
32    if sections.is_empty() {
33        return None;
34    }
35
36    // Later entries (higher priority) appear first
37    sections.reverse();
38    Some(sections.join("\n\n---\n\n"))
39}
40
41/// Factory type for creating multi-agent tools from a MultiAgentRuntime.
42#[cfg(feature = "multi_agent")]
43pub type MultiAgentToolFactory =
44    Arc<dyn Fn(Arc<MultiAgentRuntime>) -> Vec<Arc<dyn Tool>> + Send + Sync>;
45
46/// Factory type for creating a skill detail tool from skills and a tool name.
47#[cfg(feature = "skill")]
48pub type SkillDetailToolFactory =
49    Arc<dyn Fn(Vec<Arc<dyn Skill>>, String) -> Arc<dyn Tool> + Send + Sync>;
50
51/// Factory type for creating a list-skills tool from a SkillRegistry.
52#[cfg(feature = "skill")]
53pub type ListSkillsToolFactory =
54    Arc<dyn Fn(Arc<crate::skill::SkillRegistry>) -> Arc<dyn Tool> + Send + Sync>;
55
56pub struct AgentBuilder {
57    inner: agent_base::AgentBuilder,
58    client: Arc<dyn agent_base::llm_trait::LlmProvider>,
59    system_prompt: Option<String>,
60    tool_names: HashSet<String>,
61    /// Business tools to pass to child agents (all registered tools).
62    business_tools: Vec<Arc<dyn Tool>>,
63    /// Multi-agent configuration (None = disabled).
64    #[cfg(feature = "multi_agent")]
65    multi_agent_config: Option<MultiAgentConfig>,
66    /// Factory to create multi-agent tools (injected by phi-kernel-tools).
67    #[cfg(feature = "multi_agent")]
68    multi_agent_tool_factory: Option<MultiAgentToolFactory>,
69    /// Error recovery (stored for multi-agent child inheritance).
70    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
71    /// Language preference.
72    language: Option<agent_base::Language>,
73    #[cfg(feature = "skill")]
74    skills: Vec<Arc<dyn Skill>>,
75    #[cfg(feature = "skill")]
76    skill_prompter: Option<Arc<dyn SkillPrompter>>,
77    #[cfg(feature = "skill")]
78    skill_detail_tool_name: String,
79    /// Optional: inject a custom skill-detail tool (old tool-based mode).
80    /// In default prompt-injection mode, the LLM reads `SKILL.md` via
81    /// `read_file` — no dedicated detail tool is needed.
82    #[cfg(feature = "skill")]
83    skill_detail_tool_factory: Option<SkillDetailToolFactory>,
84    #[cfg(feature = "skill")]
85    list_skills_tool_factory: Option<ListSkillsToolFactory>,
86    #[cfg(feature = "skill")]
87    disable_skill_prompt_injection: bool,
88    /// Optional inline context compactor for the react loop.
89    context_compactor: Option<Arc<dyn agent_base::ContextCompaction>>,
90    /// Paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
91    /// These files are read at build time and appended to the system prompt.
92    /// Supports multiple paths (user-level + project-level); later entries
93    /// have higher priority and appear first in the prompt.
94    agent_instructions_paths: Vec<PathBuf>,
95    /// Memory configuration (Phase 9b). `None` = memory disabled: no memory
96    /// tools registered, no memory prompt injected (opt-in by design).
97    #[cfg(feature = "memory")]
98    memory_config: Option<MemoryConfig>,
99}
100
101impl AgentBuilder {
102    pub fn new(client: Arc<dyn agent_base::llm_trait::LlmProvider>) -> Self {
103        Self {
104            inner: agent_base::AgentBuilder::new(client.clone()),
105            client,
106            system_prompt: None,
107            tool_names: HashSet::new(),
108            business_tools: Vec::new(),
109            #[cfg(feature = "multi_agent")]
110            multi_agent_config: None,
111            #[cfg(feature = "multi_agent")]
112            multi_agent_tool_factory: None,
113            error_recovery: None,
114            language: None,
115            #[cfg(feature = "skill")]
116            skills: Vec::new(),
117            #[cfg(feature = "skill")]
118            skill_prompter: None,
119            #[cfg(feature = "skill")]
120            skill_detail_tool_name: "get_skill_detail".to_string(),
121            #[cfg(feature = "skill")]
122            skill_detail_tool_factory: None,
123            #[cfg(feature = "skill")]
124            list_skills_tool_factory: None,
125            #[cfg(feature = "skill")]
126            disable_skill_prompt_injection: false,
127            context_compactor: None,
128            agent_instructions_paths: Vec::new(),
129            #[cfg(feature = "memory")]
130            memory_config: None,
131        }
132    }
133
134    /// Enable multi-agent support with the given configuration.
135    ///
136    /// Also sets the tool factory to create the 5 multi-agent tools.
137    /// Callers should use `phi_kernel_tools::multi_agent::create_all_tools` as the factory.
138    #[cfg(feature = "multi_agent")]
139    pub fn with_multi_agent(mut self, config: MultiAgentConfig) -> Self {
140        self.multi_agent_config = Some(config);
141        self
142    }
143
144    /// Disable multi-agent support.
145    ///
146    /// Removes any previously set multi-agent configuration. No multi-agent tools
147    /// will be registered and the system prompt will not mention multi-agent capabilities.
148    #[cfg(feature = "multi_agent")]
149    pub fn without_multi_agent(mut self) -> Self {
150        self.multi_agent_config = None;
151        self.multi_agent_tool_factory = None;
152        self
153    }
154
155    /// Set a custom factory for creating multi-agent tools.
156    ///
157    /// The factory receives the `MultiAgentRuntime` and returns the tools to register.
158    /// If not set but multi-agent is enabled, no tools are registered (caller must
159    /// set this for multi-agent to work).
160    #[cfg(feature = "multi_agent")]
161    pub fn with_multi_agent_tool_factory(mut self, factory: MultiAgentToolFactory) -> Self {
162        self.multi_agent_tool_factory = Some(factory);
163        self
164    }
165
166    /// Set a custom factory for creating the skill detail tool.
167    ///
168    /// The factory receives the skill list and tool name, and returns the tool.
169    /// If not set but skills are registered, no detail tool is added.
170    #[cfg(feature = "skill")]
171    pub fn with_skill_detail_tool_factory(mut self, factory: SkillDetailToolFactory) -> Self {
172        self.skill_detail_tool_factory = Some(factory);
173        self
174    }
175
176    /// Set a custom factory for creating the list-skills tool.
177    ///
178    /// The factory receives the SkillRegistry and returns the tool.
179    #[cfg(feature = "skill")]
180    pub fn with_list_skills_tool_factory(mut self, factory: ListSkillsToolFactory) -> Self {
181        self.list_skills_tool_factory = Some(factory);
182        self
183    }
184
185    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
186        let prompt = prompt.into();
187        self.inner = self.inner.system_prompt(prompt.clone());
188        self.system_prompt = Some(prompt);
189        self
190    }
191
192    pub fn enable_thought(self, enable: bool) -> Self {
193        Self {
194            inner: self.inner.enable_thought(enable),
195            ..self
196        }
197    }
198
199    pub fn reasoning(self, config: agent_base::ReasoningConfig) -> Self {
200        Self {
201            inner: self.inner.reasoning(config),
202            ..self
203        }
204    }
205
206    pub fn enable_thinking(self, enable: bool) -> Self {
207        Self {
208            inner: self.inner.enable_thinking(enable),
209            ..self
210        }
211    }
212
213    pub fn thinking_budget(self, budget: u64) -> Self {
214        Self {
215            inner: self.inner.thinking_budget(budget),
216            ..self
217        }
218    }
219
220    pub fn tool_timeout(self, timeout_ms: u64) -> Self {
221        Self {
222            inner: self.inner.tool_timeout(timeout_ms),
223            ..self
224        }
225    }
226
227    pub fn max_tool_output_chars(self, max_chars: usize) -> Self {
228        Self {
229            inner: self.inner.max_tool_output_chars(max_chars),
230            ..self
231        }
232    }
233
234    pub fn max_sessions(self, max: usize) -> Self {
235        Self {
236            inner: self.inner.max_sessions(max),
237            ..self
238        }
239    }
240
241    pub fn max_turns_per_session(self, max: usize) -> Self {
242        Self {
243            inner: self.inner.max_turns_per_session(max),
244            ..self
245        }
246    }
247
248    pub fn execution_max_turns(self, max: u32) -> Self {
249        Self {
250            inner: self.inner.execution_max_turns(max),
251            ..self
252        }
253    }
254
255    pub fn max_message_tokens(self, max: usize) -> Self {
256        Self {
257            inner: self.inner.max_message_tokens(max),
258            ..self
259        }
260    }
261
262    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
263        let tool_arc: Arc<dyn Tool> = Arc::new(tool);
264        self.tool_names.insert(tool_arc.name().to_string());
265        self.business_tools.push(tool_arc.clone());
266        self.inner = self.inner.register_tool_arc(tool_arc);
267        self
268    }
269
270    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
271        self.tool_names.insert(tool.name().to_string());
272        self.business_tools.push(tool.clone());
273        self.inner = self.inner.register_tool_arc(tool);
274        self
275    }
276
277    pub fn approval_handler(self, handler: Arc<dyn agent_base::ApprovalHandler>) -> Self {
278        Self {
279            inner: self.inner.approval_handler(handler),
280            ..self
281        }
282    }
283
284    pub fn tool_policy(self, policy: Arc<dyn agent_base::ToolPolicy>) -> Self {
285        Self {
286            inner: self.inner.tool_policy(policy),
287            ..self
288        }
289    }
290
291    pub fn middleware(self, mw: impl agent_base::Middleware + 'static) -> Self {
292        Self {
293            inner: self.inner.middleware(mw),
294            ..self
295        }
296    }
297
298    pub fn guard(self, guard: impl agent_base::ReactLoopGuard + 'static) -> Self {
299        Self {
300            inner: self.inner.guard(guard),
301            ..self
302        }
303    }
304
305    /// Mount this runtime's action backend (M3 T10c): text turns route to it,
306    /// tool-envelope turns keep the tool-call backend. One backend per
307    /// runtime — build one runtime per session when the backend holds a
308    /// resident engine (the product's assembly-time choice).
309    pub fn action_backend(self, backend: Box<dyn agent_base::ActionBackend>) -> Self {
310        Self {
311            inner: self.inner.action_backend(backend),
312            ..self
313        }
314    }
315
316    /// The product's interaction surface for the action backend's `ExecCtx`
317    /// (OV-6): consent and ask_user suspend through it. Without one, every
318    /// interaction fails closed — a cell reaching for the human refuses, it
319    /// never hangs or silently allows.
320    pub fn interaction(self, channel: Arc<dyn agent_base::InteractionChannel>) -> Self {
321        Self {
322            inner: self.inner.interaction(channel),
323            ..self
324        }
325    }
326
327    /// Per-interaction deadline for the action backend's suspensions (`None`
328    /// = unbounded human time, the run's cancel token is the only guard).
329    /// Unset = the kernel's default watchdog.
330    pub fn interaction_timeout(self, interact_timeout: Option<std::time::Duration>) -> Self {
331        Self {
332            inner: self.inner.interaction_timeout(interact_timeout),
333            ..self
334        }
335    }
336
337    pub fn context_window(self, max_tokens: usize) -> Self {
338        Self {
339            inner: self.inner.context_window(max_tokens),
340            ..self
341        }
342    }
343
344    pub fn context_window_manager(self, manager: agent_base::ContextWindowManager) -> Self {
345        Self {
346            inner: self.inner.context_window_manager(manager),
347            ..self
348        }
349    }
350
351    pub fn response_format(self, format: agent_base::ResponseFormat) -> Self {
352        Self {
353            inner: self.inner.response_format(format),
354            ..self
355        }
356    }
357
358    pub fn llm_retry(self, retry: agent_base::RetryConfig) -> Self {
359        Self {
360            inner: self.inner.llm_retry(retry),
361            ..self
362        }
363    }
364
365    pub fn session_store(self, store: Arc<dyn agent_base::SessionStore>) -> Self {
366        Self {
367            inner: self.inner.session_store(store),
368            ..self
369        }
370    }
371
372    pub fn error_recovery(mut self, recovery: Arc<dyn agent_base::ToolErrorRecovery>) -> Self {
373        self.error_recovery = Some(recovery.clone());
374        self.inner = self.inner.error_recovery(recovery);
375        self
376    }
377
378    pub fn tool_error_retry_prompt(self, prompt: impl Into<String>) -> Self {
379        Self {
380            inner: self.inner.tool_error_retry_prompt(prompt),
381            ..self
382        }
383    }
384
385    pub fn language(mut self, language: agent_base::Language) -> Self {
386        self.language = Some(language.clone());
387        self.inner = self.inner.language(language);
388        self
389    }
390
391    /// Set an inline context compactor for the react loop.
392    ///
393    /// When set, the react loop will check token count after each tool turn
394    /// and compact the session if it exceeds the configured threshold.
395    pub fn context_compactor(mut self, compactor: Arc<dyn agent_base::ContextCompaction>) -> Self {
396        self.context_compactor = Some(compactor);
397        self
398    }
399
400    pub fn event_bus_capacity(self, capacity: usize) -> Self {
401        Self {
402            inner: self.inner.event_bus_capacity(capacity),
403            ..self
404        }
405    }
406
407    pub fn session_id_generator(
408        self,
409        generator: Arc<dyn agent_base::types::SessionIdGenerator>,
410    ) -> Self {
411        Self {
412            inner: self.inner.session_id_generator(generator),
413            ..self
414        }
415    }
416
417    /// Conditionally apply a transformation when `value` is `Some`.
418    ///
419    /// This is a convenience for option-chaining builder patterns:
420    ///
421    /// ```ignore
422    /// builder.apply_if(args.thinking_budget, |b, budget| b.thinking_budget(budget))
423    /// ```
424    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
425        match value {
426            Some(v) => f(self, v),
427            None => self,
428        }
429    }
430
431    #[cfg(feature = "skill")]
432    pub fn register_skill(mut self, skill: impl Skill + 'static) -> Self {
433        self.skills.push(Arc::new(skill));
434        self
435    }
436
437    #[cfg(feature = "skill")]
438    pub fn register_skills(mut self, skills: Vec<Arc<dyn Skill>>) -> Self {
439        self.skills.extend(skills);
440        self
441    }
442
443    #[cfg(feature = "skill")]
444    pub fn skill_prompter(mut self, prompter: Arc<dyn SkillPrompter>) -> Self {
445        self.skill_prompter = Some(prompter);
446        self
447    }
448
449    #[cfg(feature = "skill")]
450    pub fn disable_skill_prompt_injection(mut self) -> Self {
451        self.disable_skill_prompt_injection = true;
452        self
453    }
454
455    /// Set paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
456    ///
457    /// These files are read at build time and appended to the system prompt.
458    /// Supports multiple paths (user-level + project-level); later entries
459    /// have higher priority and appear first in the prompt.
460    ///
461    /// Example:
462    /// ```rust,ignore
463    /// use std::path::PathBuf;
464    /// use agent_works::AgentBuilder;
465    /// let builder = AgentBuilder::new();
466    /// let builder = builder.agent_instructions_paths(vec![
467    ///     PathBuf::from("~/.claude/CLAUDE.md"),  // user-level
468    ///     PathBuf::from(".claude/CLAUDE.md"),     // project-level
469    /// ]);
470    /// ```
471    pub fn agent_instructions_paths(mut self, paths: Vec<PathBuf>) -> Self {
472        self.agent_instructions_paths = paths;
473        self
474    }
475
476    #[cfg(feature = "skill")]
477    pub fn skill_detail_tool_name(mut self, name: impl Into<String>) -> Self {
478        self.skill_detail_tool_name = name.into();
479        self
480    }
481
482    /// Enable persistent auto-memory (Phase 9b) with the given configuration.
483    ///
484    /// Registers the four `memory_*` tools and appends the memory prompt
485    /// (MEMORY.md index snapshot + tool guidance) to the system prompt at
486    /// build time. Opt-in: without this call no memory tools exist and the
487    /// prompt is untouched.
488    #[cfg(feature = "memory")]
489    pub fn memory_config(mut self, config: MemoryConfig) -> Self {
490        self.memory_config = Some(config);
491        self
492    }
493
494    /// Disable auto-memory (removes any previously set configuration).
495    #[cfg(feature = "memory")]
496    pub fn without_memory_config(mut self) -> Self {
497        self.memory_config = None;
498        self
499    }
500}
501
502mod build;
503mod prompts;
504
505pub use prompts::build_memory_system_prompt;
506#[cfg(feature = "memory")]
507pub use prompts::build_memory_system_prompt_with_config;
508#[cfg(feature = "multi_agent")]
509pub use prompts::{build_multi_agent_system_prompt, setup_multi_agent};
510
511#[cfg(test)]
512mod tests;