Skip to main content

agentmux_srv/server/
muxspect_instances.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `muxspect instances` and `muxspect --channel <name> <command>`: look at another AgentMux
5//! instance on this machine from inside one
6//! (`docs/specs/SPEC_MUXSPECT_CROSS_TIER_INSTANCE_INSPECTION_2026_09_02.md` §2.3, §2.4).
7//!
8//! `GET /api/v1/muxspect/instances` lists the live instances from `backend::instance_registry`.
9//! [`forward_to_channel`] is a layer on muxspect's read routes: a request carrying `?channel=<name>`
10//! is sent, as it is minus that parameter, to that instance's own route and its answer returned.
11//! The layer sits on the routes named in `routes.rs` only. `dock/clear` and every other write is
12//! never behind it, so no instance can change another's state through this.
13
14use std::path::Path;
15use std::sync::OnceLock;
16use std::time::Duration;
17
18use axum::extract::Request;
19use axum::http::{header, HeaderValue, StatusCode};
20use axum::middleware::Next;
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23use serde_json::json;
24
25use crate::backend::instance_registry::{self, InstanceRecord};
26
27/// How long a forwarded request may take. These are diagnostic reads of a local process: a
28/// instance that does not answer in this time is reported, not waited for.
29const FORWARD_TIMEOUT: Duration = Duration::from_secs(5);
30/// The most of a forwarded answer that is passed on.
31const MAX_FORWARDED_BYTES: usize = 8 * 1024 * 1024;
32
33/// `GET /api/v1/muxspect/instances`: every live AgentMux instance on this machine (the caller's own
34/// is marked `self`), without their keys.
35pub async fn handle_muxspect_instances() -> impl IntoResponse {
36    let Some(dir) = crate::registry::resolve_shared_instances_dir() else {
37        return Json(json!({ "instances": [], "error": "this instance has no shared folder to list instances in" }));
38    };
39    let records = tokio::task::spawn_blocking(move || instance_registry::live_instances(&dir))
40        .await
41        .unwrap_or_default();
42    Json(listing_body(&records, std::process::id(), agentmux_common::time::now_ms_u64()))
43}
44
45fn listing_body(records: &[InstanceRecord], own_pid: u32, now_ms: u64) -> serde_json::Value {
46    json!({
47        "own_channel": crate::backend::reactive::registry::local_channel_id(),
48        "instances": records.iter().map(|r| r.listing(own_pid, now_ms)).collect::<Vec<_>>(),
49    })
50}
51
52/// The `channel` parameter of a query, and the query without it. `None` when the request names no
53/// channel (an empty `channel=` names none).
54fn split_channel(query: Option<&str>) -> Option<(String, String)> {
55    let mut channel = None;
56    let mut rest = url::form_urlencoded::Serializer::new(String::new());
57    for (k, v) in url::form_urlencoded::parse(query?.as_bytes()) {
58        if k == "channel" {
59            channel = Some(v.into_owned()).filter(|c| !c.is_empty());
60        } else {
61            rest.append_pair(&k, &v);
62        }
63    }
64    channel.map(|c| (c, rest.finish()))
65}
66
67fn error_response(status: StatusCode, message: String, known: &[InstanceRecord]) -> Response {
68    let channels: Vec<&str> = known.iter().map(|r| r.channel.as_str()).collect();
69    (status, Json(json!({ "error": message, "live_channels": channels }))).into_response()
70}
71
72/// How long the forwarded request for `path` may take: [`FORWARD_TIMEOUT`], except for the one read
73/// that samples for a while on purpose (`muxspect browsers`).
74fn forward_timeout(path: &str, query: &str) -> Duration {
75    if path == super::muxspect_browsers::PATH {
76        super::muxspect_browsers::longest_answer(query).max(FORWARD_TIMEOUT)
77    } else {
78        FORWARD_TIMEOUT
79    }
80}
81
82fn forward_client() -> &'static reqwest::Client {
83    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
84    // Loopback only: a proxy in the environment must never see these requests.
85    CLIENT.get_or_init(|| {
86        crate::http_client::client_with(|b| b.no_proxy().timeout(FORWARD_TIMEOUT))
87    })
88}
89
90/// A layer for muxspect's read routes. Without `?channel=`, or naming this instance's own channel,
91/// the request is served here as always.
92pub async fn forward_to_channel(req: Request, next: Next) -> Response {
93    let Some((channel, rest_query)) = split_channel(req.uri().query()) else {
94        return next.run(req).await;
95    };
96    if channel == crate::backend::reactive::registry::local_channel_id() {
97        return next.run(req).await;
98    }
99    let Some(dir) = crate::registry::resolve_shared_instances_dir() else {
100        return error_response(StatusCode::SERVICE_UNAVAILABLE, "this instance has no shared folder to find other instances in".into(), &[]);
101    };
102    let path = req.uri().path().to_string();
103    forward(&dir, &channel, &path, &rest_query, instance_registry::live_instances).await
104}
105
106/// Send `GET <path>?<query>` to the live instance on `channel`. `live` lists the live instances of
107/// `dir` (the real process table in production; a test passes its own).
108async fn forward(
109    dir: &Path,
110    channel: &str,
111    path: &str,
112    query: &str,
113    live: impl FnOnce(&Path) -> Vec<InstanceRecord> + Send + 'static,
114) -> Response {
115    let owned_dir = dir.to_path_buf();
116    let records = tokio::task::spawn_blocking(move || live(&owned_dir)).await.unwrap_or_default();
117    let Some(target) = records.iter().find(|r| r.channel == channel) else {
118        return error_response(StatusCode::NOT_FOUND, format!("no live AgentMux instance on channel '{channel}'"), &records);
119    };
120    let url = if query.is_empty() { format!("{}{path}", target.local_url) } else { format!("{}{path}?{query}", target.local_url) };
121    let sent = forward_client().get(url).timeout(forward_timeout(path, query)).header(agentmux_common::AUTH_KEY_HEADER, &target.auth_key).send().await;
122    match sent {
123        Ok(resp) => relay(resp, channel).await,
124        Err(e) => error_response(
125            StatusCode::BAD_GATEWAY,
126            format!("instance '{channel}' is listed but did not answer ({})", if e.is_timeout() { "timed out" } else { "connection failed" }),
127            &records,
128        ),
129    }
130}
131
132/// The body of `resp`, read chunk by chunk so that no more than `cap` bytes are ever held: `None`
133/// when it is larger (known from its Content-Length, or found out as it streams in).
134async fn read_capped(mut resp: reqwest::Response, cap: usize) -> Result<Option<Vec<u8>>, reqwest::Error> {
135    if resp.content_length().is_some_and(|len| len > cap as u64) {
136        return Ok(None);
137    }
138    let mut body = Vec::new();
139    while let Some(chunk) = resp.chunk().await? {
140        if body.len() + chunk.len() > cap {
141            return Ok(None);
142        }
143        body.extend_from_slice(&chunk);
144    }
145    Ok(Some(body))
146}
147
148/// The other instance's answer, as it gave it: its status, its content type and its body.
149async fn relay(resp: reqwest::Response, channel: &str) -> Response {
150    let status = StatusCode::from_u16(resp.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
151    let content_type = resp.headers().get(header::CONTENT_TYPE).cloned();
152    let version = resp.headers().get("x-agentmux-srv-version").cloned();
153    let body = match read_capped(resp, MAX_FORWARDED_BYTES).await {
154        Ok(Some(body)) => body,
155        Ok(None) => {
156            return error_response(StatusCode::BAD_GATEWAY, format!("instance '{channel}' answered with more than {MAX_FORWARDED_BYTES} bytes"), &[]);
157        }
158        Err(_) => return error_response(StatusCode::BAD_GATEWAY, format!("instance '{channel}' stopped answering part way"), &[]),
159    };
160    let mut out = (status, body).into_response();
161    let headers = out.headers_mut();
162    if let Some(v) = content_type {
163        headers.insert(header::CONTENT_TYPE, v);
164    }
165    // The caller's own version header is stamped over this by the version layer; the other
166    // instance's is kept under a name of its own so a stale-build 404 there still explains itself.
167    if let Some(v) = version {
168        headers.insert("x-agentmux-forwarded-srv-version", v);
169    }
170    if let Ok(v) = HeaderValue::from_str(channel) {
171        headers.insert("x-agentmux-forwarded-channel", v);
172    }
173    out
174}
175
176#[cfg(test)]
177#[path = "muxspect_instances_tests.rs"]
178mod tests;