1use std::sync::Arc;
7
8use serde::Serialize;
9use serde_json::json;
10
11use super::input::InputReader;
12use super::{js_number_text, resolve_sandbox, seconds, tool_error};
13use crate::cancel::CancelSignal;
14use crate::error::{Error, Result, SandboxTimeoutError};
15use crate::sandbox::{ExecuteOptions, Sandbox, is_valid_language};
16use crate::tools::{FunctionTool, ToolError};
17use crate::types::{JsonSchema, JsonValue};
18
19const DEFAULT_LANGUAGE: &str = "python3";
20const DEFAULT_TIMEOUT: f64 = 120.0;
21
22pub const PYTHON_REPL_DESCRIPTION: &str = concat!(
24 "Executes Python code and returns output (stdout), error (stderr), and exit_code (non-zero means the ",
25 "code failed). Each call runs in a fresh interpreter; variables, imports, and definitions do not persist ",
26 "across calls. Files written to the working directory persist while the sandbox is alive, so save ",
27 "intermediate results to files when later calls need them. stdin is not available (input() fails). ",
28 "Use print() to surface values."
29);
30
31tool_error!(
32 PythonReplError
36);
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
40#[non_exhaustive]
41pub struct PythonReplOutput {
42 pub output: String,
44 pub error: String,
46 pub exit_code: i32,
48}
49
50impl PythonReplOutput {
51 pub fn new(output: impl Into<String>, error: impl Into<String>, exit_code: i32) -> Self {
53 Self {
54 output: output.into(),
55 error: error.into(),
56 exit_code,
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, thiserror::Error)]
65#[error("{message}")]
66#[non_exhaustive]
67pub struct PythonReplTimeoutError {
68 message: String,
69 pub partial: PythonReplOutput,
71 #[source]
72 timeout: SandboxTimeoutError,
73}
74
75impl PythonReplTimeoutError {
76 fn new(timeout: SandboxTimeoutError) -> Result<Self> {
77 let partial = PythonReplOutput::new(timeout.stdout.clone(), timeout.stderr.clone(), 124);
78 let message = format!("{timeout}\n{}", serde_json::to_string(&partial)?);
79 Ok(Self {
80 message,
81 partial,
82 timeout,
83 })
84 }
85
86 #[must_use]
88 pub fn message(&self) -> &str {
89 &self.message
90 }
91
92 #[must_use]
94 pub fn timeout(&self) -> &SandboxTimeoutError {
95 &self.timeout
96 }
97}
98
99#[derive(Clone, Default, bon::Builder)]
101#[builder(on(String, into))]
102pub struct MakePythonReplOptions {
103 pub sandbox: Option<Arc<dyn Sandbox>>,
106 pub name: Option<String>,
108 pub description: Option<String>,
110 pub language: Option<String>,
112}
113
114impl std::fmt::Debug for MakePythonReplOptions {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 f.debug_struct("MakePythonReplOptions")
117 .field("sandbox", &self.sandbox.is_some())
118 .field("name", &self.name)
119 .field("language", &self.language)
120 .finish_non_exhaustive()
121 }
122}
123
124fn input_schema() -> JsonSchema {
125 json!({
126 "type": "object",
127 "properties": {
128 "code": {"type": "string", "description": "Python source to execute."},
129 "timeout": {
130 "description": "Timeout in seconds (default: 120). Must be positive.",
131 "type": "number",
132 "exclusiveMinimum": 0
133 }
134 },
135 "required": ["code"],
136 "additionalProperties": false
137 })
138}
139
140#[must_use]
142pub fn python_repl() -> FunctionTool {
143 build(
144 None,
145 "python_repl".to_owned(),
146 PYTHON_REPL_DESCRIPTION.to_owned(),
147 DEFAULT_LANGUAGE.to_owned(),
148 )
149}
150
151pub fn make_python_repl(options: MakePythonReplOptions) -> Result<FunctionTool> {
171 let name = options.name.unwrap_or_else(|| "python_repl".to_owned());
172 let language = options.language.unwrap_or_else(|| DEFAULT_LANGUAGE.to_owned());
173 if name.is_empty() {
174 return Err(Error::other("name must be a non-empty string"));
175 }
176 if !is_valid_language(&language) {
177 return Err(Error::other(format!(
178 "language contains invalid characters: {language}"
179 )));
180 }
181 let description = options
182 .description
183 .unwrap_or_else(|| PYTHON_REPL_DESCRIPTION.to_owned());
184 Ok(build(options.sandbox, name, description, language))
185}
186
187fn build(bound: Option<Arc<dyn Sandbox>>, name: String, description: String, language: String) -> FunctionTool {
188 let language = Arc::new(language);
189 FunctionTool::builder(name, description)
190 .input_schema(input_schema())
191 .callback(move |input, context| {
192 let sandbox = resolve_sandbox(bound.as_ref(), &context);
193 let signal = context.cancel_signal().clone();
194 let language = language.clone();
195 async move { run(sandbox.as_ref(), &input, &language, signal).await }
196 })
197}
198
199async fn run(
200 sandbox: &dyn Sandbox,
201 input: &JsonValue,
202 language: &str,
203 signal: CancelSignal,
204) -> std::result::Result<JsonValue, ToolError> {
205 let mut reader = InputReader::new(input);
206 let code = reader.string("code");
207 let timeout = reader.optional_positive("timeout", |value| {
208 format!(
209 "timeout must be a positive number of seconds, got {}",
210 js_number_text(value)
211 )
212 });
213 reader.finish()?;
214 let options = ExecuteOptions {
215 timeout: seconds(timeout.unwrap_or(DEFAULT_TIMEOUT)),
216 signal: Some(signal),
217 ..ExecuteOptions::default()
218 };
219 match sandbox.execute_code(code.unwrap_or_default(), language, options).await {
220 Ok(result) => Ok(serde_json::to_value(PythonReplOutput::new(
221 result.stdout,
222 result.stderr,
223 result.exit_code,
224 ))?),
225 Err(Error::SandboxAbort(abort)) => {
226 let partial = PythonReplOutput::new(abort.stdout.clone(), abort.stderr.clone(), 130);
227 let detail = serde_json::to_string(&partial)?;
228 Err(Error::from(abort.with_detail(&detail)).into())
229 }
230 Err(Error::SandboxTimeout(timeout)) => Err(PythonReplTimeoutError::new(timeout)?.into()),
231 Err(error) => Err(ToolError::new(PythonReplError::new(error.to_string()))),
232 }
233}
234
235#[cfg(test)]
236mod tests;