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    /// Share the session's tool-activation set with the engine. A product that
278    /// registers `ActivateTool` must hand that tool this same set, or openings
279    /// land somewhere the engine never reads.
280    pub fn with_tool_activation(self, activation: agent_base::ToolActivation) -> Self {
281        Self {
282            inner: self.inner.with_tool_activation(activation),
283            ..self
284        }
285    }
286
287    /// Re-wrap a registered tool so it is named in the roster but costs the
288    /// request nothing until the model opens it. Returns the tool's rendered
289    /// definition — what `ActivateTool` serves on open — or `None` when the
290    /// name is not registered.
291    ///
292    /// Deliberately leaves `business_tools` alone: a child agent is not subject
293    /// to its parent's roster, so it keeps the tool as registered.
294    pub fn defer_tool(&mut self, name: &str) -> Option<serde_json::Value> {
295        self.inner.defer_tool(name)
296    }
297
298    pub fn approval_handler(self, handler: Arc<dyn agent_base::ApprovalHandler>) -> Self {
299        Self {
300            inner: self.inner.approval_handler(handler),
301            ..self
302        }
303    }
304
305    pub fn tool_policy(self, policy: Arc<dyn agent_base::ToolPolicy>) -> Self {
306        Self {
307            inner: self.inner.tool_policy(policy),
308            ..self
309        }
310    }
311
312    pub fn middleware(self, mw: impl agent_base::Middleware + 'static) -> Self {
313        Self {
314            inner: self.inner.middleware(mw),
315            ..self
316        }
317    }
318
319    pub fn guard(self, guard: impl agent_base::ReactLoopGuard + 'static) -> Self {
320        Self {
321            inner: self.inner.guard(guard),
322            ..self
323        }
324    }
325
326    /// Mount this runtime's action backend (M3 T10c): text turns route to it,
327    /// tool-envelope turns keep the tool-call backend. One backend per
328    /// runtime — build one runtime per session when the backend holds a
329    /// resident engine (the product's assembly-time choice).
330    pub fn action_backend(self, backend: Box<dyn agent_base::ActionBackend>) -> Self {
331        Self {
332            inner: self.inner.action_backend(backend),
333            ..self
334        }
335    }
336
337    /// The product's interaction surface for the action backend's `ExecCtx`
338    /// (OV-6): consent and ask_user suspend through it. Without one, every
339    /// interaction fails closed — a cell reaching for the human refuses, it
340    /// never hangs or silently allows.
341    pub fn interaction(self, channel: Arc<dyn agent_base::InteractionChannel>) -> Self {
342        Self {
343            inner: self.inner.interaction(channel),
344            ..self
345        }
346    }
347
348    /// Per-interaction deadline for the action backend's suspensions (`None`
349    /// = unbounded human time, the run's cancel token is the only guard).
350    /// Unset = the kernel's default watchdog.
351    pub fn interaction_timeout(self, interact_timeout: Option<std::time::Duration>) -> Self {
352        Self {
353            inner: self.inner.interaction_timeout(interact_timeout),
354            ..self
355        }
356    }
357
358    pub fn context_window(self, max_tokens: usize) -> Self {
359        Self {
360            inner: self.inner.context_window(max_tokens),
361            ..self
362        }
363    }
364
365    pub fn context_window_manager(self, manager: agent_base::ContextWindowManager) -> Self {
366        Self {
367            inner: self.inner.context_window_manager(manager),
368            ..self
369        }
370    }
371
372    pub fn response_format(self, format: agent_base::ResponseFormat) -> Self {
373        Self {
374            inner: self.inner.response_format(format),
375            ..self
376        }
377    }
378
379    pub fn llm_retry(self, retry: agent_base::RetryConfig) -> Self {
380        Self {
381            inner: self.inner.llm_retry(retry),
382            ..self
383        }
384    }
385
386    pub fn session_store(self, store: Arc<dyn agent_base::SessionStore>) -> Self {
387        Self {
388            inner: self.inner.session_store(store),
389            ..self
390        }
391    }
392
393    pub fn error_recovery(mut self, recovery: Arc<dyn agent_base::ToolErrorRecovery>) -> Self {
394        self.error_recovery = Some(recovery.clone());
395        self.inner = self.inner.error_recovery(recovery);
396        self
397    }
398
399    pub fn tool_error_retry_prompt(self, prompt: impl Into<String>) -> Self {
400        Self {
401            inner: self.inner.tool_error_retry_prompt(prompt),
402            ..self
403        }
404    }
405
406    pub fn language(mut self, language: agent_base::Language) -> Self {
407        self.language = Some(language.clone());
408        self.inner = self.inner.language(language);
409        self
410    }
411
412    /// Set an inline context compactor for the react loop.
413    ///
414    /// When set, the react loop will check token count after each tool turn
415    /// and compact the session if it exceeds the configured threshold.
416    pub fn context_compactor(mut self, compactor: Arc<dyn agent_base::ContextCompaction>) -> Self {
417        self.context_compactor = Some(compactor);
418        self
419    }
420
421    pub fn event_bus_capacity(self, capacity: usize) -> Self {
422        Self {
423            inner: self.inner.event_bus_capacity(capacity),
424            ..self
425        }
426    }
427
428    pub fn session_id_generator(
429        self,
430        generator: Arc<dyn agent_base::types::SessionIdGenerator>,
431    ) -> Self {
432        Self {
433            inner: self.inner.session_id_generator(generator),
434            ..self
435        }
436    }
437
438    /// Conditionally apply a transformation when `value` is `Some`.
439    ///
440    /// This is a convenience for option-chaining builder patterns:
441    ///
442    /// ```ignore
443    /// builder.apply_if(args.thinking_budget, |b, budget| b.thinking_budget(budget))
444    /// ```
445    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
446        match value {
447            Some(v) => f(self, v),
448            None => self,
449        }
450    }
451
452    #[cfg(feature = "skill")]
453    pub fn register_skill(mut self, skill: impl Skill + 'static) -> Self {
454        self.skills.push(Arc::new(skill));
455        self
456    }
457
458    #[cfg(feature = "skill")]
459    pub fn register_skills(mut self, skills: Vec<Arc<dyn Skill>>) -> Self {
460        self.skills.extend(skills);
461        self
462    }
463
464    #[cfg(feature = "skill")]
465    pub fn skill_prompter(mut self, prompter: Arc<dyn SkillPrompter>) -> Self {
466        self.skill_prompter = Some(prompter);
467        self
468    }
469
470    #[cfg(feature = "skill")]
471    pub fn disable_skill_prompt_injection(mut self) -> Self {
472        self.disable_skill_prompt_injection = true;
473        self
474    }
475
476    /// Set paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
477    ///
478    /// These files are read at build time and appended to the system prompt.
479    /// Supports multiple paths (user-level + project-level); later entries
480    /// have higher priority and appear first in the prompt.
481    ///
482    /// Example:
483    /// ```rust,ignore
484    /// use std::path::PathBuf;
485    /// use agent_works::AgentBuilder;
486    /// let builder = AgentBuilder::new();
487    /// let builder = builder.agent_instructions_paths(vec![
488    ///     PathBuf::from("~/.claude/CLAUDE.md"),  // user-level
489    ///     PathBuf::from(".claude/CLAUDE.md"),     // project-level
490    /// ]);
491    /// ```
492    pub fn agent_instructions_paths(mut self, paths: Vec<PathBuf>) -> Self {
493        self.agent_instructions_paths = paths;
494        self
495    }
496
497    #[cfg(feature = "skill")]
498    pub fn skill_detail_tool_name(mut self, name: impl Into<String>) -> Self {
499        self.skill_detail_tool_name = name.into();
500        self
501    }
502
503    /// Enable persistent auto-memory (Phase 9b) with the given configuration.
504    ///
505    /// Registers the four `memory_*` tools and appends the memory prompt
506    /// (MEMORY.md index snapshot + tool guidance) to the system prompt at
507    /// build time. Opt-in: without this call no memory tools exist and the
508    /// prompt is untouched.
509    #[cfg(feature = "memory")]
510    pub fn memory_config(mut self, config: MemoryConfig) -> Self {
511        self.memory_config = Some(config);
512        self
513    }
514
515    /// Disable auto-memory (removes any previously set configuration).
516    #[cfg(feature = "memory")]
517    pub fn without_memory_config(mut self) -> Self {
518        self.memory_config = None;
519        self
520    }
521}
522
523mod build;
524mod prompts;
525
526pub use prompts::build_memory_system_prompt;
527#[cfg(feature = "memory")]
528pub use prompts::build_memory_system_prompt_with_config;
529#[cfg(feature = "multi_agent")]
530pub use prompts::{build_multi_agent_system_prompt, setup_multi_agent};
531
532#[cfg(test)]
533mod tests;