Skip to main content

adk_harness/
config.rs

1//! `HarnessConfig`: the project file `.adk/harness.toml` for a harness an application
2//! builds (spec 3.1 §8.3).
3
4use std::collections::BTreeMap;
5use std::path::Path;
6
7use adk_core::{AdkError, Result};
8use serde::Deserialize;
9
10use crate::mode::HarnessMode;
11
12/// The project file, relative to the workspace root (spec 3.1 §8.3).
13///
14/// # Example
15///
16/// ```rust
17/// assert_eq!(adk_harness::HARNESS_CONFIG_FILE, ".adk/harness.toml");
18/// ```
19pub const HARNESS_CONFIG_FILE: &str = ".adk/harness.toml";
20
21/// The `[deploy]` table is read by deployment tooling (spec 3.1 §8.5), not by the harness.
22const DEPLOY_TABLE: &str = "deploy";
23
24/// Keys `adk-rust` reads from its own config that a project file may not set.
25const LOOSENING_KEYS: [&str; 6] =
26    ["yes", "allow_unsandboxed", "auto_review", "trust", "packs", "members"];
27
28/// What `.adk/harness.toml` asks of a harness (spec 3.1 §8.3), applied with
29/// [`HarnessAgentBuilder::config`](crate::HarnessAgentBuilder::config).
30///
31/// The file sits in the workspace the agent works in, so it may only tighten
32/// (spec 3.1 §9.2 I3): a stricter mode, the OS sandbox, and `fail_if_unavailable`. Keys
33/// that would loosen what the agent may do (`yes`, `allow_unsandboxed`, `auto_review`,
34/// `trust`, `packs`, `members`) and unknown keys are ignored and reported in
35/// [`notes`](Self::notes); set them in code. The `[deploy]` table is left to deployment tooling (spec 3.1 §8.5). An
36/// unknown mode reads as `read_only` (spec 3.1 §9.2 I16).
37///
38/// ```toml
39/// mode = "plan"
40/// sandbox = true
41/// fail_if_unavailable = true
42///
43/// # Sandboxed commands reach only these hosts, through an egress proxy (#1281); turns the
44/// # OS sandbox on.
45/// [network]
46/// allow = ["pypi.org:443", "*.pythonhosted.org:443"]
47///
48/// [deploy]
49/// mode = "plan"
50/// yes_policy = "deny"
51/// ```
52///
53/// # Example
54///
55/// ```rust
56/// use adk_harness::{HarnessConfig, HarnessMode};
57///
58/// let config = HarnessConfig::from_toml("mode = \"plan\"\nmembers = [\"x=acp:evil\"]\n")?;
59/// assert_eq!(config.mode, Some(HarnessMode::Plan));
60/// assert_eq!(config.notes.len(), 1);
61/// # Ok::<(), adk_core::AdkError>(())
62/// ```
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
64#[non_exhaustive]
65pub struct HarnessConfig {
66    /// The mode the file asks for; applied only when it is stricter than the builder's.
67    pub mode: Option<HarnessMode>,
68    /// `sandbox = true`: run `bash` in the OS sandbox.
69    pub sandbox: bool,
70    /// `fail_if_unavailable = true`: refuse to build when the sandbox is unavailable.
71    pub fail_if_unavailable: bool,
72    /// `[network] allow = [...]`: the hosts sandboxed commands may reach, which narrows the
73    /// shell's egress policy and turns the OS sandbox on.
74    pub network_allow: Option<adk_core::egress::EgressPolicy>,
75    /// Settings the file made that were ignored, and why.
76    pub notes: Vec<String>,
77}
78
79/// The file as written; every key optional.
80#[derive(Debug, Default, Deserialize)]
81#[serde(default)]
82struct ConfigFile {
83    mode: Option<String>,
84    sandbox: Option<bool>,
85    fail_if_unavailable: Option<bool>,
86    network: Option<NetworkTable>,
87    /// `[[hooks]]` tables are read by `hooks::HookSet::load_workspace` (spec 3.1 §7.22),
88    /// so they are neither applied here nor reported as unknown.
89    #[serde(default)]
90    #[allow(dead_code)]
91    hooks: Vec<toml::Value>,
92    /// The `[ultracode]` table is read by `adk-rust ultracode` (spec 3.1 §7.10), so it is
93    /// neither applied here nor reported as unknown.
94    #[serde(default)]
95    #[allow(dead_code)]
96    ultracode: Option<toml::Value>,
97    /// The `[compaction]` table is read by the `adk-rust` CLI, which applies it with
98    /// `HarnessAgentBuilder::intra_compaction`, so it is neither applied here nor reported as
99    /// unknown.
100    #[serde(default)]
101    #[allow(dead_code)]
102    compaction: Option<toml::Value>,
103    /// The `[goal]` table (the rubric goals in this workspace are graded against) is read by
104    /// the `adk-rust` CLI, so it is neither applied here nor reported as unknown.
105    #[serde(default)]
106    #[allow(dead_code)]
107    goal: Option<toml::Value>,
108    #[serde(flatten)]
109    other: BTreeMap<String, toml::Value>,
110}
111
112/// The `[network]` table.
113#[derive(Debug, Default, Deserialize)]
114#[serde(default, deny_unknown_fields)]
115struct NetworkTable {
116    allow: Vec<String>,
117}
118
119impl HarnessConfig {
120    /// Reads `<dir>/.adk/harness.toml`; a missing file is the default configuration.
121    ///
122    /// # Example
123    ///
124    /// ```rust
125    /// let dir = tempfile::tempdir().unwrap();
126    /// let config = adk_harness::HarnessConfig::discover(dir.path())?;
127    /// assert_eq!(config, adk_harness::HarnessConfig::default());
128    /// # Ok::<(), adk_core::AdkError>(())
129    /// ```
130    ///
131    /// # Errors
132    ///
133    /// Returns a configuration error when the file cannot be read or is not valid TOML.
134    pub fn discover(dir: impl AsRef<Path>) -> Result<Self> {
135        let path = dir.as_ref().join(HARNESS_CONFIG_FILE);
136        match std::fs::read_to_string(&path) {
137            Ok(text) => Self::from_toml(&text)
138                .map_err(|error| AdkError::config(format!("{}: {error}", path.display()))),
139            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
140            Err(error) => {
141                Err(AdkError::config(format!("failed to read {}: {error}", path.display())))
142            }
143        }
144    }
145
146    /// Parses the contents of a `.adk/harness.toml`.
147    ///
148    /// # Example
149    ///
150    /// ```rust
151    /// let config = adk_harness::HarnessConfig::from_toml("sandbox = true")?;
152    /// assert!(config.sandbox);
153    /// # Ok::<(), adk_core::AdkError>(())
154    /// ```
155    ///
156    /// # Errors
157    ///
158    /// Returns a configuration error when `text` is not valid harness configuration.
159    pub fn from_toml(text: &str) -> Result<Self> {
160        let file: ConfigFile = toml::from_str(text).map_err(|error| {
161            AdkError::config(format!("not valid harness configuration: {error}"))
162        })?;
163        let mut notes = Vec::new();
164        let mode = file.mode.as_deref().map(|value| {
165            value.trim().parse::<HarnessMode>().unwrap_or_else(|_| {
166                notes.push(format!(
167                    "{HARNESS_CONFIG_FILE}: unknown mode `{value}` read as read_only; use \
168                     read_only, plan, ask or auto"
169                ));
170                HarnessMode::ReadOnly
171            })
172        });
173        for key in file.other.keys().filter(|key| *key != DEPLOY_TABLE) {
174            notes.push(if LOOSENING_KEYS.contains(&key.as_str()) {
175                format!(
176                    "{HARNESS_CONFIG_FILE}: `{key}` ignored — it would loosen what the agent may \
177                     do, and workspace files may only tighten. Set it in code"
178                )
179            } else {
180                format!("{HARNESS_CONFIG_FILE}: unknown key `{key}` ignored")
181            });
182        }
183        let network_allow = file
184            .network
185            .map(|network| adk_core::egress::EgressPolicy::allowlist(&network.allow))
186            .transpose()
187            .map_err(|error| {
188                AdkError::config(format!("{HARNESS_CONFIG_FILE}: [network]: {error}"))
189            })?;
190        Ok(Self {
191            mode,
192            sandbox: file.sandbox.unwrap_or(false) || network_allow.is_some(),
193            fail_if_unavailable: file.fail_if_unavailable.unwrap_or(false),
194            network_allow,
195            notes,
196        })
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn a_network_allowlist_turns_the_sandbox_on_and_must_parse() {
206        let config = HarnessConfig::from_toml(
207            "[network]\nallow = [\"pypi.org:443\", \"*.pythonhosted.org\"]\n",
208        )
209        .unwrap();
210        assert!(config.sandbox);
211        let policy = config.network_allow.expect("the allowlist is read");
212        assert!(policy.check_url("https://files.pythonhosted.org/a").is_ok());
213        assert!(policy.check_url("https://example.com/").is_err());
214        assert!(HarnessConfig::from_toml("[network]\nallow = [\"https://pypi.org\"]\n").is_err());
215        assert!(HarnessConfig::from_toml("[network]\ndeny = []\n").is_err());
216        assert_eq!(HarnessConfig::from_toml("").unwrap().network_allow, None);
217    }
218
219    #[test]
220    fn the_file_can_only_tighten_and_reports_what_it_ignored() {
221        let config = HarnessConfig::from_toml(
222            "mode = \"plan\"\nsandbox = true\nfail_if_unavailable = true\nyes = true\n\
223             trust = true\nallow_unsandboxed = true\npacks = [\"payments\"]\n\
224             members = [\"x=acp:evil\"]\nsurprise = 1\n\n[deploy]\nmode = \"plan\"\n",
225        )
226        .unwrap();
227        assert_eq!(
228            (config.mode, config.sandbox, config.fail_if_unavailable),
229            (Some(HarnessMode::Plan), true, true)
230        );
231        for key in ["yes", "trust", "allow_unsandboxed", "packs", "members", "surprise"] {
232            assert!(
233                config.notes.iter().any(|note| note.contains(&format!("`{key}`"))),
234                "{key}: {:?}",
235                config.notes
236            );
237        }
238        assert!(!config.notes.iter().any(|note| note.contains("deploy")), "{:?}", config.notes);
239    }
240
241    #[test]
242    fn the_builder_applies_only_what_tightens() {
243        let dir = tempfile::tempdir().unwrap();
244        let build = |text: &str, mode: HarnessMode| {
245            let model =
246                adk_model::ScriptedLlm::new("scripted", Vec::<adk_model::ScriptedResponse>::new());
247            crate::HarnessAgent::builder("harness")
248                .model(std::sync::Arc::new(model))
249                .workspace(adk_devtools::Workspace::new(dir.path()).allow_bash(true))
250                .project_instructions(crate::InstructionsConfig {
251                    user_file: None,
252                    ..crate::InstructionsConfig::default()
253                })
254                .mode(mode)
255                .config(HarnessConfig::from_toml(text).unwrap())
256                .build()
257                .unwrap()
258        };
259        assert_eq!(
260            build("mode = \"auto\"", HarnessMode::Ask).info().default_mode,
261            HarnessMode::Ask
262        );
263        assert_eq!(
264            build("mode = \"read_only\"", HarnessMode::Ask).info().default_mode,
265            HarnessMode::ReadOnly
266        );
267        assert_eq!(build("", HarnessMode::Ask).info().isolation, crate::IsolationStatus::Host);
268        #[cfg(feature = "sandbox")]
269        assert_ne!(
270            build("sandbox = true", HarnessMode::Ask).info().isolation,
271            crate::IsolationStatus::Host,
272            "sandbox = true must request the OS sandbox"
273        );
274    }
275
276    #[test]
277    fn the_ultracode_table_is_known() {
278        let config = HarnessConfig::from_toml("[ultracode]\nmax_rounds = 1\n").unwrap();
279        assert!(config.notes.is_empty(), "{:?}", config.notes);
280    }
281
282    #[test]
283    fn an_unknown_mode_reads_as_read_only() {
284        let config = HarnessConfig::from_toml("mode = \"yolo\"").unwrap();
285        assert_eq!(config.mode, Some(HarnessMode::ReadOnly));
286        assert_eq!(config.notes.len(), 1);
287    }
288
289    #[test]
290    fn a_missing_file_is_the_default_and_a_broken_one_an_error() {
291        let dir = tempfile::tempdir().unwrap();
292        assert_eq!(HarnessConfig::discover(dir.path()).unwrap(), HarnessConfig::default());
293        std::fs::create_dir_all(dir.path().join(".adk")).unwrap();
294        std::fs::write(dir.path().join(HARNESS_CONFIG_FILE), "mode = ").unwrap();
295        let error = HarnessConfig::discover(dir.path()).unwrap_err();
296        assert!(error.to_string().contains("harness.toml"), "{error}");
297    }
298}