Skip to main content

adk_code/
embedded_python.rs

1//! Embedded Python executors backed by the Pydantic Monty interpreter.
2//!
3//! [`MontyExecutorBuilder`] configures OS-access grants, host functions, and
4//! resource limits once, then produces either executor product:
5//!
6//! - [`build_one_shot`](MontyExecutorBuilder::build_one_shot) →
7//!   [`MontyOneShotExecutor`] — a fresh interpreter per
8//!   [`execute`](crate::CodeExecutor::execute) call, no state persists;
9//! - [`build_repl`](MontyExecutorBuilder::build_repl) →
10//!   [`MontyReplExecutor`] — interpreter state (variables, function
11//!   definitions, imports) persists across calls.
12//!
13//! # Security Model
14//!
15//! Isolation combines **explicit policy** with **enforcement by omission**:
16//!
17//! - **Explicit policy.** Every OS call Monty can emit — filesystem
18//!   reads/writes, `os.getenv`/`os.environ`, `date.today()`/`datetime.now()` —
19//!   is serviced in place against the filesystem roots, environment variables,
20//!   and clock the host grants at construction. Ungranted access raises a
21//!   catchable Python `OSError` in-script.
22//! - **Enforcement by omission.** Monty has no network or subprocess surface
23//!   at all, so those remain impossible regardless of configuration.
24//! - **Grants vs. request policy.** The builder's grants are the maximum
25//!   access any script can have; the per-request
26//!   [`SandboxPolicy`] may only *narrow* within them. A grant covers its
27//!   entire directory subtree, so a request for a granted mount or any
28//!   subdirectory of one succeeds. A request exceeding the grants is rejected
29//!   fail-closed with [`ExecutionError::UnsupportedPolicy`] naming the excess
30//!   path or variable, before any code runs. `FilesystemPolicy::None` /
31//!   `EnvironmentPolicy::None` simply grant nothing for that call.
32//! - **Boundary enforcement is delegated.** The mount boundary
33//!   (canonicalization + symlink-escape detection) is enforced by the
34//!   `monty-fs` crate, pinned to an exact `0.0.x` release in `Cargo.toml`.
35//!   Bumping that pin is a security-relevant change and warrants re-review of
36//!   its path-resolution behavior.
37//! - **Host functions run as host code.** Registered [`HostFunction`]s are the
38//!   *user's own* trust boundary, not Monty's — the interpreter sandbox does
39//!   not contain their side effects.
40//! - **Timeouts.** `SandboxPolicy::timeout` bounds *interpreter* time via
41//!   Monty's `ResourceLimits::max_duration` (real preemption). Host-function
42//!   execution gets its own wall-clock bound
43//!   ([`host_function_timeout`](MontyExecutorBuilder::host_function_timeout)).
44//! - **REPL memory accounting.** The resource tracker is serialized with the
45//!   session, so `max_memory` bounds the *cumulative* session heap, not
46//!   per-call allocation. The per-call time budget is reset on every call.
47//!
48//! # Example
49//!
50//! ```rust,no_run
51//! use std::sync::Arc;
52//! use adk_code::{MontyExecutorBuilder, PathAccess};
53//! use serde_json::json;
54//!
55//! # fn main() -> Result<(), adk_code::MontyBuildError> {
56//! let builder = MontyExecutorBuilder::new()
57//!     .allow_path("/data", "/srv/agent/data", PathAccess::ReadOnly)
58//!     .allow_path("/out", "/srv/agent/out", PathAccess::ReadWrite)
59//!     .environ_var("PROJECT", "acme")
60//!     .system_clock()
61//!     .function_fn("row_count", "Count rows in the loaded dataset.", |args, _kwargs| async move {
62//!         Ok(json!(args.len()))
63//!     })
64//!     .max_memory(64 * 1024 * 1024);
65//!
66//! let one_shot = builder.clone().build_one_shot()?;
67//! let repl = builder.build_repl()?;
68//! # Ok(())
69//! # }
70//! ```
71
72mod convert;
73mod drive;
74mod host_fn;
75mod os_access;
76mod prompt;
77
78// The Monty crates, re-exported so every consumer of this module's public
79// surface (which speaks `MontyObject`, `OsFunctionCall`, `MountTable`, ...)
80// names the exact release this crate was built against — the version is
81// stated once, here, and cannot drift between crates.
82pub use {monty, monty_fs, monty_types};
83
84use std::fmt;
85use std::future::Future;
86use std::path::PathBuf;
87use std::sync::Arc;
88use std::time::{Duration, Instant};
89
90use async_trait::async_trait;
91use monty_types::ResourceLimits;
92use serde_json::{Map, Value};
93use tokio::sync::Mutex;
94use tracing::debug;
95
96use crate::{
97    BackendCapabilities, CodeExecutor, EnvironmentPolicy, ExecutionError, ExecutionIsolation,
98    ExecutionLanguage, ExecutionPayload, ExecutionRequest, ExecutionResult, ExecutionStatus,
99    FilesystemPolicy, SandboxPolicy, validate_request,
100};
101
102use drive::{CappedStdout, DriveEnd, PausedCall, ReplSegment, RunSegment, Tracker};
103use host_fn::FunctionRegistry;
104use os_access::OsAccess;
105use prompt::ModeWording;
106
107pub use convert::{json_to_monty, monty_to_json};
108pub use host_fn::{HostFunction, HostFunctionError, MontyBuildError};
109pub use os_access::{PathAccess, resolve_os_call};
110pub use prompt::SUPPORTED_PATH_METHODS;
111
112/// Default wall-clock bound for a single host-function call.
113const DEFAULT_HOST_FUNCTION_TIMEOUT: Duration = Duration::from_secs(30);
114
115/// Default cumulative memory cap. LLM-generated Python can contain a runaway
116/// allocation; this keeps a run bounded. Override with
117/// [`MontyExecutorBuilder::max_memory`].
118const DEFAULT_MAX_MEMORY: usize = 256 * 1024 * 1024;
119
120/// Configures OS-access grants, host functions, and resource limits for the
121/// Monty executors, then produces either product with a terminal build method.
122///
123/// The builder is cheaply cloneable (grants are small, the registry holds
124/// `Arc<dyn HostFunction>`), so one configuration can mint many executors.
125///
126/// Defaults are fully sandboxed: no filesystem mounts, an empty environment,
127/// and no clock.
128///
129/// # Example
130///
131/// ```rust
132/// use adk_code::MontyExecutorBuilder;
133///
134/// # fn main() -> Result<(), adk_code::MontyBuildError> {
135/// let one_shot = MontyExecutorBuilder::new().build_one_shot()?;
136/// let repl = MontyExecutorBuilder::new().build_repl()?;
137/// # Ok(())
138/// # }
139/// ```
140#[derive(Clone)]
141pub struct MontyExecutorBuilder {
142    os: OsAccess,
143    functions: Vec<Arc<dyn HostFunction>>,
144    max_memory: Option<usize>,
145    host_function_timeout: Duration,
146    script_name: String,
147}
148
149impl fmt::Debug for MontyExecutorBuilder {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.debug_struct("MontyExecutorBuilder")
152            .field("os", &self.os)
153            .field("functions", &self.functions.iter().map(|hf| hf.name()).collect::<Vec<_>>())
154            .field("max_memory", &self.max_memory)
155            .field("host_function_timeout", &self.host_function_timeout)
156            .field("script_name", &self.script_name)
157            .finish()
158    }
159}
160
161impl Default for MontyExecutorBuilder {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167impl MontyExecutorBuilder {
168    /// Start with the fully sandboxed defaults: no filesystem mounts, an empty
169    /// environment map, and no clock.
170    #[must_use]
171    pub fn new() -> Self {
172        Self {
173            os: OsAccess::default(),
174            functions: Vec::new(),
175            max_memory: Some(DEFAULT_MAX_MEMORY),
176            host_function_timeout: DEFAULT_HOST_FUNCTION_TIMEOUT,
177            script_name: "python_snippet".to_string(),
178        }
179    }
180
181    /// Make a host directory available to scripts at `virtual_path`.
182    ///
183    /// `virtual_path` is the absolute path a script uses (e.g. `/data`);
184    /// `host_path` is the real directory it maps to. The mount boundary is
185    /// enforced by Monty (canonicalization + symlink-escape detection) — a
186    /// script can never escape it. Call repeatedly to expose several
187    /// directories.
188    ///
189    /// Virtual paths are validated at `build_*()`: each must be a normalized
190    /// absolute path (no trailing slash, no `.` or `..` components) unique
191    /// across mounts.
192    #[must_use]
193    pub fn allow_path(
194        mut self,
195        virtual_path: impl Into<String>,
196        host_path: impl Into<PathBuf>,
197        access: PathAccess,
198    ) -> Self {
199        self.os.mounts.push(os_access::MountSpec {
200            virtual_path: virtual_path.into(),
201            host_path: host_path.into(),
202            access,
203        });
204        self
205    }
206
207    /// Replace the environment map exposed via `os.getenv` / `os.environ`.
208    ///
209    /// Only the entries provided here are visible to scripts; the host process
210    /// environment is never exposed implicitly.
211    #[must_use]
212    pub fn environ<K, V>(mut self, vars: impl IntoIterator<Item = (K, V)>) -> Self
213    where
214        K: Into<String>,
215        V: Into<String>,
216    {
217        self.os.environ = vars.into_iter().map(|(k, v)| (k.into(), v.into())).collect();
218        self
219    }
220
221    /// Add or overwrite a single environment variable.
222    #[must_use]
223    pub fn environ_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
224        self.os.environ.insert(key.into(), value.into());
225        self
226    }
227
228    /// Grant host-clock access: `date.today()` and `datetime.now()` read the
229    /// real system time. Without this grant they raise a catchable `OSError`.
230    #[must_use]
231    pub fn system_clock(mut self) -> Self {
232        self.os.system_clock = true;
233        self
234    }
235
236    /// Register a host function callable from Python by bare name.
237    ///
238    /// Registered names are validated at `build_*()`: they must be valid
239    /// Python identifiers, unique, and must not collide with built-ins.
240    #[must_use]
241    pub fn function(mut self, function: Arc<dyn HostFunction>) -> Self {
242        self.functions.push(function);
243        self
244    }
245
246    /// Register a closure as a host function — the common case.
247    ///
248    /// # Example
249    ///
250    /// ```rust
251    /// use adk_code::MontyExecutorBuilder;
252    /// use serde_json::json;
253    ///
254    /// # fn main() -> Result<(), adk_code::MontyBuildError> {
255    /// let executor = MontyExecutorBuilder::new()
256    ///     .function_fn("double", "Double a number.", |args, _kwargs| async move {
257    ///         let n = args.first().and_then(|v| v.as_i64()).unwrap_or(0);
258    ///         Ok(json!(n * 2))
259    ///     })
260    ///     .build_one_shot()?;
261    /// # let _ = executor;
262    /// # Ok(())
263    /// # }
264    /// ```
265    #[must_use]
266    pub fn function_fn<F, Fut>(
267        self,
268        name: impl Into<String>,
269        description: impl Into<String>,
270        func: F,
271    ) -> Self
272    where
273        F: Fn(Vec<Value>, Map<String, Value>) -> Fut + Send + Sync + 'static,
274        Fut: Future<Output = Result<Value, HostFunctionError>> + Send + 'static,
275    {
276        self.function(Arc::new(host_fn::ClosureHostFunction::new(name, description, func)))
277    }
278
279    /// Cap the interpreter's memory use in bytes (default 256 MiB).
280    ///
281    /// For a REPL executor this bounds the cumulative session heap. Exceeding
282    /// it raises Python's `MemoryError` (the result reports `Failed`).
283    #[must_use]
284    pub fn max_memory(mut self, bytes: usize) -> Self {
285        self.max_memory = Some(bytes);
286        self
287    }
288
289    /// Wall-clock bound for a single host-function call (default 30 s), so a
290    /// hung user function cannot wedge `execute()`. On expiry the script
291    /// receives a catchable exception.
292    #[must_use]
293    pub fn host_function_timeout(mut self, timeout: Duration) -> Self {
294        self.host_function_timeout = timeout;
295        self
296    }
297
298    /// The script name used in tracebacks (default `"python_snippet"`).
299    #[must_use]
300    pub fn script_name(mut self, name: impl Into<String>) -> Self {
301        self.script_name = name.into();
302        self
303    }
304
305    /// Build the one-shot product: a fresh interpreter per `execute()` call.
306    ///
307    /// # Errors
308    ///
309    /// Returns a [`MontyBuildError`] when the host-function registry is
310    /// invalid (invalid identifier, duplicate name, built-in collision,
311    /// reserved name) or a mount's virtual path is not a normalized,
312    /// unique absolute path.
313    pub fn build_one_shot(self) -> Result<MontyOneShotExecutor, MontyBuildError> {
314        Ok(MontyOneShotExecutor { core: self.build_core(ModeWording::OneShot)? })
315    }
316
317    /// Build the REPL product: interpreter state persists across `execute()`
318    /// calls.
319    ///
320    /// # Errors
321    ///
322    /// Returns a [`MontyBuildError`] when the host-function registry is
323    /// invalid (invalid identifier, duplicate name, built-in collision,
324    /// reserved name) or a mount's virtual path is not a normalized,
325    /// unique absolute path.
326    pub fn build_repl(self) -> Result<MontyReplExecutor, MontyBuildError> {
327        Ok(MontyReplExecutor {
328            core: self.build_core(ModeWording::Repl)?,
329            repl_state: Mutex::new(None),
330        })
331    }
332
333    fn build_core(self, mode: ModeWording) -> Result<Arc<MontyCore>, MontyBuildError> {
334        os_access::validate_mounts(&self.os.mounts)?;
335        let registry = FunctionRegistry::build(self.functions)?;
336        let prompt_snippet = prompt::render_prompt_snippet(&self.os, &registry, mode);
337        let mut base_limits = ResourceLimits::default();
338        if let Some(bytes) = self.max_memory {
339            base_limits = base_limits.max_memory(bytes);
340        }
341        Ok(Arc::new(MontyCore {
342            grants: self.os,
343            registry,
344            base_limits,
345            script_name: self.script_name,
346            host_function_timeout: self.host_function_timeout,
347            prompt_snippet,
348        }))
349    }
350}
351
352/// The immutable configuration shared by both executor products: grants,
353/// host-function registry, resource limits, and the cached prompt snippet.
354#[derive(Debug)]
355struct MontyCore {
356    grants: OsAccess,
357    registry: FunctionRegistry,
358    /// Memory (and other non-time) limits; `max_duration` is applied
359    /// per-request from `SandboxPolicy::timeout`.
360    base_limits: ResourceLimits,
361    script_name: String,
362    host_function_timeout: Duration,
363    prompt_snippet: String,
364}
365
366impl MontyCore {
367    /// A fresh tracker for one call, with the request's time budget.
368    fn tracker(&self, timeout: Duration) -> Tracker {
369        Tracker::new(self.base_limits.clone().max_duration(timeout))
370    }
371
372    /// A [`SandboxPolicy`] requesting exactly this executor's grants —
373    /// what a caller passes to use everything the executor offers.
374    fn granted_policy(&self) -> SandboxPolicy {
375        let mut policy = SandboxPolicy::strict_python();
376        if !self.grants.mounts.is_empty() {
377            let mut read_only = Vec::new();
378            let mut read_write = Vec::new();
379            for mount in &self.grants.mounts {
380                let path = PathBuf::from(&mount.virtual_path);
381                match mount.access {
382                    PathAccess::ReadOnly => read_only.push(path),
383                    PathAccess::ReadWrite => read_write.push(path),
384                }
385            }
386            policy.filesystem = FilesystemPolicy::Paths { read_only, read_write };
387        }
388        if !self.grants.environ.is_empty() {
389            policy.environment =
390                EnvironmentPolicy::AllowList(self.grants.environ.keys().cloned().collect());
391        }
392        policy
393    }
394
395    /// Await a registered host function with the configured wall-clock bound.
396    /// The `Err` message becomes a catchable in-script exception.
397    async fn call_host_function(
398        &self,
399        name: &str,
400        args: Vec<Value>,
401        kwargs: Map<String, Value>,
402    ) -> Result<Value, String> {
403        // The drive loop only pauses for registered names, so the lookup
404        // cannot fail in practice; fail soft if it somehow does.
405        let Some(function) = self.registry.get(name) else {
406            return Err(self.registry.unknown_function_message(name));
407        };
408        debug!(host_fn.name = %name, args.count = args.len(), "calling host function");
409        match tokio::time::timeout(self.host_function_timeout, function.call(args, kwargs)).await {
410            Ok(Ok(value)) => Ok(value),
411            Ok(Err(err)) => Err(err.to_string()),
412            Err(_) => Err(format!(
413                "host function '{name}' timed out after {:?}",
414                self.host_function_timeout
415            )),
416        }
417    }
418}
419
420/// Shared capability report; only the persistence flags differ by mode.
421fn monty_capabilities(persistent: bool) -> BackendCapabilities {
422    BackendCapabilities {
423        isolation: ExecutionIsolation::InProcess,
424        // Enforced by explicit policy (granted mounts/environ/clock) and by
425        // omission (Monty has no network or subprocess surface at all).
426        enforce_network_policy: true,
427        enforce_filesystem_policy: true,
428        enforce_environment_policy: true,
429        // ResourceLimits::max_duration — real preemption inside the VM.
430        enforce_timeout: true,
431        // The final expression value becomes `ExecutionResult::output`.
432        supports_structured_output: true,
433        supports_process_execution: false,
434        supports_persistent_workspace: persistent,
435        supports_interactive_sessions: persistent,
436    }
437}
438
439/// Extract non-empty Python source from a request payload.
440fn source_code(request: &ExecutionRequest) -> Result<String, ExecutionError> {
441    match &request.payload {
442        ExecutionPayload::Source { code } => {
443            if code.trim().is_empty() {
444                Err(ExecutionError::InvalidRequest("empty Python source".to_string()))
445            } else {
446                Ok(code.clone())
447            }
448        }
449        ExecutionPayload::GuestModule { .. } => Err(ExecutionError::InvalidRequest(
450            "Monty executors do not support guest modules".to_string(),
451        )),
452    }
453}
454
455/// Truncate `s` to at most `max` bytes on a char boundary; returns whether
456/// anything was cut.
457fn truncate_utf8(s: &mut String, max: usize) -> bool {
458    if s.len() <= max {
459        return false;
460    }
461    let mut end = max;
462    while end > 0 && !s.is_char_boundary(end) {
463        end -= 1;
464    }
465    s.truncate(end);
466    true
467}
468
469/// Assemble the [`ExecutionResult`] from a finished drive. Script-level
470/// failures are data (`Failed`/`Timeout` status), never `Err`.
471fn build_result(
472    end: DriveEnd,
473    stdout: CappedStdout,
474    policy: &SandboxPolicy,
475    started: Instant,
476) -> ExecutionResult {
477    // The collector already enforces the cap during the drive; the post-hoc
478    // truncation is belt-and-braces and should never fire.
479    let (mut stdout, capped) = stdout.into_parts();
480    let stdout_truncated = truncate_utf8(&mut stdout, policy.max_stdout_bytes) || capped;
481    let (status, mut stderr) = match end.error {
482        None => (ExecutionStatus::Success, String::new()),
483        Some(rendered) if end.timed_out => (ExecutionStatus::Timeout, rendered),
484        Some(rendered) => (ExecutionStatus::Failed, rendered),
485    };
486    let stderr_truncated = truncate_utf8(&mut stderr, policy.max_stderr_bytes);
487    ExecutionResult {
488        status,
489        stdout,
490        stderr,
491        output: end.value,
492        exit_code: None,
493        stdout_truncated,
494        stderr_truncated,
495        duration_ms: started.elapsed().as_millis() as u64,
496        metadata: None,
497    }
498}
499
500fn join_error(err: tokio::task::JoinError) -> ExecutionError {
501    ExecutionError::InternalError(format!("interpreter thread panicked: {err}"))
502}
503
504/// One-shot Monty executor: a fresh interpreter per
505/// [`execute`](CodeExecutor::execute) call.
506///
507/// Build with [`MontyExecutorBuilder::build_one_shot`]. Lifecycle methods keep
508/// the no-op trait defaults — every call is independent. See the
509/// [module docs](self) for the security model.
510///
511/// # Example
512///
513/// ```rust,no_run
514/// use adk_code::{
515///     CodeExecutor, ExecutionLanguage, ExecutionPayload, ExecutionRequest,
516///     MontyExecutorBuilder, SandboxPolicy,
517/// };
518///
519/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
520/// let executor = MontyExecutorBuilder::new().build_one_shot()?;
521/// let request = ExecutionRequest {
522///     language: ExecutionLanguage::Python,
523///     payload: ExecutionPayload::Source { code: "1 + 1".to_string() },
524///     argv: vec![],
525///     stdin: None,
526///     input: None,
527///     sandbox: SandboxPolicy::strict_python(),
528///     identity: None,
529/// };
530/// let result = executor.execute(request).await?;
531/// assert_eq!(result.output, Some(serde_json::json!(2)));
532/// # Ok(())
533/// # }
534/// ```
535#[derive(Debug)]
536pub struct MontyOneShotExecutor {
537    core: Arc<MontyCore>,
538}
539
540impl MontyOneShotExecutor {
541    /// A [`SandboxPolicy`] requesting exactly this executor's grants.
542    ///
543    /// The per-request policy may only narrow within the grants, so
544    /// [`SandboxPolicy::strict_python`] (no filesystem, no environment) runs
545    /// fully sandboxed even on a granting executor. Use this policy to run
546    /// with everything the executor offers.
547    #[must_use]
548    pub fn granted_policy(&self) -> SandboxPolicy {
549        self.core.granted_policy()
550    }
551}
552
553#[async_trait]
554impl CodeExecutor for MontyOneShotExecutor {
555    fn name(&self) -> &str {
556        "monty-one-shot"
557    }
558
559    fn capabilities(&self) -> BackendCapabilities {
560        monty_capabilities(false)
561    }
562
563    fn supports_language(&self, lang: &ExecutionLanguage) -> bool {
564        *lang == ExecutionLanguage::Python
565    }
566
567    fn prompt_snippet(&self) -> Option<String> {
568        Some(self.core.prompt_snippet.clone())
569    }
570
571    async fn execute(&self, request: ExecutionRequest) -> Result<ExecutionResult, ExecutionError> {
572        let started = Instant::now();
573        validate_request(&self.capabilities(), &[ExecutionLanguage::Python], &request)?;
574        let code = source_code(&request)?;
575        let os = self.core.grants.narrowed(&request.sandbox)?;
576        let timeout = request.sandbox.timeout;
577
578        // First segment: parse, start, drive to the first pause or the end.
579        let core = &self.core;
580        let tracker = core.tracker(timeout);
581        let (mut segment, mut stdout) = {
582            let os = os.clone();
583            let registry = core.registry.clone();
584            let script_name = core.script_name.clone();
585            let input = request.input.clone();
586            let mut stdout = CappedStdout::new(request.sandbox.max_stdout_bytes);
587            tokio::task::spawn_blocking(move || {
588                let segment = drive::start_run(
589                    &code,
590                    &script_name,
591                    input,
592                    tracker,
593                    &os,
594                    &registry,
595                    &mut stdout,
596                )?;
597                Ok::<_, ExecutionError>((segment, stdout))
598            })
599            .await
600            .map_err(join_error)??
601        };
602
603        // Segment boundaries: await the host function in async context, then
604        // resume the serialized progress on a fresh blocking segment.
605        loop {
606            match segment {
607                RunSegment::Finished(end) => {
608                    return Ok(build_result(end, stdout, &request.sandbox, started));
609                }
610                RunSegment::Paused(PausedCall { name, args, kwargs, progress_bytes }) => {
611                    let outcome = core.call_host_function(&name, args, kwargs).await;
612                    let os = os.clone();
613                    let registry = core.registry.clone();
614                    (segment, stdout) = tokio::task::spawn_blocking(move || {
615                        let mut stdout = stdout;
616                        let segment = drive::resume_run(
617                            &progress_bytes,
618                            outcome,
619                            &os,
620                            &registry,
621                            &mut stdout,
622                        )?;
623                        Ok::<_, ExecutionError>((segment, stdout))
624                    })
625                    .await
626                    .map_err(join_error)??;
627                }
628            }
629        }
630    }
631}
632
633/// One REPL session at rest: the postcard-serialized `MontyRepl` plus the
634/// effective OS policy captured on the session's first call.
635struct ReplSession {
636    bytes: Vec<u8>,
637    /// `None` until the first `execute()` establishes the session policy.
638    policy: Option<OsAccess>,
639}
640
641/// REPL Monty executor: interpreter state (variables, function definitions,
642/// imports) persists across [`execute`](CodeExecutor::execute) calls.
643///
644/// Build with [`MontyExecutorBuilder::build_repl`]. The executor stores the
645/// **serialized** interpreter between calls (Monty's types are not designed to
646/// be held across `await` points), guarded by a `Mutex` so snippets apply in
647/// submission order. Monty preserves the session through Python-level
648/// exceptions, so a failed snippet does not destroy accumulated state.
649///
650/// # Lifecycle
651///
652/// [`start`](CodeExecutor::start) initializes an empty interpreter session,
653/// [`stop`](CodeExecutor::stop) drops it, and
654/// [`restart`](CodeExecutor::restart) resets it. Calling `execute()` before
655/// `start()` lazily initializes the session.
656///
657/// # Policy consistency
658///
659/// A session's effective OS policy must not vary between calls (a mount
660/// visible in call 1 must not silently vanish in call 2 while state persists).
661/// The first call's effective policy is captured; a later call whose policy
662/// differs is rejected with guidance to `restart()`.
663///
664/// # Example
665///
666/// ```rust,no_run
667/// use adk_code::{
668///     CodeExecutor, ExecutionLanguage, ExecutionPayload, ExecutionRequest,
669///     MontyExecutorBuilder, SandboxPolicy,
670/// };
671///
672/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
673/// let executor = MontyExecutorBuilder::new().build_repl()?;
674/// let request = |code: &str| ExecutionRequest {
675///     language: ExecutionLanguage::Python,
676///     payload: ExecutionPayload::Source { code: code.to_string() },
677///     argv: vec![],
678///     stdin: None,
679///     input: None,
680///     sandbox: SandboxPolicy::strict_python(),
681///     identity: None,
682/// };
683/// executor.execute(request("x = 41")).await?;
684/// let result = executor.execute(request("x + 1")).await?;
685/// assert_eq!(result.output, Some(serde_json::json!(42)));
686/// # Ok(())
687/// # }
688/// ```
689#[derive(Debug)]
690pub struct MontyReplExecutor {
691    core: Arc<MontyCore>,
692    /// The serialized `MontyRepl` state. `None` = no session.
693    repl_state: Mutex<Option<ReplSession>>,
694}
695
696impl fmt::Debug for ReplSession {
697    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698        f.debug_struct("ReplSession")
699            .field("bytes.len", &self.bytes.len())
700            .field("policy", &self.policy)
701            .finish()
702    }
703}
704
705impl MontyReplExecutor {
706    /// A [`SandboxPolicy`] requesting exactly this executor's grants.
707    ///
708    /// See [`MontyOneShotExecutor::granted_policy`].
709    #[must_use]
710    pub fn granted_policy(&self) -> SandboxPolicy {
711        self.core.granted_policy()
712    }
713}
714
715#[async_trait]
716impl CodeExecutor for MontyReplExecutor {
717    fn name(&self) -> &str {
718        "monty-repl"
719    }
720
721    fn capabilities(&self) -> BackendCapabilities {
722        monty_capabilities(true)
723    }
724
725    fn supports_language(&self, lang: &ExecutionLanguage) -> bool {
726        *lang == ExecutionLanguage::Python
727    }
728
729    fn prompt_snippet(&self) -> Option<String> {
730        Some(self.core.prompt_snippet.clone())
731    }
732
733    async fn execute(&self, request: ExecutionRequest) -> Result<ExecutionResult, ExecutionError> {
734        let started = Instant::now();
735        validate_request(&self.capabilities(), &[ExecutionLanguage::Python], &request)?;
736        let code = source_code(&request)?;
737        let os = self.core.grants.narrowed(&request.sandbox)?;
738        let timeout = request.sandbox.timeout;
739
740        // The lock serializes REPL calls so snippets apply in submission
741        // order, and guards the state cell across the whole call.
742        let mut guard = self.repl_state.lock().await;
743        if let Some(session) = guard.as_ref()
744            && let Some(policy) = session.policy.as_ref()
745            && *policy != os
746        {
747            return Err(ExecutionError::InvalidRequest(
748                "the request's effective OS policy differs from this REPL session's established \
749                 policy; a session's mounts and environment must not vary between calls. \
750                 Call restart() to start a fresh session under the new policy."
751                    .to_string(),
752            ));
753        }
754        let prior_bytes = guard.as_ref().map(|session| session.bytes.clone());
755
756        // First segment: load (or create) the session, feed the snippet,
757        // drive to the first pause or the end.
758        let core = &self.core;
759        let tracker = core.tracker(timeout);
760        let (mut segment, mut stdout) = {
761            let os = os.clone();
762            let registry = core.registry.clone();
763            let script_name = core.script_name.clone();
764            let input = request.input.clone();
765            let mut stdout = CappedStdout::new(request.sandbox.max_stdout_bytes);
766            tokio::task::spawn_blocking(move || {
767                let segment = drive::feed_repl(
768                    prior_bytes.as_deref(),
769                    &script_name,
770                    tracker,
771                    timeout,
772                    &code,
773                    input,
774                    &os,
775                    &registry,
776                    &mut stdout,
777                )?;
778                Ok::<_, ExecutionError>((segment, stdout))
779            })
780            .await
781            .map_err(join_error)??
782        };
783
784        loop {
785            match segment {
786                ReplSegment::Finished { end, repl_bytes } => {
787                    *guard = Some(ReplSession { bytes: repl_bytes, policy: Some(os) });
788                    return Ok(build_result(end, stdout, &request.sandbox, started));
789                }
790                ReplSegment::Paused(PausedCall { name, args, kwargs, progress_bytes }) => {
791                    let outcome = core.call_host_function(&name, args, kwargs).await;
792                    let os = os.clone();
793                    let registry = core.registry.clone();
794                    (segment, stdout) = tokio::task::spawn_blocking(move || {
795                        let mut stdout = stdout;
796                        let segment = drive::resume_repl(
797                            &progress_bytes,
798                            outcome,
799                            &os,
800                            &registry,
801                            &mut stdout,
802                        )?;
803                        Ok::<_, ExecutionError>((segment, stdout))
804                    })
805                    .await
806                    .map_err(join_error)??;
807                }
808            }
809        }
810    }
811
812    /// Initialize an empty interpreter session. A no-op if one exists.
813    async fn start(&self) -> Result<(), ExecutionError> {
814        let mut guard = self.repl_state.lock().await;
815        if guard.is_none() {
816            // The time budget is installed per call from `SandboxPolicy::timeout`.
817            let tracker = Tracker::new(self.core.base_limits.clone());
818            let bytes = drive::fresh_repl_bytes(&self.core.script_name, tracker)?;
819            *guard = Some(ReplSession { bytes, policy: None });
820        }
821        Ok(())
822    }
823
824    /// Drop the interpreter session (variables, functions, imports).
825    async fn stop(&self) -> Result<(), ExecutionError> {
826        *self.repl_state.lock().await = None;
827        Ok(())
828    }
829
830    async fn is_running(&self) -> bool {
831        self.repl_state.lock().await.is_some()
832    }
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838    use serde_json::json;
839
840    #[test]
841    fn capabilities_encode_the_mode() {
842        let one_shot = MontyExecutorBuilder::new().build_one_shot().unwrap();
843        let caps = one_shot.capabilities();
844        assert!(!caps.supports_interactive_sessions);
845        assert!(!caps.supports_persistent_workspace);
846
847        let repl = MontyExecutorBuilder::new().build_repl().unwrap();
848        let caps = repl.capabilities();
849        assert!(caps.supports_interactive_sessions);
850        assert!(caps.supports_persistent_workspace);
851    }
852
853    #[test]
854    fn one_cloned_builder_yields_both_products_with_identical_grants() {
855        let builder = MontyExecutorBuilder::new()
856            .allow_path("/data", "/srv/data", PathAccess::ReadOnly)
857            .environ_var("PROJECT", "acme")
858            .system_clock()
859            .function_fn("noop", "Do nothing.", |_args, _kwargs| async move { Ok(json!(null)) });
860
861        let one_shot = builder.clone().build_one_shot().unwrap();
862        let repl = builder.build_repl().unwrap();
863
864        assert_eq!(one_shot.core.grants, repl.core.grants);
865        assert_eq!(
866            one_shot.core.registry.names().collect::<Vec<_>>(),
867            repl.core.registry.names().collect::<Vec<_>>()
868        );
869        // Only the mode wording differs between the cached snippets.
870        assert_ne!(one_shot.core.prompt_snippet, repl.core.prompt_snippet);
871    }
872
873    #[test]
874    fn build_rejects_invalid_registries() {
875        let err = MontyExecutorBuilder::new()
876            .function_fn(
877                "len",
878                "Shadow a builtin.",
879                |_args, _kwargs| async move { Ok(json!(null)) },
880            )
881            .build_one_shot()
882            .unwrap_err();
883        assert_eq!(err, MontyBuildError::BuiltinCollision("len".to_string()));
884
885        let err = MontyExecutorBuilder::new()
886            .function_fn("dup", "One.", |_args, _kwargs| async move { Ok(json!(null)) })
887            .function_fn("dup", "Two.", |_args, _kwargs| async move { Ok(json!(null)) })
888            .build_repl()
889            .unwrap_err();
890        assert_eq!(err, MontyBuildError::DuplicateFunctionName("dup".to_string()));
891    }
892
893    #[test]
894    fn build_rejects_invalid_mount_paths() {
895        for bad in ["data", "/", "/data/", "/data//sub", "/data/../out"] {
896            let err = MontyExecutorBuilder::new()
897                .allow_path(bad, "/srv/data", PathAccess::ReadOnly)
898                .build_one_shot()
899                .unwrap_err();
900            assert!(
901                matches!(err, MontyBuildError::InvalidMountPath { .. }),
902                "expected InvalidMountPath for {bad:?}, got {err:?}"
903            );
904        }
905        let err = MontyExecutorBuilder::new()
906            .allow_path("/data", "/srv/a", PathAccess::ReadOnly)
907            .allow_path("/data", "/srv/b", PathAccess::ReadWrite)
908            .build_repl()
909            .unwrap_err();
910        assert_eq!(err, MontyBuildError::DuplicateMountPath("/data".to_string()));
911    }
912
913    #[test]
914    fn granted_policy_mirrors_the_grants() {
915        let one_shot = MontyExecutorBuilder::new()
916            .allow_path("/data", "/srv/data", PathAccess::ReadOnly)
917            .allow_path("/out", "/srv/out", PathAccess::ReadWrite)
918            .environ_var("PROJECT", "acme")
919            .build_one_shot()
920            .unwrap();
921        let policy = one_shot.granted_policy();
922        assert_eq!(
923            policy.filesystem,
924            FilesystemPolicy::Paths {
925                read_only: vec![PathBuf::from("/data")],
926                read_write: vec![PathBuf::from("/out")],
927            }
928        );
929        assert_eq!(policy.environment, EnvironmentPolicy::AllowList(vec!["PROJECT".to_string()]));
930
931        let sandboxed = MontyExecutorBuilder::new().build_one_shot().unwrap();
932        assert_eq!(sandboxed.granted_policy().filesystem, FilesystemPolicy::None);
933        assert_eq!(sandboxed.granted_policy().environment, EnvironmentPolicy::None);
934    }
935
936    #[test]
937    fn prompt_snippet_reflects_built_configuration() {
938        let executor = MontyExecutorBuilder::new()
939            .allow_path("/data", "/srv/data", PathAccess::ReadOnly)
940            .environ_var("PROJECT", "secret-value")
941            .function_fn("noop", "Do nothing.", |_args, _kwargs| async move { Ok(json!(null)) })
942            .build_repl()
943            .unwrap();
944        let snippet = executor.prompt_snippet().expect("monty executors are self-describing");
945        assert!(snippet.contains("/data (read-only)"));
946        assert!(snippet.contains("PROJECT"));
947        assert!(!snippet.contains("secret-value"));
948        assert!(snippet.contains("def noop(...):"));
949    }
950}