Skip to main content

agentmux_srv/server/
pane_commands.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The window's own calls on agent panes: `agent.pane.unregister`, `agent.takeover` and `agent.move-here`, and on a move to
5//! another computer: `agent.move-to-computer`, `agent.bring-back` and `agent.move-status` (the person's own path).
6//! Over HTTP an agent can do both for its own panes with its token (`pane_binding`); the
7//! window has no token, so it asks over its socket, and srv answers only a connection the
8//! host has proven is the AgentMux window.
9
10use std::sync::Arc;
11
12use axum::body::to_bytes;
13use axum::response::Response;
14use serde_json::Value;
15
16use crate::backend::rpc::engine::WshRpcEngine;
17use crate::backend::rpc_types::{
18    AgentMoveAnswer, AgentPaneUnregisterResult, AgentTakeoverResult, CommandAgentBringBackData, CommandAgentMoveHereData,
19    CommandAgentMoveStatusData, CommandAgentMoveToComputerData, CommandAgentPaneUnregisterData, CommandAgentTakeoverData,
20    COMMAND_AGENT_BRING_BACK, COMMAND_AGENT_MOVE_HERE, COMMAND_AGENT_MOVE_STATUS, COMMAND_AGENT_MOVE_TO_COMPUTER,
21    COMMAND_AGENT_PANE_UNREGISTER, COMMAND_AGENT_TAKEOVER,
22};
23
24use super::agent_move_here::move_here;
25use super::app_api::{agent_handover, agent_move};
26use super::agent_takeover::{take_over, TakeoverRequest};
27use super::reactive::{unregister_pane, UnregisterRequest};
28use super::AppState;
29
30/// What an HTTP handler answered, as the RPC's result: its body when it succeeded, its `error` when it did not.
31async fn answer(response: Response) -> Result<Value, String> {
32    let status = response.status();
33    let bytes = to_bytes(response.into_body(), usize::MAX).await.map_err(|e| e.to_string())?;
34    let body: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
35    if status.is_success() {
36        Ok(body)
37    } else {
38        Err(body["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("HTTP {status}")))
39    }
40}
41
42pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
43    let unregister_state = state.clone();
44    engine.register_typed(COMMAND_AGENT_PANE_UNREGISTER, move |cmd: CommandAgentPaneUnregisterData, ctx| {
45        let state = unregister_state.clone();
46        async move {
47            ctx.operator_only("only the operator's window unregisters a pane")?;
48            let request = UnregisterRequest { agent_id: cmd.agent_id, block_id: cmd.block_id };
49            let body = answer(unregister_pane(&state, request).await).await?;
50            Ok(AgentPaneUnregisterResult { success: body["success"].as_bool().unwrap_or(false) })
51        }
52    });
53    let takeover_state = state.clone();
54    engine.register_typed(COMMAND_AGENT_TAKEOVER, move |cmd: CommandAgentTakeoverData, ctx| {
55        let state = takeover_state.clone();
56        async move {
57            ctx.operator_only("only the operator's window takes an agent over")?;
58            let body = answer(take_over(&state, None, TakeoverRequest { block_id: cmd.block_id }).await).await?;
59            Ok(AgentTakeoverResult {
60                released: body["released"].as_bool().unwrap_or(false),
61                from_channel: body["from_channel"].as_str().map(str::to_string),
62            })
63        }
64    });
65    let move_state = state.clone();
66    engine.register_typed(COMMAND_AGENT_MOVE_HERE, move |cmd: CommandAgentMoveHereData, ctx| {
67        let state = move_state.clone();
68        async move {
69            ctx.operator_only("only the operator's window moves an agent between panes")?;
70            move_here(&state, &cmd.block_id).await
71        }
72    });
73    // A person's own move, through the same handlers an agent's request reaches, with no agent token: the handler acts through the
74    // named agent's leader and refuses a request that names none.
75    let to_state = state.clone();
76    engine.register_typed(COMMAND_AGENT_MOVE_TO_COMPUTER, move |cmd: CommandAgentMoveToComputerData, ctx| {
77        let state = to_state.clone();
78        async move {
79            ctx.operator_only("only the operator's window moves an agent to another computer")?;
80            let req = serde_json::json!({ "agent": cmd.agent, "host": cmd.host, "dry_run": cmd.dry_run.unwrap_or(false), "resume": cmd.resume.unwrap_or(false) });
81            let req = serde_json::from_value(req).map_err(|e| e.to_string())?;
82            Ok(AgentMoveAnswer { answer: answer(agent_move::handle_agent_move(axum::extract::State(state), None, axum::Json(req)).await).await? })
83        }
84    });
85    let back_state = state.clone();
86    engine.register_typed(COMMAND_AGENT_BRING_BACK, move |cmd: CommandAgentBringBackData, ctx| {
87        let state = back_state.clone();
88        async move {
89            ctx.operator_only("only the operator's window brings an agent back")?;
90            let req = serde_json::from_value(serde_json::json!({ "agent": cmd.agent, "force": cmd.force.unwrap_or(false) })).map_err(|e| e.to_string())?;
91            Ok(AgentMoveAnswer { answer: answer(agent_handover::handle_agent_bring_back(axum::extract::State(state), None, axum::Json(req)).await).await? })
92        }
93    });
94    let status_state = state.clone();
95    engine.register_typed(COMMAND_AGENT_MOVE_STATUS, move |cmd: CommandAgentMoveStatusData, ctx| {
96        let state = status_state.clone();
97        async move {
98            ctx.operator_only("only the operator's window asks where a move stands")?;
99            let req = serde_json::from_value(serde_json::json!({ "agent": cmd.agent })).map_err(|e| e.to_string())?;
100            Ok(AgentMoveAnswer { answer: answer(agent_handover::handle_agent_move_status(axum::extract::State(state), None, axum::Json(req)).await).await? })
101        }
102    });
103}
104
105#[cfg(test)]
106mod tests {
107    use serde_json::json;
108
109    use crate::backend::rpc::engine::WshRpcEngine;
110    use crate::backend::rpc_types::{RpcContext, RpcMessage};
111    use crate::server::tests::test_state;
112
113    async fn call(ctx: RpcContext, command: &str, data: serde_json::Value) -> Result<serde_json::Value, String> {
114        let state = test_state();
115        let (engine, mut rx) = WshRpcEngine::new();
116        super::register(&engine, &state);
117        engine.set_rpc_context(ctx);
118        engine.handle_message(RpcMessage { command: command.to_string(), reqid: "r".to_string(), data: Some(data), ..Default::default() });
119        let resp = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv()).await.unwrap().unwrap();
120        if resp.error.is_empty() {
121            Ok(resp.data.unwrap_or_default())
122        } else {
123            Err(resp.error)
124        }
125    }
126
127    /// Only the window the host proved unregisters a pane or takes an agent over; an agent's connection and an unproven one are refused.
128    #[tokio::test]
129    async fn only_the_operators_window_unregisters_or_takes_over() {
130        let agent = RpcContext { agent_id: "pc-alpha".to_string(), ..Default::default() };
131        for (command, data) in [
132            ("agent.pane.unregister", json!({ "agent_id": "pc-x", "block_id": "pc-block" })),
133            ("agent.takeover", json!({ "block_id": "pc-block" })),
134            ("agent.move-here", json!({ "block_id": "pc-block" })),
135            ("agent.move-to-computer", json!({ "agent": "pc-x", "host": "elsewhere" })),
136            ("agent.bring-back", json!({ "agent": "pc-x" })),
137            ("agent.move-status", json!({ "agent": "pc-x" })),
138        ] {
139            for ctx in [agent.clone(), RpcContext::default()] {
140                let e = call(ctx, command, data.clone()).await.unwrap_err();
141                assert!(e.starts_with("FORBIDDEN: only the operator's window"), "{command}: {e}");
142            }
143        }
144        let done = call(RpcContext::operator_for_tests(), "agent.pane.unregister", json!({ "agent_id": "pc-x", "block_id": "pc-block" })).await.unwrap();
145        assert_eq!(done["success"], true, "{done}");
146        let e = call(RpcContext::operator_for_tests(), "agent.takeover", json!({ "block_id": "pc-no-such-block" })).await.unwrap_err();
147        assert!(e.contains("block not found"), "{e}");
148    }
149
150    /// The window's own move calls reach the same handlers an agent's request does, with no agent token: they act for a person, so a
151    /// request must name an agent that exists here (the refusal is the handler's, not the window's).
152    #[tokio::test]
153    async fn the_windows_move_calls_reach_the_handlers_as_a_person() {
154        for (command, data) in [
155            ("agent.move-to-computer", json!({ "agent": "no-such-agent", "host": "elsewhere" })),
156            ("agent.bring-back", json!({ "agent": "no-such-agent" })),
157            ("agent.move-status", json!({ "agent": "no-such-agent" })),
158        ] {
159            let e = call(RpcContext::operator_for_tests(), command, data).await.unwrap_err();
160            assert!(e.contains("no agent 'no-such-agent' on this machine"), "{command}: {e}");
161        }
162    }
163}