1use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::{json, Value};
19
20use super::agent_lifecycle::{acting, refuse, Actor, Refusal};
21use crate::backend::storage::AgentDefinition;
22use crate::registry::Handover;
23use crate::server::caller::Caller;
24use crate::server::state::AppState;
25
26const AUDIT_BRING_BACK: &str = "agent.bring_back";
27const AUDIT_STATUS: &str = "agent.move_status";
28
29#[derive(Debug, Clone, Deserialize)]
30pub(crate) struct HandoverRequest {
31 #[serde(default)]
33 pub(super) agent: Option<String>,
34 #[serde(default)]
36 pub(super) force: bool,
37}
38
39fn describe(mark: &Handover) -> Value {
41 let way_out = match mark.state.as_str() {
42 Handover::HANDED_OVER => "Agents bring_back clears the mark and the agent can be started here again.",
43 Handover::MOVED => "It lives on the other computer now. Agents bring_back with force: true starts it here anyway, which is safe only when it is not running there.",
44 _ => "Agents bring_back clears the mark.",
45 };
46 json!({
47 "state": mark.state,
48 "to": mark.to,
49 "at_ms": mark.at_ms,
50 "manifest_hash": mark.manifest_hash,
51 "way_out": way_out,
52 })
53}
54
55pub(super) fn target_for(state: &AppState, actor: &Actor, named: Option<&str>, action: &str) -> Result<AgentDefinition, Refusal> {
57 let asked = named.map(str::trim).filter(|n| !n.is_empty()).unwrap_or_else(|| actor.uid());
58 let uid = crate::backend::agent_resolve::resolve_agent_named(&state.mstore, asked).map_err(|e| refuse(StatusCode::NOT_FOUND, format!("no agent '{asked}' on this machine: {e}")))?;
59 let target = state
60 .mstore
61 .agent_def_get(&uid)
62 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents {action}: {e}")))?
63 .ok_or_else(|| refuse(StatusCode::NOT_FOUND, "no such agent on this machine"))?;
64 let leads = crate::backend::agent_seat::effective_seat_by_id(&state.mstore, &target.id).and_then(|s| s.lead).as_deref() == Some(actor.uid());
65 if !actor.is_person() && target.id != actor.uid() && !leads {
66 return Err(refuse(StatusCode::FORBIDDEN, format!("Agents {action} is for your own agent or one you lead; {} is neither.", target.name)));
67 }
68 Ok(target)
69}
70
71fn mark_of(state: &AppState, target: &AgentDefinition) -> Result<Option<Handover>, Refusal> {
73 state.mstore.agent_handover_get(&target.id).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")))
74}
75
76pub(super) fn bring_back(state: &AppState, actor: &Actor, req: &HandoverRequest) -> Result<Value, Refusal> {
77 let target = target_for(state, actor, req.agent.as_deref(), "bring_back")?;
78 if super::agent_export::hand_over_in_flight(&target.id) || super::agent_move::move_in_flight(&target.id) {
81 return Err(refuse(StatusCode::CONFLICT, format!("{} is being handed over right now: try again when that has finished.", target.name)));
82 }
83 let Some(mark) = mark_of(state, &target)? else {
84 return Ok(json!({ "agent": target.name, "agent_id": target.id, "brought_back": false, "note": "it is not handed over: nothing to bring back" }));
85 };
86 if mark.state == Handover::MOVED && !req.force {
87 return Err(refuse(
88 StatusCode::CONFLICT,
89 format!(
90 "{} moved to {} and may be running there; starting it here as well would give it two lives. If it is not running there, bring it back anyway with force: true.",
91 target.name,
92 if mark.to.is_empty() { "another computer" } else { mark.to.as_str() },
93 ),
94 ));
95 }
96 state
97 .mstore
98 .agent_handover_set(&target.id, None)
99 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents bring_back: the mark could not be cleared: {e}")))?;
100 state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
101 Ok(json!({
102 "agent": target.name,
103 "agent_id": target.id,
104 "brought_back": true,
105 "was": describe(&mark),
106 "note": "the mark is cleared; the agent starts here again when someone starts it or sends it a message. A copy that was imported elsewhere from its file is a separate agent there and is not touched.",
107 }))
108}
109
110fn move_status(state: &AppState, actor: &Actor, req: &HandoverRequest) -> Result<Value, Refusal> {
111 let target = target_for(state, actor, req.agent.as_deref(), "move_status")?;
112 Ok(match mark_of(state, &target)? {
113 Some(mark) => json!({ "agent": target.name, "agent_id": target.id, "handed_over": true, "mark": describe(&mark) }),
114 None => json!({ "agent": target.name, "agent_id": target.id, "handed_over": false, "note": "it is here, not handed over" }),
115 })
116}
117
118pub(super) fn mark_moved(state: &AppState, target: &AgentDefinition, to: &str, manifest_hash: &str) -> Result<(), String> {
121 let mark = Handover { state: Handover::MOVED.to_string(), to: to.to_string(), at_ms: agentmux_common::time::now_ms(), manifest_hash: manifest_hash.to_string() };
122 state.mstore.agent_handover_set(&target.id, Some(&mark)).map_err(|e| e.to_string())?;
123 state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
124 Ok(())
125}
126
127pub(super) fn current_mark(state: &AppState, target: &AgentDefinition) -> Result<Option<Handover>, Refusal> {
129 mark_of(state, target)
130}
131
132pub(super) fn mark_handed_over(state: &AppState, target: &AgentDefinition, to: &str, manifest_hash: &str) -> Result<(), String> {
135 let mark = Handover { state: Handover::HANDED_OVER.to_string(), to: to.to_string(), at_ms: agentmux_common::time::now_ms(), manifest_hash: manifest_hash.to_string() };
136 state.mstore.agent_handover_set(&target.id, Some(&mark)).map_err(|e| e.to_string())?;
137 state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
138 Ok(())
139}
140
141fn audit(state: &AppState, actor: &Actor, action: &str, target: &str, ok: bool, error: Option<&str>, note: &str) {
142 let request_id = uuid::Uuid::new_v4().to_string();
143 let block_id = state.reactive_handler.block_for_uid(actor.uid()).unwrap_or_default();
144 let reason = format!("{} (uid {}): {note}", actor.slug(), actor.uid());
145 state.reactive_handler.log_fleet_action_audit(Some(actor.slug()), target, &block_id, action, ok, error, &request_id, Some(&reason));
146}
147
148async fn run(state: AppState, caller: Option<Caller>, action: &'static str, req: HandoverRequest) -> Result<Value, Refusal> {
149 let actor = acting(&state, caller.as_ref(), action, req.agent.as_deref())?;
150 let named = req.agent.clone().unwrap_or_else(|| actor.uid().to_string());
151 let audit_action = if action == "bring_back" { AUDIT_BRING_BACK } else { AUDIT_STATUS };
152 let kept = if action == "bring_back" { super::agent_move::release_kept_move(&state, &actor, &req).await } else { Ok(()) };
155 let st = state.clone();
156 let who = actor.clone();
157 let outcome = tokio::task::spawn_blocking(move || if let Err(r) = kept { Err(r) } else if action == "bring_back" { bring_back(&st, &who, &req) } else { move_status(&st, &who, &req) })
158 .await
159 .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("Agents {action}: {e}")))?;
160 match outcome {
161 Ok(body) => {
162 audit(&state, &actor, audit_action, &named, true, None, body["note"].as_str().unwrap_or(action));
163 Ok(body)
164 }
165 Err(r) => {
166 audit(&state, &actor, audit_action, &named, false, Some(&r.message), "refused");
167 Err(r)
168 }
169 }
170}
171
172async fn answer(state: AppState, caller: Option<Extension<Caller>>, action: &'static str, req: HandoverRequest) -> Response {
173 match run(state, caller.map(|Extension(c)| c), action, req).await {
174 Ok(body) => Json(body).into_response(),
175 Err(r) => (r.status, Json(json!({ "error": r.message }))).into_response(),
176 }
177}
178
179pub(crate) async fn handle_agent_bring_back(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<HandoverRequest>) -> Response {
180 answer(state, caller, "bring_back", req).await
181}
182
183pub(crate) async fn handle_agent_move_status(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<HandoverRequest>) -> Response {
184 answer(state, caller, "move_status", req).await
185}
186
187#[cfg(test)]
188#[path = "tests/agent_handover_tests.rs"]
189mod tests;