use std::time::Duration;
use anyhow::{Result, bail};
use chrono::{TimeDelta, Utc};
pub mod exhaustion;
pub(crate) mod fleet;
pub(crate) mod observation;
mod read;
pub mod route;
pub mod router;
mod store;
mod view;
pub use exhaustion::Exhaustion;
pub use observation::Observation;
pub use route::Routing;
pub use router::Router;
use store::Store;
pub(crate) use view::EMPTY;
pub use view::View;
use crate::config::UserConfig;
use crate::harness::{Choice, Harness};
const FRESH: Duration = Duration::from_secs(60);
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum Selection {
#[default]
Default,
Fleet,
Machine(String),
Local,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
Show {
selection: Selection,
json: bool,
},
Clear {
harness: Option<Harness>,
json: bool,
},
Push {
destination: Option<String>,
},
}
pub enum Shown {
Local(View),
Fleet(fleet::Fleet),
}
impl Shown {
pub fn json(&self) -> Result<serde_json::Value> {
Ok(match self {
Self::Local(view) => serde_json::to_value(view)?,
Self::Fleet(fleet) => serde_json::to_value(fleet)?,
})
}
}
impl std::fmt::Display for Shown {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Local(view) => view.fmt(f),
Self::Fleet(fleet) => fleet.fmt(f),
}
}
}
pub(crate) fn record(observations: Vec<Observation>) {
if observations.is_empty() || cfg!(test) {
return;
}
let Ok(store) = Store::machine() else {
return;
};
let now = Utc::now();
let _ = store.update_all(|harnesses| {
for observation in &observations {
harnesses
.entry(observation.harness.name().into())
.or_default()
.observe(observation, "session", now);
}
});
}
pub(crate) fn credits_allowed(choice: &Choice) -> bool {
if cfg!(test) {
return false;
}
UserConfig::load().is_ok_and(|config| config.routing.allows_credits(choice, &config.harness))
}
pub fn settled_route(harness: &Choice) -> Choice {
if harness.chosen_by != crate::harness::ChosenBy::Routes {
return harness.clone();
}
let Ok(config) = UserConfig::load() else {
return harness.clone();
};
let router = Router::of(&config.harness, &config.routing, harness, None, None);
router
.pick(false, &[])
.and_then(|picked| router.candidates(false).get(picked.index))
.map_or_else(|| harness.clone(), |candidate| candidate.choice.clone())
}
pub fn subscription_named(name: &str) -> Result<Harness> {
match Harness::named(name) {
Some(harness) if observation::subscription(harness) => Ok(harness),
_ => bail!(
"{name:?} is not a subscription Harness: Plan usage watches {}",
observation::SUBSCRIPTION.map(Harness::name).join(", ")
),
}
}
fn refresh(store: &Store) -> Result<()> {
let saved = store.read()?;
let now = Utc::now();
let stale: Vec<Harness> = read::READABLE
.into_iter()
.filter(|harness| harness.installed())
.filter(|harness| !read_lately(saved.get(harness.name()), now))
.collect();
read_into(store, &stale)
}
fn read_lately(state: Option<&store::State>, now: chrono::DateTime<Utc>) -> bool {
let fresh = TimeDelta::from_std(FRESH).expect("a minute fits");
state
.and_then(|state| state.read_at)
.is_some_and(|read| read <= now && now - read < fresh)
}
fn read_into(store: &Store, stale: &[Harness]) -> Result<()> {
let read: Vec<(Harness, read::Reading)> = std::thread::scope(|scope| {
let reads: Vec<_> = stale
.iter()
.map(|harness| scope.spawn(move || read::read(*harness).map(|read| (*harness, read))))
.collect();
reads
.into_iter()
.filter_map(|read| read.join().ok().flatten())
.collect()
});
if read.is_empty() {
return Ok(());
}
let now = Utc::now();
store.update_all(|harnesses| {
for (harness, reading) in read {
reading.apply(harnesses.entry(harness.name().into()).or_default(), now);
}
})
}
fn local_view(config: &UserConfig) -> Result<View> {
let store = Store::machine()?;
refresh(&store)?;
Ok(View::of(
config,
store.read()?,
Harness::installed,
Utc::now(),
))
}
pub(crate) fn saved_view(config: &UserConfig) -> Result<View> {
Ok(View::of(
config,
Store::machine()?.read()?,
Harness::installed,
Utc::now(),
))
}
pub(crate) fn show(
config: &UserConfig,
selection: &Selection,
capture: &fleet::Capture<'_>,
) -> Result<Shown> {
let reach = match selection {
Selection::Machine(name) if name != capture.local() => fleet::Reach::Machine(name),
Selection::Fleet => fleet::Reach::Fleet(local_view(config)?),
Selection::Default if capture.default_view() => fleet::Reach::Fleet(local_view(config)?),
Selection::Local | Selection::Machine(_) | Selection::Default => {
return Ok(Shown::Local(local_view(config)?));
}
};
Ok(Shown::Fleet(capture.load(reach)?))
}
pub(crate) fn clear(harness: Option<Harness>) -> Result<Vec<&'static str>> {
Store::machine()?.clear(harness)?;
Ok(match harness {
Some(harness) => vec![harness.name()],
None => observation::SUBSCRIPTION.map(Harness::name).to_vec(),
})
}
fn refresh_for_routing(store: &Store, harnesses: &[Harness]) -> Result<()> {
let saved = store.read()?;
let now = Utc::now();
let mut stale: Vec<Harness> = Vec::new();
for harness in harnesses {
if read::WINDOWED.contains(harness)
&& !stale.contains(harness)
&& harness.installed()
&& !read_lately(saved.get(harness.name()), now)
&& router::stale(saved.get(harness.name()), now)
{
stale.push(*harness);
}
}
read_into(store, &stale)
}
pub fn pass_exhaustion(
config: &UserConfig,
harness: &Choice,
security: bool,
) -> Option<Exhaustion> {
if cfg!(test) {
return None;
}
let routes = allowed_routes(config, harness, security);
let store = Store::machine().ok()?;
let harnesses: Vec<Harness> = routes.iter().map(|route| route.harness).collect();
let _ = refresh_for_routing(&store, &harnesses);
let saved = store.read().ok()?;
exhaustion::judge(
&routes,
&config.routing,
&saved,
Harness::installed,
Utc::now(),
)
}
fn allowed_routes(config: &UserConfig, harness: &Choice, security: bool) -> Vec<route::Route> {
let router = Router::of(
&config.harness,
&config.routing,
harness,
Choice::of_security_review(config.security_harness, &config.harness).as_ref(),
Some(&Choice::of(
&crate::harness::Asked::default(),
&config.harness,
)),
);
router.allowed(security, harness.harness)
}
pub fn machine_exhaustion(config: &UserConfig) -> Option<Exhaustion> {
if cfg!(test) {
return None;
}
let routes = if config.routing.routes.is_empty() {
vec![exhaustion::pinned(
config.harness.default.unwrap_or(Harness::Claude),
)]
} else {
config.routing.routes.clone()
};
let saved = Store::machine().ok()?.read().ok()?;
exhaustion::judge(
&routes,
&config.routing,
&saved,
Harness::installed,
Utc::now(),
)
}
pub(crate) fn latest_limit() -> Option<crate::session::limits::Limit> {
if cfg!(test) {
return None;
}
let saved = Store::machine().ok()?.read().ok()?;
let now = Utc::now();
let cooled = saved
.iter()
.filter_map(|(name, state)| Some((Harness::named(name)?, state)))
.filter_map(|(harness, state)| Some((harness, state, state.cooldown.as_ref()?)))
.filter(|(_, _, cooldown)| cooldown.until > now)
.max_by_key(|(_, _, cooldown)| cooldown.since);
match cooled {
Some((harness, state, cooldown)) => {
let used = cooldown
.window
.as_deref()
.and_then(|window| state.used_percent_in(window, now));
Some(crate::session::limits::Limit::of(
harness,
cooldown.window.clone(),
used,
Some(cooldown.until),
))
}
None => machine_exhaustion(&UserConfig::load().ok()?).map(|ex| ex.limit()),
}
}
pub fn banner(config: &UserConfig) -> Option<String> {
let exhaustion = machine_exhaustion(config)?;
let mut line = format!(
"Plan usage: every configured route is unavailable, so scheduled Passes skip: {}",
exhaustion.routes()
);
if let Some(reset) = exhaustion.earliest_reset() {
line.push_str(&format!(
"; earliest reset {}",
reset.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
));
}
Some(line)
}
pub fn execute(action: Action) -> Result<String> {
match action {
Action::Push { destination } => {
crate::console::report::push_plan_usage_by_hand(destination.as_deref())
}
Action::Clear { harness, json } => {
let cleared = clear(harness)?;
if json {
return Ok(serde_json::to_string_pretty(
&serde_json::json!({"version": 1, "cleared": cleared}),
)?);
}
Ok(format!(
"Cleared recorded Plan usage cooldowns and revalidation for {}",
cleared.join(", ")
))
}
Action::Show { selection, json } => {
let config = UserConfig::load()?;
let shown = show(&config, &selection, &fleet::Capture::new(&config, None))?;
if json {
Ok(serde_json::to_string_pretty(&shown.json()?)?)
} else {
Ok(shown.to_string())
}
}
}
}