Skip to main content

agentmux_srv/server/
agent_takeover.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Taking an agent over from another AgentMux instance on this host
5//! (`docs/specs/SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24.md` Phase 2, §4.6).
6//!
7//! Two halves, both behind full `auth_key` auth:
8//!
9//! - `POST /api/v1/agent/takeover {block_id}` — on the instance the user is
10//!   in. Its pane was refused because another instance runs the agent; the
11//!   user confirmed "Take over". Finds that instance (lease holder, or the
12//!   compat probe for one that takes no lease), asks it to let go, and waits
13//!   until the agent is free. The pane then runs its turn as usual.
14//! - `POST /agentmux/agent/release {uid}` — on the holder. Gracefully stops
15//!   the CLI process of every pane of this srv that holds `uid`'s lease,
16//!   shows "taken over" in those panes, and keeps this srv from re-claiming
17//!   the agent on its own for a short hold.
18//!
19//! Never jekt-drivable (spec I5, D7): a jekt body cannot reach either route.
20//! The requester side is reached from the pane's own Take over action after
21//! a confirmation; the holder side authenticates with the holder's own full
22//! auth key, which the requester reads from the host-global shared registry
23//! — the same trust cross-channel jekt forwarding already relies on.
24
25use axum::extract::State;
26use axum::http::StatusCode;
27use axum::response::{IntoResponse, Response};
28use axum::Json;
29use serde::Deserialize;
30use serde_json::json;
31
32use super::AppState;
33use crate::backend::agent_admission;
34use crate::backend::blockcontroller;
35use crate::backend::obj::{self, Block};
36use crate::sagas::pending_shutdown::Action;
37
38/// How long the holder lets a turn in flight finish before killing it.
39const RELEASE_GRACE: std::time::Duration = std::time::Duration::from_secs(10);
40
41/// How long the requester waits for the agent to become free.
42const TAKEOVER_WAIT: std::time::Duration = std::time::Duration::from_secs(25);
43
44#[derive(Debug, Deserialize)]
45pub(super) struct TakeoverRequest {
46    pub(super) block_id: String,
47}
48
49/// Take a pane's agent over. Reached from the window's own socket (`agent.takeover`, `caller` `None`)
50/// and, for an agent's own pane, from `pane_binding::handle_takeover`.
51pub(super) async fn take_over(state: &AppState, caller: Option<&super::caller::Caller>, req: TakeoverRequest) -> Response {
52    let block = {
53        let mstore = state.mstore.clone();
54        let block_id = req.block_id.clone();
55        tokio::task::spawn_blocking(move || mstore.get::<Block>(&block_id)).await
56    };
57    let Ok(Ok(Some(block))) = block else {
58        return (StatusCode::NOT_FOUND, Json(json!({ "error": "block not found" }))).into_response();
59    };
60    let uid = obj::meta_get_string(&block.meta, "agentId", "");
61    if uid.is_empty() {
62        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "this pane has no agent" }))).into_response();
63    }
64    let name = obj::meta_get_string(&block.meta, "agentName", "");
65    if let Err(error) = super::actor::own_agent_only(caller, Some(&uid)) {
66        return (StatusCode::FORBIDDEN, Json(json!({ "error": error }))).into_response();
67    }
68
69    // The user is deliberately taking the agent (back) here.
70    agent_admission::clear_handover_hold(&uid);
71    let store = agent_admission::lease_store_for(state.mstore.shared_agent_registry());
72    let holder = match agent_admission::locate_holder(store.clone(), &uid, &state.boot_id).await {
73        Some(holder) => holder,
74        // No local lease or running instance: the relay may still name a
75        // holder (its WAN lease outlives a closed pane on an older build).
76        None => match wan_takeover_target(&name) {
77            // Nobody else runs it (any more): nothing to take over.
78            WanTarget::NoHolder => {
79                return (StatusCode::OK, Json(json!({ "ok": true, "released": false }))).into_response();
80            }
81            WanTarget::OtherComputer(where_) => {
82                return (StatusCode::CONFLICT, Json(json!({ "error": other_computer_error(&name, &where_) })))
83                    .into_response();
84            }
85            WanTarget::ThisComputer(channel) => match agent_admission::endpoint_for_channel(&channel).await {
86                Some(holder) => holder,
87                None => {
88                    let agent = if name.is_empty() { "this agent" } else { name.as_str() };
89                    let error = format!(
90                        "AgentMux Cloud says the instance on this computer in channel {channel} holds {agent}, \
91                         but that instance isn't running. Its hold ends within a minute; try again then."
92                    );
93                    return (StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response();
94                }
95            },
96        },
97    };
98    tracing::info!(
99        uid = %uid,
100        block_id = %req.block_id,
101        holder_channel = %holder.channel,
102        "agent_admission.takeover: requesting release from the holder"
103    );
104    if let Err(e) = agent_admission::request_release(&holder, &uid, &name).await {
105        return (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response();
106    }
107    if let Err(e) = agent_admission::wait_until_free(store, &uid, &state.boot_id, TAKEOVER_WAIT).await {
108        return (StatusCode::GATEWAY_TIMEOUT, Json(json!({ "error": e }))).into_response();
109    }
110    // The holder let go: forget the cached relay refusal, or the pane's
111    // retry is refused from it for up to 90 s (Codex P1 on #3899).
112    crate::muxbus::wan_lease::forget_elsewhere(&name).await;
113    // ...and take the relay lease now. A holder older than #3899 answers the
114    // release but keeps renewing the lease for as long as it runs, so the new
115    // pane would be fenced seconds after starting (narko 2026-09-27; see
116    // docs/investigations/INVESTIGATION_TAKE_OVER_OLD_HOLDER_RELAY_LEASE_2026_09_27.md).
117    // Unknown (no MuxBus session, an unreachable relay) fails open as before.
118    match crate::muxbus::cloud_subscriber::take_over_lease_now(&state.id_store, &state.http_client, &name).await {
119        crate::muxbus::wan_lease::Outcome::HeldElsewhere(where_) => {
120            let error = if crate::muxbus::wan_lease::holder_on_this_computer(&where_) {
121                kept_relay_hold_error(&name, &where_)
122            } else {
123                other_computer_error(&name, &where_)
124            };
125            tracing::warn!(uid = %uid, holder = %where_, "agent_admission.takeover: the relay still names another holder");
126            return (StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response();
127        }
128        crate::muxbus::wan_lease::Outcome::Held => {
129            tracing::info!(uid = %uid, "agent_admission.takeover: relay lease is ours");
130        }
131        crate::muxbus::wan_lease::Outcome::Unknown => {}
132    }
133    (
134        StatusCode::OK,
135        Json(json!({ "ok": true, "released": true, "from_channel": holder.channel })),
136    )
137        .into_response()
138}
139
140#[derive(Debug, Deserialize)]
141pub(super) struct HoldingQuery {
142    uid: String,
143}
144
145/// `GET /agentmux/agent/holding?uid=…` — a LAN peer asking whether this host
146/// runs `uid` (spec §4.4, Phase 4). LAN-key readable, like the agent-name
147/// list: it discloses only whether an agent UID is live here, since when,
148/// and in which channel/version.
149pub(super) async fn handle_agent_holding(
150    State(state): State<AppState>,
151    axum::extract::Query(q): axum::extract::Query<HoldingQuery>,
152) -> Response {
153    let uid = q.uid.trim().to_string();
154    if uid.is_empty() {
155        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "uid required" }))).into_response();
156    }
157    let store = agent_admission::lease_store_for(state.mstore.shared_agent_registry());
158    let holding = tokio::task::spawn_blocking(move || agent_admission::local_holding(store.as_ref(), &uid))
159        .await
160        .unwrap_or_default();
161    (StatusCode::OK, Json(json!(holding))).into_response()
162}
163
164#[derive(Debug, Deserialize)]
165pub(super) struct ReleaseRequest {
166    uid: String,
167    /// The agent's name, from requesters that send it: lets this srv drop a
168    /// relay subscription (and WAN lease) that outlived the agent's panes.
169    #[serde(default)]
170    agent: String,
171    #[serde(default)]
172    requested_by_channel: String,
173    #[serde(default)]
174    requested_by_version: String,
175}
176
177pub(super) async fn handle_agent_release(
178    State(state): State<AppState>,
179    caller: Option<axum::Extension<super::caller::Caller>>,
180    Json(req): Json<ReleaseRequest>,
181) -> Response {
182    let uid = req.uid.trim().to_string();
183    if uid.is_empty() {
184        return (StatusCode::BAD_REQUEST, Json(json!({ "error": "uid required" }))).into_response();
185    }
186    if let Err(error) = super::actor::own_agent_only(caller.as_deref(), Some(&uid)) {
187        return (StatusCode::FORBIDDEN, Json(json!({ "error": error }))).into_response();
188    }
189    // The relay subscription released below is found by name: an agent's token releases its own name only.
190    if caller.as_deref().and_then(super::caller::Caller::uid).is_some() && !req.agent.trim().is_empty() {
191        let (mstore, uid, name) = (state.mstore.clone(), uid.clone(), req.agent.trim().to_string());
192        let own = tokio::task::spawn_blocking(move || super::actor::proven_slug(&mstore, &uid, &name).is_some()).await;
193        if !own.unwrap_or(false) {
194            return (StatusCode::FORBIDDEN, Json(json!({ "error": "FORBIDDEN: an agent releases its own name only" }))).into_response();
195        }
196    }
197    let blocks = {
198        let mstore = state.mstore.clone();
199        let uid = uid.clone();
200        tokio::task::spawn_blocking(move || {
201            mstore
202                .get_all::<Block>()
203                .unwrap_or_default()
204                .into_iter()
205                .filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == uid)
206                .collect::<Vec<_>>()
207        })
208        .await
209        .unwrap_or_default()
210    };
211    let to = describe_requester(&req.requested_by_channel, &req.requested_by_version);
212    let live: Vec<Block> = blocks.into_iter().filter(|b| can_release(&b.oid)).collect();
213    let mut released = 0usize;
214    if caller.as_deref().and_then(super::caller::Caller::uid).is_some() {
215        // An agent's token: the agent letting go of itself.
216        for block in &live {
217            if release_block(&state, &block.oid, &to).is_ok() {
218                released += 1;
219            }
220        }
221    } else if !live.is_empty() {
222        // Another AgentMux asks, and what it says about itself can't be checked: this instance's user is shown
223        // it and can keep the agent running.
224        let by = if to.is_empty() { "another AgentMux".to_string() } else { format!("AgentMux {to} (as claimed by another AgentMux)") };
225        let asked: Vec<_> = live
226            .iter()
227            .map(|b| crate::sagas::pending_shutdown::request(&state, &b.oid, &by, "Takeover", "", Action::Release { to: to.clone() }))
228            .collect();
229        let settled = wait_for_user(&asked).await;
230        released = settled.iter().filter(|s| **s == "shut_down").count();
231        if settled.contains(&"kept_by_user") {
232            let who = if req.agent.trim().is_empty() { "this agent" } else { req.agent.trim() };
233            let error = format!("The user of the AgentMux instance running {who} chose to keep it running there.");
234            return (StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response();
235        }
236    }
237    // The relay may still see this srv as the holder — even with no pane
238    // running it: a subscription that outlived its panes (charlie,
239    // 2026-09-26) renews the WAN lease every tick. Let go of it now, and
240    // before answering, so the requester's retry can claim the lease.
241    //
242    // Also after stopping live panes (Codex P1 on #3903): their exit hands
243    // the WAN release to a background task, so the requester's retry could
244    // still meet this srv's lease and be fenced. The handover hold keeps
245    // this srv from re-claiming the agent, so letting go here is safe.
246    let agent = req.agent.trim();
247    let was_live = released > 0;
248    // The hold goes up before the release is awaited (Codex P1 on #3908):
249    // otherwise a local turn in that window re-registers the agent, re-adds
250    // its subscription, and this srv keeps the lease it claims to hand over.
251    let hand_over = was_live || !agent.is_empty();
252    if hand_over {
253        agent_admission::hold_after_handover(&uid, &to);
254    }
255    if !agent.is_empty() {
256        use crate::muxbus::cloud_subscriber::RelayRelease;
257        match crate::muxbus::cloud_subscriber::release_agent_now(&state.id_store, agent).await {
258            RelayRelease::Released => {
259                tracing::info!(agent = %agent, was_live, "agent_admission.takeover: released the relay subscription and lease");
260                if !was_live {
261                    released += 1;
262                }
263            }
264            // Re-added despite the hold (a turn already past admission): the
265            // relay lease stays here, so the requester's retry would be fenced.
266            RelayRelease::Kept => {
267                tracing::warn!(agent = %agent, "agent_admission.takeover: the agent was re-added while releasing — relay lease kept");
268            }
269            // No relay subscription (or no relay at all): nothing to release.
270            RelayRelease::NotSubscribed => {}
271        }
272    }
273    if released == 0 && hand_over {
274        // Nothing was handed over after all: don't block this srv's own use.
275        agent_admission::clear_handover_hold(&uid);
276    }
277    tracing::info!(uid = %uid, released, to = %to, "agent_admission.takeover: release handled");
278    (StatusCode::OK, Json(json!({ "ok": true, "released": released }))).into_response()
279}
280
281/// Whether this pane holds the agent's lease and has a process to stop.
282fn can_release(block_id: &str) -> bool {
283    blockcontroller::get_controller(block_id).is_some_and(|c| {
284        c.as_any()
285            .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
286            .is_some_and(|p| p.can_release())
287    })
288}
289
290/// Let go of one pane's agent for another instance: gracefully stop its CLI (a turn in flight finishes, then it is
291/// killed at `RELEASE_GRACE`) and say so in the pane. `Err` when this pane holds nothing.
292pub(crate) fn release_block(state: &AppState, block_id: &str, to: &str) -> Result<(), String> {
293    let ctrl = blockcontroller::get_controller(block_id).ok_or_else(|| format!("NOT_RUNNING: no controller for block {block_id}"))?;
294    // The hold goes up before the process is signalled: once it exits, a message reaching this instance must not
295    // start the agent here again.
296    let uid = state
297        .mstore
298        .get::<Block>(block_id)
299        .ok()
300        .flatten()
301        .map(|b| obj::meta_get_string(&b.meta, "agentId", ""))
302        .unwrap_or_default();
303    if !uid.is_empty() {
304        agent_admission::hold_after_handover(&uid, to);
305    }
306    let released = ctrl
307        .as_any()
308        .downcast_ref::<blockcontroller::persistent::PersistentSubprocessController>()
309        .is_some_and(|p| p.release_to_other_instance(std::time::Instant::now() + RELEASE_GRACE));
310    if !released {
311        if !uid.is_empty() {
312            agent_admission::clear_handover_hold(&uid);
313        }
314        return Err(format!("NOT_RUNNING: block {block_id} holds nothing to release"));
315    }
316    let name = state
317        .mstore
318        .get::<Block>(block_id)
319        .ok()
320        .flatten()
321        .map(|b| obj::meta_get_string(&b.meta, "agentName", ""))
322        .unwrap_or_default();
323    let who = if name.is_empty() { "This agent" } else { name.as_str() };
324    let reason = format!(
325        "{who} was taken over by another AgentMux instance on this host{}. \
326         Use Take over to bring it back here.",
327        if to.is_empty() { String::new() } else { format!(" ({to})") }
328    );
329    surface_failure(state, block_id, &reason);
330    Ok(())
331}
332
333/// Wait for the user to decide on each request (their override window, then the release itself); each one's
334/// final status. A request still open after the window and the grace has no final status and reads `pending`.
335async fn wait_for_user(asked: &[crate::sagas::pending_shutdown::PendingView]) -> Vec<&'static str> {
336    use crate::sagas::pending_shutdown as ps;
337    let give_up = std::time::Instant::now() + ps::OVERRIDE_WINDOW + RELEASE_GRACE + std::time::Duration::from_secs(5);
338    loop {
339        let now: Vec<&'static str> = asked.iter().map(|v| ps::status(&v.request_id).map_or("superseded", |s| s.status)).collect();
340        if now.iter().all(|s| !matches!(*s, "pending" | "proceeding")) || std::time::Instant::now() >= give_up {
341            return now;
342        }
343        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
344    }
345}
346
347fn describe_requester(channel: &str, version: &str) -> String {
348    match (channel.is_empty(), version.is_empty()) {
349        (false, false) => format!("channel {channel}, v{version}"),
350        (false, true) => format!("channel {channel}"),
351        (true, false) => format!("v{version}"),
352        (true, true) => String::new(),
353    }
354}
355
356/// Show `message` in the pane's recovery row — the same persisted meta and
357/// live event a spawn refusal uses.
358pub(super) fn surface_failure(state: &AppState, block_id: &str, message: &str) {
359    let failure = crate::agents::failure::classify(None, None, message, None);
360    surface_classified_failure(state, block_id, &failure);
361}
362
363/// [`surface_failure`] for a failure already built (its wording set by the caller).
364pub(crate) fn surface_classified_failure(state: &AppState, block_id: &str, failure: &crate::agents::failure::AgentFailure) {
365    blockcontroller::core::persist_last_failure(
366        block_id,
367        Some(failure),
368        &Some(state.mstore.clone()),
369        &Some(state.event_bus.clone()),
370    );
371    state.broker.publish_event::<crate::backend::mps_events::AgentFailed>(failure, vec![format!("block:{block_id}")], 1);
372}
373
374/// Who holds `agent` per the relay, when no local lease or running
375/// instance does. Charlie 2026-09-26: a same-computer instance (another
376/// channel) held only the relay lease, and Take over looked nowhere else,
377/// answered `released: false`, and the pane was refused again.
378#[derive(Debug, PartialEq, Eq)]
379enum WanTarget {
380    NoHolder,
381    /// Another instance on this computer, by channel.
382    ThisComputer(String),
383    /// Another computer, as described by the relay's holder record.
384    OtherComputer(String),
385}
386
387fn wan_takeover_target(agent: &str) -> WanTarget {
388    if let Some(channel) = crate::muxbus::wan_lease::held_on_this_computer_by(agent) {
389        return WanTarget::ThisComputer(channel);
390    }
391    match crate::muxbus::wan_lease::held_on_another_computer(agent) {
392        Some(where_) => WanTarget::OtherComputer(where_),
393        None => WanTarget::NoHolder,
394    }
395}
396
397/// Take over reaches instances on this computer only.
398/// The instance on this computer let go of the pane but the relay still
399/// names it, and the relay wouldn't move the lease (a relay without
400/// `/agents/lease/take`, or a lease claimed for another account).
401fn kept_relay_hold_error(agent: &str, where_: &str) -> String {
402    let agent = if agent.is_empty() { "this agent" } else { agent };
403    format!(
404        "AgentMux Cloud still says {agent} is held by the AgentMux instance on {where_}. \
405         That instance is probably an older version that can't hand it over. \
406         Quit it completely (from the tray, not just its window); its hold ends \
407         within a minute, then try again."
408    )
409}
410
411fn other_computer_error(agent: &str, where_: &str) -> String {
412    let agent = if agent.is_empty() { "this agent" } else { agent };
413    format!(
414        "{agent} is running on another computer ({where_}), according to AgentMux Cloud. \
415         Take over only works between AgentMux instances on this computer. \
416         Close {agent} there, then try again."
417    )
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    #[test]
425    fn the_requester_is_described_by_what_it_sent() {
426        assert_eq!(describe_requester("dev-x", "0.58.0"), "channel dev-x, v0.58.0");
427        assert_eq!(describe_requester("", "0.58.0"), "v0.58.0");
428        assert_eq!(describe_requester("", ""), "");
429    }
430
431    /// The holder pane's message is classified as the takeover case, so its
432    /// row offers Take over (to bring the agent back), not Retry.
433    #[test]
434    fn the_holder_side_message_classifies_as_taken_over() {
435        let reason = "Agent3 was taken over by another AgentMux instance on this host (channel dev-x, v0.58.0). \
436                      Use Take over to bring it back here.";
437        let f = crate::agents::failure::classify(None, None, reason, None);
438        assert_eq!(f.code, crate::agents::failure::FailureClass::LiveElsewhere);
439        assert_eq!(f.title, "Taken over by another AgentMux instance");
440    }
441
442    // Charlie 2026-09-26: the relay said 0.57.6 on the same computer held
443    // Opaz, but Take over only looked at the local lease file and running
444    // instances, found nobody, answered `released: false` and did nothing.
445    #[test]
446    fn take_over_follows_a_relay_holder_on_this_computer() {
447        let here = crate::backend::reactive::registry::local_host_label();
448        let agent = format!("agent-{}", uuid::Uuid::new_v4());
449        crate::muxbus::wan_lease::note_not_holder(
450            &agent,
451            &serde_json::json!({ "held_by": { "host": here, "channel": "local-main-x", "version": "0.57.6" } }),
452        );
453        assert_eq!(wan_takeover_target(&agent), WanTarget::ThisComputer("local-main-x".into()));
454    }
455
456    #[test]
457    fn take_over_says_why_it_cannot_reach_another_computer() {
458        let agent = format!("agent-{}", uuid::Uuid::new_v4());
459        crate::muxbus::wan_lease::note_not_holder(&agent, &serde_json::json!({ "held_by": { "host": "desk", "channel": "stable" } }));
460        let WanTarget::OtherComputer(where_) = wan_takeover_target(&agent) else { panic!("expected another computer") };
461        let m = other_computer_error("Opaz", &where_);
462        assert!(m.contains("another computer (computer desk, channel stable)"), "{m}");
463        assert!(m.contains("Close Opaz there"), "{m}");
464        assert_eq!(wan_takeover_target("never-seen"), WanTarget::NoHolder);
465    }
466}