use eyre::{Result, WrapErr};
use nitpicker_agent::AgentBuilder;
use nitpicker_agent::agent::AgentResult;
use nitpicker_agent::config::{Config, ReviewerConfig};
use nitpicker_agent::provider::build_reviewer_client;
use nitpicker_agent::session::now_unix_ms;
use nitpicker_agent::tools::{GlobTool, GrepTool, ReadFileTool, Tool};
use rig_core::completion::ToolDefinition;
use rig_core::message::ToolName;
use serde::Serialize;
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
const CODER_SYSTEM_PROMPT: &str = include_str!("../prompts/build/coder.md");
pub(crate) const DEFAULT_MAX_TURNS: usize = 200;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);
const MAX_TIMEOUT: Duration = Duration::from_secs(600);
const MAX_STREAM_BYTES: usize = 20_000;
const HEAD_STREAM_BYTES: usize = 8_000;
const ENV_ALLOWLIST: &[&str] = &[
"PATH",
"HOME",
"USER",
"LOGNAME",
"SHELL",
"TMPDIR",
"LANG",
"LC_ALL",
"CARGO_HOME",
"RUSTUP_HOME",
];
pub(crate) struct BuildArgs<'a> {
pub(crate) repo: &'a Path,
pub(crate) task: &'a str,
pub(crate) coder: Option<&'a str>,
pub(crate) max_turns: usize,
pub(crate) trajectory_dir: Option<&'a Path>,
}
#[derive(Serialize)]
struct Usage {
model: String,
turns: usize,
tool_calls: usize,
input_tokens: u64,
cached_input_tokens: u64,
output_tokens: u64,
}
impl Usage {
fn new(model: &str, result: &AgentResult) -> Self {
Self {
model: model.to_string(),
turns: result.turns,
tool_calls: result.tool_calls,
input_tokens: result.usage.input_tokens,
cached_input_tokens: result.usage.cached_input_tokens,
output_tokens: result.usage.output_tokens,
}
}
}
pub(crate) async fn run_build(config: &Config, args: BuildArgs<'_>) -> Result<String> {
if let Some(dir) = args.trajectory_dir {
std::fs::create_dir_all(dir)
.wrap_err_with(|| format!("failed to create {}", dir.display()))?;
}
let coder = select_reviewer(config, args.coder)?;
let gemini_proxy = crate::proxy::GeminiProxy::start_for([coder], None).await;
let context = crate::context::build_context(args.repo).await;
eprintln!("coder: {} ({})", coder.name, coder.model);
let bash_log = args
.trajectory_dir
.map(|dir| Arc::new(dir.join("bash.jsonl")));
let result = agent(config, coder, gemini_proxy.url().as_deref(), &context, args.max_turns)?
.run(args.task, &coder_tools(bash_log), args.repo)
.await?;
let usage = Usage::new(&coder.model, &result);
eprintln!(
"done: {} turns, {} tool calls, {} input ({} cached) / {} output tokens",
usage.turns,
usage.tool_calls,
usage.input_tokens,
usage.cached_input_tokens,
usage.output_tokens
);
if let Some(dir) = args.trajectory_dir {
let written = serde_json::to_vec_pretty(&usage)
.map_err(eyre::Report::from)
.and_then(|json| Ok(std::fs::write(dir.join("usage.json"), json)?));
if let Err(err) = written {
tracing::warn!(error = %err, "failed to write usage.json");
}
}
Ok(result.text)
}
fn agent(
config: &Config,
reviewer: &ReviewerConfig,
proxy_url: Option<&str>,
context: &str,
max_turns: usize,
) -> Result<AgentBuilder> {
let client = build_reviewer_client(reviewer, proxy_url)?;
let mut builder = AgentBuilder::new("coder", &reviewer.model, CODER_SYSTEM_PROMPT, client)
.max_turns(max_turns);
if let Some(threshold) = config.reviewer_compact_threshold(reviewer) {
builder = builder.compact_threshold(threshold);
}
if let Some(max_tokens) = reviewer.max_tokens.and_then(NonZeroU64::new) {
builder = builder.max_tokens(max_tokens);
}
if !context.is_empty() {
builder = builder.project_context(context);
}
Ok(builder)
}
fn select_reviewer<'a>(config: &'a Config, name: Option<&str>) -> Result<&'a ReviewerConfig> {
match name {
None => config
.reviewer
.first()
.ok_or_else(|| eyre::eyre!("config must have at least one reviewer")),
Some(name) => config
.reviewer
.iter()
.find(|reviewer| reviewer.name == name)
.ok_or_else(|| {
let known: Vec<&str> = config.reviewer.iter().map(|r| r.name.as_str()).collect();
eyre::eyre!(
"no reviewer named '{name}'; configured: {}",
known.join(", ")
)
}),
}
}
fn coder_tools(bash_log: Option<Arc<PathBuf>>) -> HashMap<String, Arc<dyn Tool>> {
let tools: [Arc<dyn Tool>; 4] = [
Arc::new(BashTool { log: bash_log }),
Arc::new(ReadFileTool),
Arc::new(GlobTool),
Arc::new(GrepTool),
];
tools.into_iter().map(|tool| (tool.name(), tool)).collect()
}
struct BashTool {
log: Option<Arc<PathBuf>>,
}
impl Tool for BashTool {
fn name(&self) -> String {
"bash".to_string()
}
fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: ToolName::new("bash").unwrap(),
annotations: Default::default(),
description: "Run a bash command in the repository root. Returns the exit code, stdout, and stderr (each clipped to 20,000 bytes: the first 8,000 and the last 12,000, with a marker in between). No stdin; killed on timeout.".to_string(),
parameters: json!({
"type": "object",
"properties": {
"command": {"type": "string", "description": "Command passed to `bash -c`"},
"timeout_secs": {"type": "integer", "minimum": 1, "maximum": MAX_TIMEOUT.as_secs(), "description": "Default 120"}
},
"required": ["command"],
"additionalProperties": false
}),
}
}
fn call(
&self,
args: Value,
work_dir: PathBuf,
) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
let log = self.log.clone();
Box::pin(async move {
let command = args
.get("command")
.and_then(Value::as_str)
.ok_or_else(|| eyre::eyre!("missing command"))?
.to_string();
let timeout = match args.get("timeout_secs").and_then(Value::as_u64) {
Some(secs) => Duration::from_secs(secs).min(MAX_TIMEOUT),
None => DEFAULT_TIMEOUT,
};
let result = run_bash(&command, &work_dir, timeout).await;
if let Some(log) = log {
append_bash_log(&log, &command, &result).await;
}
result
})
}
fn exclusive(&self) -> bool {
true
}
}
async fn append_bash_log(log: &Path, command: &str, result: &Result<String>) {
let entry = match result {
Ok(output) => json!({"ts_unix_ms": now_unix_ms(), "command": command, "output": output}),
Err(err) => {
json!({"ts_unix_ms": now_unix_ms(), "command": command, "error": format!("{err:#}")})
}
};
let mut line = entry.to_string();
line.push('\n');
let written = async {
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log)
.await?;
file.write_all(line.as_bytes()).await?;
file.flush().await
};
if let Err(err) = written.await {
tracing::warn!(error = %err, "failed to write bash log");
}
}
async fn run_bash(command: &str, work_dir: &Path, timeout: Duration) -> Result<String> {
let mut cmd = tokio::process::Command::new("bash");
cmd.arg("-c")
.arg(command)
.current_dir(work_dir)
.env_clear()
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
for key in ENV_ALLOWLIST {
if let Ok(value) = std::env::var(key) {
cmd.env(key, value);
}
}
#[cfg(unix)]
cmd.process_group(0);
let mut child = cmd.spawn().wrap_err("failed to spawn bash")?;
let pid = child.id();
let stdout = child.stdout.take().expect("stdout is piped");
let stderr = child.stderr.take().expect("stderr is piped");
let finished = async {
let (stdout, stderr, status) = tokio::join!(drain(stdout), drain(stderr), child.wait());
Ok::<_, std::io::Error>((stdout?, stderr?, status?))
};
match tokio::time::timeout(timeout, finished).await {
Ok(output) => {
let (stdout, stderr, status) = output.wrap_err("failed to wait for bash")?;
let code = match status.code() {
Some(code) => code.to_string(),
None => "killed by signal".to_string(),
};
Ok(format!(
"exit code: {code}\n--- stdout ---\n{}\n--- stderr ---\n{}",
stdout.render(),
stderr.render()
))
}
Err(_) => {
kill_group(pid);
eyre::bail!(
"command timed out after {}s and was killed",
timeout.as_secs()
)
}
}
}
fn kill_group(pid: Option<u32>) {
#[cfg(unix)]
if let Some(pid) = pid.and_then(|pid| i32::try_from(pid).ok()) {
unsafe {
libc::kill(-pid, libc::SIGKILL);
}
}
#[cfg(not(unix))]
let _ = pid;
}
async fn drain(mut reader: impl AsyncRead + Unpin) -> std::io::Result<Clipped> {
let mut clipped = Clipped::default();
let mut buf = [0u8; 8192];
loop {
match reader.read(&mut buf).await? {
0 => return Ok(clipped),
n => clipped.push(&buf[..n]),
}
}
}
#[derive(Default)]
struct Clipped {
head: Vec<u8>,
tail: VecDeque<u8>,
total: usize,
}
const TAIL_STREAM_BYTES: usize = MAX_STREAM_BYTES - HEAD_STREAM_BYTES;
const UTF8_SLACK: usize = 3;
impl Clipped {
fn push(&mut self, mut bytes: &[u8]) {
self.total += bytes.len();
let room = (HEAD_STREAM_BYTES + UTF8_SLACK).saturating_sub(self.head.len());
let (head, rest) = bytes.split_at(room.min(bytes.len()));
self.head.extend_from_slice(head);
bytes = rest;
self.tail.extend(bytes);
let excess = self.tail.len().saturating_sub(TAIL_STREAM_BYTES + UTF8_SLACK);
self.tail.drain(..excess);
}
fn render(&self) -> String {
if self.total <= MAX_STREAM_BYTES {
let mut bytes = self.head.clone();
bytes.extend(&self.tail);
return String::from_utf8_lossy(&bytes).into_owned();
}
let head = String::from_utf8_lossy(&self.head);
let head = &head[..head.floor_char_boundary(HEAD_STREAM_BYTES)];
let tail = String::from_utf8_lossy(&self.tail.iter().copied().collect::<Vec<u8>>()).into_owned();
let tail = &tail[tail.ceil_char_boundary(tail.len().saturating_sub(TAIL_STREAM_BYTES))..];
format!(
"{head}\n... {} bytes omitted ...\n{tail}",
self.total - head.len() - tail.len()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn bash_reports_nonzero_exit_as_output() {
let dir = tempfile::tempdir().unwrap();
let out = run_bash(
"echo hi; echo oops >&2; exit 3",
dir.path(),
DEFAULT_TIMEOUT,
)
.await
.unwrap();
assert_eq!(
out,
"exit code: 3\n--- stdout ---\nhi\n\n--- stderr ---\noops\n"
);
}
#[tokio::test]
async fn bash_timeout_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let started = std::time::Instant::now();
let err = run_bash("sleep 30", dir.path(), Duration::from_millis(200)).await;
assert!(err.is_err());
assert!(started.elapsed() < Duration::from_secs(5));
}
#[tokio::test]
async fn bash_log_records_command_and_output() {
let dir = tempfile::tempdir().unwrap();
let log = Arc::new(dir.path().join("bash.jsonl"));
let tool = BashTool {
log: Some(Arc::clone(&log)),
};
tool.call(json!({"command": "echo hi"}), dir.path().to_path_buf())
.await
.unwrap();
let line: Value =
serde_json::from_str(std::fs::read_to_string(log.as_ref()).unwrap().trim()).unwrap();
assert_eq!(line["command"], "echo hi");
assert_eq!(
line["output"],
"exit code: 0\n--- stdout ---\nhi\n\n--- stderr ---\n"
);
}
fn clip(bytes: &[u8]) -> String {
let mut clipped = Clipped::default();
for chunk in bytes.chunks(7) {
clipped.push(chunk);
}
clipped.render()
}
#[test]
fn clip_keeps_head_and_tail_on_char_boundaries() {
let head = format!("{}é", "a".repeat(HEAD_STREAM_BYTES - 1));
let tail_len = MAX_STREAM_BYTES - HEAD_STREAM_BYTES;
let tail = format!("é{}", "c".repeat(tail_len - 1));
let text = format!("{head}{}{tail}", "b".repeat(1000));
let out = clip(text.as_bytes());
let omitted = text.len() - (HEAD_STREAM_BYTES - 1) - (tail_len - 1);
assert_eq!(
out,
format!(
"{}\n... {omitted} bytes omitted ...\n{}",
"a".repeat(HEAD_STREAM_BYTES - 1),
"c".repeat(tail_len - 1)
)
);
}
#[tokio::test]
async fn bash_clips_large_output_while_streaming() {
let dir = tempfile::tempdir().unwrap();
let out = run_bash("yes | head -c 5000000", dir.path(), DEFAULT_TIMEOUT)
.await
.unwrap();
assert!(out.len() < MAX_STREAM_BYTES + 200);
assert!(out.contains(&format!("... {} bytes omitted ...", 5_000_000 - MAX_STREAM_BYTES)));
}
#[test]
fn clip_leaves_short_output_untouched() {
let text = "x".repeat(MAX_STREAM_BYTES);
assert_eq!(clip(text.as_bytes()), text);
}
}