1use super::*;
7
8pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
9 match name {
10 "UIScreenshot" => run_ui_screenshot(arguments, cx).await,
11 "UIRecord" => run_ui_record(arguments, cx).await,
12 "CaptureWindow" => run_capture_window(arguments, cx).await,
13 "DiscoverWindows" => run_discover_windows(arguments, cx).await,
14 "UIClick" => run_ui_click(arguments, cx).await,
15 "UIQuery" => run_ui_query(arguments, cx).await,
16 "ListShortcuts" => run_list_shortcuts(arguments, cx).await,
17 "RunCommand" => run_run_command(arguments, cx).await,
18 "PressKeys" => run_press_keys(arguments, cx).await,
19 "SetShortcut" => run_set_shortcut(arguments, cx).await,
20 "ResetShortcuts" => run_reset_shortcuts(arguments, cx).await,
21 _ => Err(not_in_family()),
22 }
23}
24
25async fn run_ui_screenshot(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
26 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
27 require_agent_env(local_url, auth_key, block_id)?;
28 let auth = sign_ui_automation_auth()?;
29 let region = region_arg(arguments)?;
30 let request = UiScreenshotRequest {
31 auth,
32 pane: pane_arg(arguments),
33 full_page: arguments.get("full_page").and_then(Value::as_bool),
34 region,
35 canvas: arguments.get("canvas").and_then(Value::as_str).map(str::trim).filter(|c| !c.is_empty()).map(str::to_string),
36 scale: scale_arg(arguments)?,
37 };
38 let result: UiScreenshotResponse = cx.post_as("/api/v1/ui/screenshot", &request, "screenshot").await?;
39 screenshot_text(&result, crate::self_keys::in_container(), &container_media_dir())
40}
41
42fn scale_arg(arguments: &Value) -> Result<Option<f64>> {
44 match arguments.get("scale") {
45 None | Some(Value::Null) => Ok(None),
46 Some(v) => v.as_f64().map(Some).ok_or_else(|| anyhow::anyhow!("scale is a number: device pixels per CSS pixel")),
47 }
48}
49
50fn region_arg(arguments: &Value) -> Result<Option<agentmux_common::api_types::ScreenshotRegion>> {
52 match arguments.get("region") {
53 None | Some(Value::Null) => Ok(None),
54 Some(v) => serde_json::from_value(v.clone()).map(Some).map_err(|_| anyhow::anyhow!("region needs x, y, width and height, numbers in CSS pixels")),
55 }
56}
57
58fn screenshot_text(result: &UiScreenshotResponse, in_container: bool, dir: &std::path::Path) -> Result<String> {
62 let note = result.note.as_deref().map(|n| format!(" {n}")).unwrap_or_default();
63 if !in_container {
64 return Ok(format!(
65 "Screenshot saved to {} — use Read on that path to view it yourself, or Pane (action \"open\", view \"media\") to show it to the user.{note}",
66 result.path
67 ));
68 }
69 let local = save_local_copy(dir, &result.png_base64, "png")?;
70 Ok(format!(
71 "Screenshot saved to {local} (inside your container) — use Read on that path to view it yourself, or pass it in `files` of Tasks update or submit, or of Message send.{note}"
72 ))
73}
74
75fn container_media_dir() -> std::path::PathBuf {
77 std::env::temp_dir().join("agentmux-media")
78}
79
80fn save_local_copy(dir: &std::path::Path, base64: &str, ext: &str) -> Result<String> {
83 use base64::Engine as _;
84 if base64.is_empty() {
85 anyhow::bail!("srv sent no image with the {ext}, so there is nothing to save in your container: the file is on the host and cannot be read from here");
86 }
87 let bytes = base64::engine::general_purpose::STANDARD
88 .decode(base64)
89 .map_err(|e| anyhow::anyhow!("the {ext} srv sent could not be decoded: {e}"))?;
90 std::fs::create_dir_all(dir).map_err(|e| anyhow::anyhow!("cannot make {}: {e}", dir.display()))?;
91 prune_old_media(dir);
92 let path = dir.join(format!("{}.{ext}", uuid::Uuid::new_v4()));
93 std::fs::write(&path, bytes).map_err(|e| anyhow::anyhow!("cannot save {}: {e}", path.display()))?;
94 Ok(path.to_string_lossy().into_owned())
95}
96
97fn prune_old_media(dir: &std::path::Path) {
99 let Ok(entries) = std::fs::read_dir(dir) else { return };
100 let now = std::time::SystemTime::now();
101 for entry in entries.flatten() {
102 let path = entry.path();
103 if !matches!(path.extension().and_then(|e| e.to_str()), Some("png" | "gif")) {
104 continue;
105 }
106 let old = entry.metadata().and_then(|m| m.modified()).ok().and_then(|m| now.duration_since(m).ok()).is_some_and(|age| age > crate::window_capture::CAPTURE_RETENTION);
107 if old {
108 let _ = std::fs::remove_file(&path);
109 }
110 }
111}
112
113async fn run_ui_record(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
114 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
115 require_agent_env(local_url, auth_key, block_id)?;
116 let auth = sign_ui_automation_auth()?;
117 let op = arguments.get("op").and_then(|v| v.as_str()).unwrap_or("").to_string();
118 if op != "start" && op != "stop" {
119 anyhow::bail!("record needs op: \"start\" to begin a recording, \"stop\" to end it and get the file");
120 }
121 let number = |key: &str| arguments.get(key).and_then(|v| v.as_u64()).map(|v| v.min(u64::from(u32::MAX)) as u32);
122 let request = UiRecordRequest {
123 auth,
124 op,
125 pane: pane_arg(arguments),
126 fps: number("fps"),
127 seconds: number("seconds"),
128 inline: crate::self_keys::in_container(),
129 };
130 let result: UiRecordResponse = cx.post_as("/api/v1/ui/record", &request, "record").await?;
131 record_text(&result, crate::self_keys::in_container(), &container_media_dir())
132}
133
134fn record_text(result: &UiRecordResponse, in_container: bool, dir: &std::path::Path) -> Result<String> {
137 let (true, Some(host_path)) = (in_container, result.path.as_deref()) else {
138 return Ok(result.message.clone());
139 };
140 let local = save_local_copy(dir, result.gif_base64.as_deref().unwrap_or_default(), "gif")?;
141 Ok(result.message.replace(host_path, &format!("{local} (inside your container)")))
142}
143
144async fn run_capture_window(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
145 let title_contains = arguments
153 .get("title_contains")
154 .and_then(|v| v.as_str())
155 .map(|s| s.to_string());
156 let index = arguments
157 .get("index")
158 .and_then(|v| v.as_u64())
159 .map(|v| v as usize);
160 let pid = arguments
161 .get("pid")
162 .and_then(|v| v.as_u64())
163 .map(|v| v as u32);
164
165 let query_desc = match (pid, title_contains.as_deref()) {
166 (Some(p), _) => format!("pid={p}"),
167 (None, Some(t)) => format!("title_contains={t:?}"),
168 (None, None) => "<no target given>".to_string(),
169 };
170
171 let mut resolved: Option<(CaptureTier, String)> = None;
184 let outcome = capture_blacked_out(title_contains.as_deref(), index, pid, &mut resolved, cx).await;
185 audit_log_capture_window(&query_desc, &outcome, &resolved);
186 outcome.map(|c| c.message)
187}
188
189async fn capture_blacked_out(
192 title_contains: Option<&str>,
193 index: Option<usize>,
194 pid: Option<u32>,
195 resolved: &mut Option<(CaptureTier, String)>,
196 cx: &ToolCtx<'_>,
197) -> Result<CaptureOutcome> {
198 use crate::window_blackout as wb;
199 if crate::self_keys::in_container() {
200 anyhow::bail!(wb::IN_CONTAINER);
201 }
202 let target = resolve_window(title_contains, index, pid, resolved)?;
203 if !target.is_agentmux {
204 let (image, unrendered) = capture_frame(&target)?;
205 return finish_capture(&target, &image, unrendered, false);
206 }
207 if !target.is_self {
208 anyhow::bail!(wb::OTHER_INSTANCE);
209 }
210 wb::unique_title(target.same_title, &target.title)?;
211 let capture_id = uuid::Uuid::new_v4().to_string();
212 let begins = capture_masks(cx, &capture_id, "begin").await?;
213 let begin = wb::before(&begins, &target.title)?.clone();
214 let (mut image, unrendered) = capture_frame(&target)?;
215 let ends = capture_masks(cx, &capture_id, "end").await?;
216 wb::after(&begin, &ends, image.width(), image.height())?;
217 wb::black_out(&mut image, &begin);
218 finish_capture(&target, &image, unrendered, true)
219}
220
221async fn capture_masks(cx: &ToolCtx<'_>, capture_id: &str, phase: &str) -> Result<Vec<crate::window_blackout::WindowMask>> {
223 let ToolCtx { local_url, auth_key, client, .. } = *cx;
224 if local_url.is_empty() || auth_key.is_empty() {
225 anyhow::bail!("AgentMux windows can't be captured without srv, which gives the rectangles of their private panes");
226 }
227 let url = format!("{}/api/v1/ui/capture_mask", local_url.trim_end_matches('/'));
228 let resp = client
229 .post(&url)
230 .header(AUTH_KEY_HEADER, auth_key)
231 .json(&json!({ "capture_id": capture_id, "phase": phase }))
232 .timeout(std::time::Duration::from_secs(10))
233 .send()
234 .await
235 .map_err(|e| anyhow::anyhow!("the rectangles of the window's private panes could not be read, so it is not captured: {e}"))?;
236 let status = resp.status();
237 let body: Value = resp.json().await.unwrap_or_else(|_| json!({}));
238 if !status.is_success() {
239 anyhow::bail!("{}", body.get("error").and_then(Value::as_str).unwrap_or("the rectangles of the window's private panes could not be read, so it is not captured"));
240 }
241 serde_json::from_value(body.get("masks").cloned().unwrap_or_else(|| json!([])))
242 .map_err(|e| anyhow::anyhow!("srv's answer for the window's private panes was not understood, so it is not captured: {e}"))
243}
244
245async fn run_discover_windows(arguments: &Value, _cx: &ToolCtx<'_>) -> Result<String> {
246 let include_self = arguments
247 .get("include_self")
248 .and_then(|v| v.as_bool())
249 .unwrap_or(false);
250 let include_foreign = arguments
256 .get("include_foreign")
257 .and_then(|v| v.as_bool())
258 .unwrap_or(false);
259 let windows = enumerate_agentmux_windows()?;
260 let list: Vec<Value> = windows
261 .iter()
262 .filter(|w| include_self || !w.is_self)
271 .filter(|w| include_foreign || w.is_agentmux)
272 .map(window_listing_entry)
273 .collect();
274 audit_log_discover_windows(include_self, include_foreign, &list);
279 return Ok(serde_json::to_string_pretty(&json!({ "windows": list }))
280 .unwrap_or_else(|_| "{\"windows\":[]}".to_string()));
281}
282
283async fn run_ui_click(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
284 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
285 require_agent_env(local_url, auth_key, block_id)?;
286 let auth = sign_ui_automation_auth()?;
287 let selector = arguments
288 .get("selector")
289 .and_then(|v| v.as_str())
290 .ok_or_else(|| anyhow::anyhow!("missing required parameter: selector"))?;
291 let request = UiClickRequest { auth, pane: pane_arg(arguments), selector: selector.to_string() };
292 cx.post("/api/v1/ui/click", &request, "click").await?;
293 Ok(format!("Clicked {selector:?}"))
294}
295
296async fn run_ui_query(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
297 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
298 require_agent_env(local_url, auth_key, block_id)?;
299 let auth = sign_ui_automation_auth()?;
300 let selector = arguments
301 .get("selector")
302 .and_then(|v| v.as_str())
303 .ok_or_else(|| anyhow::anyhow!("missing required parameter: selector"))?;
304 let limit = arguments.get("limit").and_then(|v| v.as_u64()).map(|n| n as u32);
305 let request = UiQueryRequest { auth, pane: pane_arg(arguments), selector: selector.to_string(), limit };
306 let body: Value = cx.post_as("/api/v1/ui/query", &request, "query").await?;
307 let matches = body
308 .get("data")
309 .and_then(|d| d.get("matches"))
310 .cloned()
311 .unwrap_or_else(|| json!([]));
312 Ok(serde_json::to_string_pretty(&matches).unwrap_or_else(|_| matches.to_string()))
313}
314
315async fn run_list_shortcuts(_arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
316 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
317 require_agent_env(local_url, auth_key, block_id)?;
318 let auth = sign_ui_automation_auth()?;
319 let data = post_shortcuts(cx, "list", &UiShortcutsListRequest { auth }).await?;
320 let list = data.get("shortcuts").cloned().unwrap_or_else(|| json!([]));
321 Ok(serde_json::to_string_pretty(&list).unwrap_or_else(|_| list.to_string()))
322}
323
324async fn run_run_command(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
325 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
326 require_agent_env(local_url, auth_key, block_id)?;
327 let auth = sign_ui_automation_auth()?;
328 let command = arguments
329 .get("command")
330 .and_then(|v| v.as_str())
331 .ok_or_else(|| anyhow::anyhow!("missing required parameter: command"))?;
332 let req = UiRunCommandRequest { auth, command: command.to_string(), target: str_arg(arguments, "target") };
333 let data = post_shortcuts(cx, "run", &req).await?;
334 if data.get("ran").and_then(|v| v.as_bool()) == Some(true) {
335 Ok(format!("Ran {command}."))
336 } else if let Some(pending) = data.get("pending") {
337 let why = data.get("reason").and_then(|v| v.as_str()).unwrap_or("waiting for the user");
339 let id = pending.get("request_id").and_then(|v| v.as_str()).unwrap_or("?");
340 Ok(format!("{command} is pending: {why} (request {id})."))
341 } else {
342 let why = data.get("reason").and_then(|v| v.as_str()).unwrap_or("no reason given");
343 Ok(format!("Didn't run {command}: {why}"))
344 }
345}
346
347async fn run_press_keys(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
348 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
349 require_agent_env(local_url, auth_key, block_id)?;
350 let auth = sign_ui_automation_auth()?;
351 let keys = arguments
352 .get("keys")
353 .and_then(|v| v.as_str())
354 .ok_or_else(|| anyhow::anyhow!("missing required parameter: keys"))?;
355 let req = UiPressKeysRequest { auth, keys: keys.to_string(), target: str_arg(arguments, "target") };
356 let data = post_shortcuts(cx, "press", &req).await?;
357 Ok(serde_json::to_string_pretty(&data).unwrap_or_else(|_| data.to_string()))
358}
359
360async fn run_set_shortcut(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
362 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
363 require_agent_env(local_url, auth_key, block_id)?;
364 let auth = sign_ui_automation_auth()?;
365 let command = str_arg(arguments, "command").ok_or_else(|| anyhow::anyhow!("missing required parameter: command"))?;
366 let bindings = match arguments.get("bindings") {
367 Some(v) => v
368 .as_array()
369 .ok_or_else(|| anyhow::anyhow!("`bindings` must be a list of keys (an empty list unbinds the command)"))?
370 .iter()
371 .map(|k| k.as_str().map(str::to_string).ok_or_else(|| anyhow::anyhow!("`bindings` must be a list of strings")))
372 .collect::<Result<Vec<_>>>()?,
373 None => return Err(anyhow::anyhow!("missing required parameter: bindings (a list of keys; empty to unbind the command)")),
374 };
375 let req = UiSetShortcutRequest { auth, command, bindings, when: str_arg(arguments, "when") };
376 let data = post_shortcuts(cx, "set", &req).await?;
377 Ok(shortcut_edit_said(&data))
378}
379
380async fn run_reset_shortcuts(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
382 let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
383 require_agent_env(local_url, auth_key, block_id)?;
384 let auth = sign_ui_automation_auth()?;
385 let all = arguments.get("all").and_then(|v| v.as_bool()).unwrap_or(false);
386 let req = UiResetShortcutsRequest { auth, command: str_arg(arguments, "command"), all };
387 let data = post_shortcuts(cx, "reset", &req).await?;
388 Ok(shortcut_edit_said(&data))
389}
390
391fn shortcut_edit_said(data: &Value) -> String {
393 if data.get("changed").and_then(|v| v.as_bool()) == Some(true) {
394 let summary = data.get("summary").and_then(|v| v.as_str()).unwrap_or("changed");
395 let note = data.get("note").and_then(|v| v.as_str()).unwrap_or("");
396 return format!("Changed: {summary}. {note}").trim_end().to_string();
397 }
398 let why = data.get("reason").and_then(|v| v.as_str()).unwrap_or("no reason given");
399 format!("Not changed: {why}")
400}
401
402async fn post_shortcuts<T: serde::Serialize>(cx: &ToolCtx<'_>, route: &str, body: &T) -> Result<Value> {
404 let url = format!("{}/api/v1/ui/shortcuts/{route}", cx.local_url.trim_end_matches('/'));
405 let resp = cx
406 .client
407 .post(&url)
408 .header(AUTH_KEY_HEADER, cx.auth_key)
409 .json(body)
410 .send()
411 .await
412 .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
413 let status = resp.status();
414 let body: Value = resp.json().await.unwrap_or(Value::Null);
415 if !status.is_success() || body.get("ok").and_then(|v| v.as_bool()) != Some(true) {
416 let err = body.get("error").and_then(|v| v.as_str()).unwrap_or("no error message");
417 anyhow::bail!("shortcuts/{route} failed: HTTP {status} — {err}");
418 }
419 Ok(body.get("data").cloned().unwrap_or(Value::Null))
420}
421
422#[cfg(test)]
423mod call_tests;