agentmux_srv/server/account_episodes/
key_account.rs1use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, launch, token};
14use crate::backend::obj;
15use crate::backend::storage::identities::IdentityAccount;
16use crate::server::AppState;
17
18use super::canonical;
19
20pub fn is_key(a: &IdentityAccount) -> bool {
22 a.kind == "api_key" && a.provider.eq_ignore_ascii_case(KEY_ROUTE_ID)
23}
24
25pub(super) fn serves(provider: &str, a: &IdentityAccount) -> bool {
28 canonical(&a.provider) == provider || (provider == "claude" && is_key(a))
29}
30
31pub(super) fn is_link_of(provider: &str, link_provider: &str) -> bool {
33 canonical(link_provider) == provider || (provider == "claude" && link_provider.eq_ignore_ascii_case(KEY_ROUTE_ID))
34}
35
36pub(super) fn link_provider<'a>(to: &IdentityAccount, provider: &'a str) -> &'a str {
38 if is_key(to) {
39 KEY_ROUTE_ID
40 } else {
41 provider
42 }
43}
44
45pub(super) fn can_take_a_key(state: &AppState, def_id: &str) -> Result<(), String> {
49 if launch::choice_of(&state.mstore, def_id).is_some() {
50 return Err("ACCOUNT_CANT_RUN: this agent runs on a model route, which is billed to the route's key; move it back to its own sign-in first".to_string());
51 }
52 Ok(())
53}
54
55pub(super) fn left_the_key(def_id: &str) {
57 token::revoke(def_id, KEY_ROUTE_ID);
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 fn account(provider: &str, kind: &str) -> IdentityAccount {
65 IdentityAccount {
66 id: "a".into(),
67 name: "n".into(),
68 provider: provider.into(),
69 kind: kind.into(),
70 display_name: String::new(),
71 secret_ref: crate::backend::storage::identities::SecretRef::Env { env_var: "X".into() },
72 context: serde_json::json!({}),
73 status: "valid".into(),
74 created_at: 0,
75 updated_at: 0,
76 }
77 }
78
79 #[test]
80 fn only_an_anthropic_api_key_is_a_key_account() {
81 assert!(is_key(&account("anthropic", "api_key")));
82 assert!(!is_key(&account("anthropic", "oauth")));
83 assert!(!is_key(&account("openai", "api_key")));
84 assert!(!is_key(&account("claude", "oauth")));
85 }
86
87 #[test]
88 fn a_claude_agent_is_served_by_plans_and_keys_and_no_other_agent_by_a_key() {
89 assert!(serves("claude", &account("claude", "oauth")));
90 assert!(serves("claude", &account("claude-code", "oauth")));
91 assert!(serves("claude", &account("anthropic", "api_key")));
92 assert!(!serves("codex", &account("anthropic", "api_key")), "another harness is not offered an Anthropic key");
93 assert!(!serves("claude", &account("openai", "api_key")));
94 assert!(is_link_of("claude", "anthropic") && is_link_of("claude", "claude-code") && !is_link_of("codex", "anthropic"));
95 }
96
97 #[test]
98 fn a_key_is_linked_under_its_own_provider_and_a_plan_under_the_agents() {
99 assert_eq!(link_provider(&account("anthropic", "api_key"), "claude"), "anthropic");
100 assert_eq!(link_provider(&account("claude", "oauth"), "claude"), "claude");
101 }
102}