1mod convert;
73mod drive;
74mod host_fn;
75mod os_access;
76mod prompt;
77
78pub 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
112const DEFAULT_HOST_FUNCTION_TIMEOUT: Duration = Duration::from_secs(30);
114
115const DEFAULT_MAX_MEMORY: usize = 256 * 1024 * 1024;
119
120#[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 #[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 #[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 #[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 #[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 #[must_use]
231 pub fn system_clock(mut self) -> Self {
232 self.os.system_clock = true;
233 self
234 }
235
236 #[must_use]
241 pub fn function(mut self, function: Arc<dyn HostFunction>) -> Self {
242 self.functions.push(function);
243 self
244 }
245
246 #[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 #[must_use]
284 pub fn max_memory(mut self, bytes: usize) -> Self {
285 self.max_memory = Some(bytes);
286 self
287 }
288
289 #[must_use]
293 pub fn host_function_timeout(mut self, timeout: Duration) -> Self {
294 self.host_function_timeout = timeout;
295 self
296 }
297
298 #[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 pub fn build_one_shot(self) -> Result<MontyOneShotExecutor, MontyBuildError> {
314 Ok(MontyOneShotExecutor { core: self.build_core(ModeWording::OneShot)? })
315 }
316
317 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, ®istry, 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#[derive(Debug)]
355struct MontyCore {
356 grants: OsAccess,
357 registry: FunctionRegistry,
358 base_limits: ResourceLimits,
361 script_name: String,
362 host_function_timeout: Duration,
363 prompt_snippet: String,
364}
365
366impl MontyCore {
367 fn tracker(&self, timeout: Duration) -> Tracker {
369 Tracker::new(self.base_limits.clone().max_duration(timeout))
370 }
371
372 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 async fn call_host_function(
398 &self,
399 name: &str,
400 args: Vec<Value>,
401 kwargs: Map<String, Value>,
402 ) -> Result<Value, String> {
403 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
420fn monty_capabilities(persistent: bool) -> BackendCapabilities {
422 BackendCapabilities {
423 isolation: ExecutionIsolation::InProcess,
424 enforce_network_policy: true,
427 enforce_filesystem_policy: true,
428 enforce_environment_policy: true,
429 enforce_timeout: true,
431 supports_structured_output: true,
433 supports_process_execution: false,
434 supports_persistent_workspace: persistent,
435 supports_interactive_sessions: persistent,
436 }
437}
438
439fn 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
455fn 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
469fn build_result(
472 end: DriveEnd,
473 stdout: CappedStdout,
474 policy: &SandboxPolicy,
475 started: Instant,
476) -> ExecutionResult {
477 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#[derive(Debug)]
536pub struct MontyOneShotExecutor {
537 core: Arc<MontyCore>,
538}
539
540impl MontyOneShotExecutor {
541 #[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 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 ®istry,
595 &mut stdout,
596 )?;
597 Ok::<_, ExecutionError>((segment, stdout))
598 })
599 .await
600 .map_err(join_error)??
601 };
602
603 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 ®istry,
621 &mut stdout,
622 )?;
623 Ok::<_, ExecutionError>((segment, stdout))
624 })
625 .await
626 .map_err(join_error)??;
627 }
628 }
629 }
630 }
631}
632
633struct ReplSession {
636 bytes: Vec<u8>,
637 policy: Option<OsAccess>,
639}
640
641#[derive(Debug)]
690pub struct MontyReplExecutor {
691 core: Arc<MontyCore>,
692 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 #[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 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 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 ®istry,
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 ®istry,
801 &mut stdout,
802 )?;
803 Ok::<_, ExecutionError>((segment, stdout))
804 })
805 .await
806 .map_err(join_error)??;
807 }
808 }
809 }
810 }
811
812 async fn start(&self) -> Result<(), ExecutionError> {
814 let mut guard = self.repl_state.lock().await;
815 if guard.is_none() {
816 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 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 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}