agentmux_mcp/tools/
remote_op.rs1use super::*;
13
14pub(super) fn host_arg(arguments: &Value) -> Option<String> {
16 arguments.get("host").and_then(Value::as_str).map(str::trim).filter(|h| !h.is_empty()).map(str::to_string)
17}
18
19pub(crate) async fn remote_op_call(cx: &ToolCtx<'_>, host: &str, op: &str, params: Value, reason: &str) -> Result<Value> {
22 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
23 let url = format!("{}/api/v1/agent/remote/op", cx.local_url.trim_end_matches('/'));
24 let body = json!({ "agent_id": agent_slug()?, "host": host, "op": op, "params": params, "reason": reason });
25 let resp = cx
26 .client
27 .post(&url)
28 .header(AUTH_KEY_HEADER, cx.auth_key)
29 .json(&body)
30 .send()
31 .await
32 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
33 let status = resp.status();
34 let answer: Value = resp.json().await.unwrap_or(Value::Null);
35 if !status.is_success() {
36 anyhow::bail!("{op} on {host}: srv answered {status}: {}", answer["error"].as_str().unwrap_or(&answer.to_string()));
37 }
38 Ok(answer)
39}
40
41pub(crate) fn explain_not_done(host: &str, op: &str, answer: &Value) -> Option<String> {
43 match answer["status"].as_str() {
44 Some("done") => None,
45 Some("queued") | Some("pending_veto") => None,
46 Some("refused") => {
47 let why = answer["refused_reason"].as_str().unwrap_or("no reason given");
48 let message = answer["result"]["message"].as_str().map(|m| format!(": {m}")).unwrap_or_default();
49 let hint = if message.is_empty() { refusal_hint(why) } else if matches!(why, "unknown_op" | "peer_cannot_do_remote_ops") { String::new() } else { refusal_hint(why) };
51 let head = format!("{host} refused {op} ({why}){message}");
53 let head = head.trim_end().trim_end_matches('.');
54 Some(if hint.is_empty() { format!("{head}.") } else { format!("{head}. {hint}") })
55 }
56 _ => Some(format!("{op} on {host} failed: {}", answer["result"]["error"].as_str().unwrap_or("no reason given"))),
57 }
58}
59
60fn refusal_hint(reason: &str) -> String {
62 let hint: &str = match reason {
63 "remote_ops_off" => "That machine has turned remote operations off (network:remote_ops in its settings).",
64 "unknown_sender" | "unverified_sender" => "That machine does not yet trust this agent's key: ask one of its agents to jekt you once, so each side pins the other, then retry.",
65 "bad_signature" | "wrong_audience" | "stale_request" => "Check that both machines' clocks are right and both run a build with remote operations.",
66 "needs_certificate" => "That machine holds no certificate from your agent's install. Approve this install on that machine (the instance is listed there), then retry; a first-seen peer is not enough for account data or changes.",
67 "install_not_trusted" => "That machine has not approved the install your agent runs on. Approve this instance on that machine, then retry.",
68 "unknown_op" | "peer_cannot_do_remote_ops" => {
69 return format!("That machine's AgentMux is too old for this: update it to AgentMux {} or newer.", env!("CARGO_PKG_VERSION"));
70 }
71 _ => "",
72 };
73 hint.to_string()
74}
75
76pub(crate) fn pretty(host: &str, answer: &Value) -> String {
78 let body = serde_json::to_string_pretty(&answer["result"]).unwrap_or_else(|_| answer["result"].to_string());
79 let status = answer["status"].as_str().unwrap_or("done");
80 let mark = if status == "done" { String::new() } else { format!(" [{status}]") };
81 format!("From {host}{mark}:\n{body}")
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn a_refusal_for_an_older_machine_names_the_version_to_update_to_once() {
90 let own = env!("CARGO_PKG_VERSION");
91 let with = json!({ "status": "refused", "refused_reason": "peer_cannot_do_remote_ops", "result": { "message": "Area54 runs AgentMux 0.60.31, which is too old to do remote operations: update it to AgentMux 0.60.53 or newer." } });
93 let said = explain_not_done("Area54", "agents.list", &with).unwrap();
94 assert!(said.contains("0.60.31") && said.matches("update it to").count() == 1, "{said}");
95 assert!(!said.contains(".."), "{said}");
96 for reason in ["peer_cannot_do_remote_ops", "unknown_op"] {
98 let bare = json!({ "status": "refused", "refused_reason": reason, "result": null });
99 let said = explain_not_done("Area54", "agents.list", &bare).unwrap();
100 assert!(said.ends_with(&format!("update it to AgentMux {own} or newer.")), "{said}");
101 }
102 }
103
104 #[test]
105 fn a_blank_host_is_this_machine() {
106 assert_eq!(host_arg(&json!({})), None);
107 assert_eq!(host_arg(&json!({ "host": " " })), None);
108 assert_eq!(host_arg(&json!({ "host": " narko " })), Some("narko".to_string()));
109 }
110
111 #[test]
112 fn a_refusal_says_who_refused_why_and_what_to_do() {
113 let answer = json!({ "status": "refused", "refused_reason": "remote_ops_off", "result": null });
114 let text = explain_not_done("narko", "app.version", &answer).unwrap();
115 assert!(text.contains("narko refused app.version (remote_ops_off)") && text.contains("network:remote_ops"), "{text}");
116 let none = json!({ "status": "refused", "result": null });
117 assert!(explain_not_done("narko", "app.version", &none).unwrap().contains("no reason given"));
118 }
119
120 #[test]
121 fn a_done_or_waiting_answer_is_not_an_error() {
122 for status in ["done", "queued", "pending_veto"] {
123 assert!(explain_not_done("narko", "x", &json!({ "status": status })).is_none(), "{status}");
124 }
125 assert!(explain_not_done("narko", "x", &json!({ "status": "failed", "result": { "error": "boom" } })).unwrap().contains("boom"));
126 }
127
128 #[test]
129 fn the_answer_names_the_machine() {
130 let text = pretty("narko", &json!({ "status": "done", "result": { "version": "0.60.7" } }));
131 assert!(text.starts_with("From narko:") && text.contains("0.60.7"), "{text}");
132 assert!(pretty("narko", &json!({ "status": "queued", "result": {} })).starts_with("From narko [queued]:"));
133 }
134}