//! Profile: `./.hx/profiles/NAME.toml` (repo-local, checked first), else `/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; /// `./.hx/profiles/NAME.toml` when it exists (repo-local wins), else `/profiles/NAME.toml`. fn profile_path(name: &str) -> PathBuf { let file = format!("{name}.toml"); let local = PathBuf::from(".hx/profiles").join(&file); if local.is_file() { return local; } crate::config_dir().join("profiles").join(file) } /// [`Profile::add_allow`] on a file. fn add_allow_at(path: &std::path::Path, entry: &str) -> Result { crate::policy::check_entry(entry)?; let text = std::fs::read_to_string(path).map_err(|e| { if e.kind() == std::io::ErrorKind::NotFound { anyhow::anyhow!( "{} does not exist: the implicit default profile has no allowlist to extend", path.display() ) } else { anyhow::anyhow!("{}: {e}", path.display()) } })?; let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| path.display().to_string())?; let Some(list) = doc.get_mut("allow").and_then(|a| a.as_array_mut()) else { bail!( "{} has no `allow` list: without one every tool is already allowed", path.display() ); }; if list.iter().any(|v| v.as_str() == Some(entry)) { return Ok(false); } list.push(entry); std::fs::write(path, doc.to_string()).with_context(|| path.display().to_string())?; Ok(true) } /// macOS ships a sandbox (seatbelt); Linux needs `bwrap` on PATH; elsewhere none. pub fn sandbox_available() -> bool { if cfg!(target_os = "macos") { return true; } cfg!(target_os = "linux") && has_bwrap(&std::env::var("PATH").unwrap_or_default()) } fn has_bwrap(path: &str) -> bool { std::env::split_paths(path).any(|d| d.join("bwrap").is_file()) } #[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, Copy, Default, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub enum OnDeny { #[default] Stop, Continue, } #[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, /// Passes `--sandbox`. Unset: on when the platform has a sandbox (macOS, Linux with bwrap). pub sandbox: Option, /// Passes `--yolo`. Only allowed together with a sandbox. Unset: on whenever the sandbox is on. /// With neither set and no sandbox available hx runs with `--auto`. pub yolo: Option, /// 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>, /// What a denied tool call does: `stop` (default) ends the run as needs-human; `continue` answers the agent with /// the reason so it can pick another way. Credentials, paths outside the worktree, `git push` and `.git`/`.hx` /// always stop. Every deny is audited and counted (`denies` in the run and in telemetry). #[serde(default)] pub on_deny: OnDeny, /// 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 == Some(true) && p.sandbox == Some(false) { bail!("yolo = true requires sandbox = true"); } if p.yolo == Some(true) && p.sandbox.is_none() && !sandbox_available() { bail!("yolo = true requires a sandbox, and none is available (Linux needs bwrap)"); } Ok(p) } /// Whether hx runs sandboxed: explicit setting, else whatever the platform offers. pub fn sandboxed(&self) -> bool { self.sandbox.unwrap_or_else(sandbox_available) } /// Whether hx gets `--yolo`: explicit setting, else on with the sandbox. pub fn yolo_on(&self) -> bool { self.yolo.unwrap_or(self.sandboxed()) && self.sandboxed() } /// Permission flags for hx: `--sandbox [--yolo]`, or `--auto` when unsandboxed. pub fn hx_flags(&self) -> Vec<&'static str> { let mut f = Vec::new(); if self.sandboxed() { f.push("--sandbox"); if self.yolo_on() { f.push("--yolo"); } } else { f.push("--auto"); } f } pub fn load(name: &str) -> Result { if name.is_empty() || name.contains(['/', '.']) { bail!("bad profile name {name:?}"); } let path = profile_path(name); 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()) } /// Appends `entry` to the `allow` list of profile `name`, keeping the rest of the file (comments, order) as it /// is. Returns false when the entry was there already. Refuses a profile without a file or without `allow`: /// no list means "everything allowed", and one entry would silently turn that into "almost nothing". pub fn add_allow(name: &str, entry: &str) -> Result { if name.is_empty() || name.contains(['/', '.']) { bail!("bad profile name {name:?}"); } add_allow_at(&profile_path(name), entry) } 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 on_deny_parses() { assert_eq!(Profile::parse("").unwrap().on_deny, OnDeny::Stop); assert_eq!( Profile::parse("on_deny = \"continue\"").unwrap().on_deny, OnDeny::Continue ); assert!(Profile::parse("on_deny = \"ignore\"").is_err()); } #[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("sandbox=false\nyolo=true").is_err()); assert!(Profile::parse("bogus=1").is_err()); } #[test] fn flags_follow_sandbox_setting() { let f = |s| Profile::parse(s).unwrap().hx_flags(); assert_eq!(f("sandbox=true"), ["--sandbox", "--yolo"]); assert_eq!(f("sandbox=true\nyolo=false"), ["--sandbox"]); assert_eq!(f("sandbox=false"), ["--auto"]); } #[test] fn bwrap_lookup_scans_path() { let dir = std::env::temp_dir().join(format!("orch-bwrap-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); assert!(!has_bwrap(dir.to_str().unwrap())); std::fs::write(dir.join("bwrap"), "").unwrap(); assert!(has_bwrap(&format!("/nonexistent:{}", dir.display()))); } #[test] fn rejects_path_like_names() { assert!(Profile::load("../x").is_err()); } #[test] fn add_allow_keeps_the_file_and_refuses_what_would_change_its_meaning() { let dir = std::env::temp_dir().join(format!("orch-addallow-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let f = dir.join("p.toml"); std::fs::write( &f, "# mine\nhx = \"hx\"\nallow = [\"read\", \"edit\"] # tools\n[budget]\nmax_turns = 3\n", ) .unwrap(); assert!(add_allow_at(&f, "bash:cargo *").unwrap()); assert!(!add_allow_at(&f, "bash:cargo *").unwrap(), "already there"); let text = std::fs::read_to_string(&f).unwrap(); assert!( text.contains("# mine") && text.contains("# tools") && text.contains("max_turns = 3"), "{text}" ); let p = Profile::parse(&text).unwrap(); assert_eq!(p.allow.unwrap(), ["read", "edit", "bash:cargo *"]); assert!(add_allow_at(&f, "bad entry").is_err()); assert!( add_allow_at(&f, "edit:x").is_err(), "only bash takes a pattern" ); std::fs::write(&f, "hx = \"hx\"\n").unwrap(); assert!( add_allow_at(&f, "read") .unwrap_err() .to_string() .contains("no `allow` list") ); assert!(add_allow_at(&dir.join("none.toml"), "read").is_err()); let _ = std::fs::remove_dir_all(&dir); } }