Skip to main content

agentmux_srv/server/account_episodes/
failover.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Automatic failover (`docs/specs/SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md` ยง4.4, D4):
5//! an agent whose pane hit a usage limit moves itself to another signed-in account of its
6//! provider that has quota, once its turn is over, and says so in one note to the agent and one
7//! to its lead.
8//!
9//! It is `agent.account.switch` (`switch::switch_to`, `after_turn`) chosen by srv, so the move
10//! relinks, clears the old account's limit and restarts the pane the way every other switch does.
11//! It never picks:
12//! - an account the operator marked "never fail over to this" (`context.never_failover`);
13//! - an account that is not signed in (`valid`/`ok`; an unchecked one is not trusted with an
14//!   unattended move), or one a pane of another agent has just found out of quota;
15//! - an account of another provider.
16//!
17//! `agent:accountfailover` (default on; `false` turns it all off) is the one setting.
18
19use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use crate::backend::agent_state::AgentState;
24use crate::backend::obj::Block;
25use crate::backend::storage::identities::IdentityAccount;
26use crate::server::AppState;
27
28use super::accounts::pick;
29use super::machine::BlockedPane;
30use super::moves::signed_in;
31use super::switch::{open_panes, AccountSwitchWhen, META_PENDING_ACCOUNT};
32use super::{agent_name, canonical};
33
34/// `agent:accountfailover`: move an agent that hit its limit to an account with quota. On unless `false`.
35pub const SETTING: &str = "agent:accountfailover";
36/// Who the audit row names, and what tells [`notify`] a switch was a failover.
37pub(super) const ACTOR: &str = "failover";
38/// The same for the move off a login that expired (`login_expiry`).
39pub(super) const ACTOR_EXPIRED: &str = "failover:expired";
40
41/// Whether `actor` is one of the failovers (their moves are told to the agent and its lead).
42pub(super) fn is_actor(actor: &str) -> bool {
43    actor == ACTOR || actor == ACTOR_EXPIRED
44}
45/// The account's mark (in `context`): never move an agent onto it by itself.
46pub use crate::backend::storage::identities::NEVER_FAILOVER;
47
48/// Whether the operator marked `a` "never fail over to this".
49pub fn is_never(a: &IdentityAccount) -> bool {
50    a.context.get(NEVER_FAILOVER).and_then(|v| v.as_bool()).unwrap_or(false)
51}
52
53/// `identity.account.set_failover`.
54#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
55#[ts(export, export_to = "../../../frontend/types/rpc/")]
56pub struct IdentityAccountSetFailoverReq {
57    pub account_id: String,
58    /// `false` marks the account "never fail over to this"; `true` takes the mark off.
59    pub allow: bool,
60}
61
62/// `identity.account.set_failover`: how the account stands now.
63#[derive(Debug, Clone, Serialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct IdentityAccountSetFailoverResult {
66    pub account_id: String,
67    pub allow: bool,
68}
69
70/// `identity.account.set_failover`. BLOCKING (a store write).
71pub(super) fn set_failover(state: &AppState, req: &IdentityAccountSetFailoverReq) -> Result<IdentityAccountSetFailoverResult, String> {
72    let found = state.id_store.identity_set_never_failover(&req.account_id, !req.allow).map_err(|e| format!("identity.account.set_failover: {e}"))?;
73    if !found {
74        return Err(format!("identity.account.set_failover: no account {:?}", req.account_id));
75    }
76    super::refresh_soon();
77    Ok(IdentityAccountSetFailoverResult { account_id: req.account_id.clone(), allow: req.allow })
78}
79
80/// Accounts an agent was moved off after a limit, and when that limit lifts (unix ms): the
81/// move clears the stored failure, so without this the next failover could send the agent
82/// straight back to an account no pane has re-tested yet.
83static LEFT: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, u64>>> = std::sync::LazyLock::new(Default::default);
84/// How long to avoid an account left over a limit with no known reset.
85const UNKNOWN_RESET_MS: u64 = 60 * 60_000;
86
87fn remember_left(pane: &BlockedPane, now_ms: u64) {
88    let until = pane.resets_at_ms.unwrap_or(now_ms + UNKNOWN_RESET_MS);
89    LEFT.lock().unwrap_or_else(|e| e.into_inner()).insert(pane.account_id.clone(), until);
90}
91
92pub(super) fn recently_left(account_id: &str, now_ms: u64) -> bool {
93    let mut left = LEFT.lock().unwrap_or_else(|e| e.into_inner());
94    left.retain(|_, until| *until > now_ms);
95    left.contains_key(account_id)
96}
97
98pub(super) fn enabled(state: &AppState) -> bool {
99    state.config_watcher.extra_bool(SETTING).unwrap_or(true)
100}
101
102/// The account `pane`'s agent moves to: one of its provider's other accounts that is signed in,
103/// has quota, isn't marked and wasn't just left over its own limit, else why not.
104fn target<'a>(state: &AppState, accounts: &'a [IdentityAccount], pane: &BlockedPane, now_ms: u64) -> Result<&'a IdentityAccount, String> {
105    let usable: Vec<IdentityAccount> =
106        accounts.iter().filter(|a| canonical(&a.provider) == pane.provider && signed_in(&a.status) && !is_never(a) && !recently_left(&a.id, now_ms)).cloned().collect();
107    let chosen = pick(state, &usable, "any with quota", std::slice::from_ref(&pane.account_id), &pane.provider)?;
108    accounts.iter().find(|a| a.id == chosen.id).ok_or_else(|| "the account is gone".to_string())
109}
110
111/// Move each agent with a pane out of quota (a usage limit, not a refused sign-in) to an account
112/// that can run. `panes` are the blocked panes of this refresh. An agent with a move already
113/// queued is left to it. BLOCKING (store reads, link writes, restarts).
114pub(super) fn run(state: &AppState, panes: &[BlockedPane]) {
115    if !enabled(state) {
116        return;
117    }
118    let mut by_agent: BTreeMap<&str, &BlockedPane> = BTreeMap::new();
119    for pane in panes.iter().filter(|p| p.state == AgentState::Limited && !p.agent_id.is_empty()) {
120        by_agent.entry(pane.agent_id.as_str()).or_insert(pane);
121    }
122    if by_agent.is_empty() {
123        return;
124    }
125    let accounts = super::fresh::identity_list(state).unwrap_or_default();
126    for (def_id, pane) in by_agent {
127        if open_panes(state, def_id).iter().any(|b| b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| v.is_string())) {
128            continue;
129        }
130        let now_ms = agentmux_common::time::now_ms_u64();
131        let to = match target(state, &accounts, pane, now_ms) {
132            Ok(to) => to,
133            Err(why) => {
134                tracing::debug!(agent = %pane.agent_name, "account failover: no account to move to: {why}");
135                continue;
136            }
137        };
138        let same_provider: Vec<IdentityAccount> = accounts.iter().filter(|a| canonical(&a.provider) == pane.provider).cloned().collect();
139        match super::switch::switch_to(state, ACTOR, def_id, to, &pane.provider, &same_provider, AccountSwitchWhen::AfterTurn) {
140            Ok(_) => remember_left(pane, now_ms),
141            Err(e) => tracing::warn!(agent = %pane.agent_name, error = %e, "account failover: the move failed"),
142        }
143    }
144}
145
146/// The one-line notes for a failover that landed: to the agent's panes, and to its lead's first
147/// open pane. Held for each one's next turn: neither is woken for it, and the agent's pane is not
148/// asked to run before its account is in place. `expired` says the login ended, not the quota;
149/// the panes in `woken` get their own note that starts a turn (`login_expiry`), so not this one.
150pub(super) fn notify(state: &AppState, def_id: &str, to_label: &str, blocks: &[Block], expired: bool, woken: &[String]) {
151    let Some(first) = blocks.first() else { return };
152    let name = agent_name(&state.mstore, first);
153    let to = crate::backend::reactive::sanitize::quote_in_system_note(to_label);
154    let key = format!("failover:{def_id}");
155    let why = if expired { "Your login expired" } else { "Your account hit its usage limit" };
156    let own = format!("[AgentMux] {why}, so AgentMux moved you to {to}. Your conversation goes on there.");
157    for block in blocks.iter().filter(|b| !woken.contains(&b.oid)) {
158        crate::backend::blockcontroller::system_note_into_turn_or_hold(&block.oid, &key, &own);
159    }
160    let Some(lead) = crate::server::app_api::agent_spawn::worker_of(&state.mstore, def_id) else { return };
161    let Some(lead_pane) = open_panes(state, &lead).into_iter().next() else { return };
162    let who = crate::backend::reactive::sanitize::quote_in_system_note(&name);
163    let text = if expired {
164        format!("[AgentMux] {who}'s login expired, so AgentMux moved it to {to}.")
165    } else {
166        format!("[AgentMux] {who} hit its usage limit, so AgentMux moved it to {to}.")
167    };
168    crate::backend::blockcontroller::system_note_into_turn_or_hold(&lead_pane.oid, &key, &text);
169}