1use serde::{Deserialize, Serialize};
14
15use crate::backend::agent_resolve::resolve_agent_id;
16use crate::backend::blockcontroller;
17use crate::backend::obj::{self, Block};
18use crate::backend::storage::identities::{IdentityAccount, SecretRef};
19use crate::server::app_api::agent_spawn::account_label_in;
20use crate::server::AppState;
21
22use super::accounts::pick;
23use super::key_account::{can_take_a_key, is_key, is_link_of, serves};
24use super::switch_error::{SwitchError, SwitchRefusal};
25use super::moves::{busy, can_receive, relink, restart, signed_in};
26use super::{agent_name, canonical, tab_blocks};
27
28pub const META_PENDING_ACCOUNT: &str = "agent:pending_account";
32const META_PENDING_BY: &str = "agent:pending_account_by";
34
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, ts_rs::TS)]
36#[serde(rename_all = "snake_case")]
37#[ts(export, export_to = "../../../frontend/types/rpc/")]
38pub enum AccountSwitchWhen {
39 Now,
41 #[default]
43 AfterTurn,
44}
45
46#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
48#[ts(export, export_to = "../../../frontend/types/rpc/")]
49pub struct AgentAccountSwitchReq {
50 #[serde(default)]
52 pub agent_id: Option<String>,
53 pub account: String,
57 #[serde(default)]
58 pub when: AccountSwitchWhen,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
63#[serde(rename_all = "snake_case")]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub enum AccountSwitchStatus {
66 Switched,
68 Queued,
70 Preparing,
73 Unchanged,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
78#[ts(export, export_to = "../../../frontend/types/rpc/")]
79pub struct AgentAccountSwitchResult {
80 pub status: AccountSwitchStatus,
81 pub account_id: String,
82 pub account_label: String,
83 pub restarted: u32,
85 pub failed: Vec<String>,
87}
88
89pub(super) fn open_panes(state: &AppState, def_id: &str) -> Vec<Block> {
90 tab_blocks(&state.mstore).into_iter().filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == def_id).collect()
91}
92
93fn set_pending(state: &AppState, blocks: &[Block], pending: Option<(&str, &str)>) {
94 let ids: Vec<&str> =
96 blocks.iter().filter(|b| pending.is_some() || b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| !v.is_null())).map(|b| b.oid.as_str()).collect();
97 let null = serde_json::Value::Null;
98 let updates = [
99 (META_PENDING_ACCOUNT, pending.map_or(null.clone(), |(a, _)| serde_json::json!(a))),
100 (META_PENDING_BY, pending.map_or(null, |(_, by)| serde_json::json!(by))),
101 ];
102 crate::server::prep::set_block_meta(state, &ids, &updates);
103}
104
105fn refresh_auth_env(state: &AppState, block: &Block, to: &IdentityAccount, provider: &str) {
108 let SecretRef::OAuthConfigDir { dir } = &to.secret_ref else { return };
109 let Some(var) = crate::backend::providers::get_provider(provider).map(|p| p.auth_config_dir_env_var).filter(|v| !v.is_empty()) else { return };
110 let mut env = blockcontroller::cmd_env_of(&block.meta);
111 env.insert(var.to_string(), dir.clone());
112 let mut update = obj::MetaMapType::new();
113 update.insert("cmd:env".to_string(), serde_json::json!(env));
114 match crate::server::service::update_object_meta(&state.mstore, &format!("block:{}", block.oid), &update) {
115 Ok(()) => blockcontroller::core::broadcast_block_update(&state.mstore, &state.event_bus, &block.oid),
116 Err(e) => tracing::warn!(block_id = %block.oid, error = %e, "agent.account.switch: the pane's auth env was not updated"),
117 }
118}
119
120fn stop_turn(block: &Block) {
123 if let Some(ctrl) = blockcontroller::take_controller(&block.oid) {
124 let _ = crate::sagas::agent_teardown::replace_now(ctrl.as_ref());
125 }
126}
127
128fn apply(state: &AppState, actor: &str, def_id: &str, to: &IdentityAccount, provider: &str, blocks: &[Block], all: &[IdentityAccount], now: bool) -> AgentAccountSwitchResult {
131 set_pending(state, blocks, None);
132 let interrupted = if actor == super::failover::ACTOR_EXPIRED { super::login_expiry::interrupted(blocks) } else { Vec::new() };
134 let label = account_label_in(to, all);
135 let mut result = AgentAccountSwitchResult { status: AccountSwitchStatus::Switched, account_id: to.id.clone(), account_label: label.clone(), restarted: 0, failed: Vec::new() };
136 let linked = relink(state, def_id, to, provider);
137 let signed_out = linked.clone().unwrap_or_default();
138 let mut restarted_ok: Vec<&str> = Vec::new();
139 let request_id = uuid::Uuid::new_v4().to_string();
140 let reason = format!("switched to {label}");
141 for block in blocks {
142 let outcome = linked.clone().and_then(|_| {
143 refresh_auth_env(state, block, to, provider);
144 if now && busy(state, &block.oid) {
145 stop_turn(block);
146 }
147 restart(state, block).map_err(|e| format!("linked, but its pane didn't restart ({e}); it uses the new account when it next starts"))
148 });
149 state.reactive_handler.log_fleet_action_audit(
150 Some(actor),
151 &agent_name(&state.mstore, block),
152 &block.oid,
153 "agent.account.switch",
154 outcome.is_ok(),
155 outcome.as_ref().err().map(String::as_str),
156 &request_id,
157 Some(&reason),
158 );
159 match outcome {
160 Ok(()) => {
161 result.restarted += 1;
162 restarted_ok.push(&block.oid);
163 }
164 Err(e) => result.failed.push(e),
165 }
166 }
167 tell_signed_out(actor, signed_out, &restarted_ok);
168 crate::server::prep::hold_for_other_panes(def_id, &restarted_ok);
170 if blocks.is_empty() {
171 if let Err(e) = linked {
172 result.failed.push(e);
173 }
174 }
175 if super::failover::is_actor(actor) && result.restarted > 0 {
176 super::failover::notify(state, def_id, &label, blocks, actor == super::failover::ACTOR_EXPIRED, &interrupted);
177 super::login_expiry::resume(&interrupted, &label);
178 }
179 tracing::info!(agent = %actor, def_id = %def_id, restarted = result.restarted, failed = result.failed.len(), "agent.account.switch: switched an agent's account");
180 super::refresh_soon();
181 result
182}
183
184fn tell_signed_out(actor: &str, signed_out: Vec<super::resume::Failed>, restarted: &[&str]) {
190 super::resume::start(panes_to_tell(actor, signed_out, restarted), agentmux_common::time::now_ms());
191}
192
193pub(super) fn panes_to_tell(actor: &str, signed_out: Vec<super::resume::Failed>, restarted: &[&str]) -> Vec<super::resume::Failed> {
195 if actor == super::failover::ACTOR_EXPIRED {
196 return Vec::new();
197 }
198 signed_out.into_iter().filter(|f| restarted.contains(&f.block_id.as_str())).collect()
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
203#[ts(export, export_to = "../../../frontend/types/rpc/")]
204pub struct AccountSwitchAllEntry {
205 pub agent_id: String,
206 pub agent_name: String,
207 #[serde(skip_serializing_if = "Option::is_none")]
208 #[ts(optional)]
209 pub result: Option<AgentAccountSwitchResult>,
210 #[serde(skip_serializing_if = "Option::is_none")]
211 #[ts(optional)]
212 pub error: Option<String>,
213}
214
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
217#[ts(export, export_to = "../../../frontend/types/rpc/")]
218pub struct AccountSwitchAllResult {
219 pub agents: Vec<AccountSwitchAllEntry>,
220}
221
222pub fn is_all_limited(agent: &str) -> bool {
224 agent.trim().to_lowercase().replace(['_', '-'], " ") == "all limited"
225}
226
227pub(super) fn switch_all_limited(state: &AppState, caller: &str, req: &AgentAccountSwitchReq) -> Result<AccountSwitchAllResult, String> {
231 let now = agentmux_common::time::now_ms_u64();
232 let mut limited: Vec<(String, String)> = Vec::new();
233 for pane in super::scan(state, now).into_iter().filter(|p| p.state == crate::backend::agent_state::AgentState::Limited) {
234 if !pane.agent_id.is_empty() && !limited.iter().any(|(id, _)| *id == pane.agent_id) {
235 limited.push((pane.agent_id, pane.agent_name));
236 }
237 }
238 let mut agents = Vec::new();
239 for (agent_id, agent_name) in limited {
240 let one = AgentAccountSwitchReq { agent_id: Some(agent_id.clone()), account: req.account.clone(), when: req.when };
241 let (result, error) = match switch(state, caller, &one) {
242 Ok(r) => (Some(r), None),
243 Err(e) => (None, Some(e.to_string())),
244 };
245 agents.push(AccountSwitchAllEntry { agent_id, agent_name, result, error });
246 }
247 Ok(AccountSwitchAllResult { agents })
248}
249
250fn resolve_named(store: &crate::backend::storage::store::Store, named: &str) -> Result<String, SwitchError> {
253 let err = match resolve_agent_id(store, named) {
254 Ok(id) => return Ok(id),
255 Err(e) => e,
256 };
257 let defs = store.agent_def_list().map_err(|e| e.to_string())?;
258 let mut by_name = defs.iter().filter(|d| d.name.trim().eq_ignore_ascii_case(named));
259 match (by_name.next(), by_name.next()) {
260 (Some(d), None) => Ok(d.id.clone()),
261 (Some(_), Some(_)) => Err(SwitchError::new(SwitchRefusal::AgentNameShared, format!("more than one agent is named '{named}'; use its agent_id"))),
262 _ if err.starts_with("resolve_agent_id: store:") => Err(SwitchError::from(err)),
264 _ => Err(SwitchError::new(SwitchRefusal::UnknownAgent, err)),
265 }
266}
267
268fn actor_named(caller: &str) -> String {
271 if caller.is_empty() { "operator".to_string() } else { crate::backend::rpc::actor::Actor::Agent(caller.to_string()).label() }
272}
273
274
275pub(super) fn switch(state: &AppState, caller: &str, req: &AgentAccountSwitchReq) -> Result<AgentAccountSwitchResult, SwitchError> {
278 let named = req.agent_id.as_deref().map(str::trim).filter(|a| !a.is_empty()).unwrap_or(caller);
279 if named.is_empty() {
280 return Err(SwitchError::new(SwitchRefusal::NoAgentNamed, "agent.account.switch: say which agent"));
281 }
282 let def_id = resolve_named(&state.mstore, named).map_err(|e| e.under("agent.account.switch"))?;
283 let provider = agent_provider(state, &def_id).ok_or_else(|| SwitchError::new(SwitchRefusal::UnknownAgent, "agent.account.switch: no such agent"))?;
284 let accounts: Vec<IdentityAccount> = super::fresh::identity_list(state)
285 .map_err(|e| format!("agent.account.switch: accounts: {e}"))?
286 .into_iter()
287 .filter(|a| serves(&provider, a))
288 .collect();
289 let on: Vec<String> = state
291 .identity_store
292 .agent_identity_list_for_agent(&def_id)
293 .map_err(|e| format!("agent.account.switch: {e}"))?
294 .into_iter()
295 .filter(|l| is_link_of(&provider, &l.provider))
296 .map(|l| l.account_id)
297 .collect();
298 let to = pick(state, &accounts, req.account.trim(), &on, &provider)?;
299 if is_key(to) {
300 can_take_a_key(state, &def_id).map_err(|e| SwitchError::new(SwitchRefusal::CantRun, e))?;
301 }
302 if !(signed_in(&to.status) || (is_key(to) && can_receive(&to.status))) {
303 let why = match to.status.as_str() {
304 _ if is_key(to) => "its key was rejected; replace it in Connectors > Accounts",
305 "expired" => "its access token has lapsed and AgentMux cannot tell that it will renew; sign in to it again",
306 _ => "it is not signed in; sign in to it first",
307 };
308 return Err(SwitchError::new(SwitchRefusal::CantRun, format!("ACCOUNT_CANT_RUN: {}: {why}", account_label_in(to, &accounts))));
309 }
310 let actor = actor_named(caller);
311 switch_to(state, &actor, &def_id, to, &provider, &accounts, req.when)
312}
313
314pub(super) fn switch_to(state: &AppState, actor: &str, def_id: &str, to: &IdentityAccount, provider: &str, accounts: &[IdentityAccount], when: AccountSwitchWhen) -> Result<AgentAccountSwitchResult, SwitchError> {
318 if is_key(to) && provider != "claude" {
319 return Err(SwitchError::new(SwitchRefusal::KeyNotForThisAgent, "agent.account.switch: an API key is chosen from a Claude agent's own account menu"));
320 }
321 let blocks = open_panes(state, def_id);
322 let links: Vec<String> = state
326 .identity_store
327 .agent_identity_list_for_agent(def_id)
328 .map_err(|e| format!("agent.account.switch: {e}"))?
329 .into_iter()
330 .filter(|l| is_link_of(provider, &l.provider))
331 .map(|l| l.account_id)
332 .collect();
333 let label = account_label_in(to, accounts);
334 let result = |status| AgentAccountSwitchResult { status, account_id: to.id.clone(), account_label: label.clone(), restarted: 0, failed: Vec::new() };
335 if !links.is_empty() && links.iter().all(|a| *a == to.id) {
336 set_pending(state, &blocks, None);
337 crate::server::prep::cancel(state, def_id);
339 return Ok(result(AccountSwitchStatus::Unchanged));
340 }
341 if is_asked(state, actor, def_id, &blocks, to, &label, when) {
342 let prep = prep_of(state, actor, def_id, &blocks, to, &label, when);
343 let (s, actor_c, def, to_id) = (state.clone(), actor.to_string(), def_id.to_string(), to.id.clone());
344 let now = when == AccountSwitchWhen::Now;
345 crate::server::prep::open_with(state, prep, Box::new(move |how| settle(&s, &actor_c, &def, &to_id, now || how == crate::server::prep::How::PersonSaidNow)), || {
350 set_pending(state, &blocks, Some((&to.id, actor)));
351 });
352 return Ok(result(AccountSwitchStatus::Preparing));
353 }
354 if when == AccountSwitchWhen::AfterTurn && blocks.iter().any(|b| busy(state, &b.oid)) {
355 set_pending(state, &blocks, Some((&to.id, actor)));
356 return Ok(result(AccountSwitchStatus::Queued));
357 }
358 Ok(apply(state, actor, def_id, to, provider, &blocks, accounts, when == AccountSwitchWhen::Now))
359}
360
361fn is_asked(state: &AppState, actor: &str, def_id: &str, blocks: &[Block], to: &IdentityAccount, label: &str, when: AccountSwitchWhen) -> bool {
365 if super::failover::is_actor(actor) || blocks.is_empty() {
366 return false;
367 }
368 crate::server::prep::is_open(def_id) || crate::server::prep::decide(state, &prep_of(state, actor, def_id, blocks, to, label, when)) == crate::server::prep::Decision::Ask
369}
370
371fn prep_of(state: &AppState, actor: &str, def_id: &str, blocks: &[Block], to: &IdentityAccount, label: &str, when: AccountSwitchWhen) -> crate::server::prep::Prep {
372 crate::server::prep::Prep {
373 def_id: def_id.to_string(),
374 agent_name: blocks.first().map(|b| agent_name(&state.mstore, b)).unwrap_or_default(),
375 blocks: blocks.iter().map(|b| b.oid.clone()).collect(),
376 action: "account_switch",
377 target: to.id.clone(),
378 what: format!("move you to the account {label}"),
379 actor: actor.to_string(),
380 cuts_turn: when == AccountSwitchWhen::Now,
381 }
382}
383
384fn settle(state: &AppState, actor: &str, def_id: &str, account_id: &str, now: bool) {
388 let blocks = open_panes(state, def_id);
389 let Some((to, provider, accounts)) = receiving(state, def_id, account_id) else {
391 tracing::info!(def_id = %def_id, "agent.account.switch: a prepared switch was dropped, its account is gone or signed out");
392 set_pending(state, &blocks, None);
393 return;
394 };
395 if !now && blocks.iter().any(|b| busy(state, &b.oid)) {
396 set_pending(state, &blocks, Some((&to.id, actor)));
398 return;
399 }
400 apply(state, actor, def_id, &to, &provider, &blocks, &accounts, now);
401}
402
403pub(super) fn receiving(state: &AppState, def_id: &str, account_id: &str) -> Option<(IdentityAccount, String, Vec<IdentityAccount>)> {
405 let provider = agent_provider(state, def_id)?;
406 let all: Vec<IdentityAccount> = super::fresh::identity_list(state).unwrap_or_default();
407 let to = all.iter().find(|a| a.id == account_id && can_receive(&a.status) && serves(&provider, a))?.clone();
408 if super::key_account::is_key(&to) && super::key_account::can_take_a_key(state, def_id).is_err() {
410 return None;
411 }
412 let same_provider = all.into_iter().filter(|a| serves(&provider, a)).collect();
413 Some((to, provider, same_provider))
414}
415
416fn agent_provider(state: &AppState, def_id: &str) -> Option<String> {
418 let defs = state.mstore.agent_def_list().ok()?;
419 defs.into_iter().find(|d| d.id == def_id).map(|d| canonical(&state.mstore.resolve_effective_provider_id(&d)))
420}
421
422fn clear_stale_prep(state: &AppState) {
425 for pane in tab_blocks(&state.mstore).iter().filter(|b| b.meta.get(crate::server::prep::META_PREP).is_some_and(|v| !v.is_null())) {
426 if !crate::server::prep::is_open(&obj::meta_get_string(&pane.meta, "agentId", "")) {
427 crate::server::prep::set_block_meta(state, &[pane.oid.as_str()], &[(crate::server::prep::META_PREP, serde_json::Value::Null)]);
428 }
429 }
430}
431
432pub(super) fn apply_pending(state: &AppState) {
435 clear_stale_prep(state);
436 let panes: Vec<Block> = tab_blocks(&state.mstore).into_iter().filter(|b| b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| v.is_string())).collect();
437 let mut done = std::collections::HashSet::new();
438 for first in &panes {
439 let def_id = obj::meta_get_string(&first.meta, "agentId", "");
440 let account_id = obj::meta_get_string(&first.meta, META_PENDING_ACCOUNT, "");
441 let by = obj::meta_get_string(&first.meta, META_PENDING_BY, "operator");
442 if def_id.is_empty() || crate::server::prep::is_open(&def_id) || !done.insert(def_id.clone()) {
444 continue;
445 }
446 let blocks = open_panes(state, &def_id);
447 if blocks.iter().any(|b| busy(state, &b.oid)) {
448 continue;
449 }
450 let Some((to, provider, accounts)) = receiving(state, &def_id, &account_id) else {
451 tracing::info!(def_id = %def_id, "agent.account.switch: a queued switch was dropped, its account is gone or signed out");
452 set_pending(state, &blocks, None);
453 continue;
454 };
455 apply(state, &by, &def_id, &to, &provider, &blocks, &accounts, false);
456 }
457}
458
459#[cfg(test)]
460mod actor_tests {
461 use super::actor_named;
462
463 #[test]
464 fn an_agent_is_named_with_its_prefix_whatever_it_is_called() {
465 assert_eq!(actor_named(""), "operator");
466 assert_eq!(actor_named("wren"), "agent:wren");
467 assert_eq!(actor_named("operator"), "agent:operator");
468 assert_eq!(actor_named("failover"), "agent:failover");
469 assert_ne!(actor_named("operator"), actor_named(""));
470 }
471}