Skip to main content

agent_works/
env_ref.rs

1//! `${ENV:VAR}` — product-layer resolution interface (P1).
2//!
3//! Contract (design "`${ENV:VAR}` resolution spec"):
4//! - **Resolution happens at the product layer**: the framework takes
5//!   literals. The product calls this module to pre-resolve once at connection
6//!   setup / tool registration, and hands the literal to the framework;
7//! - timing = once at registration; **unset → report which variable is missing**
8//!   (connection failure) — it does not wait until call time to blow up;
9//! - **No recursive expansion**: resolved values are inserted as-is; `${ENV:}`
10//!   inside a value is left untouched;
11//! - Only the `${ENV:NAME}` form is recognized; `${param}` (tool-parameter
12//!   substitution), `$FOO`, `${FOO}` are all kept as-is — two substitution
13//!   syntaxes, two timings, neither swallows the other.
14
15use std::collections::BTreeMap;
16
17/// Reference errors. fail-closed: a malformed reference is not "treat it as a
18/// literal" — it is an error.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum EnvRefError {
21    /// The environment variable in `${ENV:NAME}` is not set. Carries the
22    /// variable name, so the error tells the user exactly which one to provide.
23    MissingVar { name: String },
24    /// `${ENV:}` (empty name).
25    EmptyName,
26    /// `${ENV:` without a closing `}`.
27    Unclosed,
28}
29
30impl std::fmt::Display for EnvRefError {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        match self {
33            Self::MissingVar { name } => {
34                write!(
35                    f,
36                    "environment variable `{name}` is not set (required by ${{ENV:{name}}})"
37                )
38            }
39            Self::EmptyName => write!(f, "empty environment variable name in `${{ENV:}}`"),
40            Self::Unclosed => write!(
41                f,
42                "unclosed environment reference `${{ENV:…` (missing `}}`)"
43            ),
44        }
45    }
46}
47
48impl std::error::Error for EnvRefError {}
49
50const OPEN: &str = "${ENV:";
51
52/// Resolve the `${ENV:NAME}` references in a string.
53///
54/// `lookup` is the value accessor (tests inject a dictionary, the product uses
55/// [`system_env`]). One string may hold several references; inserted values are
56/// **not re-scanned** (no recursive expansion). Any missing variable errors out
57/// immediately, and the error carries the variable name.
58pub fn resolve_env_refs<F>(input: &str, lookup: F) -> Result<String, EnvRefError>
59where
60    F: Fn(&str) -> Option<String>,
61{
62    let mut out = String::with_capacity(input.len());
63    let mut rest = input;
64    while let Some(start) = rest.find(OPEN) {
65        out.push_str(&rest[..start]);
66        let after = &rest[start + OPEN.len()..];
67        let Some(end) = after.find('}') else {
68            return Err(EnvRefError::Unclosed);
69        };
70        let name = &after[..end];
71        if name.is_empty() {
72            return Err(EnvRefError::EmptyName);
73        }
74        match lookup(name) {
75            Some(value) => out.push_str(&value), // inserted as-is, no second expansion
76            None => {
77                return Err(EnvRefError::MissingVar {
78                    name: name.to_string(),
79                });
80            }
81        }
82        rest = &after[end + 1..];
83    }
84    out.push_str(rest);
85    Ok(out)
86}
87
88/// Resolve one env/headers map value by value. Keys are untouched; only values
89/// are resolved.
90pub fn resolve_env_map<F>(
91    map: &BTreeMap<String, String>,
92    lookup: F,
93) -> Result<BTreeMap<String, String>, EnvRefError>
94where
95    F: Fn(&str) -> Option<String>,
96{
97    map.iter()
98        .map(|(k, v)| Ok((k.clone(), resolve_env_refs(v, &lookup)?)))
99        .collect()
100}
101
102/// Process-environment accessor (the product layer's default).
103pub fn system_env(name: &str) -> Option<String> {
104    std::env::var(name).ok()
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    fn lookup<'a>(dict: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
112        move |name| {
113            dict.iter()
114                .find(|(k, _)| *k == name)
115                .map(|(_, v)| (*v).to_string())
116        }
117    }
118
119    #[test]
120    fn resolves_single_and_multiple_refs() {
121        let got = resolve_env_refs("tok=${ENV:TOK} and ${ENV:HOME}", |n| match n {
122            "TOK" => Some("abc".into()),
123            "HOME" => Some("/home/me".into()),
124            _ => None,
125        })
126        .unwrap();
127        assert_eq!(got, "tok=abc and /home/me");
128    }
129
130    #[test]
131    fn missing_var_names_the_variable() {
132        let err = resolve_env_refs("${ENV:NOTION_TOKEN}", |_| None).unwrap_err();
133        assert_eq!(
134            err,
135            EnvRefError::MissingVar {
136                name: "NOTION_TOKEN".into()
137            }
138        );
139        assert!(err.to_string().contains("NOTION_TOKEN"));
140    }
141
142    #[test]
143    fn does_not_recurse_into_resolved_values() {
144        // A value containing ${ENV:} is not expanded again (no recursion).
145        let got = resolve_env_refs("${ENV:A}", lookup(&[("A", "${ENV:B}"), ("B", "x")])).unwrap();
146        assert_eq!(got, "${ENV:B}");
147    }
148
149    #[test]
150    fn leaves_other_syntaxes_untouched() {
151        let input = "${env} $FOO ${FOO} ${param} ${ENVX:Y} ${{ENV:X}";
152        let got = resolve_env_refs(input, |_| Some("SHOULD_NOT_APPEAR".into())).unwrap();
153        // `${ENV:` must not appear (isn't `${ENVX:Y}`'s prefix `${ENV:`? — it is
154        // a substring!). `${ENVX:Y}` starts with `${ENV` but its 6th char is `X` not `:`
155        assert_eq!(got, input);
156    }
157
158    #[test]
159    fn malformed_refs_fail_closed() {
160        assert_eq!(
161            resolve_env_refs("pre${ENV:NO_CLOSE", |_| None).unwrap_err(),
162            EnvRefError::Unclosed
163        );
164        assert_eq!(
165            resolve_env_refs("${ENV:}", |_| None).unwrap_err(),
166            EnvRefError::EmptyName
167        );
168        // The later malformed ref must also error, not be silently truncated
169        assert_eq!(
170            resolve_env_refs("ok${ENV:A}bad${ENV:", |_| Some("v".into())).unwrap_err(),
171            EnvRefError::Unclosed
172        );
173    }
174
175    #[test]
176    fn resolves_map_values_only() {
177        let map = BTreeMap::from([
178            (
179                "NOTION_TOKEN".to_string(),
180                "${ENV:NOTION_TOKEN}".to_string(),
181            ),
182            ("plain".to_string(), "literal".to_string()),
183        ]);
184        let got = resolve_env_map(&map, lookup(&[("NOTION_TOKEN", "tok-1")])).unwrap();
185        assert_eq!(got.get("NOTION_TOKEN").unwrap(), "tok-1");
186        assert_eq!(got.get("plain").unwrap(), "literal");
187
188        let err = resolve_env_map(&map, |_| None).unwrap_err();
189        assert_eq!(
190            err,
191            EnvRefError::MissingVar {
192                name: "NOTION_TOKEN".into()
193            }
194        );
195    }
196
197    #[test]
198    fn empty_input_and_no_refs_pass_through() {
199        assert_eq!(resolve_env_refs("", |_| None).unwrap(), "");
200        assert_eq!(
201            resolve_env_refs("plain text", |_| None).unwrap(),
202            "plain text"
203        );
204    }
205}