Skip to main content

agentmux_srv/server/
http_health.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Health, diagnostics, LAN instances, discovery, WPS publish.
5//! Split out of server/mod.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.1).
6
7use super::*;
8
9// ---- Health ----
10
11/// `status` is `ok`, or `degraded` when the messaging path is stuck or srv is panicking in bulk (`messaging_health`). The HTTP
12/// status stays 200 either way: `agentmux`'s `health_ok` reads anything else as "no server here".
13pub(super) async fn health_handler(State(state): State<AppState>) -> Json<serde_json::Value> {
14    let messaging = super::messaging_health::MessagingHealth::probe(state.reactive_handler).await;
15    Json(json!({
16        "status": messaging.status(),
17        "version": state.version,
18        "messaging": messaging.to_json(),
19    }))
20}
21
22/// Saga durability PR 2 — operator visibility into the durable saga
23/// log. Returns the most-recent 50 saga lifecycle rows + an in-flight
24/// count derived from `unresolved_sagas`.
25///
26/// **Why a JSON HTTP endpoint and not a launcher `--diag sagas`
27/// pipe-IPC client.** The `--diag srv` pipe transport (see
28/// `crates/launcher/src/diag.rs`) routes through `Tool` registration
29/// + a 2 s observation window with `GetSrvSnapshot` + `GetEvents`.
30/// Adding `GetSagaLogSnapshot` to the IPC `Command` enum + an
31/// `Event::SagaLogSnapshot` variant with a Vec of `SagaSnapshot`
32/// triples the touched-files surface for one operator command.
33/// JSON HTTP is the precedent for raw operator queries (cf
34/// `/api/lan-instances`) and matches the spec §9 PR 2 phrasing
35/// "tightened scope". Promoting to first-class `--diag sagas` via
36/// pipe IPC is a follow-up if anyone asks.
37///
38/// Operator workflow today:
39/// ```text
40/// curl -s -H "X-AuthKey: $KEY" http://127.0.0.1:$PORT/agentmux/diag/sagas | jq .
41/// ```
42/// Response shape:
43/// ```json
44/// {
45///   "recent": [ { "saga_id": ..., "name": ..., "state": ..., ... }, ... ],
46///   "in_flight_count": 1,
47///   "recently_failed_count": 0,
48///   "total_returned": 50
49/// }
50/// ```
51pub(super) async fn handle_diag_sagas(State(state): State<AppState>) -> Json<serde_json::Value> {
52    const LIMIT: u32 = 50;
53    let recent = match state.saga_log.snapshot_recent(LIMIT) {
54        Ok(rows) => rows,
55        Err(e) => {
56            return Json(json!({
57                "error": format!("snapshot_recent failed: {}", e),
58            }));
59        }
60    };
61    let in_flight = match state.saga_log.unresolved_sagas() {
62        Ok(rows) => rows.len(),
63        Err(e) => {
64            tracing::warn!("[diag/sagas] unresolved_sagas failed: {}", e);
65            0
66        }
67    };
68    let recently_failed = recent
69        .iter()
70        .filter(|s| s.state == "failed" || s.state == "failed_compensation")
71        .count();
72    Json(json!({
73        "recent": recent,
74        "in_flight_count": in_flight,
75        "recently_failed_count": recently_failed,
76        "total_returned": recent.len(),
77    }))
78}
79
80pub(super) async fn handle_lan_instances(State(state): State<AppState>) -> Json<serde_json::Value> {
81    Json(json!(state.lan_discovery.get_instances()))
82}
83
84/// `GET /agentmux/discovery` — a unified, agent-facing view of what exists and
85/// what is reachable across the muxbus delivery tiers, so an agent can resolve a
86/// target before sending. Aggregates:
87///   - `host.addressable`: the authoritative Tier-1/2 reachable set
88///     (`reactive_handler.list_agents()` — every entry has a live block_id).
89///   - `host.agents`: this host's agent directory (SQLite `instance_list`),
90///     each flagged `addressable` iff its name is in the reachable set.
91///   - `lan`: Tier-3 mDNS peers (each `LanInstance` carries its own `agents`).
92///   - `wan.local_agents_subscribed`: **this host's own** agents that are
93///     subscribed to the Tier-4 cloud relay (empty when no token). It is NOT a
94///     list of remote agents reachable over WAN — nothing here can answer that
95///     question, because the relay exposes no directory. Named
96///     `wan.subscribed_agents` until 2026-09-06, which read as "agents
97///     reachable via cloud" under a heading called `wan` in a response whose
98///     whole purpose is reachability, and produced a wrong diagnosis. See
99///     REPORT_NETWORK_ARCHITECTURE_DRYNESS_AND_ROBUST_LAN_2026_09_06.md §6.
100/// Addressing is case-insensitive (registration lowercases the key). Authed like
101/// the other reactive routes; agents reach it via AGENTMUX_LOCAL_URL + X-AuthKey.
102/// See SPEC_MUXBUS_AGENT_DISCOVERY_AND_PERSISTENT_DELIVERY_2026_06_16.
103pub(super) async fn handle_discovery(State(state): State<AppState>) -> Json<serde_json::Value> {
104    // Tier-1/2 reachable set — the authoritative "addressable" answer. Keep the
105    // live block_id per name (lowercased) so an addressable row can surface its
106    // real delivery block; the SQLite directory below does not carry one.
107    let reachable = state.reactive_handler.list_agents();
108    let reachable_block: std::collections::HashMap<String, String> = reachable
109        .iter()
110        .map(|a| (a.agent_id.to_lowercase(), a.block_id.clone()))
111        .collect();
112
113    // Host directory (live SQLite instances). `instance_list` already excludes
114    // hidden (user_hidden = 0) and template rows in SQL, and the consolidated
115    // path leaves block_id/status empty (storage/agents/instance.rs) — so addressability AND the
116    // live block_id come from the reachable set above. `block_id` is null for a
117    // known-but-unreachable agent; the always-empty `status` is omitted.
118    let instances = state.mstore.instance_list(None, None).unwrap_or_default();
119    // Each agent's seat, by its definition (SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md
120    // §4): `null` when it has none.
121    let defs = state.mstore.agent_def_list().unwrap_or_default();
122    // What a routine message to each would do now (`availability_view`).
123    let cold_after_ms = crate::backend::cold_hold::cold_after_ms(&state.config_watcher.get_full_config().settings.extra)
124        .and_then(|ms| u64::try_from(ms).ok());
125    let (now_ms, net) = (agentmux_common::time::now_ms_u64(), crate::connectivity::status());
126    // Every created agent's runtime state, with or without a pane (`agent_runtime::list`).
127    let runtime: std::collections::HashMap<String, crate::server::agent_runtime::AgentRuntime> = {
128        let looked = state.clone();
129        tokio::task::spawn_blocking(move || crate::server::agent_runtime::list(&looked, now_ms))
130            .await
131            .unwrap_or_default()
132            .into_iter()
133            .map(|r| (r.agent_id.clone(), r))
134            .collect()
135    };
136    let listed: std::collections::HashSet<String> = instances.iter().map(|i| i.id.clone()).collect();
137    let mut agents: Vec<serde_json::Value> = instances
138        .into_iter()
139        .map(|i| {
140            // A row with no name of its own (one made before names were stored on it) is listed under its
141            // definition's, so it isn't a nameless entry that no name reaches.
142            let name = listed_name(&i.instance_name, runtime.get(&i.id).map(|r| r.name.as_str()));
143            let live_block = (!name.is_empty()).then(|| reachable_block.get(&name.to_lowercase()).cloned()).flatten();
144            // By the agent's UID, not its name: two agents can share a display name, and a name
145            // the registry normalised ("Loap #3") misses the name-keyed map above.
146            let availability_block = super::availability_view::block_of_uid(&state.reactive_handler, &i.id);
147            json!({
148                "name": name,
149                "id": i.id,
150                "definition_id": i.definition_id,
151                "working_directory": i.working_directory,
152                "addressable": live_block.is_some(),
153                "block_id": live_block,
154                "seat": crate::backend::agent_seat::summary_in(&state.mstore, &defs, &i.definition_id),
155                "spend": super::spend_watch::view(&state.mstore, &state.identity_store, &state.config_watcher.get_settings().extra, &defs, &i.definition_id),
156                "availability": super::availability_view::describe_block(&state.mstore, availability_block.as_deref(), runtime.get(&i.id).and_then(|r| r.block_id.as_deref()), &net, cold_after_ms, now_ms),
157                "runtime": runtime.get(&i.id),
158            })
159        })
160        .collect();
161    // An agent created on another channel of this host has a definition and no row here yet.
162    let mut elsewhere: Vec<&crate::server::agent_runtime::AgentRuntime> =
163        runtime.values().filter(|r| !listed.contains(&r.agent_id)).collect();
164    elsewhere.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
165    agents.extend(elsewhere.into_iter().map(|r| {
166        json!({
167            "name": r.name,
168            "id": r.agent_id,
169            "definition_id": r.agent_id,
170            "addressable": false,
171            "block_id": r.block_id,
172            "seat": crate::backend::agent_seat::summary_in(&state.mstore, &defs, &r.agent_id),
173            "availability": super::availability_view::describe_block(&state.mstore, None, r.block_id.as_deref(), &net, cold_after_ms, now_ms),
174            "runtime": r,
175        })
176    }));
177
178    let wan_agents = crate::muxbus::cloud_subscriber::get_global_subscriber()
179        .map(|s| s.subscribed_agents())
180        .unwrap_or_default();
181
182    let lan = state.lan_discovery.get_instances();
183    let version = state.version.clone();
184    let local_url = state.local_web_url.clone();
185
186    // Tier 2b — other channels' agents on this same host (issue #1916), via
187    // the host-global shared registry. Excludes this instance's own channel
188    // (already covered by `agents`/`addressable` above) and this instance's
189    // own URL (a stale self-entry from a prior crash, if any).
190    let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
191    let cross_channel: Vec<serde_json::Value> = crate::registry::resolve_shared_reactive_dir()
192        .map(|shared_dir| {
193            crate::backend::reactive::registry::list_all_shared(&shared_dir)
194                .into_iter()
195                .filter(|e| e.channel != own_channel && e.local_url != local_url)
196                .map(|e| {
197                    json!({
198                        "name": e.agent_id,
199                        "channel": e.channel,
200                        "local_url": e.local_url,
201                        "block_id": e.block_id,
202                    })
203                })
204                .collect()
205        })
206        .unwrap_or_default();
207
208    Json(json!({
209        "host": {
210            "version": version,
211            "hostname": state.hostname.clone(),
212            // So a QR- or manually-paired client can name this channel
213            // (SPEC_LAN_FLEET_FEED_2026_10_03.md §5).
214            "channel": crate::backend::reactive::registry::local_channel_id(), "build_kind": agentmux_common::build_kind::build_kind().label(),
215            "local_url": local_url,
216            "addressable": reachable,
217            "agents": agents,
218            "cross_channel": cross_channel, "unreadable": unreadable_records(&state),
219        },
220        "lan": lan,
221        "wan": { "local_agents_subscribed": wan_agents },
222    }))
223}
224
225/// The agent records on this host that this build cannot read (a newer AgentMux wrote them, or the file is damaged), each with
226/// why: they are on disk and kept exactly as they are, but they are not in `agents`, and an agent that does not appear is a
227/// question nobody can answer. `kind` says which record it is (`definition` or `instance`).
228fn unreadable_records(state: &AppState) -> Vec<serde_json::Value> {
229    let row = |kind: &str, r: crate::registry::UnreadableRecord| json!({ "kind": kind, "id": r.id, "name": r.name, "provider": r.provider, "reason": r.reason });
230    let defs = state.mstore.shared_def_registry().and_then(|d| d.list_unreadable().ok()).unwrap_or_default();
231    let instances = state.mstore.shared_agent_registry().and_then(|r| r.list_unreadable().ok()).unwrap_or_default();
232    defs.into_iter().map(|r| row("definition", r)).chain(instances.into_iter().map(|r| row("instance", r))).collect()
233}
234
235/// The name a host agent is listed under: its row's, else its definition's.
236fn listed_name(instance_name: &str, definition_name: Option<&str>) -> String {
237    if instance_name.is_empty() { definition_name.unwrap_or_default().to_string() } else { instance_name.to_string() }
238}
239
240pub(super) async fn stub_501() -> impl IntoResponse {
241    (
242        StatusCode::NOT_IMPLEMENTED,
243        Json(json!({"error": "not implemented"})),
244    )
245}
246
247/// Auth-gated MPS publish endpoint
248/// (SPEC_STREAMING_BASH_RUNNER_2026_05_11.md §3.2). `agentmux-bashwrap`
249/// POSTs here while running a Bash command; we forward to the
250/// in-process MPS broker so subscribed frontends receive the event.
251/// A client event declared in `mps_events` (`client_events!`) must carry its
252/// payload type, or it is refused with 400; any other event `mps_events`
253/// declares is srv's alone, and refused with 400.
254pub(super) async fn handle_wps_publish(
255    State(state): State<AppState>,
256    Json(req): Json<WpsPublishRequest>,
257) -> impl IntoResponse {
258    // Note: this endpoint used to special-case `compaction_started` to
259    // forward into the target block's `HealthMonitor` (silence-detector
260    // compaction awareness) — removed along with the unresponsive
261    // detector itself, see
262    // docs/specs/SPEC_REMOVE_AGENT_UNRESPONSIVE_DETECTION_2026_08_25.md.
263    // `agentmux-bashwrap`'s `precompact` POST still lands here and is now
264    // a harmless no-op broadcast like any other MPS event — left as-is
265    // rather than removing the route, since deleting it isn't warranted
266    // just to avoid one no-op publish.
267    // A wrapper's report of which tool call it runs (Tower's "started by"):
268    // kept here, not broadcast, since the pane would take an unknown op for
269    // output (`backend::tool_calls`).
270    if req.event == "tool_chunk" {
271        if let Some((pid, call)) = crate::backend::tool_calls::parse_report(&req.scopes, &req.data) {
272            crate::backend::tool_calls::record(pid, call);
273            return (StatusCode::OK, Json(json!({"ok": true})));
274        }
275    }
276    // A declared client event goes out typed, or not at all if its data isn't its payload.
277    match crate::backend::mps_events::publish_client_event(&state.broker, &req.event, &req.data, &req.scopes, req.persist) {
278        Some(Ok(())) => return (StatusCode::OK, Json(json!({"ok": true}))),
279        Some(Err(e)) => return (StatusCode::BAD_REQUEST, Json(json!({"error": e}))),
280        None => {}
281    }
282    // Any other declared event is srv's: its subscribers read it as its payload type.
283    if crate::backend::mps_events::is_srv_event(&req.event) {
284        return (StatusCode::BAD_REQUEST, Json(json!({"error": format!("{}: only srv publishes this event", req.event)})));
285    }
286    // untyped-relay: publishes an undeclared event a process outside srv built (an external
287    // tool), as it was sent.
288    let event = crate::backend::mps::MuxEvent {
289        event: req.event,
290        scopes: req.scopes,
291        sender: String::new(),
292        persist: req.persist,
293        data: Some(req.data),
294    };
295    state.broker.publish(event);
296    (StatusCode::OK, Json(json!({"ok": true})))
297}
298
299#[cfg(test)]
300mod name_tests {
301    use super::listed_name;
302
303    #[test]
304    fn a_row_with_no_name_is_listed_under_its_definitions() {
305        assert_eq!(listed_name("Loap #3", Some("Loap-3")), "Loap #3", "the row's own name wins");
306        assert_eq!(listed_name("", Some("Tansy")), "Tansy");
307        assert_eq!(listed_name("", None), "", "no definition either: still empty, not invented");
308    }
309}
310
311#[cfg(test)]
312mod unreadable_tests {
313    use super::*;
314
315    #[tokio::test]
316    async fn discovery_lists_the_records_it_cannot_read_with_why_instead_of_leaving_the_agent_out() {
317        let state = crate::server::tests::test_state();
318        let dir = tempfile::tempdir().unwrap();
319        state.mstore.set_def_registry(std::sync::Arc::new(crate::registry::DefinitionStore::open(dir.path().join("definitions")).unwrap()));
320        assert!(unreadable_records(&state).is_empty());
321        let newer = json!({ "schema_version": 2, "data": { "id": "nova-id", "name": "Nova", "provider": "claude" } });
322        std::fs::write(dir.path().join("definitions").join("nova-id.json"), serde_json::to_vec_pretty(&newer).unwrap()).unwrap();
323        let listed = unreadable_records(&state);
324        assert_eq!(listed.len(), 1, "{listed:?}");
325        assert_eq!((listed[0]["kind"].as_str(), listed[0]["id"].as_str(), listed[0]["name"].as_str()), (Some("definition"), Some("nova-id"), Some("Nova")));
326        assert!(listed[0]["reason"].as_str().unwrap().contains("newer AgentMux"), "{listed:?}");
327    }
328}