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-5", "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::num::NonZeroU64;
38use std::sync::Arc;
39use std::sync::atomic::AtomicUsize;
40
41use eyre::Result;
42use tokio::sync::Semaphore;
43
44use agent::{
45    AgentConfig, AgentDepth, AgentProgress, AgentResult, MAX_CONCURRENT_LLM_CALLS, run_agent,
46};
47use config::DEFAULT_MAX_TURNS;
48use llm::{LLMClient, LLMClientDyn, LLMProvider, WithRetryExt};
49use tools::Tool;
50
51/// Curated entrypoints for driving a file-reading agent with subagents.
52pub mod prelude {
53    pub use crate::agent::{
54        AgentConfig, AgentDepth, AgentProgress, AgentResult, MAX_CONCURRENT_LLM_CALLS,
55        add_spawn_subagent_tool, run_agent,
56    };
57    pub use crate::llm::{LLMClientDyn, LLMProvider, WithRetryExt};
58    pub use crate::tools::{Tool, all_tools};
59    pub use crate::{AgentBuilder, client_from_env, file_agent_tools};
60}
61
62/// The file/git toolset plus `spawn_subagent` — the "reads files and spawns subagents" kit.
63pub fn file_agent_tools() -> HashMap<String, Arc<dyn Tool>> {
64    let mut tools = tools::all_tools();
65    agent::add_spawn_subagent_tool(&mut tools);
66    tools
67}
68
69/// Build a retry-wrapped client for a provider, reading its API key from the environment.
70pub fn client_from_env(provider: LLMProvider) -> Result<Arc<dyn LLMClientDyn>> {
71    Ok(provider.client_from_env()?.with_retry().into_arc())
72}
73
74/// Ergonomic constructor for [`AgentConfig`]. Required inputs are passed to [`AgentBuilder::new`];
75/// every other field defaults to the same values the nitpicker review path uses, and is
76/// overridable via the chainable setters. Use [`AgentBuilder::build`] for a raw config or
77/// [`AgentBuilder::run`] to execute in one call.
78///
79/// Concurrency note: each builder defaults to its **own** `Semaphore::new(MAX_CONCURRENT_LLM_CALLS)`,
80/// so it bounds in-flight LLM calls within one agent (and its subagents) but not *across*
81/// independent builders — N agents can run N × `MAX_CONCURRENT_LLM_CALLS` calls at once. To cap
82/// aggregate concurrency account-wide, share one `Arc<Semaphore>` via [`AgentBuilder::llm_semaphore`].
83pub struct AgentBuilder {
84    config: AgentConfig,
85}
86
87impl AgentBuilder {
88    pub fn new(
89        name: impl Into<String>,
90        model: impl Into<String>,
91        system_prompt: impl Into<String>,
92        client: Arc<dyn LLMClientDyn>,
93    ) -> Self {
94        let config = AgentConfig {
95            name: name.into(),
96            session_agent: "root".to_string(),
97            model: model.into(),
98            max_turns: DEFAULT_MAX_TURNS,
99            max_tokens: None,
100            compact_threshold: None,
101            system_prompt: system_prompt.into(),
102            subagent_system_prompt: None,
103            client,
104            depth: AgentDepth::TopLevel,
105            terminal_tools: Vec::new(),
106            empty_response_nudge: None,
107            max_empty_responses: 0,
108            subagent_counter: Arc::new(AtomicUsize::new(0)),
109            llm_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_LLM_CALLS)),
110            progress: None,
111            project_context: None,
112            session_writer: None,
113        };
114        Self { config }
115    }
116
117    pub fn max_turns(mut self, max_turns: usize) -> Self {
118        self.config.max_turns = max_turns;
119        self
120    }
121
122    pub fn compact_threshold(mut self, threshold: u64) -> Self {
123        self.config.compact_threshold = Some(threshold);
124        self
125    }
126
127    /// Cap the output of each turn. Unset by default, which leaves the provider's own per-model
128    /// limit to apply; set it only to bound spend, since a cap below what the model reasons
129    /// through returns empty content rather than a shorter answer. `NonZeroU64` because a zero cap
130    /// asks for a response the provider answers with nothing at all.
131    pub fn max_tokens(mut self, max_tokens: NonZeroU64) -> Self {
132        self.config.max_tokens = Some(max_tokens.get());
133        self
134    }
135
136    /// Override the system prompt spawned subagents run with (default: the built-in generic
137    /// prompt). The override propagates through nested subagent spawns.
138    pub fn subagent_system_prompt(mut self, prompt: impl Into<String>) -> Self {
139        self.config.subagent_system_prompt = Some(prompt.into());
140        self
141    }
142
143    /// Extra context appended to the system prompt (e.g. a project summary).
144    pub fn project_context(mut self, context: impl Into<String>) -> Self {
145        self.config.project_context = Some(context.into());
146        self
147    }
148
149    /// Share a concurrency limiter across agents instead of the per-builder default
150    /// (`Semaphore::new(MAX_CONCURRENT_LLM_CALLS)`), to cap aggregate in-flight LLM calls.
151    pub fn llm_semaphore(mut self, semaphore: Arc<Semaphore>) -> Self {
152        self.config.llm_semaphore = semaphore;
153        self
154    }
155
156    pub fn progress(mut self, progress: Arc<dyn Fn(AgentProgress) + Send + Sync>) -> Self {
157        self.config.progress = Some(progress);
158        self
159    }
160
161    pub fn build(self) -> AgentConfig {
162        self.config
163    }
164
165    /// Build and run the agent to completion.
166    pub async fn run(
167        self,
168        initial_message: &str,
169        tools: &HashMap<String, Arc<dyn Tool>>,
170        work_dir: &std::path::Path,
171    ) -> Result<AgentResult> {
172        run_agent(self.config, initial_message, tools, work_dir).await
173    }
174}