1use super::*;
8
9pub(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
16pub(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
35pub(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
70pub(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
82pub(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
158pub(crate) const SHELL_CREATE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(150);