Skip to main content

agentmux_srv/server/app_api/
agent_seats.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Agents set_seat` (`POST /api/v1/agent/seats`): an agent, host or container, sets or clears
5//! the seats of agents on this machine, several in one call (a whole roster).
6//! A seat is an agent's role, who it reports to and what it owns
7//! (`backend::agent_seat`); the operator's window sets one with `agent.setSeat`
8//! (`agent_handlers/seat.rs`), and an agent does it here.
9//!
10//! The caller is the agent its token names; a request without one is refused,
11//! so a change is never attributed to the operator. The checks are the
12//! window's (roles, lengths, leads that are agents here, no cycle), applied to
13//! the whole call at once: it is written all together or not at all. Each
14//! change, and each refused attempt, is recorded in the audit log under the
15//! calling agent's slug and in the `identity` log with its UID.
16
17use axum::extract::State;
18use axum::http::StatusCode;
19use axum::response::{IntoResponse, Response};
20use axum::{Extension, Json};
21use serde::Deserialize;
22use serde_json::{json, Value};
23
24use crate::backend::rpc_types::SeatInput;
25use crate::server::agent_handlers::seat::{plan_seats, write_seats, PlannedSeat, SeatActor, SeatChange};
26use crate::server::caller::Caller;
27use crate::server::state::AppState;
28
29/// The audit entry's action for a change.
30pub(crate) const AUDIT_ACTION: &str = "agent.seat.set";
31/// The most seats one call changes: a roster, not a sweep.
32pub(crate) const MAX_SEATS_PER_CALL: usize = 64;
33
34#[derive(Debug, Deserialize)]
35pub(crate) struct SetSeatsRequest {
36    seats: Vec<SeatEntry>,
37}
38
39#[derive(Debug, Deserialize)]
40struct SeatEntry {
41    /// The agent's id or slug.
42    agent: String,
43    /// The seat to set; `null` or absent clears the agent's seat.
44    #[serde(default)]
45    seat: Option<SeatInput>,
46}
47
48#[derive(Debug)]
49struct Refusal {
50    status: StatusCode,
51    message: String,
52}
53
54fn refuse(status: StatusCode, message: impl Into<String>) -> Refusal {
55    Refusal { status, message: message.into() }
56}
57
58/// The agent making the request.
59struct Actor {
60    uid: String,
61    slug: String,
62    name: String,
63}
64
65fn actor_of(state: &AppState, caller: Option<&Caller>) -> Result<Actor, Refusal> {
66    let Some(uid) = caller.and_then(Caller::uid) else {
67        return Err(refuse(
68            StatusCode::UNAUTHORIZED,
69            "no agent token: Agents set_seat acts as the calling agent; the operator sets a seat in My Agents",
70        ));
71    };
72    let def = state
73        .mstore
74        .agent_def_get(uid)
75        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent seats: {e}")))?
76        .ok_or_else(|| refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"))?;
77    Ok(Actor { uid: uid.to_string(), slug: def.slug, name: def.name })
78}
79
80/// The uid of the agent `named` (an id or a slug) on this machine.
81fn uid_of(state: &AppState, named: &str, what: &str) -> Result<String, Refusal> {
82    let named = named.trim();
83    crate::backend::agent_resolve::resolve_agent_id(&state.mstore, named)
84        .ok()
85        .filter(|id| matches!(state.mstore.agent_def_get(id), Ok(Some(_))))
86        .ok_or_else(|| refuse(StatusCode::NOT_FOUND, format!("no agent '{named}' on this machine ({what}); seats are set only for this machine's agents")))
87}
88
89/// The agents on other machines this one sees on the LAN, as `Name@host`: the leads a seat may name
90/// besides this machine's own agents.
91fn known_remote_agents(state: &AppState) -> Vec<String> {
92    let peers = state.lan_discovery.get_instances().into_iter().map(|lan| (lan.hostname, lan.agents));
93    remote_agents_on(peers, &crate::backend::reactive::registry::local_host_label())
94}
95
96/// `peers` (host, agent names) as `Name@host`, without the ones on `own_host`: another channel on this
97/// machine shares its agents, which are named by their local id, and `Name@host` would only be a second
98/// spelling of a local agent that the self-lead and cycle checks do not see.
99fn remote_agents_on(peers: impl IntoIterator<Item = (String, Vec<String>)>, own_host: &str) -> Vec<String> {
100    let mut known: Vec<String> = Vec::new();
101    for (host, agents) in peers {
102        if host.trim().eq_ignore_ascii_case(own_host.trim()) {
103            continue;
104        }
105        for name in &agents {
106            let agent = format!("{name}@{host}");
107            if !known.contains(&agent) {
108                known.push(agent);
109            }
110        }
111    }
112    known
113}
114
115/// The lead `named` (`agent@host`, any case) as the LAN lists it, else a refusal that lists what is known.
116fn remote_lead(known: &[String], named: &str) -> Result<String, Refusal> {
117    known.iter().find(|k| k.eq_ignore_ascii_case(named)).cloned().ok_or_else(|| {
118        let list = if known.is_empty() { "none right now".to_string() } else { known.join(", ") };
119        refuse(
120            StatusCode::NOT_FOUND,
121            format!("no agent '{named}' on the LAN (lead); an agent on another machine is named Name@host, as Agents list shows it. Known now: {list}"),
122        )
123    })
124}
125
126/// The changes `req` asks for, with every agent and lead named by id, and the leads on other machines
127/// among them.
128fn changes_of(state: &AppState, req: SetSeatsRequest) -> Result<(Vec<SeatChange>, Vec<String>), Refusal> {
129    let known = if req.seats.iter().any(|e| e.seat.as_ref().and_then(|s| s.lead.as_deref()).is_some_and(crate::backend::agent_seat::is_remote_lead)) {
130        known_remote_agents(state)
131    } else {
132        Vec::new()
133    };
134    changes_of_with(state, req, &known)
135}
136
137fn changes_of_with(state: &AppState, req: SetSeatsRequest, known: &[String]) -> Result<(Vec<SeatChange>, Vec<String>), Refusal> {
138    if req.seats.is_empty() {
139        return Err(refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: seats is empty; give [{agent, seat}], seat null to clear"));
140    }
141    if req.seats.len() > MAX_SEATS_PER_CALL {
142        return Err(refuse(
143            StatusCode::BAD_REQUEST,
144            format!("INVALID_ARG: at most {MAX_SEATS_PER_CALL} seats in one call (got {})", req.seats.len()),
145        ));
146    }
147    let mut changes: Vec<SeatChange> = Vec::with_capacity(req.seats.len());
148    let mut remote: Vec<String> = Vec::new();
149    for entry in req.seats {
150        let agent_id = uid_of(state, &entry.agent, "agent")?;
151        if changes.iter().any(|c| c.agent_id == agent_id) {
152            return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: '{}' appears twice in seats", entry.agent.trim())));
153        }
154        let mut seat = entry.seat;
155        if let Some(input) = seat.as_mut() {
156            // A lead may be named by slug, like the agent itself.
157            if let Some(lead) = input.lead.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
158                input.lead = Some(if crate::backend::agent_seat::is_remote_lead(lead) {
159                    let canonical = remote_lead(known, lead)?;
160                    remote.push(canonical.clone());
161                    canonical
162                } else {
163                    uid_of(state, lead, "lead")?
164                });
165            }
166        }
167        changes.push(SeatChange { agent_id, seat });
168    }
169    Ok((changes, remote))
170}
171
172fn audit(state: &AppState, actor: &Actor, target_slug: &str, ok: bool, error: Option<&str>, note: &str) -> String {
173    let request_id = uuid::Uuid::new_v4().to_string();
174    let block_id = state.reactive_handler.block_for_uid(&actor.uid).unwrap_or_default();
175    let reason = format!("{} (uid {}): {note}", actor.slug, actor.uid);
176    state.reactive_handler.log_fleet_action_audit(
177        Some(&actor.slug),
178        target_slug,
179        &block_id,
180        AUDIT_ACTION,
181        ok,
182        error,
183        &request_id,
184        Some(&reason),
185    );
186    request_id
187}
188
189/// What a change did, for the audit line and the answer.
190fn summary_of(p: &PlannedSeat) -> String {
191    match &p.seat {
192        Some(s) => format!(
193            "set the seat of {} ({}) to {}{}{}",
194            p.name,
195            p.agent_id,
196            s.role,
197            s.qualifier.as_deref().map(|q| format!(" / {q}")).unwrap_or_default(),
198            s.lead.as_deref().map(|l| format!(", reports to {l}")).unwrap_or_else(|| ", reports to the operator".to_string()),
199        ),
200        None => format!("cleared the seat of {} ({})", p.name, p.agent_id),
201    }
202}
203
204/// Plan, then write all of `changes` under the seat lock.
205fn apply(state: &AppState, actor: &Actor, changes: Vec<SeatChange>, remote: &[String]) -> Result<Vec<PlannedSeat>, Refusal> {
206    let bad = |e: String| refuse(if e.contains("not found") { StatusCode::NOT_FOUND } else { StatusCode::BAD_REQUEST }, e);
207    let mstore = &state.mstore;
208    // Held from reading every seat to writing the last, across channels and
209    // instances, so two writes can't each pass the cycle check (#5378).
210    let _seats = mstore
211        .agent_seat_lock()
212        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent seats: {e}")))?;
213    let defs = mstore
214        .agent_def_list()
215        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent seats: {e}")))?;
216    let planned = plan_seats(mstore, &defs, &changes, "", remote).map_err(bad)?;
217    write_seats(mstore, &planned, &SeatActor::Agent { uid: &actor.uid, name: &actor.name })
218        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
219    Ok(planned)
220}
221
222async fn run(state: &AppState, caller: Option<&Caller>, req: SetSeatsRequest) -> Result<Value, Refusal> {
223    let actor = actor_of(state, caller)?;
224    run_as(state, actor, req).await
225}
226
227/// `set_seat` for an agent on another machine (`remote_ops::agent_ops`): the same checks and write a
228/// local call has, recorded under `who` (`slug@machine`).
229pub(crate) async fn run_remote(state: &AppState, who: &str, req: SetSeatsRequest) -> Result<Value, (StatusCode, String)> {
230    let actor = Actor { uid: format!("remote:{who}"), slug: who.to_string(), name: who.to_string() };
231    run_as(state, actor, req).await.map_err(|r| (r.status, r.message))
232}
233
234async fn run_as(state: &AppState, actor: Actor, req: SetSeatsRequest) -> Result<Value, Refusal> {
235    let outcome = {
236        let (s, a) = (state.clone(), Actor { uid: actor.uid.clone(), slug: actor.slug.clone(), name: actor.name.clone() });
237        tokio::task::spawn_blocking(move || changes_of(&s, req).and_then(|(changes, remote)| apply(&s, &a, changes, &remote)))
238            .await
239            .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent seats: {e}")))?
240    };
241    let planned = match outcome {
242        Ok(planned) => planned,
243        Err(refusal) => {
244            audit(state, &actor, &actor.slug, false, Some(&refusal.message), "refused");
245            return Err(refusal);
246        }
247    };
248    let audit_ids: Vec<String> = planned.iter().map(|p| audit(state, &actor, &p.slug, true, None, &summary_of(p))).collect();
249    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
250    crate::server::agent_handlers::seat::refresh_pane_seats(state).await;
251    let changed: Vec<Value> = planned
252        .iter()
253        .map(|p| json!({ "agent": p.name, "id": p.agent_id, "slug": p.slug, "seat": p.seat }))
254        .collect();
255    Ok(json!({
256        "changed": changed,
257        "audit_ids": audit_ids,
258        "note": "recorded under your name; My Agents, the Swarm and the Kanban show the new seats now",
259    }))
260}
261
262pub(crate) async fn handle_agent_seats(
263    State(state): State<AppState>,
264    caller: Option<Extension<Caller>>,
265    Json(req): Json<SetSeatsRequest>,
266) -> Response {
267    let caller = caller.map(|Extension(c)| c);
268    match run(&state, caller.as_ref(), req).await {
269        Ok(body) => Json(body).into_response(),
270        Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
271    }
272}
273
274#[cfg(test)]
275#[path = "tests/agent_seats_tests.rs"]
276mod tests;