Skip to main content

agentmux_srv_core/connectivity/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether each service AgentMux depends on can be reached
5//! (docs/specs/SPEC_OFFLINE_RESILIENCE_2026_10_20.md ยง4.1).
6//!
7//! **Inputs.** Code that already makes requests reports what happened
8//! ([`report`], [`report_http`], [`report_ws_connect`],
9//! [`observe_claude_frame`]): any HTTP response means the service is
10//! reachable, whatever its status; a transport failure (DNS, connect, reset,
11//! TLS, timeout) means it isn't. While a service is believed down, and only
12//! then, [`probe`] checks it on its own with capped backoff, so recovery
13//! shows even when nothing else is calling.
14//!
15//! **States** ([`tracker`]): `offline` after [`tracker::OFFLINE_AFTER`]
16//! transport failures in a row or a failed probe; `degraded` while some
17//! fail and some answer; `online` on an answer. The internet counts as
18//! offline only when two services are and none answers.
19//!
20//! **Outputs.** The `connectivity:changed` event on every change and
21//! `connectivity.status` for a window that opens later; both carry a rising
22//! `revision`, since they can arrive out of order.
23
24pub 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
37/// The WebSocket event carrying a changed [`ConnectivityStatus`].
38pub const EVENT_CONNECTIVITY_CHANGED: &str = "connectivity:changed";
39
40/// Whether a service can be reached.
41#[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    /// Some requests fail at the transport level, some are answered.
47    Degraded,
48    /// Every recent request failed before any answer came back.
49    Offline,
50    /// Not checked yet: a model API srv tracks, between startup and its
51    /// first probe or request. Not offline, and not known to answer.
52    Unknown,
53}
54
55/// One service's reachability.
56#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
57#[ts(export, export_to = "../../../frontend/types/rpc/")]
58pub struct ServiceStatus {
59    /// `internet`, `muxbus`, or `model_api:<vendor>`.
60    pub service: String,
61    /// What the status bar calls it ("Anthropic API").
62    pub label: String,
63    pub state: Reachability,
64    /// When `state` began, in ms since the epoch.
65    #[ts(type = "number")]
66    pub since_ms: i64,
67    /// The last transport error, while not online.
68    pub last_error: Option<String>,
69}
70
71/// `connectivity:changed`'s payload and `connectivity.status`'s answer.
72#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
73#[ts(export, export_to = "../../../frontend/types/rpc/")]
74pub struct ConnectivityStatus {
75    /// Rises with every change; only an order, not a time.
76    #[ts(type = "number")]
77    pub revision: u64,
78    /// `internet` first, then every service that has reported, online or not.
79    pub services: Vec<ServiceStatus>,
80}
81
82/// A model vendor's API: where to probe it, and its name in the status bar.
83#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
84pub struct ModelApi {
85    /// The vendor id, as `ProviderConfig::supported_vendors` names it.
86    pub vendor: &'static str,
87    pub label: &'static str,
88    pub default_base_url: &'static str,
89    /// The variable that points the provider's CLI elsewhere, if any.
90    pub base_url_env: Option<&'static str>,
91}
92
93/// The API Claude Code calls. Only the persistent controller, which only
94/// Claude uses, reports today; another provider adds its own.
95pub 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
102/// The API Codex calls.
103pub 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
110/// The API Gemini CLI calls.
111pub 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
118/// The model APIs whose state srv tracks from startup: each is listed as
119/// [`Reachability::Unknown`] and probed at once, so a window can tell "not
120/// checked yet" from "answers" before any agent has made a request.
121pub static TRACKED_MODEL_APIS: [&ModelApi; 1] = [&ANTHROPIC];
122
123/// A service AgentMux depends on.
124#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
125pub enum Service {
126    ModelApi(&'static ModelApi),
127    /// A model API at an address other than the one srv itself would call (`ModelApi`'s
128    /// [`Service::probe_url`]): a pane whose CLI is pointed at a proxy or a gateway. It is its own
129    /// service, so its state, and the probe of it, are about the host that pane really uses. The
130    /// address is [`endpoint::normalise`]d.
131    ModelApiAt(&'static ModelApi, String),
132    /// The relay and its sign-in server.
133    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    /// Where a probe goes: srv's own environment for a `ModelApi` (a pane that sets its own
157    /// address is a [`Service::ModelApiAt`], probed at that address).
158    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
171/// The service a pane's calls to `api` go to, given the address its CLI was started with
172/// (`None`, empty or unreadable: the CLI's default). The same address srv itself would call is just `api`.
173pub 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    // An address that can't be read is no address: the CLI will fail on it by itself, and nothing from it is kept.
178    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
184/// The variables that route a CLI's requests through a proxy, or around it.
185const PROXY_VARS: [&str; 8] = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"];
186
187/// Whether `env` sends a CLI's requests a way srv's own probe doesn't go: a proxy or bypass variable that srv's own
188/// environment doesn't have, or has with another value.
189fn 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
196/// [`service_for`] with the address read from the environment a pane's CLI was started with. A pane with a proxy of
197/// its own has no address of its own in the status: the probe goes out the way srv does, which may not be the way
198/// that CLI does, so it could call a working address offline.
199pub 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
206/// The model API a provider's CLI calls, from its first vendor, if srv tracks it.
207pub 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
212/// What a pane keeps in its block meta (`agent:api_endpoint`) when its model API is not at srv's own
213/// address: its service id, so the pane reads its own state, and the address.
214pub 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/// What one request, or probe, found.
222#[derive(Debug, Clone, PartialEq, Eq)]
223pub enum Outcome {
224    /// Some HTTP response came back.
225    Answered,
226    /// No response: DNS, connect, reset, TLS or timeout (the error).
227    Unreachable(String),
228}
229
230/// The tracker, the probe driver's wake-up, and where changes go.
231pub(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    /// Lists every tracked model API as not checked yet, due for a probe.
248    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    /// Lists `service` as not checked yet, due for a probe, unless it has reported.
257    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    /// The OS reported a network change: every service is probed again, now.
268    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        // A service that left `online` has a probe to schedule.
285        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
294/// Where changes go, and the start of the probe driver. Call once at
295/// startup; reports before it are kept, just not sent.
296pub 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
306/// The current state, for `connectivity.status`.
307pub fn status() -> ConnectivityStatus {
308    SHARED.tracker().status()
309}
310
311/// Starts tracking `service` now: listed as not checked yet and probed at once, as the
312/// [`TRACKED_MODEL_APIS`] are at startup. For a pane's own address, when its CLI starts.
313pub fn track(service: Service) {
314    SHARED.track_at(service, agentmux_common::time::now_ms());
315}
316
317/// What a request to `service` found.
318pub fn report(service: Service, outcome: Outcome) {
319    SHARED.report_at(service, outcome, agentmux_common::time::now_ms());
320}
321
322/// The outcome a reqwest `send()` result says, or `None` for a request that
323/// was never sent (it couldn't be built).
324pub 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
332/// Reports a reqwest `send()` result.
333pub 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
339/// The outcome of a WebSocket connect: an HTTP answer to the handshake, even
340/// a refusal, means the server was reached.
341pub 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
351/// Reports a WebSocket connect: `None` when it succeeded.
352pub 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
358/// What a Claude CLI stdout frame says about the API, if anything: an
359/// `api_retry` with no HTTP status is a failed connection, one with a status
360/// was answered, and so was a reply from a model; a turn's error `result`
361/// the failure classifier calls `Network` is a failed connection. A
362/// `<synthetic>` message is the CLI's own (its "API Error" text), not the API's.
363pub 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
385/// The API of a provider whose turns end only in an exit, with no frames to read: Codex and Gemini. They join the
386/// status when their first turn reports, and are probed from then on while down. Claude reports through
387/// [`observe_claude_frame`]; other providers are not tracked.
388fn 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
393/// What a finished turn of `provider` says about its model API: a clean turn, or a failure the API itself returned
394/// (limit, auth, overload), reached it; a network failure did not. Any other failure says nothing.
395pub 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
418/// Reads one Claude CLI stdout frame (`persistent::stdout_reader`).
419pub 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;