Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ toml = "^1.0"
[dev-dependencies]
assert_cmd = "^2.1.1"
predicates = "^3.1.3"
tempfile = "^3.10"

[profile.release]
opt-level = 3
Expand Down
6 changes: 6 additions & 0 deletions devops/render-release-notes.sh
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ cat <<EOF
\** RHEL and compatible distributions like Amazon, Rocky, etc. that use musl instead of glibc.
\*** Windows x86_64 only; built with the GNU toolchain (mingw-w64).

## Install on Amazon Linux

~~~sh
curl -fsSL "https://github.com/${REPO}/releases/download/${VERSION}/commitbot-${VERSION}-unknown-linux-musl-\$(uname -m).tar.gz" | sudo tar -xz --no-same-owner -C /usr/local/bin commitbot
~~~

EOF

if [[ -n "${NOTES_FILE}" && -f "${NOTES_FILE}" ]]; then
Expand Down
45 changes: 45 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub struct Config {
pub max_concurrent_requests: usize,
/// Whether to stream responses from the LLM
pub stream: bool,
/// HTTP request timeout in seconds for LLM calls
pub request_timeout_secs: u64,
}

impl Config {
Expand Down Expand Up @@ -53,6 +55,7 @@ impl Config {

let max_concurrent_requests = r.get_usize("max_concurrent_requests", 4);
let stream = r.get_bool("stream", true);
let request_timeout_secs = r.get_u64("request_timeout_secs", 90);

// Cleanup: trim stray quotes if any upstream included them
let provider = provider.trim_matches('"').to_string();
Expand All @@ -73,6 +76,7 @@ impl Config {
base_url,
max_concurrent_requests,
stream,
request_timeout_secs,
})
}
}
Expand All @@ -86,6 +90,7 @@ struct FileConfig {
pub base_url: Option<String>,
pub max_concurrent_requests: Option<usize>,
pub stream: Option<bool>,
pub request_timeout_secs: Option<u64>,
}

/// Root of the TOML file:
Expand Down Expand Up @@ -169,6 +174,7 @@ impl<'a> ConfigResolver<'a> {
"base_url" => Some("COMMITBOT_BASE_URL"),
"max_concurrent_requests" => Some("COMMITBOT_MAX_CONCURRENT_REQUESTS"),
"stream" => Some("COMMITBOT_STREAM"),
"request_timeout_secs" => Some("COMMITBOT_REQUEST_TIMEOUT_SECS"),
_ => None,
}
}
Expand Down Expand Up @@ -202,6 +208,18 @@ impl<'a> ConfigResolver<'a> {
}
}

fn file_u64(&self, key: &str, repo: bool) -> Option<u64> {
let cfg = if repo {
&self.file_repo
} else {
&self.file_default
};
match key {
"request_timeout_secs" => cfg.request_timeout_secs,
_ => None,
}
}

fn file_bool(&self, key: &str, repo: bool) -> Option<bool> {
let cfg = if repo {
&self.file_repo
Expand All @@ -226,6 +244,11 @@ impl<'a> ConfigResolver<'a> {
env::var(env_key).ok().and_then(|s| s.parse::<usize>().ok())
}

fn env_u64(&self, key: &str) -> Option<u64> {
let env_key = self.env_key_for(key)?;
env::var(env_key).ok().and_then(|s| s.parse::<u64>().ok())
}

fn env_bool(&self, key: &str) -> Option<bool> {
let env_key = self.env_key_for(key)?;
env::var(env_key).ok().and_then(|s| s.parse::<bool>().ok())
Expand Down Expand Up @@ -429,6 +452,28 @@ impl<'a> ConfigResolver<'a> {
value
}

/// Resolve a u64.
pub fn get_u64(&self, key: &str, default: u64) -> u64 {
let mut value = default;
let mut src = ValueSource::Hardcoded;

if let Some(v) = self.file_u64(key, false) {
value = v;
src = ValueSource::FileDefault;
}
if let Some(v) = self.file_u64(key, true) {
value = v;
src = ValueSource::FileRepo;
}
if let Some(v) = self.env_u64(key) {
value = v;
src = ValueSource::Env;
}

self.log_decision(key, &value, src);
value
}

/// Resolve a bool.
pub fn get_bool(&self, key: &str, default: bool) -> bool {
let mut value = default;
Expand Down
22 changes: 19 additions & 3 deletions src/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,20 @@ pub fn git_output(args: &[&str]) -> Result<String> {
.with_context(|| format!("failed to run git {:?}", args))?;

if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stderr = stderr.trim();
if stderr.is_empty() {
return Err(anyhow!(
"git {:?} exited with status {:?}",
args,
output.status.code()
));
}
return Err(anyhow!(
"git {:?} exited with status {:?}",
"git {:?} exited with status {:?}: {}",
args,
output.status.code()
output.status.code(),
stderr
));
}

Expand Down Expand Up @@ -137,8 +147,14 @@ pub fn staged_files() -> Result<Vec<String>> {
}

/// Get per-file staged diff.
///
/// `staged_files` returns paths relative to the repo root, but a bare pathspec
/// is resolved by git relative to the current working directory. Anchor it
/// with the `:/` top-level magic pathspec so this still works when commitbot
/// is invoked from a subdirectory of the repo.
pub fn staged_diff_for_file(path: &str) -> Result<String> {
let diff = git_output(&["diff", "--cached", "--", path])?;
let pathspec = format!(":/{path}");
let diff = git_output(&["diff", "--cached", "--", &pathspec])?;
Ok(diff)
}

Expand Down
64 changes: 14 additions & 50 deletions src/llm/ollama.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use anyhow::{Result, anyhow};
use log;
use musli::json;
use musli::{Decode, Encode};
use reqwest::StatusCode;
use reqwest::blocking::Client;
use std::io::BufReader;
use std::sync::Mutex;
use std::time::Instant;

use crate::FileChange;
use crate::git::{PrItem, PrSummaryMode};
Expand Down Expand Up @@ -64,8 +64,9 @@ struct TokenUsage {
}

impl OllamaClient {
pub fn new(base_url: impl Into<String>, model: impl Into<String>, stream: bool) -> Self {
pub fn new(base_url: impl Into<String>, model: impl Into<String>, stream: bool, timeout_secs: u64) -> Self {
let http = Client::builder()
.timeout(std::time::Duration::from_secs(timeout_secs))
.build()
.expect("failed to build HTTP client");
Self {
Expand Down Expand Up @@ -115,6 +116,7 @@ impl OllamaClient {

let url = format!("{}/api/chat", self.base_url);

let t0 = Instant::now();
let resp = self
.http
.post(&url)
Expand All @@ -127,13 +129,16 @@ impl OllamaClient {

if stream {
let reader = BufReader::new(resp);
return read_stream_to_string(reader, parse_stream_line);
let result = read_stream_to_string(reader, parse_stream_line);
log::debug!("Ollama response time: {:.2?}", t0.elapsed());
return result;
}

let resp_text = resp
.text()
.map_err(|e| anyhow!("Failed to read Ollama response body: {e}"))?;

log::debug!("Ollama response time: {:.2?}", t0.elapsed());
log::trace!("Ollama raw JSON response: {resp_text}");

#[derive(Debug, Decode)]
Expand Down Expand Up @@ -194,50 +199,9 @@ fn parse_stream_line(line: &str) -> Result<Option<String>> {

impl LlmClient for OllamaClient {
fn validate_model(&self) -> Result<()> {
let url = self.tags_url();
let resp = self
.http
.get(&url)
.send()
.map_err(|e| anyhow!("Error calling Ollama at {url}: {e}"))?;

if resp.status() != StatusCode::OK {
let status = resp.status();
let body = resp.text().unwrap_or_default();
return Err(anyhow!(
"Ollama model validation failed at {url}: HTTP {} - {}",
status.as_u16(),
body
));
}

let body = resp
.text()
.map_err(|e| anyhow!("Failed to read Ollama tags response from {url}: {e}"))?;
let parsed: OllamaTagsResponse = json::from_str(&body)
.map_err(|e| anyhow!("Failed to decode Ollama tags response from {url}: {e}"))?;

if parsed.models.iter().any(|model| model.name == self.model) {
return Ok(());
}

let available = parsed
.models
.iter()
.map(|model| model.name.as_str())
.collect::<Vec<_>>()
.join(", ");

Err(anyhow!(
"Model {:?} was not found at {}. Available models: {}",
self.model,
url,
if available.is_empty() {
"<none>"
} else {
&available
}
))
// Skipping model validation for Ollama; use a future "list models" command
// to query /api/tags if the user requests it.
Ok(())
}

fn summarize_file(
Expand Down Expand Up @@ -309,19 +273,19 @@ mod tests {

#[test]
fn trims_trailing_slash_in_tags_url() {
let client = OllamaClient::new("http://localhost:11434/", "qwen3-coder:30b", false);
let client = OllamaClient::new("http://localhost:11434/", "gemma4:31b", false, 90);
assert_eq!(client.tags_url(), "http://localhost:11434/api/tags");
}

#[test]
fn decodes_ollama_tags_payload() {
let body = r#"{"models":[{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#;
let body = r#"{"models":[{"name":"gemma4:31b"},{"name":"qwen3-coder:30b"},{"name":"gpt-oss:20b"}]}"#;
let parsed: OllamaTagsResponse = json::from_str(body).expect("valid tags payload");

assert!(parsed
.models
.iter()
.any(|model| model.name == "qwen3-coder:30b"));
.any(|model| model.name == "gemma4:31b"));
assert!(!parsed
.models
.iter()
Expand Down
13 changes: 10 additions & 3 deletions src/llm/openai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ struct TokenUsage {
}

impl OpenAiClient {
pub fn new(api_key: String, model: String, api_base_url: String, stream: bool) -> Self {
pub fn new(api_key: String, model: String, api_base_url: String, stream: bool, timeout_secs: u64) -> Self {
let client = Client::builder()
.timeout(Duration::from_secs(90))
.timeout(Duration::from_secs(timeout_secs))
.build()
.expect("failed to build HTTP client");

Expand Down Expand Up @@ -122,6 +122,7 @@ impl OpenAiClient {

log::info!("Calling OpenAI model {:?}", &req.model);

let t0 = std::time::Instant::now();
let resp = self
.client
.post(url)
Expand All @@ -141,6 +142,7 @@ impl OpenAiClient {
}

let chat_resp: ChatResponse = resp.json().context("failed to parse OpenAI response")?;
log::debug!("OpenAI response time: {:.2?}", t0.elapsed());
let content = chat_resp
.choices
.first()
Expand All @@ -164,6 +166,7 @@ impl OpenAiClient {

log::info!("Streaming OpenAI model {:?}", &req.model);

let t0 = std::time::Instant::now();
let resp = self
.client
.post(url)
Expand All @@ -183,7 +186,9 @@ impl OpenAiClient {
}

let reader = BufReader::new(resp);
read_stream_to_string(reader, parse_stream_line)
let result = read_stream_to_string(reader, parse_stream_line);
log::debug!("OpenAI streaming response time: {:.2?}", t0.elapsed());
result
}
}

Expand Down Expand Up @@ -401,6 +406,7 @@ mod tests {
"gpt-5-nano".into(),
"https://api.openai.com".into(),
false,
90,
);

assert_eq!(
Expand All @@ -416,6 +422,7 @@ mod tests {
"gpt-5-nano".into(),
"https://api.openai.com/v1".into(),
false,
90,
);

assert_eq!(
Expand Down
Loading
Loading