Files
orch/src/profile.rs
T
johannesandClaude Sonnet 5.5 cfb735cdb3 TUI hosts sessions: new-session form, named worktrees, resume, faster permissions
- Use the terminal's own colors and background; the key bar and the Needs-you
  panel wrap, fixed-width panels shrink on narrow terminals.
- Sessions run on threads of the TUI (tui/host.rs), capped by the profile's
  `workers`; quitting asks for `yes` and suspends them. New `suspend` command
  keeps the state so a session can be resumed.
- `N` opens a new-session form: machine, name, --after, a named branch or
  worktree (place.rs; never deleted by orch), and a "keep for a PR" option.
- `u` resumes suspended sessions and ones whose process died.
- `A` allows identical permission requests across sessions, `P` saves an allow
  rule to the profile with toml_edit (comments kept).
- Fix clippy lint in report.rs so tests/all.sh passes; add GLOSSARY.md.

Includes the already staged `orch init` work (init.rs, example profile).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:04:41 +01:00

262 lines
9.3 KiB
Rust

//! Profile: `<config>/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;
/// [`Profile::add_allow`] on a file.
fn add_allow_at(path: &std::path::Path, entry: &str) -> Result<bool> {
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)
}
#[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<u64>,
/// Max `turn_start` events over the whole run (all attempts) before hx is killed.
pub max_turns: Option<u64>,
/// Max input+output tokens over the whole run, summed over `stream/done` events.
pub max_tokens: Option<u64>,
}
#[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<PathBuf>,
pub provider: Option<String>,
#[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<String>,
/// 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<Vec<String>>,
/// 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<PathBuf>,
/// 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<String>,
/// 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<String>,
/// Max simultaneous runs on the account across all orch processes (default = workers).
pub max_concurrent: Option<u32>,
#[serde(default)]
pub budget: Budget,
/// Default repo for tasks that name none (`orch pull`).
pub repo: Option<PathBuf>,
pub source: Option<crate::adapter::Adapter>,
pub sink: Option<crate::adapter::Adapter>,
}
fn one() -> u32 {
1
}
fn default_retries() -> u32 {
2
}
fn default_hx() -> String {
"hx".into()
}
impl Profile {
pub fn parse(s: &str) -> Result<Self> {
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<Self> {
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())
}
/// 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<bool> {
if name.is_empty() || name.contains(['/', '.']) {
bail!("bad profile name {name:?}");
}
let path = crate::config_dir()
.join("profiles")
.join(format!("{name}.toml"));
add_allow_at(&path, 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("yolo=true").is_err());
assert!(Profile::parse("bogus=1").is_err());
}
#[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);
}
}