//! 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 per hx attempt (not the gate). Default 30 min. pub wall_secs: Option, /// Max `turn_start` events over the whole run (all attempts) before hx is killed. pub max_turns: Option, /// Max input+output tokens over the whole run, 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, /// Extra hx attempts after a red gate (default 2). 0 = fail straight to needs-human. #[serde(default = "default_retries")] pub max_retries: u32, /// Tool allowlist, see policy.rs. Absent = no policy (hx runs headless with every tool allowed). /// Present = enforced by `orch guard` inside hx and re-checked on the event stream; a denied call ends /// the run as needs-human. pub allow: Option>, /// Extra directories the agent may read besides the worktree. #[serde(default)] pub read_roots: Vec, /// Names (trailing `*` = prefix) of orch's environment variables passed to hx. hx gets a cleared /// environment plus PATH, HOME, USER, LOGNAME, SHELL, TERM, LANG, LC_*, TMPDIR, CARGO_*, RUST*. #[serde(default)] pub env: Vec, /// Parallel runs for `orch pull` (default 1). #[serde(default = "one")] pub workers: u32, /// Provider account this profile bills to; profiles sharing a login set the same name. Default: profile name. pub account: Option, /// Max simultaneous runs on the account across all orch processes (default = workers). pub max_concurrent: Option, #[serde(default)] pub budget: Budget, /// Default repo for tasks that name none (`orch pull`). pub repo: Option, pub source: Option, pub sink: Option, } fn one() -> u32 { 1 } fn default_retries() -> u32 { 2 } fn default_hx() -> String { "hx".into() } impl Profile { pub fn parse(s: &str) -> Result { let p: Profile = toml::from_str(s)?; for e in p.allow.iter().flatten() { crate::policy::check_entry(e)?; } if p.workers == 0 || p.max_concurrent == Some(0) { bail!("workers and max_concurrent must be >= 1"); } 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 = match std::fs::read_to_string(&path) { // only the implicit profile may be missing; a typo in any other name must still fail Err(e) if name == "default" && e.kind() == std::io::ErrorKind::NotFound => { String::new() } r => r.with_context(|| format!("profile {}", path.display()))?, }; Self::parse(&s).with_context(|| path.display().to_string()) } pub fn account<'a>(&'a self, profile: &'a str) -> &'a str { self.account.as_deref().unwrap_or(profile) } 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.workers, p.account("x")), (1, "x")); 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 allowlist_validated() { assert!(Profile::parse("allow = [\"read\", \"bash:cargo *\"]").is_ok()); assert!(Profile::parse("allow = [\"read:x\"]").is_err()); } #[test] fn rejects_zero_workers() { assert!(Profile::parse("workers = 0").is_err()); assert!(Profile::parse("max_concurrent = 0").is_err()); } #[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()); } }