Skip to main content

agentmux_mcp/tools/
panes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Panes, tabs and windows: open, name, arrange, focus, close; the agent's own
5//! identity and lifecycle. Not advertised: `Pane` (pane_tool.rs), `Stop`
6//! (stop_tool.rs) and `Agents` (agents_tool.rs) call these by their old
7//! names, and RegisterDevServer passes through Pane unchanged.
8
9use super::*;
10
11pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
12    match name {
13        "OpenEditor" | "OpenMedia" => run_open_editor(name, arguments, cx).await,
14        "OpenFiles" => run_open_files(arguments, cx).await,
15        "OpenLink" => run_open_link(arguments, cx).await,
16        "OpenAgent" => run_open_agent(arguments, cx).await,
17        "WhoAmI" => run_who_am_i(arguments, cx).await,
18        "SetName" => run_set_name(arguments, cx).await,
19        "Layout" => run_layout(arguments, cx).await,
20        "SetActiveTab" => run_set_active_tab(arguments, cx).await,
21        "NewTab" => run_new_tab(arguments, cx).await,
22        "FocusWindow" => run_focus_window(arguments, cx).await,
23        "ClosePane" => run_close_pane(arguments, cx).await,
24        "ResizePane" => run_place_pane("resize", arguments, cx).await,
25        "MovePane" => run_place_pane("move", arguments, cx).await,
26        "PlacePane" => run_place_pane("place", arguments, cx).await,
27        "DockPane" => run_place_pane("dock", arguments, cx).await,
28        "FloatPane" => run_place_pane("float", arguments, cx).await,
29        "PinPane" => run_place_pane("pin", arguments, cx).await,
30        "UnpinPane" => run_place_pane("unpin", arguments, cx).await,
31        "QuitSelf" => run_quit_self(arguments, cx).await,
32        "RegisterDevServer" => run_register_dev_server(arguments, cx).await,
33        _ => Err(not_in_family()),
34    }
35}
36
37/// OpenMedia is an alias of OpenEditor since the Media pane was folded
38/// into the Editor: the same open, with the tab following newer files
39/// in the folder. SPEC_EDITOR_REVAMP_UNIFIED_VIEWERS_2026_10_15.md §4.11.
40async fn run_open_editor(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
41    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
42    let media = name == "OpenMedia";
43    let connection = connection_arg(arguments);
44    let (viewer, line, offset, page) = viewer_args(arguments);
45    let file = arguments
46        .get("file")
47        .and_then(|v| v.as_str())
48        .filter(|s| !s.is_empty())
49        .ok_or_else(|| anyhow::anyhow!("missing required parameter: file"))?;
50
51    if local_url.is_empty() || auth_key.is_empty() {
52        anyhow::bail!(
53            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
54             Is this agent pane opened via AgentMux?"
55        );
56    }
57    let split = arguments
58        .get("split")
59        .and_then(|v| v.as_str())
60        .filter(|s| matches!(*s, "right" | "left" | "down" | "up"));
61
62    // Place the editor relative to the calling agent pane when we know
63    // its block id (AGENTMUX_BLOCKID); otherwise the sidecar inserts it
64    // at the tab root.
65    // Only a split the agent asked for is sent: with none, srv opens the pane as a tab of the agent's own pane group.
66    let split_direction = split.map(str::to_string);
67    let split_reference_block_id = (!block_id.is_empty()).then(|| block_id.to_string());
68    let req = PaneOpenRequest {
69        view: "editor".to_string(),
70        file: Some(file.to_string()),
71        focus: Some(true),
72        split_direction,
73        split_reference_block_id,
74        title: arguments.get("title").and_then(|v| v.as_str()).map(str::to_string),
75        // `collapse_tree` maps to the editor's `tree_expanded` meta (collapsed == not expanded):
76        // true collapses, false opens it expanded, absent leaves it to the Editor (collapsed
77        // for a file).
78        tree_expanded: arguments.get("collapse_tree").and_then(|v| v.as_bool()).map(|collapse| !collapse),
79        floating: arguments.get("floating").and_then(|v| v.as_bool()).filter(|f| *f),
80        url: None,
81        cwd: None,
82        tab_id: None,
83        // Reuse an already-open Editor pane in this agent's own tab
84        // instead of always spawning a new one — the explicit opt-in
85        // only OpenEditor sets (see reuse_editor_pane's doc comment on
86        // PaneOpenRequest for why this can't be inferred from
87        // split_reference_block_id alone).
88        reuse_editor_pane: Some(true),
89        target_block_id: arguments.get("target_id").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string),
90        follow_folder: media.then_some(true),
91        viewer,
92        line,
93        offset,
94        page,
95        select: None,
96        // On an SSH host: srv asks the user to allow it, checking this
97        // agent's signed identity (remote terminals spec §8.2).
98        auth: if connection.is_some() { Some(sign_ui_automation_auth()?) } else { None },
99        connection,
100        place: PlaceArgs::of(arguments).map_err(|e| anyhow::anyhow!("INVALID_ARG: {e}"))?,
101    };
102
103    let result: PaneOpenResponse = cx.post_as("/api/v1/pane/open", &req, "pane.open").await?;
104
105    let note = format!("{}{}", result.note.as_deref().map(|n| format!(" {n}")).unwrap_or_default(), placed_note(&result));
106    Ok(if media {
107        format!(
108            "Opened {file} in the editor (block {}); OpenMedia is now an alias of OpenEditor.{note}",
109            result.block_id
110        )
111    } else {
112        format!("Opened {file} in editor pane (block {}).{note}", result.block_id)
113    })
114}
115
116/// What a floating open says about where its window went, for the agent: the rect it got, and whether it had
117/// to be pulled in; or that the window has not answered yet.
118pub(super) fn placed_note(r: &PaneOpenResponse) -> String {
119    if let Some(p) = &r.placed {
120        let n = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(0.0);
121        let spot = p.get("spot").and_then(Value::as_str).map(|s| format!(", spot {s}")).unwrap_or_default();
122        let clamped = if p.get("clamped").and_then(Value::as_bool) == Some(true) {
123            " It was pulled into the work area or raised to the minimum size."
124        } else {
125            ""
126        };
127        return format!(
128            " Floating at x {}, y {}, {} x {} (CSS pixels from the work area's top-left{spot}; display scale {}).{clamped}",
129            n("x"),
130            n("y"),
131            n("width"),
132            n("height"),
133            n("display_scale")
134        );
135    }
136    if r.queued {
137        return " The floating window has not answered yet (it is hidden or starting): it takes its place when it opens.".to_string();
138    }
139    String::new()
140}
141
142/// What a floating `open` says about where its window went (`placed`, or `queued`), from srv's `data`.
143pub(super) fn floating_note(data: Option<&Value>) -> String {
144    let Some(d) = data else { return String::new() };
145    let answered = agentmux_common::api_types::PaneOpenResponse {
146        block_id: String::new(),
147        placed: d.get("placed").filter(|v| !v.is_null()).cloned(),
148        queued: d.get("queued").and_then(Value::as_bool) == Some(true),
149        note: None,
150    };
151    placed_note(&answered)
152}
153
154/// The deep link a `Pane` open names: `link` as given, or one written from `view`, `place` (an id, or ids joined by
155/// `/`), `params` and `anchor`. srv's parser is the judge of it; this only writes it in its one form.
156pub(super) fn link_of(arguments: &Value) -> Result<String> {
157    use agentmux_common::deeplinks::{parse::encode_part, REGISTRY};
158    if let Some(link) = arguments.get("link").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()) {
159        return Ok(link.to_string());
160    }
161    let view = arguments.get("view").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty());
162    let Some(view) = view else { anyhow::bail!("Pane open needs link (agentmux://…) or view") };
163    let mut link = format!("agentmux://{}", encode_part(view));
164    if let Some(place) = arguments.get("place").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()) {
165        use agentmux_common::deeplinks::{Kind, Segment};
166        // A view whose place is a path takes it whole, as one segment; any other place is ids joined by `/`.
167        let by_path = REGISTRY.view(view).is_some_and(|v| {
168            v.places.iter().any(|p| matches!(p.segments, [Segment::Var(var)] if var.kind == Kind::Path))
169        });
170        let segments: Vec<&str> = if by_path { vec![place] } else { place.split('/').collect() };
171        for seg in segments {
172            link.push('/');
173            link.push_str(&encode_part(seg));
174        }
175    }
176    if let Some(params) = arguments.get("params").and_then(|v| v.as_object()).filter(|m| !m.is_empty()) {
177        // In the registry's order, which the parser requires (R7); a name it doesn't know goes last and is refused there.
178        let order: Vec<&str> = REGISTRY.view(view).map(|v| v.places.iter().flat_map(|p| p.params.iter().map(|x| x.name)).collect()).unwrap_or_default();
179        let mut pairs: Vec<(&String, String)> = params
180            .iter()
181            .map(|(k, v)| (k, v.as_str().map(str::to_string).unwrap_or_else(|| v.to_string())))
182            .collect();
183        pairs.sort_by_key(|(k, _)| order.iter().position(|o| o == k).unwrap_or(usize::MAX));
184        let written: Vec<String> = pairs.iter().map(|(k, v)| format!("{k}={}", encode_part(v))).collect();
185        link.push('?');
186        link.push_str(&written.join("&"));
187    }
188    if let Some(anchor) = arguments.get("anchor").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()) {
189        link.push('#');
190        link.push_str(&encode_part(anchor));
191    }
192    Ok(link)
193}
194
195/// A place opened by its deep link (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md R16): srv's guard
196/// decides, the window opens it, and the answer is the outcome (opened, reused, queued or refused, with the reason).
197/// srv answers within 13 s (`queued` if the window hasn't finished by then), so the wait is longer than that.
198const OPEN_LINK_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
199
200async fn run_open_link(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
201    let ToolCtx { local_url, auth_key, client, .. } = *cx;
202    if local_url.is_empty() || auth_key.is_empty() {
203        anyhow::bail!("AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. Is this agent pane opened via AgentMux?");
204    }
205    let link = link_of(arguments)?;
206    // `open_in`, because Pane's `target` is rename's (what to rename).
207    let target = arguments.get("open_in").and_then(|v| v.as_str()).filter(|s| !s.is_empty());
208    let url = format!("{}/api/v1/pane/open_link", local_url.trim_end_matches('/'));
209    let resp = client
210        .post(&url)
211        .header(AUTH_KEY_HEADER, auth_key)
212        .json(&json!({ "link": link, "target": target }))
213        .timeout(OPEN_LINK_WAIT)
214        .send()
215        .await
216        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
217    let status = resp.status();
218    let body: Value = resp.json().await.unwrap_or_else(|_| json!({}));
219    if !status.is_success() {
220        anyhow::bail!("Pane open: HTTP {status} — {}", body.get("error").and_then(|v| v.as_str()).unwrap_or(""));
221    }
222    Ok(describe_open_outcome(&body))
223}
224
225/// The answer an agent reads: what happened, where, and for a refusal why and what would work.
226pub(super) fn describe_open_outcome(body: &Value) -> String {
227    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("");
228    let label = s("label");
229    let mut out = match s("outcome") {
230        "opened" => format!("Opened {label} beside this conversation"),
231        "reused" => format!("Showed {label} again, in the pane that already had it"),
232        "queued" => format!("Queued {label}: {}", s("reason")),
233        "refused" => format!("Not opened: {}", s("reason")),
234        other => format!("Pane open: {other}"),
235    };
236    if !s("block_id").is_empty() {
237        out.push_str(&format!(" (block {})", s("block_id")));
238    }
239    if s("place") == "missing" {
240        out.push_str(". The place inside it is gone, so the view opened at its nearest place");
241    }
242    if !s("remedy").is_empty() {
243        out.push_str(&format!(". {}", s("remedy")));
244    }
245    if !s("link").is_empty() {
246        out.push_str(&format!(". Link: {}", s("link")));
247    }
248    out.push('.');
249    out
250}
251
252/// A Files pane on a folder, optionally with entries selected.
253/// Navigation only (SPEC_FILE_BROWSER_PANE_2026_10_01.md §8.1, §9:
254/// agents don't mutate through this pane).
255async fn run_open_files(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
256    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
257    let connection = connection_arg(arguments);
258    let path = arguments
259        .get("path")
260        .and_then(|v| v.as_str())
261        .filter(|s| !s.is_empty())
262        .ok_or_else(|| anyhow::anyhow!("missing required parameter: path"))?;
263    let select: Vec<String> = arguments
264        .get("select")
265        .and_then(|v| v.as_array())
266        .map(|a| a.iter().filter_map(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string).collect())
267        .unwrap_or_default();
268
269    if local_url.is_empty() || auth_key.is_empty() {
270        anyhow::bail!(
271            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
272             Is this agent pane opened via AgentMux?"
273        );
274    }
275
276    let split = arguments
277        .get("split")
278        .and_then(|v| v.as_str())
279        .filter(|s| matches!(*s, "right" | "left" | "down" | "up"));
280
281    // Only a split the agent asked for is sent: with none, srv opens the pane as a tab of the agent's own pane group.
282    let split_direction = split.map(str::to_string);
283    let split_reference_block_id = (!block_id.is_empty()).then(|| block_id.to_string());
284    let req = PaneOpenRequest {
285        view: "files".to_string(),
286        file: Some(path.to_string()),
287        focus: Some(true),
288        split_direction,
289        split_reference_block_id,
290        title: arguments.get("title").and_then(|v| v.as_str()).map(str::to_string),
291        tree_expanded: None,
292        floating: if arguments.get("floating").and_then(|v| v.as_bool()) == Some(true) {
293            Some(true)
294        } else {
295            None
296        },
297        url: None,
298        cwd: None,
299        tab_id: None,
300        reuse_editor_pane: None, // view != "editor" — irrelevant here
301        target_block_id: None,
302        follow_folder: None,
303        viewer: None,
304        line: None,
305        offset: None,
306        page: None,
307        select: if select.is_empty() { None } else { Some(select) },
308        // On an SSH host: srv asks the user to allow it, checking this
309        // agent's signed identity (remote terminals spec §8.2).
310        auth: if connection.is_some() { Some(sign_ui_automation_auth()?) } else { None },
311        connection,
312        place: PlaceArgs::of(arguments).map_err(|e| anyhow::anyhow!("INVALID_ARG: {e}"))?,
313    };
314
315    let result: PaneOpenResponse = cx.post_as("/api/v1/pane/open", &req, "pane.open").await?;
316
317    Ok(format!("Opened {path} in a Files pane (block {}).{}", result.block_id, placed_note(&result)))
318}
319
320async fn run_open_agent(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
321    let ToolCtx { local_url, auth_key, .. } = *cx;
322    let agent_id = arguments
323        .get("agent_id")
324        .and_then(|v| v.as_str())
325        .filter(|s| !s.is_empty())
326        .ok_or_else(|| anyhow::anyhow!("missing required parameter: agent_id"))?;
327    let tab_id = arguments.get("tab_id").and_then(|v| v.as_str()).map(str::to_string);
328    let focus = arguments.get("focus").and_then(|v| v.as_bool());
329
330    if local_url.is_empty() || auth_key.is_empty() {
331        anyhow::bail!(
332            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
333             Is this agent pane opened via AgentMux?"
334        );
335    }
336
337    let body = json!({
338        "agent_id": agent_id,
339        "tab_id": tab_id,
340        "focus": focus,
341    });
342    let result = cx.post_json("/api/v1/agent/open", &body, "agent open").await?;
343
344    Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
345}
346
347async fn run_who_am_i(_arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
348    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
349    if local_url.is_empty() || auth_key.is_empty() {
350        anyhow::bail!(
351            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
352             Is this agent pane opened via AgentMux?"
353        );
354    }
355    if block_id.is_empty() {
356        anyhow::bail!(
357            "neither AGENTMUX_AGENT_BUS_ID nor AGENTMUX_BLOCKID is set \
358             — cannot resolve this agent's pane. Is this agent pane opened via AgentMux?"
359        );
360    }
361
362    let result = cx.get_json("/api/v1/self", &[("block_id", block_id)], "self lookup").await?;
363
364    Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
365}
366
367async fn run_set_name(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
368    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
369    let target = arguments
370        .get("target")
371        .and_then(|v| v.as_str())
372        .map(|s| s.trim())
373        .filter(|s| !s.is_empty())
374        .ok_or_else(|| anyhow::anyhow!("missing required parameter: target"))?;
375    let new_name = arguments
376        .get("name")
377        .and_then(|v| v.as_str())
378        .map(|s| s.trim())
379        .filter(|s| !s.is_empty())
380        .ok_or_else(|| anyhow::anyhow!("missing required parameter: name"))?;
381    let target_id = arguments
382        .get("target_id")
383        .and_then(|v| v.as_str())
384        .filter(|s| !s.is_empty())
385        .map(str::to_string);
386
387    if local_url.is_empty() || auth_key.is_empty() {
388        anyhow::bail!(
389            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
390             Is this agent pane opened via AgentMux?"
391        );
392    }
393    if target == "file" {
394        return run_rename_file(arguments, new_name, cx).await;
395    }
396    // block_id is only needed for own-context resolution; when
397    // target_id is explicit we can reach any element without it.
398    if target_id.is_none() && block_id.is_empty() {
399        anyhow::bail!(
400            "neither AGENTMUX_AGENT_BUS_ID nor AGENTMUX_BLOCKID is set \
401             — pass target_id to name a specific element, or open this \
402             agent in an AgentMux pane to default to your own."
403        );
404    }
405
406    // window/tab/workspace POST {"name": …} to /…/name; pane POSTs
407    // {"title": …} to /pane/title. `label` and `resp_field` are the
408    // human-facing echo and the response key used to surface the
409    // server-applied value (e.g. a window name clamped to 64 chars).
410    let own_block = if block_id.is_empty() { None } else { Some(block_id.to_string()) };
411    let (path, label, resp_field, body) = match target {
412        "window" => ("window/name", "Window name", "name", serde_json::to_value(WindowNameRequest {
413            block_id: own_block,
414            name: new_name.to_string(),
415            window_id: target_id,
416        })?),
417        "tab" => ("tab/name", "Tab name", "name", serde_json::to_value(TabNameRequest {
418            block_id: own_block,
419            tab_id: target_id,
420            name: new_name.to_string(),
421        })?),
422        "workspace" => ("workspace/name", "Workspace name", "name", serde_json::to_value(WorkspaceNameRequest {
423            block_id: own_block,
424            workspace_id: target_id,
425            name: new_name.to_string(),
426        })?),
427        "pane" => ("pane/title", "Pane title", "title", serde_json::to_value(PaneTitleRequest {
428            block_id: target_id.or(own_block),
429            title: new_name.to_string(),
430        })?),
431        other => anyhow::bail!(
432            "invalid target '{other}' — expected one of: window, tab, pane, workspace, file"
433        ),
434    };
435    let url = format!("{}/api/v1/{path}", local_url.trim_end_matches('/'));
436    let resp = client
437        .post(&url)
438        .header(AUTH_KEY_HEADER, auth_key)
439        .json(&body)
440        .send()
441        .await
442        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
443    if !resp.status().is_success() {
444        let status = resp.status();
445        let text = resp.text().await.unwrap_or_default();
446        anyhow::bail!("{label} change failed: HTTP {status} — {text}");
447    }
448    // Surface the server-applied value (e.g. a window name clamped to 64
449    // chars) when the endpoint echoes it back; fall back to the request.
450    let applied = resp
451        .json::<Value>()
452        .await
453        .ok()
454        .and_then(|v| v.get(resp_field).and_then(|s| s.as_str()).map(str::to_string))
455        .unwrap_or_else(|| new_name.to_string());
456    Ok(format!("{label} set to \"{applied}\""))
457}
458
459/// `rename` with target `file`: srv renames the file or folder in its folder, as the Files pane and
460/// an Editor tab do, so every Editor tab open on it follows (a rename in the agent's own shell
461/// leaves them on the old path). A refusal is srv's own sentence.
462async fn run_rename_file(arguments: &Value, name: &str, cx: &ToolCtx<'_>) -> Result<String> {
463    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
464    let path = arguments
465        .get("path")
466        .and_then(|v| v.as_str())
467        .map(str::trim)
468        .filter(|s| !s.is_empty())
469        .ok_or_else(|| anyhow::anyhow!("missing required parameter: path (the file or folder to rename, absolute)"))?;
470    let connection = connection_arg(arguments);
471    let req = FileRenameRequest {
472        path: path.to_string(),
473        name: name.to_string(),
474        block_id: if block_id.is_empty() { None } else { Some(block_id.to_string()) },
475        // On an SSH host: srv asks the user to allow it, checking this agent's signed identity.
476        auth: if connection.is_some() { Some(sign_ui_automation_auth()?) } else { None },
477        connection,
478    };
479    let url = format!("{}/api/v1/file/rename", local_url.trim_end_matches('/'));
480    let resp = client
481        .post(&url)
482        .header(AUTH_KEY_HEADER, auth_key)
483        .json(&req)
484        .send()
485        .await
486        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
487    let status = resp.status();
488    let text = resp.text().await.unwrap_or_default();
489    let reply: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
490    if !status.is_success() {
491        match reply.get("error").and_then(|e| e.as_str()) {
492            Some(why) => anyhow::bail!("{why}"),
493            None => anyhow::bail!("File rename failed: HTTP {status} — {text}"),
494        }
495    }
496    let new_path = reply.get("new_path").and_then(|p| p.as_str()).unwrap_or(name);
497    Ok(format!("Renamed {path} to {new_path}. Editor tabs open on it follow."))
498}
499
500async fn run_layout(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
501    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
502    if local_url.is_empty() || auth_key.is_empty() {
503        anyhow::bail!(
504            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
505             Is this agent pane opened via AgentMux?"
506        );
507    }
508    let query = arguments
509        .get("query")
510        .and_then(|v| v.as_str())
511        .map(|s| s.trim())
512        .filter(|s| !s.is_empty())
513        .unwrap_or("layout");
514    let path = match query {
515        "layout" => "layout",
516        "windows" => "windows",
517        "workspaces" => "workspaces",
518        "tabs" => "tabs",
519        other => anyhow::bail!(
520            "invalid query '{other}' — expected one of: layout, windows, workspaces, tabs"
521        ),
522    };
523    // The "tabs" query scopes to the caller's own workspace when we know it.
524    let own = [("block_id", block_id)];
525    let scope: &[(&str, &str)] = if query == "tabs" && !block_id.is_empty() { &own } else { &[] };
526    let label = format!("Layout {query}");
527    let result = cx.get_json(&format!("/api/v1/{path}"), scope, label.as_str()).await?;
528    Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
529}
530
531async fn run_set_active_tab(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
532    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
533    let tab_id = arguments
534        .get("tab_id")
535        .and_then(|v| v.as_str())
536        .map(|s| s.trim())
537        .filter(|s| !s.is_empty())
538        .ok_or_else(|| anyhow::anyhow!("missing required parameter: tab_id"))?;
539    require_agent_env(local_url, auth_key, block_id)?;
540    cx.post("/api/v1/tab/activate", &TabActivateRequest { tab_id: tab_id.to_string() }, "set active tab").await?;
541    Ok(format!("Switched to tab {tab_id}"))
542}
543
544async fn run_new_tab(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
545    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
546    require_agent_env(local_url, auth_key, block_id)?;
547    let name = arguments.get("name").and_then(|v| v.as_str()).unwrap_or("");
548    let request = TabNewRequest {
549        block_id: Some(block_id.to_string()),
550        workspace_id: None,
551        name: if name.is_empty() { None } else { Some(name.to_string()) },
552    };
553    cx.post("/api/v1/tab/new", &request, "new tab").await?;
554    Ok(if name.is_empty() {
555        "Opened a new tab".to_string()
556    } else {
557        format!("Opened new tab \"{name}\"")
558    })
559}
560
561async fn run_focus_window(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
562    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
563    require_agent_env(local_url, auth_key, block_id)?;
564    let window_id = arguments.get("window_id").and_then(|v| v.as_str()).unwrap_or("");
565    let request = WindowFocusRequest {
566        block_id: Some(block_id.to_string()),
567        window_id: if window_id.is_empty() { None } else { Some(window_id.to_string()) },
568    };
569    cx.post("/api/v1/window/focus", &request, "focus window").await?;
570    Ok("Focused window".to_string())
571}
572
573/// `Pane` resize, move and place: a floating pane this agent opened, set to a size, a place or both. srv checks
574/// that it is the agent's own and asks the pane's window, which answers with where it went.
575async fn run_place_pane(op: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
576    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
577    require_agent_env(local_url, auth_key, block_id)?;
578    let named = arguments.get("target_id").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty());
579    // pin and unpin act on your own pane when none is named; the others need a floating pane you opened.
580    let target_id = match (named, matches!(op, "pin" | "unpin")) {
581        (Some(t), _) => t,
582        (None, true) if !block_id.is_empty() => block_id,
583        _ => anyhow::bail!("Pane {op}: missing required parameter: target_id (a floating pane you opened, from Pane layout)"),
584    };
585    let place = PlaceArgs::of(arguments).map_err(|e| anyhow::anyhow!("INVALID_ARG: {e}"))?;
586    let url = format!("{}/api/v1/pane/place", local_url.trim_end_matches('/'));
587    let resp = client
588        .post(&url)
589        .header(AUTH_KEY_HEADER, auth_key)
590        .json(&PanePlaceRequest {
591            op: op.to_string(),
592            target_id: target_id.to_string(),
593            place,
594            split: arguments.get("split").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string),
595            // The caller's own pane: `dock` goes into its tab, `float` is shown from its window.
596            block_id: Some(block_id.to_string()).filter(|b| !b.is_empty()),
597        })
598        .send()
599        .await
600        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
601    if !resp.status().is_success() {
602        let status = resp.status();
603        let text = resp.text().await.unwrap_or_default();
604        // srv's own words (the refusal and what would work), not the HTTP envelope.
605        let said = serde_json::from_str::<Value>(&text).ok().and_then(|b| b.get("error").and_then(Value::as_str).map(str::to_string));
606        anyhow::bail!("Pane {op} failed ({status}): {}", said.unwrap_or(text));
607    }
608    let body: Value = resp.json().await.map_err(|e| anyhow::anyhow!("response parse failed: {e}"))?;
609    if op == "dock" {
610        let tab = body.get("tab_id").and_then(Value::as_str).unwrap_or("your tab");
611        return Ok(format!("Docked pane {target_id} into tab {tab}; its window closes."));
612    }
613    if op == "pin" {
614        return Ok(format!("Pinned pane {target_id}: it stays on screen, where it is, in every tab of its window."));
615    }
616    if op == "unpin" {
617        return Ok(format!("Unpinned pane {target_id}: it is an ordinary pane of the tab that is showing."));
618    }
619    let done = match op {
620        "resize" => "Resized",
621        "move" => "Moved",
622        "float" => "Floated",
623        _ => "Placed",
624    };
625    Ok(format!("{done} pane {target_id}.{}", floating_note(Some(&body))))
626}
627
628async fn run_close_pane(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
629    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
630    require_agent_env(local_url, auth_key, block_id)?;
631    let auth = sign_ui_automation_auth()?;
632    let target_block_id = arguments.get("block_id").and_then(|v| v.as_str()).map(str::to_string);
633    let reason = arguments.get("reason").and_then(|v| v.as_str()).map(str::to_string);
634    let url = format!("{}/api/v1/agent/pane/close", local_url.trim_end_matches('/'));
635    let resp = client
636        .post(&url)
637        .header(AUTH_KEY_HEADER, auth_key)
638        .json(&ClosePaneRequest { auth, block_id: target_block_id.clone(), reason })
639        .send()
640        .await
641        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
642    if !resp.status().is_success() {
643        let status = resp.status();
644        let text = resp.text().await.unwrap_or_default();
645        anyhow::bail!("close failed: HTTP {status} — {text}");
646    }
647    if resp.status().as_u16() == 202 {
648        let body: Value = resp.json().await.unwrap_or(Value::Null);
649        let request_id = body["request_id"].as_str().unwrap_or_default();
650        return match target_block_id.as_deref() {
651            // Another pane: its user has 30 s to keep it, 10 s for a browser pane (§6.5). srv runs the window and tells this
652            // agent by note if it is kept or the close fails, so the call doesn't wait.
653            Some(b) => Ok(close_pane_pending(b, &body, agentmux_common::time::now_ms())),
654            // Yourself (§7): as QuitSelf, done once it's proceeding —
655            // the quit waits for this very turn to end.
656            None => {
657                let now = own_outcome(await_shutdown_of(client, local_url, auth_key, request_id, false, Some(block_id)).await, block_id);
658                match now["status"].as_str().unwrap_or("") {
659                    "" | "pending" => anyhow::bail!("ClosePane: no answer on the pending shutdown {request_id}"),
660                    state => quit_self_outcome(state, &now),
661                }
662            }
663        };
664    }
665    match target_block_id {
666        Some(b) => Ok(format!("Closed tab {b:?}")),
667        // srv's only 200 for the no-argument form (§7): a quit already
668        // scheduled or under way.
669        None => quit_self_result(200, &Value::Null),
670    }
671}
672
673async fn run_quit_self(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
674    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
675    require_agent_env(local_url, auth_key, block_id)?;
676    let field = |k: &str| {
677        arguments
678            .get(k)
679            .and_then(|v| v.as_str())
680            .map(str::trim)
681            .filter(|s| !s.is_empty())
682            .map(str::to_string)
683            .ok_or_else(|| anyhow::anyhow!("missing required parameter: {k}"))
684    };
685    let (reason, user_instruction) = (field("reason")?, field("user_instruction")?);
686    let auth = sign_ui_automation_auth()?;
687    let url = format!("{}/api/v1/agent/self/quit", local_url.trim_end_matches('/'));
688    let resp = client
689        .post(&url)
690        .header(AUTH_KEY_HEADER, auth_key)
691        .json(&QuitSelfRequest { auth, reason, user_instruction })
692        .send()
693        .await
694        .map_err(|e| anyhow::anyhow!("request failed: {e}"))?;
695    let status = resp.status();
696    let body: Value = resp.json().await.unwrap_or(Value::Null);
697    if status.as_u16() != 202 || body["status"] != "pending_user_override" {
698        return quit_self_result(status.as_u16(), &body);
699    }
700    // Not the user's own ask: the user has 15 s to keep this agent
701    // (SPEC_AGENT_SELF_QUIT_2026_09_24.md §6.5). Poll for the answer —
702    // one long request would outlast the client's timeout.
703    let request_id = body["request_id"].as_str().unwrap_or_default();
704    // `proceeding` is final for QuitSelf: the shutdown waits for this
705    // very turn to end, so waiting on here would hold it up.
706    let now = own_outcome(await_shutdown_of(client, local_url, auth_key, request_id, false, Some(block_id)).await, block_id);
707    match now["status"].as_str().unwrap_or("") {
708        "" | "pending" => anyhow::bail!("QuitSelf: no answer on the pending shutdown {request_id}"),
709        state => quit_self_outcome(state, &now),
710    }
711}
712
713async fn run_register_dev_server(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
714    let ToolCtx { local_url, auth_key, block_id, .. } = *cx;
715    require_agent_env(local_url, auth_key, block_id)?;
716    let auth = sign_ui_automation_auth()?;
717    let project = arguments
718        .get("project")
719        .and_then(|v| v.as_str())
720        .filter(|s| !s.is_empty())
721        .ok_or_else(|| anyhow::anyhow!("missing required parameter: project"))?
722        .to_string();
723    let port = arguments
724        .get("port")
725        .and_then(|v| v.as_u64())
726        .filter(|p| *p > 0 && *p <= u16::MAX as u64)
727        .ok_or_else(|| anyhow::anyhow!("missing or invalid required parameter: port (must be 1-65535)"))?
728        as u16;
729    let text = |key: &str| arguments.get(key).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
730    let (command, dir) = (text("command"), text("dir"));
731    let request = RegisterDevServerRequest { auth, project: project.clone(), port, command, dir };
732    let body: RegisterDevServerResponse = cx.post_as("/api/v1/agent/dev_server/register", &request, "RegisterDevServer").await?;
733    let starting = if body.starting {
734        format!(" The server is still starting, so the URL works once it is listening; its output is in /tmp/amx-dev-{}.log in your container.", project.trim().to_lowercase())
735    } else {
736        String::new()
737    };
738    Ok(format!("Registered. Browse to: {}{starting}", body.url))
739}
740
741
742/// The `connection` an Open tool was given: an SSH host or WSL name, trimmed;
743/// `None` for absent, empty or "local" (this machine).
744/// An editor open's viewer and where in the file to land (a text line, a hex byte offset, a PDF page); srv checks the
745/// viewer and ignores a position the viewer has no use for.
746fn viewer_args(arguments: &Value) -> (Option<String>, Option<u32>, Option<u64>, Option<u32>) {
747    let viewer = arguments.get("viewer").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
748    let small = |key| positive_arg(arguments, key).and_then(|n| u32::try_from(n).ok());
749    (viewer, small("line"), arguments.get("offset").and_then(|v| v.as_u64()), small("page"))
750}
751
752/// A whole-number argument of 1 or more (a line or a page); anything else counts as absent.
753fn positive_arg(arguments: &Value, key: &str) -> Option<u64> {
754    arguments.get(key).and_then(|v| v.as_u64()).filter(|n| *n >= 1)
755}
756
757fn connection_arg(arguments: &Value) -> Option<String> {
758    arguments
759        .get("connection")
760        .and_then(|v| v.as_str())
761        .map(str::trim)
762        .filter(|c| !c.is_empty() && *c != "local")
763        .map(str::to_string)
764}
765
766#[cfg(test)]
767mod call_tests;
768
769#[cfg(test)]
770mod connection_arg_tests {
771    use super::*;
772
773    #[test]
774    fn only_a_named_connection_is_one() {
775        let c = |v: Value| connection_arg(&serde_json::json!({ "connection": v }));
776        assert_eq!(c(serde_json::json!(" user@box ")).as_deref(), Some("user@box"));
777        assert_eq!(c(serde_json::json!("wsl://Ubuntu")).as_deref(), Some("wsl://Ubuntu"));
778        assert_eq!(c(serde_json::json!("local")), None);
779        assert_eq!(c(serde_json::json!("")), None);
780        assert_eq!(connection_arg(&serde_json::json!({})), None);
781    }
782}