Skip to main content

agentmux_srv/server/account_episodes/
moves.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "Move these agents to another signed-in account"
5//! (`docs/specs/SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §6.3): `agent.account.switch`
6//! (`switch::switch_to`) for each agent of the episode, so an agent in a turn is queued.
7
8use std::collections::BTreeMap;
9
10use serde::{Deserialize, Serialize};
11
12use crate::backend::agent_state;
13use crate::backend::blockcontroller;
14use crate::backend::obj::{self, Block};
15use crate::backend::storage::identities::IdentityAccount;
16use crate::server::app_api::agent_spawn::{account_blocks, account_label_in};
17use crate::server::AppState;
18
19use super::resume::Failed;
20use super::{canonical, AccountEpisodeAgent, AccountMoveCandidate};
21
22/// `identity.account.move_agents`: move these panes' agents from one account
23/// to another of the same provider.
24#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
25#[ts(export, export_to = "../../../frontend/types/rpc/")]
26pub struct IdentityAccountMoveAgentsReq {
27    pub from: String,
28    pub to: String,
29    pub block_ids: Vec<String>,
30}
31
32/// A pane whose agent couldn't be moved, and why.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
34#[ts(export, export_to = "../../../frontend/types/rpc/")]
35pub struct AccountMoveFailure {
36    pub block_id: String,
37    pub agent_name: String,
38    pub error: String,
39}
40
41/// `identity.account.move_agents`: what moved, what was left because it is
42/// in a turn, and what failed.
43#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, ts_rs::TS)]
44#[ts(export, export_to = "../../../frontend/types/rpc/")]
45pub struct IdentityAccountMoveAgentsResult {
46    pub moved: Vec<AccountEpisodeAgent>,
47    /// In a turn (working, or waiting on a question): its move is queued and
48    /// happens when the turn ends (`agent:pending_account`).
49    pub busy: Vec<AccountEpisodeAgent>,
50    pub failed: Vec<AccountMoveFailure>,
51}
52
53pub(super) fn signed_in(status: &str) -> bool {
54    matches!(status, "valid" | "ok")
55}
56
57/// Whether a queued move may still land on the account: what the strip offered (signed in, or not
58/// checked yet), so a move it reported as queued isn't dropped when the turn ends.
59pub(super) fn can_receive(status: &str) -> bool {
60    signed_in(status) || status == "unknown"
61}
62
63/// Where `from`'s agents can go (spec §6.3): the channel's other accounts of
64/// the same canonical provider that nothing blocks (`account_blocks`: signed
65/// out, or a pane on it out of quota). Signed-in ones first, so the picker's
66/// first entry is the one to preselect (spec §13, decision 2).
67pub(super) fn candidates(state: &AppState, from: &str, provider: &str) -> Vec<AccountMoveCandidate> {
68    // Labels are numbered against every account of the provider, the source included.
69    let every: Vec<IdentityAccount> =
70        super::fresh::identity_list(state).unwrap_or_default().into_iter().filter(|a| canonical(&a.provider) == provider).collect();
71    let accounts: Vec<IdentityAccount> = every.iter().filter(|a| a.id != from).cloned().collect();
72    let blocked = account_blocks(state, &accounts);
73    let mut out: Vec<AccountMoveCandidate> = accounts
74        .iter()
75        .filter(|a| !blocked.contains_key(&a.id))
76        .map(|a| AccountMoveCandidate { account_id: a.id.clone(), label: account_label_in(a, &every), status: a.status.clone() })
77        .collect();
78    out.sort_by_key(|c| !signed_in(&c.status));
79    out
80}
81
82/// Link `agent_id` to `to` for `provider`: unlink its rows stored under an
83/// alias of the provider first (one would otherwise silently win at the next
84/// spawn), then link, then clear the failures its old account caused. Returns the panes among them whose turn
85/// failed on the login: they are told they are signed in once restarted on `to`, not here
86/// ([`super::resume::start`]).
87pub(super) fn relink(state: &AppState, agent_id: &str, to: &IdentityAccount, provider: &str) -> Result<Vec<Failed>, String> {
88    let before = super::failed_panes(&state.mstore, &state.identity_store, agent_id, provider);
89    let links = state.identity_store.agent_identity_list_for_agent(agent_id).map_err(|e| e.to_string())?;
90    // One payer: a Claude agent moved onto a key loses its plan link, and one moved onto a plan loses its key link.
91    let stored_under = super::key_account::link_provider(to, provider);
92    for l in links.iter().filter(|l| l.provider != stored_under && super::key_account::is_link_of(provider, &l.provider)) {
93        state.identity_store.agent_identity_unlink(agent_id, &l.provider).map_err(|e| e.to_string())?;
94    }
95    state.identity_store.agent_identity_link(agent_id, &to.id, stored_under).map_err(|e| e.to_string())?;
96    if !super::key_account::is_key(to) {
97        super::key_account::left_the_key(agent_id);
98    }
99    let to = to.id.as_str();
100    state.broker.publish_event_for::<crate::backend::mps_events::AgentIdentitiesChanged>(agent_id, &(), vec![], 0);
101    if let Some(watcher) = crate::backend::subagent_watcher::global() {
102        watcher.recheck_all_watched_agents();
103    }
104    Ok(super::rebind_clearing(&state.mstore, &state.event_bus, before, to, true).1)
105}
106
107/// Restart `block`'s process on the new link, keeping its conversation
108/// (`ControllerResync` with `forcerestart`). A parked block, one in no tab, restarts with no tab
109/// (an empty id, as everywhere a block is parked): its agent runs with no pane showing it.
110pub(super) fn restart(state: &AppState, block: &Block) -> Result<(), String> {
111    let tab_id = block.parentoref.strip_prefix("tab:").unwrap_or("");
112    let started = blockcontroller::resync_controller(
113        block,
114        tab_id,
115        None,
116        true,
117        true,
118        Some(state.broker.clone()),
119        Some(state.event_bus.clone()),
120        Some(state.mstore.clone()),
121        Some(state.filestore.clone()),
122        Some(state.id_store.clone()),
123        Some(state.identity_store.clone()),
124        state.mstore.shared_agent_registry(),
125        state.boot_id.clone(),
126        &state.auth_key,
127        Some(state.config_watcher.clone()),
128    );
129    // It runs now, so it is wanted running: a restart resume brings back only an agent recorded so, and
130    // a move starts an agent that was stopped (idle, or by hand) as readily as it restarts a running one.
131    if started.is_ok() {
132        crate::server::app_api::agent_attach::set_desired(&state.mstore, &block.oid, crate::server::app_api::agent_attach::DESIRED_RUNNING);
133    }
134    started
135}
136
137/// Whether the pane is in a turn: it isn't moved under it.
138pub(super) fn busy(state: &AppState, block_id: &str) -> bool {
139    agent_state::in_turn(&state.mstore, block_id)
140}
141
142/// `identity.account.move_agents`. BLOCKING (store reads, link writes, restarts).
143pub(super) fn move_agents(state: &AppState, req: &IdentityAccountMoveAgentsReq) -> Result<IdentityAccountMoveAgentsResult, String> {
144    let accounts = super::fresh::identity_list(state).map_err(|e| format!("identity.account.move_agents: accounts: {e}"))?;
145    let to = accounts.iter().find(|a| a.id == req.to).ok_or("identity.account.move_agents: no such account to move to")?;
146    if req.to == req.from {
147        return Err("identity.account.move_agents: that is the account they are on".to_string());
148    }
149    let provider = canonical(&to.provider);
150    if let Some(from) = accounts.iter().find(|a| a.id == req.from) {
151        if canonical(&from.provider) != provider {
152            return Err(format!("identity.account.move_agents: {} is a {} account; agents never move across providers", account_label_in(to, &accounts), to.provider));
153        }
154    }
155    if let Some(why) = account_blocks(state, std::slice::from_ref(to)).get(&to.id) {
156        return Err(format!("identity.account.move_agents: {} {why}", account_label_in(to, &accounts)));
157    }
158
159    let mut result = IdentityAccountMoveAgentsResult::default();
160    let mut by_agent: BTreeMap<String, Vec<Block>> = BTreeMap::new();
161    let mut seen = std::collections::HashSet::new();
162    for block_id in req.block_ids.iter().filter(|b| seen.insert(b.as_str())) {
163        let block = state.mstore.get::<Block>(block_id).ok().flatten();
164        let agent_id = block.as_ref().map(|b| obj::meta_get_string(&b.meta, "agentId", "")).unwrap_or_default();
165        match block {
166            Some(b) if !agent_id.is_empty() => by_agent.entry(agent_id).or_default().push(b),
167            _ => result.failed.push(AccountMoveFailure {
168                block_id: block_id.clone(),
169                agent_name: String::new(),
170                error: "not an open agent pane".to_string(),
171            }),
172        }
173    }
174
175    let same_provider: Vec<IdentityAccount> = accounts.iter().filter(|a| canonical(&a.provider) == provider).cloned().collect();
176    let open = super::tab_blocks(&state.mstore);
177    for (agent_id, asked) in by_agent {
178        // The link is the agent's, for every pane of it, not only the ones asked for.
179        let mut blocks: Vec<Block> = open.iter().filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == agent_id).cloned().collect();
180        for b in asked {
181            if !blocks.iter().any(|o| o.oid == b.oid) {
182                blocks.push(b);
183            }
184        }
185        let agents: Vec<AccountEpisodeAgent> = blocks
186            .iter()
187            .map(|b| AccountEpisodeAgent { block_id: b.oid.clone(), agent_id: agent_id.clone(), agent_name: super::agent_name(&state.mstore, b) })
188            .collect();
189        // The one door the composer and agents use: an agent in a turn is queued, not left.
190        match super::switch::switch_to(state, "operator", &agent_id, to, &provider, &same_provider, super::switch::AccountSwitchWhen::AfterTurn) {
191            Ok(r) if matches!(r.status, super::switch::AccountSwitchStatus::Queued | super::switch::AccountSwitchStatus::Preparing) => result.busy.extend(agents),
192            Ok(r) if r.failed.is_empty() => result.moved.extend(agents),
193            // Linked, but some panes didn't restart. The failures don't say which pane, and the
194            // strip names the agent, so the counts are what matters: one failure per pane that
195            // didn't restart, the rest moved.
196            Ok(r) => {
197                let mut panes = agents.into_iter();
198                for error in &r.failed {
199                    if let Some(a) = panes.next() {
200                        result.failed.push(AccountMoveFailure { block_id: a.block_id, agent_name: a.agent_name, error: error.clone() });
201                    }
202                }
203                result.moved.extend(panes);
204            }
205            Err(error) => {
206                let error = error.to_string();
207                result.failed.extend(agents.into_iter().map(|a| AccountMoveFailure { block_id: a.block_id, agent_name: a.agent_name, error: error.clone() }))
208            }
209        }
210    }
211    tracing::info!(
212        provider = %provider,
213        moved = result.moved.len(),
214        busy = result.busy.len(),
215        failed = result.failed.len(),
216        "identity.account.move_agents: moved an episode's agents to another account"
217    );
218    if !result.moved.is_empty() {
219        crate::backend::reactive::held_jekt_wake().notify_one();
220    }
221    Ok(result)
222}