use std::net::SocketAddr;
use std::path::{Path, PathBuf};
pub mod chat;
pub mod claude_config;
pub mod project_discovery;
pub mod log_buffer;
pub mod sys_metrics;
#[cfg(target_os = "macos")]
pub mod launchd;
#[cfg(feature = "axum-server")]
pub mod server;
#[cfg(feature = "mcp")]
pub mod mcp;
#[cfg(feature = "rpc")]
pub mod rpc;
#[cfg(feature = "embedder")]
pub mod embedder;
#[cfg(feature = "symgraph")]
pub mod symgraph;
#[cfg(feature = "memory-core")]
pub mod memory_core;
#[cfg(feature = "monitor-tui")]
pub mod monitor;
pub use chat::{
ChatEvent, ChatProvider, LocalModelConfig, OllamaProvider, OpenRouterProvider, ToolCall,
ToolDef, auto_detect_local_provider,
};
use anyhow::{Context, Result, anyhow};
use serde::{Deserialize, Serialize};
use tokio::net::TcpListener;
pub async fn bind_with_auto_port(addr: SocketAddr, max_attempts: u16) -> Result<TcpListener> {
use std::io::ErrorKind;
let mut current = addr;
for attempt in 0..=max_attempts {
match TcpListener::bind(current).await {
Ok(l) => return Ok(l),
Err(e) if e.kind() == ErrorKind::AddrInUse && attempt < max_attempts => {
let next_port = current.port().saturating_add(1);
if next_port == 0 {
anyhow::bail!("ran out of ports while searching for free slot");
}
tracing::warn!("port {} in use, trying {}", current.port(), next_port);
current.set_port(next_port);
}
Err(e) => return Err(e.into()),
}
}
anyhow::bail!("could not find free port after {max_attempts} attempts")
}
pub const DATA_DIR_OVERRIDE_ENV: &str = "TRUSTY_DATA_DIR_OVERRIDE";
pub fn resolve_data_dir(app_name: &str) -> Result<PathBuf> {
let base = if let Ok(override_dir) = std::env::var(DATA_DIR_OVERRIDE_ENV) {
PathBuf::from(override_dir)
} else {
dirs::data_dir()
.or_else(|| dirs::home_dir().map(|h| h.join(format!(".{app_name}"))))
.context("could not resolve data directory or home directory")?
};
let dir = if base.ends_with(format!(".{app_name}")) {
base
} else {
base.join(app_name)
};
std::fs::create_dir_all(&dir)
.with_context(|| format!("create data directory {}", dir.display()))?;
Ok(dir)
}
const DAEMON_ADDR_FILENAME: &str = "http_addr";
pub fn write_daemon_addr(app_name: &str, addr: &str) -> Result<()> {
let dir = resolve_data_dir(app_name)?;
let path = dir.join(DAEMON_ADDR_FILENAME);
std::fs::write(&path, addr).with_context(|| format!("write daemon addr to {}", path.display()))
}
pub fn read_daemon_addr(app_name: &str) -> Result<Option<String>> {
let dir = resolve_data_dir(app_name)?;
let path = dir.join(DAEMON_ADDR_FILENAME);
match std::fs::read_to_string(&path) {
Ok(s) => Ok(Some(s.trim().to_string())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(anyhow::Error::new(e))
.with_context(|| format!("read daemon addr from {}", path.display())),
}
}
pub fn init_tracing(verbose_count: u8) {
let default_filter = match verbose_count {
0 => "warn",
1 => "info",
2 => "debug",
_ => "trace",
};
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_filter));
let _ = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_writer(std::io::stderr)
.with_target(false)
.try_init();
}
#[must_use]
pub fn init_tracing_with_buffer(verbose_count: u8, capacity: usize) -> log_buffer::LogBuffer {
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let default_filter = match verbose_count {
0 => "warn",
1 => "info",
2 => "debug",
_ => "trace",
};
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_filter));
let buffer = log_buffer::LogBuffer::new(capacity);
let fmt_layer = tracing_subscriber::fmt::layer()
.with_writer(std::io::stderr)
.with_target(false);
let _ = tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.with(log_buffer::LogBufferLayer::new(buffer.clone()))
.try_init();
buffer
}
pub fn maybe_disable_color(no_color: bool) {
let env_says_no =
std::env::var("NO_COLOR").is_ok() || std::env::var("TERM").as_deref() == Ok("dumb");
if no_color || env_says_no {
colored::control::set_override(false);
}
}
const OPENROUTER_URL: &str = "https://openrouter.ai/api/v1/chat/completions";
const HTTP_REFERER: &str = "https://github.com/bobmatnyc/trusty-common";
const X_TITLE: &str = "trusty-common";
const OPENROUTER_CONNECT_TIMEOUT_SECS: u64 = 10;
const OPENROUTER_REQUEST_TIMEOUT_SECS: u64 = 120;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChatMessage {
pub role: String,
pub content: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub tool_call_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub tool_calls: Option<Vec<serde_json::Value>>,
}
#[derive(Debug, Serialize)]
struct ChatRequest<'a> {
model: &'a str,
messages: &'a [ChatMessage],
stream: bool,
}
#[derive(Debug, Deserialize)]
struct ChatResponse {
choices: Vec<Choice>,
}
#[derive(Debug, Deserialize)]
struct Choice {
message: ResponseMessage,
}
#[derive(Debug, Deserialize)]
struct ResponseMessage {
#[serde(default)]
content: String,
}
#[deprecated(since = "0.3.1", note = "Use OpenRouterProvider::chat_stream instead")]
pub async fn openrouter_chat(
api_key: &str,
model: &str,
messages: Vec<ChatMessage>,
) -> Result<String> {
if api_key.is_empty() {
return Err(anyhow!("openrouter api key is empty"));
}
let client = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(
OPENROUTER_CONNECT_TIMEOUT_SECS,
))
.timeout(std::time::Duration::from_secs(
OPENROUTER_REQUEST_TIMEOUT_SECS,
))
.build()
.context("build reqwest client for openrouter_chat")?;
let body = ChatRequest {
model,
messages: &messages,
stream: false,
};
let resp = client
.post(OPENROUTER_URL)
.bearer_auth(api_key)
.header("HTTP-Referer", HTTP_REFERER)
.header("X-Title", X_TITLE)
.json(&body)
.send()
.await
.context("POST openrouter chat completions")?;
let status = resp.status();
if !status.is_success() {
let text = resp.text().await.unwrap_or_default();
return Err(anyhow!("openrouter HTTP {status}: {text}"));
}
let payload: ChatResponse = resp.json().await.context("decode openrouter response")?;
payload
.choices
.into_iter()
.next()
.map(|c| c.message.content)
.ok_or_else(|| anyhow!("openrouter returned no choices"))
}
#[deprecated(since = "0.3.1", note = "Use OpenRouterProvider::chat_stream instead")]
pub async fn openrouter_chat_stream(
api_key: &str,
model: &str,
messages: Vec<ChatMessage>,
tx: tokio::sync::mpsc::Sender<String>,
) -> Result<()> {
use futures_util::StreamExt;
if api_key.is_empty() {
return Err(anyhow!("openrouter api key is empty"));
}
let client = reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(
OPENROUTER_CONNECT_TIMEOUT_SECS,
))
.timeout(std::time::Duration::from_secs(
OPENROUTER_REQUEST_TIMEOUT_SECS,
))
.build()
.context("build reqwest client for openrouter_chat_stream")?;
let body = ChatRequest {
model,
messages: &messages,
stream: true,
};
let resp = client
.post(OPENROUTER_URL)
.bearer_auth(api_key)
.header("HTTP-Referer", HTTP_REFERER)
.header("X-Title", X_TITLE)
.json(&body)
.send()
.await
.context("POST openrouter chat completions (stream)")?;
let status = resp.status();
if !status.is_success() {
let text = resp.text().await.unwrap_or_default();
return Err(anyhow!("openrouter HTTP {status}: {text}"));
}
let mut buf = String::new();
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let bytes = chunk.context("read openrouter stream chunk")?;
let text = match std::str::from_utf8(&bytes) {
Ok(s) => s,
Err(_) => continue,
};
buf.push_str(text);
while let Some(idx) = buf.find('\n') {
let line: String = buf.drain(..=idx).collect();
let line = line.trim();
let Some(payload) = line.strip_prefix("data:").map(str::trim) else {
continue;
};
if payload.is_empty() || payload == "[DONE]" {
continue;
}
let v: serde_json::Value = match serde_json::from_str(payload) {
Ok(v) => v,
Err(_) => continue,
};
if let Some(delta) = v
.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("delta"))
.and_then(|d| d.get("content"))
.and_then(|c| c.as_str())
&& !delta.is_empty()
&& tx.send(delta.to_string()).await.is_err()
{
return Ok(());
}
}
}
Ok(())
}
pub fn is_dir(path: &Path) -> bool {
path.metadata().map(|m| m.is_dir()).unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
#[tokio::test]
async fn auto_port_walks_forward() {
let occupied = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = occupied.local_addr().unwrap().port();
let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
let next = bind_with_auto_port(addr, 8).await.unwrap();
let got = next.local_addr().unwrap().port();
assert_ne!(got, port, "expected walk-forward to a different port");
}
#[tokio::test]
async fn auto_port_zero_attempts_still_binds_free() {
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let l = bind_with_auto_port(addr, 0).await.unwrap();
assert!(l.local_addr().unwrap().port() > 0);
}
#[test]
fn resolve_data_dir_creates_directory() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile_like_dir();
unsafe {
std::env::set_var(DATA_DIR_OVERRIDE_ENV, &tmp);
}
let dir = resolve_data_dir("trusty-test-xyz").unwrap();
assert!(
dir.exists(),
"data dir should be created at {}",
dir.display()
);
assert!(dir.is_dir());
assert!(
dir.starts_with(&tmp),
"data dir {} should live under override {}",
dir.display(),
tmp.display()
);
unsafe {
std::env::remove_var(DATA_DIR_OVERRIDE_ENV);
}
}
#[test]
fn daemon_addr_round_trips() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile_like_dir();
unsafe {
std::env::set_var(DATA_DIR_OVERRIDE_ENV, &tmp);
}
let app = format!(
"trusty-test-daemon-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
);
write_daemon_addr(&app, "127.0.0.1:12345").unwrap();
let got = read_daemon_addr(&app).unwrap();
unsafe {
std::env::remove_var(DATA_DIR_OVERRIDE_ENV);
}
assert_eq!(got.as_deref(), Some("127.0.0.1:12345"));
}
#[test]
fn read_daemon_addr_missing_returns_none() {
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let tmp = tempfile_like_dir();
unsafe {
std::env::set_var(DATA_DIR_OVERRIDE_ENV, &tmp);
}
let app = format!(
"trusty-test-daemon-missing-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0)
);
let got = read_daemon_addr(&app).unwrap();
unsafe {
std::env::remove_var(DATA_DIR_OVERRIDE_ENV);
}
assert!(got.is_none(), "expected None when file absent, got {got:?}");
}
#[test]
fn is_dir_recognises_directories() {
let tmp = tempfile_like_dir();
assert!(is_dir(&tmp));
assert!(!is_dir(&tmp.join("nope")));
}
#[test]
fn chat_message_round_trips() {
let m = ChatMessage {
role: "user".into(),
content: "hello".into(),
tool_call_id: None,
tool_calls: None,
};
let s = serde_json::to_string(&m).unwrap();
let back: ChatMessage = serde_json::from_str(&s).unwrap();
assert_eq!(back.role, "user");
assert_eq!(back.content, "hello");
}
#[tokio::test]
#[allow(deprecated)]
async fn openrouter_chat_rejects_empty_key() {
let err = openrouter_chat("", "x", vec![]).await.unwrap_err();
assert!(err.to_string().contains("api key"));
}
fn tempfile_like_dir() -> PathBuf {
let pid = std::process::id();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let p = std::env::temp_dir().join(format!("trusty-common-test-{pid}-{nanos}"));
std::fs::create_dir_all(&p).unwrap();
p
}
}