//! Profile: `/profiles/NAME.toml`. One profile = one identity (own HOME/auth), budget and gate. use anyhow::{Context, Result, bail}; use serde::Deserialize; use std::path::PathBuf; #[derive(Deserialize, Debug, Default, Clone)] #[serde(deny_unknown_fields)] pub struct Budget { /// Wall clock limit for the hx run (not the gate). Default 30 min. pub wall_secs: Option, /// Max `turn_start` events before hx is killed. pub max_turns: Option, /// Max input+output tokens, summed over `stream/done` events. pub max_tokens: Option, } #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct Profile { /// hx command, whitespace-split (ponytail: no quoting; wrap in a script if needed). #[serde(default = "default_hx")] pub hx: String, /// HOME for hx, so each profile keeps its own `~/.hx/auth.json`. pub home: Option, pub provider: Option, #[serde(default)] pub sandbox: bool, /// Passes `--yolo`. Only allowed together with `sandbox = true`. #[serde(default)] pub yolo: bool, /// Shell command run in the worktree after hx; exit 0 = pass. None = no gate. pub gate: Option, #[serde(default)] pub budget: Budget, } fn default_hx() -> String { "hx".into() } impl Profile { pub fn parse(s: &str) -> Result { let p: Profile = toml::from_str(s)?; if p.yolo && !p.sandbox { bail!("yolo = true requires sandbox = true"); } Ok(p) } pub fn load(name: &str) -> Result { if name.is_empty() || name.contains(['/', '.']) { bail!("bad profile name {name:?}"); } let path = crate::config_dir() .join("profiles") .join(format!("{name}.toml")); let s = std::fs::read_to_string(&path) .with_context(|| format!("profile {}", path.display()))?; Self::parse(&s).with_context(|| path.display().to_string()) } pub fn wall_secs(&self) -> u64 { self.budget.wall_secs.unwrap_or(1800) } } #[cfg(test)] mod tests { use super::*; #[test] fn minimal_and_full() { let p = Profile::parse("").unwrap(); assert_eq!( (p.hx.as_str(), p.wall_secs(), p.gate.is_none()), ("hx", 1800, true) ); let p = Profile::parse( "hx='x'\nhome='/h'\nsandbox=true\nyolo=true\ngate='true'\n[budget]\nmax_turns=3\nwall_secs=9\n", ) .unwrap(); assert_eq!( (p.budget.max_turns, p.wall_secs(), p.home.unwrap().to_str()), (Some(3), 9, Some("/h")) ); } #[test] fn rejects_yolo_without_sandbox_and_unknown_keys() { assert!(Profile::parse("yolo=true").is_err()); assert!(Profile::parse("bogus=1").is_err()); } #[test] fn rejects_path_like_names() { assert!(Profile::load("../x").is_err()); } }