agentmux_srv/server/account_episodes/
accounts.rs1use 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#[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#[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 #[ts(type = "number | null")]
44 pub resets_at_ms: Option<u64>,
45 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#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
57#[ts(export, export_to = "../../../frontend/types/rpc/")]
58pub struct AccountView {
59 #[serde(skip_serializing_if = "Option::is_none")]
62 #[ts(optional)]
63 pub stable_id: Option<String>,
64 pub account_id: String,
66 pub provider: String,
67 pub email: String,
68 pub label: String,
70 pub sign_in: String,
72 pub quota: AccountQuota,
73 pub usage: AccountUsage,
76 pub never_failover: bool,
78 pub agents: Vec<AccountAgent>,
79}
80
81#[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
88fn 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 *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
110pub(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
153fn has_quota(a: &IdentityAccount, blocked: &HashMap<String, String>) -> bool {
156 can_receive(&a.status) && !blocked.contains_key(&a.id)
157}
158
159pub(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
165pub(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 return accounts
197 .iter()
198 .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 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 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 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}