Skip to main content

agentmux_mcp/
srv_http.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! HTTP helpers for calls to the sidecar srv.
5//! Split out of main.rs unchanged (SPEC_LARGE_FILE_MODULE_ANALYSIS_2026_09_30.md §4.2).
6
7use super::*;
8
9/// Said wherever a tool finds this agent has no AgentMux credential. An agent that went looking for the
10/// key (in AgentMux's config, other agents' folders, the process list) was working around a launch fault
11/// it could not fix, and reading what it was never given.
12pub(crate) const NO_KEY_HUNT: &str = "Don't search AgentMux's config files, other agents' folders or \
13    the process list for a key: an agent is never given one that way. Tell your leader or the operator \
14    that this agent's AgentMux tools have no auth key, so they fix how it was launched.";
15
16/// Guard for the self-scoped agent-API verbs: they need the sidecar URL +
17/// auth key to reach it, and the caller's block id to resolve "my own"
18/// tab/pane/window/workspace.
19pub(crate) fn require_agent_env(local_url: &str, auth_key: &str, block_id: &str) -> Result<()> {
20    if local_url.is_empty() || auth_key.is_empty() {
21        anyhow::bail!(
22            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
23             Is this agent pane opened via AgentMux? {NO_KEY_HUNT}"
24        );
25    }
26    if block_id.is_empty() {
27        anyhow::bail!(
28            "neither AGENTMUX_AGENT_BUS_ID nor AGENTMUX_BLOCKID is set \
29             — cannot resolve this agent's context. Is this agent pane opened via AgentMux?"
30        );
31    }
32    Ok(())
33}
34
35/// GET a srv route and return its JSON body, with every failure described by
36/// what actually happened (#3473). reqwest's own message for a refused
37/// connection or a timeout is only "error sending request for url (…)", which
38/// reads like a network fault whatever the cause; and parsing the body before
39/// checking the status loses the status whenever an error body isn't JSON.
40/// So: refused / timed out / other transport failures are told apart, the
41/// status is checked first, and an error carries srv's own `error` message,
42/// else the raw body.
43pub(crate) async fn srv_get_json(
44    client: &reqwest::Client,
45    url: &str,
46    auth_key: &str,
47    query: &[(&str, String)],
48    what: &str,
49) -> Result<Value> {
50    let resp = client
51        .get(url)
52        .header(AUTH_KEY_HEADER, auth_key)
53        .query(query)
54        .send()
55        .await
56        .map_err(|e| anyhow::anyhow!(describe_transport_error(what, url, &e)))?;
57    let status = resp.status();
58    let text = resp
59        .text()
60        .await
61        .map_err(|e| anyhow::anyhow!("{what}: reading AgentMux's response failed: {e}"))?;
62    if !status.is_success() {
63        anyhow::bail!(describe_http_error(what, status, &text));
64    }
65    serde_json::from_str(&text).map_err(|e| {
66        anyhow::anyhow!("{what}: AgentMux answered HTTP {status} but not with JSON ({e})")
67    })
68}
69
70/// POST a JSON body to a srv route and return its JSON answer, failures
71/// described as [`srv_get_json`] describes them.
72pub(crate) async fn srv_post_json(
73    client: &reqwest::Client,
74    url: &str,
75    auth_key: &str,
76    body: &Value,
77    what: &str,
78) -> Result<Value> {
79    srv_post_json_within(client, url, auth_key, body, what, None).await
80}
81
82/// [`srv_post_json`] with its own time limit, for a call that waits for the person's answer.
83pub(crate) async fn srv_post_json_within(
84    client: &reqwest::Client,
85    url: &str,
86    auth_key: &str,
87    body: &Value,
88    what: &str,
89    timeout: Option<std::time::Duration>,
90) -> Result<Value> {
91    let mut req = client.post(url).header(AUTH_KEY_HEADER, auth_key).json(body);
92    if let Some(t) = timeout {
93        req = req.timeout(t);
94    }
95    let resp = req
96        .send()
97        .await
98        .map_err(|e| anyhow::anyhow!(describe_transport_error(what, url, &e)))?;
99    let status = resp.status();
100    let text = resp
101        .text()
102        .await
103        .map_err(|e| anyhow::anyhow!("{what}: reading AgentMux's response failed: {e}"))?;
104    if !status.is_success() {
105        anyhow::bail!(describe_http_error(what, status, &text));
106    }
107    serde_json::from_str(&text).map_err(|e| {
108        anyhow::anyhow!("{what}: AgentMux answered HTTP {status} but not with JSON ({e})")
109    })
110}
111
112pub(crate) fn describe_transport_error(what: &str, url: &str, e: &reqwest::Error) -> String {
113    let mut causes = String::new();
114    let mut source = std::error::Error::source(e);
115    while let Some(s) = source {
116        causes.push_str(&format!(": {s}"));
117        source = s.source();
118    }
119    if e.is_timeout() {
120        format!(
121            "{what} timed out: AgentMux didn't answer in time. This is not an empty result — retry, \
122             or ask for less"
123        )
124    } else if e.is_connect() {
125        format!(
126            "{what}: can't reach AgentMux at {url}{causes}. Is it still running? An agent started \
127             by an AgentMux that has since restarted must be reopened."
128        )
129    } else {
130        format!("{what}: the request to AgentMux failed: {e}{causes}")
131    }
132}
133
134pub(crate) fn describe_http_error(what: &str, status: reqwest::StatusCode, body: &str) -> String {
135    let detail = serde_json::from_str::<Value>(body)
136        .ok()
137        .and_then(|v| v.get("error").and_then(Value::as_str).map(str::to_string))
138        .unwrap_or_else(|| {
139            let body = body.trim();
140            if body.is_empty() {
141                "(no body)".to_string()
142            } else {
143                body.chars().take(300).collect()
144            }
145        });
146    let hint = match status.as_u16() {
147        401 => {
148            " — AgentMux rejected this process's auth key (AGENTMUX_AUTH_KEY). The agent was \
149             probably started by an AgentMux that has since restarted; reopen it. \
150             Don't look for another key: ask your leader or the operator."
151        }
152        503 => " — temporary; retry shortly.",
153        _ => "",
154    };
155    format!("{what} failed (HTTP {status}): {detail}{hint}")
156}
157
158/// How long a Shell or PtyShell create may take: one on an SSH host the user
159/// has not allowed yet waits for their answer in a consent dialog (srv gives
160/// them two minutes), well past the client's usual 10 s.
161pub(crate) const SHELL_CREATE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(150);