Skip to main content

agentmux_srv/server/account_episodes/
accounts.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `identity.accounts`: the signed-in accounts on this machine as an agent sees
5//! them, and how `identity.switch` names one
6//! (`docs/specs/SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md` §4.3, §4.4).
7//!
8//! The same view answers a local call and, later, a remote one, so it holds
9//! only what a person reads off the Connectors page: the stable id, provider,
10//! email, label, whether it is signed in, whether it has quota and when that
11//! returns, and which agents run on it. Never a credential, a secret reference
12//! or a config directory.
13
14use std::collections::HashMap;
15
16use serde::Serialize;
17
18use crate::backend::account_usage::AccountUsage;
19use crate::backend::agent_state::AgentState;
20use crate::backend::storage::identities::IdentityAccount;
21use crate::identity::stable_account::stable_account_id;
22use crate::server::app_api::agent_spawn::{account_blocks, account_label_in};
23use crate::server::AppState;
24
25use super::moves::{can_receive, signed_in};
26use super::{canonical, scan, SwitchError, SwitchRefusal};
27
28/// An agent that runs on an account.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
30#[ts(export, export_to = "../../../frontend/types/rpc/")]
31pub struct AccountAgent {
32    pub agent_id: String,
33    pub name: String,
34}
35
36/// Whether an account can take work now.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, ts_rs::TS)]
38#[ts(export, export_to = "../../../frontend/types/rpc/")]
39pub struct AccountQuota {
40    #[ts(type = r#""ok" | "limited" | "signed_out""#)]
41    pub state: String,
42    /// When the last of its limits lifts (unix ms), when known.
43    #[ts(type = "number | null")]
44    pub resets_at_ms: Option<u64>,
45    /// The provider's name for that limit's window (`five_hour`, `seven_day`, …).
46    pub limit_window: Option<String>,
47}
48
49impl AccountQuota {
50    fn of(state: &str) -> Self {
51        AccountQuota { state: state.to_string(), resets_at_ms: None, limit_window: None }
52    }
53}
54
55/// One account, as `identity.accounts` lists it.
56#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
57#[ts(export, export_to = "../../../frontend/types/rpc/")]
58pub struct AccountView {
59    /// The id every machine agrees on (`identity::stable_account`); absent for an
60    /// account with neither provider ids nor an email.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    #[ts(optional)]
63    pub stable_id: Option<String>,
64    /// This machine's id for it, which `identity.switch` also takes.
65    pub account_id: String,
66    pub provider: String,
67    pub email: String,
68    /// What the pane shows: the name or email, numbered (`email ·2`) when several share it.
69    pub label: String,
70    /// `valid`, `ok`, `unknown`, `expired`, `needs_reauth` or `invalid`.
71    pub sign_in: String,
72    pub quota: AccountQuota,
73    /// How much of each usage window is used and when it resets, from the provider's own report
74    /// (`backend::account_usage`); `not_reported` for a provider whose CLI reports none.
75    pub usage: AccountUsage,
76    /// Marked "never fail over to this": no agent is moved onto it by itself (`failover`).
77    pub never_failover: bool,
78    pub agents: Vec<AccountAgent>,
79}
80
81/// `identity.accounts`.
82#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
83#[ts(export, export_to = "../../../frontend/types/rpc/")]
84pub struct IdentityAccountsResult {
85    pub accounts: Vec<AccountView>,
86}
87
88/// The quota of each account that a pane's stored failure puts out of work now,
89/// by local account id. An account missing from the map has quota as far as
90/// this machine knows: it learns of a limit when a pane hits it.
91fn quotas(state: &AppState, now_ms: u64) -> HashMap<String, AccountQuota> {
92    let mut out: HashMap<String, AccountQuota> = HashMap::new();
93    for pane in scan(state, now_ms) {
94        let entry = out.entry(pane.account_id.clone()).or_insert_with(|| AccountQuota::of("limited"));
95        if pane.state != AgentState::Limited {
96            // Signed out wins over limited, as it does in an episode.
97            *entry = AccountQuota::of("signed_out");
98        } else if entry.state == "limited" && (entry.resets_at_ms.is_none() || pane.resets_at_ms > entry.resets_at_ms) {
99            entry.resets_at_ms = pane.resets_at_ms;
100            entry.limit_window = pane.limit_window.clone();
101        }
102    }
103    out
104}
105
106fn email_of(a: &IdentityAccount) -> String {
107    a.context.get("email").and_then(|e| e.as_str()).unwrap_or("").trim().to_string()
108}
109
110/// Every account of an agent provider on this machine. BLOCKING (store reads).
111pub(super) fn accounts(state: &AppState, now_ms: u64) -> Result<IdentityAccountsResult, String> {
112    let all: Vec<IdentityAccount> = super::fresh::identity_list(state).map_err(|e| format!("identity.accounts: {e}"))?;
113    let quotas = quotas(state, now_ms);
114    let names: HashMap<String, String> =
115        state.mstore.agent_def_list().map_err(|e| format!("identity.accounts: {e}"))?.into_iter().map(|d| (d.id, d.name)).collect();
116    let mut users: HashMap<String, Vec<AccountAgent>> = HashMap::new();
117    for link in state.identity_store.agent_identity_list_all().map_err(|e| format!("identity.accounts: {e}"))? {
118        let Some(name) = names.get(&link.agent_id) else { continue };
119        let agents = users.entry(link.account_id).or_default();
120        if !agents.iter().any(|a| a.agent_id == link.agent_id) {
121            agents.push(AccountAgent { agent_id: link.agent_id, name: name.clone() });
122        }
123    }
124    let mut out = Vec::new();
125    for a in all.iter().filter(|a| crate::backend::providers::get_provider(&canonical(&a.provider)).is_some()) {
126        let provider = canonical(&a.provider);
127        let same_provider: Vec<IdentityAccount> = all.iter().filter(|o| canonical(&o.provider) == provider).cloned().collect();
128        let mut agents = users.remove(&a.id).unwrap_or_default();
129        agents.sort_by(|x, y| x.name.cmp(&y.name));
130        let quota = match quotas.get(&a.id) {
131            Some(q) => q.clone(),
132            None if matches!(a.status.as_str(), "expired" | "needs_reauth" | "invalid") => AccountQuota::of("signed_out"),
133            None => AccountQuota::of("ok"),
134        };
135        let usage = AccountUsage::of(&provider, &a.id, now_ms);
136        out.push(AccountView {
137            stable_id: stable_account_id(a),
138            account_id: a.id.clone(),
139            provider,
140            email: email_of(a),
141            label: account_label_in(a, &same_provider),
142            sign_in: a.status.clone(),
143            quota,
144            usage,
145            never_failover: super::failover::is_never(a),
146            agents,
147        });
148    }
149    out.sort_by(|x, y| (&x.provider, &x.label, &x.account_id).cmp(&(&y.provider, &y.label, &y.account_id)));
150    Ok(IdentityAccountsResult { accounts: out })
151}
152
153/// Whether an account can take an agent now: signed in (or not checked yet) and
154/// not blocked by a pane's limit or refused sign-in.
155fn has_quota(a: &IdentityAccount, blocked: &HashMap<String, String>) -> bool {
156    can_receive(&a.status) && !blocked.contains_key(&a.id)
157}
158
159/// `"any with quota"`, in the words an agent may type.
160pub(super) fn is_any_with_quota(wanted: &str) -> bool {
161    let w = wanted.trim().to_lowercase().replace(['_', '-'], " ");
162    w == "any with quota" || w == "any"
163}
164
165/// Name one account among `accounts` (one provider's): by stable id, by local
166/// id or label, by email when exactly one account of that email has quota, or
167/// `"any with quota"`. `skip` holds the accounts an agent is already on, which
168/// `any with quota` does not pick. The refusal lists what the caller could use, and says which
169/// kind it is: no such account, a name several share, or none with quota now.
170pub(super) fn pick<'a>(
171    state: &AppState,
172    accounts: &'a [IdentityAccount],
173    wanted: &str,
174    skip: &[String],
175    provider: &str,
176) -> Result<&'a IdentityAccount, SwitchError> {
177    let wanted = wanted.trim();
178    let blocked = account_blocks(state, accounts);
179    let list = |only_quota: bool| -> String {
180        let shown: Vec<String> = accounts
181            .iter()
182            .filter(|a| !only_quota || has_quota(a, &blocked))
183            .map(|a| match stable_account_id(a) {
184                Some(id) => format!("{} ({id})", account_label_in(a, accounts)),
185                None => account_label_in(a, accounts),
186            })
187            .collect();
188        if shown.is_empty() {
189            "none".to_string()
190        } else {
191            shown.join(", ")
192        }
193    };
194    if is_any_with_quota(wanted) {
195        // The signed-in ones before the unchecked, then the oldest: a stable choice.
196        return accounts
197            .iter()
198            // Never a key: moving onto one is a person's choice of who pays, not what `any` stands for.
199            .filter(|a| has_quota(a, &blocked) && !skip.contains(&a.id) && !super::key_account::is_key(a))
200            .min_by_key(|a| (!signed_in(&a.status), a.created_at, a.id.clone()))
201            .ok_or_else(|| SwitchError::new(SwitchRefusal::NoQuota, format!("NO_ACCOUNT_WITH_QUOTA: no {provider} account has quota now; the accounts are: {}", list(false))));
202    }
203    // Sign-ins of one provider account share the id and its quota: the one that can run wins.
204    if let Some(a) = accounts
205        .iter()
206        .filter(|a| stable_account_id(a).is_some_and(|s| s.eq_ignore_ascii_case(wanted)))
207        .min_by_key(|a| (!has_quota(a, &blocked), !signed_in(&a.status), a.created_at, a.id.clone()))
208    {
209        return Ok(a);
210    }
211    // A bare email names the one account of it that has quota, even when several sign-ins share it.
212    let same_email: Vec<&IdentityAccount> = accounts.iter().filter(|a| !email_of(a).is_empty() && email_of(a).eq_ignore_ascii_case(wanted)).collect();
213    if !same_email.is_empty() {
214        let with_quota: Vec<&IdentityAccount> = same_email.iter().copied().filter(|a| has_quota(a, &blocked)).collect();
215        // Already on one of them: that is the answer, and the switch reports it unchanged.
216        if let Some(own) = with_quota.iter().copied().find(|a| skip.contains(&a.id)) {
217            return Ok(own);
218        }
219        return match with_quota.as_slice() {
220            [one] => Ok(one),
221            [] => Err(SwitchError::new(SwitchRefusal::NoQuota, format!("NO_ACCOUNT_WITH_QUOTA: no {provider} account of {wanted} has quota now; the accounts are: {}", list(false)))),
222            _ => Err(SwitchError::new(
223                SwitchRefusal::AccountNameShared,
224                format!("AMBIGUOUS_ACCOUNT: {} {provider} accounts of {wanted} have quota; name one: {}", with_quota.len(), list(true)),
225            )),
226        };
227    }
228    if let Some(a) = accounts.iter().find(|a| crate::identity::account_numbering::names(a, wanted, accounts)) {
229        return Ok(a);
230    }
231    Err(SwitchError::new(SwitchRefusal::NoSuchAccount, format!("UNKNOWN_ACCOUNT: no {provider} account {wanted:?}; the accounts are: {}", list(false))))
232}