diff --git a/neurosploit-rs/crates/harness/src/budget.rs b/neurosploit-rs/crates/harness/src/budget.rs index 8a16e38..98990fc 100644 --- a/neurosploit-rs/crates/harness/src/budget.rs +++ b/neurosploit-rs/crates/harness/src/budget.rs @@ -425,6 +425,19 @@ impl ModelPricing { /// Look up pricing for a model id. Falls back to a conservative default /// (Sonnet-class pricing) for unknown models. pub fn pricing_for(model_id: &str) -> ModelPricing { + // A custom provider's declared price wins: the table below guesses from + // the model name, and a private gateway's name says nothing about what the + // operator is billed. Priced as `provider:model`, which is how the pool + // labels a completion. + if let Some((provider, _)) = model_id.split_once(':') { + let base = crate::custom_providers::install_base(); + if let Some(c) = crate::custom_providers::profile(&base, provider) { + if c.has_pricing() { + return ModelPricing::new(c.price_input, c.price_output, c.price_cache_read); + } + } + } + let low = model_id.to_ascii_lowercase(); // Anthropic if low.contains("opus") { diff --git a/neurosploit-rs/crates/harness/src/custom_providers.rs b/neurosploit-rs/crates/harness/src/custom_providers.rs index 5fbb0ef..847a8d4 100644 --- a/neurosploit-rs/crates/harness/src/custom_providers.rs +++ b/neurosploit-rs/crates/harness/src/custom_providers.rs @@ -21,19 +21,132 @@ //! a stale registry entry exists. use crate::models::Provider; +use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock}; +/// Everything an operator can configure about a provider without a rebuild. +/// +/// The registry began as `{name: base_url}`. That covers an endpoint speaking +/// plain OpenAI over a direct connection, which is most of them and none of the +/// awkward ones: a gateway that wants its own session header, an endpoint only +/// reachable through a SOCKS proxy, a model whose price the cost ledger cannot +/// know, a tenant with a rate limit far below the provider's published one. +/// +/// Every field here changes behaviour. Nothing is stored for display. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CustomProvider { + /// Endpoint root. The wire path (`/chat/completions`) is appended. + pub base_url: String, + + /// Wire format: `openai` (default) or `anthropic`. + #[serde(default = "default_format")] + pub format: String, + + /// Models to offer in pickers. Empty means the operator types the id, which + /// always works — this list is a convenience, not a constraint. + #[serde(default)] + pub models: Vec, + + /// Egress proxy for this provider only: `socks5://[user:pass@]host:port` + /// or `http://host:port`. + #[serde(default)] + pub proxy: String, + + /// Header name to carry a stable per-session id, for gateways that pin + /// prompt-cache routing on one. Empty sends nothing. + #[serde(default)] + pub session_header: String, + + /// Overrides User-Agent on requests to this provider. + #[serde(default)] + pub user_agent: String, + + /// Requests per second, and per minute. 0 means unlimited. + #[serde(default)] + pub rps: f64, + #[serde(default)] + pub rpm: f64, + + /// Context window in thousands of tokens. 0 takes the global default. + #[serde(default)] + pub context_k: u32, + + /// USD per million tokens, so the cost ledger can account for a model it + /// has no built-in price for. + #[serde(default)] + pub price_input: f64, + #[serde(default)] + pub price_output: f64, + #[serde(default)] + pub price_cache_read: f64, + #[serde(default)] + pub price_cache_write: f64, +} + +fn default_format() -> String { "openai".to_string() } + +impl Default for CustomProvider { + fn default() -> Self { + Self { + base_url: String::new(), + format: default_format(), + models: Vec::new(), + proxy: String::new(), + session_header: String::new(), + user_agent: String::new(), + rps: 0.0, + rpm: 0.0, + context_k: 0, + price_input: 0.0, + price_output: 0.0, + price_cache_read: 0.0, + price_cache_write: 0.0, + } + } +} + +impl CustomProvider { + pub fn from_base_url(url: &str) -> Self { + Self { base_url: url.trim().trim_end_matches('/').to_string(), ..Default::default() } + } + + /// Whether the cost ledger has a price to work with. + pub fn has_pricing(&self) -> bool { + self.price_input > 0.0 || self.price_output > 0.0 + } +} + +/// A registry entry, which is either the original bare base-url string or a +/// full profile. Entries written before profiles existed stay readable, and an +/// operator who only needs a URL can still keep one in the file by hand. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +enum Entry { + Url(String), + Profile(CustomProvider), +} + +impl From for CustomProvider { + fn from(e: Entry) -> Self { + match e { + Entry::Url(u) => CustomProvider::from_base_url(&u), + Entry::Profile(p) => p, + } + } +} + fn registry_path(base: &Path) -> PathBuf { base.join(".neurosploit").join("custom_providers.json") } -fn read(base: &Path) -> BTreeMap { - std::fs::read_to_string(registry_path(base)) +fn read(base: &Path) -> BTreeMap { + let raw: BTreeMap = std::fs::read_to_string(registry_path(base)) .ok() .and_then(|s| serde_json::from_str(&s).ok()) - .unwrap_or_default() + .unwrap_or_default(); + raw.into_iter().map(|(k, v)| (k, v.into())).collect() } /// A provider's display name, as a legal name component (`[a-z0-9_-]+`, @@ -62,7 +175,11 @@ pub fn register(base: &Path, name: &str, base_url: &str) -> Result std::io::Result { } pub fn list(base: &Path) -> BTreeMap { + read(base).into_iter().map(|(k, v)| (k, v.base_url)).collect() +} + +/// Every registered provider with its full profile. +pub fn list_profiles(base: &Path) -> BTreeMap { read(base) } +/// One provider's profile, or `None` when the name is not registered. +pub fn profile(base: &Path, name: &str) -> Option { + read(base).remove(&sanitize_name(name)) +} + +/// Store a complete profile, replacing whatever was there. +/// +/// The same name rules as [`register`] apply: sanitized, non-empty, and never +/// shadowing a built-in provider. +pub fn save_profile(base: &Path, name: &str, prof: CustomProvider) -> Result { + let name = sanitize_name(name); + if name.is_empty() { + return Err("empty provider name".into()); + } + if prof.base_url.trim().is_empty() { + return Err("base URL is required".into()); + } + if crate::models::provider_for(&name).is_some() && !read(base).contains_key(&name) { + return Err(format!("'{name}' is already a built-in provider — pick a different name")); + } + if !prof.proxy.trim().is_empty() { + let pr = prof.proxy.trim(); + if !(pr.starts_with("socks5://") || pr.starts_with("http://") || pr.starts_with("https://")) { + return Err("proxy must start with socks5://, http:// or https://".into()); + } + } + if !matches!(prof.format.as_str(), "openai" | "anthropic") { + return Err(format!("unknown wire format '{}' — use openai or anthropic", prof.format)); + } + + let mut prof = prof; + prof.base_url = prof.base_url.trim().trim_end_matches('/').to_string(); + + let mut m = read(base); + m.insert(name.clone(), prof); + let path = registry_path(base); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; + } + let body = serde_json::to_string_pretty(&m).map_err(|e| e.to_string())?; + std::fs::write(&path, body).map_err(|e| e.to_string())?; + // A profile's proxy, headers and models all feed the cached Provider. + invalidate_cache(&name); + Ok(name) +} + +fn invalidate_cache(name: &str) { + if let Some(c) = CACHE.get() { + if let Ok(mut g) = c.lock() { + g.remove(name); + } + } +} + /// Build a usable [`Provider`] for a registered custom name, or `None` when it /// isn't registered. Every `&'static str` field is leaked once per distinct /// name/base_url pair in a process's life — bounded by how many custom /// providers an operator configures, not by call volume. pub fn provider_for(base: &Path, name: &str) -> Option { let name = sanitize_name(name); - let url = read(base).get(&name)?.clone(); - Some(synthesize(&name, &url)) + let prof = read(base).remove(&name)?; + Some(synthesize_profile(&name, &prof)) } pub fn synthesize(name: &str, base_url: &str) -> Provider { + synthesize_profile(name, &CustomProvider::from_base_url(base_url)) +} + +pub fn synthesize_profile(name: &str, prof: &CustomProvider) -> Provider { let leak = |s: String| -> &'static str { Box::leak(s.into_boxed_str()) }; Provider { key: leak(name.to_string()), label: leak(format!("Custom: {name}")), - base_url: leak(base_url.trim_end_matches('/').to_string()), + base_url: leak(prof.base_url.trim_end_matches('/').to_string()), env_key: leak(format!("NEUROSPLOIT_CUSTOM_{}_API_KEY", name.to_ascii_uppercase())), kind: "api", - models: Vec::new(), + models: prof.models.iter().map(|m| leak(m.clone())).collect(), } } @@ -204,3 +384,122 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } } + +#[cfg(test)] +mod profile_tests { + use super::*; + + fn tmp() -> PathBuf { + let d = std::env::temp_dir().join(format!( + "ns-cp-{:x}", + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) + .map(|t| t.as_nanos()).unwrap_or(0), + )); + std::fs::create_dir_all(d.join(".neurosploit")).unwrap(); + d + } + + /// Registries written before profiles existed hold a bare URL string. They + /// must keep working, or an upgrade silently loses every provider. + #[test] + fn a_bare_url_registry_still_loads() { + let base = tmp(); + std::fs::write( + registry_path(&base), + r#"{"mycorp": "https://api.mycorp.test/v1"}"#, + ).unwrap(); + + let prof = profile(&base, "mycorp").expect("legacy entry did not load"); + assert_eq!(prof.base_url, "https://api.mycorp.test/v1"); + assert_eq!(prof.format, "openai", "legacy entry should default to openai"); + assert!(!prof.has_pricing()); + } + + /// Editing the URL from the CLI must not drop a profile set in the UI. + #[test] + fn registering_a_url_keeps_the_rest_of_the_profile() { + let base = tmp(); + save_profile(&base, "gw", CustomProvider { + base_url: "https://old.test/v1".into(), + proxy: "socks5://127.0.0.1:1080".into(), + price_input: 1.5, + price_output: 6.0, + ..Default::default() + }).unwrap(); + + register(&base, "gw", "https://new.test/v1").unwrap(); + + let prof = profile(&base, "gw").unwrap(); + assert_eq!(prof.base_url, "https://new.test/v1"); + assert_eq!(prof.proxy, "socks5://127.0.0.1:1080", "proxy was dropped"); + assert_eq!(prof.price_input, 1.5, "pricing was dropped"); + } + + #[test] + fn a_profile_round_trips() { + let base = tmp(); + let want = CustomProvider { + base_url: "https://gw.test/v1".into(), + format: "openai".into(), + models: vec!["m-1".into(), "m-2".into()], + proxy: "http://127.0.0.1:8080".into(), + session_header: "x-session-id".into(), + user_agent: "ns/1.0".into(), + rps: 2.0, rpm: 60.0, context_k: 200, + price_input: 0.5, price_output: 1.5, + price_cache_read: 0.05, price_cache_write: 0.6, + }; + save_profile(&base, "gw", want.clone()).unwrap(); + + let got = profile(&base, "gw").unwrap(); + assert_eq!(got.models, want.models); + assert_eq!(got.session_header, "x-session-id"); + assert_eq!(got.context_k, 200); + assert_eq!(got.price_cache_write, 0.6); + + // And it must reach the pool as a usable Provider. + let p = provider_for(&base, "gw").unwrap(); + assert_eq!(p.base_url, "https://gw.test/v1"); + assert_eq!(p.models.len(), 2, "declared models did not reach the Provider"); + } + + /// A proxy that cannot be parsed must be refused at save time, not + /// discovered as a silent direct connection during an engagement. + #[test] + fn a_malformed_proxy_is_refused() { + let base = tmp(); + let e = save_profile(&base, "gw", CustomProvider { + base_url: "https://gw.test/v1".into(), + proxy: "127.0.0.1:1080".into(), + ..Default::default() + }).unwrap_err(); + assert!(e.contains("socks5://"), "unhelpful error: {e}"); + } + + #[test] + fn an_unknown_wire_format_is_refused() { + let base = tmp(); + let e = save_profile(&base, "gw", CustomProvider { + base_url: "https://gw.test/v1".into(), + format: "grpc".into(), + ..Default::default() + }).unwrap_err(); + assert!(e.contains("openai"), "unhelpful error: {e}"); + } + + #[test] + fn a_profile_cannot_shadow_a_built_in_provider() { + let base = tmp(); + let e = save_profile(&base, "anthropic", CustomProvider { + base_url: "https://evil.test/v1".into(), + ..Default::default() + }).unwrap_err(); + assert!(e.contains("built-in"), "unhelpful error: {e}"); + } + + #[test] + fn a_profile_without_a_base_url_is_refused() { + let base = tmp(); + assert!(save_profile(&base, "gw", CustomProvider::default()).is_err()); + } +} diff --git a/neurosploit-rs/crates/harness/src/models.rs b/neurosploit-rs/crates/harness/src/models.rs index c9a47a1..c60a66b 100644 --- a/neurosploit-rs/crates/harness/src/models.rs +++ b/neurosploit-rs/crates/harness/src/models.rs @@ -206,6 +206,60 @@ fn http_timeout_secs() -> u64 { .unwrap_or(300) } +/// Per-provider HTTP clients, for the custom providers that need their own +/// egress route or User-Agent. Built once per provider and reused: a reqwest +/// Client owns a connection pool, so building one per request would open a new +/// connection every time. +fn client_for(name: &str, prof: &crate::custom_providers::CustomProvider) -> reqwest::Client { + use std::sync::{Mutex, OnceLock}; + static CLIENTS: OnceLock>> = + OnceLock::new(); + let cache = CLIENTS.get_or_init(|| Mutex::new(std::collections::HashMap::new())); + + // Key on the settings, not just the name, so editing a profile takes effect + // without a restart. + let key = format!("{name}|{}|{}", prof.proxy, prof.user_agent); + if let Ok(g) = cache.lock() { + if let Some(c) = g.get(&key) { + return c.clone(); + } + } + + let mut b = reqwest::Client::builder().timeout(Duration::from_secs(http_timeout_secs())); + if !prof.proxy.trim().is_empty() { + match reqwest::Proxy::all(prof.proxy.trim()) { + Ok(p) => b = b.proxy(p), + // A misconfigured proxy must not silently become a direct + // connection: that is the one outcome an operator routing through + // a proxy cannot afford. + Err(e) => { + eprintln!(" [!] provider '{name}': proxy '{}' rejected ({e}) — refusing to fall back to a direct connection", prof.proxy); + b = b.proxy(reqwest::Proxy::all("http://127.0.0.1:1").unwrap()); + } + } + } + if !prof.user_agent.trim().is_empty() { + b = b.user_agent(prof.user_agent.trim()); + } + let client = b.build().unwrap_or_else(|_| reqwest::Client::new()); + if let Ok(mut g) = cache.lock() { + g.insert(key, client.clone()); + } + client +} + +/// A stable id for this process, for `session_header`. +fn session_id() -> &'static str { + use std::sync::OnceLock; + static ID: OnceLock = OnceLock::new(); + ID.get_or_init(|| { + format!("ns-{:x}", std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0)) + }) +} + impl ChatClient { pub fn new() -> Self { let http = reqwest::Client::builder() @@ -273,10 +327,29 @@ impl ChatClient { {"role": "user", "content": user} ] }); - let mut req = self.http.post(&url).json(&body); + // A custom provider may need its own egress route or headers, so it + // gets its own client. Built-ins share the one on self. + let prof = crate::custom_providers::profile( + &crate::custom_providers::install_base(), &m.provider, + ); + let http = match prof.as_ref() { + Some(c) if !c.proxy.trim().is_empty() || !c.user_agent.trim().is_empty() => { + client_for(&m.provider, c) + } + _ => self.http.clone(), + }; + + let mut req = http.post(&url).json(&body); if !key.is_empty() { if azure { req = req.header("api-key", &key); } else { req = req.bearer_auth(&key); } } + // Gateways that pin prompt-cache routing on a session id want it stable + // across a run and distinct between runs. + if let Some(c) = prof.as_ref() { + if !c.session_header.trim().is_empty() { + req = req.header(c.session_header.trim(), session_id()); + } + } let resp = req.send().await.map_err(|e| { if e.is_connect() { let local = matches!(p.key, "ollama" | "litellm" | "llamacpp");