Skip to main content

nitpicker_agent/
lib.rs

1//! Reusable agentic loop extracted from [nitpicker](https://github.com/arsenyinfo/nitpicker):
2//! an LLM agent that reads files (read_file / glob / grep / git) and fans out parallel
3//! subagents, with provider-agnostic LLM clients and optional config-file-driven setup.
4//!
5//! The fastest way in is the [`prelude`] plus [`AgentBuilder`]:
6//!
7//! ```no_run
8//! use nitpicker_agent::prelude::*;
9//! use std::path::Path;
10//!
11//! # async fn run() -> eyre::Result<()> {
12//! let client = client_from_env(LLMProvider::Anthropic { base_url: None, api_key_env: None })?;
13//! let result = AgentBuilder::new("explorer", "claude-sonnet-4-6", "You explore codebases.", client)
14//!     .subagent_system_prompt("You are a focused file-reading worker. Report findings concisely.")
15//!     .run("Map the module layout of this repo.", &file_agent_tools(), Path::new("."))
16//!     .await?;
17//! println!("{}", result.text);
18//! # Ok(())
19//! # }
20//! ```
21
22pub mod agent;
23pub mod codex;
24pub mod compact;
25pub mod config;
26pub mod llm;
27pub mod openrouter;
28pub mod prompts;
29pub mod provider;
30pub mod session;
31pub mod tools;
32
33#[cfg(feature = "azure")]
34pub mod azure;
35
36use std::collections::HashMap;
37use std::sync::Arc;
38use std::sync::atomic::AtomicUsize;
39
40use eyre::Result;
41use tokio::sync::Semaphore;
42
43use agent::{AgentConfig, AgentDepth, AgentProgress, AgentResult, MAX_CONCURRENT_LLM_CALLS, run_agent};
44use config::DEFAULT_MAX_TURNS;
45use llm::{LLMClient, LLMClientDyn, LLMProvider, WithRetryExt};
46use tools::Tool;
47
48/// Curated entrypoints for driving a file-reading agent with subagents.
49pub mod prelude {
50    pub use crate::agent::{
51        AgentConfig, AgentDepth, AgentProgress, AgentResult, MAX_CONCURRENT_LLM_CALLS,
52        add_spawn_subagent_tool, run_agent,
53    };
54    pub use crate::llm::{LLMClientDyn, LLMProvider, WithRetryExt};
55    pub use crate::tools::{Tool, all_tools};
56    pub use crate::{AgentBuilder, client_from_env, file_agent_tools};
57}
58
59/// The file/git toolset plus `spawn_subagent` — the "reads files and spawns subagents" kit.
60pub fn file_agent_tools() -> HashMap<String, Arc<dyn Tool>> {
61    let mut tools = tools::all_tools();
62    agent::add_spawn_subagent_tool(&mut tools);
63    tools
64}
65
66/// Build a retry-wrapped client for a provider, reading its API key from the environment.
67pub fn client_from_env(provider: LLMProvider) -> Result<Arc<dyn LLMClientDyn>> {
68    Ok(provider.client_from_env()?.with_retry().into_arc())
69}
70
71/// Ergonomic constructor for [`AgentConfig`]. Required inputs are passed to [`AgentBuilder::new`];
72/// every other field defaults to the same values the nitpicker review path uses, and is
73/// overridable via the chainable setters. Use [`AgentBuilder::build`] for a raw config or
74/// [`AgentBuilder::run`] to execute in one call.
75///
76/// Concurrency note: each builder defaults to its **own** `Semaphore::new(MAX_CONCURRENT_LLM_CALLS)`,
77/// so it bounds in-flight LLM calls within one agent (and its subagents) but not *across*
78/// independent builders — N agents can run N × `MAX_CONCURRENT_LLM_CALLS` calls at once. To cap
79/// aggregate concurrency account-wide, share one `Arc<Semaphore>` via [`AgentBuilder::llm_semaphore`].
80pub struct AgentBuilder {
81    config: AgentConfig,
82}
83
84impl AgentBuilder {
85    pub fn new(
86        name: impl Into<String>,
87        model: impl Into<String>,
88        system_prompt: impl Into<String>,
89        client: Arc<dyn LLMClientDyn>,
90    ) -> Self {
91        let config = AgentConfig {
92            name: name.into(),
93            session_agent: "root".to_string(),
94            model: model.into(),
95            max_turns: DEFAULT_MAX_TURNS,
96            compact_threshold: None,
97            system_prompt: system_prompt.into(),
98            subagent_system_prompt: None,
99            client,
100            depth: AgentDepth::TopLevel,
101            terminal_tools: Vec::new(),
102            empty_response_nudge: None,
103            max_empty_responses: 0,
104            subagent_counter: Arc::new(AtomicUsize::new(0)),
105            llm_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_LLM_CALLS)),
106            progress: None,
107            project_context: None,
108            session_writer: None,
109        };
110        Self { config }
111    }
112
113    pub fn max_turns(mut self, max_turns: usize) -> Self {
114        self.config.max_turns = max_turns;
115        self
116    }
117
118    pub fn compact_threshold(mut self, threshold: u64) -> Self {
119        self.config.compact_threshold = Some(threshold);
120        self
121    }
122
123    /// Override the system prompt spawned subagents run with (default: the built-in generic
124    /// prompt). The override propagates through nested subagent spawns.
125    pub fn subagent_system_prompt(mut self, prompt: impl Into<String>) -> Self {
126        self.config.subagent_system_prompt = Some(prompt.into());
127        self
128    }
129
130    /// Extra context appended to the system prompt (e.g. a project summary).
131    pub fn project_context(mut self, context: impl Into<String>) -> Self {
132        self.config.project_context = Some(context.into());
133        self
134    }
135
136    /// Share a concurrency limiter across agents instead of the per-builder default
137    /// (`Semaphore::new(MAX_CONCURRENT_LLM_CALLS)`), to cap aggregate in-flight LLM calls.
138    pub fn llm_semaphore(mut self, semaphore: Arc<Semaphore>) -> Self {
139        self.config.llm_semaphore = semaphore;
140        self
141    }
142
143    pub fn progress(mut self, progress: Arc<dyn Fn(AgentProgress) + Send + Sync>) -> Self {
144        self.config.progress = Some(progress);
145        self
146    }
147
148    pub fn build(self) -> AgentConfig {
149        self.config
150    }
151
152    /// Build and run the agent to completion.
153    pub async fn run(
154        self,
155        initial_message: &str,
156        tools: &HashMap<String, Arc<dyn Tool>>,
157        work_dir: &std::path::Path,
158    ) -> Result<AgentResult> {
159        run_agent(self.config, initial_message, tools, work_dir).await
160    }
161}