POST /run — write Python code to a temp file and execute it via python3
(
State(state): State<Arc<AppState>>,
Json(body): Json<RunPythonBody>,
)
| 73 | |
| 74 | /// POST /run — write Python code to a temp file and execute it via python3 |
| 75 | async fn run_python( |
| 76 | State(state): State<Arc<AppState>>, |
| 77 | Json(body): Json<RunPythonBody>, |
| 78 | ) -> impl IntoResponse { |
| 79 | let code = match &body.code { |
| 80 | Some(c) if !c.is_empty() => c.clone(), |
| 81 | _ => { |
| 82 | return ( |
| 83 | StatusCode::BAD_REQUEST, |
| 84 | Json(json!({"error": "code required"})), |
| 85 | ) |
| 86 | } |
| 87 | }; |
| 88 | |
| 89 | let sandbox_dir = resolve_sandbox_dir(&state).await; |
| 90 | |
| 91 | // Route through the same sandboxed runner the agents use: dangerous-pattern |
| 92 | // check, container/sandbox-exec tiers, 60s timeout, kill-on-timeout. The |
| 93 | // previous direct `python3 file.py` here had NO sandbox and NO timeout. |
| 94 | let result = crate::server::services::toolbox::run_python_sandboxed(&code, &sandbox_dir).await; |
| 95 | |
| 96 | let ok = result.get("ok").and_then(|v| v.as_bool()).unwrap_or(false); |
| 97 | let stdout = result.get("stdout").and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 98 | let mut stderr = result.get("stderr").and_then(|v| v.as_str()).unwrap_or("").to_string(); |
| 99 | if let Some(err) = result.get("error").and_then(|v| v.as_str()) { |
| 100 | if stderr.is_empty() { stderr = err.to_string(); } |
| 101 | } |
| 102 | let exit_code = result.get("exit_code").and_then(|v| v.as_i64()) |
| 103 | .unwrap_or(if ok { 0 } else { 1 }); |
| 104 | |
| 105 | ( |
| 106 | StatusCode::OK, |
| 107 | Json(json!({ |
| 108 | "stdout": stdout, |
| 109 | "stderr": stderr, |
| 110 | "code": exit_code, |
| 111 | })), |
| 112 | ) |
| 113 | } |
| 114 | |
| 115 | // --------------------------------------------------------------------------- |
| 116 | // Router |
nothing calls this directly
no test coverage detected