Skip to main content

adk_code/embedded_python/
prompt.rs

1//! Prompt-snippet rendering for the Monty executors.
2//!
3//! Both executor products describe their **built** capabilities through
4//! [`CodeExecutor::prompt_snippet`](crate::CodeExecutor::prompt_snippet) —
5//! grants and the host-function registry are immutable after `build_*()`, so
6//! the snippet is rendered once and cached in the shared core. Because the
7//! snippet and the in-interpreter behavior derive from the same configuration,
8//! they cannot drift.
9//!
10//! Environment variable **names only** are rendered — values never appear in
11//! the prompt.
12
13use super::host_fn::FunctionRegistry;
14use super::os_access::OsAccess;
15
16/// The state-persistence wording that differs between the two products.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub(crate) enum ModeWording {
19    /// Fresh interpreter per call.
20    OneShot,
21    /// Interpreter state persists across calls.
22    Repl,
23}
24
25/// The exact `pathlib.Path` surface Monty implements, listed for the model
26/// when any path is mounted (anything else raises `AttributeError`).
27///
28/// Hand-maintained against the `monty` release pinned in `Cargo.toml`
29/// (0.0.21) — re-check this list whenever that pin is bumped, or the prompt
30/// silently drifts from interpreter behavior. Public so other Monty
31/// integrations (`adk-codeact-monty`) render the same list from the same
32/// source.
33pub const SUPPORTED_PATH_METHODS: &str = "  Monty implements only this subset of `pathlib.Path` (any other method raises AttributeError):
34    - Read/query (any mount): `exists()`, `is_file()`, `is_dir()`, `is_symlink()`, `read_text()`, `read_bytes()`, `stat()`, `iterdir()`, `resolve()`, `absolute()`, `open(\"r\")`.
35    - Write (read-write mounts only): `write_text(s)`, `write_bytes(b)`, `append_text(s)`, `append_bytes(b)`, `mkdir(parents=False, exist_ok=False)`, `unlink()`, `rmdir()`, `rename(target)`, `open(\"w\")`/`open(\"a\")`.
36    - Pure path ops (no I/O, always available): the `/` operator and `joinpath(...)`, `is_absolute()`, `with_name()`, `with_stem()`, `with_suffix()`, `as_posix()`, and the properties `.name`, `.parent`, `.stem`, `.suffix`, `.suffixes`, `.parts`.
37";
38
39/// Render the full snippet from the built grants and registry.
40pub(crate) fn render_prompt_snippet(
41    os: &OsAccess,
42    registry: &FunctionRegistry,
43    mode: ModeWording,
44) -> String {
45    let mut snippet = String::from("## Python execution environment\n");
46
47    match mode {
48        ModeWording::Repl => snippet.push_str(
49            "- State: persistent REPL session — variables, functions, and imports persist \
50             across calls. Pass `reset: true` to start fresh.\n",
51        ),
52        ModeWording::OneShot => snippet.push_str(
53            "- State: each call runs in a fresh interpreter — no state persists between calls.\n",
54        ),
55    }
56
57    if os.mounts.is_empty() {
58        snippet.push_str("- Filesystem: no access. Any path access raises OSError.\n");
59    } else {
60        let mounts: Vec<String> = os
61            .mounts
62            .iter()
63            .map(|spec| format!("{} ({})", spec.virtual_path, spec.access.label()))
64            .collect();
65        snippet.push_str(&format!(
66            "- Filesystem: use `pathlib.Path` against these paths only: {}. \
67             Any other path raises OSError (existence checks return False).\n",
68            mounts.join(", ")
69        ));
70        snippet.push_str(SUPPORTED_PATH_METHODS);
71    }
72
73    if os.environ.is_empty() {
74        snippet.push_str("- Environment variables: none available.\n");
75    } else {
76        let names: Vec<&str> = os.environ.keys().map(String::as_str).collect();
77        snippet.push_str(&format!(
78            "- Environment variables: {} (via os.getenv / os.environ).\n",
79            names.join(", ")
80        ));
81    }
82
83    if os.system_clock {
84        snippet
85            .push_str("- Clock: real system time available via datetime.now() / date.today().\n");
86    } else {
87        snippet.push_str(
88            "- Clock: not available — calling datetime.now() or date.today() raises OSError.\n",
89        );
90    }
91
92    snippet.push_str("- Network and subprocess access: unavailable.\n");
93    snippet.push_str(
94        "- The value of the final expression is returned as structured output; print() \
95         output is captured as stdout.\n",
96    );
97
98    if !registry.is_empty() {
99        snippet.push_str(
100            "- Available functions (call synchronously — never use `await`):\n\n```python\n",
101        );
102        for function in registry.iter() {
103            snippet.push_str(&format!(
104                "def {}:\n    \"\"\"{}\"\"\"\n\n",
105                function.signature(),
106                function.description()
107            ));
108        }
109        // Drop the trailing blank line inside the fence.
110        snippet.truncate(snippet.trim_end_matches('\n').len());
111        snippet.push_str("\n```\n");
112    }
113
114    snippet
115}
116
117#[cfg(test)]
118mod tests {
119    use std::collections::BTreeMap;
120    use std::path::PathBuf;
121    use std::sync::Arc;
122
123    use super::super::host_fn::{ClosureHostFunction, HostFunction, HostFunctionError};
124    use super::super::os_access::{MountSpec, PathAccess};
125    use super::*;
126
127    use async_trait::async_trait;
128    use serde_json::{Map, Value, json};
129
130    struct GetWeather;
131
132    #[async_trait]
133    impl HostFunction for GetWeather {
134        fn name(&self) -> &str {
135            "get_weather"
136        }
137        fn description(&self) -> &str {
138            "Current weather for a city."
139        }
140        fn signature(&self) -> String {
141            "get_weather(city: str, unit: str = \"C\") -> dict".to_string()
142        }
143        async fn call(
144            &self,
145            _args: Vec<Value>,
146            _kwargs: Map<String, Value>,
147        ) -> Result<Value, HostFunctionError> {
148            Ok(json!({}))
149        }
150    }
151
152    fn full_access() -> OsAccess {
153        OsAccess {
154            mounts: vec![
155                MountSpec {
156                    virtual_path: "/data".to_string(),
157                    host_path: PathBuf::from("/srv/data"),
158                    access: PathAccess::ReadOnly,
159                },
160                MountSpec {
161                    virtual_path: "/out".to_string(),
162                    host_path: PathBuf::from("/srv/out"),
163                    access: PathAccess::ReadWrite,
164                },
165            ],
166            environ: BTreeMap::from([
167                ("PROJECT".to_string(), "acme-secret-value".to_string()),
168                ("REGION".to_string(), "eu-west-1".to_string()),
169            ]),
170            system_clock: true,
171        }
172    }
173
174    fn registry() -> FunctionRegistry {
175        FunctionRegistry::build(vec![
176            Arc::new(GetWeather),
177            Arc::new(ClosureHostFunction::new(
178                "row_count",
179                "Count rows in the loaded dataset.",
180                |_args, _kwargs| async move { Ok(json!(0)) },
181            )),
182        ])
183        .unwrap()
184    }
185
186    #[test]
187    fn snippet_lists_mounts_with_access_levels() {
188        let snippet = render_prompt_snippet(&full_access(), &registry(), ModeWording::OneShot);
189        assert!(snippet.contains("/data (read-only)"));
190        assert!(snippet.contains("/out (read-write)"));
191    }
192
193    #[test]
194    fn snippet_lists_environ_names_but_never_values() {
195        let snippet = render_prompt_snippet(&full_access(), &registry(), ModeWording::OneShot);
196        assert!(snippet.contains("PROJECT"));
197        assert!(snippet.contains("REGION"));
198        assert!(!snippet.contains("acme-secret-value"));
199        assert!(!snippet.contains("eu-west-1"));
200    }
201
202    #[test]
203    fn clock_line_tracks_the_grant() {
204        let granted = render_prompt_snippet(&full_access(), &registry(), ModeWording::OneShot);
205        assert!(granted.contains("real system time available"));
206
207        let denied = render_prompt_snippet(
208            &OsAccess { system_clock: false, ..full_access() },
209            &registry(),
210            ModeWording::OneShot,
211        );
212        assert!(denied.contains("Clock: not available"));
213    }
214
215    #[test]
216    fn mode_wording_differs_between_products() {
217        let one_shot = render_prompt_snippet(&full_access(), &registry(), ModeWording::OneShot);
218        let repl = render_prompt_snippet(&full_access(), &registry(), ModeWording::Repl);
219        assert!(one_shot.contains("fresh interpreter"));
220        assert!(repl.contains("persistent REPL session"));
221        assert!(repl.contains("reset: true"));
222        assert_ne!(one_shot, repl);
223    }
224
225    #[test]
226    fn function_stubs_render_signature_and_description() {
227        let snippet = render_prompt_snippet(&full_access(), &registry(), ModeWording::Repl);
228        assert!(snippet.contains("def get_weather(city: str, unit: str = \"C\") -> dict:"));
229        assert!(snippet.contains("\"\"\"Current weather for a city.\"\"\""));
230        // Default signature rendering for the closure adapter.
231        assert!(snippet.contains("def row_count(...):"));
232        assert!(snippet.contains("\"\"\"Count rows in the loaded dataset.\"\"\""));
233    }
234
235    #[test]
236    fn fully_sandboxed_default_renders_the_no_access_lines() {
237        let snippet = render_prompt_snippet(
238            &OsAccess::default(),
239            &FunctionRegistry::default(),
240            ModeWording::OneShot,
241        );
242        assert!(snippet.contains("Filesystem: no access"));
243        assert!(snippet.contains("Environment variables: none available"));
244        assert!(snippet.contains("Clock: not available"));
245        assert!(!snippet.contains("Available functions"));
246    }
247
248    #[test]
249    fn pathlib_surface_renders_only_when_a_path_is_mounted() {
250        let with_mounts = render_prompt_snippet(&full_access(), &registry(), ModeWording::OneShot);
251        assert!(with_mounts.contains("subset of `pathlib.Path`"));
252
253        let no_mounts = render_prompt_snippet(
254            &OsAccess { mounts: Vec::new(), ..full_access() },
255            &registry(),
256            ModeWording::OneShot,
257        );
258        assert!(!no_mounts.contains("pathlib.Path"));
259    }
260}