agentmux_mcp/tools/
widgets.rs1use super::*;
9
10const INSTALL_WAIT_SECS: u64 = 300;
12const INSTALL_WAIT_MAX_SECS: u64 = 600;
13
14fn require_srv(local_url: &str, auth_key: &str) -> Result<()> {
15 if local_url.is_empty() || auth_key.is_empty() {
16 anyhow::bail!("AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. Is this agent pane opened via AgentMux?");
17 }
18 Ok(())
19}
20
21async fn list(cx: &ToolCtx<'_>) -> Result<Vec<Value>> {
22 let url = format!("{}/api/v1/widgets", cx.local_url.trim_end_matches('/'));
23 let resp = cx.client.get(&url).header(AUTH_KEY_HEADER, cx.auth_key).send().await.map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
24 if !resp.status().is_success() {
25 let status = resp.status();
26 anyhow::bail!("listing widgets failed: HTTP {status}: {}", resp.text().await.unwrap_or_default());
27 }
28 let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("response parse failed: {e}"))?;
29 Ok(body.get("packages").and_then(Value::as_array).cloned().unwrap_or_default())
30}
31
32pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
33 match name {
34 "WidgetList" => run_widget_list(arguments, cx).await,
35 "WidgetInstall" => run_widget_install(arguments, cx).await,
36 "OpenWidget" => run_open_widget(arguments, cx).await,
37 _ => Err(not_in_family()),
38 }
39}
40
41async fn run_widget_list(_arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
42 require_srv(cx.local_url, cx.auth_key)?;
43 let rows: Vec<Value> = list(cx)
44 .await?
45 .iter()
46 .map(|p| {
47 json!({
48 "id": p["id"], "name": p["name"], "version": p["version"], "kind": p["kind"], "state": p["state"],
49 "permissions": p["permissions"], "error": p["error"], "folder": p["folder"],
50 "views": p["panes"].as_array().map(|ps| ps.iter().map(|x| x["view"].clone()).collect::<Vec<_>>()).unwrap_or_default(),
51 })
52 })
53 .collect();
54 Ok(serde_json::to_string_pretty(&json!({ "widgets": rows })).unwrap_or_default())
55}
56
57async fn run_widget_install(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
58 require_srv(cx.local_url, cx.auth_key)?;
59 let path = arguments
60 .get("path")
61 .and_then(Value::as_str)
62 .filter(|s| !s.is_empty())
63 .ok_or_else(|| anyhow::anyhow!("missing required parameter: path"))?;
64 let wait = arguments.get("wait_secs").and_then(Value::as_u64).unwrap_or(INSTALL_WAIT_SECS).min(INSTALL_WAIT_MAX_SECS);
65 let body = json!({
68 "path": resolve_workdir_path(path),
69 "replace": arguments.get("replace").and_then(Value::as_bool).unwrap_or(true),
70 "auth": crate::identity::sign_ui_automation_auth().ok(),
71 "wait_secs": wait,
72 });
73 let url = format!("{}/api/v1/widgets/install", cx.local_url.trim_end_matches('/'));
74 let resp = cx
75 .client
76 .post(&url)
77 .header(AUTH_KEY_HEADER, cx.auth_key)
78 .timeout(std::time::Duration::from_secs(wait + 60))
79 .json(&body)
80 .send()
81 .await
82 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
83 let status = resp.status();
84 let result: Value = resp.json().await.unwrap_or_default();
85 if !status.is_success() {
86 anyhow::bail!("the widget wasn't installed: {}", result["error"].as_str().unwrap_or("unknown error"));
87 }
88 let mut result = result;
89 if result["status"] == "requested" {
90 result["message"] = json!(format!(
91 "Asked for the install as a sensitive operation ({}). If the super agent approves, the person sees a \
92 countdown and can veto it, and the widget is installed when it ends; you'll get [AgentMux] notes as it \
93 goes. Widget list shows when it is approved; then open it.",
94 result["review"].as_str().unwrap_or("")
95 ));
96 }
97 Ok(serde_json::to_string_pretty(&result).unwrap_or_default())
98}
99
100async fn run_open_widget(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
101 require_srv(cx.local_url, cx.auth_key)?;
102 let view = arguments
103 .get("view")
104 .and_then(Value::as_str)
105 .filter(|s| !s.is_empty())
106 .ok_or_else(|| anyhow::anyhow!("missing required parameter: view"))?;
107 let packages = list(cx).await?;
108 let found = packages.iter().find_map(|p| {
109 p["panes"].as_array().and_then(|ps| ps.iter().find(|x| x["view"] == view)).map(|pane| (p, pane))
110 });
111 let Some((pkg, pane)) = found else {
112 anyhow::bail!("no installed widget has the view {view}; Widget action \"list\" shows the views there are");
113 };
114 if pkg["state"] != "approved" {
115 anyhow::bail!(
116 "{} is {}, so it can't open; the user approves or turns it on in Settings → Widgets",
117 pkg["id"].as_str().unwrap_or(""),
118 pkg["state"].as_str().unwrap_or("not approved")
119 );
120 }
121 let id = pkg["id"].as_str().unwrap_or_default();
124 let mut meta = pane["default_meta"].as_object().cloned().unwrap_or_default();
125 if let Some(own) = arguments.get("meta").and_then(Value::as_object) {
126 for (k, v) in own {
127 meta.insert(format!("widget:{id}:{k}"), v.clone());
128 }
129 }
130 meta.insert("view".into(), json!(view));
131 let split = arguments.get("split").and_then(Value::as_str).filter(|s| matches!(*s, "right" | "down"));
132 let mut req = json!({ "view": view, "meta": meta, "focus": true });
133 if !cx.block_id.is_empty() {
135 if let Some(split) = split {
136 req["split_direction"] = json!(split);
137 }
138 req["split_reference_block_id"] = json!(cx.block_id);
139 }
140 if arguments.get("floating").and_then(Value::as_bool) == Some(true) {
141 req["floating"] = json!(true);
142 let place = agentmux_common::api_types::PlaceArgs::of(arguments).map_err(|e| anyhow::anyhow!("INVALID_ARG: {e}"))?;
143 if let Value::Object(fields) = serde_json::to_value(place)? {
144 if let Some(o) = req.as_object_mut() {
145 o.extend(fields);
146 }
147 }
148 }
149 let url = format!("{}/api/v1/pane/open", cx.local_url.trim_end_matches('/'));
150 let resp = cx
151 .client
152 .post(&url)
153 .header(AUTH_KEY_HEADER, cx.auth_key)
154 .json(&req)
155 .send()
156 .await
157 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
158 let status = resp.status();
159 let result: Value = resp.json().await.unwrap_or_default();
160 if !status.is_success() {
161 anyhow::bail!("the pane didn't open: HTTP {status}: {result}");
162 }
163 let placed = serde_json::from_value::<agentmux_common::api_types::PaneOpenResponse>(result.clone()).map(|r| super::panes::placed_note(&r)).unwrap_or_default();
164 Ok(format!("Opened {view} (pane {}).{placed}", result["block_id"].as_str().unwrap_or("?")))
165}
166
167#[cfg(test)]
168mod call_tests;