Skip to main content

agentmux_srv/server/remote_ops/
move_consent.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The decision on an agent moving to this computer (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 6.3, step D of the
5//! build). An offer that passed its checks is filed here as the `agent_move_in` sensitive request: this computer's super
6//! agent reviews it, and the person sees a banner naming the agent, where it comes from, who asked, what it carries and
7//! how big it is, with a countdown they can stop. The banner's words come from the source's signed summary, never from
8//! anything the offer carries outside it, and say the agent's history is carried as it is.
9//!
10//! The staging area takes no chunk until the move is **allowed**, and the move is allowed only by this route:
11//!
12//! - the countdown ending unvetoed runs [`run_after_countdown`], which records the allowance for the attempt that was
13//!   shown (a later attempt is a new offer and is asked about again);
14//! - a veto, a denial, a withdrawal or an expiry is noticed by [`reconcile`] the next time the source asks where the move
15//!   stands, and ends the move there.
16
17use std::collections::{BTreeMap, HashMap};
18use std::sync::{Mutex, MutexGuard, OnceLock};
19use std::time::{Duration, Instant};
20
21use super::{AppState, RemoteCaller, RemoteRefusal};
22use crate::backend::agent_move::signed::OfferSummary;
23use crate::backend::agent_move::staging::{Counterpart, Staging};
24use crate::backend::sensitive_ops::VALUE_MAX;
25use crate::backend::sensitive_requests::{registry, Request, Status, REMOTE_OWNER_PREFIX};
26use crate::server::app_api::agent_spawn::import::moved::RouteCall;
27use super::move_harness::HarnessCall;
28
29/// Moves waiting for an answer at once; the staging area holds fewer, so this is only a bound on the table.
30const MAX_HELD: usize = 16;
31/// How long a request is kept before its allowance is let go: past the longest countdown and the offer's own lifetime.
32const HOLD: Duration = Duration::from_secs(30 * 60);
33
34/// What the request stands for.
35struct Held {
36    /// The staging area the move is in (its address): one per AgentMux, so a table shared by tests never crosses areas.
37    area: usize,
38    move_id: String,
39    who: Counterpart,
40    attempt: u32,
41    at: Instant,
42}
43
44fn held() -> MutexGuard<'static, HashMap<String, Held>> {
45    static HELD: OnceLock<Mutex<HashMap<String, Held>>> = OnceLock::new();
46    HELD.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap_or_else(|e| e.into_inner())
47}
48
49fn area_of(staging: &Staging) -> usize {
50    std::ptr::from_ref(staging) as usize
51}
52
53fn fit(text: &str) -> String {
54    if text.chars().count() <= VALUE_MAX {
55        return text.to_string();
56    }
57    let mut cut: String = text.chars().take(VALUE_MAX - 1).collect();
58    cut.push('…');
59    cut
60}
61
62fn size_text(bytes: u64) -> String {
63    const MIB: u64 = 1024 * 1024;
64    if bytes >= MIB {
65        format!("{:.1} MB", bytes as f64 / MIB as f64)
66    } else {
67        format!("{} KB", bytes.div_ceil(1024).max(1))
68    }
69}
70
71/// The facts of the banner, from the signed summary.
72fn facts(caller: &RemoteCaller, summary: &OfferSummary, route: &RouteCall, harness: &HarnessCall) -> BTreeMap<String, String> {
73    let mut carries = if summary.contents.is_empty() { "its definition only".to_string() } else { summary.contents.join("; ") };
74    // A harness that is not installed here is said too, after the route (the route is put in front below): the agent will not start until it is.
75    if let HarnessCall::Installs(note) = harness {
76        carries = format!("{note}; {carries}");
77    }
78    // What a paid route would bill is said by this computer from the signed route, never from the source's own wording.
79    // It comes first: a long list is cut at the end, and who pays must not be what is cut.
80    match route {
81        RouteCall::None => {}
82        RouteCall::Keep(text) | RouteCall::Drop(text) => carries = format!("{text}; {carries}"),
83    }
84    BTreeMap::from([
85        ("agent".to_string(), fit(&summary.agent_name)),
86        ("from".to_string(), fit(&caller.machine)),
87        // Who asked, as the source signed it: the agent that sends the move may be another than the one that asked.
88        ("asked_by".to_string(), fit(&format!("{} ({})", summary.requester, summary.asker_kind))),
89        ("runs".to_string(), fit(&summary.runtime)),
90        ("carries".to_string(), fit(&carries)),
91        ("size".to_string(), size_text(summary.total_bytes)),
92        // The move and the attempt the person is shown, so a higher attempt is a request of its own: a request is joined
93        // by its facts, and a joined one would carry an earlier attempt's countdown over to the replacement.
94        ("move".to_string(), format!("{} attempt {}", summary.move_id.chars().take(8).collect::<String>(), summary.attempt)),
95    ])
96}
97
98/// File the request for the person to decide on the offered move, as the agent that made the offer.
99pub(super) async fn ask(state: &AppState, caller: &RemoteCaller, who: &Counterpart, summary: &OfferSummary, route: &RouteCall, harness: &HarnessCall) -> Result<(), RemoteRefusal> {
100    let owner = format!("{REMOTE_OWNER_PREFIX}{}", caller.actor());
101    let reason = format!("move the agent {} to this computer", summary.agent_name);
102    let filed = crate::server::sensitive_handlers::file_request(state, &owner, &caller.actor(), "agent_move_in", &facts(caller, summary, route, harness), &reason)
103        .await
104        .map_err(RemoteRefusal::failed)?;
105    let id = filed.get("id").and_then(serde_json::Value::as_str).unwrap_or_default().to_string();
106    if id.is_empty() {
107        return Err(RemoteRefusal::failed("the request for the person could not be filed"));
108    }
109    let staging = state.move_staging.as_deref().ok_or_else(|| RemoteRefusal::new("not_available", "this AgentMux has no staging area for incoming agents"))?;
110    // Moves whose requests ended since are ended first, so no entry is let go with its move left waiting.
111    settle(staging, None);
112    let mut all = held();
113    if all.len() >= MAX_HELD && !all.contains_key(&id) {
114        drop(all);
115        let _ = registry().cancel(&id, &owner, agentmux_common::time::now_ms());
116        return Err(RemoteRefusal::new("busy", "too many moves are waiting for an answer here; try again when one has been decided"));
117    }
118    // A request that was joined keeps what it was filed for: the facts name the move and the attempt, so it is the same.
119    all.entry(id).or_insert(Held { area: area_of(staging), move_id: summary.move_id.clone(), who: who.clone(), attempt: summary.attempt, at: Instant::now() });
120    Ok(())
121}
122
123/// The runner: the countdown ended unvetoed, so the move the person was shown is allowed.
124pub(crate) async fn run_after_countdown(state: AppState, request: Request) -> Result<(), String> {
125    let entry = held().remove(&request.id).ok_or("the offer this request was for is no longer known; the source asks again")?;
126    let staging: &Staging = state.move_staging.as_deref().ok_or("this AgentMux has no staging area for incoming agents")?;
127    staging.decide(&entry.move_id, &entry.who, entry.attempt, true).map_err(|e| e.to_string())?;
128    tracing::info!(requester = %request.requester_slug, approver = ?request.decided_by, "agent move: allowed by the person's countdown");
129    Ok(())
130}
131
132/// Ends the moves whose request ended without allowing them (vetoed, denied, withdrawn, expired), and lets go of the
133/// entries that waited too long. `only` limits it to one move: the source asking where it stands.
134fn settle(staging: &Staging, only: Option<(&str, &Counterpart)>) {
135    let ended: Vec<(String, Held)> = {
136        let mut all = held();
137        let ids: Vec<String> = all
138            .iter()
139            .filter(|(_, h)| h.area == area_of(staging))
140            .filter(|(_, h)| only.is_none_or(|(move_id, who)| h.move_id == move_id && h.who == *who))
141            .filter(|(id, h)| h.at.elapsed() >= HOLD || registry().get(id).is_none_or(|r| !r.status.is_open() && r.status != Status::Done))
142            .map(|(id, _)| id.clone())
143            .collect();
144        ids.into_iter().filter_map(|id| all.remove(&id).map(|h| (id, h))).collect()
145    };
146    for (id, h) in ended {
147        tracing::info!(request_id = %id, "agent move: the person's request ended without allowing it; the move is refused");
148        let _ = staging.decide(&h.move_id, &h.who, h.attempt, false);
149    }
150}
151
152/// If the request for this move ended without allowing it, end the move.
153pub(super) fn reconcile(staging: &Staging, move_id: &str, who: &Counterpart) {
154    settle(staging, Some((move_id, who)));
155}