1pub mod endpoint;
25pub mod netchange;
26pub mod probe;
27pub mod tracker;
28
29use std::sync::{Arc, LazyLock, Mutex, OnceLock};
30
31use serde::Serialize;
32use tokio::sync::Notify;
33
34use crate::backend::eventbus::EventBus;
35use tracker::Tracker;
36
37pub const EVENT_CONNECTIVITY_CHANGED: &str = "connectivity:changed";
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, ts_rs::TS)]
42#[serde(rename_all = "snake_case")]
43#[ts(export, export_to = "../../../frontend/types/rpc/")]
44pub enum Reachability {
45 Online,
46 Degraded,
48 Offline,
50 Unknown,
53}
54
55#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
57#[ts(export, export_to = "../../../frontend/types/rpc/")]
58pub struct ServiceStatus {
59 pub service: String,
61 pub label: String,
63 pub state: Reachability,
64 #[ts(type = "number")]
66 pub since_ms: i64,
67 pub last_error: Option<String>,
69}
70
71#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
73#[ts(export, export_to = "../../../frontend/types/rpc/")]
74pub struct ConnectivityStatus {
75 #[ts(type = "number")]
77 pub revision: u64,
78 pub services: Vec<ServiceStatus>,
80}
81
82#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
84pub struct ModelApi {
85 pub vendor: &'static str,
87 pub label: &'static str,
88 pub default_base_url: &'static str,
89 pub base_url_env: Option<&'static str>,
91}
92
93pub static ANTHROPIC: ModelApi = ModelApi {
96 vendor: "anthropic",
97 label: "Anthropic API",
98 default_base_url: "https://api.anthropic.com",
99 base_url_env: Some("ANTHROPIC_BASE_URL"),
100};
101
102pub static OPENAI: ModelApi = ModelApi {
104 vendor: "openai",
105 label: "OpenAI API",
106 default_base_url: "https://api.openai.com",
107 base_url_env: Some("OPENAI_BASE_URL"),
108};
109
110pub static GOOGLE: ModelApi = ModelApi {
112 vendor: "google",
113 label: "Google AI API",
114 default_base_url: "https://generativelanguage.googleapis.com",
115 base_url_env: Some("GOOGLE_GEMINI_BASE_URL"),
116};
117
118pub static TRACKED_MODEL_APIS: [&ModelApi; 1] = [&ANTHROPIC];
122
123#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
125pub enum Service {
126 ModelApi(&'static ModelApi),
127 ModelApiAt(&'static ModelApi, String),
132 Muxbus,
134}
135
136impl Service {
137 const INTERNET_ID: &'static str = "internet";
138 const INTERNET_LABEL: &'static str = "Internet";
139
140 pub fn id(&self) -> String {
141 match self {
142 Service::ModelApi(api) => format!("model_api:{}", api.vendor),
143 Service::ModelApiAt(api, url) => format!("model_api:{}@{}", api.vendor, endpoint::host_of(url)),
144 Service::Muxbus => "muxbus".to_string(),
145 }
146 }
147
148 pub fn label(&self) -> String {
149 match self {
150 Service::ModelApi(api) => api.label.to_string(),
151 Service::ModelApiAt(api, url) => format!("{} ({})", api.label, endpoint::host_of(url)),
152 Service::Muxbus => "MuxBus".to_string(),
153 }
154 }
155
156 pub fn probe_url(&self) -> String {
159 match self {
160 Service::ModelApiAt(_, url) => url.clone(),
161 Service::ModelApi(api) => api
162 .base_url_env
163 .and_then(|var| std::env::var(var).ok())
164 .filter(|v| !v.trim().is_empty())
165 .unwrap_or_else(|| api.default_base_url.to_string()),
166 Service::Muxbus => crate::muxbus::relay::rest_base_url(),
167 }
168 }
169}
170
171pub fn service_for(api: &'static ModelApi, configured: Option<&str>) -> Service {
174 let Some(url) = configured.map(str::trim).filter(|u| !u.is_empty()) else {
175 return Service::ModelApi(api);
176 };
177 match endpoint::normalise(url) {
179 Some(url) if Some(&url) != endpoint::normalise(&Service::ModelApi(api).probe_url()).as_ref() => Service::ModelApiAt(api, url),
180 _ => Service::ModelApi(api),
181 }
182}
183
184const PROXY_VARS: [&str; 8] = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"];
186
187fn own_proxy(env: &std::collections::HashMap<String, String>) -> bool {
190 PROXY_VARS.iter().any(|var| {
191 let theirs = env.get(*var).map(|v| v.trim()).filter(|v| !v.is_empty());
192 theirs.is_some() && theirs != std::env::var(var).ok().as_deref().map(str::trim)
193 })
194}
195
196pub fn service_for_env(api: &'static ModelApi, env: &std::collections::HashMap<String, String>) -> Service {
200 if own_proxy(env) {
201 return Service::ModelApi(api);
202 }
203 service_for(api, api.base_url_env.and_then(|var| env.get(var)).map(String::as_str))
204}
205
206pub fn model_api_of(provider: &str) -> Option<&'static ModelApi> {
208 let vendor = *crate::backend::providers::get_provider(provider)?.supported_vendors.first()?;
209 [&ANTHROPIC, &OPENAI, &GOOGLE].into_iter().find(|api| api.vendor == vendor)
210}
211
212pub fn endpoint_meta(service: &Service) -> Option<serde_json::Value> {
215 match service {
216 Service::ModelApiAt(_, url) => Some(serde_json::json!({ "service": service.id(), "url": url })),
217 _ => None,
218 }
219}
220
221#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum Outcome {
224 Answered,
226 Unreachable(String),
228}
229
230pub(crate) struct Shared {
232 tracker: Mutex<Tracker>,
233 wake: Notify,
234 sink: OnceLock<Arc<EventBus>>,
235}
236
237impl Shared {
238 fn new(now_ms: i64) -> Self {
239 let first_revision = u64::try_from(now_ms).unwrap_or(0).saturating_mul(1000);
240 Self { tracker: Mutex::new(Tracker::new(first_revision, now_ms)), wake: Notify::new(), sink: OnceLock::new() }
241 }
242
243 fn tracker(&self) -> std::sync::MutexGuard<'_, Tracker> {
244 self.tracker.lock().unwrap_or_else(|e| e.into_inner())
245 }
246
247 fn seed_at(&self, now_ms: i64) {
249 let mut changed = None;
250 for api in TRACKED_MODEL_APIS {
251 changed = self.tracker().seed(Service::ModelApi(api), now_ms).or(changed);
252 }
253 self.publish(changed);
254 }
255
256 fn track_at(&self, service: Service, now_ms: i64) {
258 let changed = self.tracker().seed(service, now_ms);
259 self.publish(changed);
260 }
261
262 fn report_at(&self, service: Service, outcome: Outcome, now_ms: i64) {
263 let changed = self.tracker().report(service, outcome, now_ms);
264 self.publish(changed);
265 }
266
267 fn network_changed_at(&self, now_ms: i64) {
269 if self.tracker().network_changed(now_ms) {
270 tracing::info!("connectivity: the network changed, probing again");
271 self.wake.notify_one();
272 }
273 }
274
275 fn publish(&self, changed: Option<ConnectivityStatus>) {
276 let Some(status) = changed else { return };
277 let down: Vec<String> = status
278 .services
279 .iter()
280 .filter(|s| s.state != Reachability::Online)
281 .map(|s| format!("{}={:?}", s.service, s.state))
282 .collect();
283 tracing::info!(down = %down.join(","), "connectivity: changed");
284 self.wake.notify_one();
286 if let Some(bus) = self.sink.get() {
287 bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::ConnectivityChanged>(&status, String::new()));
288 }
289 }
290}
291
292static SHARED: LazyLock<Arc<Shared>> = LazyLock::new(|| Arc::new(Shared::new(agentmux_common::time::now_ms())));
293
294pub fn install(event_bus: Arc<EventBus>) {
297 if SHARED.sink.set(event_bus).is_err() || tokio::runtime::Handle::try_current().is_err() {
298 return;
299 }
300 SHARED.seed_at(agentmux_common::time::now_ms());
301 let clock: probe::Clock = Arc::new(agentmux_common::time::now_ms);
302 tokio::spawn(probe::drive(SHARED.clone(), Arc::new(probe::NetProber::new()), clock));
303 netchange::start(SHARED.clone());
304}
305
306pub fn status() -> ConnectivityStatus {
308 SHARED.tracker().status()
309}
310
311pub fn track(service: Service) {
314 SHARED.track_at(service, agentmux_common::time::now_ms());
315}
316
317pub fn report(service: Service, outcome: Outcome) {
319 SHARED.report_at(service, outcome, agentmux_common::time::now_ms());
320}
321
322pub fn http_outcome(result: &Result<reqwest::Response, reqwest::Error>) -> Option<Outcome> {
325 match result {
326 Ok(_) => Some(Outcome::Answered),
327 Err(e) if e.is_builder() => None,
328 Err(e) => Some(Outcome::Unreachable(crate::http_client::explain(e))),
329 }
330}
331
332pub fn report_http(service: Service, result: &Result<reqwest::Response, reqwest::Error>) {
334 if let Some(outcome) = http_outcome(result) {
335 report(service, outcome);
336 }
337}
338
339pub fn ws_connect_outcome(error: Option<&tokio_tungstenite::tungstenite::Error>) -> Option<Outcome> {
342 use tokio_tungstenite::tungstenite::Error;
343 match error {
344 None => Some(Outcome::Answered),
345 Some(e @ (Error::Io(_) | Error::Tls(_))) => Some(Outcome::Unreachable(e.to_string())),
346 Some(Error::Url(_)) => None,
347 Some(_) => Some(Outcome::Answered),
348 }
349}
350
351pub fn report_ws_connect(service: Service, error: Option<&tokio_tungstenite::tungstenite::Error>) {
353 if let Some(outcome) = ws_connect_outcome(error) {
354 report(service, outcome);
355 }
356}
357
358pub fn claude_frame_outcome(frame: &serde_json::Value) -> Option<Outcome> {
364 use serde_json::Value;
365 match frame.get("type").and_then(Value::as_str)? {
366 "system" if frame.get("subtype").and_then(Value::as_str) == Some("api_retry") => {
367 if frame.get("error_status").and_then(Value::as_u64).is_some() {
368 return Some(Outcome::Answered);
369 }
370 let error = frame.get("error").and_then(Value::as_str).filter(|e| !e.is_empty()).unwrap_or("connection failed");
371 Some(Outcome::Unreachable(format!("Claude CLI retrying: {error}")))
372 }
373 "assistant" => {
374 let model = frame.get("message")?.get("model")?.as_str()?;
375 (model != "<synthetic>").then_some(Outcome::Answered)
376 }
377 "result" if frame.get("is_error").and_then(Value::as_bool) == Some(true) => {
378 let failure = crate::agents::failure::classify(None, None, "", Some(frame));
379 (failure.code == crate::agents::failure::FailureClass::Network).then_some(Outcome::Unreachable(failure.title))
380 }
381 _ => None,
382 }
383}
384
385fn exit_reported_api(provider: &str) -> Option<&'static ModelApi> {
389 let vendor = *crate::backend::providers::get_provider(provider)?.supported_vendors.first()?;
390 [&OPENAI, &GOOGLE].into_iter().find(|api| api.vendor == vendor)
391}
392
393pub fn observe_provider_turn(provider: &str, failure: Option<&crate::agents::failure::AgentFailure>, configured: Option<&str>) {
396 if let Some((api, outcome)) = provider_turn_outcome(provider, failure) {
397 report(service_for(api, configured), outcome);
398 }
399}
400
401fn provider_turn_outcome(
402 provider: &str,
403 failure: Option<&crate::agents::failure::AgentFailure>,
404) -> Option<(&'static ModelApi, Outcome)> {
405 use crate::agents::failure::FailureClass::{Auth, ContextExceeded, Network, Overloaded, RateLimited, UsageLimit};
406 let api = exit_reported_api(provider)?;
407 let outcome = match failure {
408 None => Outcome::Answered,
409 Some(f) => match f.code {
410 Network => Outcome::Unreachable(f.title.clone()),
411 RateLimited | Overloaded | UsageLimit | Auth | ContextExceeded => Outcome::Answered,
412 _ => return None,
413 },
414 };
415 Some((api, outcome))
416}
417
418pub fn observe_claude_frame(frame: &serde_json::Value, service: &Service) {
420 if let Some(outcome) = claude_frame_outcome(frame) {
421 report(service.clone(), outcome);
422 }
423}
424
425#[cfg(test)]
426mod tests;