agentmux_srv/server/remote_ops/
move_consent.rs1use 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
29const MAX_HELD: usize = 16;
31const HOLD: Duration = Duration::from_secs(30 * 60);
33
34struct Held {
36 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
71fn 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 if let HarnessCall::Installs(note) = harness {
76 carries = format!("{note}; {carries}");
77 }
78 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 ("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 ("move".to_string(), format!("{} attempt {}", summary.move_id.chars().take(8).collect::<String>(), summary.attempt)),
95 ])
96}
97
98pub(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 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 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
123pub(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
132fn 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
152pub(super) fn reconcile(staging: &Staging, move_id: &str, who: &Counterpart) {
154 settle(staging, Some((move_id, who)));
155}