Craft Anything: understand how any software works, and craft your own.
Rust
A remote OpenAI-compatible service gets the cloud context budget and its price, not a local model's (R2.1) (#379)
Agapenor3861132c0486
diff --git a/crates/ai/src/detect.rs b/crates/ai/src/detect.rsindex 98662223..81aa43b5 100644--- a/crates/ai/src/detect.rs+++ b/crates/ai/src/detect.rs@@ -134,8 +134,13 @@ pub fn opencode_servers(text: &str) -> Vec<(String, String)> {.collect()}-/// An http(s) address on this computer or its local network.-fn on_this_network(url: &str) -> bool {+/// Name endings kept for local networks, which public DNS never answers.+const LAN_SUFFIXES: &[&str] = &[".local", ".lan", ".home.arpa", ".internal"];++/// An http(s) address on this computer or its local network: a private or loopback IP, or a name+/// that only a local network can answer (`localhost`, a bare name such as Docker's `ollama`, or a+/// [`LAN_SUFFIXES`] name). Nothing is looked up.+pub(crate) fn on_this_network(url: &str) -> bool {let Some(rest) = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://")) else { return false };let host = rest.split('/').next().unwrap_or_default();// `[::1]:1234`, `127.0.0.1:1234` or `name:1234`.@@ -145,8 +150,11 @@ fn on_this_network(url: &str) -> bool {};match host.parse::<std::net::IpAddr>() {Ok(std::net::IpAddr::V4(ip)) => ip.is_loopback() || ip.is_private() || ip.is_link_local(),- Ok(std::net::IpAddr::V6(ip)) => ip.is_loopback() || ip.is_unique_local(),- Err(_) => host.eq_ignore_ascii_case("localhost") || host.to_ascii_lowercase().ends_with(".local"),+ Ok(std::net::IpAddr::V6(ip)) => ip.is_loopback() || ip.is_unique_local() || ip.is_unicast_link_local(),+ Err(_) => {+ let host = host.to_ascii_lowercase();+ !host.is_empty() && (!host.contains('.') || LAN_SUFFIXES.iter().any(|s| host.ends_with(s)))+ }}}@@ -309,13 +317,28 @@ mod tests {"http://localhost:1234/v1","http://127.0.0.1/v1","http://[::1]:8080",+ "http://[fe80::1]:11434/v1","http://10.0.0.5:8000/v1","https://studio.local:1234/v1","http://172.20.0.2:1234",+ "http://ollama:11434/v1",+ "http://GPU-Box:8000",+ "http://gpu.lan:1234/v1",+ "http://studio.home.arpa/v1",+ "http://llm.internal:8080",] {assert!(on_this_network(url), "{url}");}- for url in ["https://api.openai.com/v1", "http://8.8.8.8/v1", "ftp://127.0.0.1", "127.0.0.1:1234", ""] {+ for url in [+ "https://api.openai.com/v1",+ "http://8.8.8.8/v1",+ "ftp://127.0.0.1",+ "127.0.0.1:1234",+ "",+ "http://",+ "https://lan.example.com",+ "https://internal.example.com/v1",+ ] {assert!(!on_this_network(url), "{url}");}}diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex ab1c27cd..81a2981c 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -558,6 +558,10 @@ impl AiHub {_ => None,};let base = tunneled_base.as_deref().or(base);+ // A server on this computer or its network (Ollama, LM Studio, one reached over ssh) costs+ // nothing and gets the small context budget; a remote OpenAI-compatible service has a+ // large context and a bill, as any other cloud API (#374).+ let local = c.kind == BackendKind::OpenaiCompatible && base.is_none_or(detect::on_this_network);let model: Box<dyn ChatModel> = match c.kind {BackendKind::Anthropic => {let mut a = anthropic::Anthropic::new(base, self.key_for(e)?, &c.model);@@ -577,13 +581,7 @@ impl AiHub {Some(t) => Box::new(Tunneled { inner: model, _tunnel: t }) as Box<dyn ChatModel>,None => model,};- Ok(ModelSlot {- name: c.name.clone(),- model,- local: c.kind == BackendKind::OpenaiCompatible,- effort: e.options.effort,- max_turns: e.options.max_turns.unwrap_or(agent::DEFAULT_MAX_TURNS),- })+ Ok(ModelSlot { name: c.name.clone(), model, local, effort: e.options.effort, max_turns: e.options.max_turns.unwrap_or(agent::DEFAULT_MAX_TURNS) })}fn project_root(&self) -> Option<PathBuf> {diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex 25203fa8..ecb66aea 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -275,6 +275,33 @@ fn a_server_is_added_by_its_address() {assert_eq!(h.backends().len(), 2, "only the ones that answered");}+/// #374: a remote OpenAI-compatible service was treated as a local model: a 24K-token context+/// and a cost of nothing. Only a server on this computer or its network is local.+#[test]+fn only_an_openai_compatible_server_nearby_is_local() {+ let (h, _d) = hub();+ for (name, base, local) in [+ ("Ollama", "http://127.0.0.1:11434/v1", true),+ ("LM Studio box", "http://192.168.1.20:1234/v1", true),+ ("Docker Ollama", "http://ollama:11434/v1", true),+ ("IPv6 link-local", "http://[fe80::1]:11434/v1", true),+ ("Z.ai", "https://api.z.ai/api/coding/paas/v4", false),+ ("Public vLLM", "http://8.8.8.8:8000/v1", false),+ ] {+ add(&h, name, BackendKind::OpenaiCompatible, base, None);+ let slot = h.build_model(&h.entry(name).unwrap()).unwrap();+ assert_eq!(slot.local, local, "{name} at {base}");+ }+ h.add_backend(+ BackendConfig { name: "Default".into(), kind: BackendKind::OpenaiCompatible, model: String::new(), base_url: None, ssh_host: None, enabled: true },+ None,+ )+ .unwrap();+ assert!(h.build_model(&h.entry("Default").unwrap()).unwrap().local, "no address means Ollama on this computer");+ add(&h, "OpenAI", BackendKind::Openai, "http://127.0.0.1:9/v1", Some("sk-test"));+ assert!(!h.build_model(&h.entry("OpenAI").unwrap()).unwrap().local, "only OpenAI-compatible servers can be local");+}+fn add(h: &AiHub, name: &str, kind: BackendKind, base: &str, key: Option<&str>) {h.add_backend(BackendConfig { name: name.into(), kind, model: String::new(), base_url: Some(base.into()), ssh_host: None, enabled: true },diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex b40aa2c5..7b9a4b06 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -513,6 +513,10 @@ Owner: maintainers · Status: in progress (built; live runs need keys)24k for local models, `LoopConfig::context_tokens`) old tool results are trimmed, then theoldest part is replaced by a summary the model writes; the conversation is kept in`transcript.json` after every step and a follow-up resumes it+- [x] Only an OpenAI-compatible server on this computer or its network counts as local (24k+ context, no cost); a remote one gets the cloud budget and its price (#374)+- [ ] A per-backend context budget in `[[ai.backends]]` (`LoopConfig::context_tokens` exists), for+ services whose real window differs from 150k (#374)### R2.2 More coding agentsOwner: open · Status: in progress