Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-switchboard/src/rules.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-switchboard / src / rules.rs` 411 lines ยท 14337 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! The rule table: one plain TOML file the operator edits. 17 //! 18 //! ```toml 19 //! [settings] 20 //! ceiling_percent = 90 # an account at or over this is treated as full 21 //! default_backoff_secs = 1800 # cooldown when a limit hit gives no reset time 22 //! 23 //! [[accounts]] 24 //! id = "anthropic-1" 25 //! provider = "anthropic" # anthropic openai google xai openrouter local 26 //! program = "claude" 27 //! settings_dir = "/home/me/.switchboard/anthropic-1" 28 //! 29 //! [[accounts]] 30 //! id = "openrouter-1" 31 //! provider = "openrouter" 32 //! program = "http" 33 //! key_ref = "openrouter-key" # a NAME in the vault, never the key itself 34 //! 35 //! [[accounts]] 36 //! id = "local" 37 //! provider = "local" 38 //! program = "aien" 39 //! 40 //! [routes] 41 //! code = ["anthropic-1", "openrouter-1"] 42 //! default = ["anthropic-1"] 43 //! 44 //! [launch] 45 //! pass_env = ["HTTPS_PROXY"] # proxy variables only; see launch::PROXY_ENV 46 //! ``` 47 //! 48 //! A route may hold at most one subscription account (one with 49 //! `settings_dir`) per provider: automatic routing between two subscriptions 50 //! of the same provider is excluded (operator decision 2026-10-16). 51 //! `settings_dir` must be absolute and different for every account. 52 //! 53 //! `local` is always the last fallback of every route so AIEN works offline. 54 //! If the file lists it earlier it is moved to the end; if the file omits it 55 //! it is added. 56 57 use crate::account::{Account, AccountId, Credential, Provider}; 58 use crate::job::JobKind; 59 use crate::launch::PROXY_ENV; 60 use serde::Deserialize; 61 use std::collections::{BTreeMap, BTreeSet}; 62 use std::fmt; 63 use std::path::{Path, PathBuf}; 64 65 #[derive(Debug, Clone, PartialEq, Eq)] 66 pub enum RulesError { 67 Read(String), 68 /// Syntax or shape error, with the parser's own line and column text. 69 Parse(String), 70 /// The file parsed but breaks a rule; the text says which and how to fix. 71 Invalid(String), 72 } 73 74 impl fmt::Display for RulesError { 75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 76 match self { 77 RulesError::Read(m) => write!(f, "cannot read rule file: {m}"), 78 RulesError::Parse(m) => write!(f, "rule file is not valid: {m}"), 79 RulesError::Invalid(m) => write!(f, "rule file has a mistake: {m}"), 80 } 81 } 82 } 83 84 impl std::error::Error for RulesError {} 85 86 fn bad(m: impl Into) -> Result { 87 Err(RulesError::Invalid(m.into())) 88 } 89 90 #[derive(Deserialize)] 91 #[serde(deny_unknown_fields)] 92 struct RawFile { 93 #[serde(default)] 94 settings: RawSettings, 95 #[serde(default)] 96 accounts: Vec, 97 #[serde(default)] 98 launch: RawLaunch, 99 routes: RawRoutes, 100 } 101 102 /// `[launch]`: how `switchboard launch` builds the environment for `claude`. 103 #[derive(Default, Deserialize)] 104 #[serde(deny_unknown_fields)] 105 struct RawLaunch { 106 /// Proxy variables to pass through from the shell. Only names in 107 /// `launch::PROXY_ENV` are accepted; nothing else can be added. 108 #[serde(default)] 109 pass_env: Vec, 110 } 111 112 #[derive(Deserialize)] 113 #[serde(deny_unknown_fields)] 114 struct RawSettings { 115 #[serde(default = "default_ceiling")] 116 ceiling_percent: f64, 117 #[serde(default = "default_backoff")] 118 default_backoff_secs: u64, 119 } 120 121 fn default_ceiling() -> f64 { 122 90.0 123 } 124 fn default_backoff() -> u64 { 125 1800 126 } 127 128 impl Default for RawSettings { 129 fn default() -> Self { 130 RawSettings { 131 ceiling_percent: default_ceiling(), 132 default_backoff_secs: default_backoff(), 133 } 134 } 135 } 136 137 #[derive(Deserialize)] 138 #[serde(deny_unknown_fields)] 139 struct RawAccount { 140 id: String, 141 provider: Provider, 142 program: String, 143 settings_dir: Option, 144 key_ref: Option, 145 } 146 147 #[derive(Deserialize)] 148 #[serde(deny_unknown_fields)] 149 struct RawRoutes { 150 code: Option>, 151 review: Option>, 152 research: Option>, 153 default: Vec, 154 } 155 156 #[derive(Debug, Clone, PartialEq)] 157 pub struct RuleTable { 158 accounts: Vec, 159 ceiling_percent: f64, 160 default_backoff_secs: u64, 161 routes: BTreeMap>, 162 default_route: Vec, 163 local: AccountId, 164 pass_env: Vec, 165 } 166 167 fn valid_name(s: &str) -> bool { 168 !s.is_empty() 169 && s.len() <= 64 170 && s.chars() 171 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') 172 } 173 174 impl RuleTable { 175 pub fn from_path(path: &Path) -> Result { 176 let text = std::fs::read_to_string(path) 177 .map_err(|e| RulesError::Read(format!("{}: {e}", path.display())))?; 178 Self::from_toml_str(&text) 179 } 180 181 pub fn from_toml_str(text: &str) -> Result { 182 let raw: RawFile = toml::from_str(text).map_err(|e| RulesError::Parse(e.to_string()))?; 183 184 let c = raw.settings.ceiling_percent; 185 if !(c > 0.0 && c <= 100.0) { 186 return bad(format!( 187 "ceiling_percent must be above 0 and at most 100, got {c}" 188 )); 189 } 190 191 let mut accounts = Vec::new(); 192 let mut seen = BTreeSet::new(); 193 let mut local: Option = None; 194 let mut folders: BTreeMap = BTreeMap::new(); 195 for a in raw.accounts { 196 if !valid_name(&a.id) { 197 return bad(format!( 198 "account id {:?} must be 1 to 64 letters, digits, '-', '_' or '.'", 199 a.id 200 )); 201 } 202 if !seen.insert(a.id.clone()) { 203 return bad(format!("account id {:?} is listed twice", a.id)); 204 } 205 if a.program.trim().is_empty() { 206 return bad(format!("account {:?} has an empty program name", a.id)); 207 } 208 if a.program.contains('/') && !Path::new(&a.program).is_absolute() { 209 return bad(format!( 210 "account {:?}: program must be a bare name found on PATH or an absolute path, got {:?}; a relative path would run a file from the working folder", 211 a.id, a.program 212 )); 213 } 214 let credential = match (a.settings_dir, a.key_ref) { 215 (Some(_), Some(_)) => { 216 return bad(format!( 217 "account {:?} sets both settings_dir and key_ref; pick one", 218 a.id 219 )) 220 } 221 (Some(p), None) => { 222 if !p.is_absolute() { 223 return bad(format!( 224 "account {:?}: settings_dir must be an absolute path, got {}", 225 a.id, 226 p.display() 227 )); 228 } 229 if p.components().any(|c| c == std::path::Component::ParentDir) { 230 return bad(format!( 231 "account {:?}: settings_dir must not contain '..', got {}", 232 a.id, 233 p.display() 234 )); 235 } 236 if let Some(other) = folders.insert(p.clone(), a.id.clone()) { 237 return bad(format!( 238 "accounts {other:?} and {:?} use the same settings_dir {}; each account needs its own folder", 239 a.id, 240 p.display() 241 )); 242 } 243 Credential::SettingsFolder(p) 244 } 245 (None, Some(k)) => { 246 if !valid_name(&k) { 247 return bad(format!( 248 "account {:?}: key_ref must be a key NAME (letters, digits, '-', '_', '.'), never the key itself", 249 a.id 250 )); 251 } 252 Credential::KeyRef(k) 253 } 254 (None, None) => { 255 // Only the local model needs no login. Any other account 256 // without a setting would fall back to its program's default 257 // login (for claude: ~/.claude, a subscription the route rule 258 // could not see). 259 if a.provider != Provider::Local { 260 return bad(format!( 261 "account {:?} ({}) needs settings_dir or key_ref; only the local account may have neither", 262 a.id, 263 a.provider.as_str() 264 )); 265 } 266 Credential::None 267 } 268 }; 269 if a.provider == Provider::Local { 270 if credential != Credential::None { 271 return bad(format!( 272 "account {:?} is local and must not set settings_dir or key_ref", 273 a.id 274 )); 275 } 276 if local.is_some() { 277 return bad("more than one local account; exactly one is allowed"); 278 } 279 local = Some(AccountId::new(a.id.clone())); 280 } 281 accounts.push(Account { 282 id: AccountId::new(a.id), 283 provider: a.provider, 284 program: a.program, 285 credential, 286 }); 287 } 288 let local = match local { 289 Some(l) => l, 290 None => { 291 return bad( 292 "no account with provider = \"local\"; AIEN must always have the local model as the last fallback", 293 ) 294 } 295 }; 296 297 let resolve = |label: &str, ids: Vec| -> Result, RulesError> { 298 if ids.is_empty() { 299 return bad(format!("route {label:?} is an empty list")); 300 } 301 let mut out: Vec = Vec::new(); 302 for id in ids { 303 if !seen.contains(&id) { 304 return bad(format!( 305 "route {label:?} names account {id:?}, which is not in [[accounts]]" 306 )); 307 } 308 let id = AccountId::new(id); 309 if out.contains(&id) { 310 return bad(format!("route {label:?} lists {id} twice")); 311 } 312 out.push(id); 313 } 314 // Local is always last, exactly once. 315 no_same_provider_subscriptions(label, &out, &accounts)?; 316 out.retain(|i| *i != local); 317 out.push(local.clone()); 318 Ok(out) 319 }; 320 321 let default_route = resolve("default", raw.routes.default)?; 322 let mut routes = BTreeMap::new(); 323 for (kind, list) in [ 324 (JobKind::Code, raw.routes.code), 325 (JobKind::Review, raw.routes.review), 326 (JobKind::Research, raw.routes.research), 327 ] { 328 if let Some(ids) = list { 329 routes.insert(kind, resolve(kind.as_str(), ids)?); 330 } 331 } 332 333 for name in &raw.launch.pass_env { 334 if !PROXY_ENV.contains(&name.as_str()) { 335 return bad(format!( 336 "[launch] pass_env may list only proxy variables ({}); {name:?} is not one", 337 PROXY_ENV.join(", ") 338 )); 339 } 340 } 341 342 Ok(RuleTable { 343 accounts, 344 ceiling_percent: c, 345 default_backoff_secs: raw.settings.default_backoff_secs, 346 routes, 347 default_route, 348 local, 349 pass_env: raw.launch.pass_env, 350 }) 351 } 352 353 pub fn ceiling_percent(&self) -> f64 { 354 self.ceiling_percent 355 } 356 357 pub fn default_backoff_secs(&self) -> u64 { 358 self.default_backoff_secs 359 } 360 361 /// Proxy variable names `switchboard launch` passes through from the 362 /// shell (from `[launch] pass_env`). Every name is in `PROXY_ENV`. 363 pub fn pass_env(&self) -> &[String] { 364 &self.pass_env 365 } 366 367 pub fn local(&self) -> &AccountId { 368 &self.local 369 } 370 371 pub fn accounts(&self) -> &[Account] { 372 &self.accounts 373 } 374 375 pub fn account(&self, id: &AccountId) -> Option<&Account> { 376 self.accounts.iter().find(|a| a.id == *id) 377 } 378 379 /// Ordered account ids for this kind of job; the last one is always local. 380 pub fn route_for(&self, kind: JobKind) -> &[AccountId] { 381 self.routes.get(&kind).unwrap_or(&self.default_route) 382 } 383 } 384 385 /// Operator decision 2026-10-16 (aien-architecture#236; issue #592): 386 /// no automatic routing between two subscription accounts of the same 387 /// provider. A subscription account is one whose program keeps its own login 388 /// in a settings folder. Manual `switchboard launch` may still open any 389 /// profile; this rule only governs routes. 390 fn no_same_provider_subscriptions( 391 label: &str, 392 route: &[AccountId], 393 accounts: &[Account], 394 ) -> Result<(), RulesError> { 395 let mut seen: BTreeMap<&'static str, &AccountId> = BTreeMap::new(); 396 for id in route { 397 let Some(a) = accounts.iter().find(|a| a.id == *id) else { 398 continue; 399 }; 400 if !matches!(a.credential, Credential::SettingsFolder(_)) { 401 continue; 402 } 403 if let Some(first) = seen.insert(a.provider.as_str(), id) { 404 return bad(format!( 405 "route {label:?} holds two {} subscription accounts ({first}, {id}); automatic routing between subscriptions of the same provider is excluded (operator decision 2026-10-16, aien-architecture#236). Keep one per route and open the other by hand with `switchboard launch {id}`", 406 a.provider.as_str() 407 )); 408 } 409 } 410 Ok(()) 411 }