Skip to main content

agentmux_srv/server/live_facts/
handler.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /agentmux/discovery` with the live facts' parameters (spec ยง5): the same answer as ever with no
5//! parameter, this host's agents narrowed, paged and given the groups asked for with `fields`, `detail`
6//! and the filters, or, with `view=status`, the compact status (`Agents status`). The same answer is what
7//! the LAN op `agents.status` gives a peer (`answer`).
8
9use std::collections::HashMap;
10
11use axum::extract::{Query, State};
12use axum::http::StatusCode;
13use axum::response::{IntoResponse, Response};
14use axum::Json;
15use serde_json::{json, Value};
16
17use super::query::{apply, status, Params};
18use crate::server::AppState;
19
20fn bad_request(message: String) -> Response {
21    (StatusCode::BAD_REQUEST, Json(json!({ "error": message }))).into_response()
22}
23
24/// Which answer a query asks for: the discovery list (the default) or the compact status.
25pub(crate) fn is_status_view(query: &HashMap<String, String>) -> Result<bool, String> {
26    match query.get("view").map(|v| v.trim()) {
27        None | Some("") | Some("list") => Ok(false),
28        Some("status") => Ok(true),
29        Some(other) => Err(format!("unknown view {other:?}: use list or status")),
30    }
31}
32
33/// This machine's answer to `query`: the discovery body with its agents narrowed and paged, or the compact
34/// status. With `host=all` it also has `peers`, the LAN peers a caller may ask the same question.
35pub(crate) async fn answer(state: &AppState, query: &HashMap<String, String>) -> Result<Value, String> {
36    let params = Params::from_map(query, &state.hostname)?;
37    let compact = is_status_view(query)?;
38    let Json(mut body) = crate::server::http_health::handle_discovery(State(state.clone())).await;
39    // Nothing asked for: the answer as it always was, plus each row's short model.
40    let rows: Vec<Value> = match body.pointer_mut("/host/agents").map(Value::take) {
41        Some(Value::Array(rows)) => rows,
42        _ => Vec::new(),
43    };
44    let now_ms = agentmux_common::time::now_ms_u64();
45    let worker = state.clone();
46    let all_hosts = params.all_hosts;
47    let mut out = if compact {
48        tokio::task::spawn_blocking(move || status(&worker, rows, &params, now_ms)).await.map_err(|e| e.to_string())?
49    } else {
50        let (agents, page) = tokio::task::spawn_blocking(move || apply(&worker, rows, &params, now_ms)).await.map_err(|e| e.to_string())?;
51        body["host"]["agents"] = Value::Array(agents);
52        body["host"]["page"] = page;
53        body
54    };
55    if all_hosts {
56        out["peers"] = json!(state.lan_discovery.get_instances());
57    }
58    Ok(out)
59}
60
61pub(crate) async fn handle(State(state): State<AppState>, Query(query): Query<HashMap<String, String>>) -> Response {
62    match answer(&state, &query).await {
63        Ok(body) => Json(body).into_response(),
64        Err(e) => bad_request(e),
65    }
66}