Skip to main content

agentmux_srv/server/
drone_access_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who may fire a drone at once (`SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md` ยง6.5), read and set over the websocket.
5//!
6//! * `getdroneaccess`: the agent that owns the drone and the agents it was given to. Anyone may read it.
7//! * `setdroneagents`: replace the agents the drone is given to. The person's window may, and so may the agent that
8//!   owns the drone (it gives its own drone to another agent). No other agent: giving oneself a drone would undo
9//!   the whole check. The owner never changes.
10
11use std::sync::Arc;
12
13use serde::{Deserialize, Serialize};
14
15use crate::backend::rpc::actor::{actor_of, Actor};
16use crate::backend::rpc::engine::WshRpcEngine;
17use crate::backend::rpc_types::{RpcContext, COMMAND_GET_DRONE_ACCESS, COMMAND_SET_DRONE_AGENTS};
18use crate::drone::access::{key, DroneAccess, DroneAccessStore};
19use crate::drone::storage::DroneStore;
20use crate::server::AppState;
21use agentmux_common::time::now_ms;
22
23/// The most agents one drone is given to, and the longest an agent's name.
24const MAX_AGENTS: usize = 50;
25const MAX_NAME: usize = 64;
26
27#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
28#[ts(export, export_to = "../../../frontend/types/rpc/")]
29pub struct GetDroneAccessReq {
30    pub drone_id: String,
31}
32
33#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
34#[ts(export, export_to = "../../../frontend/types/rpc/")]
35pub struct SetDroneAgentsReq {
36    pub drone_id: String,
37    /// The agents (by id) the drone is given to: this list replaces the old one.
38    pub agents: Vec<String>,
39}
40
41fn must_exist(state: &AppState, drone_id: &str) -> Result<(), String> {
42    match state.id_store.drone_get(drone_id) {
43        Ok(Some(_)) => Ok(()),
44        Ok(None) => Err(format!("NOT_FOUND: no drone {drone_id:?}")),
45        Err(e) => Err(format!("drone: {e}")),
46    }
47}
48
49pub(crate) fn get_drone_access(state: &AppState, cmd: GetDroneAccessReq) -> Result<DroneAccess, String> {
50    must_exist(state, &cmd.drone_id)?;
51    state.id_store.access_get(&cmd.drone_id).map_err(|e| format!("getdroneaccess: {e}"))
52}
53
54pub(crate) fn set_drone_agents(state: &AppState, ctx: &RpcContext, cmd: SetDroneAgentsReq) -> Result<DroneAccess, String> {
55    must_exist(state, &cmd.drone_id)?;
56    let current = state.id_store.access_get(&cmd.drone_id).map_err(|e| format!("setdroneagents: {e}"))?;
57    let by = match actor_of(ctx) {
58        Actor::Operator | Actor::Person(_) => actor_of(ctx).label(),
59        Actor::Agent(id) if !current.owner.is_empty() && current.owner == key(&id) => Actor::Agent(id).label(),
60        _ => return Err("FORBIDDEN: only the person, or the agent that owns the drone, gives it to other agents".to_string()),
61    };
62    let agents: Vec<String> = cmd.agents.iter().map(|a| key(a)).filter(|a| !a.is_empty()).collect();
63    if agents.len() > MAX_AGENTS || agents.iter().any(|a| a.chars().count() > MAX_NAME) {
64        return Err(format!("INVALID_ARG: at most {MAX_AGENTS} agents, each name at most {MAX_NAME} characters"));
65    }
66    tracing::info!(drone_id = %cmd.drone_id, by = %by, agents = ?agents, "setdroneagents");
67    state.id_store.access_set_agents(&cmd.drone_id, &agents, &by, now_ms()).map_err(|e| format!("setdroneagents: {e}"))?;
68    state.broker.publish_event::<crate::backend::mps_events::DronesChanged>(&(), vec![], 0);
69    state.id_store.access_get(&cmd.drone_id).map_err(|e| format!("setdroneagents: {e}"))
70}
71
72pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
73    let s = state.clone();
74    engine.register_typed(COMMAND_GET_DRONE_ACCESS, move |cmd: GetDroneAccessReq, _ctx| {
75        let s = s.clone();
76        async move { get_drone_access(&s, cmd) }
77    });
78    let s = state.clone();
79    engine.register_typed(COMMAND_SET_DRONE_AGENTS, move |cmd: SetDroneAgentsReq, ctx| {
80        let s = s.clone();
81        async move { set_drone_agents(&s, &ctx, cmd) }
82    });
83}
84
85#[cfg(test)]
86#[path = "drone_access_handlers_tests.rs"]
87mod tests;