Skip to main content

phi_agent/agent/
builder.rs

1//! General-purpose AgentBuilder factory — provides default configuration
2//! shared across consumers.
3//!
4//! Returns a pre-configured [`agent_works::AgentBuilder`]; callers then register
5//! tools and approval handlers on top.
6
7#[cfg(any(feature = "file", feature = "skill"))]
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use agent_base::{ConsecutiveFailureRecovery, Language, ReasoningConfig, ReasoningEffort, UpdatePlanTool};
12
13#[cfg(feature = "compression")]
14use agent_works::compression::{CompressionConfig, CompressionMiddleware, ContextCompactor};
15
16/// Module-level compactor handle, set once by `base_agent_builder_with_excludes`
17/// when the `compression` feature is enabled.  Shared cache with the middleware.
18///
19/// **Limitation**: This is a process-global static, so it only works correctly
20/// for single-agent processes (the normal phi-agent use case).  Multi-agent
21/// processes that run multiple independent agents in the same process would
22/// need a per-agent compactor instead.
23#[cfg(feature = "compression")]
24static COMPACTOR: std::sync::Mutex<Option<ContextCompactor>> = std::sync::Mutex::new(None);
25
26/// Clear the compression summary cache.
27///
28/// Called by the `/compact` REPL command.  The next turn will re-summarise
29/// (if compression triggers).  No-op when `compression` is disabled.
30pub fn clear_compression_cache() {
31    #[cfg(feature = "compression")]
32    {
33        if let Ok(guard) = COMPACTOR.lock()
34            && let Some(ref compactor) = *guard
35        {
36            compactor.clear_cache();
37            tracing::info!("compression cache cleared");
38            return;
39        }
40        tracing::warn!("clear_compression_cache: no compactor registered");
41    }
42}
43
44/// Run `compact_session` on the current session: read → compress → write back.
45///
46/// - `Ok(Some(true))` — compression applied, session rewritten.
47/// - `Ok(Some(false))` — session is below the threshold, no-op.
48/// - `Ok(None)` — compression not available (feature disabled or no compactor registered).
49/// - `Err(...)` — actual error (write-back failure, concurrent modification, etc.).
50///
51/// When `emit_fn` is provided, lifecycle events
52/// (`CompressionEvent::Preparing/Started/Progress/Completed`) with
53/// `CompressionTrigger::Manual` are emitted through it.
54pub async fn run_compact_session(
55    runtime: &agent_base::AgentRuntime,
56    session_id: &agent_base::SessionId,
57    emit_fn: Option<std::sync::Arc<dyn Fn(agent_base::UserEvent) + Send + Sync>>,
58) -> agent_base::AgentResult<Option<bool>> {
59    #[cfg(feature = "compression")]
60    {
61        // Clone the handle so we can drop the lock before the async call.
62        let handle = {
63            let guard = COMPACTOR
64                .lock()
65                .map_err(|e| agent_base::AgentError::internal(format!("COMPACTOR lock poisoned: {e}")))?;
66            guard.as_ref().map(|c| c.clone_handle())
67        };
68        if let Some(compactor) = handle {
69            return compactor.compact_session(runtime, session_id, emit_fn).await.map(Some);
70        }
71        tracing::warn!("run_compact_session: no compactor registered");
72        Ok(None)
73    }
74    #[cfg(not(feature = "compression"))]
75    {
76        let _ = (runtime, session_id, emit_fn);
77        Ok(None)
78    }
79}
80
81/// Returns an [`agent_works::AgentBuilder`] with sensible defaults:
82/// - English
83/// - Medium reasoning effort
84/// - Thinking enabled
85/// - Consecutive failure recovery (default 3 retries)
86/// - Session limits (50 sessions / 100 turns per session / 50k per-message cap)
87/// - Per-run react-loop cap (200 iterations for one user input)
88/// - LLM-based context compression for long tool-heavy conversations
89///   (uses `CompressionMiddleware` from agent-works when `compression` feature is enabled)
90/// - File tools (read_file / write_file / edit_file / list_files) — enabled by default
91/// - Plan checklist (update_plan) — display-only progress tracking, enabled by default
92/// - Skills injected into system prompt (not as tools — LLM uses read_file;
93///   enabled by default via `file` feature)
94/// - MCP protocol support — enabled by default
95/// - Telemetry + logging — enabled by default
96///
97/// Callers are responsible for: registering additional tools, setting the approval
98/// handler, setting the system prompt, then calling `.build()`.
99///
100/// Feature groups (opt-in):
101/// - `shell`: shell execution (`--features shell`)
102/// - `multi-agent`: multi-agent support (`--features multi-agent`)
103/// - `browser`: browser automation via CDP (`--features browser`)
104/// - `protocol` meta: MCP
105/// - `observability` meta: telemetry + logging
106/// - `app` meta: browser (NOT included in `full`)
107/// - `full`: file + shell + mcp + telemetry + logging (excludes browser and multi-agent)
108#[allow(unused_mut)]
109pub fn base_agent_builder(llm_client: Arc<dyn agent_base::llm_trait::LlmProvider>) -> agent_works::AgentBuilder {
110    base_agent_builder_with_excludes(llm_client, Vec::new())
111}
112
113/// Like [`base_agent_builder`], but lets the consumer inject a list of entry
114/// names for [`phi_kernel_tools::file::ListFilesTool`] to skip (e.g. a coding agent passing
115/// `["target", "node_modules"]`). The framework stays domain-agnostic: it
116/// defaults to no excludes; the consumer decides what counts as noise.
117#[allow(unused_mut)]
118pub fn base_agent_builder_with_excludes(
119    llm_client: Arc<dyn agent_base::llm_trait::LlmProvider>,
120    file_excludes: Vec<String>,
121) -> agent_works::AgentBuilder {
122    base_agent_builder_with_options(llm_client, file_excludes, None)
123}
124
125/// Like [`base_agent_builder_with_excludes`], but also lets the consumer
126/// override the [`CompressionConfig`] used by the context-compression
127/// middleware.  Pass `None` to use the defaults.
128#[allow(unused_mut)]
129pub fn base_agent_builder_with_options(
130    llm_client: Arc<dyn agent_base::llm_trait::LlmProvider>,
131    file_excludes: Vec<String>,
132    compression_config: Option<CompressionConfig>,
133) -> agent_works::AgentBuilder {
134    // Tool-output cap (default 4000 chars). Tune via PHI_MAX_TOOL_OUTPUT_CHARS for large
135    // outputs (HTML, base64 images, long lists). The engine REJECTS output that exceeds
136    // this cap (design §6.5) rather than silently truncating. Tools that can bound
137    // themselves — e.g. read_file — self-truncate to the per-call budget exposed via
138    // `ToolContext::max_output_chars` and emit a "...(truncated)" continuation hint.
139    let max_tool_output_chars = match std::env::var("PHI_MAX_TOOL_OUTPUT_CHARS") {
140        Ok(value) => match value.trim().parse::<usize>() {
141            Ok(n) => n,
142            Err(_) => {
143                tracing::warn!(
144                    value = %value,
145                    "PHI_MAX_TOOL_OUTPUT_CHARS is not a valid integer; falling back to default 4000"
146                );
147                4000
148            },
149        },
150        Err(_) => 4000,
151    };
152
153    #[cfg(feature = "file")]
154    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
155
156    let mut builder = agent_works::AgentBuilder::new(llm_client.clone())
157        .language(Language::En)
158        .reasoning(ReasoningConfig { effort: Some(ReasoningEffort::Medium), ..Default::default() })
159        .enable_thought(true)
160        .enable_thinking(true)
161        .max_sessions(50)
162        .max_turns_per_session(100)
163        .execution_max_turns(200)
164        // Session 20260904_c6559510: the fan-in batch injection (all child
165        // reports in one message) hit this valve and was SILENTLY popped —
166        // the parent turned without any reports and hallucinated a synthesis.
167        // 50k was sized for single user inputs, not multi-report batches.
168        // Injection senders still cap their own payloads; this valve is the
169        // last-resort guard, not the size manager.
170        .max_message_tokens(120_000)
171        .max_tool_output_chars(max_tool_output_chars)
172        .error_recovery(Arc::new(ConsecutiveFailureRecovery::new(3)));
173
174    // Context compression: use CompressionMiddleware from agent-works
175    // (hybrid retention + stable-prefix cache + handoff summary).
176    #[cfg(feature = "compression")]
177    {
178        let compactor = ContextCompactor::new(llm_client.clone(), compression_config.unwrap_or_default());
179        // Store a cloned handle (shared cache) for the /compact command.
180        let handle = compactor.clone_handle();
181        if let Ok(mut guard) = COMPACTOR.lock() {
182            *guard = Some(handle);
183        }
184        builder = builder.middleware(CompressionMiddleware::from_compactor(compactor));
185    }
186
187    // ── File tools (opt-in via `file` feature) ──
188    #[cfg(feature = "file")]
189    {
190        use phi_kernel_tools::file::{EditFileTool, ListFilesTool, ReadFileTool, WriteFileTool};
191        builder = builder
192            .register_tool_arc(Arc::new(ReadFileTool::new(cwd.clone())))
193            .register_tool_arc(Arc::new(WriteFileTool::new(cwd.clone())))
194            .register_tool_arc(Arc::new(EditFileTool::new(cwd.clone())))
195            .register_tool_arc(Arc::new(ListFilesTool::with_excludes(cwd.clone(), file_excludes)));
196    }
197
198    // ── Plan checklist (display-only progress tracking) ──
199    // `build_system_prompt` instructs the model to call `update_plan` for complex tasks,
200    // so the base builder registers it unconditionally — otherwise the prompt references
201    // a tool the agent doesn't have (the `init`/`serve` entry points used to hit this).
202    builder = builder.register_tool_arc(Arc::new(UpdatePlanTool::new()));
203
204    // ── Multi-agent (opt-in) ──
205    #[cfg(feature = "multi-agent")]
206    {
207        use agent_works::multi_agent::MultiAgentConfig;
208        // Children share this process's cwd (phimint chdir's to the workspace
209        // at startup), so it is the base their relative paths resolve against.
210        // Injected as a fact into each child's system prompt — session
211        // 20260904_3eeb5610: a child silently analyzed the wrong directory
212        // because nothing told it where its relative paths land.
213        let ma_cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
214        builder = builder.with_multi_agent(MultiAgentConfig::default()).with_multi_agent_tool_factory(Arc::new(
215            move |runtime| phi_kernel_tools::multi_agent::create_all_tools(runtime, ma_cwd.clone()),
216        ));
217    }
218
219    // ── Skills: prompt-injection mode (uses read_file, no skill-specific tools) ──
220    #[cfg(feature = "skill")]
221    {
222        use agent_works::skill::Skill;
223        use agent_works::skill::prompt_skill::PromptSkill;
224        let skill_dirs: Vec<PathBuf> = vec![
225            // User-level skills (low priority)
226            dirs_next().join(".claude").join("skills"),
227            // Project-level skills (high priority, loaded last to override)
228            PathBuf::from(".claude/skills"),
229        ];
230
231        for dir in &skill_dirs {
232            if dir.is_dir() {
233                match PromptSkill::scan_dir(dir) {
234                    Ok(skills) => {
235                        for skill in skills {
236                            tracing::debug!(
237                                name = skill.name(),
238                                dir = %dir.display(),
239                                "auto-loaded skill (prompt-injection mode)"
240                            );
241                            builder = builder.register_skill(skill);
242                        }
243                    },
244                    Err(e) => {
245                        tracing::warn!(dir = %dir.display(), error = %e, "failed to scan skills directory");
246                    },
247                }
248            }
249        }
250    }
251
252    builder
253}
254
255/// Resolve the user's home directory for `~/.claude/skills/`.
256#[cfg(feature = "skill")]
257fn dirs_next() -> std::path::PathBuf {
258    std::env::var("HOME")
259        .or_else(|_| std::env::var("USERPROFILE"))
260        .map(PathBuf::from)
261        .unwrap_or_else(|_| PathBuf::from("."))
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use async_trait::async_trait;
268    use futures_core::Stream;
269    use std::pin::Pin;
270    use std::task::{Context, Poll};
271
272    struct StubClient;
273    struct EmptyStream;
274
275    impl Stream for EmptyStream {
276        type Item = Result<agent_base::StreamChunk, agent_base::llm_trait::LlmError>;
277        fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
278            Poll::Ready(None)
279        }
280    }
281
282    #[async_trait]
283    impl agent_base::llm_trait::LlmProvider for StubClient {
284        async fn stream(
285            &self,
286            _request: agent_base::llm_trait::ChatRequest,
287        ) -> Result<agent_base::llm_trait::ChatStream, agent_base::llm_trait::LlmError> {
288            Ok(agent_base::llm_trait::ChatStream::new(Box::pin(EmptyStream)))
289        }
290        async fn chat(
291            &self,
292            _request: agent_base::llm_trait::ChatRequest,
293        ) -> Result<agent_base::llm_trait::ChatResponse, agent_base::llm_trait::LlmError> {
294            Ok(agent_base::llm_trait::ChatResponse {
295                content: "stub".to_string(),
296                reasoning_content: None,
297                tool_calls: vec![],
298                usage: agent_base::UsageInfo::default(),
299                finish_reason: agent_base::llm_trait::FinishReason::Stop,
300                raw: None,
301                thinking_signature: None,
302            })
303        }
304        fn capabilities(&self) -> agent_base::llm_trait::Capabilities {
305            agent_base::llm_trait::Capabilities::default()
306        }
307        fn info(&self) -> agent_base::llm_trait::ProviderInfo {
308            agent_base::llm_trait::ProviderInfo { name: "stub".to_string(), model: "stub".to_string(), version: None }
309        }
310    }
311
312    #[test]
313    fn test_max_tool_output_chars_default() {
314        unsafe { std::env::remove_var("PHI_MAX_TOOL_OUTPUT_CHARS") };
315        let builder = base_agent_builder(Arc::new(StubClient));
316        let _ = builder;
317    }
318
319    #[test]
320    fn test_max_tool_output_chars_custom() {
321        unsafe { std::env::set_var("PHI_MAX_TOOL_OUTPUT_CHARS", "8000") };
322        let builder = base_agent_builder(Arc::new(StubClient));
323        let _ = builder;
324        unsafe { std::env::remove_var("PHI_MAX_TOOL_OUTPUT_CHARS") };
325    }
326
327    #[test]
328    fn test_max_tool_output_chars_invalid_fallback() {
329        unsafe { std::env::set_var("PHI_MAX_TOOL_OUTPUT_CHARS", "not-a-number") };
330        let builder = base_agent_builder(Arc::new(StubClient));
331        let _ = builder;
332        unsafe { std::env::remove_var("PHI_MAX_TOOL_OUTPUT_CHARS") };
333    }
334
335    /// Verify that the default `base_agent_builder()` registers the 4 multi-agent tools.
336    #[cfg(feature = "multi-agent")]
337    #[tokio::test(flavor = "multi_thread")]
338    async fn test_base_agent_builder_registers_multi_agent_tools() {
339        let builder = base_agent_builder(Arc::new(StubClient)).system_prompt("test");
340
341        let runtime = builder.build().unwrap();
342
343        let tools = tokio::task::block_in_place(|| {
344            let tools = runtime.tools_mut();
345            let guard = tools.blocking_read();
346            guard.metadatas().into_iter().map(|m| m.name).collect::<Vec<String>>()
347        });
348
349        assert!(tools.contains(&"spawn_agent".to_string()), "expected spawn_agent tool");
350        assert!(tools.contains(&"send_message".to_string()), "expected send_message tool");
351        // followup_task is deprecated and dropped from the factory (agent-works
352        // §8.3); its trigger semantics now live in send_message(trigger=true).
353        assert!(!tools.contains(&"followup_task".to_string()), "followup_task must not be registered");
354        // wait_agent was removed with the result-push model (agent-works §8.3):
355        // child results are pushed to the parent's mailbox automatically, so
356        // there is nothing left to poll.
357        assert!(!tools.contains(&"wait_agent".to_string()), "wait_agent must not be registered");
358        assert!(tools.contains(&"list_agents".to_string()), "expected list_agents tool");
359        assert!(tools.contains(&"close_agent".to_string()), "expected close_agent tool");
360    }
361
362    /// Verify that `.without_multi_agent()` on the returned builder removes the tools.
363    #[cfg(feature = "multi-agent")]
364    #[tokio::test(flavor = "multi_thread")]
365    async fn test_base_agent_builder_without_multi_agent() {
366        let builder = base_agent_builder(Arc::new(StubClient)).system_prompt("test").without_multi_agent();
367
368        let runtime = builder.build().unwrap();
369
370        let tools = tokio::task::block_in_place(|| {
371            let tools = runtime.tools_mut();
372            let guard = tools.blocking_read();
373            guard.metadatas().into_iter().map(|m| m.name).collect::<Vec<String>>()
374        });
375
376        assert!(!tools.contains(&"spawn_agent".to_string()), "spawn_agent should not be registered");
377        assert!(!tools.contains(&"list_agents".to_string()), "list_agents should not be registered");
378    }
379}