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