Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

refactor: remove unused sandbox code (#20389)

Jin Hai8614e2c38d28
diff --git a/agent/sandbox/.env.example b/agent/sandbox/.env.example
deleted file mode 100644
index 98a357fc82..0000000000
--- a/agent/sandbox/.env.example
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copy this file to `.env` and modify as needed
-
-SANDBOX_EXECUTOR_MANAGER_POOL_SIZE=5
-SANDBOX_BASE_PYTHON_IMAGE=sandbox-base-python:latest
-SANDBOX_BASE_NODEJS_IMAGE=sandbox-base-nodejs:latest
-SANDBOX_EXECUTOR_MANAGER_PORT=9385
-SANDBOX_ENABLE_SECCOMP=false
-SANDBOX_MAX_MEMORY=256m # b, k, m, g
-SANDBOX_TIMEOUT=10s # s, m, 1m30s
-# Shared secret required by the executor manager /run endpoint (Authorization:
-# Bearer or X-Sandbox-Token). Authentication is fail-closed: with no token set,
-# /run answers 503 instead of staying open. Generate one with, for example:
-# python -c "import secrets; print(secrets.token_urlsafe(32))"
-SANDBOX_EXECUTOR_MANAGER_API_TOKEN=
-# Explicit, risk-accepting opt-in for deployments that cannot provide a token.
-# Leave unset (or false) in normal deployments.
-SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=false
-# Docker network used for sandbox runner containers. "none" (default) gives
-# sandboxed code no external network access. Set to "bridge" only if your
-# sandboxed code genuinely needs outbound network (e.g. pip/npm installs at
-# runtime); prefer baking dependencies into the base images instead.
-SANDBOX_CONTAINER_NETWORK=none
-# Rate limits for POST /run, keyed by client address: a small pre-auth
-# throttle applied to ALL /run traffic (including invalid-token requests) and
-# the larger quota for authenticated execution.
-SANDBOX_RUN_PREAUTH_RATE_LIMIT=30/minute
-SANDBOX_RUN_RATE_LIMIT=120/minute
diff --git a/agent/sandbox/Makefile b/agent/sandbox/Makefile
deleted file mode 100644
index b4caceece9..0000000000
--- a/agent/sandbox/Makefile
+++ /dev/null
@@ -1,124 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# Force using Bash to ensure the source command is available
-SHELL := /bin/bash
-
-# Environment variable definitions
-VENV := .venv
-PYTHON := $(VENV)/bin/python
-UV := uv
-ACTIVATE_SCRIPT := $(VENV)/bin/activate
-SYS_PYTHON := python3
-PYTHONPATH := $(shell pwd)
-
-.PHONY: all setup ensure_env ensure_uv start stop restart build clean test logs
-
-all: setup start
-
-# 🌱 Initialize environment + install dependencies
-setup: ensure_env ensure_uv
- @echo "πŸ“¦ Installing dependencies with uv..."
- @$(UV) sync --python 3.13
- source $(ACTIVATE_SCRIPT) && \
- export PYTHONPATH=$(PYTHONPATH)
- @$(UV) pip install -r executor_manager/requirements.txt
- @echo "βœ… Setup complete."
-
-# πŸ”‘ Ensure .env exists (copy from .env.example on first run)
-ensure_env:
- @if [ ! -f ".env" ]; then \
- if [ -f ".env.example" ]; then \
- echo "πŸ“ Creating .env from .env.example..."; \
- cp .env.example .env; \
- else \
- echo "⚠️ Warning: .env.example not found, creating empty .env"; \
- touch .env; \
- fi; \
- else \
- echo "βœ… .env already exists."; \
- fi
-
-# πŸ”§ Ensure uv is executable (install using system Python)
-ensure_uv:
- @if ! command -v $(UV) >/dev/null 2>&1; then \
- echo "πŸ› οΈ Installing uv using system Python..."; \
- $(SYS_PYTHON) -m pip install -q --upgrade pip; \
- $(SYS_PYTHON) -m pip install -q uv || (echo "⚠️ uv install failed, check manually" && exit 1); \
- fi
-
-# 🐳 Service control (using safer variable loading)
-start:
- @echo "πŸš€ Starting services..."
- source $(ACTIVATE_SCRIPT) && \
- export PYTHONPATH=$(PYTHONPATH) && \
- [ -f .env ] && source .env || true && \
- bash scripts/start.sh
-
-stop:
- @echo "πŸ›‘ Stopping services..."
- source $(ACTIVATE_SCRIPT) && \
- bash scripts/stop.sh
-
-restart: stop start
- @echo "πŸ” Restarting services..."
-
-build:
- @echo "πŸ”§ Building base sandbox images..."
- @if [ -f .env ]; then \
- source .env && \
- echo "🐍 Building base sandbox image for Python ($$SANDBOX_BASE_PYTHON_IMAGE)..." && \
- docker build -t "$$SANDBOX_BASE_PYTHON_IMAGE" ./sandbox_base_image/python && \
- echo "β¬’ Building base sandbox image for Nodejs ($$SANDBOX_BASE_NODEJS_IMAGE)..." && \
- docker build -t "$$SANDBOX_BASE_NODEJS_IMAGE" ./sandbox_base_image/nodejs; \
- else \
- echo "⚠️ .env file not found, skipping build."; \
- fi
-
-test:
- @echo "πŸ§ͺ Running sandbox security tests..."
- source $(ACTIVATE_SCRIPT) && \
- export PYTHONPATH=$(PYTHONPATH) && \
- $(PYTHON) tests/sandbox_security_tests_full.py
-
-logs:
- @echo "πŸ“‹ Showing logs from api-server and executor-manager..."
- docker compose logs -f
-
-# 🧹 Clean all containers and volumes
-clean:
- @echo "🧹 Cleaning all containers and volumes..."
- @docker compose down -v || true
- @# Same discovery as scripts/stop.sh: the containers that exist, not a range derived from
- @# SANDBOX_EXECUTOR_MANAGER_POOL_SIZE, which misses a pool created at a different size, skips
- @# cleanup entirely when .env is gone, and never covers a container that failed to join the
- @# executor-manager queue.
- @# A failed `docker ps` and an empty result both collapse to an empty string, and only the
- @# first means the containers are still running. Tolerate grep's no-match exit, not docker's.
- @if ! all_containers="$$(docker ps -a --format '{{.Names}}')"; then \
- echo "❌ Could not list Docker containers; sandbox containers were NOT removed" >&2; \
- exit 1; \
- fi; \
- sandbox_containers="$$(printf '%s\n' "$$all_containers" | \
- grep -E '^sandbox_(python|nodejs)_[0-9]+$$' || true)"; \
- if [ -n "$$sandbox_containers" ]; then \
- while IFS= read -r container; do \
- echo "🧹 Deleting $$container..."; \
- docker rm -f "$$container" >/dev/null 2>&1 || true; \
- done <<<"$$sandbox_containers"; \
- else \
- echo "βœ… No sandbox containers found"; \
- fi
diff --git a/agent/sandbox/README.md b/agent/sandbox/README.md
deleted file mode 100644
index 78375907dc..0000000000
--- a/agent/sandbox/README.md
+++ /dev/null
@@ -1,386 +0,0 @@
-# RAGFlow Sandbox
-
-A secure, pluggable code execution backend for RAGFlow and beyond.
-
-## πŸ”§ Features
-
-- βœ… **Seamless RAGFlow Integration** β€” Out-of-the-box compatibility with the `code` component.
-- πŸ” **High Security** β€” Leverages [gVisor](https://gvisor.dev/) for syscall-level sandboxing.
-- πŸ”§ **Customizable Sandboxing** β€” Easily modify `seccomp` settings as needed.
-- 🧩 **Pluggable Runtime Support** β€” Easily extend to support any programming language.
-- βš™οΈ **Developer Friendly** β€” Get started with a single command using `Makefile`.
-
-## πŸ— Architecture
-
-<p align="center">
- <img src="asserts/code_executor_manager.svg" width="520" alt="Architecture Diagram">
-</p>
-
-## πŸš€ Quick Start
-
-### πŸ“‹ Prerequisites
-
-#### Required
-
-- Linux distro compatible with gVisor
-- [gVisor](https://gvisor.dev/docs/user_guide/install/)
-- Docker >= `25.0` (API 1.44+) β€” executor manager now bundles Docker CLI `29.1.0` to match newer daemons.
-- Docker Compose >= `v2.26.1` like [RAGFlow](https://github.com/infiniflow/ragflow)
-- [uv](https://docs.astral.sh/uv/) as package and project manager
-
-#### Optional (Recommended)
-
-- [GNU Make](https://www.gnu.org/software/make/) for simplified CLI management
-
----
-
-> ⚠️ **New Docker CLI requirement**
->
-> If you see `client version 1.43 is too old. Minimum supported API version is 1.44`, pull the latest `infiniflow/sandbox-executor-manager:latest` (rebuilt with Docker CLI `29.1.0`) or rebuild it in `./sandbox/executor_manager`. Older images shipped Docker 24.x, which cannot talk to newer Docker daemons.
-
-### 🐳 Build Docker Base Images
-
-We use isolated base images for secure containerized execution:
-
-```bash
-# Build base images manually
-docker build -t sandbox-base-python:latest ./sandbox_base_image/python
-docker build -t sandbox-base-nodejs:latest ./sandbox_base_image/nodejs
-
-# OR use Makefile
-make build
-```
-
-Then, build the executor manager image:
-
-```bash
-docker build -t sandbox-executor-manager:latest ./executor_manager
-```
-
----
-
-### πŸ“¦ Running with RAGFlow
-
-1. Ensure gVisor is correctly installed.
-2. Configure your `.env` in `docker/.env`:
-
- - Uncomment sandbox-related variables.
- - Enable sandbox profile at the bottom.
-3. Add the following line to `/etc/hosts` as recommended:
-
- ```text
- 127.0.0.1 sandbox-executor-manager
- ```
-
-4. Start RAGFlow service.
-
----
-
-### 🧭 Running Standalone
-
-#### Manual Setup
-
-1. Initialize environment:
-
- ```bash
- cp .env.example .env
- ```
-
-2. Launch:
-
- ```bash
- docker compose -f docker-compose.yml up
- ```
-
-3. Test:
-
- ```bash
- source .venv/bin/activate
- export PYTHONPATH=$(pwd)
- uv pip install -r executor_manager/requirements.txt
- uv run tests/sandbox_security_tests_full.py
- ```
-
-#### With Make
-
-```bash
-make # setup + build + launch + test
-```
-
----
-
-### πŸ“ˆ Monitoring
-
-```bash
-docker logs -f sandbox-executor-manager # Manual
-make logs # With Make
-```
-
----
-
-### 🧰 Makefile Toolbox
-
-| Command | Description |
-|-------------------|--------------------------------------------------|
-| `make` | Setup, build, launch and test all at once |
-| `make setup` | Initialize environment and install uv |
-| `make ensure_env` | Auto-create `.env` if missing |
-| `make ensure_uv` | Install `uv` package manager if missing |
-| `make build` | Build all Docker base images |
-| `make start` | Start services with safe env loading and testing |
-| `make stop` | Gracefully stop all services |
-| `make restart` | Shortcut for `stop` + `start` |
-| `make test` | Run full test suite |
-| `make logs` | Stream container logs |
-| `make clean` | Stop and remove orphan containers and volumes |
-
----
-
-## πŸ” Security
-
-The RAGFlow sandbox is designed to balance security and usability, offering solid protection without compromising developer experience.
-
-### βœ… gVisor Isolation
-
-At its core, we use [gVisor](https://gvisor.dev/docs/architecture_guide/security/), a user-space kernel, to isolate code execution from the host system. gVisor intercepts and restricts syscalls, offering robust protection against container escapes and privilege escalations.
-
-### πŸ”’ Optional seccomp Support (Advanced)
-
-For users who need **zero-trust-level syscall control**, we support an additional `seccomp` profile. This feature restricts containers to only a predefined set of system calls, as specified in `executor_manager/seccomp-profile-default.json`.
-
-> ⚠️ This feature is **disabled by default** to maintain compatibility and usability. Enabling it may cause compatibility issues with some dependencies.
-
-#### To enable seccomp
-
-1. Edit your `.env` file:
-
- ```dotenv
- SANDBOX_ENABLE_SECCOMP=true
- ```
-
-2. Customize allowed syscalls in:
-
- ```
- executor_manager/seccomp-profile-default.json
- ```
-
- This profile is passed to the container with:
-
- ```bash
- --security-opt seccomp=/app/seccomp-profile-default.json
- ```
-
-### 🧠 Python Code AST Inspection
-
-In addition to sandboxing, Python code is **statically analyzed via AST (Abstract Syntax Tree)** before execution. Potentially malicious code (e.g. file operations, subprocess calls, etc.) is rejected early, providing an extra layer of protection.
-
-### 🌐 Network Isolation (Default: No External Access)
-
-Sandbox runner containers are started with `--network none`: sandboxed code has **no external network access** by default. `docker exec` (used to feed code in and collect results) is unaffected.
-
-If your sandboxed code genuinely needs outbound network access (e.g. runtime `pip install` / `npm install`), opt in explicitly via `.env`:
-
-```dotenv
-SANDBOX_CONTAINER_NETWORK=bridge
-```
-
-Prefer baking dependencies into the base images (`sandbox_base_image/python/requirements.txt`, `sandbox_base_image/nodejs/package.json`) instead β€” that keeps the default hermetic profile.
-
-### πŸ”‘ Executor API Authentication (Shared Secret)
-
-The `/run` endpoint can require a shared secret. Set the same value on both sides:
-
-```dotenv
-# executor manager (and RAGFlow when using the compose profile)
-SANDBOX_EXECUTOR_MANAGER_API_TOKEN=<openssl rand -hex 32>
-```
-
-Requests must then carry `Authorization: Bearer <token>` (or `X-Sandbox-Token: <token>`); the RAGFlow self-managed provider sends this automatically. When the variable is unset the endpoint accepts unauthenticated requests (the pre-token behavior), and the executor manager logs a prominent security warning at startup and on first request. `/run` is additionally rate limited per client address (`SANDBOX_RUN_RATE_LIMIT`, default `120/minute`).
-
----
-
-This security model strikes a balance between **robust isolation** and **developer usability**. While `seccomp` can be highly restrictive, our default setup aims to keep things usable for most developers β€” no obscure crashes or cryptic setup required.
-
-## πŸ“¦ Add Extra Dependencies for Supported Languages
-
-Currently, the following languages are officially supported:
-
-| Language | Priority |
-|----------|----------|
-| Python | High |
-| Node.js | Medium |
-
-### 🐍 Python
-
-Pre-installed packages: `requests`, `numpy`, `pandas`, `matplotlib`.
-
-> `matplotlib` uses the `Agg` (non-interactive) backend by default in the sandbox (`MPLBACKEND=Agg`). No display server is available, so always save figures to files (e.g. `fig.savefig("artifacts/chart.png")`) rather than calling `plt.show()`.
->
-> Tip: if Chinese text renders as missing boxes/squares in `matplotlib`, install Debian package `fonts-noto-cjk` in your custom image. We do not preinstall it by default to keep the base image smaller. The sandbox base image ships a `matplotlibrc` that already lists common CJK fonts in the `font.sans-serif` fallback chain, so no code-level font configuration is needed β€” just install the font package and rebuild the image.
->
-> Example:
->
-> ```dockerfile
-> RUN apt-get update && apt-get install -y --no-install-recommends fonts-noto-cjk && rm -rf /var/lib/apt/lists/*
-> ```
-
-To add more dependencies, edit:
-
-```bash
-sandbox_base_image/python/requirements.txt
-```
-
-Add any additional packages you need, one per line (just like a normal pip requirements file).
-
-### 🟨 Node.js
-
-Pre-installed packages: `axios`.
-
-To add Node.js dependencies:
-
-1. Navigate to the Node.js base image directory:
-
- ```bash
- cd sandbox_base_image/nodejs
- ```
-
-2. Use `npm` to install the desired packages. For example:
-
- ```bash
- npm install lodash
- ```
-
-3. The dependencies will be saved to `package.json` and `package-lock.json`, and included in the Docker image when rebuilt.
-
----
-
-
-## Usage
-
-### 🐍 A Python example
-
-```python
-def main(arg1: str, arg2: str) -> str:
- return f"result: {arg1 + arg2}"
-```
-
-### 🟨 JavaScript examples
-
-A simple sync function
-
-```javascript
-function main({arg1, arg2}) {
- return arg1+arg2
-}
-```
-
-Async funcion with aioxs
-
-> Note: outbound HTTP requires opting into network access (`SANDBOX_CONTAINER_NETWORK=bridge`); by default sandbox containers have no external network.
-
-```javascript
-const axios = require('axios');
-async function main() {
- try {
- const response = await axios.get('https://github.com/infiniflow/ragflow');
- return 'Body:' + response.data;
- } catch (error) {
- return 'Error:' + error.message;
- }
-}
-```
-
----
-
-## πŸ“‹ FAQ
-
-### ❓Sandbox Not Working?
-
-Follow this checklist to troubleshoot:
-
-- [ ] **Is your machine compatible with gVisor?**
-
- Ensure that your system supports gVisor. Refer to the [gVisor installation guide](https://gvisor.dev/docs/user_guide/install/).
-
-- [ ] **Is gVisor properly installed?**
-
- **Common error:**
-
- `HTTPConnectionPool(host='sandbox-executor-manager', port=9385): Read timed out.`
-
- Cause: `runsc` is an unknown or invalid Docker runtime.
- **Fix:**
-
- - Install gVisor
-
- - Restart Docker
-
- - Test with:
-
- ```bash
- docker run --rm --runtime=runsc hello-world
- ```
-
-- [ ] **Is `sandbox-executor-manager` mapped in `/etc/hosts`?**
-
- **Common error:**
-
- `HTTPConnectionPool(host='none', port=9385): Max retries exceeded.`
-
- **Fix:**
-
- Add the following entry to `/etc/hosts`:
-
- ```text
- 127.0.0.1 es01 infinity mysql minio redis sandbox-executor-manager
- ```
-
-- [ ] **Are you running the latest executor manager image?**
-
- **Common error:**
-
- `docker: Error response from daemon: client version 1.43 is too old. Minimum supported API version is 1.44`
-
- **Fix:**
-
- Pull the refreshed image that bundles Docker CLI `29.1.0`, or rebuild it in `./sandbox/executor_manager`:
-
- ```bash
- docker pull infiniflow/sandbox-executor-manager:latest
- # or
- docker build -t sandbox-executor-manager:latest ./sandbox/executor_manager
- ```
-
-- [ ] **Have you enabled sandbox-related configurations in RAGFlow?**
-
- Double-check that all sandbox settings are correctly enabled in your RAGFlow configuration.
-
-- [ ] **Have you pulled the required base images for the runners?**
-
- **Common error:**
-
- `HTTPConnectionPool(host='sandbox-executor-manager', port=9385): Read timed out.`
-
- Cause: no runner was started.
-
- **Fix:**
-
- Pull the necessary base images:
-
- ```bash
- docker pull infiniflow/sandbox-base-nodejs:latest
- docker pull infiniflow/sandbox-base-python:latest
- ```
-
-- [ ] **Did you restart the service after making changes?**
-
- Any changes to configuration or environment require a full service restart to take effect.
-
-
-### ❓Container pool is busy?
-
-All available runners are currently in use, executing tasks/running code. Please try again shortly, or consider increasing the pool size in the configuration to improve availability and reduce wait times.
-
-## 🀝 Contribution
-
-Contributions are welcome!
diff --git a/agent/sandbox/asserts/code_executor_manager.svg b/agent/sandbox/asserts/code_executor_manager.svg
deleted file mode 100644
index 710beabf21..0000000000
--- a/agent/sandbox/asserts/code_executor_manager.svg
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Do not edit this file with editors other than draw.io -->
-<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
-<svg xmlns="http://www.w3.org/2000/svg" style="background: transparent; background-color: transparent; color-scheme: light dark;" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1058px" height="581px" viewBox="-0.5 -0.5 1058 581" content="&lt;mxfile host=&quot;app.diagrams.net&quot; agent=&quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:138.0) Gecko/20100101 Firefox/138.0&quot; version=&quot;27.0.8&quot;&gt;&#xA; &lt;diagram name=&quot;Page-1&quot; id=&quot;SWtVYv8wlh6JJXHhfL9S&quot;&gt;&#xA; &lt;mxGraphModel dx=&quot;2063&quot; dy=&quot;899&quot; grid=&quot;1&quot; gridSize=&quot;10&quot; guides=&quot;1&quot; tooltips=&quot;1&quot; connect=&quot;1&quot; arrows=&quot;1&quot; fold=&quot;1&quot; page=&quot;1&quot; pageScale=&quot;1&quot; pageWidth=&quot;850&quot; pageHeight=&quot;1100&quot; math=&quot;0&quot; shadow=&quot;0&quot;&gt;&#xA; &lt;root&gt;&#xA; &lt;mxCell id=&quot;0&quot; /&gt;&#xA; &lt;mxCell id=&quot;1&quot; parent=&quot;0&quot; /&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-20&quot; value=&quot;&quot; style=&quot;rounded=1;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;-47.5&quot; y=&quot;400&quot; width=&quot;735&quot; height=&quot;360&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-15&quot; style=&quot;edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.25;exitY=1;exitDx=0;exitDy=0;entryX=0.25;entryY=0;entryDx=0;entryDy=0;fontSize=13;&quot; edge=&quot;1&quot; parent=&quot;1&quot; source=&quot;Mp0bcvQGua8Wo26LydRW-1&quot; target=&quot;Mp0bcvQGua8Wo26LydRW-3&quot;&gt;&#xA; &lt;mxGeometry relative=&quot;1&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-1&quot; value=&quot;RAGFlow&quot; style=&quot;rounded=1;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;260&quot; y=&quot;180&quot; width=&quot;120&quot; height=&quot;60&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-17&quot; style=&quot;edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.75;exitY=0;exitDx=0;exitDy=0;entryX=0.75;entryY=1;entryDx=0;entryDy=0;fontSize=13;&quot; edge=&quot;1&quot; parent=&quot;1&quot; source=&quot;Mp0bcvQGua8Wo26LydRW-3&quot; target=&quot;Mp0bcvQGua8Wo26LydRW-1&quot;&gt;&#xA; &lt;mxGeometry relative=&quot;1&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-3&quot; value=&quot;executor_manager&quot; style=&quot;rounded=1;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;260&quot; y=&quot;280&quot; width=&quot;120&quot; height=&quot;60&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-14&quot; value=&quot;Code executor pool&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;250&quot; y=&quot;520&quot; width=&quot;140&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-18&quot; value=&quot;code run reqest&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;170&quot; y=&quot;248&quot; width=&quot;110&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-19&quot; value=&quot;response&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;365&quot; y=&quot;248&quot; width=&quot;80&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-21&quot; value=&quot;executor_manager lifespan&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;675&quot; y=&quot;370&quot; width=&quot;180&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-22&quot; style=&quot;edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.25;exitY=1;exitDx=0;exitDy=0;entryX=0.459;entryY=0;entryDx=0;entryDy=0;entryPerimeter=0;fontSize=13;&quot; edge=&quot;1&quot; parent=&quot;1&quot; source=&quot;Mp0bcvQGua8Wo26LydRW-3&quot; target=&quot;Mp0bcvQGua8Wo26LydRW-20&quot;&gt;&#xA; &lt;mxGeometry relative=&quot;1&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-26&quot; style=&quot;edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.542;exitY=0;exitDx=0;exitDy=0;entryX=0.75;entryY=1;entryDx=0;entryDy=0;exitPerimeter=0;fontSize=13;&quot; edge=&quot;1&quot; parent=&quot;1&quot; source=&quot;Mp0bcvQGua8Wo26LydRW-20&quot; target=&quot;Mp0bcvQGua8Wo26LydRW-3&quot;&gt;&#xA; &lt;mxGeometry relative=&quot;1&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-27&quot; value=&quot;patch run task&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;175&quot; y=&quot;358&quot; width=&quot;110&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-28&quot; value=&quot;code result&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;345&quot; y=&quot;358&quot; width=&quot;90&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-29&quot; value=&quot;Before: creating gVisor guarded code executor pool&amp;amp;nbsp; &quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;690&quot; y=&quot;455&quot; width=&quot;320&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-37&quot; value=&quot;After: resource clean up&amp;amp;nbsp; &quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;690&quot; y=&quot;655&quot; width=&quot;170&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-38&quot; value=&quot;&quot; style=&quot;group;fontSize=13;&quot; vertex=&quot;1&quot; connectable=&quot;0&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;28.75&quot; y=&quot;420&quot; width=&quot;582.5&quot; height=&quot;100&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-5&quot; value=&quot;&quot; style=&quot;rounded=0;whiteSpace=wrap;html=1;container=0;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry width=&quot;582.5&quot; height=&quot;100&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-6&quot; value=&quot;&amp;lt;div&amp;gt;&amp;lt;br&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;Python&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;in&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;runsc&amp;lt;/div&amp;gt;&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;41.25&quot; y=&quot;10&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-8&quot; value=&quot;&amp;lt;div&amp;gt;&amp;lt;br&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;&amp;lt;br&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;Python&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;in&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;runsc&amp;lt;/div&amp;gt;&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;181.25&quot; y=&quot;10&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-9&quot; value=&quot;&amp;lt;div&amp;gt;&amp;lt;br&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;&amp;lt;br&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;Node.js&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;in&amp;lt;/div&amp;gt;&amp;lt;div&amp;gt;runsc&amp;lt;/div&amp;gt;&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;321.25&quot; y=&quot;10&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-13&quot; value=&quot;&amp;lt;br&amp;gt;&amp;lt;div&amp;gt;...&amp;lt;/div&amp;gt;&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;461.25&quot; y=&quot;10&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-30&quot; value=&quot;gVisor&quot; style=&quot;rounded=0;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;46.25&quot; y=&quot;15&quot; width=&quot;70&quot; height=&quot;20&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-31&quot; value=&quot;gVisor&quot; style=&quot;rounded=0;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;186.25&quot; y=&quot;15&quot; width=&quot;70&quot; height=&quot;20&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-32&quot; value=&quot;gVisor&quot; style=&quot;rounded=0;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;326.25&quot; y=&quot;15&quot; width=&quot;70&quot; height=&quot;20&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-33&quot; value=&quot;gVisor&quot; style=&quot;rounded=0;whiteSpace=wrap;html=1;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;Mp0bcvQGua8Wo26LydRW-38&quot;&gt;&#xA; &lt;mxGeometry x=&quot;466.25&quot; y=&quot;15&quot; width=&quot;70&quot; height=&quot;20&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-40&quot; value=&quot;&quot; style=&quot;rounded=0;whiteSpace=wrap;html=1;container=0;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;28.75&quot; y=&quot;630&quot; width=&quot;582.5&quot; height=&quot;100&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-41&quot; value=&quot;&amp;lt;div&amp;gt;x_x&amp;lt;/div&amp;gt;&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;70&quot; y=&quot;640&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-42&quot; value=&quot;x_x&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;210&quot; y=&quot;640&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-43&quot; value=&quot;x_x&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;350&quot; y=&quot;640&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-44&quot; value=&quot;&amp;lt;br&amp;gt;&amp;lt;div&amp;gt;...&amp;lt;/div&amp;gt;&quot; style=&quot;whiteSpace=wrap;html=1;aspect=fixed;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;490&quot; y=&quot;640&quot; width=&quot;80&quot; height=&quot;80&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-59&quot; value=&quot;Clean up&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;285&quot; y=&quot;730&quot; width=&quot;80&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;mxCell id=&quot;Mp0bcvQGua8Wo26LydRW-60&quot; value=&quot;Task orchestration and pool management...&quot; style=&quot;text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;fontSize=13;&quot; vertex=&quot;1&quot; parent=&quot;1&quot;&gt;&#xA; &lt;mxGeometry x=&quot;175&quot; y=&quot;565&quot; width=&quot;270&quot; height=&quot;30&quot; as=&quot;geometry&quot; /&gt;&#xA; &lt;/mxCell&gt;&#xA; &lt;/root&gt;&#xA; &lt;/mxGraphModel&gt;&#xA; &lt;/diagram&gt;&#xA;&lt;/mxfile&gt;&#xA;"><defs/><g><g data-cell-id="0"><g data-cell-id="1"><g data-cell-id="Mp0bcvQGua8Wo26LydRW-20"><g><rect x="0.5" y="220" width="735" height="360" rx="54" ry="54" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-15"><g><path d="M 338 60 L 338 93.63" fill="none" stroke="#000000" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 338 98.88 L 334.5 91.88 L 338 93.63 L 341.5 91.88 Z" fill="#000000" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-1"><g><rect x="308" y="0" width="120" height="60" rx="9" ry="9" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 30px; margin-left: 309px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">RAGFlow</div></div></div></foreignObject><text x="368" y="34" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">RAGFlow</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-17"><g><path d="M 398 100 L 398 66.37" fill="none" stroke="#000000" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 398 61.12 L 401.5 68.12 L 398 66.37 L 394.5 68.12 Z" fill="#000000" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-3"><g><rect x="308" y="100" width="120" height="60" rx="9" ry="9" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 118px; height: 1px; padding-top: 130px; margin-left: 309px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">executor_manager</div></div></div></foreignObject><text x="368" y="134" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">executor_manager</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-14"><g><rect x="298" y="340" width="140" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 355px; margin-left: 368px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">Code executor pool</div></div></div></foreignObject><text x="368" y="359" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Code executor pool</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-18"><g><rect x="218" y="68" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 83px; margin-left: 273px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">code run reqest</div></div></div></foreignObject><text x="273" y="87" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">code run reqest</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-19"><g><rect x="413" y="68" width="80" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 83px; margin-left: 453px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">response</div></div></div></foreignObject><text x="453" y="87" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">response</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-21"><g><rect x="723" y="190" width="180" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 205px; margin-left: 813px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">executor_manager lifespan</div></div></div></foreignObject><text x="813" y="209" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">executor_manager lifespan</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-22"><g><path d="M 338 160 L 338 190 L 337.89 213.63" fill="none" stroke="#000000" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 337.87 218.88 L 334.4 211.87 L 337.89 213.63 L 341.4 211.9 Z" fill="#000000" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-26"><g><path d="M 398.87 220 L 398.9 190 L 398.19 166.37" fill="none" stroke="#000000" style="stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke-miterlimit="10" pointer-events="stroke"/><path d="M 398.03 161.12 L 401.74 168.01 L 398.19 166.37 L 394.75 168.22 Z" fill="#000000" style="fill: light-dark(rgb(0, 0, 0), rgb(255, 255, 255)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" stroke-miterlimit="10" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-27"><g><rect x="223" y="178" width="110" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 193px; margin-left: 278px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">patch run task</div></div></div></foreignObject><text x="278" y="197" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">patch run task</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-28"><g><rect x="393" y="178" width="90" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 193px; margin-left: 438px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">code result</div></div></div></foreignObject><text x="438" y="197" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">code result</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-29"><g><rect x="738" y="275" width="320" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 290px; margin-left: 898px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">Before: creating gVisor guarded code executor poolΒ  </div></div></div></foreignObject><text x="898" y="294" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Before: creating gVisor guarded code executor poo...</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-37"><g><rect x="738" y="475" width="170" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 490px; margin-left: 823px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">After: resource clean upΒ  </div></div></div></foreignObject><text x="823" y="494" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">After: resource clean upΒ  </text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-38"><g/><g data-cell-id="Mp0bcvQGua8Wo26LydRW-5"><g><rect x="76.75" y="240" width="582.5" height="100" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-6"><g><rect x="118" y="250" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 290px; margin-left: 119px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; "><div><br /></div><div>Python</div><div>in</div><div>runsc</div></div></div></div></foreignObject><text x="158" y="294" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Python...</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-8"><g><rect x="258" y="250" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 290px; margin-left: 259px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; "><div><br /></div><div><br /></div><div>Python</div><div>in</div><div>runsc</div></div></div></div></foreignObject><text x="298" y="294" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Python...</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-9"><g><rect x="398" y="250" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 290px; margin-left: 399px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; "><div><br /></div><div><br /></div><div>Node.js</div><div>in</div><div>runsc</div></div></div></div></foreignObject><text x="438" y="294" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Node.js...</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-13"><g><rect x="538" y="250" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 290px; margin-left: 539px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; "><br /><div>...</div></div></div></div></foreignObject><text x="578" y="294" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">&#xa;...</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-30"><g><rect x="123" y="255" width="70" height="20" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 68px; height: 1px; padding-top: 265px; margin-left: 124px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">gVisor</div></div></div></foreignObject><text x="158" y="269" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">gVisor</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-31"><g><rect x="263" y="255" width="70" height="20" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 68px; height: 1px; padding-top: 265px; margin-left: 264px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">gVisor</div></div></div></foreignObject><text x="298" y="269" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">gVisor</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-32"><g><rect x="403" y="255" width="70" height="20" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 68px; height: 1px; padding-top: 265px; margin-left: 404px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">gVisor</div></div></div></foreignObject><text x="438" y="269" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">gVisor</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-33"><g><rect x="543" y="255" width="70" height="20" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 68px; height: 1px; padding-top: 265px; margin-left: 544px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">gVisor</div></div></div></foreignObject><text x="578" y="269" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">gVisor</text></switch></g></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-40"><g><rect x="76.75" y="450" width="582.5" height="100" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-41"><g><rect x="118" y="460" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 500px; margin-left: 119px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; "><div>x_x</div></div></div></div></foreignObject><text x="158" y="504" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">x_x</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-42"><g><rect x="258" y="460" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 500px; margin-left: 259px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">x_x</div></div></div></foreignObject><text x="298" y="504" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">x_x</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-43"><g><rect x="398" y="460" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 500px; margin-left: 399px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; ">x_x</div></div></div></foreignObject><text x="438" y="504" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">x_x</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-44"><g><rect x="538" y="460" width="80" height="80" fill="#ffffff" style="fill: light-dark(#ffffff, var(--ge-dark-color, #121212)); stroke: light-dark(rgb(0, 0, 0), rgb(255, 255, 255));" stroke="#000000" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 78px; height: 1px; padding-top: 500px; margin-left: 539px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: normal; word-wrap: normal; "><br /><div>...</div></div></div></div></foreignObject><text x="578" y="504" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">&#xa;...</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-59"><g><rect x="333" y="550" width="80" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 565px; margin-left: 373px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">Clean up</div></div></div></foreignObject><text x="373" y="569" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Clean up</text></switch></g></g></g><g data-cell-id="Mp0bcvQGua8Wo26LydRW-60"><g><rect x="223" y="385" width="270" height="30" fill="none" stroke="none" pointer-events="all"/></g><g><g transform="translate(-0.5 -0.5)"><switch><foreignObject style="overflow: visible; text-align: left;" pointer-events="none" width="100%" height="100%" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: flex; align-items: unsafe center; justify-content: unsafe center; width: 1px; height: 1px; padding-top: 400px; margin-left: 358px;"><div style="box-sizing: border-box; font-size: 0; text-align: center; color: #000000; "><div style="display: inline-block; font-size: 13px; font-family: &quot;Helvetica&quot;; color: light-dark(#000000, #ffffff); line-height: 1.2; pointer-events: all; white-space: nowrap; ">Task orchestration and pool management...</div></div></div></foreignObject><text x="358" y="404" fill="light-dark(#000000, #ffffff)" font-family="&quot;Helvetica&quot;" font-size="13px" text-anchor="middle">Task orchestration and pool management...</text></switch></g></g></g></g></g></g><switch><g requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"/><a transform="translate(0,-5)" xlink:href="https://www.drawio.com/doc/faq/svg-export-text-problems" target="_blank"><text text-anchor="middle" font-size="10px" x="50%" y="100%">Text is not SVG - cannot display</text></a></switch></svg>
\ No newline at end of file
diff --git a/agent/sandbox/client.py b/agent/sandbox/client.py
deleted file mode 100644
index 9c28048bfc..0000000000
--- a/agent/sandbox/client.py
+++ /dev/null
@@ -1,253 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Sandbox client for agent components.
-
-This module provides a unified interface for agent components to interact
-with the configured sandbox provider.
-"""
-
-import json
-import logging
-from typing import Dict, Any, Optional
-
-from api.db.services.system_settings_service import SystemSettingsService
-from agent.sandbox.providers import ProviderManager
-from agent.sandbox.providers.base import ExecutionResult, SandboxProviderConfigError
-
-logger = logging.getLogger(__name__)
-
-
-# Global provider manager instance
-_provider_manager: Optional[ProviderManager] = None
-
-
-def get_provider_manager() -> ProviderManager:
- """
- Get the global provider manager instance.
-
- Returns:
- ProviderManager instance with active provider loaded
- """
- global _provider_manager
-
- if _provider_manager is not None:
- return _provider_manager
-
- _provider_manager = ProviderManager()
- _load_provider_from_settings()
-
- return _provider_manager
-
-
-def _load_provider_from_settings() -> None:
- """
- Load sandbox provider from system settings and configure the provider manager.
-
- This function resolves the active provider type, then loads configuration
- from system settings.
- """
- global _provider_manager
-
- if _provider_manager is None:
- return
-
- try:
- provider_type = _resolve_provider_type()
- config = _load_provider_config(provider_type)
-
- # Import and instantiate the provider
- from agent.sandbox.providers import (
- SelfManagedProvider,
- AliyunCodeInterpreterProvider,
- E2BProvider,
- LocalProvider,
- SSHProvider,
- TenkiProvider,
- UCloudAgentSandboxProvider,
- )
-
- provider_classes = {
- "self_managed": SelfManagedProvider,
- "aliyun_codeinterpreter": AliyunCodeInterpreterProvider,
- "e2b": E2BProvider,
- "local": LocalProvider,
- "ssh": SSHProvider,
- "tenki": TenkiProvider,
- "ucloud_agent_sandbox": UCloudAgentSandboxProvider,
- }
-
- if provider_type not in provider_classes:
- logger.error(f"Unknown provider type: {provider_type}")
- return
-
- provider_class = provider_classes[provider_type]
- provider = provider_class()
-
- # Initialize the provider
- if not provider.initialize(config):
- message = f"Failed to initialize sandbox provider: {provider_type}. Config keys: {list(config.keys())}"
- if provider_type in {"local", "ssh", "tenki", "ucloud_agent_sandbox"}:
- raise SandboxProviderConfigError(message)
- logger.error(message)
- return
-
- # Set the active provider
- _provider_manager.set_provider(provider_type, provider)
- logger.info(f"Sandbox provider '{provider_type}' initialized successfully")
-
- except SandboxProviderConfigError:
- raise
- except Exception as e:
- logger.error(f"Failed to load sandbox provider from settings: {e}")
- import traceback
-
- traceback.print_exc()
-
-
-def _load_provider_config_from_settings(provider_type: str) -> Dict[str, Any]:
- provider_config_settings = SystemSettingsService.get_by_name(f"sandbox.{provider_type}")
- if not provider_config_settings:
- logger.warning(f"No configuration found for provider: {provider_type}")
- return {}
-
- try:
- return json.loads(provider_config_settings[0].value)
- except json.JSONDecodeError as e:
- logger.error(f"Failed to parse sandbox config for {provider_type}: {e}")
- return {}
-
-
-def _resolve_provider_type() -> str:
- provider_type_settings = SystemSettingsService.get_by_name("sandbox.provider_type")
- if not provider_type_settings:
- return "self_managed"
- return provider_type_settings[0].value
-
-
-def _load_provider_config(provider_type: str) -> Dict[str, Any]:
- return _load_provider_config_from_settings(provider_type)
-
-
-def reload_provider() -> None:
- """
- Reload the sandbox provider from system settings.
-
- Use this function when sandbox settings have been updated.
- """
- global _provider_manager
- _provider_manager = None
- _load_provider_from_settings()
-
-
-def execute_code(code: str, language: str = "python", timeout: int = 30, arguments: Optional[Dict[str, Any]] = None) -> ExecutionResult:
- """
- Execute code in the configured sandbox.
-
- This is the main entry point for agent components to execute code.
-
- Args:
- code: Source code to execute
- language: Programming language (python, nodejs, javascript)
- timeout: Maximum execution time in seconds
- arguments: Optional arguments dict to pass to main() function
-
- Returns:
- ExecutionResult containing stdout, stderr, exit_code, and metadata
-
- Raises:
- RuntimeError: If no provider is configured or execution fails
- """
- provider_manager = get_provider_manager()
-
- if not provider_manager.is_configured():
- raise RuntimeError("No sandbox provider configured. Please configure sandbox settings in the admin panel.")
-
- provider = provider_manager.get_provider()
- provider_name = provider_manager.get_provider_name() or getattr(provider, "__class__", type(provider)).__name__
-
- logger.info(
- "CodeExec using sandbox provider '%s' (language=%s, timeout=%ss)",
- provider_name,
- language,
- timeout,
- )
-
- # Create a sandbox instance
- instance = provider.create_instance(template=language)
-
- try:
- # Execute the code
- result = provider.execute_code(instance_id=instance.instance_id, code=code, language=language, timeout=timeout, arguments=arguments)
-
- return result
-
- finally:
- # Clean up the instance
- try:
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- logger.warning(f"Failed to destroy sandbox instance {instance.instance_id}: {e}")
-
-
-def health_check() -> bool:
- """
- Check if the sandbox provider is healthy.
-
- Returns:
- True if provider is configured and healthy, False otherwise
- """
- try:
- provider_manager = get_provider_manager()
-
- if not provider_manager.is_configured():
- return False
-
- provider = provider_manager.get_provider()
- return provider.health_check()
-
- except Exception as e:
- logger.error(f"Sandbox health check failed: {e}")
- return False
-
-
-def get_provider_info() -> Dict[str, Any]:
- """
- Get information about the current sandbox provider.
-
- Returns:
- Dictionary with provider information:
- - provider_type: Type of the active provider
- - configured: Whether provider is configured
- - healthy: Whether provider is healthy
- """
- try:
- provider_manager = get_provider_manager()
-
- return {
- "provider_type": provider_manager.get_provider_name(),
- "configured": provider_manager.is_configured(),
- "healthy": health_check(),
- }
-
- except Exception as e:
- logger.error(f"Failed to get provider info: {e}")
- return {
- "provider_type": None,
- "configured": False,
- "healthy": False,
- }
diff --git a/agent/sandbox/docker-compose.yml b/agent/sandbox/docker-compose.yml
deleted file mode 100644
index 7bb39de55f..0000000000
--- a/agent/sandbox/docker-compose.yml
+++ /dev/null
@@ -1,46 +0,0 @@
-services:
- sandbox-executor-manager:
- build:
- context: ./executor_manager
- dockerfile: Dockerfile
- image: sandbox-executor-manager:latest
- runtime: runc
- privileged: true
- # Bind to loopback only: the /run endpoint executes arbitrary sandboxed code.
- ports:
- - "127.0.0.1:${SANDBOX_EXECUTOR_MANAGER_PORT:-9385}:9385"
- volumes:
- - /var/run/docker.sock:/var/run/docker.sock
- networks:
- - sandbox-network
- restart: always
- security_opt:
- - no-new-privileges:true
- environment:
- - SANDBOX_EXECUTOR_MANAGER_POOL_SIZE=${SANDBOX_EXECUTOR_MANAGER_POOL_SIZE:-5}
- - SANDBOX_BASE_PYTHON_IMAGE=${SANDBOX_BASE_PYTHON_IMAGE-sandbox-base-python:latest}
- - SANDBOX_BASE_NODEJS_IMAGE=${SANDBOX_BASE_NODEJS_IMAGE-sandbox-base-nodejs:latest}
- - SANDBOX_ENABLE_SECCOMP=${SANDBOX_ENABLE_SECCOMP:-false}
- - SANDBOX_MAX_MEMORY=${SANDBOX_MAX_MEMORY:-256m} # b, k, m, g
- - SANDBOX_TIMEOUT=${SANDBOX_TIMEOUT:-10s} # s, m, 1m30s
- # Shared secret for the /run API. Authentication is fail-closed: with
- # no token the API refuses /run (503) unless the explicit opt-in flag
- # below is set.
- - SANDBOX_EXECUTOR_MANAGER_API_TOKEN=${SANDBOX_EXECUTOR_MANAGER_API_TOKEN:-}
- # Explicit, risk-accepting opt-in for deployments that cannot provide a
- # token. Leave unset/false in normal deployments.
- - SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=${SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED:-false}
- # Sandbox runner containers get no external network by default.
- - SANDBOX_CONTAINER_NETWORK=${SANDBOX_CONTAINER_NETWORK:-none}
- # Rate limits: a small pre-auth throttle applied to all /run traffic,
- # and the larger per-address quota for authenticated execution.
- - SANDBOX_RUN_PREAUTH_RATE_LIMIT=${SANDBOX_RUN_PREAUTH_RATE_LIMIT:-30/minute}
- - SANDBOX_RUN_RATE_LIMIT=${SANDBOX_RUN_RATE_LIMIT:-120/minute}
- healthcheck:
- test: ["CMD-SHELL", "curl --fail http://localhost:9385/healthz || exit 1"]
- interval: 10s
- timeout: 5s
- retries: 5
-networks:
- sandbox-network:
- driver: bridge
diff --git a/agent/sandbox/executor_manager/Dockerfile b/agent/sandbox/executor_manager/Dockerfile
deleted file mode 100644
index 56c8338401..0000000000
--- a/agent/sandbox/executor_manager/Dockerfile
+++ /dev/null
@@ -1,41 +0,0 @@
-FROM python:3.11-slim-bookworm
-
-ARG NEED_MIRROR=1
-
-RUN if [ "$NEED_MIRROR" = 1 ]; then \
- grep -rl 'deb.debian.org' /etc/apt/ | xargs sed -i 's|http[s]*://deb.debian.org|https://mirrors.tuna.tsinghua.edu.cn|g'; \
- fi; \
- apt-get update && \
- apt-get install -y curl gcc && \
- rm -rf /var/lib/apt/lists/*
-
-ARG TARGETARCH
-ARG TARGETVARIANT
-
-RUN set -eux; \
- case "${TARGETARCH}${TARGETVARIANT}" in \
- amd64) DOCKER_ARCH=x86_64 ;; \
- arm64) DOCKER_ARCH=aarch64 ;; \
- armv7) DOCKER_ARCH=armhf ;; \
- armv6) DOCKER_ARCH=armel ;; \
- arm64v8) DOCKER_ARCH=aarch64 ;; \
- arm64v7) DOCKER_ARCH=armhf ;; \
- arm*) DOCKER_ARCH=armhf ;; \
- ppc64le) DOCKER_ARCH=ppc64le ;; \
- s390x) DOCKER_ARCH=s390x ;; \
- *) echo "Unsupported architecture: ${TARGETARCH}${TARGETVARIANT}" && exit 1 ;; \
- esac; \
- echo "Downloading Docker for architecture: ${DOCKER_ARCH}"; \
- curl -fsSL "https://download.docker.com/linux/static/stable/${DOCKER_ARCH}/docker-29.1.0.tgz" | \
- tar xz -C /usr/local/bin --strip-components=1 docker/docker; \
- ln -sf /usr/local/bin/docker /usr/bin/docker
-
-COPY --from=ghcr.io/astral-sh/uv:0.7.5 /uv /uvx /bin/
-
-WORKDIR /app
-COPY . .
-
-RUN if [ "$NEED_MIRROR" = 1 ]; then export UV_INDEX_URL="https://pypi.tuna.tsinghua.edu.cn/simple"; else export UV_INDEX_URL="https://pypi.org/simple"; fi && \
- uv pip install --system -r requirements.txt
-
-CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "9385"]
diff --git a/agent/sandbox/executor_manager/api/__init__.py b/agent/sandbox/executor_manager/api/__init__.py
deleted file mode 100644
index 177b91dd05..0000000000
--- a/agent/sandbox/executor_manager/api/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
diff --git a/agent/sandbox/executor_manager/api/handlers.py b/agent/sandbox/executor_manager/api/handlers.py
deleted file mode 100644
index d6ae1ee536..0000000000
--- a/agent/sandbox/executor_manager/api/handlers.py
+++ /dev/null
@@ -1,47 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import base64
-
-from core.container import _CONTAINER_EXECUTION_SEMAPHORES
-from core.logger import logger
-from fastapi import Request
-from models.enums import ResultStatus, SupportLanguage
-from models.schemas import CodeExecutionRequest, CodeExecutionResult
-from services.execution import execute_code
-from services.security import analyze_code_security
-
-
-async def healthz_handler():
- return {"status": "ok"}
-
-
-async def run_code_handler(req: CodeExecutionRequest, request: Request):
- logger.info("🟒 Received /run request")
-
- async with _CONTAINER_EXECUTION_SEMAPHORES[req.language]:
- code = base64.b64decode(req.code_b64).decode("utf-8")
- if req.language == SupportLanguage.NODEJS:
- code += "\n\nmodule.exports = { main };"
- req.code_b64 = base64.b64encode(code.encode("utf-8")).decode("utf-8")
- is_safe, issues = analyze_code_security(code, language=req.language)
- if not is_safe:
- issue_details = "\n".join([f"Line {lineno}: {issue}" for issue, lineno in issues])
- return CodeExecutionResult(status=ResultStatus.PROGRAM_RUNNER_ERROR, stdout="", stderr=issue_details, exit_code=-999, detail="Code is unsafe")
-
- try:
- return await execute_code(req)
- except Exception as e:
- return CodeExecutionResult(status=ResultStatus.PROGRAM_RUNNER_ERROR, stdout="", stderr=str(e), exit_code=-999, detail="unhandled_exception")
diff --git a/agent/sandbox/executor_manager/api/routes.py b/agent/sandbox/executor_manager/api/routes.py
deleted file mode 100644
index 0c426c049e..0000000000
--- a/agent/sandbox/executor_manager/api/routes.py
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-from fastapi import APIRouter, Depends
-from services.auth import require_api_token
-from services.limiter import RUN_RATE_LIMIT, limiter
-from services.preauth import preauth_rate_limit
-
-from api.handlers import healthz_handler, run_code_handler
-
-router = APIRouter()
-
-router.get("/")(healthz_handler)
-router.get("/healthz")(healthz_handler)
-# Execution endpoints throttle ALL traffic per client address before
-# authentication (so invalid-token floods eventually receive 429), then
-# require the shared-secret token, then apply the larger authenticated
-# execution quota. Health probes stay unauthenticated.
-router.post("/run", dependencies=[Depends(preauth_rate_limit), Depends(require_api_token)])(limiter.limit(RUN_RATE_LIMIT)(run_code_handler))
diff --git a/agent/sandbox/executor_manager/core/__init__.py b/agent/sandbox/executor_manager/core/__init__.py
deleted file mode 100644
index 177b91dd05..0000000000
--- a/agent/sandbox/executor_manager/core/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
diff --git a/agent/sandbox/executor_manager/core/config.py b/agent/sandbox/executor_manager/core/config.py
deleted file mode 100644
index 6e9989dc08..0000000000
--- a/agent/sandbox/executor_manager/core/config.py
+++ /dev/null
@@ -1,45 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import os
-from contextlib import asynccontextmanager
-
-from fastapi import FastAPI
-from services.auth import log_authentication_startup_state
-from util import format_timeout_duration, parse_timeout_duration
-
-from core.container import init_containers, teardown_containers
-from core.logger import logger
-
-TIMEOUT = parse_timeout_duration(os.getenv("SANDBOX_TIMEOUT", "10s"))
-
-
-@asynccontextmanager
-async def _lifespan(app: FastAPI):
- """Asynchronous lifecycle management"""
- size = int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", 1))
-
- success_count, total_task_count = await init_containers(size)
- logger.info(f"\nπŸ“Š Container pool initialization complete: {success_count}/{total_task_count} available")
-
- yield
-
- await teardown_containers()
-
-
-def init():
- logger.info(f"Global timeout: {format_timeout_duration(TIMEOUT)}")
- log_authentication_startup_state()
- return _lifespan
diff --git a/agent/sandbox/executor_manager/core/container.py b/agent/sandbox/executor_manager/core/container.py
deleted file mode 100644
index 4093b262b6..0000000000
--- a/agent/sandbox/executor_manager/core/container.py
+++ /dev/null
@@ -1,196 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import asyncio
-import contextlib
-import os
-from queue import Empty, Queue
-
-from models.enums import SupportLanguage
-from util import env_setting_enabled, is_valid_memory_limit
-from utils.common import async_run_command
-
-from core.logger import logger
-
-_CONTAINER_QUEUES: dict[SupportLanguage, Queue] = {}
-_CONTAINER_LOCK: asyncio.Lock = asyncio.Lock()
-_CONTAINER_EXECUTION_SEMAPHORES: dict[SupportLanguage, asyncio.Semaphore] = {}
-
-
-async def init_containers(size: int) -> tuple[int, int]:
- global _CONTAINER_QUEUES
- _CONTAINER_QUEUES = {SupportLanguage.PYTHON: Queue(), SupportLanguage.NODEJS: Queue()}
-
- async with _CONTAINER_LOCK:
- while not _CONTAINER_QUEUES[SupportLanguage.PYTHON].empty():
- _CONTAINER_QUEUES[SupportLanguage.PYTHON].get_nowait()
- while not _CONTAINER_QUEUES[SupportLanguage.NODEJS].empty():
- _CONTAINER_QUEUES[SupportLanguage.NODEJS].get_nowait()
-
- for language in SupportLanguage:
- _CONTAINER_EXECUTION_SEMAPHORES[language] = asyncio.Semaphore(size)
-
- create_tasks = []
- for i in range(size):
- name = f"sandbox_python_{i}"
- logger.info(f"πŸ› οΈ Creating Python container {i + 1}/{size}")
- create_tasks.append(_prepare_container(name, SupportLanguage.PYTHON))
-
- name = f"sandbox_nodejs_{i}"
- logger.info(f"πŸ› οΈ Creating Node.js container {i + 1}/{size}")
- create_tasks.append(_prepare_container(name, SupportLanguage.NODEJS))
-
- results = await asyncio.gather(*create_tasks, return_exceptions=True)
- success_count = sum(1 for r in results if r is True)
- total_task_count = len(create_tasks)
- return success_count, total_task_count
-
-
-async def teardown_containers():
- async with _CONTAINER_LOCK:
- while not _CONTAINER_QUEUES[SupportLanguage.PYTHON].empty():
- name = _CONTAINER_QUEUES[SupportLanguage.PYTHON].get_nowait()
- await async_run_command("docker", "rm", "-f", name, timeout=5)
- while not _CONTAINER_QUEUES[SupportLanguage.NODEJS].empty():
- name = _CONTAINER_QUEUES[SupportLanguage.NODEJS].get_nowait()
- await async_run_command("docker", "rm", "-f", name, timeout=5)
-
-
-async def _prepare_container(name: str, language: SupportLanguage) -> bool:
- """Prepare a single container"""
- with contextlib.suppress(Exception):
- await async_run_command("docker", "rm", "-f", name, timeout=5)
-
- if await create_container(name, language):
- _CONTAINER_QUEUES[language].put(name)
- return True
- return False
-
-
-async def create_container(name: str, language: SupportLanguage) -> bool:
- """Asynchronously create a container"""
- create_args = [
- "docker",
- "run",
- "-d",
- "--runtime=runsc",
- "--name",
- name,
- "--read-only",
- "--tmpfs",
- "/workspace:rw,exec,size=100M,uid=65534,gid=65534",
- "--tmpfs",
- "/tmp:rw,exec,size=50M",
- "--user",
- "nobody",
- "--workdir",
- "/workspace",
- ]
- # Network isolation by default: sandboxed code gets no external network
- # access unless a deployment explicitly opts in (e.g. needing pip/npm
- # installs or outbound requests) via SANDBOX_CONTAINER_NETWORK.
- container_network = (os.getenv("SANDBOX_CONTAINER_NETWORK") or "").strip() or "none"
- create_args.extend(["--network", container_network])
- if os.getenv("SANDBOX_MAX_MEMORY"):
- memory_limit = os.getenv("SANDBOX_MAX_MEMORY") or "256m"
- if is_valid_memory_limit(memory_limit):
- logger.info(f"SANDBOX_MAX_MEMORY: {os.getenv('SANDBOX_MAX_MEMORY')}")
- else:
- logger.info("Invalid SANDBOX_MAX_MEMORY, using default value: 256m")
- memory_limit = "256m"
- create_args.extend(["--memory", memory_limit])
- else:
- logger.info("Set default SANDBOX_MAX_MEMORY: 256m")
- create_args.extend(["--memory", "256m"])
-
- if env_setting_enabled("SANDBOX_ENABLE_SECCOMP", "false"):
- logger.info(f"SANDBOX_ENABLE_SECCOMP: {os.getenv('SANDBOX_ENABLE_SECCOMP')}")
- create_args.extend(["--security-opt", "seccomp=/app/seccomp-profile-default.json"])
-
- if language == SupportLanguage.PYTHON:
- create_args.append(os.getenv("SANDBOX_BASE_PYTHON_IMAGE", "sandbox-base-python:latest"))
- elif language == SupportLanguage.NODEJS:
- create_args.append(os.getenv("SANDBOX_BASE_NODEJS_IMAGE", "sandbox-base-nodejs:latest"))
-
- logger.info(f"Sandbox config:\n\t {create_args}")
-
- try:
- return_code, _, stderr = await async_run_command(*create_args, timeout=10)
- if return_code != 0:
- logger.error(f"❌ Container creation failed {name}: {stderr}")
- return False
-
- if language == SupportLanguage.NODEJS:
- copy_cmd = ["docker", "exec", name, "bash", "-c", "cp -a /app/node_modules /workspace/"]
- return_code, _, stderr = await async_run_command(*copy_cmd, timeout=10)
- if return_code != 0:
- logger.error(f"❌ Failed to prepare dependencies for {name}: {stderr}")
- return False
-
- return await container_is_running(name)
- except Exception as e:
- logger.error(f"❌ Container creation exception {name}: {e!s}")
- return False
-
-
-async def recreate_container(name: str, language: SupportLanguage) -> bool:
- """Asynchronously recreate a container"""
- logger.info(f"πŸ› οΈ Recreating container: {name}")
- try:
- await async_run_command("docker", "rm", "-f", name, timeout=5)
-
- return await create_container(name, language)
- except Exception as e:
- logger.error(f"❌ Container {name} recreation failed: {e!s}")
- return False
-
-
-async def release_container(name: str, language: SupportLanguage):
- """Asynchronously release a container"""
- async with _CONTAINER_LOCK:
- if await container_is_running(name):
- _CONTAINER_QUEUES[language].put(name)
- logger.info(f"🟒 Released container: {name} (remaining available: {_CONTAINER_QUEUES[language].qsize()})")
- else:
- logger.warning(f"⚠️ Container {name} has crashed, attempting to recreate...")
- if await recreate_container(name, language):
- _CONTAINER_QUEUES[language].put(name)
- logger.info(f"βœ… Container {name} successfully recreated and returned to queue")
-
-
-async def allocate_container_blocking(language: SupportLanguage, timeout=10) -> str:
- """Asynchronously allocate an available container"""
- start_time = asyncio.get_running_loop().time()
- while asyncio.get_running_loop().time() - start_time < timeout:
- try:
- name = _CONTAINER_QUEUES[language].get_nowait()
- async with _CONTAINER_LOCK:
- if not await container_is_running(name) and not await recreate_container(name, language):
- continue
-
- return name
- except Empty:
- await asyncio.sleep(0.1)
-
- return ""
-
-
-async def container_is_running(name: str) -> bool:
- """Asynchronously check the container status"""
- try:
- return_code, stdout, _ = await async_run_command("docker", "inspect", "-f", "{{.State.Running}}", name, timeout=2)
- return return_code == 0 and stdout.strip() == "true"
- except Exception:
- return False
diff --git a/agent/sandbox/executor_manager/core/logger.py b/agent/sandbox/executor_manager/core/logger.py
deleted file mode 100644
index c393129db2..0000000000
--- a/agent/sandbox/executor_manager/core/logger.py
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import logging
-
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger("sandbox")
diff --git a/agent/sandbox/executor_manager/main.py b/agent/sandbox/executor_manager/main.py
deleted file mode 100644
index ccad79b48a..0000000000
--- a/agent/sandbox/executor_manager/main.py
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-from api.routes import router as api_router
-from core.config import init
-from fastapi import FastAPI
-from services.limiter import limiter, rate_limit_exceeded_handler
-from slowapi.errors import RateLimitExceeded
-
-app = FastAPI(lifespan=init())
-app.include_router(api_router)
-app.state.limiter = limiter
-app.add_exception_handler(RateLimitExceeded, rate_limit_exceeded_handler)
diff --git a/agent/sandbox/executor_manager/models/__init__.py b/agent/sandbox/executor_manager/models/__init__.py
deleted file mode 100644
index 177b91dd05..0000000000
--- a/agent/sandbox/executor_manager/models/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
diff --git a/agent/sandbox/executor_manager/models/enums.py b/agent/sandbox/executor_manager/models/enums.py
deleted file mode 100644
index b575e54c26..0000000000
--- a/agent/sandbox/executor_manager/models/enums.py
+++ /dev/null
@@ -1,47 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-from enum import Enum
-
-
-class SupportLanguage(str, Enum):
- PYTHON = "python"
- NODEJS = "nodejs"
-
-
-class ResultStatus(str, Enum):
- SUCCESS = "success"
- PROGRAM_ERROR = "program_error"
- RESOURCE_LIMIT_EXCEEDED = "resource_limit_exceeded"
- UNAUTHORIZED_ACCESS = "unauthorized_access"
- RUNTIME_ERROR = "runtime_error"
- PROGRAM_RUNNER_ERROR = "program_runner_error"
-
-
-class ResourceLimitType(str, Enum):
- TIME = "time"
- MEMORY = "memory"
- OUTPUT = "output"
-
-
-class UnauthorizedAccessType(str, Enum):
- DISALLOWED_SYSCALL = "disallowed_syscall"
- FILE_ACCESS = "file_access"
- NETWORK_ACCESS = "network_access"
-
-
-class RuntimeErrorType(str, Enum):
- SIGNALLED = "signalled"
- NONZERO_EXIT = "nonzero_exit"
diff --git a/agent/sandbox/executor_manager/models/schemas.py b/agent/sandbox/executor_manager/models/schemas.py
deleted file mode 100644
index ed50c26a18..0000000000
--- a/agent/sandbox/executor_manager/models/schemas.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import base64
-from typing import Any, Optional
-
-from pydantic import BaseModel, Field, field_validator
-
-from models.enums import ResourceLimitType, ResultStatus, RuntimeErrorType, SupportLanguage, UnauthorizedAccessType
-
-
-class ArtifactItem(BaseModel):
- name: str
- mime_type: str
- size: int
- content_b64: str
-
-
-class ExecutionStructuredResult(BaseModel):
- present: bool
- value: Any = None
- type: str = "json"
-
-
-class CodeExecutionResult(BaseModel):
- status: ResultStatus
- stdout: str
- stderr: str
- exit_code: int
- detail: Optional[str] = None
-
- # Resource usage
- time_used_ms: Optional[float] = None
- memory_used_kb: Optional[float] = None
-
- # Error details
- resource_limit_type: Optional[ResourceLimitType] = None
- unauthorized_access_type: Optional[UnauthorizedAccessType] = None
- runtime_error_type: Optional[RuntimeErrorType] = None
-
- # File artifacts produced by code execution (images, PDFs, CSVs, etc.)
- artifacts: list[ArtifactItem] = []
-
- # Structured return value produced by main()
- result: Optional[ExecutionStructuredResult] = None
-
-
-class CodeExecutionRequest(BaseModel):
- code_b64: str = Field(..., description="Base64 encoded code string")
- language: SupportLanguage = Field(default=SupportLanguage.PYTHON, description="Programming language")
- arguments: Optional[dict] = Field(default={}, description="Arguments")
-
- @field_validator("code_b64")
- @classmethod
- def validate_base64(cls, v: str) -> str:
- try:
- base64.b64decode(v, validate=True)
- return v
- except Exception as e:
- raise ValueError(f"Invalid base64 encoding: {str(e)}")
diff --git a/agent/sandbox/executor_manager/pytest.ini b/agent/sandbox/executor_manager/pytest.ini
deleted file mode 100644
index b93bddf2d6..0000000000
--- a/agent/sandbox/executor_manager/pytest.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-[pytest]
-# Unit tests for the executor manager. They use top-level imports resolved
-# against this directory (mirroring WORKDIR /app in the Docker image), so the
-# rootdir must stay here and not pick up the repository-level pytest config.
-python_files = test_*.py
-testpaths = tests
diff --git a/agent/sandbox/executor_manager/requirements.txt b/agent/sandbox/executor_manager/requirements.txt
deleted file mode 100644
index 5295d12a90..0000000000
--- a/agent/sandbox/executor_manager/requirements.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-fastapi
-uvicorn
-slowapi
\ No newline at end of file
diff --git a/agent/sandbox/executor_manager/seccomp-profile-default.json b/agent/sandbox/executor_manager/seccomp-profile-default.json
deleted file mode 100644
index e384ac3582..0000000000
--- a/agent/sandbox/executor_manager/seccomp-profile-default.json
+++ /dev/null
@@ -1,55 +0,0 @@
-{
- "defaultAction": "SCMP_ACT_ERRNO",
- "archMap": [
- {
- "architecture": "SCMP_ARCH_X86_64",
- "subArchitectures": [
- "SCMP_ARCH_X86",
- "SCMP_ARCH_X32"
- ]
- }
- ],
- "syscalls": [
- {
- "names": [
- "read",
- "write",
- "exit",
- "sigreturn",
- "brk",
- "mmap",
- "munmap",
- "rt_sigaction",
- "rt_sigprocmask",
- "futex",
- "clone",
- "execve",
- "arch_prctl",
- "access",
- "openat",
- "close",
- "stat",
- "fstat",
- "lstat",
- "getpid",
- "gettid",
- "getuid",
- "getgid",
- "geteuid",
- "getegid",
- "clock_gettime",
- "nanosleep",
- "uname",
- "writev",
- "readlink",
- "getrandom",
- "statx",
- "faccessat2",
- "pread64",
- "pwrite64",
- "rt_sigreturn"
- ],
- "action": "SCMP_ACT_ALLOW"
- }
- ]
-}
diff --git a/agent/sandbox/executor_manager/services/__init__.py b/agent/sandbox/executor_manager/services/__init__.py
deleted file mode 100644
index 177b91dd05..0000000000
--- a/agent/sandbox/executor_manager/services/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
diff --git a/agent/sandbox/executor_manager/services/auth.py b/agent/sandbox/executor_manager/services/auth.py
deleted file mode 100644
index 64ff506624..0000000000
--- a/agent/sandbox/executor_manager/services/auth.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import os
-import secrets
-
-from core.logger import logger
-from fastapi import HTTPException, Request, status
-
-API_TOKEN_ENV_VAR = "SANDBOX_EXECUTOR_MANAGER_API_TOKEN"
-ALLOW_UNAUTHENTICATED_ENV_VAR = "SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED"
-
-_TRUTHY_FLAG_VALUES = {"1", "true", "yes", "on"}
-
-_UNAUTH_OPT_IN_HINT = (
- "Set SANDBOX_EXECUTOR_MANAGER_API_TOKEN to a strong shared secret "
- "(and configure RAGFlow with the same value), or explicitly accept the risk by "
- "setting SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=true."
-)
-
-_UNAUTHENTICATED_WARNING = (
- "********************************************************************************\n"
- "\u26a0\ufe0f SECURITY WARNING: SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=true and\n"
- " no API token is configured. The executor manager accepts unauthenticated\n"
- " requests on /run: anyone who can reach this endpoint can execute code in\n"
- " the sandbox pool. Remove the flag and set SANDBOX_EXECUTOR_MANAGER_API_TOKEN\n"
- " to a strong shared secret.\n"
- "********************************************************************************"
-)
-
-_no_token_or_opt_in_warned = False
-
-
-def get_configured_api_token() -> str:
- """Return the configured shared-secret API token, or an empty string."""
- return (os.getenv(API_TOKEN_ENV_VAR) or "").strip()
-
-
-def unauthenticated_access_explicitly_allowed() -> bool:
- """Whether the operator explicitly opted into unauthenticated /run.
-
- Authentication is fail-closed by default: when no API token is configured,
- /run refuses to serve instead of silently staying open. Deployments that
- genuinely cannot provide a token must set
- SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=true, making the insecure
- state an explicit operator decision rather than the default.
- """
- return (os.getenv(ALLOW_UNAUTHENTICATED_ENV_VAR) or "").strip().lower() in _TRUTHY_FLAG_VALUES
-
-
-def warn_if_unauthenticated_opt_in() -> None:
- """Log a prominent warning (once) while the explicit insecure opt-in is active."""
- global _no_token_or_opt_in_warned
- if _no_token_or_opt_in_warned:
- return
- _no_token_or_opt_in_warned = True
- logger.warning(_UNAUTHENTICATED_WARNING)
-
-
-def log_authentication_startup_state() -> None:
- """Log the effective /run authentication posture once at startup.
-
- Fail-closed with no token (503 for every /run request), the explicit
- insecure opt-in, or token-enforced authentication.
- """
- if get_configured_api_token():
- logger.info("Sandbox executor /run authentication: shared-secret token configured")
- return
- if unauthenticated_access_explicitly_allowed():
- warn_if_unauthenticated_opt_in()
- return
- logger.error(
- "SANDBOX_EXECUTOR_MANAGER_API_TOKEN is not set: /run will refuse requests with 503. %s",
- _UNAUTH_OPT_IN_HINT,
- )
-
-
-def _extract_request_token(request: Request) -> str:
- """Extract the caller-supplied token from supported headers.
-
- Supported formats:
- - Authorization: Bearer <token>
- - X-Sandbox-Token: <token>
- """
- authorization = request.headers.get("Authorization", "")
- if authorization[:7].lower() == "bearer ":
- return authorization[7:].strip()
- return (request.headers.get("X-Sandbox-Token") or "").strip()
-
-
-async def require_api_token(request: Request) -> None:
- """FastAPI dependency enforcing shared-secret authentication.
-
- Fail-closed by default (CWE-306): when SANDBOX_EXECUTOR_MANAGER_API_TOKEN
- is unset or blank, /run refuses requests with 503 instead of staying open.
- Legacy open behaviour survives only through the explicit operator opt-in
- SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=true.
-
- When a token is configured, every request must present the same secret via
- `Authorization: Bearer <token>` or `X-Sandbox-Token`. Comparison uses
- secrets.compare_digest to avoid timing attacks.
- """
- configured_token = get_configured_api_token()
- if not configured_token:
- if unauthenticated_access_explicitly_allowed():
- warn_if_unauthenticated_opt_in()
- return
- raise HTTPException(
- status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
- detail=f"Sandbox executor authentication is not configured; refusing unauthenticated /run. {_UNAUTH_OPT_IN_HINT}",
- )
-
- provided_token = _extract_request_token(request)
- if not provided_token or not secrets.compare_digest(provided_token, configured_token):
- logger.warning("\U0001f6ab Rejected unauthenticated %s request from %s", request.url.path, request.client.host if request.client else "unknown")
- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing or invalid sandbox executor API token")
diff --git a/agent/sandbox/executor_manager/services/execution.py b/agent/sandbox/executor_manager/services/execution.py
deleted file mode 100644
index 935d94b3a6..0000000000
--- a/agent/sandbox/executor_manager/services/execution.py
+++ /dev/null
@@ -1,478 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import asyncio
-import base64
-import json
-import os
-import time
-import uuid
-from core.config import TIMEOUT
-from core.container import allocate_container_blocking, release_container
-from core.logger import logger
-from models.enums import ResourceLimitType, ResultStatus, RuntimeErrorType, SupportLanguage, UnauthorizedAccessType
-from models.schemas import ArtifactItem, CodeExecutionRequest, CodeExecutionResult, ExecutionStructuredResult
-from utils.common import async_run_command
-
-RESULT_MARKER_PREFIX = "__RAGFLOW_RESULT__:"
-
-
-def _extract_result_envelope(stdout: str) -> tuple[str, ExecutionStructuredResult | None]:
- if not stdout:
- return "", None
-
- cleaned_lines: list[str] = []
- envelope: ExecutionStructuredResult | None = None
-
- for line in str(stdout).splitlines():
- if line.startswith(RESULT_MARKER_PREFIX):
- payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
- if not payload_b64:
- continue
- try:
- payload = base64.b64decode(payload_b64).decode("utf-8")
- envelope = ExecutionStructuredResult.model_validate_json(payload)
- except Exception as exc:
- logger.warning(f"Failed to decode structured result marker: {exc}")
- cleaned_lines.append(line)
- continue
- cleaned_lines.append(line)
-
- cleaned_stdout = "\n".join(cleaned_lines)
- if stdout.endswith("\n") and cleaned_stdout and not cleaned_stdout.endswith("\n"):
- cleaned_stdout += "\n"
- return cleaned_stdout, envelope
-
-
-def _build_execution_bundle(req: CodeExecutionRequest, workdir: str) -> dict[str, str | bytes]:
- arguments = req.arguments or {}
- args_source = json.dumps(arguments, ensure_ascii=False)
- args_name = "args.json"
- code_bytes = base64.b64decode(req.code_b64)
-
- if req.language == SupportLanguage.PYTHON:
- code_name = "main.py"
- runner_name = "runner.py"
- runner_source = f"""import base64
-import json
-import os
-import sys
-
-os.makedirs(os.path.join(os.getcwd(), "artifacts"), exist_ok=True)
-
-sys.path.insert(0, os.path.dirname(__file__))
-from main import main
-
-RESULT_MARKER_PREFIX = {RESULT_MARKER_PREFIX!r}
-
-
-def emit_result(value):
- payload = json.dumps(
- {{
- "present": True,
- "value": value,
- "type": "json",
- }},
- ensure_ascii=False,
- separators=(",", ":"),
- )
- print(RESULT_MARKER_PREFIX + base64.b64encode(payload.encode("utf-8")).decode("ascii"))
-
-
-if __name__ == "__main__":
- with open(os.path.join(os.path.dirname(__file__), "args.json"), encoding="utf-8") as f:
- args = json.load(f)
- result = main(**args)
- emit_result(result)
-"""
- elif req.language == SupportLanguage.NODEJS:
- code_name = "main.js"
- runner_name = "runner.js"
- runner_source = """
-const fs = require('fs');
-const path = require('path');
-
-const args = JSON.parse(fs.readFileSync(path.join(__dirname, 'args.json'), 'utf8'));
-const mainPath = path.join(__dirname, 'main.js');
-const RESULT_MARKER_PREFIX = '__RESULT_MARKER_PREFIX__';
-
-function isPromise(value) {
- return Boolean(value && typeof value.then === 'function');
-}
-
-function emitResult(value) {
- if (typeof value === 'undefined') {
- console.error('Error: main() must return a value. Use null for an empty result.');
- process.exit(1);
- }
-
- const payload = JSON.stringify({ present: true, value, type: 'json' });
- if (typeof payload === 'undefined') {
- console.error('Error: main() returned a non-JSON-serializable value.');
- process.exit(1);
- }
-
- console.log(RESULT_MARKER_PREFIX + Buffer.from(payload, 'utf8').toString('base64'));
-}
-
-if (fs.existsSync(mainPath)) {
- const mod = require(mainPath);
- const main = typeof mod === 'function' ? mod : mod.main;
-
- if (typeof main !== 'function') {
- console.error('Error: main is not a function');
- process.exit(1);
- }
-
- if (typeof args === 'object' && args !== null) {
- try {
- const result = Promise.resolve(main(args));
- if (isPromise(result)) {
- result.then(output => {
- emitResult(output);
- }).catch(err => {
- console.error('Error in async main function:', err);
- process.exit(1);
- });
- } else {
- emitResult(result);
- }
- } catch (err) {
- console.error('Error when executing main:', err);
- process.exit(1);
- }
- } else {
- console.error('Error: args is not a valid object:', args);
- process.exit(1);
- }
-} else {
- console.error('main.js not found in the current directory');
- process.exit(1);
-}
-"""
- runner_source = runner_source.replace("__RESULT_MARKER_PREFIX__", RESULT_MARKER_PREFIX)
- else:
- assert False, "Will never reach here"
-
- return {
- "code_name": code_name,
- "code_bytes": code_bytes,
- "runner_name": runner_name,
- "runner_source": runner_source,
- "args_name": args_name,
- "args_source": args_source,
- }
-
-
-def _build_container_run_args(language: SupportLanguage, task_id: str, container: str, runner_name: str) -> list[str]:
- run_args = [
- "docker",
- "exec",
- "--workdir",
- f"/workspace/{task_id}",
- container,
- "timeout",
- str(TIMEOUT),
- language,
- ]
- if language == SupportLanguage.PYTHON:
- run_args.extend(["-I", "-B"])
- run_args.append(runner_name)
- return run_args
-
-
-async def execute_code(req: CodeExecutionRequest):
- language = req.language
- container = await allocate_container_blocking(language)
- if not container:
- return CodeExecutionResult(
- status=ResultStatus.PROGRAM_RUNNER_ERROR,
- stdout="",
- stderr="Container pool is busy",
- exit_code=-10,
- detail="no_available_container",
- )
-
- task_id = str(uuid.uuid4())
- workdir = f"/tmp/sandbox_{task_id}"
- os.makedirs(workdir, mode=0o700, exist_ok=True)
-
- try:
- bundle = _build_execution_bundle(req, workdir)
- code_name = str(bundle["code_name"])
- runner_name = str(bundle["runner_name"])
-
- code_path = os.path.join(workdir, code_name)
- with open(code_path, "wb") as f:
- f.write(bundle["code_bytes"])
-
- runner_path = os.path.join(workdir, runner_name)
- with open(runner_path, "w", encoding="utf-8") as f:
- f.write(str(bundle["runner_source"]))
-
- args_path = os.path.join(workdir, str(bundle["args_name"]))
- with open(args_path, "w", encoding="utf-8") as f:
- f.write(str(bundle["args_source"]))
-
- returncode, _, stderr = await async_run_command("docker", "exec", container, "mkdir", "-p", f"/workspace/{task_id}", timeout=5)
- if returncode != 0:
- raise RuntimeError(f"Directory creation failed: {stderr}")
-
- tar_proc = await asyncio.create_subprocess_exec("tar", "czf", "-", "-C", workdir, code_name, runner_name, str(bundle["args_name"]), stdout=asyncio.subprocess.PIPE)
- tar_stdout, _ = await tar_proc.communicate()
-
- docker_proc = await asyncio.create_subprocess_exec(
- "docker", "exec", "-i", container, "tar", "xzf", "-", "-C", f"/workspace/{task_id}", stdin=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
- )
- stdout, stderr = await docker_proc.communicate(input=tar_stdout)
-
- if docker_proc.returncode != 0:
- raise RuntimeError(stderr.decode())
-
- start_time = time.time()
- try:
- arguments = req.arguments or {}
- logger.info("Passed in args keys=%s size_bytes=%s", list(arguments.keys()), len(json.dumps(arguments, ensure_ascii=False).encode("utf-8")))
- run_args = _build_container_run_args(language=language, task_id=task_id, container=container, runner_name=runner_name)
-
- returncode, stdout, stderr = await async_run_command(
- *run_args,
- timeout=TIMEOUT + 5,
- )
-
- time_used_ms = (time.time() - start_time) * 1000
-
- logger.info("----------------------------------------------")
- logger.info(f"Code: {str(base64.b64decode(req.code_b64))}")
- logger.info(f"{returncode=}")
- logger.info(f"{stdout=}")
- logger.info(f"{stderr=}")
-
- if returncode == 0:
- clean_stdout, structured_result = _extract_result_envelope(stdout)
- await _promote_root_artifacts(container, task_id)
- artifacts = await _collect_artifacts(container, task_id, workdir)
- return CodeExecutionResult(
- status=ResultStatus.SUCCESS,
- stdout=clean_stdout,
- stderr=stderr,
- exit_code=0,
- time_used_ms=time_used_ms,
- artifacts=artifacts,
- result=structured_result,
- )
- elif returncode == 124:
- return CodeExecutionResult(
- status=ResultStatus.RESOURCE_LIMIT_EXCEEDED,
- stdout="",
- stderr="Execution timeout",
- exit_code=-124,
- resource_limit_type=ResourceLimitType.TIME,
- time_used_ms=time_used_ms,
- )
- elif returncode == 137:
- return CodeExecutionResult(
- status=ResultStatus.RESOURCE_LIMIT_EXCEEDED,
- stdout="",
- stderr="Memory limit exceeded (killed by OOM)",
- exit_code=-137,
- resource_limit_type=ResourceLimitType.MEMORY,
- time_used_ms=time_used_ms,
- )
- return analyze_error_result(stderr, returncode)
-
- except asyncio.TimeoutError:
- await async_run_command("docker", "exec", container, "pkill", "-9", language)
- return CodeExecutionResult(
- status=ResultStatus.RESOURCE_LIMIT_EXCEEDED,
- stdout="",
- stderr="Execution timeout",
- exit_code=-1,
- resource_limit_type=ResourceLimitType.TIME,
- time_used_ms=(time.time() - start_time) * 1000,
- )
-
- except Exception as e:
- logger.error(f"Execution exception: {str(e)}")
- return CodeExecutionResult(status=ResultStatus.PROGRAM_RUNNER_ERROR, stdout="", stderr=str(e), exit_code=-3, detail="internal_error")
-
- finally:
- cleanup_tasks = [async_run_command("docker", "exec", container, "rm", "-rf", f"/workspace/{task_id}"), async_run_command("rm", "-rf", workdir)]
- await asyncio.gather(*cleanup_tasks, return_exceptions=True)
- await release_container(container, language)
-
-
-ALLOWED_ARTIFACT_EXTENSIONS = {
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".svg": "image/svg+xml",
- ".pdf": "application/pdf",
- ".csv": "text/csv",
- ".json": "application/json",
- ".html": "text/html",
-}
-MAX_ARTIFACT_COUNT = 10
-MAX_ARTIFACT_SIZE = 10 * 1024 * 1024 # 10MB per file
-
-
-async def _collect_artifacts(container: str, task_id: str, host_workdir: str) -> list[ArtifactItem]:
- artifacts_path = f"/workspace/{task_id}/artifacts"
- return await _collect_artifacts_from_path(container, artifacts_path)
-
-
-async def _promote_root_artifacts(container: str, task_id: str) -> None:
- """Move allowlisted outputs into the request's artifacts directory."""
- task_root = f"/workspace/{task_id}"
- artifacts = f"{task_root}/artifacts"
- excluded = {"main.py", "runner.py", "args.json"}
- returncode, _, _ = await async_run_command("docker", "exec", container, "mkdir", "-p", artifacts, timeout=5)
- if returncode != 0:
- return
- returncode, stdout, _ = await async_run_command("docker", "exec", container, "find", task_root, "-maxdepth", "1", "-type", "f", "-print0", timeout=5)
- if returncode != 0:
- return
- for path in stdout.split("\0"):
- name = path.rsplit("/", 1)[-1]
- if not name or name in excluded or name.startswith(".") or any(ord(char) < 32 or ord(char) == 127 for char in name):
- continue
- if os.path.splitext(name)[1].lower() not in ALLOWED_ARTIFACT_EXTENSIONS:
- continue
- await async_run_command("docker", "exec", container, "mv", path, f"{artifacts}/{name}", timeout=5)
-
-
-async def _collect_artifacts_from_path(container: str, artifacts_path: str, excluded: set[str] | None = None) -> list[ArtifactItem]:
- excluded = excluded or set()
-
- # List files in the artifacts directory inside the container
- returncode, stdout, _ = await async_run_command(
- "docker",
- "exec",
- container,
- "find",
- artifacts_path,
- "-maxdepth",
- "1",
- "-type",
- "f",
- "-print0",
- timeout=5,
- )
- if returncode != 0 or not stdout.strip():
- return []
-
- raw_names = [path.rsplit("/", 1)[-1] for path in stdout.split("\0") if path]
- # Sanitize: reject names with path traversal or control characters
- filenames = [
- n for n in raw_names if n and n not in excluded and "/" not in n and "\\" not in n and ".." not in n and not n.startswith(".") and not any(ord(char) < 32 or ord(char) == 127 for char in n)
- ]
- if not filenames:
- return []
-
- items: list[ArtifactItem] = []
-
- for fname in filenames[:MAX_ARTIFACT_COUNT]:
- ext = os.path.splitext(fname)[1].lower()
- mime_type = ALLOWED_ARTIFACT_EXTENSIONS.get(ext)
- if not mime_type:
- logger.warning(f"Skipping artifact with disallowed extension: {fname}")
- continue
-
- file_path = f"{artifacts_path}/{fname}"
-
- # Check file size inside the container
- returncode, size_str, _ = await async_run_command(
- "docker",
- "exec",
- container,
- "stat",
- "-c",
- "%s",
- file_path,
- timeout=5,
- )
- if returncode != 0:
- logger.warning(f"Failed to stat artifact {fname}")
- continue
-
- file_size = int(size_str.strip())
- if file_size > MAX_ARTIFACT_SIZE:
- logger.warning(f"Artifact {fname} too large ({file_size} bytes), skipping")
- continue
- if file_size == 0:
- continue
-
- # Read file content via docker exec (docker cp doesn't work with gVisor tmpfs)
- returncode, content_b64, stderr = await async_run_command(
- "docker",
- "exec",
- container,
- "base64",
- file_path,
- timeout=30,
- )
- if returncode != 0:
- logger.warning(f"Failed to read artifact {fname}: {stderr}")
- continue
-
- content_b64 = content_b64.replace("\n", "").strip()
-
- items.append(
- ArtifactItem(
- name=fname,
- mime_type=mime_type,
- size=file_size,
- content_b64=content_b64,
- )
- )
- logger.info(f"Collected artifact: {fname} ({file_size} bytes, {mime_type})")
-
- return items
-
-
-def analyze_error_result(stderr: str, exit_code: int) -> CodeExecutionResult:
- """Analyze the error result and classify it"""
- if "Permission denied" in stderr:
- return CodeExecutionResult(
- status=ResultStatus.UNAUTHORIZED_ACCESS,
- stdout="",
- stderr=stderr,
- exit_code=exit_code,
- unauthorized_access_type=UnauthorizedAccessType.FILE_ACCESS,
- )
- elif "Operation not permitted" in stderr:
- return CodeExecutionResult(
- status=ResultStatus.UNAUTHORIZED_ACCESS,
- stdout="",
- stderr=stderr,
- exit_code=exit_code,
- unauthorized_access_type=UnauthorizedAccessType.DISALLOWED_SYSCALL,
- )
- elif "MemoryError" in stderr:
- return CodeExecutionResult(
- status=ResultStatus.RESOURCE_LIMIT_EXCEEDED,
- stdout="",
- stderr=stderr,
- exit_code=exit_code,
- resource_limit_type=ResourceLimitType.MEMORY,
- )
- else:
- return CodeExecutionResult(
- status=ResultStatus.PROGRAM_ERROR,
- stdout="",
- stderr=stderr,
- exit_code=exit_code,
- runtime_error_type=RuntimeErrorType.NONZERO_EXIT,
- )
diff --git a/agent/sandbox/executor_manager/services/limiter.py b/agent/sandbox/executor_manager/services/limiter.py
deleted file mode 100644
index 8b380abf1f..0000000000
--- a/agent/sandbox/executor_manager/services/limiter.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import os
-
-from fastapi import Request
-from fastapi.responses import JSONResponse
-from models.enums import ResultStatus
-from models.schemas import CodeExecutionResult
-from slowapi import Limiter
-from slowapi.errors import RateLimitExceeded
-from slowapi.util import get_remote_address
-
-# Rate limit applied to POST /run, keyed by remote address (see key_func above).
-# Callers behind a Docker bridge network share a single address, so this acts as
-# a coarse per-deployment throttle; tune via SANDBOX_RUN_RATE_LIMIT if needed.
-RUN_RATE_LIMIT = os.getenv("SANDBOX_RUN_RATE_LIMIT", "120/minute")
-
-limiter = Limiter(key_func=get_remote_address)
-
-
-async def rate_limit_exceeded_handler(request: Request, exc: Exception) -> JSONResponse:
- if isinstance(exc, RateLimitExceeded):
- return JSONResponse(
- status_code=429,
- content=CodeExecutionResult(
- status=ResultStatus.PROGRAM_RUNNER_ERROR,
- stdout="",
- stderr="Too many requests, please try again later",
- exit_code=-429,
- detail="Too many requests, please try again later",
- ).model_dump(),
- )
- raise exc
diff --git a/agent/sandbox/executor_manager/services/preauth.py b/agent/sandbox/executor_manager/services/preauth.py
deleted file mode 100644
index 0cf2988d70..0000000000
--- a/agent/sandbox/executor_manager/services/preauth.py
+++ /dev/null
@@ -1,110 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-"""Pre-authentication rate limiting for /run.
-
-Authentication dependencies run before the SlowAPI-decorated handler, so
-without this layer invalid-token traffic never touches the execution rate
-limit: a reachable executor manager could be made to perform unbounded
-authentication work (compare_digest plus a warning log per attempt) without
-ever receiving a 429. This module applies a small per-address sliding-window
-limit to ALL /run traffic, before authentication, so repeated unauthenticated
-requests are eventually throttled. Authenticated execution keeps the larger
-SlowAPI quota as a second layer.
-"""
-
-import os
-import threading
-import time
-from collections import deque
-
-from core.logger import logger
-from fastapi import Request
-from limits import parse_many
-from slowapi.errors import RateLimitExceeded
-
-PRE_AUTH_RATE_LIMIT = os.getenv("SANDBOX_RUN_PREAUTH_RATE_LIMIT", "30/minute")
-
-
-class _LimitDescriptor:
- """Minimal stand-in for slowapi's Limit that RateLimitExceeded accepts."""
-
- def __init__(self, limit):
- self.limit = limit
- self.error_message = "Too many requests, please try again later"
-
-
-def _parse_rate_limit(value: str):
- items = list(parse_many(value))
- if len(items) != 1:
- raise ValueError(f"SANDBOX_RUN_PREAUTH_RATE_LIMIT must be a single rate like '30/minute', got {value!r}")
- return items[0]
-
-
-class PreAuthRateLimiter:
- """Thread-safe sliding-window limiter keyed by client address."""
-
- def __init__(self, limit):
- self._limit = limit
- self._window_seconds = limit.get_expiry()
- self._max_amount = limit.amount
- self._hits: dict[str, deque] = {}
- # Bounded rejection logging: at most one warning per address per
- # window, so throttling is observable without unbounded log writes.
- self._last_logged: dict[str, float] = {}
- self._lock = threading.Lock()
-
- def hit(self, address: str, now: float | None = None) -> None:
- """Record one hit for `address`; raise RateLimitExceeded when over budget."""
- timestamp = time.monotonic() if now is None else now
- with self._lock:
- window = self._hits.get(address)
- if window is None:
- window = deque()
- self._hits[address] = window
- cutoff = timestamp - self._window_seconds
- while window and window[0] <= cutoff:
- window.popleft()
- if len(window) >= self._max_amount:
- if timestamp - self._last_logged.get(address, float("-inf")) >= self._window_seconds:
- self._last_logged[address] = timestamp
- logger.warning(
- "Pre-auth rate limit exceeded for %s on /run (%s); further rejections from this address are throttled silently for this window",
- address,
- self._limit,
- )
- raise RateLimitExceeded(_LimitDescriptor(self._limit))
- window.append(timestamp)
- # Opportunistic cleanup keeps the address maps bounded under scans.
- if len(self._hits) > 10_000:
- stale = [key for key, hits in self._hits.items() if not hits or hits[-1] <= cutoff]
- for key in stale:
- del self._hits[key]
- self._last_logged.pop(key, None)
-
- def reset(self) -> None:
- with self._lock:
- self._hits.clear()
- self._last_logged.clear()
-
-
-_preauth_limit_item = _parse_rate_limit(PRE_AUTH_RATE_LIMIT)
-preauth_limiter = PreAuthRateLimiter(_preauth_limit_item)
-
-
-def preauth_rate_limit(request: Request) -> None:
- """FastAPI dependency: throttle /run traffic before authentication."""
- address = request.client.host if request.client else "unknown"
- preauth_limiter.hit(address)
diff --git a/agent/sandbox/executor_manager/services/security.py b/agent/sandbox/executor_manager/services/security.py
deleted file mode 100644
index f0323e747a..0000000000
--- a/agent/sandbox/executor_manager/services/security.py
+++ /dev/null
@@ -1,207 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import ast
-import re
-from typing import List, Tuple
-
-from core.logger import logger
-from models.enums import SupportLanguage
-
-
-class SecurePythonAnalyzer(ast.NodeVisitor):
- """
- An AST-based analyzer for detecting unsafe Python code patterns.
- """
-
- DANGEROUS_IMPORTS = {"os", "subprocess", "sys", "shutil", "socket", "ctypes", "pickle", "threading", "multiprocessing", "asyncio", "http.client", "ftplib", "telnetlib", "builtins"}
-
- DANGEROUS_CALLS = {
- "eval",
- "exec",
- "open",
- "__import__",
- "compile",
- "input",
- "system",
- "popen",
- "remove",
- "rename",
- "rmdir",
- "chdir",
- "chmod",
- "chown",
- "getattr",
- "setattr",
- "globals",
- "locals",
- "shutil.rmtree",
- "subprocess.call",
- "subprocess.Popen",
- "ctypes",
- "pickle.load",
- "pickle.loads",
- "pickle.dump",
- "pickle.dumps",
- }
-
- def __init__(self):
- self.unsafe_items: List[Tuple[str, int]] = []
-
- def visit_Import(self, node: ast.Import):
- """Check for dangerous imports."""
- for alias in node.names:
- if alias.name.split(".")[0] in self.DANGEROUS_IMPORTS:
- self.unsafe_items.append((f"Import: {alias.name}", node.lineno))
- self.generic_visit(node)
-
- def visit_ImportFrom(self, node: ast.ImportFrom):
- """Check for dangerous imports from specific modules."""
- if node.module and node.module.split(".")[0] in self.DANGEROUS_IMPORTS:
- self.unsafe_items.append((f"From Import: {node.module}", node.lineno))
- self.generic_visit(node)
-
- def visit_Call(self, node: ast.Call):
- """Check for dangerous function calls."""
- if isinstance(node.func, ast.Name) and node.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append((f"Call: {node.func.id}", node.lineno))
- elif isinstance(node.func, ast.Attribute) and node.func.attr in self.DANGEROUS_CALLS:
- # Surface the attribute-style match in the analyzer log so that
- # incident response can grep for it just like the other unsafe-item
- # findings; the bare append is invisible to operators.
- logger.warning(
- "[SafeCheck] Attribute-style dangerous call detected: %s (line %s)",
- node.func.attr,
- node.lineno,
- )
- self.unsafe_items.append((f"Call: {node.func.attr}", node.lineno))
- self.generic_visit(node)
-
- def visit_Attribute(self, node: ast.Attribute):
- """Check for dangerous attribute access."""
- if isinstance(node.value, ast.Name) and node.value.id in self.DANGEROUS_IMPORTS:
- self.unsafe_items.append((f"Attribute Access: {node.value.id}.{node.attr}", node.lineno))
- self.generic_visit(node)
-
- def visit_BinOp(self, node: ast.BinOp):
- """Check for possible unsafe operations like concatenating strings with commands."""
- # This could be useful to detect `eval("os." + "system")`
- if isinstance(node.left, ast.Constant) and isinstance(node.right, ast.Constant):
- self.unsafe_items.append(("Possible unsafe string concatenation", node.lineno))
- self.generic_visit(node)
-
- def visit_FunctionDef(self, node: ast.FunctionDef):
- """Check for dangerous function definitions (e.g., user-defined eval)."""
- if node.name in self.DANGEROUS_CALLS:
- self.unsafe_items.append((f"Function Definition: {node.name}", node.lineno))
- self.generic_visit(node)
-
- def visit_Assign(self, node: ast.Assign):
- """Check for assignments to variables that might lead to dangerous operations."""
- for target in node.targets:
- if isinstance(target, ast.Name) and target.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append((f"Assignment to dangerous variable: {target.id}", node.lineno))
- self.generic_visit(node)
-
- def visit_Lambda(self, node: ast.Lambda):
- """Check for lambda functions with dangerous operations."""
- if isinstance(node.body, ast.Call) and isinstance(node.body.func, ast.Name) and node.body.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append(("Lambda with dangerous function call", node.lineno))
- self.generic_visit(node)
-
- def visit_ListComp(self, node: ast.ListComp):
- """Check for list comprehensions with dangerous operations."""
- # First, visit the generators to check for any issues there
- for elem in node.generators:
- if isinstance(elem, ast.comprehension):
- self.generic_visit(elem)
-
- if isinstance(node.elt, ast.Call) and isinstance(node.elt.func, ast.Name) and node.elt.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append(("List comprehension with dangerous function call", node.lineno))
- self.generic_visit(node)
-
- def visit_DictComp(self, node: ast.DictComp):
- """Check for dictionary comprehensions with dangerous operations."""
- # Check for dangerous calls in both the key and value expressions of the dictionary comprehension
- if isinstance(node.key, ast.Call) and isinstance(node.key.func, ast.Name) and node.key.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append(("Dict comprehension with dangerous function call in key", node.lineno))
-
- if isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) and node.value.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append(("Dict comprehension with dangerous function call in value", node.lineno))
-
- # Visit other sub-nodes (e.g., the generators in the comprehension)
- self.generic_visit(node)
-
- def visit_SetComp(self, node: ast.SetComp):
- """Check for set comprehensions with dangerous operations."""
- for elt in node.generators:
- if isinstance(elt, ast.comprehension):
- self.generic_visit(elt)
-
- if isinstance(node.elt, ast.Call) and isinstance(node.elt.func, ast.Name) and node.elt.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append(("Set comprehension with dangerous function call", node.lineno))
-
- self.generic_visit(node)
-
- def visit_Yield(self, node: ast.Yield):
- """Check for yield statements that could be used to produce unsafe values."""
- if isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) and node.value.func.id in self.DANGEROUS_CALLS:
- self.unsafe_items.append(("Yield with dangerous function call", node.lineno))
- self.generic_visit(node)
-
-
-class SecureJavaScriptAnalyzer:
- DANGEROUS_PATTERNS = [
- (re.compile(r"""require\s*\(\s*['"`]child_process['"`]\s*\)"""), "Require: child_process"),
- (re.compile(r"""require\s*\(\s*['"`]fs['"`]\s*\)"""), "Require: fs"),
- (re.compile(r"""require\s*\(\s*['"`]worker_threads['"`]\s*\)"""), "Require: worker_threads"),
- (re.compile(r"""\beval\s*\("""), "Call: eval"),
- (re.compile(r"""\bFunction\s*\("""), "Call: Function"),
- (re.compile(r"""\bprocess\s*\.\s*binding\s*\("""), "Call: process.binding"),
- ]
-
- @classmethod
- def analyze(cls, code: str) -> List[Tuple[str, int]]:
- issues: List[Tuple[str, int]] = []
- for pattern, description in cls.DANGEROUS_PATTERNS:
- for match in pattern.finditer(code):
- lineno = code.count("\n", 0, match.start()) + 1
- issues.append((description, lineno))
- return issues
-
-
-def analyze_code_security(code: str, language: SupportLanguage) -> Tuple[bool, List[Tuple[str, int]]]:
- """
- Analyze the provided code string and return whether it's safe and why.
-
- :param code: The source code to analyze.
- :param language: The programming language of the code.
- :return: (is_safe: bool, issues: List of (description, line number))
- """
- if language == SupportLanguage.PYTHON:
- try:
- tree = ast.parse(code)
- analyzer = SecurePythonAnalyzer()
- analyzer.visit(tree)
- return len(analyzer.unsafe_items) == 0, analyzer.unsafe_items
- except Exception as e:
- logger.error(f"[SafeCheck] Python parsing failed: {str(e)}")
- return False, [(f"Parsing Error: {str(e)}", -1)]
- if language == SupportLanguage.NODEJS:
- issues = SecureJavaScriptAnalyzer.analyze(code)
- return len(issues) == 0, issues
-
- logger.warning(f"[SafeCheck] Unsupported language for security analysis: {language}")
- return False, [(f"Unsupported language for security analysis: {language}", -1)]
diff --git a/agent/sandbox/executor_manager/tests/conftest.py b/agent/sandbox/executor_manager/tests/conftest.py
deleted file mode 100644
index 9858e3a1b7..0000000000
--- a/agent/sandbox/executor_manager/tests/conftest.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import os
-import sys
-from pathlib import Path
-
-# executor_manager modules use top-level imports (e.g. `from api.handlers
-# import ...`) resolved against the executor_manager directory (WORKDIR /app
-# in Docker). Make that directory importable regardless of the pytest rootdir.
-EXECUTOR_MANAGER_ROOT = Path(__file__).resolve().parent.parent
-sys.path.insert(0, str(EXECUTOR_MANAGER_ROOT))
-
-# Keep tests hermetic: a small window makes the 429 case cheap to exercise.
-# Must be set before `services.limiter` / `services.preauth` are first imported
-# (module-level env reads). The pre-auth budget stays generous by default so
-# ordinary auth tests never trip it; the dedicated pre-auth tests shrink the
-# limiter explicitly.
-os.environ["SANDBOX_RUN_RATE_LIMIT"] = os.environ.get("SANDBOX_TEST_RATE_LIMIT_OVERRIDE", "3/minute")
-os.environ["SANDBOX_RUN_PREAUTH_RATE_LIMIT"] = os.environ.get("SANDBOX_TEST_PREAUTH_RATE_LIMIT_OVERRIDE", "1000/minute")
-
-import pytest # noqa: E402 (env vars above must be set before these imports)
-from services.limiter import limiter # noqa: E402
-from services.preauth import preauth_limiter # noqa: E402
-
-
[email protected](autouse=True)
-def _reset_rate_limiters():
- limiter.reset()
- preauth_limiter.reset()
- yield
- preauth_limiter.reset()
- limiter.reset()
-
-
[email protected](autouse=True)
-def _clean_token_env(monkeypatch):
- monkeypatch.delenv("SANDBOX_EXECUTOR_MANAGER_API_TOKEN", raising=False)
- yield
diff --git a/agent/sandbox/executor_manager/tests/test_artifact_promotion.py b/agent/sandbox/executor_manager/tests/test_artifact_promotion.py
deleted file mode 100644
index 9b0df4e503..0000000000
--- a/agent/sandbox/executor_manager/tests/test_artifact_promotion.py
+++ /dev/null
@@ -1,46 +0,0 @@
-import asyncio
-import unittest
-from unittest.mock import patch
-
-from services import execution
-
-
-class ArtifactPromotionTest(unittest.TestCase):
- def test_promote_root_artifacts_moves_task_output(self):
- calls = []
-
- async def run_command(*args, **kwargs):
- calls.append(args)
- if args[-7:] == ("find", "/workspace/task-id", "-maxdepth", "1", "-type", "f", "-print0"):
- return 0, "/workspace/task-id/chart.png\0", ""
- return 0, "", ""
-
- with patch.object(execution, "async_run_command", run_command):
- asyncio.run(execution._promote_root_artifacts("runner", "task-id"))
-
- self.assertIn(
- (
- "docker",
- "exec",
- "runner",
- "mv",
- "/workspace/task-id/chart.png",
- "/workspace/task-id/artifacts/chart.png",
- ),
- calls,
- )
- self.assertNotIn(("docker", "exec", "runner", "find", "/workspace", "-maxdepth", "1", "-type", "f", "-print0"), calls)
-
- def test_promote_root_artifacts_skips_control_characters(self):
- calls = []
-
- async def run_command(*args, **kwargs):
- calls.append(args)
- if args[-7:] == ("find", "/workspace/task-id", "-maxdepth", "1", "-type", "f", "-print0"):
- return 0, "/workspace/task-id/chart\ncopy.png\0", ""
- return 0, "", ""
-
- with patch.object(execution, "async_run_command", run_command):
- asyncio.run(execution._promote_root_artifacts("runner", "task-id"))
-
- self.assertFalse(any(call[3] == "mv" for call in calls))
diff --git a/agent/sandbox/executor_manager/tests/test_run_endpoint_security.py b/agent/sandbox/executor_manager/tests/test_run_endpoint_security.py
deleted file mode 100644
index d924f7ca84..0000000000
--- a/agent/sandbox/executor_manager/tests/test_run_endpoint_security.py
+++ /dev/null
@@ -1,241 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-"""Security tests for the executor manager /run endpoint.
-
-Run from the executor_manager directory:
-
- cd agent/sandbox/executor_manager
- python -m pytest tests/
-
-Covers: fail-closed shared-secret authentication (503 when no token is
-configured unless the explicit unauthenticated opt-in flag is set, 401 with a
-wrong token, success via Authorization: Bearer and X-Sandbox-Token), the
-pre-auth rate limit applied to all /run traffic, the authenticated execution
-quota, the standalone Compose environment contract, and the docker network
-flag used for sandbox runner containers.
-"""
-
-import asyncio
-import base64
-from pathlib import Path
-
-import pytest
-from fastapi.testclient import TestClient
-from models.enums import ResultStatus, SupportLanguage
-from models.schemas import CodeExecutionResult
-
-API_TOKEN_ENV = "SANDBOX_EXECUTOR_MANAGER_API_TOKEN"
-ALLOW_UNAUTH_ENV = "SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED"
-TEST_TOKEN = "unit-test-shared-secret"
-
-
-def _payload() -> dict:
- code = "def main():\n return 42\n"
- return {"code_b64": base64.b64encode(code.encode("utf-8")).decode("utf-8"), "language": "python", "arguments": {}}
-
-
-def client(monkeypatch):
- async def fake_execute_code(req):
- return CodeExecutionResult(status=ResultStatus.SUCCESS, stdout="42", stderr="", exit_code=0)
-
- monkeypatch.setattr("api.handlers.execute_code", fake_execute_code)
-
- import core.container as container_module
-
- # Normally populated by the lifespan hook (which provisions real docker
- # containers); handlers uses the same dict object by reference.
- container_module._CONTAINER_EXECUTION_SEMAPHORES[SupportLanguage.PYTHON] = asyncio.Semaphore(1)
- container_module._CONTAINER_EXECUTION_SEMAPHORES[SupportLanguage.NODEJS] = asyncio.Semaphore(1)
-
- import main
-
- # Instantiated without a context manager on purpose: the lifespan hook
- # provisions real docker containers, which these unit tests must avoid.
- return TestClient(main.app)
-
-
-class TestRunEndpointAuth:
- def test_missing_token_returns_401_when_configured(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- response = client.post("/run", json=_payload())
- assert response.status_code == 401
-
- def test_wrong_bearer_token_returns_401(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- response = client.post("/run", json=_payload(), headers={"Authorization": "Bearer not-the-token"})
- assert response.status_code == 401
-
- def test_wrong_x_sandbox_token_returns_401(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- response = client.post("/run", json=_payload(), headers={"X-Sandbox-Token": "also-wrong"})
- assert response.status_code == 401
-
- def test_correct_bearer_token_is_accepted(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- response = client.post("/run", json=_payload(), headers={"Authorization": f"Bearer {TEST_TOKEN}"})
- assert response.status_code == 200
- assert response.json()["status"] == ResultStatus.SUCCESS
-
- def test_correct_x_sandbox_token_is_accepted(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- response = client.post("/run", json=_payload(), headers={"X-Sandbox-Token": TEST_TOKEN})
- assert response.status_code == 200
-
- def test_unset_token_fails_closed_with_503(self, client, monkeypatch):
- monkeypatch.delenv(API_TOKEN_ENV, raising=False)
- monkeypatch.delenv(ALLOW_UNAUTH_ENV, raising=False)
- response = client.post("/run", json=_payload())
- assert response.status_code == 503
- assert "SANDBOX_EXECUTOR_MANAGER_API_TOKEN" in response.json()["detail"]
-
- def test_blank_token_fails_closed_with_503(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, " ")
- monkeypatch.delenv(ALLOW_UNAUTH_ENV, raising=False)
- assert client.post("/run", json=_payload()).status_code == 503
-
- def test_explicit_opt_in_restores_open_endpoint(self, client, monkeypatch):
- monkeypatch.delenv(API_TOKEN_ENV, raising=False)
- monkeypatch.setenv(ALLOW_UNAUTH_ENV, "true")
- response = client.post("/run", json=_payload())
- assert response.status_code == 200
-
- @pytest.mark.parametrize("flag", ["1", "TRUE", "Yes", "on "])
- def test_opt_in_accepts_truthy_flag_spellings(self, client, monkeypatch, flag):
- monkeypatch.delenv(API_TOKEN_ENV, raising=False)
- monkeypatch.setenv(ALLOW_UNAUTH_ENV, flag)
- assert client.post("/run", json=_payload()).status_code == 200
-
- @pytest.mark.parametrize("flag", ["false", "0", "no", "unexpected"])
- def test_opt_in_rejects_non_truthy_flag_spellings(self, client, monkeypatch, flag):
- monkeypatch.delenv(API_TOKEN_ENV, raising=False)
- monkeypatch.setenv(ALLOW_UNAUTH_ENV, flag)
- assert client.post("/run", json=_payload()).status_code == 503
-
- def test_opt_in_is_ignored_when_a_token_is_configured(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- monkeypatch.setenv(ALLOW_UNAUTH_ENV, "true")
- # The flag never weakens a configured token: bad credentials still 401.
- assert client.post("/run", json=_payload(), headers={"Authorization": "Bearer wrong"}).status_code == 401
-
- def test_healthz_does_not_require_token(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- assert client.get("/healthz").status_code == 200
- assert client.get("/").status_code == 200
-
-
-class TestRunEndpointRateLimit:
- def test_requests_beyond_limit_get_429(self, client, monkeypatch):
- # conftest pins SANDBOX_RUN_RATE_LIMIT to 3/minute.
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- headers = {"Authorization": f"Bearer {TEST_TOKEN}"}
- for _ in range(3):
- assert client.post("/run", json=_payload(), headers=headers).status_code == 200
- response = client.post("/run", json=_payload(), headers=headers)
- assert response.status_code == 429
- body = response.json()
- assert body["exit_code"] == -429
-
- def test_repeated_unauthenticated_requests_eventually_get_429(self, client, monkeypatch):
- # The pre-auth limiter throttles ALL /run traffic before authentication,
- # so an invalid-token flood cannot generate unbounded authentication
- # work. The limiter is shrunk to 3/minute for this test (conftest
- # resets it afterwards).
- import services.preauth as preauth_module
-
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- monkeypatch.setattr(
- preauth_module,
- "preauth_limiter",
- preauth_module.PreAuthRateLimiter(preauth_module._parse_rate_limit("3/minute")),
- )
- for _ in range(3):
- assert client.post("/run", json=_payload()).status_code == 401
- response = client.post("/run", json=_payload())
- assert response.status_code == 429
- body = response.json()
- assert body["exit_code"] == -429
-
- def test_single_auth_failures_still_return_401_under_generous_preauth(self, client, monkeypatch):
- monkeypatch.setenv(API_TOKEN_ENV, TEST_TOKEN)
- assert client.post("/run", json=_payload()).status_code == 401
- assert client.post("/run", json=_payload(), headers={"X-Sandbox-Token": "wrong"}).status_code == 401
-
-
-class TestContainerNetworkIsolation:
- @staticmethod
- def _captured_docker_run_argv(monkeypatch) -> list[list[str]]:
- calls: list[list[str]] = []
-
- async def fake_run_command(*args, timeout=5):
- calls.append(list(args))
- return 0, "true", ""
-
- import core.container as container_module
-
- monkeypatch.setattr(container_module, "async_run_command", fake_run_command)
- assert asyncio.run(container_module.create_container("sandbox_python_0", SupportLanguage.PYTHON)) is True
- return next(argv for argv in calls if argv[:3] == ["docker", "run", "-d"])
-
- def test_container_defaults_to_network_none(self, monkeypatch):
- monkeypatch.delenv("SANDBOX_CONTAINER_NETWORK", raising=False)
- argv = self._captured_docker_run_argv(monkeypatch)
- assert argv[argv.index("--network") + 1] == "none"
-
- def test_blank_network_env_falls_back_to_none(self, monkeypatch):
- monkeypatch.setenv("SANDBOX_CONTAINER_NETWORK", " ")
- argv = self._captured_docker_run_argv(monkeypatch)
- assert argv[argv.index("--network") + 1] == "none"
-
- def test_network_env_override_is_passed_through(self, monkeypatch):
- monkeypatch.setenv("SANDBOX_CONTAINER_NETWORK", "bridge")
- argv = self._captured_docker_run_argv(monkeypatch)
- assert argv[argv.index("--network") + 1] == "bridge"
-
- def test_other_hardening_flags_still_present(self, monkeypatch):
- monkeypatch.delenv("SANDBOX_CONTAINER_NETWORK", raising=False)
- argv = self._captured_docker_run_argv(monkeypatch)
- assert "--runtime=runsc" in argv
- assert "--read-only" in argv
- assert argv[argv.index("--user") + 1] == "nobody"
-
-
-class TestStandaloneComposeEnvironment:
- """Regression: the standalone Compose file must actually deliver the
- documented environment contract (SANDBOX_RUN_RATE_LIMIT, the pre-auth
- limit, and the explicit unauthenticated opt-in flag) into the container."""
-
- COMPOSE_PATH = Path(__file__).resolve().parents[2] / "docker-compose.yml"
- ENV_EXAMPLE_PATH = Path(__file__).resolve().parents[2] / ".env.example"
-
- def test_documented_rate_limit_reaches_the_container(self):
- compose = self.COMPOSE_PATH.read_text(encoding="utf-8")
- assert "- SANDBOX_RUN_RATE_LIMIT=${SANDBOX_RUN_RATE_LIMIT:-120/minute}" in compose
- assert "- SANDBOX_RUN_PREAUTH_RATE_LIMIT=${SANDBOX_RUN_PREAUTH_RATE_LIMIT:-30/minute}" in compose
-
- def test_unauthenticated_opt_in_flag_is_forwarded(self):
- compose = self.COMPOSE_PATH.read_text(encoding="utf-8")
- assert "- SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=${SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED:-false}" in compose
-
- def test_env_example_matches_compose_defaults(self):
- example = self.ENV_EXAMPLE_PATH.read_text(encoding="utf-8")
- for name in (
- "SANDBOX_RUN_RATE_LIMIT",
- "SANDBOX_RUN_PREAUTH_RATE_LIMIT",
- "SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED",
- "SANDBOX_EXECUTOR_MANAGER_API_TOKEN",
- ):
- assert name in example, f"{name} missing from .env.example"
diff --git a/agent/sandbox/executor_manager/util.py b/agent/sandbox/executor_manager/util.py
deleted file mode 100644
index a84fe57061..0000000000
--- a/agent/sandbox/executor_manager/util.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import os
-import re
-
-
-def is_enabled(value: str) -> bool:
- return str(value).strip().lower() in {"1", "true", "yes", "on"}
-
-
-def env_setting_enabled(env_key: str, default: str = "false") -> bool:
- value = os.getenv(env_key, default)
- return is_enabled(value)
-
-
-def is_valid_memory_limit(mem: str | None) -> bool:
- """
- Return True if the input string is a valid Docker memory limit (e.g. '256m', '1g').
- Units allowed: b, k, m, g (case-insensitive).
- Disallows zero or negative values.
- """
- if not mem or not isinstance(mem, str):
- return False
-
- mem = mem.strip().lower()
-
- return re.fullmatch(r"[1-9]\d*(b|k|m|g)", mem) is not None
-
-
-def parse_timeout_duration(timeout: str | None, default_seconds: int = 10) -> int:
- """
- Parses a string like '90s', '2m', '1m30s' into total seconds (int).
- Supports 's', 'm' (lower or upper case). Returns default if invalid.
- '1m30s' -> 90
- """
- if not timeout or not isinstance(timeout, str):
- return default_seconds
-
- timeout = timeout.strip().lower()
-
- pattern = r"^(?:(\d+)m)?(?:(\d+)s)?$"
- match = re.fullmatch(pattern, timeout)
- if not match:
- return default_seconds
-
- minutes = int(match.group(1)) if match.group(1) else 0
- seconds = int(match.group(2)) if match.group(2) else 0
- total = minutes * 60 + seconds
-
- return total if total > 0 else default_seconds
-
-
-def format_timeout_duration(seconds: int) -> str:
- """
- Formats an integer number of seconds into a string like '1m30s'.
- 90 -> '1m30s'
- """
- if seconds < 60:
- return f"{seconds}s"
- minutes, sec = divmod(seconds, 60)
- if sec == 0:
- return f"{minutes}m"
- return f"{minutes}m{sec}s"
diff --git a/agent/sandbox/executor_manager/utils/__init__.py b/agent/sandbox/executor_manager/utils/__init__.py
deleted file mode 100644
index 177b91dd05..0000000000
--- a/agent/sandbox/executor_manager/utils/__init__.py
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
diff --git a/agent/sandbox/executor_manager/utils/common.py b/agent/sandbox/executor_manager/utils/common.py
deleted file mode 100644
index 9a85566ce1..0000000000
--- a/agent/sandbox/executor_manager/utils/common.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import asyncio
-from typing import Tuple
-
-
-async def async_run_command(*args, timeout: float = 5) -> Tuple[int, str, str]:
- """Safe asynchronous command execution tool"""
- proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
-
- try:
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)
- if proc.returncode is None:
- raise RuntimeError("Process finished but returncode is None")
- return proc.returncode, stdout.decode(), stderr.decode()
- except asyncio.TimeoutError:
- proc.kill()
- await proc.wait()
- raise RuntimeError("Command timed out")
- except Exception as e:
- proc.kill()
- await proc.wait()
- raise e
diff --git a/agent/sandbox/providers/__init__.py b/agent/sandbox/providers/__init__.py
deleted file mode 100644
index e0935ea124..0000000000
--- a/agent/sandbox/providers/__init__.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Sandbox providers package.
-
-This package contains:
-- base.py: Base interface for all sandbox providers
-- manager.py: Provider manager for managing active provider
-- self_managed.py: Self-managed provider implementation (wraps existing executor_manager)
-- aliyun_codeinterpreter.py: Aliyun Code Interpreter provider implementation
- Official Documentation: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter
-- e2b.py: E2B provider implementation
-- local.py: Local process provider implementation
-- ssh.py: Remote SSH provider implementation
-- tenki.py: Tenki disposable microVM provider implementation
-- ucloud_agent_sandbox.py: UCloud Agent Sandbox provider implementation
-"""
-
-from .base import SandboxProvider, SandboxInstance, ExecutionResult, SandboxProviderConfigError
-from .manager import ProviderManager
-from .self_managed import SelfManagedProvider
-from .aliyun_codeinterpreter import AliyunCodeInterpreterProvider
-from .e2b import E2BProvider
-from .local import LocalProvider
-from .ssh import SSHProvider
-from .tenki import TenkiProvider
-from .ucloud_agent_sandbox import UCloudAgentSandboxProvider
-
-__all__ = [
- "SandboxProvider",
- "SandboxInstance",
- "ExecutionResult",
- "SandboxProviderConfigError",
- "ProviderManager",
- "SelfManagedProvider",
- "AliyunCodeInterpreterProvider",
- "E2BProvider",
- "LocalProvider",
- "SSHProvider",
- "TenkiProvider",
- "UCloudAgentSandboxProvider",
-]
diff --git a/agent/sandbox/providers/aliyun_codeinterpreter.py b/agent/sandbox/providers/aliyun_codeinterpreter.py
deleted file mode 100644
index fd4adb41bd..0000000000
--- a/agent/sandbox/providers/aliyun_codeinterpreter.py
+++ /dev/null
@@ -1,481 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Aliyun Code Interpreter provider implementation.
-
-This provider integrates with Aliyun Function Compute Code Interpreter service
-for secure code execution in serverless microVMs using the official agentrun-sdk.
-
-Official Documentation: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter
-Official SDK: https://github.com/Serverless-Devs/agentrun-sdk-python
-
-https://api.aliyun.com/api/AgentRun/2025-09-10/CreateTemplate?lang=PYTHON
-https://api.aliyun.com/api/AgentRun/2025-09-10/CreateSandbox?lang=PYTHON
-"""
-
-import logging
-import os
-import time
-import json
-from typing import Dict, Any, List, Optional
-from datetime import datetime, timezone
-
-from agentrun.sandbox import TemplateType, CodeLanguage, Template, TemplateInput, Sandbox
-from agentrun.utils.config import Config
-from agentrun.utils.exception import ServerError
-
-from agent.sandbox.result_protocol import build_javascript_wrapper, build_python_wrapper, extract_structured_result
-from .base import SandboxProvider, SandboxInstance, ExecutionResult
-
-logger = logging.getLogger(__name__)
-
-
-class AliyunCodeInterpreterProvider(SandboxProvider):
- """
- Aliyun Code Interpreter provider implementation.
-
- This provider uses the official agentrun-sdk to interact with
- Aliyun Function Compute's Code Interpreter service.
- """
-
- def __init__(self):
- self.access_key_id: Optional[str] = ""
- self.access_key_secret: Optional[str] = ""
- self.account_id: Optional[str] = ""
- self.region: str = "cn-hangzhou"
- self.template_name: str = ""
- self.timeout: int = 30
- self._initialized: bool = False
- self._config: Optional[Config] = None
-
- def initialize(self, config: Dict[str, Any]) -> bool:
- """
- Initialize the provider with Aliyun credentials.
-
- Args:
- config: Configuration dictionary with keys:
- - access_key_id: Aliyun AccessKey ID
- - access_key_secret: Aliyun AccessKey Secret
- - account_id: Aliyun primary account ID
- - region: Region (default: "cn-hangzhou")
- - template_name: Optional sandbox template name
- - timeout: Request timeout in seconds (default: 30, max 30)
-
- Returns:
- True if initialization successful, False otherwise
- """
- # Get values from config or environment variables
- access_key_id = config.get("access_key_id") or os.getenv("AGENTRUN_ACCESS_KEY_ID")
- access_key_secret = config.get("access_key_secret") or os.getenv("AGENTRUN_ACCESS_KEY_SECRET")
- account_id = config.get("account_id") or os.getenv("AGENTRUN_ACCOUNT_ID")
- region = config.get("region") or os.getenv("AGENTRUN_REGION", "cn-hangzhou")
-
- self.access_key_id = access_key_id
- self.access_key_secret = access_key_secret
- self.account_id = account_id
- self.region = region
- self.template_name = config.get("template_name", "")
- self.timeout = min(config.get("timeout", 30), 30) # Max 30 seconds
-
- logger.info(f"Aliyun Code Interpreter: Initializing with account_id={self.account_id}, region={self.region}")
-
- # Validate required fields
- if not self.access_key_id or not self.access_key_secret:
- logger.error("Aliyun Code Interpreter: Missing access_key_id or access_key_secret")
- return False
-
- if not self.account_id:
- logger.error("Aliyun Code Interpreter: Missing account_id (primary account ID)")
- return False
-
- # Create SDK configuration
- try:
- logger.info(f"Aliyun Code Interpreter: Creating Config object with account_id={self.account_id}")
- self._config = Config(
- access_key_id=self.access_key_id,
- access_key_secret=self.access_key_secret,
- account_id=self.account_id,
- region_id=self.region,
- timeout=self.timeout,
- )
- logger.info("Aliyun Code Interpreter: Config object created successfully")
-
- # Verify connection with health check
- if not self.health_check():
- logger.error(f"Aliyun Code Interpreter: Health check failed for region {self.region}")
- return False
-
- self._initialized = True
- logger.info(f"Aliyun Code Interpreter: Initialized successfully for region {self.region}")
- return True
-
- except Exception as e:
- logger.error(f"Aliyun Code Interpreter: Initialization failed - {str(e)}")
- return False
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """
- Create a new sandbox instance in Aliyun Code Interpreter.
-
- Args:
- template: Programming language (python, javascript)
-
- Returns:
- SandboxInstance object
-
- Raises:
- RuntimeError: If instance creation fails
- """
- if not self._initialized or not self._config:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # Normalize language
- language = self._normalize_language(template)
-
- try:
- # Get or create template
- if self.template_name:
- # Use existing template
- template_name = self.template_name
- else:
- # Try to get default template, or create one if it doesn't exist
- default_template_name = f"ragflow-{language}-default"
- try:
- # Check if template exists
- Template.get_by_name(default_template_name, config=self._config)
- template_name = default_template_name
- except Exception:
- # Create default template if it doesn't exist
- template_input = TemplateInput(
- template_name=default_template_name,
- template_type=TemplateType.CODE_INTERPRETER,
- )
- Template.create(template_input, config=self._config)
- template_name = default_template_name
-
- # Create sandbox directly
- sandbox = Sandbox.create(
- template_type=TemplateType.CODE_INTERPRETER,
- template_name=template_name,
- sandbox_idle_timeout_seconds=self.timeout,
- config=self._config,
- )
-
- instance_id = sandbox.sandbox_id
-
- return SandboxInstance(
- instance_id=instance_id,
- provider="aliyun_codeinterpreter",
- status="READY",
- metadata={
- "language": language,
- "region": self.region,
- "account_id": self.account_id,
- "template_name": template_name,
- "created_at": datetime.now(timezone.utc).isoformat(),
- },
- )
-
- except ServerError as e:
- raise RuntimeError(f"Failed to create sandbox instance: {str(e)}")
- except Exception as e:
- raise RuntimeError(f"Unexpected error creating instance: {str(e)}")
-
- def execute_code(self, instance_id: str, code: str, language: str, timeout: int = 10, arguments: Optional[Dict[str, Any]] = None) -> ExecutionResult:
- """
- Execute code in the Aliyun Code Interpreter instance.
-
- Args:
- instance_id: ID of the sandbox instance
- code: Source code to execute
- language: Programming language (python, javascript)
- timeout: Maximum execution time in seconds (max 30)
- arguments: Optional arguments dict to pass to main() function
-
- Returns:
- ExecutionResult containing stdout, stderr, exit_code, and metadata
-
- Raises:
- RuntimeError: If execution fails
- TimeoutError: If execution exceeds timeout
- """
- if not self._initialized or not self._config:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # Normalize language
- normalized_lang = self._normalize_language(language)
-
- # Enforce 30-second hard limit
- timeout = min(timeout or self.timeout, 30)
-
- try:
- # Connect to existing sandbox instance
- sandbox = Sandbox.connect(sandbox_id=instance_id, config=self._config)
-
- # CodeLanguage enum only exposes PYTHON across agentrun-sdk 0.0.26+; keep JS as string fallback.
- code_language = CodeLanguage.PYTHON if normalized_lang == "python" else "javascript"
-
- # Wrap code to call main() function
- # Matches self_managed provider behavior: call main(**arguments)
- args_json = json.dumps(arguments or {})
- wrapped_code = build_python_wrapper(code, args_json) if normalized_lang == "python" else build_javascript_wrapper(code, args_json)
- logger.debug(f"Aliyun Code Interpreter: Wrapped code (first 200 chars): {wrapped_code[:200]}")
-
- start_time = time.time()
-
- # Execute code using SDK's simplified execute endpoint
- logger.info(f"Aliyun Code Interpreter: Executing code (language={normalized_lang}, timeout={timeout})")
- logger.debug(f"Aliyun Code Interpreter: Original code (first 200 chars): {code[:200]}")
- result = sandbox.context.execute(
- code=wrapped_code,
- language=code_language,
- timeout=timeout,
- )
-
- execution_time = time.time() - start_time
- logger.info(f"Aliyun Code Interpreter: Execution completed in {execution_time:.2f}s")
- logger.debug(f"Aliyun Code Interpreter: Raw SDK result: {result}")
-
- # Parse execution result
- results = result.get("results", []) if isinstance(result, dict) else []
- logger.info(f"Aliyun Code Interpreter: Parsed {len(results)} result items")
-
- # Extract stdout and stderr from results
- stdout_parts = []
- stderr_parts = []
- exit_code = 0
- execution_status = "ok"
-
- for item in results:
- result_type = item.get("type", "")
- text = item.get("text", "")
-
- if result_type == "stdout":
- stdout_parts.append(text)
- elif result_type == "stderr":
- stderr_parts.append(text)
- exit_code = 1 # Error occurred
- elif result_type == "endOfExecution":
- execution_status = item.get("status", "ok")
- if execution_status != "ok":
- exit_code = 1
- elif result_type == "error":
- stderr_parts.append(text)
- exit_code = 1
-
- stdout = "\n".join(stdout_parts)
- stderr = "\n".join(stderr_parts)
- stdout, structured_result = extract_structured_result(stdout)
-
- logger.info(f"Aliyun Code Interpreter: stdout length={len(stdout)}, stderr length={len(stderr)}, exit_code={exit_code}")
- if stdout:
- logger.debug(f"Aliyun Code Interpreter: stdout (first 200 chars): {stdout[:200]}")
- if stderr:
- logger.debug(f"Aliyun Code Interpreter: stderr (first 200 chars): {stderr[:200]}")
-
- return ExecutionResult(
- stdout=stdout,
- stderr=stderr,
- exit_code=exit_code,
- execution_time=execution_time,
- metadata={
- "instance_id": instance_id,
- "language": normalized_lang,
- "context_id": result.get("contextId") if isinstance(result, dict) else None,
- "timeout": timeout,
- "result_present": structured_result.get("present", False),
- "result_value": structured_result.get("value"),
- "result_type": structured_result.get("type"),
- },
- )
-
- except ServerError as e:
- if "timeout" in str(e).lower():
- raise TimeoutError(f"Execution timed out after {timeout} seconds")
- raise RuntimeError(f"Failed to execute code: {str(e)}")
- except Exception as e:
- raise RuntimeError(f"Unexpected error during execution: {str(e)}")
-
- def destroy_instance(self, instance_id: str) -> bool:
- """
- Destroy an Aliyun Code Interpreter instance.
-
- Args:
- instance_id: ID of the instance to destroy
-
- Returns:
- True if destruction successful, False otherwise
- """
- if not self._initialized or not self._config:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- try:
- # Delete sandbox by ID directly
- Sandbox.delete_by_id(sandbox_id=instance_id)
-
- logger.info(f"Successfully destroyed sandbox instance {instance_id}")
- return True
-
- except ServerError as e:
- logger.error(f"Failed to destroy instance {instance_id}: {str(e)}")
- return False
- except Exception as e:
- logger.error(f"Unexpected error destroying instance {instance_id}: {str(e)}")
- return False
-
- def health_check(self) -> bool:
- """
- Check if the Aliyun Code Interpreter service is accessible.
-
- Returns:
- True if provider is healthy, False otherwise
- """
- if not self._initialized and not (self.access_key_id and self.account_id):
- return False
-
- try:
- # Try to list templates to verify connection
- from agentrun.sandbox import Template
-
- templates = Template.list_templates(config=self._config)
- return templates is not None
-
- except Exception as e:
- logger.warning(f"Aliyun Code Interpreter health check failed: {str(e)}")
- # If we get any response (even an error), the service is reachable
- return "connection" not in str(e).lower()
-
- def get_supported_languages(self) -> List[str]:
- """
- Get list of supported programming languages.
-
- Returns:
- List of language identifiers
- """
- return ["python", "javascript"]
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- """
- Return configuration schema for Aliyun Code Interpreter provider.
-
- Returns:
- Dictionary mapping field names to their schema definitions
- """
- return {
- "access_key_id": {
- "type": "string",
- "required": True,
- "label": "Access Key ID",
- "placeholder": "LTAI5t...",
- "description": "Aliyun AccessKey ID for authentication",
- "secret": False,
- },
- "access_key_secret": {
- "type": "string",
- "required": True,
- "label": "Access Key Secret",
- "placeholder": "β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’β€’",
- "description": "Aliyun AccessKey Secret for authentication",
- "secret": True,
- },
- "account_id": {
- "type": "string",
- "required": True,
- "label": "Account ID",
- "placeholder": "1234567890...",
- "description": "Aliyun primary account ID, required for API calls",
- },
- "region": {
- "type": "string",
- "required": False,
- "label": "Region",
- "default": "cn-hangzhou",
- "description": "Aliyun region for Code Interpreter service",
- "options": ["cn-hangzhou", "cn-beijing", "cn-shanghai", "cn-shenzhen", "cn-guangzhou"],
- },
- "template_name": {
- "type": "string",
- "required": False,
- "label": "Template Name",
- "placeholder": "my-interpreter",
- "description": "Optional sandbox template name for pre-configured environments",
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "label": "Execution Timeout (seconds)",
- "default": 30,
- "min": 1,
- "max": 30,
- "description": "Code execution timeout (max 30 seconds - hard limit)",
- },
- }
-
- def validate_config(self, config: Dict[str, Any]) -> tuple[bool, Optional[str]]:
- """
- Validate Aliyun-specific configuration.
-
- Args:
- config: Configuration dictionary to validate
-
- Returns:
- Tuple of (is_valid, error_message)
- """
- # Validate access key format
- access_key_id = config.get("access_key_id", "")
- if access_key_id and not access_key_id.startswith("LTAI"):
- return False, "Invalid AccessKey ID format (should start with 'LTAI')"
-
- # Validate account ID
- account_id = config.get("account_id", "")
- if not account_id:
- return False, "Account ID is required"
-
- # Validate region
- valid_regions = ["cn-hangzhou", "cn-beijing", "cn-shanghai", "cn-shenzhen", "cn-guangzhou"]
- region = config.get("region", "cn-hangzhou")
- if region and region not in valid_regions:
- return False, f"Invalid region. Must be one of: {', '.join(valid_regions)}"
-
- # Validate timeout range (max 30 seconds)
- timeout = config.get("timeout", 30)
- if isinstance(timeout, int) and (timeout < 1 or timeout > 30):
- return False, "Timeout must be between 1 and 30 seconds"
-
- return True, None
-
- def _normalize_language(self, language: str) -> str:
- """
- Normalize language identifier to Aliyun format.
-
- Args:
- language: Language identifier (python, python3, javascript, nodejs)
-
- Returns:
- Normalized language identifier
- """
- if not language:
- return "python"
-
- lang_lower = language.lower()
- if lang_lower in ("python", "python3"):
- return "python"
- elif lang_lower in ("javascript", "nodejs"):
- return "javascript"
- else:
- return language
diff --git a/agent/sandbox/providers/base.py b/agent/sandbox/providers/base.py
deleted file mode 100644
index 012eaff009..0000000000
--- a/agent/sandbox/providers/base.py
+++ /dev/null
@@ -1,211 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Base interface for sandbox providers.
-
-Each sandbox provider (self-managed, SaaS) implements this interface
-to provide code execution capabilities.
-"""
-
-from abc import ABC, abstractmethod
-from dataclasses import dataclass
-from typing import Dict, Any, Optional, List
-
-
-class SandboxProviderConfigError(Exception):
- """Raised when the selected provider is explicitly configured but unusable."""
-
-
-@dataclass
-class SandboxInstance:
- """Represents a sandbox execution instance"""
-
- instance_id: str
- provider: str
- status: str # running, stopped, error
- metadata: Dict[str, Any]
-
- def __post_init__(self):
- if self.metadata is None:
- self.metadata = {}
-
-
-@dataclass
-class ExecutionResult:
- """Result of code execution in a sandbox"""
-
- stdout: str
- stderr: str
- exit_code: int
- execution_time: float # in seconds
- metadata: Dict[str, Any]
-
- def __post_init__(self):
- if self.metadata is None:
- self.metadata = {}
-
-
-class SandboxProvider(ABC):
- """
- Base interface for all sandbox providers.
-
- Each provider implementation (self-managed, Aliyun OpenSandbox, E2B, etc.)
- must implement these methods to provide code execution capabilities.
- """
-
- @abstractmethod
- def initialize(self, config: Dict[str, Any]) -> bool:
- """
- Initialize the provider with configuration.
-
- Args:
- config: Provider-specific configuration dictionary
-
- Returns:
- True if initialization successful, False otherwise
- """
- pass
-
- @abstractmethod
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """
- Create a new sandbox instance.
-
- Args:
- template: Programming language/template for the instance
- (e.g., "python", "nodejs", "bash")
-
- Returns:
- SandboxInstance object representing the created instance
-
- Raises:
- RuntimeError: If instance creation fails
- """
- pass
-
- @abstractmethod
- def execute_code(self, instance_id: str, code: str, language: str, timeout: int = 10, arguments: Optional[Dict[str, Any]] = None) -> ExecutionResult:
- """
- Execute code in a sandbox instance.
-
- Args:
- instance_id: ID of the sandbox instance
- code: Source code to execute
- language: Programming language (python, javascript, etc.)
- timeout: Maximum execution time in seconds
- arguments: Optional arguments dict to pass to main() function
-
- Returns:
- ExecutionResult containing stdout, stderr, exit_code, and metadata
-
- Raises:
- RuntimeError: If execution fails
- TimeoutError: If execution exceeds timeout
- """
- pass
-
- @abstractmethod
- def destroy_instance(self, instance_id: str) -> bool:
- """
- Destroy a sandbox instance.
-
- Args:
- instance_id: ID of the instance to destroy
-
- Returns:
- True if destruction successful, False otherwise
-
- Raises:
- RuntimeError: If destruction fails
- """
- pass
-
- @abstractmethod
- def health_check(self) -> bool:
- """
- Check if the provider is healthy and accessible.
-
- Returns:
- True if provider is healthy, False otherwise
- """
- pass
-
- @abstractmethod
- def get_supported_languages(self) -> List[str]:
- """
- Get list of supported programming languages.
-
- Returns:
- List of language identifiers (e.g., ["python", "javascript", "go"])
- """
- pass
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- """
- Return configuration schema for this provider.
-
- The schema defines what configuration fields are required/optional,
- their types, validation rules, and UI labels.
-
- Returns:
- Dictionary mapping field names to their schema definitions.
-
- Example:
- {
- "endpoint": {
- "type": "string",
- "required": True,
- "label": "API Endpoint",
- "placeholder": "http://sandbox-executor-manager:9385"
- },
- "timeout": {
- "type": "integer",
- "default": 30,
- "label": "Timeout (seconds)",
- "min": 5,
- "max": 300
- }
- }
- """
- return {}
-
- def validate_config(self, config: Dict[str, Any]) -> tuple[bool, Optional[str]]:
- """
- Validate provider-specific configuration.
-
- This method allows providers to implement custom validation logic beyond
- the basic schema validation. Override this method to add provider-specific
- checks like URL format validation, API key format validation, etc.
-
- Args:
- config: Configuration dictionary to validate
-
- Returns:
- Tuple of (is_valid, error_message):
- - is_valid: True if configuration is valid, False otherwise
- - error_message: Error message if invalid, None if valid
-
- Example:
- >>> def validate_config(self, config):
- >>> endpoint = config.get("endpoint", "")
- >>> if not endpoint.startswith(("http://", "https://")):
- >>> return False, "Endpoint must start with http:// or https://"
- >>> return True, None
- """
- # Default implementation: no custom validation
- return True, None
diff --git a/agent/sandbox/providers/e2b.py b/agent/sandbox/providers/e2b.py
deleted file mode 100644
index 0ebd837564..0000000000
--- a/agent/sandbox/providers/e2b.py
+++ /dev/null
@@ -1,225 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-E2B provider implementation.
-
-This provider integrates with E2B Cloud for cloud-based code execution
-using Firecracker microVMs.
-"""
-
-import uuid
-from typing import Dict, Any, List
-
-from .base import SandboxProvider, SandboxInstance, ExecutionResult
-
-
-class E2BProvider(SandboxProvider):
- """
- E2B provider implementation.
-
- This provider uses E2B Cloud service for secure code execution
- in Firecracker microVMs.
- """
-
- def __init__(self):
- self.api_key: str = ""
- self.region: str = "us"
- self.timeout: int = 30
- self._initialized: bool = False
-
- def initialize(self, config: Dict[str, Any]) -> bool:
- """
- Initialize the provider with E2B credentials.
-
- Args:
- config: Configuration dictionary with keys:
- - api_key: E2B API key
- - region: Region (us, eu) (default: "us")
- - timeout: Request timeout in seconds (default: 30)
-
- Returns:
- True if initialization successful, False otherwise
- """
- self.api_key = config.get("api_key", "")
- self.region = config.get("region", "us")
- self.timeout = config.get("timeout", 30)
-
- # Validate required fields
- if not self.api_key:
- return False
-
- # TODO: Implement actual E2B API client initialization
- # For now, we'll mark as initialized but actual API calls will fail
- self._initialized = True
- return True
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """
- Create a new sandbox instance in E2B.
-
- Args:
- template: Programming language template (python, nodejs, go, bash)
-
- Returns:
- SandboxInstance object
-
- Raises:
- RuntimeError: If instance creation fails
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # Normalize language
- language = self._normalize_language(template)
-
- # TODO: Implement actual E2B API call
- # POST /sandbox with template
- instance_id = str(uuid.uuid4())
-
- return SandboxInstance(
- instance_id=instance_id,
- provider="e2b",
- status="running",
- metadata={
- "language": language,
- "region": self.region,
- },
- )
-
- def execute_code(self, instance_id: str, code: str, language: str, timeout: int = 10) -> ExecutionResult:
- """
- Execute code in the E2B instance.
-
- Args:
- instance_id: ID of the sandbox instance
- code: Source code to execute
- language: Programming language (python, nodejs, go, bash)
- timeout: Maximum execution time in seconds
-
- Returns:
- ExecutionResult containing stdout, stderr, exit_code, and metadata
-
- Raises:
- RuntimeError: If execution fails
- TimeoutError: If execution exceeds timeout
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # TODO: Implement actual E2B API call
- # POST /sandbox/{sandboxID}/execute
-
- raise RuntimeError(
- "E2B provider is not yet fully implemented. Please use the self-managed provider or implement the E2B API integration. See https://github.com/e2b-dev/e2b for API documentation."
- )
-
- def destroy_instance(self, instance_id: str) -> bool:
- """
- Destroy an E2B instance.
-
- Args:
- instance_id: ID of the instance to destroy
-
- Returns:
- True if destruction successful, False otherwise
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # TODO: Implement actual E2B API call
- # DELETE /sandbox/{sandboxID}
- return True
-
- def health_check(self) -> bool:
- """
- Check if the E2B service is accessible.
-
- Returns:
- True if provider is healthy, False otherwise
- """
- if not self._initialized:
- return False
-
- # TODO: Implement actual E2B health check API call
- # GET /healthz or similar
- # For now, return True if initialized with API key
- return bool(self.api_key)
-
- def get_supported_languages(self) -> List[str]:
- """
- Get list of supported programming languages.
-
- Returns:
- List of language identifiers
- """
- return ["python", "nodejs", "javascript", "go", "bash"]
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- """
- Return configuration schema for E2B provider.
-
- Returns:
- Dictionary mapping field names to their schema definitions
- """
- return {
- "api_key": {
- "type": "string",
- "required": True,
- "label": "API Key",
- "placeholder": "e2b_sk_...",
- "description": "E2B API key for authentication",
- "secret": True,
- },
- "region": {
- "type": "string",
- "required": False,
- "label": "Region",
- "default": "us",
- "description": "E2B service region (us or eu)",
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "label": "Request Timeout (seconds)",
- "default": 30,
- "min": 5,
- "max": 300,
- "description": "API request timeout for code execution",
- },
- }
-
- def _normalize_language(self, language: str) -> str:
- """
- Normalize language identifier to E2B template format.
-
- Args:
- language: Language identifier
-
- Returns:
- Normalized language identifier
- """
- if not language:
- return "python"
-
- lang_lower = language.lower()
- if lang_lower in ("python", "python3"):
- return "python"
- elif lang_lower in ("javascript", "nodejs"):
- return "nodejs"
- else:
- return language
diff --git a/agent/sandbox/providers/local.py b/agent/sandbox/providers/local.py
deleted file mode 100644
index 6a9ac516bd..0000000000
--- a/agent/sandbox/providers/local.py
+++ /dev/null
@@ -1,354 +0,0 @@
-#
-# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import base64
-import json
-import mimetypes
-import os
-import shutil
-import signal
-import subprocess
-import time
-import uuid
-from pathlib import Path
-from typing import Any, Dict, List, Optional
-
-from agent.sandbox.result_protocol import build_javascript_wrapper, build_python_wrapper, extract_structured_result
-from .base import ExecutionResult, SandboxInstance, SandboxProvider, SandboxProviderConfigError
-
-
-ALLOWED_ARTIFACT_EXTENSIONS = {
- ".csv",
- ".html",
- ".jpeg",
- ".jpg",
- ".json",
- ".pdf",
- ".png",
- ".svg",
-}
-
-LOCAL_PYTHON_THREAD_ENV_VARS = (
- "OPENBLAS_NUM_THREADS",
- "OMP_NUM_THREADS",
- "MKL_NUM_THREADS",
- "NUMEXPR_NUM_THREADS",
- "BLIS_NUM_THREADS",
- "VECLIB_MAXIMUM_THREADS",
-)
-
-
-class LocalProvider(SandboxProvider):
- """
- Execute code as a local child process.
-
- This provider is intentionally gated by SANDBOX_LOCAL_ENABLED because it is
- not a sandbox boundary. Use a low-privilege runtime account.
- """
-
- def __init__(self):
- self.python_bin = "python3"
- self.node_bin = "node"
- self.work_dir = Path("/tmp/ragflow-codeexec")
- self.timeout = 30
- self.max_memory_mb = 512
- self.max_output_bytes = 1024 * 1024
- self.max_artifacts = 20
- self.max_artifact_bytes = 10 * 1024 * 1024
- self._initialized = False
- self._instances: dict[str, Path] = {}
-
- def initialize(self, config: Dict[str, Any]) -> bool:
- self.python_bin = str(config.get("python_bin", "python3"))
- self.node_bin = str(config.get("node_bin", "node"))
- self.work_dir = Path(str(config.get("work_dir", "/tmp/ragflow-codeexec"))).resolve()
- self.timeout = int(config.get("timeout", 30))
- self.max_memory_mb = int(config.get("max_memory_mb", 512))
- self.max_output_bytes = int(config.get("max_output_bytes", 1024 * 1024))
- self.max_artifacts = int(config.get("max_artifacts", 20))
- self.max_artifact_bytes = int(config.get("max_artifact_bytes", 10 * 1024 * 1024))
-
- self._validate_limits()
- self.work_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
- self._initialized = True
- return True
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- language = self._normalize_language(template)
- instance_id = str(uuid.uuid4())
- instance_dir = self.work_dir / instance_id
- instance_dir.mkdir(mode=0o700)
- (instance_dir / "artifacts").mkdir(mode=0o700)
- self._instances[instance_id] = instance_dir
-
- return SandboxInstance(
- instance_id=instance_id,
- provider="local",
- status="running",
- metadata={"language": language, "work_dir": str(instance_dir)},
- )
-
- def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10,
- arguments: Optional[Dict[str, Any]] = None,
- ) -> ExecutionResult:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- normalized_lang = self._normalize_language(language)
- instance_dir = self._instances[instance_id]
- args_json = json.dumps(arguments or {}, ensure_ascii=False)
- command, script_path = self._prepare_script(instance_dir, normalized_lang, code, args_json)
- requested_timeout = self.timeout if timeout is None else int(timeout)
- if requested_timeout <= 0:
- raise RuntimeError(f"Execution timeout must be greater than 0 seconds, got {requested_timeout}.")
- exec_timeout = min(requested_timeout, self.timeout)
-
- start_time = time.time()
- process = subprocess.Popen(
- command,
- cwd=instance_dir,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- encoding="utf-8",
- errors="replace",
- env=self._build_child_env(instance_dir),
- preexec_fn=self._limit_child_process if os.name == "posix" else None,
- start_new_session=os.name == "posix",
- )
-
- try:
- stdout, stderr = process.communicate(timeout=exec_timeout)
- except subprocess.TimeoutExpired:
- if os.name == "posix":
- os.killpg(process.pid, signal.SIGKILL)
- else:
- process.kill()
- process.communicate()
- raise TimeoutError(f"Execution timed out after {exec_timeout} seconds")
-
- execution_time = time.time() - start_time
- self._validate_output_size(stdout, stderr)
- stdout, structured_result = extract_structured_result(stdout)
-
- return ExecutionResult(
- stdout=stdout,
- stderr=stderr,
- exit_code=process.returncode,
- execution_time=execution_time,
- metadata={
- "instance_id": instance_id,
- "language": normalized_lang,
- "script_path": str(script_path),
- "status": "ok" if process.returncode == 0 else "error",
- "timeout": exec_timeout,
- "artifacts": self._collect_artifacts(instance_dir / "artifacts"),
- "result_present": structured_result.get("present", False),
- "result_value": structured_result.get("value"),
- "result_type": structured_result.get("type"),
- },
- )
-
- def destroy_instance(self, instance_id: str) -> bool:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- instance_dir = self._instances.pop(instance_id)
- shutil.rmtree(instance_dir)
- return True
-
- def health_check(self) -> bool:
- return self._initialized and self.work_dir.exists() and os.access(self.work_dir, os.W_OK)
-
- def get_supported_languages(self) -> List[str]:
- return ["python", "javascript", "nodejs"]
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "python_bin": {
- "type": "string",
- "required": False,
- "default": "python3",
- "label": "Python Binary",
- "description": "Python executable used for local code execution.",
- },
- "node_bin": {
- "type": "string",
- "required": False,
- "default": "node",
- "label": "Node.js Binary",
- "description": "Node.js executable used for local JavaScript execution.",
- },
- "work_dir": {
- "type": "string",
- "required": False,
- "default": "/tmp/ragflow-codeexec",
- "label": "Working Directory",
- "description": "Directory used to store temporary scripts and artifacts on the current host.",
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "default": 30,
- "label": "Timeout (seconds)",
- "description": "Maximum execution time for each local run. Unit: seconds.",
- "min": 1,
- "max": 600,
- },
- "max_memory_mb": {
- "type": "integer",
- "required": False,
- "default": 512,
- "label": "Max Memory (MB)",
- "description": "Address-space memory limit for the local child process. Unit: MB.",
- "min": 1,
- "max": 65536,
- },
- "max_output_bytes": {
- "type": "integer",
- "required": False,
- "default": 1048576,
- "label": "Max Output (bytes)",
- "description": "Maximum combined stdout and stderr size. Unit: bytes.",
- "min": 1024,
- "max": 10485760,
- },
- "max_artifacts": {
- "type": "integer",
- "required": False,
- "default": 20,
- "label": "Max Artifacts",
- "description": "Maximum number of files collected from the artifacts directory.",
- "min": 0,
- "max": 100,
- },
- "max_artifact_bytes": {
- "type": "integer",
- "required": False,
- "default": 10485760,
- "label": "Max Artifact Size (bytes)",
- "description": "Maximum size of a single artifact file. Unit: bytes.",
- "min": 1024,
- "max": 104857600,
- },
- }
-
- def _validate_limits(self) -> None:
- if self.timeout <= 0:
- raise SandboxProviderConfigError("SANDBOX_LOCAL_TIMEOUT must be greater than 0.")
- if self.max_memory_mb <= 0:
- raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_MEMORY_MB must be greater than 0.")
- if self.max_output_bytes <= 0:
- raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_OUTPUT_BYTES must be greater than 0.")
- if self.max_artifacts < 0:
- raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACTS must be greater than or equal to 0.")
- if self.max_artifact_bytes <= 0:
- raise SandboxProviderConfigError("SANDBOX_LOCAL_MAX_ARTIFACT_BYTES must be greater than 0.")
-
- def _prepare_script(self, instance_dir: Path, language: str, code: str, args_json: str) -> tuple[list[str], Path]:
- if language == "python":
- script_path = instance_dir / "main.py"
- script_path.write_text(build_python_wrapper(code, args_json), encoding="utf-8")
- return [self.python_bin, str(script_path)], script_path
- if language in {"javascript", "nodejs"}:
- script_path = instance_dir / "main.js"
- script_path.write_text(build_javascript_wrapper(code, args_json), encoding="utf-8")
- return [self.node_bin, str(script_path)], script_path
- raise RuntimeError(f"Unsupported language for local provider: {language}")
-
- def _build_child_env(self, instance_dir: Path) -> dict[str, str]:
- env = {
- "HOME": str(instance_dir),
- "MPLBACKEND": "Agg",
- "PATH": os.environ.get("PATH", ""),
- "PYTHONUNBUFFERED": "1",
- "TMPDIR": str(instance_dir),
- }
- for name in LOCAL_PYTHON_THREAD_ENV_VARS:
- value = os.environ.get(name)
- if value is not None:
- env[name] = value
- return env
-
- def _limit_child_process(self) -> None:
- import resource
-
- self._set_resource_limit(resource.RLIMIT_CPU, self.timeout + 1)
- self._set_resource_limit(resource.RLIMIT_AS, self.max_memory_mb * 1024 * 1024)
- self._set_resource_limit(resource.RLIMIT_FSIZE, self.max_artifact_bytes)
- self._set_resource_limit(resource.RLIMIT_NOFILE, 64)
-
- @staticmethod
- def _set_resource_limit(kind: int, value: int) -> None:
- import resource
-
- _, hard = resource.getrlimit(kind)
- limit = value if hard == resource.RLIM_INFINITY else min(value, hard)
- resource.setrlimit(kind, (limit, limit))
-
- def _validate_output_size(self, stdout: str, stderr: str) -> None:
- output_size = len((stdout or "").encode("utf-8")) + len((stderr or "").encode("utf-8"))
- if output_size > self.max_output_bytes:
- raise RuntimeError(f"Local execution output exceeded {self.max_output_bytes} bytes.")
-
- def _collect_artifacts(self, artifacts_dir: Path) -> list[dict[str, Any]]:
- artifacts: list[dict[str, Any]] = []
- for path in sorted(artifacts_dir.rglob("*")):
- if path.is_symlink():
- raise RuntimeError(f"Artifact symlinks are not allowed: {path.name}")
- if path.is_dir():
- continue
- if not path.is_file():
- raise RuntimeError(f"Unsupported artifact entry: {path.name}")
-
- if len(artifacts) >= self.max_artifacts:
- raise RuntimeError(f"Local execution produced more than {self.max_artifacts} artifacts.")
-
- size = path.stat().st_size
- if size > self.max_artifact_bytes:
- raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {path.name}")
-
- ext = path.suffix.lower()
- if ext not in ALLOWED_ARTIFACT_EXTENSIONS:
- raise RuntimeError(f"Unsupported artifact type: {path.name}")
-
- artifacts.append(
- {
- "name": path.relative_to(artifacts_dir).as_posix(),
- "content_b64": base64.b64encode(path.read_bytes()).decode("ascii"),
- "mime_type": mimetypes.guess_type(path.name)[0] or "application/octet-stream",
- "size": size,
- }
- )
- return artifacts
-
- @staticmethod
- def _normalize_language(language: str) -> str:
- lang_lower = (language or "python").lower()
- if lang_lower in {"python", "python3"}:
- return "python"
- if lang_lower in {"javascript", "nodejs"}:
- return "nodejs"
- return lang_lower
diff --git a/agent/sandbox/providers/manager.py b/agent/sandbox/providers/manager.py
deleted file mode 100644
index 3a6fce5c25..0000000000
--- a/agent/sandbox/providers/manager.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Provider manager for sandbox providers.
-
-Since sandbox configuration is global (system-level), we only use one
-active provider at a time. This manager is a thin wrapper that holds a reference
-to the currently active provider.
-"""
-
-from typing import Optional
-from .base import SandboxProvider
-
-
-class ProviderManager:
- """
- Manages the currently active sandbox provider.
-
- With global configuration, there's only one active provider at a time.
- This manager simply holds a reference to that provider.
- """
-
- def __init__(self):
- """Initialize an empty provider manager."""
- self.current_provider: Optional[SandboxProvider] = None
- self.current_provider_name: Optional[str] = None
-
- def set_provider(self, name: str, provider: SandboxProvider):
- """
- Set the active provider.
-
- Args:
- name: Provider identifier (e.g., "self_managed", "e2b")
- provider: Provider instance
- """
- self.current_provider = provider
- self.current_provider_name = name
-
- def get_provider(self) -> Optional[SandboxProvider]:
- """
- Get the active provider.
-
- Returns:
- Currently active SandboxProvider instance, or None if not set
- """
- return self.current_provider
-
- def get_provider_name(self) -> Optional[str]:
- """
- Get the active provider name.
-
- Returns:
- Provider name (e.g., "self_managed"), or None if not set
- """
- return self.current_provider_name
-
- def is_configured(self) -> bool:
- """
- Check if a provider is configured.
-
- Returns:
- True if a provider is set, False otherwise
- """
- return self.current_provider is not None
diff --git a/agent/sandbox/providers/self_managed.py b/agent/sandbox/providers/self_managed.py
deleted file mode 100644
index 296e21757f..0000000000
--- a/agent/sandbox/providers/self_managed.py
+++ /dev/null
@@ -1,421 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Self-managed sandbox provider implementation.
-
-This provider wraps the existing executor_manager HTTP API which manages
-a pool of Docker containers with gVisor for secure code execution.
-"""
-
-import base64
-import os
-import time
-import uuid
-from typing import Any
-
-import requests
-
-from .base import ExecutionResult, SandboxInstance, SandboxProvider
-
-
-class SelfManagedProvider(SandboxProvider):
- """
- Self-managed sandbox provider using Daytona/Docker.
-
- This provider communicates with the executor_manager HTTP API
- which manages a pool of containers for code execution.
- """
-
- def __init__(self):
- self.endpoint: str = "http://sandbox-executor-manager:9385"
- self.timeout: int = 30
- self.max_retries: int = 3
- self.pool_size: int = 3
- self.api_token: str = ""
- self._initialized: bool = False
-
- def initialize(self, config: dict[str, Any]) -> bool:
- """
- Initialize the provider with configuration.
-
- Args:
- config: Configuration dictionary with keys:
- - endpoint: HTTP endpoint (default: "http://sandbox-executor-manager:9385")
- - timeout: Request timeout in seconds (default: 30)
- - max_retries: Maximum retry attempts (default: 3)
- - pool_size: Container pool size for info (default: 3)
- - api_token: Shared secret for the executor manager API
- (falls back to SANDBOX_EXECUTOR_MANAGER_API_TOKEN env var)
-
- Returns:
- True if initialization successful, False otherwise
- """
- self.endpoint = config.get("endpoint", "http://sandbox-executor-manager:9385")
- self.timeout = config.get("timeout", 30)
- self.max_retries = config.get("max_retries", 3)
- self.pool_size = config.get("executor_manager_pool_size", config.get("pool_size", 3))
- # Shared-secret token authenticating RAGFlow towards the executor
- # manager. Explicit config wins over the environment variable.
- self.api_token = str(config.get("api_token") or os.getenv("SANDBOX_EXECUTOR_MANAGER_API_TOKEN", "") or "").strip()
-
- # Validate endpoint is accessible
- if not self.health_check():
- return False
-
- self._initialized = True
- return True
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """
- Create a new sandbox instance.
-
- Note: For self-managed provider, instances are managed internally
- by the executor_manager's container pool. This method returns
- a logical instance handle.
-
- Args:
- template: Programming language (python, nodejs)
-
- Returns:
- SandboxInstance object
-
- Raises:
- RuntimeError: If instance creation fails
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # Normalize language
- language = self._normalize_language(template)
-
- # The executor_manager manages instances internally via container pool
- # We create a logical instance ID for tracking
- instance_id = str(uuid.uuid4())
-
- return SandboxInstance(
- instance_id=instance_id,
- provider="self_managed",
- status="running",
- metadata={
- "language": language,
- "endpoint": self.endpoint,
- "pool_size": self.pool_size,
- },
- )
-
- def execute_code(self, instance_id: str, code: str, language: str, timeout: int = 10, arguments: dict[str, Any] | None = None) -> ExecutionResult:
- """
- Execute code in the sandbox.
-
- Args:
- instance_id: ID of the sandbox instance (not used for self-managed)
- code: Source code to execute
- language: Programming language (python, nodejs, javascript)
- timeout: Maximum execution time in seconds
- arguments: Optional arguments dict to pass to main() function
-
- Returns:
- ExecutionResult containing stdout, stderr, exit_code, and metadata
-
- Raises:
- RuntimeError: If execution fails
- TimeoutError: If execution exceeds timeout
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- # Normalize language
- normalized_lang = self._normalize_language(language)
-
- # Prepare request
- code_b64 = base64.b64encode(code.encode("utf-8")).decode("utf-8")
- payload = {"code_b64": code_b64, "language": normalized_lang, "arguments": arguments or {}}
-
- url = f"{self.endpoint}/run"
- exec_timeout = timeout or self.timeout
-
- headers = {"Content-Type": "application/json"}
- if self.api_token:
- headers["Authorization"] = f"Bearer {self.api_token}"
-
- start_time = time.time()
-
- try:
- response = requests.post(url, json=payload, timeout=exec_timeout, headers=headers)
-
- execution_time = time.time() - start_time
-
- if response.status_code != 200:
- raise RuntimeError(f"HTTP {response.status_code}: {response.text}")
-
- result = response.json()
- structured_result = result.get("result") or {}
-
- return ExecutionResult(
- stdout=result.get("stdout", ""),
- stderr=result.get("stderr", ""),
- exit_code=result.get("exit_code", 0),
- execution_time=execution_time,
- metadata={
- "status": result.get("status"),
- "time_used_ms": result.get("time_used_ms"),
- "memory_used_kb": result.get("memory_used_kb"),
- "detail": result.get("detail"),
- "instance_id": instance_id,
- "artifacts": result.get("artifacts", []),
- "result_present": structured_result.get("present", False),
- "result_value": structured_result.get("value"),
- "result_type": structured_result.get("type"),
- },
- )
-
- except requests.Timeout:
- execution_time = time.time() - start_time
- raise TimeoutError(f"Execution timed out after {exec_timeout} seconds")
-
- except requests.RequestException as e:
- raise RuntimeError(f"HTTP request failed: {e!s}")
-
- def destroy_instance(self, instance_id: str) -> bool:
- """
- Destroy a sandbox instance.
-
- Note: For self-managed provider, instances are returned to the
- internal pool automatically by executor_manager after execution.
- This is a no-op for tracking purposes.
-
- Args:
- instance_id: ID of the instance to destroy
-
- Returns:
- True (always succeeds for self-managed)
- """
- # The executor_manager manages container lifecycle internally
- # Container is returned to pool after execution
- return True
-
- def health_check(self) -> bool:
- """
- Check if the provider is healthy and accessible.
-
- Returns:
- True if provider is healthy, False otherwise
- """
- try:
- url = f"{self.endpoint}/healthz"
- response = requests.get(url, timeout=5)
- return response.status_code == 200
- except Exception:
- return False
-
- def get_supported_languages(self) -> list[str]:
- """
- Get list of supported programming languages.
-
- Returns:
- List of language identifiers
- """
- return ["python", "nodejs", "javascript"]
-
- @staticmethod
- def get_config_schema() -> dict[str, dict]:
- """
- Return configuration schema for self-managed provider.
-
- Returns:
- Dictionary mapping field names to their schema definitions
- """
- return {
- "endpoint": {
- "type": "string",
- "required": True,
- "label": "Executor Manager Endpoint",
- "placeholder": "http://sandbox-executor-manager:9385",
- "default": "http://sandbox-executor-manager:9385",
- "description": "HTTP endpoint used by RAGFlow to call sandbox-executor-manager.",
- "scope": "runtime",
- "readonly": False,
- },
- "api_token": {
- "type": "string",
- "required": False,
- "label": "Executor Manager API Token",
- "secret": True,
- "placeholder": "Optional; defaults to SANDBOX_EXECUTOR_MANAGER_API_TOKEN",
- "default": "",
- "description": "Shared secret authenticating RAGFlow to sandbox-executor-manager. Must match SANDBOX_EXECUTOR_MANAGER_API_TOKEN on the executor-manager side.",
- "scope": "runtime",
- "readonly": False,
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "label": "Request Timeout (seconds)",
- "default": 30,
- "min": 5,
- "max": 300,
- "description": "Maximum request time for a single code execution call. Unit: seconds.",
- "scope": "runtime",
- "readonly": False,
- },
- "executor_manager_image": {
- "type": "string",
- "required": False,
- "label": "Executor Manager Image",
- "default": os.getenv("SANDBOX_EXECUTOR_MANAGER_IMAGE", "infiniflow/sandbox-executor-manager:latest"),
- "description": "Docker image used by sandbox-executor-manager.",
- "scope": "deployment",
- "readonly": True,
- },
- "executor_manager_pool_size": {
- "type": "integer",
- "required": False,
- "label": "Container Pool Size",
- "default": int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "3")),
- "min": 1,
- "max": 100,
- "description": "Container pool size used by sandbox-executor-manager.",
- "scope": "deployment",
- "readonly": True,
- },
- "base_python_image": {
- "type": "string",
- "required": False,
- "label": "Base Python Image",
- "default": os.getenv("SANDBOX_BASE_PYTHON_IMAGE", "infiniflow/sandbox-base-python:latest"),
- "description": "Python runtime image used by executor-managed containers.",
- "scope": "deployment",
- "readonly": True,
- },
- "base_nodejs_image": {
- "type": "string",
- "required": False,
- "label": "Base Node.js Image",
- "default": os.getenv("SANDBOX_BASE_NODEJS_IMAGE", "infiniflow/sandbox-base-nodejs:latest"),
- "description": "Node.js runtime image used by executor-managed containers.",
- "scope": "deployment",
- "readonly": True,
- },
- "executor_manager_port": {
- "type": "integer",
- "required": False,
- "label": "Executor Manager Port",
- "default": int(os.getenv("SANDBOX_EXECUTOR_MANAGER_PORT", "9385")),
- "min": 1,
- "max": 65535,
- "description": "Host port exposed by sandbox-executor-manager.",
- "scope": "deployment",
- "readonly": True,
- },
- "enable_seccomp": {
- "type": "boolean",
- "required": False,
- "label": "Enable Seccomp",
- "default": os.getenv("SANDBOX_ENABLE_SECCOMP", "false").lower() == "true",
- "description": "Whether sandbox-executor-manager starts containers with seccomp enabled.",
- "scope": "deployment",
- "readonly": True,
- },
- "max_memory": {
- "type": "string",
- "required": False,
- "label": "Max Memory",
- "default": os.getenv("SANDBOX_MAX_MEMORY", "256m"),
- "description": "Memory limit applied to each sandbox container. Common format: 256m or 1g.",
- "scope": "deployment",
- "readonly": True,
- },
- "container_network": {
- "type": "string",
- "required": False,
- "label": "Container Network",
- "default": os.getenv("SANDBOX_CONTAINER_NETWORK", "none"),
- "description": "Docker network attached to sandbox containers. Defaults to 'none' (no external network access); set to 'bridge' only if sandboxed code needs outbound network.",
- "scope": "deployment",
- "readonly": True,
- },
- "sandbox_timeout": {
- "type": "string",
- "required": False,
- "label": "Sandbox Timeout",
- "default": os.getenv("SANDBOX_TIMEOUT", "10s"),
- "description": "Executor-manager container timeout for each sandbox run. Common format: 10s or 1m.",
- "scope": "deployment",
- "readonly": True,
- },
- }
-
- def _normalize_language(self, language: str) -> str:
- """
- Normalize language identifier to executor_manager format.
-
- Args:
- language: Language identifier (python, python3, nodejs, javascript)
-
- Returns:
- Normalized language identifier
- """
- if not language:
- return "python"
-
- lang_lower = language.lower()
- if lang_lower in ("python", "python3"):
- return "python"
- elif lang_lower in ("javascript", "nodejs"):
- return "nodejs"
- else:
- return language
-
- def validate_config(self, config: dict) -> tuple[bool, str | None]:
- """
- Validate self-managed provider configuration.
-
- Performs custom validation beyond the basic schema validation,
- such as checking URL format.
-
- Args:
- config: Configuration dictionary to validate
-
- Returns:
- Tuple of (is_valid, error_message)
- """
- # Validate endpoint URL format
- endpoint = config.get("endpoint", "")
- if endpoint:
- # Check if it's a valid HTTP/HTTPS URL or localhost
- import re
-
- url_pattern = r"^(https?://|http://localhost|http://[\d\.]+:[a-z]+:[/]|http://[\w\.]+:)"
- if not re.match(url_pattern, endpoint):
- return False, f"Invalid endpoint format: {endpoint}. Must start with http:// or https://"
-
- # Validate pool_size is positive
- pool_size = config.get("executor_manager_pool_size", config.get("pool_size", 3))
- if isinstance(pool_size, int) and pool_size <= 0:
- return False, "Pool size must be greater than 0"
-
- # Validate timeout is reasonable
- timeout = config.get("timeout", 30)
- if isinstance(timeout, int) and (timeout < 1 or timeout > 600):
- return False, "Timeout must be between 1 and 600 seconds"
-
- # Validate max_retries
- max_retries = config.get("max_retries", 3)
- if isinstance(max_retries, int) and (max_retries < 0 or max_retries > 10):
- return False, "Max retries must be between 0 and 10"
-
- return True, None
diff --git a/agent/sandbox/providers/ssh.py b/agent/sandbox/providers/ssh.py
deleted file mode 100644
index 001c294300..0000000000
--- a/agent/sandbox/providers/ssh.py
+++ /dev/null
@@ -1,686 +0,0 @@
-#
-# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-import base64
-import io
-import json
-import logging
-import mimetypes
-import os
-import posixpath
-import shlex
-import stat
-import time
-import uuid
-from typing import TYPE_CHECKING, Any, Dict, List, Optional
-
-from agent.sandbox.result_protocol import (
- build_javascript_wrapper,
- build_python_wrapper,
- extract_structured_result,
-)
-from .base import (
- ExecutionResult,
- SandboxInstance,
- SandboxProvider,
- SandboxProviderConfigError,
-)
-
-if TYPE_CHECKING:
- import paramiko
-
-
-ALLOWED_ARTIFACT_EXTENSIONS = {
- ".csv",
- ".html",
- ".jpeg",
- ".jpg",
- ".json",
- ".pdf",
- ".png",
- ".svg",
-}
-
-
-class SSHProvider(SandboxProvider):
- """Execute code on a remote host through SSH."""
-
- def __init__(self):
- self.host = ""
- self.port = 22
- self.username = ""
- self.password = ""
- self.private_key = ""
- self.passphrase = ""
- self.python_bin = "python3"
- self.node_bin = "node"
- self.work_dir = "/tmp"
- self.timeout = 30
- self.max_output_bytes = 1024 * 1024
- self.max_artifacts = 20
- self.max_artifact_bytes = 10 * 1024 * 1024
- self.known_hosts = ""
- self._initialized = False
- self._instances: dict[str, dict[str, Any]] = {}
-
- def initialize(self, config: Dict[str, Any]) -> bool:
- self.host = str(config.get("host", "")).strip()
- self.port = int(config.get("port", 22) or 22)
- self.username = str(config.get("username", "")).strip()
- self.password = str(config.get("password", "") or "")
- self.private_key = str(config.get("private_key", "") or "")
- self.passphrase = str(config.get("passphrase", "") or "")
- self.python_bin = str(config.get("python_bin", "python3") or "python3").strip() or "python3"
- self.node_bin = str(config.get("node_bin", "node") or "node").strip() or "node"
- self.work_dir = str(config.get("work_dir", "/tmp") or "/tmp").strip() or "/tmp"
- self.timeout = int(config.get("timeout", 30) or 30)
- self.max_output_bytes = int(config.get("max_output_bytes", 1024 * 1024) or 1024 * 1024)
- self.max_artifacts = int(config.get("max_artifacts", 20) or 20)
- self.max_artifact_bytes = int(config.get("max_artifact_bytes", 10 * 1024 * 1024) or 10 * 1024 * 1024)
- self.known_hosts = str(config.get("known_hosts", "") or "").strip()
-
- is_valid, error_message = self.validate_config(
- {
- "host": self.host,
- "port": self.port,
- "username": self.username,
- "password": self.password,
- "private_key": self.private_key,
- "passphrase": self.passphrase,
- "python_bin": self.python_bin,
- "node_bin": self.node_bin,
- "work_dir": self.work_dir,
- "timeout": self.timeout,
- "max_output_bytes": self.max_output_bytes,
- "max_artifacts": self.max_artifacts,
- "max_artifact_bytes": self.max_artifact_bytes,
- }
- )
- if not is_valid:
- raise SandboxProviderConfigError(error_message or "Invalid SSH provider configuration.")
-
- self._assert_connectivity()
-
- self._initialized = True
- return True
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- language = self._normalize_language(template)
- client = self._create_ssh_client()
- sftp = client.open_sftp()
-
- try:
- remote_work_dir = self._create_remote_workspace(client)
- stdout, stderr, exit_code = self._run_remote_command(
- client,
- f"mkdir -p {shlex.quote(posixpath.join(remote_work_dir, 'artifacts'))}",
- timeout=min(self.timeout, 10),
- )
- if exit_code != 0:
- raise RuntimeError(f"Failed to create remote artifacts directory: {stderr or stdout or 'unknown error'}")
- except Exception:
- sftp.close()
- client.close()
- raise
-
- instance_id = str(uuid.uuid4())
- self._instances[instance_id] = {
- "client": client,
- "sftp": sftp,
- "remote_work_dir": remote_work_dir,
- "language": language,
- }
-
- return SandboxInstance(
- instance_id=instance_id,
- provider="ssh",
- status="running",
- metadata={"language": language, "remote_work_dir": remote_work_dir},
- )
-
- def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10,
- arguments: Optional[Dict[str, Any]] = None,
- ) -> ExecutionResult:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
- if instance_id not in self._instances:
- raise RuntimeError(f"Unknown SSH sandbox instance: {instance_id}")
-
- normalized_lang = self._normalize_language(language)
- instance = self._instances[instance_id]
- client: paramiko.SSHClient = instance["client"]
- sftp: paramiko.SFTPClient = instance["sftp"]
- remote_work_dir: str = instance["remote_work_dir"]
-
- args_json = json.dumps(arguments or {}, ensure_ascii=False)
- remote_script_path, command = self._upload_script(
- sftp=sftp,
- remote_work_dir=remote_work_dir,
- language=normalized_lang,
- code=code,
- args_json=args_json,
- )
-
- requested_timeout = self.timeout if timeout is None else int(timeout)
- if requested_timeout <= 0:
- raise RuntimeError(f"Execution timeout must be greater than 0 seconds, got {requested_timeout}.")
- exec_timeout = min(requested_timeout, self.timeout)
-
- start_time = time.time()
- stdout, stderr, exit_code = self._run_remote_command(client, command, timeout=exec_timeout)
- execution_time = time.time() - start_time
-
- self._validate_output_size(stdout, stderr)
- stdout, structured_result = extract_structured_result(stdout)
-
- return ExecutionResult(
- stdout=stdout,
- stderr=stderr,
- exit_code=exit_code,
- execution_time=execution_time,
- metadata={
- "instance_id": instance_id,
- "language": normalized_lang,
- "script_path": remote_script_path,
- "remote_work_dir": remote_work_dir,
- "status": "ok" if exit_code == 0 else "error",
- "timeout": exec_timeout,
- "command": command,
- "artifacts": self._collect_artifacts(sftp, posixpath.join(remote_work_dir, "artifacts")),
- "result_present": structured_result.get("present", False),
- "result_value": structured_result.get("value"),
- "result_type": structured_result.get("type"),
- },
- )
-
- def destroy_instance(self, instance_id: str) -> bool:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
- if instance_id not in self._instances:
- return True
-
- instance = self._instances.pop(instance_id)
- client: paramiko.SSHClient = instance["client"]
- sftp: paramiko.SFTPClient = instance["sftp"]
- remote_work_dir: str = instance["remote_work_dir"]
-
- cleanup_error: Optional[Exception] = None
- try:
- stdout, stderr, exit_code = self._run_remote_command(
- client,
- f"rm -rf {shlex.quote(remote_work_dir)}",
- timeout=min(self.timeout, 10),
- )
- if exit_code != 0:
- raise RuntimeError(stderr or stdout or "unknown error")
- except Exception as exc:
- cleanup_error = exc
- finally:
- try:
- sftp.close()
- finally:
- client.close()
-
- if cleanup_error is not None:
- raise RuntimeError(f"Failed to clean remote workspace {remote_work_dir}: {cleanup_error}")
- return True
-
- def health_check(self) -> bool:
- try:
- self._assert_connectivity()
- return True
- except Exception:
- return False
-
- def _assert_connectivity(self) -> None:
- try:
- client = self._create_ssh_client()
- try:
- _, stderr, exit_code = self._run_remote_command(
- client,
- "true",
- timeout=min(self.timeout, 10),
- )
- if exit_code != 0:
- raise SandboxProviderConfigError(f"SSH connectivity check failed on {self.username}@{self.host}:{self.port}: {stderr or 'remote command returned non-zero exit status'}")
- finally:
- client.close()
- except SandboxProviderConfigError:
- raise
- except Exception as exc:
- raise SandboxProviderConfigError(f"Failed to connect to SSH host {self.username}@{self.host}:{self.port}: {exc}") from exc
-
- def get_supported_languages(self) -> List[str]:
- return ["python", "javascript", "nodejs"]
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "host": {
- "type": "string",
- "required": True,
- "label": "SSH Host",
- "placeholder": "192.168.1.10",
- "description": "Remote host that will execute generated code.",
- },
- "port": {
- "type": "integer",
- "required": True,
- "label": "SSH Port",
- "default": 22,
- "min": 1,
- "max": 65535,
- "description": "SSH port on the remote host.",
- },
- "username": {
- "type": "string",
- "required": True,
- "label": "SSH Username",
- "placeholder": "ragflow",
- "description": "Username used to connect to the remote host.",
- },
- "password": {
- "type": "string",
- "required": False,
- "label": "SSH Password",
- "secret": True,
- "placeholder": "Optional when using a private key",
- "description": "Password-based SSH authentication.",
- },
- "private_key": {
- "type": "string",
- "required": False,
- "label": "SSH Private Key",
- "secret": True,
- "multiline": True,
- "placeholder": "Paste PEM content or enter a local file path",
- "description": "Private key PEM content or a readable private key path on the RAGFlow host.",
- },
- "passphrase": {
- "type": "string",
- "required": False,
- "label": "Private Key Passphrase",
- "secret": True,
- "placeholder": "Optional",
- "description": "Passphrase for the private key if it is encrypted.",
- },
- "known_hosts": {
- "type": "string",
- "required": False,
- "label": "SSH known_hosts File",
- "placeholder": "/etc/ragflow/ssh_known_hosts",
- "description": (
- "Path to an OpenSSH-format known_hosts file used to verify "
- "the remote host's key. When set, the file is loaded on top "
- "of the system host keys (~/.ssh/known_hosts). When unset, "
- "only system keys are used and unknown hosts are rejected."
- ),
- },
- "python_bin": {
- "type": "string",
- "required": False,
- "default": "python3",
- "label": "Python Binary",
- "description": "Python executable used for remote code execution.",
- },
- "node_bin": {
- "type": "string",
- "required": False,
- "default": "node",
- "label": "Node.js Binary",
- "description": "Node.js executable used for remote JavaScript execution.",
- },
- "work_dir": {
- "type": "string",
- "required": False,
- "label": "Remote Workspace Root",
- "default": "/tmp",
- "placeholder": "/tmp",
- "description": "Writable remote directory used to create a temporary workspace.",
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "label": "Timeout (seconds)",
- "default": 30,
- "min": 1,
- "max": 600,
- "description": "Maximum SSH execution time for a single run.",
- },
- "max_output_bytes": {
- "type": "integer",
- "required": False,
- "label": "Max Output Bytes",
- "default": 1048576,
- "min": 1024,
- "max": 10485760,
- "description": "Maximum combined stdout and stderr size.",
- },
- "max_artifacts": {
- "type": "integer",
- "required": False,
- "label": "Max Artifacts",
- "default": 20,
- "min": 0,
- "max": 100,
- "description": "Maximum number of files collected from the remote artifacts directory.",
- },
- "max_artifact_bytes": {
- "type": "integer",
- "required": False,
- "label": "Max Artifact Bytes",
- "default": 10485760,
- "min": 1024,
- "max": 104857600,
- "description": "Maximum size of a single artifact file in bytes.",
- },
- }
-
- def validate_config(self, config: Dict[str, Any]) -> tuple[bool, Optional[str]]:
- host = str(config.get("host", "") or "").strip()
- username = str(config.get("username", "") or "").strip()
- password = str(config.get("password", "") or "")
- private_key = str(config.get("private_key", "") or "")
- python_bin = str(config.get("python_bin", "python3") or "python3").strip()
- node_bin = str(config.get("node_bin", "node") or "node").strip()
-
- if not host:
- return False, "SSH host is required"
- if not username:
- return False, "SSH username is required"
- if not password and not private_key:
- return False, "Either password or private_key must be provided"
- if not python_bin:
- return False, "Python binary is required"
- if not node_bin:
- return False, "Node.js binary is required"
-
- try:
- port = int(config.get("port", 22) or 22)
- except (TypeError, ValueError):
- return False, "SSH port must be an integer"
- if port <= 0 or port > 65535:
- return False, "SSH port must be between 1 and 65535"
-
- for key in ("timeout", "max_output_bytes", "max_artifacts", "max_artifact_bytes"):
- try:
- value = int(config.get(key, 0) or 0)
- except (TypeError, ValueError):
- return False, f"{key} must be an integer"
- if key == "max_artifacts":
- if value < 0:
- return False, "max_artifacts must be greater than or equal to 0"
- elif value <= 0:
- return False, f"{key} must be greater than 0"
-
- return True, None
-
- def _create_ssh_client(self) -> paramiko.SSHClient:
- paramiko = _get_paramiko_module()
- client = paramiko.SSHClient()
- # Load trusted host keys BEFORE setting the policy. Without
- # load_system_host_keys() the in-memory store is empty and
- # RejectPolicy would reject every host on first connect,
- # breaking the provider for normal setups. The order matters:
- # load_system_host_keys() populates the store from
- # ~/.ssh/known_hosts (and the legacy /etc/ssh/ssh_known_hosts);
- # an optional explicit known_hosts file from `known_hosts`
- # config is then merged on top.
- client.load_system_host_keys()
- if self.known_hosts:
- try:
- client.load_host_keys(self.known_hosts)
- except OSError as exc:
- # Fail closed when the operator-configured trust store
- # is unreadable: continuing with system keys could let
- # the connection succeed against an unintended anchor
- # (e.g. an attacker who can write ~/.ssh/known_hosts).
- # Match the Go provider's fail-closed posture (see
- # internal/agent/sandbox/ssh.go::hostKeyCallback).
- logging.warning("SSH: failed to load configured known_hosts file; refusing connection")
- raise SandboxProviderConfigError("Failed to load configured SSH known_hosts file.") from exc
- # Reject unknown hosts: this is the default fail-closed posture
- # to prevent silent MITM. Operators must either ship a populated
- # known_hosts file or accept the warning (paramiko will fail the
- # connect) on first encounter.
- client.set_missing_host_key_policy(paramiko.RejectPolicy())
-
- connect_kwargs: dict[str, Any] = {
- "hostname": self.host,
- "port": self.port,
- "username": self.username,
- "timeout": self.timeout,
- "banner_timeout": self.timeout,
- "auth_timeout": self.timeout,
- "look_for_keys": False,
- "allow_agent": False,
- }
- if self.private_key:
- connect_kwargs["pkey"] = self._load_private_key()
- if self.password:
- connect_kwargs["password"] = self.password
-
- client.connect(**connect_kwargs)
- return client
-
- def _load_private_key(self) -> paramiko.PKey:
- paramiko = _get_paramiko_module()
- loaders = (
- paramiko.RSAKey,
- paramiko.Ed25519Key,
- paramiko.ECDSAKey,
- paramiko.DSSKey,
- )
- errors: list[str] = []
- private_key_value = self.private_key.strip()
- passphrase = self.passphrase or None
-
- if os.path.exists(private_key_value):
- for key_cls in loaders:
- try:
- return key_cls.from_private_key_file(private_key_value, password=passphrase)
- except Exception as exc:
- errors.append(str(exc))
- else:
- for key_cls in loaders:
- try:
- return key_cls.from_private_key(io.StringIO(private_key_value), password=passphrase)
- except Exception as exc:
- errors.append(str(exc))
-
- raise SandboxProviderConfigError("Failed to load SSH private key. " + "; ".join(error for error in errors if error))
-
- def _create_remote_workspace(self, client: paramiko.SSHClient) -> str:
- base_dir = self.work_dir.rstrip("/") or "/tmp"
- template = posixpath.join(base_dir, "ragflow-codeexec.XXXXXX")
- stdout, stderr, exit_code = self._run_remote_command(
- client,
- f"mkdir -p {shlex.quote(base_dir)} && mktemp -d {shlex.quote(template)}",
- timeout=min(self.timeout, 10),
- )
- if exit_code != 0:
- raise RuntimeError(f"Failed to create remote workspace on {self.host}: {stderr or stdout or 'unknown error'}")
-
- remote_work_dir = stdout.strip().splitlines()[-1] if stdout.strip() else ""
- if not remote_work_dir:
- raise RuntimeError("Remote workspace creation did not return a path.")
- return remote_work_dir
-
- def _upload_script(
- self,
- sftp: paramiko.SFTPClient,
- remote_work_dir: str,
- language: str,
- code: str,
- args_json: str,
- ) -> tuple[str, str]:
- if language == "python":
- script_name = "main.py"
- script_content = build_python_wrapper(code, args_json)
- elif language in {"javascript", "nodejs"}:
- script_name = "main.js"
- script_content = build_javascript_wrapper(code, args_json)
- else:
- raise RuntimeError(f"Unsupported language for SSH provider: {language}")
-
- remote_script_path = posixpath.join(remote_work_dir, script_name)
- with sftp.file(remote_script_path, "w") as remote_file:
- remote_file.write(script_content)
-
- command = self._build_execution_command(remote_work_dir, remote_script_path, language)
- return remote_script_path, command
-
- def _build_execution_command(self, remote_work_dir: str, remote_script_path: str, language: str) -> str:
- normalized_lang = self._normalize_language(language)
- if normalized_lang == "python":
- executable = self.python_bin
- elif normalized_lang == "nodejs":
- executable = self.node_bin
- else:
- raise RuntimeError(f"Unsupported language for SSH provider: {language}")
-
- return f"cd {shlex.quote(remote_work_dir)} && {shlex.quote(executable)} {shlex.quote(remote_script_path)}"
-
- def _run_remote_command(
- self,
- client: paramiko.SSHClient,
- command: str,
- timeout: int,
- ) -> tuple[str, str, int]:
- stdin, stdout_stream, stderr_stream = client.exec_command(command, timeout=timeout)
- stdin.close()
- channel = stdout_stream.channel
-
- stdout_chunks: list[bytes] = []
- stderr_chunks: list[bytes] = []
- deadline = time.time() + timeout
-
- while True:
- while channel.recv_ready():
- stdout_chunks.append(channel.recv(65536))
- while channel.recv_stderr_ready():
- stderr_chunks.append(channel.recv_stderr(65536))
-
- if channel.exit_status_ready():
- break
- if time.time() > deadline:
- channel.close()
- raise TimeoutError(f"Execution timed out after {timeout} seconds")
- time.sleep(0.1)
-
- while channel.recv_ready():
- stdout_chunks.append(channel.recv(65536))
- while channel.recv_stderr_ready():
- stderr_chunks.append(channel.recv_stderr(65536))
-
- exit_code = channel.recv_exit_status()
- stdout = b"".join(stdout_chunks).decode("utf-8", errors="replace")
- stderr = b"".join(stderr_chunks).decode("utf-8", errors="replace")
- return stdout, stderr, exit_code
-
- def _validate_output_size(self, stdout: str, stderr: str) -> None:
- output_size = len((stdout or "").encode("utf-8")) + len((stderr or "").encode("utf-8"))
- if output_size > self.max_output_bytes:
- raise RuntimeError(f"SSH execution output exceeded {self.max_output_bytes} bytes.")
-
- def _collect_artifacts(
- self,
- sftp: paramiko.SFTPClient,
- artifacts_dir: str,
- ) -> list[dict[str, Any]]:
- artifacts: list[dict[str, Any]] = []
- self._collect_artifacts_recursive(sftp, artifacts_dir, "", artifacts)
- return artifacts
-
- def _collect_artifacts_recursive(
- self,
- sftp: paramiko.SFTPClient,
- current_dir: str,
- relative_dir: str,
- artifacts: list[dict[str, Any]],
- ) -> None:
- try:
- entries = sftp.listdir_attr(current_dir)
- except FileNotFoundError:
- return
-
- for entry in sorted(entries, key=lambda item: item.filename):
- name = entry.filename
- remote_path = posixpath.join(current_dir, name)
- relative_path = posixpath.join(relative_dir, name) if relative_dir else name
- mode = entry.st_mode
- if mode is None:
- mode = sftp.lstat(remote_path).st_mode
- if mode is None:
- raise RuntimeError(f"Unable to determine artifact entry type: {relative_path}")
-
- if stat.S_ISLNK(mode):
- raise RuntimeError(f"Artifact symlinks are not allowed: {relative_path}")
- if stat.S_ISDIR(mode):
- self._collect_artifacts_recursive(sftp, remote_path, relative_path, artifacts)
- continue
- if not stat.S_ISREG(mode):
- raise RuntimeError(f"Unsupported artifact entry: {relative_path}")
-
- if len(artifacts) >= self.max_artifacts:
- raise RuntimeError(f"SSH execution produced more than {self.max_artifacts} artifacts.")
-
- size = int(entry.st_size or 0)
- if size > self.max_artifact_bytes:
- raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {relative_path}")
-
- ext = os.path.splitext(name)[1].lower()
- if ext not in ALLOWED_ARTIFACT_EXTENSIONS:
- raise RuntimeError(f"Unsupported artifact type: {relative_path}")
-
- with sftp.file(remote_path, "rb") as artifact_file:
- content = artifact_file.read()
-
- artifacts.append(
- {
- "name": relative_path,
- "content_b64": base64.b64encode(content).decode("ascii"),
- "mime_type": mimetypes.guess_type(name)[0] or "application/octet-stream",
- "size": size,
- }
- )
-
- @staticmethod
- def _normalize_language(language: str) -> str:
- lang_lower = (language or "python").lower()
- if lang_lower in {"python", "python3"}:
- return "python"
- if lang_lower in {"javascript", "nodejs"}:
- return "nodejs"
- return lang_lower
-
-
-def _get_paramiko_module():
- try:
- import paramiko
- except ImportError as exc:
- raise SandboxProviderConfigError("paramiko is required for the SSH sandbox provider. Install the project dependencies to enable it.") from exc
- return paramiko
diff --git a/agent/sandbox/providers/tenki.py b/agent/sandbox/providers/tenki.py
deleted file mode 100644
index d33b5c4c79..0000000000
--- a/agent/sandbox/providers/tenki.py
+++ /dev/null
@@ -1,521 +0,0 @@
-#
-# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-from __future__ import annotations
-
-import base64
-import json
-import logging
-import mimetypes
-import os
-import posixpath
-import stat
-import time
-import uuid
-from typing import Any, Dict, List, Optional
-
-from agent.sandbox.result_protocol import (
- build_javascript_wrapper,
- build_python_wrapper,
- extract_structured_result,
-)
-from .base import (
- ExecutionResult,
- SandboxInstance,
- SandboxProvider,
- SandboxProviderConfigError,
-)
-
-logger = logging.getLogger(__name__)
-
-ALLOWED_ARTIFACT_EXTENSIONS = {
- ".csv",
- ".html",
- ".jpeg",
- ".jpg",
- ".json",
- ".pdf",
- ".png",
- ".svg",
-}
-
-# Base directory inside the Tenki sandbox. The default image runs as the
-# unprivileged "tenki" user whose home is writable.
-SANDBOX_HOME = "/home/tenki"
-
-# Maximum directory depth walked when collecting artifacts, guarding against
-# deeply nested or symlink-looped trees produced by untrusted code.
-MAX_ARTIFACT_DEPTH = 16
-
-
-class TenkiProvider(SandboxProvider):
- """Execute code in a disposable Tenki microVM.
-
- Each create_instance() provisions a fresh sandbox, execute_code() runs a
- single script in it, and destroy_instance() terminates it. Only the stable
- create/exec/destroy path is used; no volumes or snapshots.
- """
-
- def __init__(self):
- self.api_key = ""
- self.base_url = ""
- self.image = ""
- self.allow_outbound = False
- self.timeout = 30
- self.max_lifetime = 3600
- self.cpu_cores = 0
- self.memory_mb = 0
- self.disk_size_gb = 0
- self.max_output_bytes = 1024 * 1024
- self.max_artifacts = 20
- self.max_artifact_bytes = 10 * 1024 * 1024
- self._initialized = False
- self._client = None
- self._instances: dict[str, dict[str, Any]] = {}
-
- def initialize(self, config: Dict[str, Any]) -> bool:
- self.api_key = str(config.get("api_key", "") or "").strip()
- self.base_url = str(config.get("base_url", "") or "").strip()
- self.image = str(config.get("image", "") or "").strip()
- self.allow_outbound = bool(config.get("allow_outbound", False))
- self.timeout = int(config.get("timeout", 30) or 30)
- self.max_lifetime = int(config.get("max_lifetime", 3600) or 3600)
- self.cpu_cores = int(config.get("cpu_cores", 0) or 0)
- self.memory_mb = int(config.get("memory_mb", 0) or 0)
- self.disk_size_gb = int(config.get("disk_size_gb", 0) or 0)
- self.max_output_bytes = int(config.get("max_output_bytes", 1024 * 1024) or 1024 * 1024)
- self.max_artifacts = int(config.get("max_artifacts", 20) or 20)
- self.max_artifact_bytes = int(config.get("max_artifact_bytes", 10 * 1024 * 1024) or 10 * 1024 * 1024)
-
- is_valid, error_message = self.validate_config(
- {
- "api_key": self.api_key,
- "timeout": self.timeout,
- "max_lifetime": self.max_lifetime,
- "max_output_bytes": self.max_output_bytes,
- "max_artifacts": self.max_artifacts,
- "max_artifact_bytes": self.max_artifact_bytes,
- }
- )
- if not is_valid:
- raise SandboxProviderConfigError(error_message or "Invalid Tenki provider configuration.")
-
- self._client = self._create_client()
- self._assert_connectivity()
-
- self._initialized = True
- logger.info("Tenki provider initialized")
- return True
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- language = self._normalize_language(template)
- errors = self._tenki_errors()
-
- create_kwargs: dict[str, Any] = {
- "allow_outbound": self.allow_outbound,
- "max_duration": self.max_lifetime,
- "metadata": {"source": "ragflow"},
- }
- if self.image:
- create_kwargs["image"] = self.image
- if self.cpu_cores > 0:
- create_kwargs["cpu_cores"] = self.cpu_cores
- if self.memory_mb > 0:
- create_kwargs["memory_mb"] = self.memory_mb
- if self.disk_size_gb > 0:
- create_kwargs["disk_size_gb"] = self.disk_size_gb
-
- try:
- sandbox = self._client.create(**create_kwargs)
- except errors.QuotaExceededError as exc:
- raise RuntimeError(f"Tenki quota exceeded: {exc}") from exc
- except errors.RateLimitedError as exc:
- raise RuntimeError(f"Tenki rate limited, please retry: {exc}") from exc
- except errors.UnauthorizedError as exc:
- raise SandboxProviderConfigError("Tenki authentication failed: check the API key.") from exc
- except Exception as exc:
- # Satisfy the base contract: any other SDK failure becomes RuntimeError.
- raise RuntimeError(f"Failed to create Tenki sandbox: {exc}") from exc
-
- remote_work_dir = posixpath.join(SANDBOX_HOME, f"ragflow-codeexec-{uuid.uuid4().hex}")
- try:
- result = sandbox.exec(
- "mkdir",
- "-p",
- posixpath.join(remote_work_dir, "artifacts"),
- timeout=min(self.timeout, 10),
- )
- if result.exit_code != 0:
- raise RuntimeError(f"Failed to create sandbox workspace: {result.stderr_text or 'unknown error'}")
- except Exception:
- self._safe_terminate(sandbox)
- raise
-
- instance_id = str(uuid.uuid4())
- self._instances[instance_id] = {
- "sandbox": sandbox,
- "remote_work_dir": remote_work_dir,
- "language": language,
- }
- logger.info("Tenki sandbox created (instance=%s, session=%s)", instance_id, sandbox.id)
-
- return SandboxInstance(
- instance_id=instance_id,
- provider="tenki",
- status="running",
- metadata={"language": language, "remote_work_dir": remote_work_dir, "sandbox_id": sandbox.id},
- )
-
- def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10,
- arguments: Optional[Dict[str, Any]] = None,
- ) -> ExecutionResult:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
- if instance_id not in self._instances:
- raise RuntimeError(f"Unknown Tenki sandbox instance: {instance_id}")
-
- normalized_lang = self._normalize_language(language)
- instance = self._instances[instance_id]
- sandbox = instance["sandbox"]
- remote_work_dir: str = instance["remote_work_dir"]
- errors = self._tenki_errors()
-
- args_json = json.dumps(arguments or {}, ensure_ascii=False)
- script_path, argv = self._prepare_script(sandbox, remote_work_dir, normalized_lang, code, args_json)
-
- requested_timeout = self.timeout if timeout is None else int(timeout)
- if requested_timeout <= 0:
- raise RuntimeError(f"Execution timeout must be greater than 0 seconds, got {requested_timeout}.")
- exec_timeout = min(requested_timeout, self.timeout)
-
- start_time = time.time()
- try:
- result = sandbox.exec(*argv, cwd=remote_work_dir, timeout=exec_timeout)
- except (errors.CommandTimeoutError, errors.PrimitiveTimeoutError) as exc:
- logger.warning("Tenki execution timed out (instance=%s, timeout=%ss)", instance_id, exec_timeout)
- raise TimeoutError(f"Execution timed out after {exec_timeout} seconds") from exc
- except (errors.SessionTerminatedError, errors.SessionNotFoundError) as exc:
- # The sandbox was reclaimed (e.g. max_lifetime) or lost mid-run;
- # surface it as RuntimeError per the base contract, not an SDK type.
- raise RuntimeError(f"Tenki sandbox is no longer available: {exc}") from exc
- except Exception as exc:
- raise RuntimeError(f"Tenki execution failed: {exc}") from exc
- execution_time = time.time() - start_time
-
- stdout = result.stdout_text
- stderr = result.stderr_text
- exit_code = int(result.exit_code)
-
- self._validate_output_size(stdout, stderr)
- stdout, structured_result = extract_structured_result(stdout)
-
- return ExecutionResult(
- stdout=stdout,
- stderr=stderr,
- exit_code=exit_code,
- execution_time=execution_time,
- metadata={
- "instance_id": instance_id,
- "language": normalized_lang,
- "script_path": script_path,
- "remote_work_dir": remote_work_dir,
- "status": "ok" if exit_code == 0 else "error",
- "timeout": exec_timeout,
- "artifacts": self._collect_artifacts(sandbox, posixpath.join(remote_work_dir, "artifacts")),
- "result_present": structured_result.get("present", False),
- "result_value": structured_result.get("value"),
- "result_type": structured_result.get("type"),
- },
- )
-
- def destroy_instance(self, instance_id: str) -> bool:
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
- if instance_id not in self._instances:
- return True
-
- instance = self._instances.pop(instance_id)
- self._safe_terminate(instance["sandbox"])
- logger.info("Tenki sandbox destroyed (instance=%s)", instance_id)
- return True
-
- def health_check(self) -> bool:
- try:
- self._assert_connectivity()
- return True
- except Exception:
- return False
-
- def get_supported_languages(self) -> List[str]:
- return ["python", "javascript"]
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "api_key": {
- "type": "string",
- "required": True,
- "label": "API Key",
- "secret": True,
- "placeholder": "tk_...",
- "description": "Tenki API key. Create one at https://app.tenki.cloud under API Keys.",
- },
- "base_url": {
- "type": "string",
- "required": False,
- "label": "API Endpoint",
- "placeholder": "https://api.tenki.cloud",
- "description": "Override the Tenki API endpoint. Leave empty for the default.",
- },
- "image": {
- "type": "string",
- "required": False,
- "label": "Sandbox Image",
- "description": "Base image for sandboxes. Empty uses the Tenki default image (includes python3 and node).",
- },
- "allow_outbound": {
- "type": "boolean",
- "required": False,
- "label": "Allow Outbound Network",
- "default": False,
- "description": "Security-relevant. Disabled by default so sandboxed code has no network access. Enable it to let code make outbound connections (e.g. to install packages).",
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "label": "Timeout (seconds)",
- "default": 30,
- "min": 1,
- "max": 600,
- "description": "Maximum execution time for a single run.",
- },
- "max_lifetime": {
- "type": "integer",
- "required": False,
- "label": "Max Sandbox Lifetime (seconds)",
- "default": 3600,
- "min": 60,
- "max": 86400,
- "description": "Tenki reclaims a sandbox after this, guarding against leaks if the run is interrupted.",
- },
- "cpu_cores": {
- "type": "integer",
- "required": False,
- "label": "vCPU Cores",
- "default": 0,
- "min": 0,
- "max": 16,
- "description": "vCPU per sandbox. 0 uses the Tenki default.",
- },
- "memory_mb": {
- "type": "integer",
- "required": False,
- "label": "Memory (MB)",
- "default": 0,
- "min": 0,
- "max": 65536,
- "description": "Memory per sandbox in MB. 0 uses the Tenki default.",
- },
- "disk_size_gb": {
- "type": "integer",
- "required": False,
- "label": "Disk Size (GB)",
- "default": 0,
- "min": 0,
- "max": 100,
- "description": "Disk size per sandbox in GB. 0 uses the Tenki default.",
- },
- "max_output_bytes": {
- "type": "integer",
- "required": False,
- "label": "Max Output Bytes",
- "default": 1048576,
- "min": 1024,
- "max": 10485760,
- "description": "Maximum combined stdout and stderr size.",
- },
- "max_artifacts": {
- "type": "integer",
- "required": False,
- "label": "Max Artifacts",
- "default": 20,
- "min": 0,
- "max": 100,
- "description": "Maximum number of files collected from the sandbox artifacts directory.",
- },
- "max_artifact_bytes": {
- "type": "integer",
- "required": False,
- "label": "Max Artifact Bytes",
- "default": 10485760,
- "min": 1024,
- "max": 104857600,
- "description": "Maximum size of a single artifact file in bytes.",
- },
- }
-
- def validate_config(self, config: Dict[str, Any]) -> tuple[bool, Optional[str]]:
- api_key = str(config.get("api_key", "") or "").strip()
-
- if not api_key:
- return False, "Tenki API key is required"
-
- for key in ("timeout", "max_lifetime", "max_output_bytes", "max_artifacts", "max_artifact_bytes"):
- try:
- value = int(config.get(key, 0) or 0)
- except (TypeError, ValueError):
- return False, f"{key} must be an integer"
- if key == "max_artifacts":
- if value < 0:
- return False, "max_artifacts must be greater than or equal to 0"
- elif value <= 0:
- return False, f"{key} must be greater than 0"
-
- return True, None
-
- # -- internal helpers -------------------------------------------------
-
- def _create_client(self):
- tenki = _get_tenki_module()
- # Bound control-plane requests (who_am_i, create) so a slow or
- # unreachable API cannot block initialize()/create_instance() forever.
- kwargs: dict[str, Any] = {"auth_token": self.api_key, "timeout": float(self.timeout)}
- if self.base_url:
- kwargs["base_url"] = self.base_url
- return tenki.Client(**kwargs)
-
- def _assert_connectivity(self) -> None:
- client = self._client or self._create_client()
- errors = self._tenki_errors()
- try:
- client.who_am_i()
- except errors.UnauthorizedError as exc:
- raise SandboxProviderConfigError("Tenki authentication failed: check the API key.") from exc
- except Exception as exc:
- raise SandboxProviderConfigError(f"Failed to reach Tenki API: {exc}") from exc
-
- def _prepare_script(self, sandbox, remote_work_dir: str, language: str, code: str, args_json: str) -> tuple[str, list[str]]:
- if language == "python":
- script_name = "main.py"
- script_content = build_python_wrapper(code, args_json)
- executable = "python3"
- elif language in {"javascript", "nodejs"}:
- script_name = "main.js"
- script_content = build_javascript_wrapper(code, args_json)
- executable = "node"
- else:
- raise RuntimeError(f"Unsupported language for Tenki provider: {language}")
-
- script_path = posixpath.join(remote_work_dir, script_name)
- sandbox.fs.write_text(script_path, script_content)
- return script_path, [executable, script_path]
-
- def _validate_output_size(self, stdout: str, stderr: str) -> None:
- output_size = len((stdout or "").encode("utf-8")) + len((stderr or "").encode("utf-8"))
- if output_size > self.max_output_bytes:
- raise RuntimeError(f"Tenki execution output exceeded {self.max_output_bytes} bytes.")
-
- def _collect_artifacts(self, sandbox, artifacts_dir: str) -> list[dict[str, Any]]:
- artifacts: list[dict[str, Any]] = []
- self._collect_artifacts_recursive(sandbox, artifacts_dir, "", artifacts, depth=0)
- return artifacts
-
- def _collect_artifacts_recursive(self, sandbox, current_dir: str, relative_dir: str, artifacts: list[dict[str, Any]], depth: int) -> None:
- if depth > MAX_ARTIFACT_DEPTH:
- raise RuntimeError(f"Artifact directory nesting exceeds {MAX_ARTIFACT_DEPTH} levels: {relative_dir}")
-
- errors = self._tenki_errors()
- try:
- entries = sandbox.fs.list(current_dir)
- except errors.FileNotFoundError:
- return
- except FileNotFoundError:
- return
-
- # fs.list returns each entry's basename in `.path`, not an absolute
- # path, so join it onto the directory being listed.
- for entry in sorted(entries, key=lambda item: item.path):
- name = posixpath.basename(entry.path)
- remote_path = posixpath.join(current_dir, name)
- relative_path = posixpath.join(relative_dir, name) if relative_dir else name
-
- # Reject symlinks. `is_symlink` is not populated by every SDK
- # release, so also inspect the stat mode bits as the reliable check.
- if getattr(entry, "is_symlink", False) or stat.S_ISLNK(entry.mode or 0):
- raise RuntimeError(f"Artifact symlinks are not allowed: {relative_path}")
- if entry.is_dir:
- self._collect_artifacts_recursive(sandbox, remote_path, relative_path, artifacts, depth + 1)
- continue
-
- if len(artifacts) >= self.max_artifacts:
- raise RuntimeError(f"Tenki execution produced more than {self.max_artifacts} artifacts.")
-
- size = int(entry.size or 0)
- if size > self.max_artifact_bytes:
- raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {relative_path}")
-
- ext = os.path.splitext(name)[1].lower()
- if ext not in ALLOWED_ARTIFACT_EXTENSIONS:
- raise RuntimeError(f"Unsupported artifact type: {relative_path}")
-
- content = sandbox.fs.read_bytes(remote_path)
- artifacts.append(
- {
- "name": relative_path,
- "content_b64": base64.b64encode(content).decode("ascii"),
- "mime_type": mimetypes.guess_type(name)[0] or "application/octet-stream",
- "size": size,
- }
- )
-
- def _safe_terminate(self, sandbox) -> None:
- # Best-effort: max_lifetime reclaims the sandbox if this fails.
- try:
- sandbox.terminate()
- except Exception as exc:
- logger.warning("Failed to terminate Tenki sandbox, relying on max_lifetime: %s", exc)
-
- def _tenki_errors(self):
- tenki = _get_tenki_module()
- return tenki.errors
-
- @staticmethod
- def _normalize_language(language: str) -> str:
- lang_lower = (language or "python").lower()
- if lang_lower in {"python", "python3"}:
- return "python"
- if lang_lower in {"javascript", "nodejs"}:
- return "nodejs"
- return lang_lower
-
-
-def _get_tenki_module():
- try:
- import tenki_sandbox
- except ImportError as exc:
- # tenki is an optional dependency: it requires protobuf>=6.31,
- # which conflicts with RAGFlow's pinned gRPC stack, so it is not a core
- # dependency. Install it into the runtime to enable this provider.
- raise SandboxProviderConfigError("tenki is required for the Tenki sandbox provider. Install it with `pip install tenki` (or `uv pip install tenki`).") from exc
- return tenki_sandbox
diff --git a/agent/sandbox/providers/ucloud_agent_sandbox.py b/agent/sandbox/providers/ucloud_agent_sandbox.py
deleted file mode 100644
index 774c548764..0000000000
--- a/agent/sandbox/providers/ucloud_agent_sandbox.py
+++ /dev/null
@@ -1,471 +0,0 @@
-#
-# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""UCloud Agent Sandbox provider for remote code execution."""
-
-from __future__ import annotations
-
-import base64
-import json
-import logging
-import mimetypes
-import os
-import posixpath
-import shlex
-import time
-import uuid
-from typing import Any
-
-from agent.sandbox.result_protocol import build_javascript_wrapper, build_python_wrapper, extract_structured_result
-
-from .base import ExecutionResult, SandboxInstance, SandboxProvider, SandboxProviderConfigError
-
-logger = logging.getLogger(__name__)
-
-ALLOWED_ARTIFACT_EXTENSIONS = {".csv", ".html", ".jpeg", ".jpg", ".json", ".pdf", ".png", ".svg"}
-DEFAULT_REGION = "cn-wlcb"
-DOMAIN_SUFFIX = "sandbox.ucloudai.com"
-SANDBOX_HOME = "/home/user"
-MAX_ARTIFACT_DEPTH = 16
-
-
-class UCloudAgentSandboxProvider(SandboxProvider):
- """Execute Python and JavaScript in disposable UCloud Agent Sandboxes."""
-
- def __init__(self):
- """Initialize the provider with safe defaults and no active instances."""
- self.api_key = ""
- self.region = DEFAULT_REGION
- self.domain = ""
- self.api_url = ""
- self.template = "base"
- self.allow_internet_access = False
- self.insecure_http = False
- self.timeout = 30
- self.sandbox_timeout = 300
- self.max_output_bytes = 1024 * 1024
- self.max_artifacts = 20
- self.max_artifact_bytes = 10 * 1024 * 1024
- self._initialized = False
- self._instances: dict[str, dict[str, Any]] = {}
-
- def initialize(self, config: dict[str, Any]) -> bool:
- """Validate and apply provider configuration.
-
- Args:
- config: Provider credentials, endpoint options, and execution limits.
-
- Returns:
- True when the provider is ready to create sandboxes.
-
- Raises:
- SandboxProviderConfigError: If the configuration or SDK is invalid.
- """
- self.api_key = str(config.get("api_key", "") or "").strip()
- self.region = str(config.get("region", DEFAULT_REGION) or DEFAULT_REGION).strip()
- self.domain = str(config.get("domain", "") or "").strip()
- self.api_url = str(config.get("api_url", "") or "").strip()
- self.template = str(config.get("template", "base") or "base").strip()
- self.allow_internet_access = bool(config.get("allow_internet_access", False))
- self.insecure_http = bool(config.get("insecure_http", False))
- self.timeout = int(config.get("timeout", 30) or 30)
- self.sandbox_timeout = int(config.get("sandbox_timeout", 300) or 300)
- self.max_output_bytes = int(config.get("max_output_bytes", 1024 * 1024) or 1024 * 1024)
- self.max_artifacts = int(config.get("max_artifacts", 20) or 20)
- self.max_artifact_bytes = int(config.get("max_artifact_bytes", 10 * 1024 * 1024) or 10 * 1024 * 1024)
-
- is_valid, error_message = self.validate_config(config | {"api_key": self.api_key})
- if not is_valid:
- raise SandboxProviderConfigError(error_message or "Invalid UCloud Agent Sandbox configuration.")
-
- _get_ucloud_sandbox_module()
- self._initialized = True
- logger.info("UCloud Agent Sandbox provider initialized")
- return True
-
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """Create a disposable sandbox and its isolated execution workspace.
-
- Args:
- template: Requested language identifier used to validate the runtime.
-
- Returns:
- A RAGFlow sandbox instance handle.
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
-
- language = self._normalize_language(template)
- if language not in {"python", "nodejs"}:
- raise RuntimeError(f"Unsupported language for UCloud Agent Sandbox provider: {template}")
-
- sdk = _get_ucloud_sandbox_module()
- try:
- sandbox = sdk.Sandbox.create(
- template=self.template,
- timeout=self.sandbox_timeout,
- metadata={"source": "ragflow"},
- secure=True,
- allow_internet_access=self.allow_internet_access,
- **self._api_options(),
- )
- except sdk.AuthenticationException as exc:
- raise SandboxProviderConfigError("UCloud Agent Sandbox authentication failed: check the API key.") from exc
- except sdk.RateLimitException as exc:
- raise RuntimeError(f"UCloud Agent Sandbox rate limited, please retry: {exc}") from exc
- except sdk.TimeoutException as exc:
- raise TimeoutError("Timed out while creating a UCloud Agent Sandbox.") from exc
- except Exception as exc:
- raise RuntimeError(f"Failed to create UCloud Agent Sandbox: {exc}") from exc
-
- remote_work_dir = posixpath.join(SANDBOX_HOME, f"ragflow-codeexec-{uuid.uuid4().hex}")
- try:
- sandbox.commands.run(
- f"mkdir -p {shlex.quote(posixpath.join(remote_work_dir, 'artifacts'))}",
- timeout=min(self.timeout, 10),
- request_timeout=self.timeout,
- )
- except Exception:
- self._safe_kill(sandbox)
- raise
-
- instance_id = str(uuid.uuid4())
- self._instances[instance_id] = {"sandbox": sandbox, "remote_work_dir": remote_work_dir, "language": language}
- return SandboxInstance(
- instance_id=instance_id,
- provider="ucloud_agent_sandbox",
- status="running",
- metadata={
- "language": language,
- "remote_work_dir": remote_work_dir,
- "sandbox_id": sandbox.sandbox_id,
- "template": self.template,
- },
- )
-
- def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10,
- arguments: dict[str, Any] | None = None,
- ) -> ExecutionResult:
- """Execute wrapped code in an existing UCloud sandbox.
-
- Args:
- instance_id: RAGFlow instance identifier returned by create_instance.
- code: User-provided source code defining a main function.
- language: Python or JavaScript language identifier.
- timeout: Maximum execution duration in seconds.
- arguments: Values passed to the user-defined main function.
-
- Returns:
- Captured output, structured result metadata, and allowed artifacts.
- """
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
- if instance_id not in self._instances:
- raise RuntimeError(f"Unknown UCloud Agent Sandbox instance: {instance_id}")
-
- normalized_lang = self._normalize_language(language)
- instance = self._instances[instance_id]
- sandbox = instance["sandbox"]
- remote_work_dir: str = instance["remote_work_dir"]
- script_path, executable = self._prepare_script(sandbox, remote_work_dir, normalized_lang, code, arguments or {})
-
- requested_timeout = self.timeout if timeout is None else int(timeout)
- if requested_timeout <= 0:
- raise RuntimeError(f"Execution timeout must be greater than 0 seconds, got {requested_timeout}.")
- exec_timeout = min(requested_timeout, self.timeout)
- sdk = _get_ucloud_sandbox_module()
-
- start_time = time.time()
- try:
- sandbox.set_timeout(max(self.sandbox_timeout, exec_timeout + 30), request_timeout=self.timeout)
- result = sandbox.commands.run(
- f"{executable} {shlex.quote(script_path)}",
- cwd=remote_work_dir,
- timeout=exec_timeout,
- request_timeout=max(self.timeout, exec_timeout),
- )
- except sdk.CommandExitException as exc:
- result = exc
- except sdk.TimeoutException as exc:
- raise TimeoutError(f"Execution timed out after {exec_timeout} seconds") from exc
- except Exception as exc:
- raise RuntimeError(f"UCloud Agent Sandbox execution failed: {exc}") from exc
- execution_time = time.time() - start_time
-
- stdout = result.stdout or ""
- stderr = result.stderr or ""
- exit_code = int(result.exit_code)
- self._validate_output_size(stdout, stderr)
- stdout, structured_result = extract_structured_result(stdout)
-
- return ExecutionResult(
- stdout=stdout,
- stderr=stderr,
- exit_code=exit_code,
- execution_time=execution_time,
- metadata={
- "instance_id": instance_id,
- "sandbox_id": sandbox.sandbox_id,
- "language": normalized_lang,
- "script_path": script_path,
- "remote_work_dir": remote_work_dir,
- "status": "ok" if exit_code == 0 else "error",
- "timeout": exec_timeout,
- "artifacts": self._collect_artifacts(sandbox, posixpath.join(remote_work_dir, "artifacts")),
- "result_present": structured_result.get("present", False),
- "result_value": structured_result.get("value"),
- "result_type": structured_result.get("type"),
- },
- )
-
- def destroy_instance(self, instance_id: str) -> bool:
- """Destroy a sandbox instance if it is still tracked by the provider."""
- if not self._initialized:
- raise RuntimeError("Provider not initialized. Call initialize() first.")
- instance = self._instances.pop(instance_id, None)
- if instance is None:
- return True
- self._safe_kill(instance["sandbox"])
- return True
-
- def health_check(self) -> bool:
- """Return whether the provider is initialized with an API key."""
- return self._initialized and bool(self.api_key)
-
- def get_supported_languages(self) -> list[str]:
- """Return the language identifiers accepted by this provider."""
- return ["python", "javascript"]
-
- @staticmethod
- def get_config_schema() -> dict[str, dict]:
- """Return the Admin UI configuration schema for this provider."""
- return {
- "api_key": {
- "type": "string",
- "required": True,
- "label": "API Key",
- "secret": True,
- "description": "UCloud Agent Sandbox API key.",
- },
- "region": {
- "type": "string",
- "required": False,
- "label": "Region",
- "default": DEFAULT_REGION,
- "description": "UCloud Agent Sandbox region, for example cn-wlcb or us-ca.",
- },
- "domain": {
- "type": "string",
- "required": False,
- "label": "Domain",
- "description": "Override the sandbox domain. Leave empty to derive it from Region.",
- },
- "api_url": {
- "type": "string",
- "required": False,
- "label": "API URL",
- "description": "Override the UCloud Agent Sandbox control-plane API URL.",
- },
- "template": {
- "type": "string",
- "required": False,
- "label": "Template",
- "default": "base",
- "description": "Sandbox template. The base template includes Python and Node.js.",
- },
- "allow_internet_access": {
- "type": "boolean",
- "required": False,
- "label": "Allow Internet Access",
- "default": False,
- "description": "Allow sandboxed code to access the internet. Disabled by default.",
- },
- "insecure_http": {
- "type": "boolean",
- "required": False,
- "label": "Use Insecure HTTP",
- "default": False,
- "description": "Use HTTP instead of HTTPS. Enable only for trusted private deployments.",
- },
- "timeout": {
- "type": "integer",
- "required": False,
- "label": "Execution Timeout (seconds)",
- "default": 30,
- "min": 1,
- "max": 600,
- },
- "sandbox_timeout": {
- "type": "integer",
- "required": False,
- "label": "Sandbox Lifetime (seconds)",
- "default": 300,
- "min": 60,
- "max": 86400,
- },
- "max_output_bytes": {
- "type": "integer",
- "required": False,
- "label": "Max Output Bytes",
- "default": 1048576,
- "min": 1024,
- "max": 10485760,
- },
- "max_artifacts": {
- "type": "integer",
- "required": False,
- "label": "Max Artifacts",
- "default": 20,
- "min": 0,
- "max": 100,
- },
- "max_artifact_bytes": {
- "type": "integer",
- "required": False,
- "label": "Max Artifact Bytes",
- "default": 10485760,
- "min": 1024,
- "max": 104857600,
- },
- }
-
- def validate_config(self, config: dict[str, Any]) -> tuple[bool, str | None]:
- """Validate required credentials and numeric execution limits."""
- if not str(config.get("api_key", "") or "").strip():
- return False, "UCloud Agent Sandbox API key is required"
- if not str(config.get("template", "base") or "").strip():
- return False, "template is required"
- for key in ("timeout", "sandbox_timeout", "max_output_bytes", "max_artifact_bytes"):
- try:
- value = int(config.get(key, self.get_config_schema()[key]["default"]) or 0)
- except (TypeError, ValueError):
- return False, f"{key} must be an integer"
- if value <= 0:
- return False, f"{key} must be greater than 0"
- try:
- max_artifacts = int(config.get("max_artifacts", 20) or 0)
- except (TypeError, ValueError):
- return False, "max_artifacts must be an integer"
- if max_artifacts < 0:
- return False, "max_artifacts must be greater than or equal to 0"
- return True, None
-
- def _api_options(self) -> dict[str, Any]:
- """Build keyword arguments shared by UCloud SDK API calls."""
- options: dict[str, Any] = {
- "api_key": self.api_key,
- "domain": self.domain or f"{self.region}.{DOMAIN_SUFFIX}",
- "insecure_http": self.insecure_http,
- "request_timeout": float(self.timeout),
- "integration": "ragflow",
- }
- if self.api_url:
- options["api_url"] = self.api_url
- return options
-
- def _prepare_script(self, sandbox, remote_work_dir: str, language: str, code: str, arguments: dict[str, Any]) -> tuple[str, str]:
- """Wrap user code, upload it, and return its path and executable."""
- args_json = json.dumps(arguments, ensure_ascii=False)
- if language == "python":
- script_name = "main.py"
- script_content = build_python_wrapper(code, args_json)
- executable = "python3"
- elif language == "nodejs":
- script_name = "main.js"
- script_content = build_javascript_wrapper(code, args_json)
- executable = "node"
- else:
- raise RuntimeError(f"Unsupported language for UCloud Agent Sandbox provider: {language}")
- script_path = posixpath.join(remote_work_dir, script_name)
- sandbox.files.write(script_path, script_content, request_timeout=self.timeout)
- return script_path, executable
-
- def _validate_output_size(self, stdout: str, stderr: str) -> None:
- """Reject combined standard output that exceeds the configured limit."""
- output_size = len(stdout.encode("utf-8")) + len(stderr.encode("utf-8"))
- if output_size > self.max_output_bytes:
- raise RuntimeError(f"UCloud Agent Sandbox execution output exceeded {self.max_output_bytes} bytes.")
-
- def _collect_artifacts(self, sandbox, artifacts_dir: str) -> list[dict[str, Any]]:
- """Collect allowed files from the execution artifact directory."""
- artifacts: list[dict[str, Any]] = []
- self._collect_artifacts_recursive(sandbox, artifacts_dir, "", artifacts, depth=0)
- return artifacts
-
- def _collect_artifacts_recursive(self, sandbox, current_dir: str, relative_dir: str, artifacts: list[dict[str, Any]], depth: int) -> None:
- """Traverse artifact directories while enforcing type, size, and depth limits."""
- if depth > MAX_ARTIFACT_DEPTH:
- raise RuntimeError(f"Artifact directory nesting exceeds {MAX_ARTIFACT_DEPTH} levels: {relative_dir}")
- sdk = _get_ucloud_sandbox_module()
- try:
- entries = sandbox.files.list(current_dir, depth=1, request_timeout=self.timeout)
- except sdk.FileNotFoundException:
- return
- for entry in sorted(entries, key=lambda item: item.path):
- name = posixpath.basename(entry.path)
- relative_path = posixpath.join(relative_dir, name) if relative_dir else name
- if entry.symlink_target is not None:
- raise RuntimeError(f"Artifact symlinks are not allowed: {relative_path}")
- if entry.type == sdk.FileType.DIR:
- self._collect_artifacts_recursive(sandbox, entry.path, relative_path, artifacts, depth + 1)
- continue
- if len(artifacts) >= self.max_artifacts:
- raise RuntimeError(f"UCloud Agent Sandbox execution produced more than {self.max_artifacts} artifacts.")
- if entry.size > self.max_artifact_bytes:
- raise RuntimeError(f"Artifact exceeds {self.max_artifact_bytes} bytes: {relative_path}")
- extension = os.path.splitext(name)[1].lower()
- if extension not in ALLOWED_ARTIFACT_EXTENSIONS:
- raise RuntimeError(f"Unsupported artifact type: {relative_path}")
- content = bytes(sandbox.files.read(entry.path, format="bytes", request_timeout=self.timeout))
- artifacts.append(
- {
- "name": relative_path,
- "content_b64": base64.b64encode(content).decode("ascii"),
- "mime_type": mimetypes.guess_type(name)[0] or "application/octet-stream",
- "size": entry.size,
- }
- )
-
- def _safe_kill(self, sandbox) -> None:
- """Best-effort terminate a remote sandbox during cleanup."""
- try:
- sandbox.kill(request_timeout=self.timeout)
- except Exception as exc: # noqa: BLE001 - cleanup is deliberately best-effort
- logger.warning("Failed to kill UCloud Agent Sandbox %s: %s", sandbox.sandbox_id, exc)
-
- @staticmethod
- def _normalize_language(language: str) -> str:
- """Normalize supported language aliases to provider runtime names."""
- value = (language or "python").lower()
- if value in {"python", "python3"}:
- return "python"
- if value in {"javascript", "js", "node", "nodejs"}:
- return "nodejs"
- return value
-
-
-def _get_ucloud_sandbox_module():
- """Import and return the UCloud SDK with a provider-specific error."""
- try:
- import ucloud_sandbox
- except ImportError as exc:
- raise SandboxProviderConfigError("ucloud-sandbox is required for the UCloud Agent Sandbox provider.") from exc
- return ucloud_sandbox
diff --git a/agent/sandbox/pyproject.toml b/agent/sandbox/pyproject.toml
deleted file mode 100644
index 7fefa775ce..0000000000
--- a/agent/sandbox/pyproject.toml
+++ /dev/null
@@ -1,28 +0,0 @@
-[project]
-name = "gvisor-sandbox"
-version = "0.1.0"
-description = "Add your description here"
-readme = "README.md"
-requires-python = ">=3.13,<3.14"
-dependencies = [
- "fastapi>=0.115.12",
- "httpx>=0.28.1",
- "pydantic>=2.11.4",
- "requests>=2.32.4",
- "slowapi>=0.1.9",
- "uvicorn>=0.34.2",
-]
-
-[[tool.uv.index]]
-url = "https://pypi.tuna.tsinghua.edu.cn/simple"
-
-[dependency-groups]
-dev = [
- "basedpyright>=1.29.1",
-]
-
-[tool.ruff]
-line-length = 200
-
-[tool.ruff.lint]
-extend-select = ["C4", "SIM", "TCH"]
diff --git a/agent/sandbox/result_protocol.py b/agent/sandbox/result_protocol.py
deleted file mode 100644
index 385f6fb615..0000000000
--- a/agent/sandbox/result_protocol.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#
-# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-import base64
-import json
-from typing import Any
-
-
-RESULT_MARKER_PREFIX = "__RAGFLOW_RESULT__:"
-
-
-def build_python_wrapper(code: str, args_json: str) -> str:
- return f'''{code}
-
-if __name__ == "__main__":
- import base64
- import json
-
- result = main(**{args_json})
- payload = json.dumps({{"present": True, "value": result, "type": "json"}}, ensure_ascii=False, separators=(",", ":"))
- print("{RESULT_MARKER_PREFIX}" + base64.b64encode(payload.encode("utf-8")).decode("ascii"))
-'''
-
-
-def build_javascript_wrapper(code: str, args_json: str) -> str:
- return f"""{code}
-
-const __ragflowArgs = {args_json};
-
-(async () => {{
- const __ragflowMain = typeof main !== 'undefined' ? main : module.exports && module.exports.main;
- if (typeof __ragflowMain !== 'function') {{
- throw new Error('main() must be defined or exported.');
- }}
- const output = await Promise.resolve(__ragflowMain(__ragflowArgs));
- if (typeof output === 'undefined') {{
- throw new Error('main() must return a value. Use null for an empty result.');
- }}
- const payload = JSON.stringify({{ present: true, value: output, type: 'json' }});
- if (typeof payload === 'undefined') {{
- throw new Error('main() returned a non-JSON-serializable value.');
- }}
- console.log('{RESULT_MARKER_PREFIX}' + Buffer.from(payload, 'utf8').toString('base64'));
-}})();
-"""
-
-
-def extract_structured_result(stdout: str) -> tuple[str, dict[str, Any]]:
- if not stdout:
- return "", {}
-
- cleaned_lines: list[str] = []
- structured_result: dict[str, Any] = {}
-
- for line in str(stdout).splitlines():
- if line.startswith(RESULT_MARKER_PREFIX):
- payload_b64 = line[len(RESULT_MARKER_PREFIX) :].strip()
- if not payload_b64:
- cleaned_lines.append(line)
- continue
- try:
- payload = base64.b64decode(payload_b64, validate=True).decode("utf-8")
- structured_result = json.loads(payload)
- except Exception:
- cleaned_lines.append(line)
- continue
- cleaned_lines.append(line)
-
- cleaned_stdout = "\n".join(cleaned_lines)
- if stdout.endswith("\n") and cleaned_stdout and not cleaned_stdout.endswith("\n"):
- cleaned_stdout += "\n"
- return cleaned_stdout, structured_result
diff --git a/agent/sandbox/sandbox_base_image/nodejs/Dockerfile b/agent/sandbox/sandbox_base_image/nodejs/Dockerfile
deleted file mode 100644
index 21432b818a..0000000000
--- a/agent/sandbox/sandbox_base_image/nodejs/Dockerfile
+++ /dev/null
@@ -1,23 +0,0 @@
-FROM node:24.13-bookworm-slim
-
-ARG NEED_MIRROR=1
-
-RUN if [ "$NEED_MIRROR" = 1 ]; then \
- npm config set registry https://registry.npmmirror.com; \
- else \
- npm config set registry https://registry.npmjs.org; \
- fi
-
-# RUN grep -rl 'deb.debian.org' /etc/apt/ | xargs sed -i 's|http[s]*://deb.debian.org|https://mirrors.ustc.edu.cn|g' && \
-# apt-get update && \
-# apt-get install -y curl gcc make
-
-
-WORKDIR /app
-
-COPY package.json package-lock.json .
-
-RUN npm install
-
-CMD ["sleep", "infinity"]
-
diff --git a/agent/sandbox/sandbox_base_image/nodejs/package-lock.json b/agent/sandbox/sandbox_base_image/nodejs/package-lock.json
deleted file mode 100644
index ebca636262..0000000000
--- a/agent/sandbox/sandbox_base_image/nodejs/package-lock.json
+++ /dev/null
@@ -1,347 +0,0 @@
-{
- "name": "nodejs",
- "version": "1.0.0",
- "lockfileVersion": 3,
- "requires": true,
- "packages": {
- "": {
- "name": "nodejs",
- "version": "1.0.0",
- "license": "ISC",
- "dependencies": {
- "axios": "^1.15.2"
- }
- },
- "node_modules/agent-base": {
- "version": "6.0.2",
- "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
- "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
- "license": "MIT",
- "dependencies": {
- "debug": "4"
- },
- "engines": {
- "node": ">= 6.0.0"
- }
- },
- "node_modules/asynckit": {
- "version": "0.4.0",
- "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
- "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
- "license": "MIT"
- },
- "node_modules/axios": {
- "version": "1.18.0",
- "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.0.tgz",
- "integrity": "sha512-E32NzpYKp++W7XRe52rHiXV2ehxmh3wbdgO7MHeFM+vqxLBYHzt0ElkiImtOBxtOmyp0yoC8C6uESVV84Y2/hw==",
- "license": "MIT",
- "dependencies": {
- "follow-redirects": "^1.16.0",
- "form-data": "^4.0.5",
- "https-proxy-agent": "^5.0.1",
- "proxy-from-env": "^2.1.0"
- }
- },
- "node_modules/call-bind-apply-helpers": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
- "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0",
- "function-bind": "^1.1.2"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/combined-stream": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
- "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
- "license": "MIT",
- "dependencies": {
- "delayed-stream": "~1.0.0"
- },
- "engines": {
- "node": ">= 0.8"
- }
- },
- "node_modules/debug": {
- "version": "4.4.3",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
- "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
- "license": "MIT",
- "dependencies": {
- "ms": "^2.1.3"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
- "node_modules/delayed-stream": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
- "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
- "license": "MIT",
- "engines": {
- "node": ">=0.4.0"
- }
- },
- "node_modules/dunder-proto": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
- "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
- "license": "MIT",
- "dependencies": {
- "call-bind-apply-helpers": "^1.0.1",
- "es-errors": "^1.3.0",
- "gopd": "^1.2.0"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/es-define-property": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
- "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/es-errors": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
- "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/es-object-atoms": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
- "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/es-set-tostringtag": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
- "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
- "license": "MIT",
- "dependencies": {
- "es-errors": "^1.3.0",
- "get-intrinsic": "^1.2.6",
- "has-tostringtag": "^1.0.2",
- "hasown": "^2.0.2"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/follow-redirects": {
- "version": "1.16.0",
- "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
- "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",
- "funding": [
- {
- "type": "individual",
- "url": "https://github.com/sponsors/RubenVerborgh"
- }
- ],
- "license": "MIT",
- "engines": {
- "node": ">=4.0"
- },
- "peerDependenciesMeta": {
- "debug": {
- "optional": true
- }
- }
- },
- "node_modules/form-data": {
- "version": "4.0.5",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
- "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
- "license": "MIT",
- "dependencies": {
- "asynckit": "^0.4.0",
- "combined-stream": "^1.0.8",
- "es-set-tostringtag": "^2.1.0",
- "hasown": "^2.0.2",
- "mime-types": "^2.1.12"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/function-bind": {
- "version": "1.1.2",
- "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
- "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
- "license": "MIT",
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/get-intrinsic": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
- "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
- "license": "MIT",
- "dependencies": {
- "call-bind-apply-helpers": "^1.0.2",
- "es-define-property": "^1.0.1",
- "es-errors": "^1.3.0",
- "es-object-atoms": "^1.1.1",
- "function-bind": "^1.1.2",
- "get-proto": "^1.0.1",
- "gopd": "^1.2.0",
- "has-symbols": "^1.1.0",
- "hasown": "^2.0.2",
- "math-intrinsics": "^1.1.0"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/get-proto": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
- "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
- "license": "MIT",
- "dependencies": {
- "dunder-proto": "^1.0.1",
- "es-object-atoms": "^1.0.0"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/gopd": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
- "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/has-symbols": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
- "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/has-tostringtag": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
- "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
- "license": "MIT",
- "dependencies": {
- "has-symbols": "^1.0.3"
- },
- "engines": {
- "node": ">= 0.4"
- },
- "funding": {
- "url": "https://github.com/sponsors/ljharb"
- }
- },
- "node_modules/hasown": {
- "version": "2.0.2",
- "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
- "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
- "license": "MIT",
- "dependencies": {
- "function-bind": "^1.1.2"
- },
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/https-proxy-agent": {
- "version": "5.0.1",
- "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
- "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
- "license": "MIT",
- "dependencies": {
- "agent-base": "6",
- "debug": "4"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/math-intrinsics": {
- "version": "1.1.0",
- "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
- "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.4"
- }
- },
- "node_modules/mime-db": {
- "version": "1.52.0",
- "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
- "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
- "license": "MIT",
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/mime-types": {
- "version": "2.1.35",
- "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
- "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
- "license": "MIT",
- "dependencies": {
- "mime-db": "1.52.0"
- },
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/ms": {
- "version": "2.1.3",
- "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
- "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
- "license": "MIT"
- },
- "node_modules/proxy-from-env": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
- "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
- "license": "MIT",
- "engines": {
- "node": ">=10"
- }
- }
- }
-}
diff --git a/agent/sandbox/sandbox_base_image/nodejs/package.json b/agent/sandbox/sandbox_base_image/nodejs/package.json
deleted file mode 100644
index 3bfa73b3ed..0000000000
--- a/agent/sandbox/sandbox_base_image/nodejs/package.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "name": "nodejs",
- "version": "1.0.0",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "keywords": [],
- "author": "",
- "license": "ISC",
- "description": "",
- "dependencies": {
- "axios": "^1.15.2"
- }
-}
diff --git a/agent/sandbox/sandbox_base_image/python/Dockerfile b/agent/sandbox/sandbox_base_image/python/Dockerfile
deleted file mode 100644
index 585d5c2676..0000000000
--- a/agent/sandbox/sandbox_base_image/python/Dockerfile
+++ /dev/null
@@ -1,27 +0,0 @@
-FROM python:3.11-slim-bookworm
-
-ARG NEED_MIRROR=1
-
-COPY --from=ghcr.io/astral-sh/uv:0.7.5 /uv /uvx /bin/
-ENV MPLBACKEND=Agg
-ENV MPLCONFIGDIR=/tmp/matplotlib
-ENV MATPLOTLIBRC=/usr/local/etc/matplotlibrc
-
-COPY requirements.txt .
-COPY matplotlibrc /usr/local/etc/matplotlibrc
-
-RUN if [ "$NEED_MIRROR" = 1 ]; then \
- grep -rl 'deb.debian.org' /etc/apt/ | xargs sed -i 's|http[s]*://deb.debian.org|https://mirrors.tuna.tsinghua.edu.cn|g'; \
- export UV_INDEX_URL="https://pypi.tuna.tsinghua.edu.cn/simple"; \
- else \
- export UV_INDEX_URL="https://pypi.org/simple"; \
- fi; \
- apt-get update && \
- apt-get install -y --no-install-recommends curl gcc && \
- mkdir -p /tmp/matplotlib && \
- uv pip install --system -r requirements.txt && \
- rm -rf /var/lib/apt/lists/*
-
-WORKDIR /workspace
-
-CMD ["sleep", "infinity"]
\ No newline at end of file
diff --git a/agent/sandbox/sandbox_base_image/python/matplotlibrc b/agent/sandbox/sandbox_base_image/python/matplotlibrc
deleted file mode 100644
index fe2a1462b7..0000000000
--- a/agent/sandbox/sandbox_base_image/python/matplotlibrc
+++ /dev/null
@@ -1,11 +0,0 @@
-## RAGFlow sandbox – matplotlib defaults
-## Only overrides are listed; all other settings use matplotlib built-in defaults.
-
-# Prefer CJK-capable fonts so Chinese / Japanese / Korean text renders correctly.
-# matplotlib silently skips fonts that are not installed, falling back to the
-# next entry in the list, so this is safe even without any CJK font package.
-font.family: sans-serif
-font.sans-serif: Noto Sans CJK SC, Noto Sans CJK TC, Noto Sans CJK JP, Noto Sans CJK KR, Source Han Sans SC, Source Han Sans CN, WenQuanYi Zen Hei, Microsoft YaHei, SimHei, PingFang SC, Heiti SC, STHeiti, Arial Unicode MS, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
-
-# Use ASCII hyphen-minus for the minus sign so it renders correctly with any font.
-axes.unicode_minus: False
diff --git a/agent/sandbox/sandbox_base_image/python/requirements.txt b/agent/sandbox/sandbox_base_image/python/requirements.txt
deleted file mode 100644
index d199e9e91e..0000000000
--- a/agent/sandbox/sandbox_base_image/python/requirements.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-numpy
-pandas
-matplotlib
-requests
diff --git a/agent/sandbox/sandbox_spec.md b/agent/sandbox/sandbox_spec.md
deleted file mode 100644
index 9b35ac252e..0000000000
--- a/agent/sandbox/sandbox_spec.md
+++ /dev/null
@@ -1,1872 +0,0 @@
-# RAGFlow Sandbox multi-provider architecture - design specification
-
-## 1. Overview
-
-The goal of this design specification is to enable RAGFlow to support multiple Sandbox deployment modes:
-
-- Self-Managed: On-premise deployment using Daytona/Docker (current implementation)
-- SaaS providers: Cloud-based sandbox services (Aliyun Code Interpreter, E2B)
-
-### Key requirements
-
-- Provider-agnostic interface for sandbox operations
-- Admin-configurable provider settings with dynamic schema
-- Multi-tenant isolation (1:1 session-to-sandbox mapping)
-- Graceful fallback and error handling
-- Unified monitoring and observability
-
-## Architecture
-
-### Provider abstraction layer
-
-Defines a unified `SandboxProvider` interface, and is located at `agent/sandbox/providers/`.
-
-```python
-# agent/sandbox/providers/base.py
-from abc import ABC, abstractmethod
-from typing import Dict, Any, Optional
-from dataclasses import dataclass
-
-@dataclass
-class SandboxInstance:
- instance_id: str
- provider: str
- status: str # running, stopped, error
- metadata: Dict[str, Any]
-
-@dataclass
-class ExecutionResult:
- stdout: str
- stderr: str
- exit_code: int
- execution_time: float
- metadata: Dict[str, Any]
-
-class SandboxProvider(ABC):
- """Base interface for all sandbox providers"""
-
- @abstractmethod
- def initialize(self, config: Dict[str, Any]) -> bool:
- """Initialize provider with configuration"""
- pass
-
- @abstractmethod
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """Create a new sandbox instance"""
- pass
-
- @abstractmethod
- def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10
- ) -> ExecutionResult:
- """Execute code in the sandbox"""
- pass
-
- @abstractmethod
- def destroy_instance(self, instance_id: str) -> bool:
- """Destroy a sandbox instance"""
- pass
-
- @abstractmethod
- def health_check(self) -> bool:
- """Check if provider is healthy"""
- pass
-
- @abstractmethod
- def get_supported_languages(self) -> list[str]:
- """Get list of supported programming languages"""
- pass
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- """
- Return configuration schema for this provider.
-
- Returns a dictionary mapping field names to their schema definitions,
- including type, required status, validation rules, labels, and descriptions.
- """
- pass
-
- def validate_config(self, config: Dict[str, Any]) -> tuple[bool, Optional[str]]:
- """
- Validate provider-specific configuration.
-
- This method allows providers to implement custom validation logic beyond
- the basic schema validation. Override this method to add provider-specific
- checks like URL format validation, API key format validation, etc.
-
- Args:
- config: Configuration dictionary to validate
-
- Returns:
- Tuple of (is_valid, error_message):
- - is_valid: True if configuration is valid, False otherwise
- - error_message: Error message if invalid, None if valid
- """
- # Default implementation: no custom validation
- return True, None
-```
-
-### Provider implementations
-
-#### Self-managed provider
-
-Wraps the existing executor_manager implementation. The implementation file is located at `agent/sandbox/providers/self_managed.py`.
-
-**Prerequisites**:
-
-- gVisor (runsc): Required for secure container isolation. Install with:
- ```bash
- go install gvisor.dev/gvisor/runsc@latest
- sudo cp ~/go/bin/runsc /usr/local/bin/
- runsc --version
- ```
- Or download from: https://github.com/google/gvisor/releases
-- Docker: Docker runtime with gVisor support.
-- Base Images: Pull sandbox base images:
- ```bash
- docker pull infiniflow/sandbox-base-python:latest
- docker pull infiniflow/sandbox-base-nodejs:latest
- ```
-
-**Configuration**: Docker API endpoint, request behavior, resource limits:
-
-- `endpoint`: HTTP endpoint (default: "http://sandbox-executor-manager:9385")
-- `timeout`: Request timeout in seconds (default: 30)
-- `max_retries`: Maximum retry attempts (default: 3)
-- `api_token`: Shared secret for the executor manager API (falls back to the `SANDBOX_EXECUTOR_MANAGER_API_TOKEN` environment variable)
-
-The container pool is **not** sized from this configuration. sandbox-executor-manager reads
-`SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` from its environment once at startup
-(`agent/sandbox/executor_manager/core/config.py`), so changing the pool size is a deployment
-change that requires restarting that service. A `pool_size` key passed to the provider is carried
-for reporting only β€” `get_info()` echoes it back β€” and reloading `sandbox.self_managed` recreates
-the RAGFlow-side client without resizing anything.
-
-**Executor manager environment variables**:
-
-- `SANDBOX_EXECUTOR_MANAGER_API_TOKEN`: Shared secret required on the `/run` endpoint (sent as `Authorization: Bearer <token>` or `X-Sandbox-Token: <token>`, compared with `secrets.compare_digest`). When unset, `/run` refuses requests with HTTP 503 instead of staying open; the legacy open behaviour survives only through the explicit operator opt-in `SANDBOX_EXECUTOR_MANAGER_ALLOW_UNAUTHENTICATED=true`. The RAGFlow side must be configured with the same value.
-- `SANDBOX_CONTAINER_NETWORK`: Docker network attached to sandbox runner containers (default: `none`, i.e. no external network access). Set to `bridge` (or a custom network) only when sandboxed code genuinely needs outbound network access; prefer baking dependencies into the base images instead.
-- `SANDBOX_RUN_RATE_LIMIT`: Rate limit for `POST /run`, keyed by client address (default: `120/minute`).
-
-**Languages**:
-- Python
-- Node.js
-- JavaScript
-
-**Security**:
-- gVisor (runsc runtime)
-- seccomp
-- read-only filesystem
-- memory limits
-- network isolation (`--network none` by default)
-- shared-secret authentication on the executor API
-
-**Advantages**:
-- Low latency (&lt;90ms), data privacy, full control
-- No per-execution costs
-- Supports `arguments` parameter for passing data to `main()` function
-
-**Limitations**:
-- Operational overhead, finite resources
-- Requires gVisor installation for security
-- Pool exhaustion causes "Container pool is busy" errors
-
-**Common issues**:
-- `"Container pool is busy"`: Raise `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE` above the baseline your deployment already applies β€” 5 with the standalone compose file, 3 in the main RAGFlow stack
-- `Container creation fails`: Ensure gVisor is installed and accessible at `/usr/local/bin/runsc`
-
-#### 2.2.2 Aliyun code interpreter provider
-
-**File**: `agent/sandbox/providers/aliyun_codeinterpreter.py`
-
-SaaS integration with Aliyun Function Compute Code Interpreter service using the official agentrun-sdk.
-
-**Official Resources**:
-- API Documentation: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter
-- Official SDK: https://github.com/Serverless-Devs/agentrun-sdk-python
-- SDK Docs: https://docs.agent.run
-
-**Implementation**:
-- Uses official `agentrun-sdk` package
-- SDK handles authentication (AccessKey signature) automatically
-- Supports environment variable configuration
-- Structured error handling with `ServerError` exceptions
-
-**Configuration**:
-- `access_key_id`: Aliyun AccessKey ID
-- `access_key_secret`: Aliyun AccessKey Secret
-- `account_id`: Aliyun primary account ID - Required for API calls
-- `region`: Region (cn-hangzhou, cn-beijing, cn-shanghai, cn-shenzhen, cn-guangzhou)
-- `template_name`: Optional sandbox template name for pre-configured environments
-- `timeout`: Execution timeout (max 30 seconds - hard limit)
-
-**Languages**: Python, JavaScript
-
-**Security**: Serverless microVM isolation, 30-second hard timeout limit
-
-**Advantages**:
-- Official SDK with automatic signature handling
-- Unlimited scalability, no maintenance
-- China region support with low latency
-- Built-in file system management
-- Support for execution contexts (Jupyter kernel)
-- Context-based execution for state persistence
-
-**Limitations**:
-- Network dependency
-- 30-second execution time limit (hard limit)
-- Pay-as-you-go costs
-- Requires Aliyun primary account ID for API calls
-
-**Setup instructions - Creating a RAM user with minimal privileges**:
-
-⚠️ **Security warning**: Never use your Aliyun primary account (root account) AccessKey for SDK operations. Primary accounts have full resource permissions, and leaked credentials pose significant security risks.
-
-**Step 1: Create a RAM user**
-
-1. Log in to [RAM Console](https://ram.console.aliyun.com/)
-2. Navigate to **People** β†’ **Users**
-3. Click **Create User**
-4. Configure the user:
- - **Username**: e.g., `ragflow-sandbox-user`
- - **Display Name**: e.g., `RAGFlow Sandbox Service Account`
- - **Access Mode**: Check βœ… **OpenAPI/Programmatic Access** (this creates an AccessKey)
- - **Console Login**: Optional (not needed for SDK-only access)
-5. Click **OK** and save the AccessKey ID and Secret immediately (displayed only once!)
-
-**Step 2: Create a custom authorization policy**
-
-Navigate to **Permissions** β†’ **Policies** β†’ **Create Policy** β†’ **Custom Policy** β†’ **Configuration Script (JSON)**
-
-Choose one of the following policy options based on your security requirements:
-
-**Option A: Minimal privilege policy (Recommended)**
-
-Grants only the permissions required by the AgentRun SDK:
-
-```json
-{
- "Version": "1",
- "Statement": [
- {
- "Effect": "Allow",
- "Action": [
- "agentrun:CreateTemplate",
- "agentrun:GetTemplate",
- "agentrun:UpdateTemplate",
- "agentrun:DeleteTemplate",
- "agentrun:ListTemplates",
- "agentrun:CreateSandbox",
- "agentrun:GetSandbox",
- "agentrun:DeleteSandbox",
- "agentrun:StopSandbox",
- "agentrun:ListSandboxes",
- "agentrun:CreateContext",
- "agentrun:ExecuteCode",
- "agentrun:DeleteContext",
- "agentrun:ListContexts",
- "agentrun:CreateFile",
- "agentrun:GetFile",
- "agentrun:DeleteFile",
- "agentrun:ListFiles",
- "agentrun:CreateProcess",
- "agentrun:GetProcess",
- "agentrun:KillProcess",
- "agentrun:ListProcesses",
- "agentrun:CreateRecording",
- "agentrun:GetRecording",
- "agentrun:DeleteRecording",
- "agentrun:ListRecordings",
- "agentrun:CheckHealth"
- ],
- "Resource": [
- "acs:agentrun:*:{account_id}:template/*",
- "acs:agentrun:*:{account_id}:sandbox/*"
- ]
- }
- ]
-}
-```
-
-> Replace `{account_id}` with your Aliyun primary account ID
-
-**Option B: Resource-Level privilege control (most secure)**
-
-Limits access to specific resource prefixes:
-
-```json
-{
- "Version": "1",
- "Statement": [
- {
- "Effect": "Allow",
- "Action": [
- "agentrun:CreateTemplate",
- "agentrun:GetTemplate",
- "agentrun:UpdateTemplate",
- "agentrun:DeleteTemplate",
- "agentrun:ListTemplates"
- ],
- "Resource": "acs:agentrun:*:{account_id}:template/ragflow-*"
- },
- {
- "Effect": "Allow",
- "Action": [
- "agentrun:CreateSandbox",
- "agentrun:GetSandbox",
- "agentrun:DeleteSandbox",
- "agentrun:StopSandbox",
- "agentrun:ListSandboxes",
- "agentrun:CheckHealth"
- ],
- "Resource": "acs:agentrun:*:{account_id}:sandbox/*"
- },
- {
- "Effect": "Allow",
- "Action": ["agentrun:*"],
- "Resource": "acs:agentrun:*:{account_id}:sandbox/*/context/*"
- },
- {
- "Effect": "Allow",
- "Action": ["agentrun:*"],
- "Resource": "acs:agentrun:*:{account_id}:sandbox/*/file/*"
- },
- {
- "Effect": "Allow",
- "Action": ["agentrun:*"],
- "Resource": "acs:agentrun:*:{account_id}:sandbox/*/process/*"
- },
- {
- "Effect": "Allow",
- "Action": ["agentrun:*"],
- "Resource": "acs:agentrun:*:{account_id}:sandbox/*/recording/*"
- }
- ]
-}
-```
-
-> This limits template creation to only those prefixed with `ragflow-*`
-
-**Option C: Full access (not recommended for production)**
-
-```json
-{
- "Version": "1",
- "Statement": [
- {
- "Effect": "Allow",
- "Action": "agentrun:*",
- "Resource": "*"
- }
- ]
-}
-```
-
-**Step 3: Authorize the RAM user**
-
-1. Return to **Users** list
-2. Find the user you just created (e.g., `ragflow-sandbox-user`)
-3. Click **Add Permissions** in the Actions column
-4. In the **Custom Policy** tab, select the policy you created in Step 2
-5. Click **OK**
-
-**Step 4: Configure RAGFlow with the RAM User credentials**
-
-After creating the RAM user and obtaining the AccessKey, configure it in RAGFlow's admin settings or environment variables:
-
-```bash
-# Method 1: Environment variables (for development/testing)
-export AGENTRUN_ACCESS_KEY_ID="LTAI5t..." # RAM user's AccessKey ID
-export AGENTRUN_ACCESS_KEY_SECRET="xxx..." # RAM user's AccessKey Secret
-export AGENTRUN_ACCOUNT_ID="123456789..." # Your primary account ID
-export AGENTRUN_REGION="cn-hangzhou"
-```
-
-Or via Admin UI (recommended for production):
-
-1. Navigate to **Admin Settings** β†’ **Sandbox Providers**
-2. Select **Aliyun Code Interpreter** provider
-3. Fill in the configuration:
- - `access_key_id`: RAM user's AccessKey ID
- - `access_key_secret`: RAM user's AccessKey Secret
- - `account_id`: Your primary account ID
- - `region`: e.g., `cn-hangzhou`
-
-**Step 5: Verify permissions**
-
-Test if the RAM user permissions are correctly configured:
-
-```python
-from agentrun.sandbox import Sandbox, TemplateInput, TemplateType
-
-try:
- # Test template creation
- template = Sandbox.create_template(
- input=TemplateInput(
- template_name="ragflow-permission-test",
- template_type=TemplateType.CODE_INTERPRETER
- )
- )
- print("βœ… RAM user permissions are correctly configured")
-except Exception as e:
- print(f"❌ Permission test failed: {e}")
-finally:
- # Cleanup test resources
- try:
- Sandbox.delete_template("ragflow-permission-test")
- except:
- pass
-```
-
-**Security best practices**:
-
-- **Always use RAM user AccessKeys**, never primary account AccessKeys.
-- **Follow the principle of least privilege** - grant only necessary permissions.
-- **Rotate AccessKeys regularly** - recommend every 3-6 months.
-- **Enable MFA** - enable multi-factor authentication for RAM users.
-- **Use secure storage** - store credentials in environment variables or secret management services, never hardcode in code.
-- **Restrict IP access** - add IP whitelist policies for RAM users if needed.
-- **Monitor access logs** - regularly check RAM user access logs in CloudTrail.
-
-**References**:
-
-- [Aliyun RAM Documentation](https://help.aliyun.com/product/28625.html)
-- [RAM Policy Language](https://help.aliyun.com/document_detail/100676.html)
-- [AgentRun Official Documentation](https://docs.agent.run)
-- [AgentRun SDK GitHub](https://github.com/Serverless-Devs/agentrun-sdk-python)
-
-#### E2B provider
-
-The file is located at `agent/sandbox/providers/e2b.py`.
-
-SaaS integration with E2B Cloud.
-- **Configuration**: api_key, region (us/eu)
-- **Languages**: Python, JavaScript, Go, Bash, etc.
-- **Security**: Firecracker microVMs
-- **Advantages**: Global CDN, fast startup, multiple language support
-- **Limitations**: International network latency for China users
-
-### Provider management
-
-The file is located at `agent/sandbox/providers/manager.py`.
-
-Since we only use one active provider at a time (configured globally), the provider management is simplified:
-
-```python
-class ProviderManager:
- """Manages the currently active sandbox provider"""
-
- def __init__(self):
- self.current_provider: Optional[SandboxProvider] = None
- self.current_provider_name: Optional[str] = None
-
- def set_provider(self, name: str, provider: SandboxProvider):
- """Set the active provider"""
- self.current_provider = provider
- self.current_provider_name = name
-
- def get_provider(self) -> Optional[SandboxProvider]:
- """Get the active provider"""
- return self.current_provider
-
- def get_provider_name(self) -> Optional[str]:
- """Get the active provider name"""
- return self.current_provider_name
-```
-
-**Rationale**: With global configuration, there's only one active provider at a time. The provider manager simply holds a reference to the currently active provider, making it a thin wrapper rather than a complex multi-provider manager.
-
-## Admin configuration
-
-### Database Schema
-
-Use the existing **SystemSettings** table for global sandbox configuration:
-
-```python
-# In api/db/db_models.py
-
-class SystemSettings(DataBaseModel):
- name = CharField(max_length=128, primary_key=True)
- source = CharField(max_length=32, null=False, index=False)
- data_type = CharField(max_length=32, null=False, index=False)
- value = CharField(max_length=1024, null=False, index=False)
-```
-
-**Rationale**: Sandbox manager is a **system-level service** shared by all tenants:
-- No per-tenant configuration needed (unlike LLM providers where each tenant has their own API keys)
-- Global settings like system email, DOC_ENGINE, etc.
-- Managed by administrators only
-- Leverages existing `SettingsMgr` in admin interface
-
-**Storage Strategy**: Each provider's configuration stored as a **single JSON object**:
-- `sandbox.provider_type` - Active provider selection ("self_managed", "aliyun_codeinterpreter", "e2b")
-- `sandbox.self_managed` - JSON config for self-managed provider
-- `sandbox.aliyun_codeinterpreter` - JSON config for Aliyun Code Interpreter provider
-- `sandbox.e2b` - JSON config for E2B provider
-
-**Note**: The `value` field has a 1024 character limit, which should be sufficient for typical sandbox configurations. If larger configs are needed, consider using a TextField or a separate configuration table.
-
-### Configuration Schema
-
-Each provider's configuration is stored as a **single JSON object** in the `value` field:
-
-#### Self-managed provider
-
-```json
-{
- "name": "sandbox.self_managed",
- "source": "variable",
- "data_type": "json",
- "value": "{\"endpoint\": \"http://sandbox-executor-manager:9385\", \"max_memory\": \"256m\", \"timeout\": 30}"
-}
-```
-
-#### Aliyun code interpreter
-```json
-{
- "name": "sandbox.aliyun_codeinterpreter",
- "source": "variable",
- "data_type": "json",
- "value": "{\"access_key_id\": \"LTAI5t...\", \"access_key_secret\": \"xxxxx\", \"account_id\": \"1234567890...\", \"region\": \"cn-hangzhou\", \"timeout\": 30}"
-}
-```
-
-#### E2B
-```json
-{
- "name": "sandbox.e2b",
- "source": "variable",
- "data_type": "json",
- "value": "{\"api_key\": \"e2b_sk_...\", \"region\": \"us\", \"timeout\": 30}"
-}
-```
-
-#### Active provider selection
-```json
-{
- "name": "sandbox.provider_type",
- "source": "variable",
- "data_type": "string",
- "value": "self_managed"
-}
-```
-
-### Provider self-describing Schema
-
-Each provider class implements a static method to describe its configuration schema:
-
-```python
-# agent/sandbox/providers/base.py
-
-class SandboxProvider(ABC):
- """Base interface for all sandbox providers"""
-
- @abstractmethod
- def initialize(self, config: Dict[str, Any]) -> bool:
- """Initialize provider with configuration"""
- pass
-
- @abstractmethod
- def create_instance(self, template: str = "python") -> SandboxInstance:
- """Create a new sandbox instance"""
- pass
-
- @abstractmethod
- def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10
- ) -> ExecutionResult:
- """Execute code in the sandbox"""
- pass
-
- @abstractmethod
- def destroy_instance(self, instance_id: str) -> bool:
- """Destroy a sandbox instance"""
- pass
-
- @abstractmethod
- def health_check(self) -> bool:
- """Check if provider is healthy"""
- pass
-
- @abstractmethod
- def get_supported_languages(self) -> list[str]:
- """Get list of supported programming languages"""
- pass
-
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- """Return configuration schema for this provider"""
- return {}
-```
-
-**Example implementation**:
-
-```python
-# agent/sandbox/providers/self_managed.py
-
-class SelfManagedProvider(SandboxProvider):
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "endpoint": {
- "type": "string",
- "required": True,
- "label": "API Endpoint",
- "placeholder": "http://sandbox-executor-manager:9385"
- },
- # Deployment-level: the pool is sized by SANDBOX_EXECUTOR_MANAGER_POOL_SIZE in the
- # sandbox-executor-manager environment, not by this field, and the UI renders it
- # read-only. The default below is read from the RAGFlow server's own environment and
- # falls back to 3, so it can disagree with the manager's actual pool. The standalone
- # compose file starts that service with 5, and the manager's own in-code fallback is 1.
- "executor_manager_pool_size": {
- "type": "integer",
- "default": int(os.getenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "3")),
- "label": "Container Pool Size",
- "min": 1,
- "max": 100,
- "scope": "deployment",
- "readonly": True
- },
- "max_memory": {
- "type": "string",
- "default": "256m",
- "label": "Max Memory per Container",
- "options": ["128m", "256m", "512m", "1g"]
- },
- "timeout": {
- "type": "integer",
- "default": 30,
- "label": "Execution Timeout (seconds)",
- "min": 5,
- "max": 300
- }
- }
-
-# agent/sandbox/providers/aliyun_codeinterpreter.py
-
-class AliyunCodeInterpreterProvider(SandboxProvider):
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "access_key_id": {
- "type": "string",
- "required": True,
- "secret": True,
- "label": "Access Key ID",
- "description": "Aliyun AccessKey ID for authentication"
- },
- "access_key_secret": {
- "type": "string",
- "required": True,
- "secret": True,
- "label": "Access Key Secret",
- "description": "Aliyun AccessKey Secret for authentication"
- },
- "account_id": {
- "type": "string",
- "required": True,
- "label": "Account ID",
- "description": "Aliyun primary account ID, required for API calls"
- },
- "region": {
- "type": "string",
- "default": "cn-hangzhou",
- "label": "Region",
- "options": ["cn-hangzhou", "cn-beijing", "cn-shanghai", "cn-shenzhen", "cn-guangzhou"],
- "description": "Aliyun region for Code Interpreter service"
- },
- "template_name": {
- "type": "string",
- "required": False,
- "label": "Template Name",
- "description": "Optional sandbox template name for pre-configured environments"
- },
- "timeout": {
- "type": "integer",
- "default": 30,
- "label": "Execution Timeout (seconds)",
- "min": 1,
- "max": 30,
- "description": "Code execution timeout (max 30 seconds - hard limit)"
- }
- }
-
-# agent/sandbox/providers/e2b.py
-
-class E2BProvider(SandboxProvider):
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "api_key": {
- "type": "string",
- "required": True,
- "secret": True,
- "label": "API Key"
- },
- "region": {
- "type": "string",
- "default": "us",
- "label": "Region",
- "options": ["us", "eu"]
- },
- "timeout": {
- "type": "integer",
- "default": 30,
- "label": "Execution Timeout (seconds)",
- "min": 5,
- "max": 300
- }
- }
-```
-
-**Benefits of Self-describing providers**:
-
-- Single source of truth - schema defined alongside implementation
-- Easy to add new providers - no central registry to update
-- Type safety - schema stays in sync with provider code
-- Flexible - frontend can use schema for validation or hardcode if preferred
-
-### Admin API endpoints
-
-Follow existing pattern in `admin/server/routes.py` and use `SettingsMgr`:
-
-```python
-# admin/server/routes.py (add new endpoints)
-
-from flask import request, jsonify
-import json
-from api.db.services.system_settings_service import SystemSettingsService
-from agent.agent.sandbox.providers.self_managed import SelfManagedProvider
-from agent.agent.sandbox.providers.aliyun_codeinterpreter import AliyunCodeInterpreterProvider
-from agent.agent.sandbox.providers.e2b import E2BProvider
-from admin.server.services import SettingsMgr
-
-# Map provider IDs to their classes
-PROVIDER_CLASSES = {
- "self_managed": SelfManagedProvider,
- "aliyun_codeinterpreter": AliyunCodeInterpreterProvider,
- "e2b": E2BProvider,
-}
-
-@admin_bp.route('/api/admin/sandbox/providers', methods=['GET'])
-def list_sandbox_providers():
- """List available sandbox providers with their schemas"""
- providers = []
- for provider_id, provider_class in PROVIDER_CLASSES.items():
- schema = provider_class.get_config_schema()
- providers.append({
- "id": provider_id,
- "name": provider_id.replace("_", " ").title(),
- "config_schema": schema
- })
- return jsonify({"data": providers})
-
-@admin_bp.route('/api/admin/sandbox/config', methods=['GET'])
-def get_sandbox_config():
- """Get current sandbox configuration"""
- # Get active provider
- active_provider_setting = SystemSettingsService.get_by_name("sandbox.provider_type")
- active_provider = active_provider_setting[0].value if active_provider_setting else None
-
- config = {"active": active_provider}
-
- # Load all provider configs
- for provider_id in PROVIDER_CLASSES.keys():
- setting = SystemSettingsService.get_by_name(f"sandbox.{provider_id}")
- if setting:
- try:
- config[provider_id] = json.loads(setting[0].value)
- except json.JSONDecodeError:
- config[provider_id] = {}
- else:
- # Return default values from schema
- provider_class = PROVIDER_CLASSES[provider_id]
- schema = provider_class.get_config_schema()
- config[provider_id] = {
- key: field_def.get("default", "")
- for key, field_def in schema.items()
- }
-
- return jsonify({"data": config})
-
-@admin_bp.route('/api/admin/sandbox/config', methods=['POST'])
-def set_sandbox_config():
- """
- Update sandbox provider configuration.
-
- Request Parameters:
- - provider_type: Provider identifier (e.g., "self_managed", "e2b")
- - config: Provider configuration dictionary
- - set_active: (optional) If True, also set this provider as active.
- Default: True for backward compatibility.
- Set to False to update config without switching providers.
- - test_connection: (optional) If True, test connection before saving
-
- Response: Success message
- """
- req = request.json
- provider_type = req.get('provider_type')
- config = req.get('config')
- set_active = req.get('set_active', True) # Default to True
-
- # Validate provider exists
- if provider_type not in PROVIDER_CLASSES:
- return jsonify({"error": "Unknown provider"}), 400
-
- # Validate configuration against schema
- provider_class = PROVIDER_CLASSES[provider_type]
- schema = provider_class.get_config_schema()
- validation_result = validate_config(config, schema)
- if not validation_result.valid:
- return jsonify({"error": "Invalid config", "details": validation_result.errors}), 400
-
- # Test connection if requested
- if req.get('test_connection'):
- test_result = test_provider_connection(provider_type, config)
- if not test_result.success:
- return jsonify({"error": "Connection failed", "details": test_result.error}), 400
-
- # Store entire config as a single JSON record
- config_json = json.dumps(config)
- setting_name = f"sandbox.{provider_type}"
-
- existing = SystemSettingsService.get_by_name(setting_name)
- if existing:
- SettingsMgr.update_by_name(setting_name, config_json)
- else:
- SystemSettingsService.save(
- name=setting_name,
- source="variable",
- data_type="json",
- value=config_json
- )
-
- # Set as active provider if requested (default: True)
- if set_active:
- SettingsMgr.update_by_name("sandbox.provider_type", provider_type)
-
- return jsonify({"message": "Configuration saved"})
-
-@admin_bp.route('/api/admin/sandbox/test', methods=['POST'])
-def test_sandbox_connection():
- """Test connection to sandbox provider"""
- provider_type = request.json.get('provider_type')
- config = request.json.get('config')
-
- test_result = test_provider_connection(provider_type, config)
- return jsonify({
- "success": test_result.success,
- "message": test_result.message,
- "latency_ms": test_result.latency_ms
- })
-
-@admin_bp.route('/api/admin/sandbox/active', methods=['PUT'])
-def set_active_sandbox_provider():
- """Set active sandbox provider"""
- provider_name = request.json.get('provider')
-
- if provider_name not in PROVIDER_CLASSES:
- return jsonify({"error": "Unknown provider"}), 400
-
- # Check if provider is configured
- provider_setting = SystemSettingsService.get_by_name(f"sandbox.{provider_name}")
- if not provider_setting:
- return jsonify({"error": "Provider not configured"}), 400
-
- SettingsMgr.update_by_name("sandbox.provider_type", provider_name)
- return jsonify({"message": "Active provider updated"})
-```
-
-## Frontend integration
-
-### Admin settings UI
-
-**Location**: `web/src/pages/SandboxSettings/index.tsx`
-
-```typescript
-import { Form, Select, Input, Button, Card, Space, Tag, message } from 'antd';
-import { listSandboxProviders, getSandboxConfig, setSandboxConfig, testSandboxConnection } from '@/utils/api';
-
-const SandboxSettings: React.FC = () => {
- const [providers, setProviders] = useState<Provider[]>([]);
- const [configs, setConfigs] = useState<Config[]>([]);
- const [selectedProvider, setSelectedProvider] = useState<string>('');
- const [testing, setTesting] = useState(false);
-
- const providerSchema = providers.find(p => p.id === selectedProvider);
-
- const renderConfigForm = () => {
- if (!providerSchema) return null;
-
- return (
- <Form layout="vertical">
- {Object.entries(providerSchema.config_schema).map(([key, schema]) => (
- <Form.Item
- key={key}
- name={key}
- label={schema.label}
- rules={[{ required: schema.required }]}
- >
- {schema.secret ? (
- <Input.Password placeholder={schema.placeholder} />
- ) : schema.type === 'integer' ? (
- <InputNumber min={schema.min} max={schema.max} />
- ) : schema.options ? (
- <Select>
- {schema.options.map((opt: string) => (
- <Option key={opt} value={opt}>{opt}</Option>
- ))}
- </Select>
- ) : (
- <Input placeholder={schema.placeholder} />
- )}
- </Form.Item>
- ))}
- </Form>
- );
- };
-
- return (
- <Card title="Sandbox Provider Configuration">
- <Space direction="vertical" style={{ width: '100%' }}>
- {/* Provider Selection */}
- <Form.Item label="Select Provider">
- <Select
- style={{ width: '100%' }}
- onChange={setSelectedProvider}
- value={selectedProvider}
- >
- {providers.map(provider => (
- <Option key={provider.id} value={provider.id}>
- <Space>
- <Icon type={provider.icon} />
- {provider.name}
- {provider.tags.map(tag => (
- <Tag key={tag}>{tag}</Tag>
- ))}
- </Space>
- </Option>
- ))}
- </Select>
- </Form.Item>
-
- {/* Dynamic Configuration Form */}
- {renderConfigForm()}
-
- {/* Actions */}
- <Space>
- <Button type="primary" onClick={handleSave}>
- Save Configuration
- </Button>
- <Button onClick={handleTest} loading={testing}>
- Test Connection
- </Button>
- </Space>
- </Space>
- </Card>
- );
-};
-```
-
-### API client
-
-**File**: `web/src/utils/api.ts`
-
-```typescript
-export async function listSandboxProviders() {
- return request<{ data: Provider[] }>('/api/admin/sandbox/providers');
-}
-
-export async function getSandboxConfig() {
- return request<{ data: SandboxConfig }>('/api/admin/sandbox/config');
-}
-
-export async function setSandboxConfig(config: SandboxConfigRequest) {
- return request('/api/admin/sandbox/config', {
- method: 'POST',
- data: config,
- });
-}
-
-export async function testSandboxConnection(provider: string, config: any) {
- return request('/api/admin/sandbox/test', {
- method: 'POST',
- data: { provider, config },
- });
-}
-
-export async function setActiveSandboxProvider(provider: string) {
- return request('/api/admin/sandbox/active', {
- method: 'PUT',
- data: { provider },
- });
-}
-```
-
-### 4.3 Type Definitions
-
-**File**: `web/src/types/sandbox.ts`
-
-```typescript
-interface Provider {
- id: string;
- name: string;
- description: string;
- icon: string;
- tags: string[];
- config_schema: Record<string, ConfigField>;
- supported_languages: string[];
-}
-
-interface ConfigField {
- type: 'string' | 'integer' | 'boolean';
- required: boolean;
- secret?: boolean;
- label: string;
- placeholder?: string;
- default?: any;
- options?: string[];
- min?: number;
- max?: number;
-}
-
-// Configuration response grouped by provider
-interface SandboxConfig {
- active: string; // Currently active provider
- self_managed?: Record<string, string>;
- aliyun_codeinterpreter?: Record<string, string>;
- e2b?: Record<string, string>;
- // Add more providers as needed
-}
-
-// Request to update provider configuration
-interface SandboxConfigRequest {
- provider_type: string;
- config: Record<string, string | number | boolean>;
- test_connection?: boolean;
- set_active?: boolean;
-}
-```
-
-## Integration with Agent system
-
-### Agent component usage
-
-The agent system will use the sandbox through the simplified provider manager, loading global configuration from SystemSettings:
-
-```python
-# In agent/components/code_executor.py
-
-import json
-from agent.agent.sandbox.providers.manager import ProviderManager
-from agent.agent.sandbox.providers.self_managed import SelfManagedProvider
-from agent.agent.sandbox.providers.aliyun_codeinterpreter import AliyunCodeInterpreterProvider
-from agent.agent.sandbox.providers.e2b import E2BProvider
-from api.db.services.system_settings_service import SystemSettingsService
-
-# Map provider IDs to their classes
-PROVIDER_CLASSES = {
- "self_managed": SelfManagedProvider,
- "aliyun_codeinterpreter": AliyunCodeInterpreterProvider,
- "e2b": E2BProvider,
-}
-
-class CodeExecutorComponent:
- def __init__(self):
- self.provider_manager = ProviderManager()
- self._load_active_provider()
-
- def _load_active_provider(self):
- """Load the active provider from system settings"""
- # Get active provider
- active_setting = SystemSettingsService.get_by_name("sandbox.provider_type")
- if not active_setting:
- raise RuntimeError("No sandbox provider configured")
-
- active_provider = active_setting[0].value
-
- # Load configuration for active provider (single JSON record)
- provider_setting = SystemSettingsService.get_by_name(f"sandbox.{active_provider}")
- if not provider_setting:
- raise RuntimeError(f"Sandbox provider {active_provider} not configured")
-
- # Parse JSON configuration
- try:
- config = json.loads(provider_setting[0].value)
- except json.JSONDecodeError as e:
- raise RuntimeError(f"Invalid sandbox configuration for {active_provider}: {e}")
-
- # Get provider class
- provider_class = PROVIDER_CLASSES.get(active_provider)
- if not provider_class:
- raise RuntimeError(f"Unknown provider: {active_provider}")
-
- # Initialize provider
- provider = provider_class()
- provider.initialize(config)
-
- # Set as active provider in manager
- self.provider_manager.set_provider(active_provider, provider)
-
- def execute(self, code: str, language: str) -> ExecutionResult:
- """Execute code using the active provider"""
- provider = self.provider_manager.get_provider()
-
- if not provider:
- raise RuntimeError("No sandbox provider configured")
-
- # Create instance
- instance = provider.create_instance(template=language)
-
- try:
- # Execute code
- result = provider.execute_code(
- instance_id=instance.instance_id,
- code=code,
- language=language
- )
- return result
- finally:
- # Always cleanup
- provider.destroy_instance(instance.instance_id)
-```
-
-## Security considerations
-
-### Credential storage
-- Sensitive credentials (API keys, secrets) encrypted at rest in database
-- Use RAGFlow's existing encryption mechanisms (AES-256)
-- Never log or expose credentials in error messages or API responses
-- Credentials redacted in UI (show only last 4 characters)
-
-### Tenant isolation
-
-- **Configuration**: Global sandbox settings shared by all tenants (admin-only access)
-- **Execution**: Sandboxes never shared across tenants/sessions during runtime
-- **Instance IDs**: Scoped to tenant: `{tenant_id}:{session_id}:{instance_id}`
-- **Network Isolation**: Between tenant sandboxes (VPC per tenant for SaaS providers)
-- **Resource Quotas**: Per-tenant limits on concurrent executions, total execution time
-- **Audit Logging**: All sandbox executions logged with tenant_id for traceability
-
-### Resource limits
-- Timeout limits per execution (configurable per provider, default 30s)
-- Memory/CPU limits enforced at provider level
-- Automatic cleanup of stale instances (max lifetime: 5 minutes)
-- Rate limiting per tenant (max concurrent executions: 10)
-
-### Code security
-- For self-managed: AST-based security analysis before execution
-- Blocked operations: file system writes, network calls, system commands
-- Allowlist approach: only specific imports allowed
-- Runtime monitoring for malicious patterns
-
-### Network security
-- Self-managed: Network isolation by default, no external access
- - Sandbox runner containers are started with `--network none` (opt out via `SANDBOX_CONTAINER_NETWORK`, e.g. `bridge`, when sandboxed code needs outbound network such as runtime `pip`/`npm` installs; prefer baking dependencies into the base images instead)
- - The executor manager API itself requires a shared secret (`SANDBOX_EXECUTOR_MANAGER_API_TOKEN`) on execution endpoints when configured; requests are authenticated with a constant-time comparison of the `Authorization: Bearer` or `X-Sandbox-Token` header
- - The executor manager port is published to loopback (`127.0.0.1`) only; RAGFlow reaches it over the internal compose network
-- SaaS: HTTPS only, certificate pinning
-- IP whitelisting for self-managed endpoint access
-
-## Monitoring and observability
-
-### Metrics to track
-
-**Common metrics (all providers)**:
-- Execution success rate (target: >95%)
-- Average execution time (p50, p95, p99)
-- Error rate by error type
-- Active instance count
-- Queue depth (for self-managed pool)
-
-**Self-managed specific**:
-- Container pool utilization (target: 60-80%)
-- Host resource usage (CPU, memory, disk)
-- Container creation latency
-- Container restart rate
-- gVisor runtime health
-
-**SaaS specific**:
-- API call latency by region
-- Rate limit usage and throttling events
-- Cost estimation (execution count Γ— unit cost)
-- Provider availability (uptime %)
-- API error rate by error code
-
-### Logging
-
-Structured logging for all provider operations:
-```json
-{
- "timestamp": "2025-01-26T10:00:00Z",
- "tenant_id": "tenant_123",
- "provider": "aliyun_codeinterpreter",
- "operation": "execute_code",
- "instance_id": "inst_xyz",
- "language": "python",
- "code_hash": "sha256:...",
- "duration_ms": 1234,
- "status": "success",
- "exit_code": 0,
- "memory_used_mb": 64,
- "region": "cn-hangzhou"
-}
-```
-
-### Alerts
-
-**Critical alerts**:
-- Provider availability < 99%
-- Error rate > 5%
-- Average execution time > 10s
-- Container pool exhaustion (0 available)
-
-**Warning alerts**:
-- Cost spike (2x daily average)
-- Rate limit approaching (>80%)
-- High memory usage (>90%)
-- Slow execution times (p95 > 5s)
-
-## Migration path
-
-### Phase 1: Refactor existing code (week 1-2)
-**Goals**: Extract current implementation into provider pattern
-
-**Tasks**:
-- [ ] Create `agent/sandbox/providers/base.py` with `SandboxProvider` interface
-- [ ] Implement `agent/sandbox/providers/self_managed.py` wrapping executor_manager
-- [ ] Create `agent/sandbox/providers/manager.py` for provider management
-- [ ] Write unit tests for self-managed provider
-- [ ] Document existing behavior and configuration
-
-**Deliverables**:
-- Provider abstraction layer
-- Self-managed provider implementation
-- Unit test suite
-
-### Phase 2: Database entegration (week 3)
-**Goals**: Add sandbox configuration to admin system
-
-**Tasks**:
-- [ ] Add sandbox entries to `conf/system_settings.json` initialization file
-- [ ] Extend `SettingsMgr` in `admin/server/services.py` with sandbox-specific methods
-- [ ] Add admin endpoints to `admin/server/routes.py`
-- [ ] Implement configuration validation logic
-- [ ] Add provider connection testing
-- [ ] Write API tests
-
-**Deliverables**:
-- SystemSettings integration
-- Admin API endpoints (`/api/admin/sandbox/*`)
-- Configuration validation
-- API test suite
-
-### Phase 3: Frontend UI (week 4)
-**Goals**: Build admin settings interface
-
-**Tasks**:
-- [ ] Create `web/src/pages/SandboxSettings/index.tsx`
-- [ ] Implement dynamic form generation from provider schema
-- [ ] Add connection testing UI
-- [ ] Create TypeScript types
-- [ ] Write frontend tests
-
-**Deliverables**:
-- Admin settings UI
-- Type definitions
-- Frontend test suite
-
-### Phase 4: SaaS provider implementation (Week 5-6)
-**Goals**: Implement Aliyun Code Interpreter and E2B providers
-
-**Tasks**:
-- [ ] Implement `agent/sandbox/providers/aliyun_codeinterpreter.py`
-- [ ] Implement `agent/sandbox/providers/e2b.py`
-- [ ] Add provider-specific tests with mocking
-- [ ] Document provider-specific behaviors
-- [ ] Create provider setup guides
-
-**Deliverables**:
-- Aliyun Code Interpreter provider
-- E2B provider
-- Provider documentation
-
-### Phase 5: Agent integration (week 7)
-**Goals**: Update agent components to use new provider system
-
-**Tasks**:
-- [ ] Update `agent/components/code_executor.py` to use ProviderManager
-- [ ] Implement fallback logic
-- [ ] Add tenant-specific provider loading
-- [ ] Update agent tests
-- [ ] Performance testing
-
-**Deliverables**:
-- Agent integration
-- Fallback mechanism
-- Updated test suite
-
-### Phase 6: Monitoring & documentation (week 8)
-**Goals**: Add observability and complete documentation
-
-**Tasks**:
-- [ ] Implement metrics collection
-- [ ] Add structured logging
-- [ ] Configure alerts
-- [ ] Write deployment guide
-- [ ] Write user documentation
-- [ ] Create troubleshooting guide
-
-**Deliverables**:
-- Monitoring dashboards
-- Complete documentation
-- Deployment guides
-
-## Testing strategy
-
-### Unit tests
-
-**Provider tests** (`test/agent/sandbox/providers/test_*.py`):
-```python
-class TestSelfManagedProvider:
- def test_initialize_with_config():
- provider = SelfManagedProvider()
- assert provider.initialize({"endpoint": "http://sandbox-executor-manager:9385"})
-
- def test_create_python_instance():
- provider = SelfManagedProvider()
- provider.initialize(test_config)
- instance = provider.create_instance("python")
- assert instance.status == "running"
-
- def test_execute_code():
- provider = SelfManagedProvider()
- result = provider.execute_code(instance_id, "print('hello')", "python")
- assert result.exit_code == 0
- assert "hello" in result.stdout
-```
-
-**Configuration tests**:
-- Test configuration validation for each provider schema
-- Test error handling for invalid configurations
-- Test secret field redaction
-
-### Integration tests
-
-**Provider Switching**:
-- Test switching between providers
-- Test fallback mechanism
-- Test concurrent provider usage
-
-**Multi-Tenant Isolation**:
-- Test tenant configuration isolation
-- Test instance ID scoping
-- Test resource separation
-
-**Admin API Tests**:
-- Test CRUD operations for configurations
-- Test connection testing endpoint
-- Test validation error responses
-
-### E2E tests
-
-**Complete flow tests**:
-```python
-def test_sandbox_execution_flow():
- # 1. Configure provider via admin API
- setSandboxConfig(provider="self_managed", config={...})
-
- # 2. Create agent task with code execution
- task = create_agent_task(code="print('test')")
-
- # 3. Execute task
- result = execute_agent_task(task.id)
-
- # 4. Verify result
- assert result.status == "success"
- assert "test" in result.output
-
- # 5. Verify sandbox cleanup
- assert get_active_instances() == 0
-```
-
-**Admin UI tests**:
-- Test provider configuration flow
-- Test connection testing
-- Test error handling in UI
-
-### Performance tests
-
-**Load Testing**:
-- Test 100 concurrent executions
-- Test pool exhaustion behavior
-- Test queue performance (self-managed)
-
-**Latency Testing**:
-- Measure cold start time per provider
-- Measure execution latency percentiles
-- Compare provider performance
-
-## Cost considerations
-
-### Self-managed costs
-
-**Infrastructure**:
-- Server hosting: $X/month (depends on specs)
-- Maintenance: engineering time
-- Scaling: manual, requires additional servers
-
-**Pros**:
-- Predictable costs
-- No per-execution fees
-- Full control over resources
-
-**Cons**:
-- High initial setup cost
-- Operational overhead
-- Finite capacity
-
-### SaaS costs
-
-**Aliyun Code Interpreter** (estimated):
-- Pricing: execution time Γ— memory configuration
-- Example: 1000 executions/day Γ— 30s Γ— $0.01/1000s = ~$0.30/day
-
-**E2B** (estimated):
-- Pricing: $0.02/execution-second
-- Example: 1000 executions/day Γ— 30s Γ— $0.02/s = ~$600/day
-
-**Pros**:
-- No upfront costs
-- Automatic scaling
-- No maintenance
-
-**Cons**:
-- Variable costs (can spike with usage)
-- Network dependency
-- Potential for runaway costs
-
-### Cost optimization
-
-**Recommendations**:
-- **Hybrid Approach**: Use self-managed for base load, SaaS for spikes
-- **Cost Monitoring**: Set budget alerts per tenant
-- **Resource Limits**: Enforce max executions per tenant/day
-- **Caching**: Reuse instances when possible (self-managed pool)
-- **Smart Routing**: Route to cheapest provider based on availability
-
-## Future extensibility
-
-The architecture supports easy addition of new providers:
-
-### Adding a new provider
-
-**Step 1**: Implement provider class with schema
-
-```python
-# agent/sandbox/providers/new_provider.py
-from .base import SandboxProvider
-
-class NewProvider(SandboxProvider):
- @staticmethod
- def get_config_schema() -> Dict[str, Dict]:
- return {
- "api_key": {
- "type": "string",
- "required": True,
- "secret": True,
- "label": "API Key"
- },
- "region": {
- "type": "string",
- "default": "us-east-1",
- "label": "Region"
- }
- }
-
- def initialize(self, config: Dict[str, Any]) -> bool:
- self.api_key = config.get("api_key")
- self.region = config.get("region", "us-east-1")
- # Initialize client
- return True
-
- # Implement other abstract methods...
-```
-
-**Step 2**: Register in provider mapping
-
-```python
-# In api/apps/sandbox_app.py or wherever providers are listed
-from agent.agent.sandbox.providers.new_provider import NewProvider
-
-PROVIDER_CLASSES = {
- "self_managed": SelfManagedProvider,
- "aliyun_codeinterpreter": AliyunCodeInterpreterProvider,
- "e2b": E2BProvider,
- "new_provider": NewProvider, # Add here
-}
-```
-
-**No central registry to update** - just import and add to the mapping!
-
-### Potential future providers
-
-- **GitHub Codespaces**: For GitHub-integrated workflows
-- **Gitpod**: Cloud development environments
-- **CodeSandbox**: Frontend code execution
-- **AWS Firecracker**: Raw microVM management
-- **Custom Provider**: User-defined provider implementations
-
-### Advanced features
-
-**Feature pooling**:
-- Share instances across executions (same language, same user)
-- Warm pool for reduced latency
-- Instance hibernation for cost savings
-
-**Feature multi-region**:
-- Route to nearest region
-- Failover across regions
-- Regional cost optimization
-
-**Feature hybrid execution**:
-- Split workloads between providers
-- Dynamic provider selection based on cost/performance
-- A/B testing for provider performance
-
-## Appendix
-
-### Configuration examples
-
-**SystemSettings initialization file** (`conf/system_settings.json` - add these entries):
-
-```json
-{
- "system_settings": [
- {
- "name": "sandbox.provider_type",
- "source": "variable",
- "data_type": "string",
- "value": "self_managed"
- },
- {
- "name": "sandbox.self_managed",
- "source": "variable",
- "data_type": "json",
- "value": "{\"endpoint\": \"http://sandbox-executor-manager:9385\", \"max_memory\": \"512m\", \"timeout\": 60, \"enable_seccomp\": true, \"enable_ast_analysis\": true}"
- },
- {
- "name": "sandbox.aliyun_codeinterpreter",
- "source": "variable",
- "data_type": "json",
- "value": "{\"access_key_id\": \"\", \"access_key_secret\": \"\", \"account_id\": \"\", \"region\": \"cn-hangzhou\", \"template_name\": \"\", \"timeout\": 30}"
- },
- {
- "name": "sandbox.e2b",
- "source": "variable",
- "data_type": "json",
- "value": "{\"api_key\": \"\", \"region\": \"us\", \"timeout\": 30}"
- }
- ]
-}
-```
-
-**Admin API request example** (POST to `/api/admin/sandbox/config`):
-
-```json
-{
- "provider_type": "self_managed",
- "config": {
- "endpoint": "http://sandbox-executor-manager:9385",
- "max_memory": "512m",
- "timeout": 60,
- "enable_seccomp": true,
- "enable_ast_analysis": true
- },
- "test_connection": true,
- "set_active": true
-}
-```
-
-**Note**: The `config` object in the request is a plain JSON object. The API will serialize it to a JSON string before storing in SystemSettings.
-
-**Admin API response example** (GET from `/api/admin/sandbox/config`):
-
-```json
-{
- "data": {
- "active": "self_managed",
- "self_managed": {
- "endpoint": "http://sandbox-executor-manager:9385",
- "max_memory": "512m",
- "timeout": 60,
- "enable_seccomp": true,
- "enable_ast_analysis": true
- },
- "aliyun_codeinterpreter": {
- "access_key_id": "",
- "access_key_secret": "",
- "region": "cn-hangzhou",
- "workspace_id": ""
- },
- "e2b": {
- "api_key": "",
- "region": "us",
- "timeout": 30
- }
- }
-}
-```
-
-**Note**: The response deserializes the JSON strings back to objects for easier frontend consumption.
-
-### Error codes
-
-| Code | Description | Resolution |
-|------|-------------|------------|
-| SB001 | Provider not initialized | Configure provider in admin |
-| SB002 | Invalid configuration | Check configuration values |
-| SB003 | Connection failed | Check network and credentials |
-| SB004 | Instance creation failed | Check provider capacity |
-| SB005 | Execution timeout | Increase timeout or optimize code |
-| SB006 | Out of memory | Reduce memory usage or increase limits |
-| SB007 | Code blocked by security policy | Remove blocked imports/operations |
-| SB008 | Rate limit exceeded | Reduce concurrency or upgrade plan |
-| SB009 | Provider unavailable | Check provider status or use fallback |
-
-### References
-
-- [Daytona Documentation](https://daytona.dev/docs)
-- [Aliyun Code Interpreter](https://help.aliyun.com/...)
-- [E2B Documentation](https://e2b.dev/docs)
-
----
-
-**Document version**: 1.0
-**Last updated**: 2026-01-26
-**Author**: RAGFlow Team
-**Status**: Design Specification - Ready for Review
-
-## Appendix C: configuration storage considerations
-
-### Current implementation
-- **Storage**: SystemSettings table with `value` field as `TextField` (unlimited length)
-- **Migration**: Database migration added to convert from `CharField(1024)` to `TextField`
-- **Benefit**: Supports arbitrarily long API keys, workspace IDs, and other SaaS provider credentials
-
-### Validation
-- **Schema validation**: Type checking, range validation, required field validation
-- **Provider-specific validation**: Custom validation via `validate_config()` method
-- **Example**: SelfManagedProvider validates URL format, timeout ranges, pool size constraints
-
-### Configuration storage format
-Each provider's configuration is stored as JSON in `SystemSettings.value`:
-- `sandbox.provider_type`: Active provider selection
-- `sandbox.self_managed`: Self-managed provider JSON config
-- `sandbox.aliyun_codeinterpreter`: Aliyun provider JSON config
-- `sandbox.e2b`: E2B provider JSON config
-
-## Appendix D: Configuration hot reload limitations
-
-### Current behavior
-**Provider configuration requires restart**: When switching sandbox providers in the admin panel, the ragflow service must be restarted for changes to take effect.
-
-**Reason**:
-- Admin and ragflow are separate processes
-- ragflow loads sandbox provider configuration only at startup
-- The `get_provider_manager()` function caches the provider globally
-- Configuration changes in MySQL are not automatically detected
-
-**Impact**:
-- Switching from `self_managed` β†’ `aliyun_codeinterpreter` requires ragflow restart
-- Updating credentials/config requires ragflow restart
-- Not a dynamic configuration system
-
-**Workarounds**:
-1. **Production**: Restart ragflow service after configuration changes:
- ```bash
- cd docker
- docker compose restart ragflow-server
- ```
-
-2. **Development**: Use the `reload_provider()` function in code:
- ```python
- from agent.sandbox.client import reload_provider
- reload_provider() # Reloads from MySQL settings
- ```
-
-**Future enhancement**:
-To support hot reload without restart, implement configuration change detection:
-```python
-# In agent/sandbox/client.py
-_config_timestamp: Optional[int] = None
-
-def get_provider_manager() -> ProviderManager:
- global _provider_manager, _config_timestamp
-
- # Check if configuration has changed
- setting = SystemSettingsService.get_by_name("sandbox.provider_type")
- current_timestamp = setting[0].update_time if setting else 0
-
- if _config_timestamp is None or current_timestamp > _config_timestamp:
- # Configuration changed, reload provider
- _provider_manager = None
- _load_provider_from_settings()
- _config_timestamp = current_timestamp
-
- return _provider_manager
-```
-
-However, this adds overhead on every `execute_code()` call. For production use, explicit restart is preferred for simplicity and reliability.
-
-## Appendix E: Arguments parameter support
-
-### Overview
-All sandbox providers support passing arguments to the `main()` function in user code. This enables dynamic parameter injection for code execution.
-
-### Implementation details
-
-**Base interface**:
-```python
-# agent/sandbox/providers/base.py
-@abstractmethod
-def execute_code(
- self,
- instance_id: str,
- code: str,
- language: str,
- timeout: int = 10,
- arguments: Optional[Dict[str, Any]] = None
-) -> ExecutionResult:
- """
- Execute code in the sandbox.
-
- The code should contain a main() function that will be called with:
- - Python: main(**arguments) if arguments provided, else main()
- - JavaScript: main(arguments) if arguments provided, else main()
- """
- pass
-```
-
-**Provider implementations**:
-
-1. **Self-managed provider** ([self_managed.py:164](providers/self_managed.py)):
- - Passes arguments via HTTP API: `"arguments": arguments or {}`
- - executor_manager writes `args.json` into the per-task workspace
- - Runner script loads arguments from `args.json`
- - Python runner calls `main(**args)` and JavaScript runner calls `main(args)`
-
-2. **Aliyun Code Interpreter** ([aliyun_codeinterpreter.py:260-275](providers/aliyun_codeinterpreter.py)):
- - Wraps user code to call `main(**arguments)` or `main()` if no arguments
- - Python example:
- ```python
- if arguments:
- wrapped_code = f'''{code}
-
- if __name__ == "__main__":
- import json
- result = main(**{json.dumps(arguments)})
- print(json.dumps(result) if isinstance(result, dict) else result)
- '''
- ```
- - JavaScript example:
- ```javascript
- if arguments:
- wrapped_code = f'''{code}
-
- const result = main({json.dumps(arguments)});
- console.log(typeof result === 'object' ? JSON.stringify(result) : String(result));
- '''
- ```
-
-**Client layer** ([client.py:138-190](client.py)):
-```python
-def execute_code(
- code: str,
- language: str = "python",
- timeout: int = 30,
- arguments: Optional[Dict[str, Any]] = None
-) -> ExecutionResult:
- provider_manager = get_provider_manager()
- provider = provider_manager.get_provider()
-
- instance = provider.create_instance(template=language)
- try:
- result = provider.execute_code(
- instance_id=instance.instance_id,
- code=code,
- language=language,
- timeout=timeout,
- arguments=arguments # Passed through to provider
- )
- return result
- finally:
- provider.destroy_instance(instance.instance_id)
-```
-
-**CodeExec tool integration** ([code_exec.py:136-165](../tools/code_exec.py)):
-```python
-def _execute_code(self, language: str, code: str, arguments: dict):
- # ... collect arguments from component configuration
-
- result = sandbox_execute_code(
- code=code,
- language=language,
- timeout=int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10 * 60)),
- arguments=arguments # Passed through to sandbox client
- )
-```
-
-### Usage examples
-
-**Python code with arguments**:
-```python
-# User code
-def main(name: str, count: int) -> dict:
- """Generate greeting"""
- return {"message": f"Hello {name}!" * count}
-
-# Called with: arguments={"name": "World", "count": 3}
-# Result: {"message": "Hello World!Hello World!Hello World!"}
-```
-
-**JavaScript code with arguments**:
-```javascript
-// User code
-function main(args) {
- const { name, count } = args;
- return `Hello ${name}!`.repeat(count);
-}
-
-// Called with: arguments={"name": "World", "count": 3}
-// Result: "Hello World!Hello World!Hello World!"
-```
-
-### Important notes
-
-1. **Function signature**: Code MUST define a `main()` function
- - Python: `def main(**kwargs)` or `def main()` if no arguments
- - JavaScript: `function main(args)` or `function main()` if no arguments
-
-2. **Type consistency**: Arguments are passed as JSON, so types are preserved:
- - Numbers β†’ int/float
- - Strings β†’ str
- - Booleans β†’ bool
- - Objects β†’ dict (Python) / object (JavaScript)
- - Arrays β†’ list (Python) / array (JavaScript)
-
-3. **Return value**: Return value is serialized as JSON for parsing
- - Python: `print(json.dumps(result))` if dict
- - JavaScript: `console.log(JSON.stringify(result))` if object
-
-4. **Provider alignment**: All providers (self_managed, aliyun_codeinterpreter, e2b) implement arguments passing consistently
diff --git a/agent/sandbox/scripts/restart.sh b/agent/sandbox/scripts/restart.sh
deleted file mode 100755
index 525465903e..0000000000
--- a/agent/sandbox/scripts/restart.sh
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-set -e
-
-bash "$(dirname "$0")/stop.sh"
-bash "$(dirname "$0")/start.sh"
diff --git a/agent/sandbox/scripts/start.sh b/agent/sandbox/scripts/start.sh
deleted file mode 100755
index 68c7227d53..0000000000
--- a/agent/sandbox/scripts/start.sh
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-set -e
-
-BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
-cd "$BASE_DIR"
-
-if [ -f .env ]; then
- source .env
- SANDBOX_EXECUTOR_MANAGER_PORT="${SANDBOX_EXECUTOR_MANAGER_PORT:-9385}" # Default to 9385 if not set in .env
- SANDBOX_EXECUTOR_MANAGER_POOL_SIZE="${SANDBOX_EXECUTOR_MANAGER_POOL_SIZE:-5}" # Default to 5 if not set in .env
- SANDBOX_BASE_PYTHON_IMAGE=${SANDBOX_BASE_PYTHON_IMAGE-"sandbox-base-python:latest"}
- SANDBOX_BASE_NODEJS_IMAGE=${SANDBOX_BASE_NODEJS_IMAGE-"sandbox-base-nodejs:latest"}
-else
- echo "⚠️ .env not found, using default ports and pool size"
- SANDBOX_EXECUTOR_MANAGER_PORT=9385
- SANDBOX_EXECUTOR_MANAGER_POOL_SIZE=5
- SANDBOX_BASE_PYTHON_IMAGE=sandbox-base-python:latest
- SANDBOX_BASE_NODEJS_IMAGE=sandbox-base-nodejs:latest
-fi
-
-echo "πŸ“¦ STEP 1: Build sandbox-base image ..."
-if [ -f .env ]; then
- source .env &&
- echo "🐍 Building base sandbox image for Python ($SANDBOX_BASE_PYTHON_IMAGE)..." &&
- docker build -t "$SANDBOX_BASE_PYTHON_IMAGE" ./sandbox_base_image/python &&
- echo "β¬’ Building base sandbox image for Nodejs ($SANDBOX_BASE_NODEJS_IMAGE)..." &&
- docker build -t "$SANDBOX_BASE_NODEJS_IMAGE" ./sandbox_base_image/nodejs
-else
- echo "⚠️ .env file not found, skipping build."
-fi
-
-echo "🧹 STEP 2: Clean up old sandbox containers (sandbox_nodejs_0~$((SANDBOX_EXECUTOR_MANAGER_POOL_SIZE - 1)) and sandbox_python_0~$((SANDBOX_EXECUTOR_MANAGER_POOL_SIZE - 1))) ..."
-for i in $(seq 0 $((SANDBOX_EXECUTOR_MANAGER_POOL_SIZE - 1))); do
- echo "🧹 Deleting sandbox_python_$i..."
- docker rm -f "sandbox_python_$i" >/dev/null 2>&1 || true
-
- echo "🧹 Deleting sandbox_nodejs_$i..."
- docker rm -f "sandbox_nodejs_$i" >/dev/null 2>&1 || true
-done
-
-echo "πŸ”§ STEP 3: Build executor services ..."
-docker compose build
-
-echo "πŸš€ STEP 4: Start services ..."
-docker compose up -d
-
-echo "⏳ STEP 5a: Check if ports are open (basic connectivity) ..."
-bash ./scripts/wait-for-it.sh "localhost" "$SANDBOX_EXECUTOR_MANAGER_PORT" -t 30
-
-echo "⏳ STEP 5b: Check if the interfaces are healthy (/healthz) ..."
-bash ./scripts/wait-for-it-http.sh "http://localhost:$SANDBOX_EXECUTOR_MANAGER_PORT/healthz" 30
-
-echo "βœ… STEP 6: Run security tests ..."
-python3 ./tests/sandbox_security_tests_full.py
-
-echo "πŸŽ‰ Service is ready: http://localhost:$SANDBOX_EXECUTOR_MANAGER_PORT/docs"
diff --git a/agent/sandbox/scripts/stop.sh b/agent/sandbox/scripts/stop.sh
deleted file mode 100755
index 8e2ec02ff2..0000000000
--- a/agent/sandbox/scripts/stop.sh
+++ /dev/null
@@ -1,51 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-set -e
-
-BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
-cd "$BASE_DIR"
-
-echo "πŸ›‘ Stopping all services..."
-docker compose down
-
-echo "🧹 Deleting sandbox containers..."
-# Remove the sandbox containers that actually exist instead of walking a range derived from
-# SANDBOX_EXECUTOR_MANAGER_POOL_SIZE. A pool created at one size and torn down after .env changed
-# left every container above the new size running; a missing .env skipped cleanup altogether; and a
-# container that never joined the executor-manager queue was never in the range to begin with.
-# The pattern is anchored to the generated pool names, so an unrelated container that merely
-# contains "sandbox_python_" in its name is not touched.
-# `docker ps` failing and finding nothing look identical once both become an empty string, and
-# the difference matters: the first leaves every sandbox container running while reporting
-# success. Only grep's no-match exit is tolerated here.
-if ! all_containers="$(docker ps -a --format '{{.Names}}')"; then
- echo "❌ Could not list Docker containers; sandbox containers were NOT removed" >&2
- exit 1
-fi
-sandbox_containers="$(printf '%s\n' "$all_containers" |
- grep -E '^sandbox_(python|nodejs)_[0-9]+$' || true)"
-if [ -n "$sandbox_containers" ]; then
- while IFS= read -r container; do
- echo "🧹 Deleting $container..."
- docker rm -f "$container" >/dev/null 2>&1 || true
- done <<<"$sandbox_containers"
-else
- echo "βœ… No sandbox containers found"
-fi
-
-echo "βœ… Stopping and cleanup complete"
diff --git a/agent/sandbox/scripts/wait-for-it-http.sh b/agent/sandbox/scripts/wait-for-it-http.sh
deleted file mode 100755
index c99c4970d3..0000000000
--- a/agent/sandbox/scripts/wait-for-it-http.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-url=$1
-timeout=${2:-15}
-quiet=${3:-0}
-
-for i in $(seq "$timeout"); do
- if curl -fs "$url" >/dev/null; then
- [[ "$quiet" -ne 1 ]] && echo "βœ” $url is healthy after $i seconds"
- exit 0
- fi
- sleep 1
-done
-
-echo "βœ– Timeout after $timeout seconds waiting for $url"
-exit 1
diff --git a/agent/sandbox/scripts/wait-for-it.sh b/agent/sandbox/scripts/wait-for-it.sh
deleted file mode 100755
index 718f25488f..0000000000
--- a/agent/sandbox/scripts/wait-for-it.sh
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/bin/bash
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-host=$1
-port=$2
-shift 2
-
-timeout=15
-quiet=0
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- -t | --timeout)
- timeout="$2"
- shift 2
- ;;
- -q | --quiet)
- quiet=1
- shift
- ;;
- *)
- break
- ;;
- esac
-done
-
-for i in $(seq "$timeout"); do
- if nc -z "$host" "$port" >/dev/null 2>&1; then
- [[ "$quiet" -ne 1 ]] && echo "βœ” $host:$port is available after $i seconds"
- exit 0
- fi
- sleep 1
-done
-
-echo "βœ– Timeout after $timeout seconds waiting for $host:$port"
-exit 1
diff --git a/agent/sandbox/tests/MIGRATION_GUIDE.md b/agent/sandbox/tests/MIGRATION_GUIDE.md
deleted file mode 100644
index 46f4894de2..0000000000
--- a/agent/sandbox/tests/MIGRATION_GUIDE.md
+++ /dev/null
@@ -1,261 +0,0 @@
-# Aliyun Code Interpreter Provider - Using the Official SDK
-
-## Important Changes
-
-### Official Resources
-- **Code Interpreter API**: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter
-- **Official SDK**: https://github.com/Serverless-Devs/agentrun-sdk-python
-- **SDK Documentation**: https://docs.agent.run
-
-## Advantages of Using the Official SDK
-
-Migrating from manual HTTP requests to the official SDK (`agentrun-sdk`) offers the following benefits:
-
-### 1. **Automatic Signature Authentication**
-- The SDK automatically handles Aliyun API signing (no need to manually implement `Authorization` headers)
-- Supports multiple authentication methods: AccessKey, STS Token
-- Automatically reads environment variables
-
-### 2. **Simplified API**
-```python
-# Old implementation (manual HTTP requests)
-response = requests.post(
- f"{DATA_ENDPOINT}/sandboxes/{sandbox_id}/execute",
- headers={"X-Acs-Parent-Id": account_id},
- json={"code": code, "language": "python"}
-)
-
-# New implementation (using SDK)
-sandbox = CodeInterpreterSandbox(template_name="python-sandbox", config=config)
-result = sandbox.context.execute(code="print('hello')")
-```
-
-### 3. **Better Error Handling**
-- Structured exception types (`ServerError`)
-- Automatic retry mechanism
-- Detailed error messages
-
-## Key Changes
-
-### 1. File Renames
-
-| Old Filename | New Filename | Description |
-|---------|---------|------|
-| `aliyun_opensandbox.py` | `aliyun_codeinterpreter.py` | Provider implementation |
-| `test_aliyun_provider.py` | `test_aliyun_codeinterpreter.py` | Unit tests |
-| `test_aliyun_integration.py` | `test_aliyun_codeinterpreter_integration.py` | Integration tests |
-
-### 2. Configuration Field Changes
-
-#### Old Configuration (OpenSandbox)
-```json
-{
- "access_key_id": "LTAI5t...",
- "access_key_secret": "...",
- "region": "cn-hangzhou",
- "workspace_id": "ws-xxxxx"
-}
-```
-
-#### New Configuration (Code Interpreter)
-```json
-{
- "access_key_id": "LTAI5t...",
- "access_key_secret": "...",
- "account_id": "1234567890...", // New: Aliyun primary account ID (required)
- "region": "cn-hangzhou",
- "template_name": "python-sandbox", // New: sandbox template name
- "timeout": 30 // Max 30 seconds (hard limit)
-}
-```
-
-### 3. Key Differences
-
-| Feature | OpenSandbox | Code Interpreter |
-|------|-------------|-----------------|
-| **API Endpoint** | `opensandbox.{region}.aliyuncs.com` | `agentrun.{region}.aliyuncs.com` (control plane) |
-| **API Version** | `2024-01-01` | `2025-09-10` |
-| **Authentication** | AccessKey required | AccessKey + primary account ID required |
-| **Request Headers** | Standard signature | Requires `X-Acs-Parent-Id` header |
-| **Timeout Limit** | Configurable | **Max 30 seconds** (hard limit) |
-| **Context** | Not supported | Supports context (Jupyter kernel) |
-
-### 4. API Call Changes
-
-#### Old Implementation (assumed OpenSandbox)
-```python
-# Single endpoint
-API_ENDPOINT = "https://opensandbox.cn-hangzhou.aliyuncs.com"
-
-# Simple request/response
-response = requests.post(
- f"{API_ENDPOINT}/execute",
- json={"code": "print('hello')", "language": "python"}
-)
-```
-
-#### New Implementation (Code Interpreter)
-```python
-# Control plane API - manage sandbox lifecycle
-CONTROL_ENDPOINT = "https://agentrun.cn-hangzhou.aliyuncs.com/2025-09-10"
-
-# Data plane API - execute code
-DATA_ENDPOINT = "https://{account_id}.agentrun-data.cn-hangzhou.aliyuncs.com"
-
-# Create sandbox (control plane)
-response = requests.post(
- f"{CONTROL_ENDPOINT}/sandboxes",
- headers={"X-Acs-Parent-Id": account_id},
- json={"templateName": "python-sandbox"}
-)
-
-# Execute code (data plane)
-response = requests.post(
- f"{DATA_ENDPOINT}/sandboxes/{sandbox_id}/execute",
- headers={"X-Acs-Parent-Id": account_id},
- json={"code": "print('hello')", "language": "python", "timeout": 30}
-)
-```
-
-### 5. Migration Steps
-
-#### Step 1: Update Configuration
-
-If you were previously using `aliyun_opensandbox`:
-
-**Old configuration**:
-```json
-{
- "name": "sandbox.provider_type",
- "value": "aliyun_opensandbox"
-}
-```
-
-**New configuration**:
-```json
-{
- "name": "sandbox.provider_type",
- "value": "aliyun_codeinterpreter"
-}
-```
-
-#### Step 2: Add the Required account_id
-
-Get your primary account ID from the Aliyun console:
-1. Log in to the [Aliyun Console](https://ram.console.aliyun.com/manage/ak)
-2. Click on your avatar in the top-right corner
-3. Copy the primary account ID (16-digit number)
-
-#### Step 3: Update Environment Variables
-
-```bash
-# New required environment variable
-export ALIYUN_ACCOUNT_ID="1234567890123456"
-
-# Other environment variables remain unchanged
-export ALIYUN_ACCESS_KEY_ID="LTAI5t..."
-export ALIYUN_ACCESS_KEY_SECRET="..."
-export ALIYUN_REGION="cn-hangzhou"
-```
-
-#### Step 4: Run Tests
-
-```bash
-# Unit tests (no real credentials required)
-pytest agent/sandbox/tests/test_aliyun_codeinterpreter.py -v
-
-# Integration tests (real credentials required)
-pytest agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py -v -m integration
-```
-
-## File Change Checklist
-
-### βœ… Completed
-
-- [x] Created `aliyun_codeinterpreter.py` - new provider implementation
-- [x] Updated `sandbox_spec.md` - specification document
-- [x] Updated `admin/services.py` - service manager
-- [x] Updated `providers/__init__.py` - package exports
-- [x] Created `test_aliyun_codeinterpreter.py` - unit tests
-- [x] Created `test_aliyun_codeinterpreter_integration.py` - integration tests
-
-### πŸ“ Optional Cleanup
-
-If you want to remove the old OpenSandbox implementation:
-
-```bash
-# Remove old files (optional)
-rm agent/sandbox/providers/aliyun_opensandbox.py
-rm agent/sandbox/tests/test_aliyun_provider.py
-rm agent/sandbox/tests/test_aliyun_integration.py
-```
-
-**Note**: Keeping the old files does not affect the new functionality; it just results in redundant code.
-
-## API Reference
-
-### Control Plane API (Sandbox Management)
-
-| Endpoint | Method | Description |
-|------|------|------|
-| `/sandboxes` | POST | Create a sandbox instance |
-| `/sandboxes/{id}/stop` | POST | Stop an instance |
-| `/sandboxes/{id}` | DELETE | Delete an instance |
-| `/templates` | GET | List templates |
-
-### Data Plane API (Code Execution)
-
-| Endpoint | Method | Description |
-|------|------|------|
-| `/sandboxes/{id}/execute` | POST | Execute code (simplified) |
-| `/sandboxes/{id}/contexts` | POST | Create a context |
-| `/sandboxes/{id}/contexts/{ctx_id}/execute` | POST | Execute within a context |
-| `/sandboxes/{id}/health` | GET | Health check |
-| `/sandboxes/{id}/files` | GET/POST | File read/write |
-| `/sandboxes/{id}/processes/cmd` | POST | Execute shell command |
-
-## FAQ
-
-### Q: Why is account_id required?
-
-**A**: The Code Interpreter API requires the `X-Acs-Parent-Id` (Aliyun primary account ID) header for authentication. This is a required parameter for the Aliyun Code Interpreter API.
-
-### Q: Can the 30-second timeout limit be bypassed?
-
-**A**: No. This is a **hard limit** of Aliyun Code Interpreter and cannot be bypassed through configuration or request parameters. If your code execution exceeds 30 seconds, consider:
-1. Optimizing the code logic
-2. Processing data in batches
-3. Using contexts to maintain state
-
-### Q: Can the old OpenSandbox configuration still be used?
-
-**A**: No. OpenSandbox and Code Interpreter are two different services with incompatible APIs. You must migrate to the new configuration format.
-
-### Q: How do I get the Aliyun primary account ID?
-
-**A**:
-1. Log in to the Aliyun console
-2. Click on your avatar in the top-right corner
-3. The primary account ID will be displayed in the popup
-
-### Q: Will the migration affect existing functionality?
-
-**A**:
-- **Self-managed provider (self_managed)**: Not affected
-- **E2B provider**: Not affected
-- **Aliyun provider**: Configuration update and re-testing required
-
-## Related Documentation
-
-- [Official Documentation](https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter)
-- [Sandbox Specification](../sandbox_spec.md)
-- [Testing Guide](./README.md)
-- [Quick Start](./QUICKSTART.md)
-
-## Support
-
-If you have any issues:
-1. Review the official documentation
-2. Verify the configuration is correct
-3. Check the error messages in the test output
-4. Contact the RAGFlow team
diff --git a/agent/sandbox/tests/QUICKSTART.md b/agent/sandbox/tests/QUICKSTART.md
deleted file mode 100644
index 609af547e2..0000000000
--- a/agent/sandbox/tests/QUICKSTART.md
+++ /dev/null
@@ -1,178 +0,0 @@
-# Aliyun OpenSandbox Provider - Quick Test Guide
-
-## Test Overview
-
-### 1. Unit Tests (No Credentials Required)
-
-Unit tests use mocks and do **not** require real Aliyun credentials; they can be run at any time.
-
-```bash
-# Run unit tests for the Aliyun provider
-pytest agent/sandbox/tests/test_aliyun_provider.py -v
-
-# Expected output:
-# test_aliyun_provider.py::TestAliyunOpenSandboxProvider::test_provider_initialization PASSED
-# test_aliyun_provider.py::TestAliyunOpenSandboxProvider::test_initialize_success PASSED
-# ...
-# ========================= 48 passed in 2.34s ==========================
-```
-
-### 2. Integration Tests (Real Credentials Required)
-
-Integration tests call the real Aliyun API and require credentials to be configured.
-
-#### Step 1: Configure Environment Variables
-
-```bash
-export ALIYUN_ACCESS_KEY_ID="LTAI5t..." # Replace with your real Access Key ID
-export ALIYUN_ACCESS_KEY_SECRET="..." # Replace with your real Access Key Secret
-export ALIYUN_REGION="cn-hangzhou" # Optional, defaults to cn-hangzhou
-```
-
-#### Step 2: Run Integration Tests
-
-```bash
-# Run all integration tests
-pytest agent/sandbox/tests/test_aliyun_integration.py -v -m integration
-
-# Run a specific test
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_health_check -v
-```
-
-#### Step 3: Expected Output
-
-```
-test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_initialize_provider PASSED
-test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_health_check PASSED
-test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_execute_python_code PASSED
-...
-========================== 10 passed in 15.67s ==========================
-```
-
-### 3. Test Scenarios
-
-#### Basic Functionality Tests
-
-```bash
-# Health check
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_health_check -v
-
-# Create instance
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_create_python_instance -v
-
-# Execute code
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_execute_python_code -v
-
-# Destroy instance
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_destroy_instance -v
-```
-
-#### Error Handling Tests
-
-```bash
-# Code execution error
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_execute_python_code_with_error -v
-
-# Timeout handling
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_execute_python_code_timeout -v
-```
-
-#### Real-World Scenario Tests
-
-```bash
-# Data processing workflow
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunRealWorldScenarios::test_data_processing_workflow -v
-
-# String manipulation
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunRealWorldScenarios::test_string_manipulation -v
-
-# Multiple executions
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunRealWorldScenarios::test_multiple_executions_same_instance -v
-```
-
-## FAQ
-
-### Q: What if I don't have credentials?
-
-**A:** Just run the unit tests β€” no real credentials needed:
-```bash
-pytest agent/sandbox/tests/test_aliyun_provider.py -v
-```
-
-### Q: How do I skip integration tests?
-
-**A:** Use pytest markers to skip them:
-```bash
-# Run only unit tests, skip integration tests
-pytest agent/sandbox/tests/ -v -m "not integration"
-```
-
-### Q: What should I do if integration tests fail?
-
-**A:** Check the following:
-
-1. **Are the credentials correct?**
- ```bash
- echo $ALIYUN_ACCESS_KEY_ID
- echo $ALIYUN_ACCESS_KEY_SECRET
- ```
-
-2. **Is the network connection working?**
- ```bash
- curl -I https://opensandbox.cn-hangzhou.aliyuncs.com
- ```
-
-3. **Do you have OpenSandbox service permissions?**
- - Log in to the Aliyun console
- - Check if the OpenSandbox service is enabled
- - Verify AccessKey permissions
-
-4. **View detailed error messages:**
- ```bash
- pytest agent/sandbox/tests/test_aliyun_integration.py -v -s
- ```
-
-### Q: What should I do if tests time out?
-
-**A:** Increase the timeout or check network connectivity:
-```bash
-# Use a longer timeout
-pytest agent/sandbox/tests/test_aliyun_integration.py -v --timeout=60
-```
-
-## Quick Reference: Test Commands
-
-| Command | Description | Credentials Required |
-|------|------|---------|
-| `pytest agent/sandbox/tests/test_aliyun_provider.py -v` | Unit tests | ❌ |
-| `pytest agent/sandbox/tests/test_aliyun_integration.py -v` | Integration tests | βœ… |
-| `pytest agent/sandbox/tests/ -v -m "not integration"` | Unit tests only | ❌ |
-| `pytest agent/sandbox/tests/ -v -m integration` | Integration tests only | βœ… |
-| `pytest agent/sandbox/tests/ -v` | All tests | Partially required |
-
-## Getting Aliyun Credentials
-
-1. Visit the [Aliyun Console](https://ram.console.aliyun.com/manage/ak)
-2. Create an AccessKey
-3. Save your AccessKey ID and AccessKey Secret
-4. Set the environment variables
-
-⚠️ **Security Tips:**
-- Do not hardcode credentials in your code
-- Use environment variables or configuration files
-- Rotate AccessKeys regularly
-- Restrict AccessKey permissions
-
-## Next Steps
-
-1. βœ… **Run unit tests** - Verify code logic
-2. πŸ”§ **Configure credentials** - Set environment variables
-3. πŸš€ **Run integration tests** - Test the real API
-4. πŸ“Š **Review results** - Ensure all tests pass
-5. 🎯 **Integrate into your system** - Configure the provider via the admin API
-
-## Need Help?
-
-- See the [full documentation](README.md)
-- Check the [sandbox specification](../sandbox_spec.md)
-- Contact the RAGFlow team
diff --git a/agent/sandbox/tests/README.md b/agent/sandbox/tests/README.md
deleted file mode 100644
index 11b350d3c3..0000000000
--- a/agent/sandbox/tests/README.md
+++ /dev/null
@@ -1,213 +0,0 @@
-# Sandbox Provider Tests
-
-This directory contains tests for the RAGFlow sandbox provider system.
-
-## Test Structure
-
-```
-tests/
-β”œβ”€β”€ pytest.ini # Pytest configuration
-β”œβ”€β”€ test_providers.py # Unit tests for all providers (mocked)
-β”œβ”€β”€ test_aliyun_provider.py # Unit tests for Aliyun provider (mocked)
-β”œβ”€β”€ test_aliyun_integration.py # Integration tests for Aliyun (real API)
-└── sandbox_security_tests_full.py # Security tests for self-managed provider
-```
-
-## Test Types
-
-### 1. Unit Tests (No Credentials Required)
-
-Unit tests use mocks and don't require any external services or credentials.
-
-**Files:**
-- `test_providers.py` - Tests for base provider interface and manager
-- `test_aliyun_provider.py` - Tests for Aliyun provider with mocked API calls
-
-**Run unit tests:**
-```bash
-# Run all unit tests
-pytest agent/sandbox/tests/test_providers.py -v
-pytest agent/sandbox/tests/test_aliyun_provider.py -v
-
-# Run specific test
-pytest agent/sandbox/tests/test_aliyun_provider.py::TestAliyunOpenSandboxProvider::test_initialize_success -v
-
-# Run all unit tests (skip integration)
-pytest agent/sandbox/tests/ -v -m "not integration"
-```
-
-### 2. Integration Tests (Real Credentials Required)
-
-Integration tests make real API calls to Aliyun OpenSandbox service.
-
-**Files:**
-- `test_aliyun_integration.py` - Tests with real Aliyun API calls
-
-**Setup environment variables:**
-```bash
-export ALIYUN_ACCESS_KEY_ID="LTAI5t..."
-export ALIYUN_ACCESS_KEY_SECRET="..."
-export ALIYUN_REGION="cn-hangzhou" # Optional, defaults to cn-hangzhou
-export ALIYUN_WORKSPACE_ID="ws-..." # Optional
-```
-
-**Run integration tests:**
-```bash
-# Run only integration tests
-pytest agent/sandbox/tests/test_aliyun_integration.py -v -m integration
-
-# Run all tests including integration
-pytest agent/sandbox/tests/ -v
-
-# Run specific integration test
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_health_check -v
-```
-
-### 3. Security Tests
-
-Security tests validate the security features of the self-managed sandbox provider.
-
-**Files:**
-- `sandbox_security_tests_full.py` - Comprehensive security tests
-
-**Run security tests:**
-```bash
-# Run all security tests
-pytest agent/sandbox/tests/sandbox_security_tests_full.py -v
-
-# Run specific security test
-pytest agent/sandbox/tests/sandbox_security_tests_full.py -k "test_dangerous_imports" -v
-```
-
-## Test Commands
-
-### Quick Test Commands
-
-```bash
-# Run all sandbox tests (unit only, fast)
-pytest agent/sandbox/tests/ -v -m "not integration" --tb=short
-
-# Run tests with coverage
-pytest agent/sandbox/tests/ -v --cov=agent.sandbox --cov-report=term-missing -m "not integration"
-
-# Run tests and stop on first failure
-pytest agent/sandbox/tests/ -v -x -m "not integration"
-
-# Run tests in parallel (requires pytest-xdist)
-pytest agent/sandbox/tests/ -v -n auto -m "not integration"
-```
-
-### Aliyun Provider Testing
-
-```bash
-# 1. Run unit tests (no credentials needed)
-pytest agent/sandbox/tests/test_aliyun_provider.py -v
-
-# 2. Set up credentials for integration tests
-export ALIYUN_ACCESS_KEY_ID="your-key-id"
-export ALIYUN_ACCESS_KEY_SECRET="your-secret"
-export ALIYUN_REGION="cn-hangzhou"
-
-# 3. Run integration tests (makes real API calls)
-pytest agent/sandbox/tests/test_aliyun_integration.py -v
-
-# 4. Test specific scenarios
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_execute_python_code -v
-pytest agent/sandbox/tests/test_aliyun_integration.py::TestAliyunRealWorldScenarios -v
-```
-
-## Understanding Test Results
-
-### Unit Test Output
-
-```
-agent/sandbox/tests/test_aliyun_provider.py::TestAliyunOpenSandboxProvider::test_initialize_success PASSED
-agent/sandbox/tests/test_aliyun_provider.py::TestAliyunOpenSandboxProvider::test_create_instance_python PASSED
-...
-========================== 48 passed in 2.34s ===========================
-```
-
-### Integration Test Output
-
-```
-agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_health_check PASSED
-agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_create_python_instance PASSED
-agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_execute_python_code PASSED
-...
-========================== 10 passed in 15.67s ===========================
-```
-
-**Note:** Integration tests will be skipped if credentials are not set:
-```
-agent/sandbox/tests/test_aliyun_integration.py::TestAliyunOpenSandboxIntegration::test_health_check SKIPPED
-...
-========================== 48 skipped, 10 passed in 0.12s ===========================
-```
-
-## Troubleshooting
-
-### Integration Tests Fail
-
-1. **Check credentials:**
- ```bash
- echo $ALIYUN_ACCESS_KEY_ID
- echo $ALIYUN_ACCESS_KEY_SECRET
- ```
-
-2. **Check network connectivity:**
- ```bash
- curl -I https://opensandbox.cn-hangzhou.aliyuncs.com
- ```
-
-3. **Verify permissions:**
- - Make sure your Aliyun account has OpenSandbox service enabled
- - Check that your AccessKey has the required permissions
-
-4. **Check region:**
- - Verify the region is correct for your account
- - Try different regions: cn-hangzhou, cn-beijing, cn-shanghai, etc.
-
-### Tests Timeout
-
-If tests timeout, increase the timeout in the test configuration or run with a longer timeout:
-```bash
-pytest agent/sandbox/tests/test_aliyun_integration.py -v --timeout=60
-```
-
-### Mock Tests Fail
-
-If unit tests fail, it's likely a code issue, not a credentials issue:
-1. Check the test error message
-2. Review the code changes
-3. Run with verbose output: `pytest -vv`
-
-## Contributing
-
-When adding new providers:
-
-1. **Create unit tests** in `test_{provider}_provider.py` with mocks
-2. **Create integration tests** in `test_{provider}_integration.py` with real API calls
-3. **Add markers** to distinguish test types
-4. **Update this README** with provider-specific testing instructions
-
-Example:
-```python
-def test_new_provider_real_api():
- """Test with real API calls."""
- # Your test here
-```
-
-## Continuous Integration
-
-In CI/CD pipelines:
-
-```yaml
-# Run unit tests only (fast, no credentials)
-pytest agent/sandbox/tests/ -v -m "not integration"
-
-# Run integration tests if credentials available
-if [ -n "$ALIYUN_ACCESS_KEY_ID" ]; then
- pytest agent/sandbox/tests/test_aliyun_integration.py -v -m integration
-fi
-```
diff --git a/agent/sandbox/tests/__init__.py b/agent/sandbox/tests/__init__.py
deleted file mode 100644
index f6a24fc983..0000000000
--- a/agent/sandbox/tests/__init__.py
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Sandbox provider tests package.
-"""
diff --git a/agent/sandbox/tests/pytest.ini b/agent/sandbox/tests/pytest.ini
deleted file mode 100644
index 61b0d3392e..0000000000
--- a/agent/sandbox/tests/pytest.ini
+++ /dev/null
@@ -1,33 +0,0 @@
-[pytest]
-# Pytest configuration for sandbox tests
-
-# Test discovery patterns
-python_files = test_*.py
-python_classes = Test*
-python_functions = test_*
-
-# Markers for different test types
-markers =
- integration: Tests that require external services (Aliyun API, etc.)
- unit: Fast tests that don't require external services
- slow: Tests that take a long time to run
-
-# Test paths
-testpaths = .
-
-# Minimum version
-minversion = 7.0
-
-# Output options
-addopts =
- -v
- --strict-markers
- --tb=short
- --disable-warnings
-
-# Log options
-log_cli = false
-log_cli_level = INFO
-
-# Coverage options (if using pytest-cov)
-# addopts = --cov=agent.sandbox --cov-report=html --cov-report=term
diff --git a/agent/sandbox/tests/sandbox_security_tests_full.py b/agent/sandbox/tests/sandbox_security_tests_full.py
deleted file mode 100644
index bb6975d205..0000000000
--- a/agent/sandbox/tests/sandbox_security_tests_full.py
+++ /dev/null
@@ -1,436 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import base64
-import os
-import textwrap
-import time
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from enum import Enum
-from typing import Dict, Optional
-
-import requests
-from pydantic import BaseModel
-
-API_URL = os.getenv("SANDBOX_API_URL", "http://sandbox-executor-manager:9385/run")
-TIMEOUT = 15
-MAX_WORKERS = 5
-
-
-class ResultStatus(str, Enum):
- SUCCESS = "success"
- PROGRAM_ERROR = "program_error"
- RESOURCE_LIMIT_EXCEEDED = "resource_limit_exceeded"
- UNAUTHORIZED_ACCESS = "unauthorized_access"
- RUNTIME_ERROR = "runtime_error"
- PROGRAM_RUNNER_ERROR = "program_runner_error"
-
-
-class ResourceLimitType(str, Enum):
- TIME = "time"
- MEMORY = "memory"
- OUTPUT = "output"
-
-
-class UnauthorizedAccessType(str, Enum):
- DISALLOWED_SYSCALL = "disallowed_syscall"
- FILE_ACCESS = "file_access"
- NETWORK_ACCESS = "network_access"
-
-
-class RuntimeErrorType(str, Enum):
- SIGNALLED = "signalled"
- NONZERO_EXIT = "nonzero_exit"
-
-
-class ExecutionResult(BaseModel):
- status: ResultStatus
- stdout: str
- stderr: str
- exit_code: int
- detail: Optional[str] = None
- resource_limit_type: Optional[ResourceLimitType] = None
- unauthorized_access_type: Optional[UnauthorizedAccessType] = None
- runtime_error_type: Optional[RuntimeErrorType] = None
-
-
-class TestResult(BaseModel):
- name: str
- passed: bool
- duration: float
- expected_failure: bool = False
- result: Optional[ExecutionResult] = None
- error: Optional[str] = None
- validation_error: Optional[str] = None
-
-
-def encode_code(code: str) -> str:
- return base64.b64encode(code.encode("utf-8")).decode("utf-8")
-
-
-def execute_single_test(name: str, code: str, language: str, arguments: dict, expect_fail: bool = False) -> TestResult:
- """Execute a single test case"""
- payload = {
- "code_b64": encode_code(textwrap.dedent(code)),
- "language": language,
- "arguments": arguments,
- }
-
- test_result = TestResult(name=name, passed=False, duration=0, expected_failure=expect_fail)
-
- really_processed = False
- try:
- while not really_processed:
- start_time = time.perf_counter()
-
- resp = requests.post(API_URL, json=payload, timeout=TIMEOUT)
- resp.raise_for_status()
- response_data = resp.json()
- if response_data["exit_code"] == -429: # too many request
- print(f"[{name}] Reached request limit, retring...")
- time.sleep(0.5)
- continue
- really_processed = True
-
- print("-------------------")
- print(f"{name}:\n{response_data}")
- print("-------------------")
-
- test_result.duration = time.perf_counter() - start_time
- test_result.result = ExecutionResult(**response_data)
-
- # Validate test result expectations
- validate_test_result(name, expect_fail, test_result)
-
- except requests.exceptions.RequestException as e:
- test_result.duration = time.perf_counter() - start_time
- test_result.error = f"Request failed: {str(e)}"
- test_result.result = ExecutionResult(
- status=ResultStatus.PROGRAM_RUNNER_ERROR,
- stdout="",
- stderr=str(e),
- exit_code=-999,
- detail="request_failed",
- )
-
- return test_result
-
-
-def validate_test_result(name: str, expect_fail: bool, test_result: TestResult):
- """Validate if the test result meets expectations"""
- if not test_result.result:
- test_result.passed = False
- test_result.validation_error = "No result returned"
- return
-
- test_result.passed = test_result.result.status == ResultStatus.SUCCESS
- # General validation logic
- if expect_fail:
- # Tests expected to fail should return a non-success status
- if test_result.passed:
- test_result.validation_error = "Expected failure but actually succeeded"
- else:
- # Tests expected to succeed should return a success status
- if not test_result.passed:
- test_result.validation_error = f"Unexpected failure (status={test_result.result.status})"
-
-
-def get_test_cases() -> Dict[str, dict]:
- """Return test cases (code, whether expected to fail)"""
- return {
- "1 Infinite loop: Should be forcibly terminated": {
- "code": """
-def main():
- while True:
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "2 Infinite loop: Should be forcibly terminated": {
- "code": """
-def main():
- while True:
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "3 Infinite loop: Should be forcibly terminated": {
- "code": """
-def main():
- while True:
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "4 Infinite loop: Should be forcibly terminated": {
- "code": """
-def main():
- while True:
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "5 Infinite loop: Should be forcibly terminated": {
- "code": """
-def main():
- while True:
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "6 Infinite loop: Should be forcibly terminated": {
- "code": """
-def main():
- while True:
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "7 Normal test: Python without dependencies": {
- "code": """
-def main():
- return {"data": "hello, world"}
- """,
- "should_fail": False,
- "arguments": {},
- "language": "python",
- },
- "8 Normal test: Python with pandas, should pass without any error": {
- "code": """
-import pandas as pd
-
-def main():
- data = {'Name': ['Alice', 'Bob', 'Charlie'],
- 'Age': [25, 30, 35]}
- df = pd.DataFrame(data)
- """,
- "should_fail": False,
- "arguments": {},
- "language": "python",
- },
- "9 Normal test: Nodejs without dependencies, should pass without any error": {
- "code": """
-const https = require('https');
-
-async function main(args) {
- return new Promise((resolve, reject) => {
- const req = https.get('https://example.com/', (res) => {
- let data = '';
-
- res.on('data', (chunk) => {
- data += chunk;
- });
-
- res.on('end', () => {
- clearTimeout(timeout);
- console.log('Body:', data);
- resolve(data);
- });
- });
-
- const timeout = setTimeout(() => {
- req.destroy(new Error('Request timeout after 10s'));
- }, 10000);
-
- req.on('error', (err) => {
- clearTimeout(timeout);
- console.error('Error:', err.message);
- reject(err);
- });
- });
-}
-
-module.exports = { main };
- """,
- "should_fail": False,
- "arguments": {},
- "language": "nodejs",
- },
- "10 Normal test: Nodejs with axios, should pass without any error": {
- "code": """
-const axios = require('axios');
-
-async function main(args) {
- try {
- const response = await axios.get('https://example.com/', {
- timeout: 10000
- });
- console.log('Body:', response.data);
- } catch (error) {
- console.error('Error:', error.message);
- }
-}
-
-module.exports = { main };
- """,
- "should_fail": False,
- "arguments": {},
- "language": "nodejs",
- },
- "11 Dangerous import: Should fail due to os module import": {
- "code": """
-import os
-
-def main():
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "12 Dangerous import from subprocess: Should fail due to subprocess import": {
- "code": """
-from subprocess import Popen
-
-def main():
- pass
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "13 Dangerous call: Should fail due to eval function call": {
- "code": """
-def main():
- eval('os.system("echo hello")')
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "14 Dangerous attribute access: Should fail due to shutil.rmtree": {
- "code": """
-import shutil
-
-def main():
- shutil.rmtree('/some/path')
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "15 Dangerous binary operation: Should fail due to unsafe concatenation leading to eval": {
- "code": """
-def main():
- dangerous_string = "os." + "system"
- eval(dangerous_string + '("echo hello")')
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "16 Dangerous function definition: Should fail due to user-defined eval function": {
- "code": """
-def eval_function():
- eval('os.system("echo hello")')
-
-def main():
- eval_function()
- """,
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- "17 Memory exhaustion(256m): Should fail due to exceeding memory limit(try to allocate 300m)": {
- "code": """
-def main():
- x = ['a' * 1024 * 1024] * 300 # 300MB
-""",
- "should_fail": True,
- "arguments": {},
- "language": "python",
- },
- }
-
-
-def print_test_report(results: Dict[str, TestResult]):
- print("\n=== πŸ” Test Report ===")
-
- max_name_len = max(len(name) for name in results)
-
- for name, result in results.items():
- status = "βœ…" if result.passed else "❌"
- if result.expected_failure:
- status = "⚠️" if result.passed else "βœ“" # Expected failure case
-
- print(f"{status} {name.ljust(max_name_len)} {result.duration:.2f}s")
-
- if result.error:
- print(f" REQUEST ERROR: {result.error}")
- if result.validation_error:
- print(f" VALIDATION ERROR: {result.validation_error}")
-
- if result.result and not result.passed:
- print(f" STATUS: {result.result.status}")
- if result.result.stderr:
- print(f" STDERR: {result.result.stderr[:200]}...")
- if result.result.detail:
- print(f" DETAIL: {result.result.detail}")
-
- passed = sum(1 for r in results.values() if ((not r.expected_failure and r.passed) or (r.expected_failure and not r.passed)))
- failed = len(results) - passed
-
- print("\n=== πŸ“Š Statistics ===")
- print(f"βœ… Passed: {passed}")
- print(f"❌ Failed: {failed}")
- print(f"πŸ“Œ Total: {len(results)}")
-
-
-def main():
- print(f"πŸ” Starting sandbox security tests (API: {API_URL})")
- print(f"πŸš€ Concurrent threads: {MAX_WORKERS}")
-
- test_cases = get_test_cases()
- results = {}
-
- with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
- futures = {}
- for name, detail in test_cases.items():
- # βœ… Log when a task is submitted
- print(f"βœ… Task submitted: {name}")
- time.sleep(0.4)
- future = executor.submit(execute_single_test, name, detail["code"], detail["language"], detail["arguments"], detail["should_fail"])
- futures[future] = name
-
- print("\n=== 🚦 Test Progress ===")
- for i, future in enumerate(as_completed(futures)):
- name = futures[future]
- print(f" {i + 1}/{len(test_cases)} completed: {name}")
- try:
- results[name] = future.result()
- except Exception as e:
- print(f"⚠️ Test {name} execution exception: {str(e)}")
- results[name] = TestResult(name=name, passed=False, duration=0, error=f"Execution exception: {str(e)}")
-
- print_test_report(results)
-
- if any(not r.passed and not r.expected_failure for r in results.values()):
- exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/agent/sandbox/tests/test_aliyun_codeinterpreter.py b/agent/sandbox/tests/test_aliyun_codeinterpreter.py
deleted file mode 100644
index 966d8e33d5..0000000000
--- a/agent/sandbox/tests/test_aliyun_codeinterpreter.py
+++ /dev/null
@@ -1,361 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Unit tests for Aliyun Code Interpreter provider.
-
-These tests use mocks and don't require real Aliyun credentials.
-
-Official Documentation: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter
-Official SDK: https://github.com/Serverless-Devs/agentrun-sdk-python
-"""
-
-import pytest
-from unittest.mock import patch, MagicMock
-
-from agent.sandbox.providers.base import SandboxProvider
-from agent.sandbox.providers.aliyun_codeinterpreter import AliyunCodeInterpreterProvider
-
-
-class TestAliyunCodeInterpreterProvider:
- """Test AliyunCodeInterpreterProvider implementation."""
-
- def test_provider_initialization(self):
- """Test provider initialization."""
- provider = AliyunCodeInterpreterProvider()
-
- assert provider.access_key_id == ""
- assert provider.access_key_secret == ""
- assert provider.account_id == ""
- assert provider.region == "cn-hangzhou"
- assert provider.template_name == ""
- assert provider.timeout == 30
- assert not provider._initialized
-
- @patch("agentrun.sandbox.Template")
- def test_initialize_success(self, mock_template):
- """Test successful initialization."""
- # Mock health check response
- mock_template.list_templates.return_value = []
-
- provider = AliyunCodeInterpreterProvider()
- result = provider.initialize(
- {
- "access_key_id": "LTAI5tXXXXXXXXXX",
- "access_key_secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
- "account_id": "1234567890123456",
- "region": "cn-hangzhou",
- "template_name": "python-sandbox",
- "timeout": 20,
- }
- )
-
- assert result is True
- assert provider.access_key_id == "LTAI5tXXXXXXXXXX"
- assert provider.access_key_secret == "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
- assert provider.account_id == "1234567890123456"
- assert provider.region == "cn-hangzhou"
- assert provider.template_name == "python-sandbox"
- assert provider.timeout == 20
- assert provider._initialized
-
- def test_initialize_missing_credentials(self):
- """Test initialization with missing credentials."""
- provider = AliyunCodeInterpreterProvider()
-
- # Missing access_key_id
- result = provider.initialize({"access_key_secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"})
- assert result is False
-
- # Missing access_key_secret
- result = provider.initialize({"access_key_id": "LTAI5tXXXXXXXXXX"})
- assert result is False
-
- # Missing account_id
- provider2 = AliyunCodeInterpreterProvider()
- result = provider2.initialize({"access_key_id": "LTAI5tXXXXXXXXXX", "access_key_secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"})
- assert result is False
-
- @patch("agentrun.sandbox.Template")
- def test_initialize_default_config(self, mock_template):
- """Test initialization with default config."""
- mock_template.list_templates.return_value = []
-
- provider = AliyunCodeInterpreterProvider()
- result = provider.initialize({"access_key_id": "LTAI5tXXXXXXXXXX", "access_key_secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "account_id": "1234567890123456"})
-
- assert result is True
- assert provider.region == "cn-hangzhou"
- assert provider.template_name == ""
-
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Template")
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Sandbox")
- def test_create_instance_python(self, mock_sandbox_class, mock_template):
- """Test creating a Python instance."""
- # Mock successful instance creation
- mock_sandbox = MagicMock()
- mock_sandbox.sandbox_id = "01JCED8Z9Y6XQVK8M2NRST5WXY"
- mock_sandbox_class.create.return_value = mock_sandbox
- mock_template.get_by_name.return_value = MagicMock()
-
- provider = AliyunCodeInterpreterProvider()
- provider._initialized = True
- provider._config = MagicMock()
-
- instance = provider.create_instance("python")
-
- assert instance.provider == "aliyun_codeinterpreter"
- assert instance.status == "READY"
- assert instance.metadata["language"] == "python"
-
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Template")
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Sandbox")
- def test_create_instance_javascript(self, mock_sandbox_class, mock_template):
- """Test creating a JavaScript instance."""
- mock_sandbox = MagicMock()
- mock_sandbox.sandbox_id = "01JCED8Z9Y6XQVK8M2NRST5WXY"
- mock_sandbox_class.create.return_value = mock_sandbox
- mock_template.get_by_name.return_value = MagicMock()
-
- provider = AliyunCodeInterpreterProvider()
- provider._initialized = True
- provider._config = MagicMock()
-
- instance = provider.create_instance("javascript")
-
- assert instance.metadata["language"] == "javascript"
-
- def test_create_instance_not_initialized(self):
- """Test creating instance when provider not initialized."""
- provider = AliyunCodeInterpreterProvider()
-
- with pytest.raises(RuntimeError, match="Provider not initialized"):
- provider.create_instance("python")
-
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Sandbox")
- def test_execute_code_success(self, mock_sandbox_class):
- """Test successful code execution."""
- # Mock sandbox instance
- mock_sandbox = MagicMock()
- mock_sandbox.context.execute.return_value = {
- "results": [{"type": "stdout", "text": "Hello, World!"}, {"type": "result", "text": "None"}, {"type": "endOfExecution", "status": "ok"}],
- "contextId": "kernel-12345-67890",
- }
- mock_sandbox_class.connect.return_value = mock_sandbox
-
- provider = AliyunCodeInterpreterProvider()
- provider._initialized = True
- provider._config = MagicMock()
-
- result = provider.execute_code(instance_id="01JCED8Z9Y6XQVK8M2NRST5WXY", code="print('Hello, World!')", language="python", timeout=10)
-
- assert result.stdout == "Hello, World!"
- assert result.stderr == ""
- assert result.exit_code == 0
- assert result.execution_time > 0
-
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Sandbox")
- def test_execute_code_timeout(self, mock_sandbox_class):
- """Test code execution timeout."""
- from agentrun.utils.exception import ServerError
-
- mock_sandbox = MagicMock()
- mock_sandbox.context.execute.side_effect = ServerError(408, "Request timeout")
- mock_sandbox_class.connect.return_value = mock_sandbox
-
- provider = AliyunCodeInterpreterProvider()
- provider._initialized = True
- provider._config = MagicMock()
-
- with pytest.raises(TimeoutError, match="Execution timed out"):
- provider.execute_code(instance_id="01JCED8Z9Y6XQVK8M2NRST5WXY", code="while True: pass", language="python", timeout=5)
-
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Sandbox")
- def test_execute_code_with_error(self, mock_sandbox_class):
- """Test code execution with error."""
- mock_sandbox = MagicMock()
- mock_sandbox.context.execute.return_value = {
- "results": [{"type": "stderr", "text": "Traceback..."}, {"type": "error", "text": "NameError: name 'x' is not defined"}, {"type": "endOfExecution", "status": "error"}]
- }
- mock_sandbox_class.connect.return_value = mock_sandbox
-
- provider = AliyunCodeInterpreterProvider()
- provider._initialized = True
- provider._config = MagicMock()
-
- result = provider.execute_code(instance_id="01JCED8Z9Y6XQVK8M2NRST5WXY", code="print(x)", language="python")
-
- assert result.exit_code != 0
- assert len(result.stderr) > 0
-
- @patch("agent.sandbox.providers.aliyun_codeinterpreter.Sandbox")
- def test_execute_code_uses_structured_result_marker_for_async_javascript(self, mock_sandbox_class):
- """Test JavaScript wrapper uses the structured result marker and awaits async main."""
- mock_sandbox = MagicMock()
- mock_sandbox.context.execute.return_value = {
- "results": [{"type": "stdout", "text": "__RAGFLOW_RESULT__:eyJwcmVzZW50Ijp0cnVlLCJ2YWx1ZSI6eyJhIjoiYiJ9LCJ0eXBlIjoianNvbiJ9"}],
- "contextId": "kernel-12345-67890",
- }
- mock_sandbox_class.connect.return_value = mock_sandbox
-
- provider = AliyunCodeInterpreterProvider()
- provider._initialized = True
- provider._config = MagicMock()
-
- result = provider.execute_code(
- instance_id="01JCED8Z9Y6XQVK8M2NRST5WXY",
- code="async function main(args) { return { a: 'b' }; }",
- language="javascript",
- timeout=10,
- )
-
- wrapped_code = mock_sandbox.context.execute.call_args.kwargs["code"]
- assert "__RAGFLOW_RESULT__:" in wrapped_code
- assert "await Promise.resolve(main(" in wrapped_code
- assert result.metadata["result_present"] is True
- assert result.metadata["result_value"] == {"a": "b"}
- assert result.metadata["result_type"] == "json"
-
- def test_get_supported_languages(self):
- """Test getting supported languages."""
- provider = AliyunCodeInterpreterProvider()
-
- languages = provider.get_supported_languages()
-
- assert "python" in languages
- assert "javascript" in languages
-
- def test_get_config_schema(self):
- """Test getting configuration schema."""
- schema = AliyunCodeInterpreterProvider.get_config_schema()
-
- assert "access_key_id" in schema
- assert schema["access_key_id"]["required"] is True
-
- assert "access_key_secret" in schema
- assert schema["access_key_secret"]["required"] is True
-
- assert "account_id" in schema
- assert schema["account_id"]["required"] is True
-
- assert "region" in schema
- assert "template_name" in schema
- assert "timeout" in schema
-
- def test_validate_config_success(self):
- """Test successful configuration validation."""
- provider = AliyunCodeInterpreterProvider()
-
- is_valid, error_msg = provider.validate_config({"access_key_id": "LTAI5tXXXXXXXXXX", "account_id": "1234567890123456", "region": "cn-hangzhou"})
-
- assert is_valid is True
- assert error_msg is None
-
- def test_validate_config_invalid_access_key(self):
- """Test validation with invalid access key format."""
- provider = AliyunCodeInterpreterProvider()
-
- is_valid, error_msg = provider.validate_config({"access_key_id": "INVALID_KEY"})
-
- assert is_valid is False
- assert "AccessKey ID format" in error_msg
-
- def test_validate_config_missing_account_id(self):
- """Test validation with missing account ID."""
- provider = AliyunCodeInterpreterProvider()
-
- is_valid, error_msg = provider.validate_config({})
-
- assert is_valid is False
- assert "Account ID" in error_msg
-
- def test_validate_config_invalid_region(self):
- """Test validation with invalid region."""
- provider = AliyunCodeInterpreterProvider()
-
- is_valid, error_msg = provider.validate_config(
- {
- "access_key_id": "LTAI5tXXXXXXXXXX",
- "account_id": "1234567890123456", # Provide required field
- "region": "us-west-1",
- }
- )
-
- assert is_valid is False
- assert "Invalid region" in error_msg
-
- def test_validate_config_invalid_timeout(self):
- """Test validation with invalid timeout (> 30 seconds)."""
- provider = AliyunCodeInterpreterProvider()
-
- is_valid, error_msg = provider.validate_config(
- {
- "access_key_id": "LTAI5tXXXXXXXXXX",
- "account_id": "1234567890123456", # Provide required field
- "timeout": 60,
- }
- )
-
- assert is_valid is False
- assert "Timeout must be between 1 and 30 seconds" in error_msg
-
- def test_normalize_language_python(self):
- """Test normalizing Python language identifier."""
- provider = AliyunCodeInterpreterProvider()
-
- assert provider._normalize_language("python") == "python"
- assert provider._normalize_language("python3") == "python"
- assert provider._normalize_language("PYTHON") == "python"
-
- def test_normalize_language_javascript(self):
- """Test normalizing JavaScript language identifier."""
- provider = AliyunCodeInterpreterProvider()
-
- assert provider._normalize_language("javascript") == "javascript"
- assert provider._normalize_language("nodejs") == "javascript"
- assert provider._normalize_language("JavaScript") == "javascript"
-
-
-class TestAliyunCodeInterpreterInterface:
- """Test that Aliyun provider correctly implements the interface."""
-
- def test_aliyun_provider_is_abstract(self):
- """Test that AliyunCodeInterpreterProvider is a SandboxProvider."""
- provider = AliyunCodeInterpreterProvider()
-
- assert isinstance(provider, SandboxProvider)
-
- def test_aliyun_provider_has_abstract_methods(self):
- """Test that AliyunCodeInterpreterProvider implements all abstract methods."""
- provider = AliyunCodeInterpreterProvider()
-
- assert hasattr(provider, "initialize")
- assert callable(provider.initialize)
-
- assert hasattr(provider, "create_instance")
- assert callable(provider.create_instance)
-
- assert hasattr(provider, "execute_code")
- assert callable(provider.execute_code)
-
- assert hasattr(provider, "destroy_instance")
- assert callable(provider.destroy_instance)
-
- assert hasattr(provider, "health_check")
- assert callable(provider.health_check)
-
- assert hasattr(provider, "get_supported_languages")
- assert callable(provider.get_supported_languages)
diff --git a/agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py b/agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py
deleted file mode 100644
index a114b5d4e5..0000000000
--- a/agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py
+++ /dev/null
@@ -1,353 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Integration tests for Aliyun Code Interpreter provider.
-
-These tests require real Aliyun credentials and will make actual API calls.
-To run these tests, set the following environment variables:
-
- export AGENTRUN_ACCESS_KEY_ID="LTAI5t..."
- export AGENTRUN_ACCESS_KEY_SECRET="..."
- export AGENTRUN_ACCOUNT_ID="1234567890..." # Aliyun primary account ID
- export AGENTRUN_REGION="cn-hangzhou" # Note: AGENTRUN_REGION (SDK will read this)
-
-Then run:
- pytest agent/sandbox/tests/test_aliyun_codeinterpreter_integration.py -v
-
-Official Documentation: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter
-"""
-
-import os
-import pytest
-from agent.sandbox.providers.aliyun_codeinterpreter import AliyunCodeInterpreterProvider
-
-
-# Skip all tests if credentials are not provided
-pytestmark = pytest.mark.skipif(
- not all(
- [
- os.getenv("AGENTRUN_ACCESS_KEY_ID"),
- os.getenv("AGENTRUN_ACCESS_KEY_SECRET"),
- os.getenv("AGENTRUN_ACCOUNT_ID"),
- ]
- ),
- reason="Aliyun credentials not set. Set AGENTRUN_ACCESS_KEY_ID, AGENTRUN_ACCESS_KEY_SECRET, and AGENTRUN_ACCOUNT_ID.",
-)
-
-
-def aliyun_config():
- """Get Aliyun configuration from environment variables."""
- return {
- "access_key_id": os.getenv("AGENTRUN_ACCESS_KEY_ID"),
- "access_key_secret": os.getenv("AGENTRUN_ACCESS_KEY_SECRET"),
- "account_id": os.getenv("AGENTRUN_ACCOUNT_ID"),
- "region": os.getenv("AGENTRUN_REGION", "cn-hangzhou"),
- "template_name": os.getenv("AGENTRUN_TEMPLATE_NAME", ""),
- "timeout": 30,
- }
-
-
-def provider(aliyun_config):
- """Create an initialized Aliyun provider."""
- provider = AliyunCodeInterpreterProvider()
- initialized = provider.initialize(aliyun_config)
- if not initialized:
- pytest.skip("Failed to initialize Aliyun provider. Check credentials, account ID, and network.")
- return provider
-
-
-class TestAliyunCodeInterpreterIntegration:
- """Integration tests for Aliyun Code Interpreter provider."""
-
- def test_initialize_provider(self, aliyun_config):
- """Test provider initialization with real credentials."""
- provider = AliyunCodeInterpreterProvider()
- result = provider.initialize(aliyun_config)
-
- assert result is True
- assert provider._initialized is True
-
- def test_health_check(self, provider):
- """Test health check with real API."""
- result = provider.health_check()
-
- assert result is True
-
- def test_get_supported_languages(self, provider):
- """Test getting supported languages."""
- languages = provider.get_supported_languages()
-
- assert "python" in languages
- assert "javascript" in languages
- assert isinstance(languages, list)
-
- def test_create_python_instance(self, provider):
- """Test creating a Python sandbox instance."""
- try:
- instance = provider.create_instance("python")
-
- assert instance.provider == "aliyun_codeinterpreter"
- assert instance.status in ["READY", "CREATING"]
- assert instance.metadata["language"] == "python"
- assert len(instance.instance_id) > 0
-
- # Clean up
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"Instance creation failed: {str(e)}. API might not be available yet.")
-
- def test_execute_python_code(self, provider):
- """Test executing Python code in the sandbox."""
- try:
- # Create instance
- instance = provider.create_instance("python")
-
- # Execute simple code
- result = provider.execute_code(
- instance_id=instance.instance_id,
- code="print('Hello from Aliyun Code Interpreter!')\nprint(42)",
- language="python",
- timeout=30, # Max 30 seconds
- )
-
- assert result.exit_code == 0
- assert "Hello from Aliyun Code Interpreter!" in result.stdout
- assert "42" in result.stdout
- assert result.execution_time > 0
-
- # Clean up
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"Code execution test failed: {str(e)}. API might not be available yet.")
-
- def test_execute_python_code_with_arguments(self, provider):
- """Test executing Python code with arguments parameter."""
- try:
- # Create instance
- instance = provider.create_instance("python")
-
- # Execute code with arguments
- result = provider.execute_code(
- instance_id=instance.instance_id,
- code="""def main(name: str, count: int) -> dict:
- return {"message": f"Hello {name}!" * count}
-""",
- language="python",
- timeout=30,
- arguments={"name": "World", "count": 2},
- )
-
- assert result.exit_code == 0
- assert "Hello World!Hello World!" in result.stdout
-
- # Clean up
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"Arguments test failed: {str(e)}. API might not be available yet.")
-
- def test_execute_python_code_with_error(self, provider):
- """Test executing Python code that produces an error."""
- try:
- # Create instance
- instance = provider.create_instance("python")
-
- # Execute code with error
- result = provider.execute_code(instance_id=instance.instance_id, code="raise ValueError('Test error')", language="python", timeout=30)
-
- assert result.exit_code != 0
- assert len(result.stderr) > 0 or "ValueError" in result.stdout
-
- # Clean up
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"Error handling test failed: {str(e)}. API might not be available yet.")
-
- def test_execute_javascript_code(self, provider):
- """Test executing JavaScript code in the sandbox."""
- try:
- # Create instance
- instance = provider.create_instance("javascript")
-
- # Execute simple code
- result = provider.execute_code(instance_id=instance.instance_id, code="console.log('Hello from JavaScript!');", language="javascript", timeout=30)
-
- assert result.exit_code == 0
- assert "Hello from JavaScript!" in result.stdout
-
- # Clean up
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"JavaScript execution test failed: {str(e)}. API might not be available yet.")
-
- def test_execute_javascript_code_with_arguments(self, provider):
- """Test executing JavaScript code with arguments parameter."""
- try:
- # Create instance
- instance = provider.create_instance("javascript")
-
- # Execute code with arguments
- result = provider.execute_code(
- instance_id=instance.instance_id,
- code="""function main(args) {
- const { name, count } = args;
- return `Hello ${name}!`.repeat(count);
-}""",
- language="javascript",
- timeout=30,
- arguments={"name": "World", "count": 2},
- )
-
- assert result.exit_code == 0
- assert "Hello World!Hello World!" in result.stdout
-
- # Clean up
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"JavaScript arguments test failed: {str(e)}. API might not be available yet.")
-
- def test_destroy_instance(self, provider):
- """Test destroying a sandbox instance."""
- try:
- # Create instance
- instance = provider.create_instance("python")
-
- # Destroy instance
- result = provider.destroy_instance(instance.instance_id)
-
- # Note: The API might return True immediately or async
- assert result is True or result is False
- except Exception as e:
- pytest.skip(f"Destroy instance test failed: {str(e)}. API might not be available yet.")
-
- def test_config_validation(self, provider):
- """Test configuration validation."""
- # Valid config
- is_valid, error = provider.validate_config({"access_key_id": "LTAI5tXXXXXXXXXX", "account_id": "1234567890123456", "region": "cn-hangzhou", "timeout": 30})
- assert is_valid is True
- assert error is None
-
- # Invalid access key
- is_valid, error = provider.validate_config({"access_key_id": "INVALID_KEY"})
- assert is_valid is False
-
- # Missing account ID
- is_valid, error = provider.validate_config({})
- assert is_valid is False
- assert "Account ID" in error
-
- def test_timeout_limit(self, provider):
- """Test that timeout is limited to 30 seconds."""
- # Timeout > 30 should be clamped to 30
- provider2 = AliyunCodeInterpreterProvider()
- provider2.initialize(
- {
- "access_key_id": os.getenv("AGENTRUN_ACCESS_KEY_ID"),
- "access_key_secret": os.getenv("AGENTRUN_ACCESS_KEY_SECRET"),
- "account_id": os.getenv("AGENTRUN_ACCOUNT_ID"),
- "timeout": 60, # Request 60 seconds
- }
- )
-
- # Should be clamped to 30
- assert provider2.timeout == 30
-
-
-class TestAliyunCodeInterpreterScenarios:
- """Test real-world usage scenarios."""
-
- def test_data_processing_workflow(self, provider):
- """Test a simple data processing workflow."""
- try:
- instance = provider.create_instance("python")
-
- # Execute data processing code
- code = """
-import json
-data = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
-result = json.dumps(data, indent=2)
-print(result)
-"""
- result = provider.execute_code(instance_id=instance.instance_id, code=code, language="python", timeout=30)
-
- assert result.exit_code == 0
- assert "Alice" in result.stdout
- assert "Bob" in result.stdout
-
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"Data processing test failed: {str(e)}")
-
- def test_string_manipulation(self, provider):
- """Test string manipulation operations."""
- try:
- instance = provider.create_instance("python")
-
- code = """
-text = "Hello, World!"
-print(text.upper())
-print(text.lower())
-print(text.replace("World", "Aliyun"))
-"""
- result = provider.execute_code(instance_id=instance.instance_id, code=code, language="python", timeout=30)
-
- assert result.exit_code == 0
- assert "HELLO, WORLD!" in result.stdout
- assert "hello, world!" in result.stdout
- assert "Hello, Aliyun!" in result.stdout
-
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"String manipulation test failed: {str(e)}")
-
- def test_context_persistence(self, provider):
- """Test code execution with context persistence."""
- try:
- instance = provider.create_instance("python")
-
- # First execution - define variable
- result1 = provider.execute_code(instance_id=instance.instance_id, code="x = 42\nprint(x)", language="python", timeout=30)
- assert result1.exit_code == 0
-
- # Second execution - use variable
- # Note: Context persistence depends on whether the contextId is reused
- result2 = provider.execute_code(instance_id=instance.instance_id, code="print(f'x is {x}')", language="python", timeout=30)
-
- # Context might or might not persist depending on API implementation
- assert result2.exit_code == 0
-
- provider.destroy_instance(instance.instance_id)
- except Exception as e:
- pytest.skip(f"Context persistence test failed: {str(e)}")
-
-
-def test_without_credentials():
- """Test that tests are skipped without credentials."""
- # This test should always run (not skipped)
- if all(
- [
- os.getenv("AGENTRUN_ACCESS_KEY_ID"),
- os.getenv("AGENTRUN_ACCESS_KEY_SECRET"),
- os.getenv("AGENTRUN_ACCOUNT_ID"),
- ]
- ):
- assert True # Credentials are set
- else:
- assert True # Credentials not set, test still passes
diff --git a/agent/sandbox/tests/test_providers.py b/agent/sandbox/tests/test_providers.py
deleted file mode 100644
index 9ed0117386..0000000000
--- a/agent/sandbox/tests/test_providers.py
+++ /dev/null
@@ -1,456 +0,0 @@
-#
-# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-"""
-Unit tests for sandbox provider abstraction layer.
-"""
-
-from unittest.mock import Mock, patch
-
-import pytest
-import requests
-from agent.sandbox.providers.base import ExecutionResult, SandboxInstance, SandboxProvider
-from agent.sandbox.providers.manager import ProviderManager
-from agent.sandbox.providers.self_managed import SelfManagedProvider
-
-
-class TestSandboxDataclasses:
- """Test sandbox dataclasses."""
-
- def test_sandbox_instance_creation(self):
- """Test SandboxInstance dataclass creation."""
- instance = SandboxInstance(instance_id="test-123", provider="self_managed", status="running", metadata={"language": "python"})
-
- assert instance.instance_id == "test-123"
- assert instance.provider == "self_managed"
- assert instance.status == "running"
- assert instance.metadata == {"language": "python"}
-
- def test_sandbox_instance_default_metadata(self):
- """Test SandboxInstance with None metadata."""
- instance = SandboxInstance(instance_id="test-123", provider="self_managed", status="running", metadata=None)
-
- assert instance.metadata == {}
-
- def test_execution_result_creation(self):
- """Test ExecutionResult dataclass creation."""
- result = ExecutionResult(stdout="Hello, World!", stderr="", exit_code=0, execution_time=1.5, metadata={"status": "success"})
-
- assert result.stdout == "Hello, World!"
- assert result.stderr == ""
- assert result.exit_code == 0
- assert result.execution_time == 1.5
- assert result.metadata == {"status": "success"}
-
- def test_execution_result_default_metadata(self):
- """Test ExecutionResult with None metadata."""
- result = ExecutionResult(stdout="output", stderr="error", exit_code=1, execution_time=0.5, metadata=None)
-
- assert result.metadata == {}
-
-
-class TestProviderManager:
- """Test ProviderManager functionality."""
-
- def test_manager_initialization(self):
- """Test ProviderManager initialization."""
- manager = ProviderManager()
-
- assert manager.current_provider is None
- assert manager.current_provider_name is None
- assert not manager.is_configured()
-
- def test_set_provider(self):
- """Test setting a provider."""
- manager = ProviderManager()
- mock_provider = Mock(spec=SandboxProvider)
-
- manager.set_provider("self_managed", mock_provider)
-
- assert manager.current_provider == mock_provider
- assert manager.current_provider_name == "self_managed"
- assert manager.is_configured()
-
- def test_get_provider(self):
- """Test getting the current provider."""
- manager = ProviderManager()
- mock_provider = Mock(spec=SandboxProvider)
-
- manager.set_provider("self_managed", mock_provider)
-
- assert manager.get_provider() == mock_provider
-
- def test_get_provider_name(self):
- """Test getting the current provider name."""
- manager = ProviderManager()
- mock_provider = Mock(spec=SandboxProvider)
-
- manager.set_provider("self_managed", mock_provider)
-
- assert manager.get_provider_name() == "self_managed"
-
- def test_get_provider_when_not_set(self):
- """Test getting provider when none is set."""
- manager = ProviderManager()
-
- assert manager.get_provider() is None
- assert manager.get_provider_name() is None
-
-
-class TestSelfManagedProvider:
- """Test SelfManagedProvider implementation."""
-
- def test_provider_initialization(self):
- """Test provider initialization."""
- provider = SelfManagedProvider()
-
- assert provider.endpoint == "http://sandbox-executor-manager:9385"
- assert provider.timeout == 30
- assert provider.max_retries == 3
- assert provider.pool_size == 3
- assert not provider._initialized
-
- @patch("requests.get")
- def test_initialize_success(self, mock_get):
- """Test successful initialization."""
- mock_response = Mock()
- mock_response.status_code = 200
- mock_get.return_value = mock_response
-
- provider = SelfManagedProvider()
- result = provider.initialize({"endpoint": "http://test-endpoint:9385", "timeout": 60, "max_retries": 5, "pool_size": 20})
-
- assert result is True
- assert provider.endpoint == "http://test-endpoint:9385"
- assert provider.timeout == 60
- assert provider.max_retries == 5
- assert provider.pool_size == 20
- assert provider._initialized
- mock_get.assert_called_once_with("http://test-endpoint:9385/healthz", timeout=5)
-
- @patch("requests.get")
- def test_initialize_failure(self, mock_get):
- """Test initialization failure."""
- mock_get.side_effect = Exception("Connection error")
-
- provider = SelfManagedProvider()
- result = provider.initialize({"endpoint": "http://invalid:9385"})
-
- assert result is False
- assert not provider._initialized
-
- def test_initialize_default_config(self):
- """Test initialization with default config."""
- with patch("requests.get") as mock_get:
- mock_response = Mock()
- mock_response.status_code = 200
- mock_get.return_value = mock_response
-
- provider = SelfManagedProvider()
- result = provider.initialize({})
-
- assert result is True
- assert provider.endpoint == "http://sandbox-executor-manager:9385"
- assert provider.timeout == 30
-
- def test_create_instance_python(self):
- """Test creating a Python instance."""
- provider = SelfManagedProvider()
- provider._initialized = True
-
- instance = provider.create_instance("python")
-
- assert instance.provider == "self_managed"
- assert instance.status == "running"
- assert instance.metadata["language"] == "python"
- assert instance.metadata["endpoint"] == "http://sandbox-executor-manager:9385"
- assert len(instance.instance_id) > 0 # Verify instance_id exists
-
- def test_create_instance_nodejs(self):
- """Test creating a Node.js instance."""
- provider = SelfManagedProvider()
- provider._initialized = True
-
- instance = provider.create_instance("nodejs")
-
- assert instance.metadata["language"] == "nodejs"
-
- def test_create_instance_not_initialized(self):
- """Test creating instance when provider not initialized."""
- provider = SelfManagedProvider()
-
- with pytest.raises(RuntimeError, match="Provider not initialized"):
- provider.create_instance("python")
-
- @patch("requests.post")
- def test_execute_code_success(self, mock_post):
- """Test successful code execution."""
- mock_response = Mock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"status": "success", "stdout": '{"result": 42}', "stderr": "", "exit_code": 0, "time_used_ms": 100.0, "memory_used_kb": 1024.0}
- mock_post.return_value = mock_response
-
- provider = SelfManagedProvider()
- provider._initialized = True
-
- result = provider.execute_code(instance_id="test-123", code="def main(): return {'result': 42}", language="python", timeout=10)
-
- assert result.stdout == '{"result": 42}'
- assert result.stderr == ""
- assert result.exit_code == 0
- assert result.execution_time > 0
- assert result.metadata["status"] == "success"
- assert result.metadata["instance_id"] == "test-123"
-
- @patch("requests.post")
- def test_execute_code_maps_structured_result_into_metadata(self, mock_post):
- """Test successful code execution with structured result envelope."""
- mock_response = Mock()
- mock_response.status_code = 200
- mock_response.json.return_value = {
- "status": "success",
- "stdout": "debug line\n",
- "stderr": "",
- "exit_code": 0,
- "time_used_ms": 100.0,
- "memory_used_kb": 1024.0,
- "result": {
- "present": True,
- "value": {"items": ["a", "b"]},
- "type": "json",
- },
- }
- mock_post.return_value = mock_response
-
- provider = SelfManagedProvider()
- provider._initialized = True
-
- result = provider.execute_code(instance_id="test-123", code="def main(): return {'items': ['a', 'b']}", language="python", timeout=10)
-
- assert result.stdout == "debug line\n"
- assert result.metadata["result_present"] is True
- assert result.metadata["result_value"] == {"items": ["a", "b"]}
- assert result.metadata["result_type"] == "json"
-
- @patch("requests.post")
- def test_execute_code_sends_bearer_token_when_configured(self, mock_post):
- """Test that the shared-secret token is sent to the executor manager."""
- mock_response = Mock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"status": "success", "stdout": "", "stderr": "", "exit_code": 0}
- mock_post.return_value = mock_response
-
- provider = SelfManagedProvider()
- provider._initialized = True
- provider.api_token = "shared-secret"
-
- provider.execute_code(instance_id="test-123", code="def main(): return 1", language="python", timeout=10)
-
- _, kwargs = mock_post.call_args
- assert kwargs["headers"]["Authorization"] == "Bearer shared-secret"
-
- @patch("requests.post")
- def test_execute_code_omits_auth_header_without_token(self, mock_post):
- """Test that no Authorization header is sent when no token is set."""
- mock_response = Mock()
- mock_response.status_code = 200
- mock_response.json.return_value = {"status": "success", "stdout": "", "stderr": "", "exit_code": 0}
- mock_post.return_value = mock_response
-
- provider = SelfManagedProvider()
- provider._initialized = True
- provider.api_token = ""
-
- provider.execute_code(instance_id="test-123", code="def main(): return 1", language="python", timeout=10)
-
- _, kwargs = mock_post.call_args
- assert "Authorization" not in kwargs["headers"]
-
- @patch("requests.post")
- def test_execute_code_timeout(self, mock_post):
- """Test code execution timeout."""
- mock_post.side_effect = requests.Timeout()
-
- provider = SelfManagedProvider()
- provider._initialized = True
-
- with pytest.raises(TimeoutError, match="Execution timed out"):
- provider.execute_code(instance_id="test-123", code="while True: pass", language="python", timeout=5)
-
- @patch("requests.post")
- def test_execute_code_http_error(self, mock_post):
- """Test code execution with HTTP error."""
- mock_response = Mock()
- mock_response.status_code = 500
- mock_response.text = "Internal Server Error"
- mock_post.return_value = mock_response
-
- provider = SelfManagedProvider()
- provider._initialized = True
-
- with pytest.raises(RuntimeError, match="HTTP 500"):
- provider.execute_code(instance_id="test-123", code="invalid code", language="python")
-
- def test_execute_code_not_initialized(self):
- """Test executing code when provider not initialized."""
- provider = SelfManagedProvider()
-
- with pytest.raises(RuntimeError, match="Provider not initialized"):
- provider.execute_code(instance_id="test-123", code="print('hello')", language="python")
-
- def test_destroy_instance(self):
- """Test destroying an instance (no-op for self-managed)."""
- provider = SelfManagedProvider()
- provider._initialized = True
-
- # For self-managed, destroy_instance is a no-op
- result = provider.destroy_instance("test-123")
-
- assert result is True
-
- @patch("requests.get")
- def test_health_check_success(self, mock_get):
- """Test successful health check."""
- mock_response = Mock()
- mock_response.status_code = 200
- mock_get.return_value = mock_response
-
- provider = SelfManagedProvider()
-
- result = provider.health_check()
-
- assert result is True
- mock_get.assert_called_once_with("http://sandbox-executor-manager:9385/healthz", timeout=5)
-
- @patch("requests.get")
- def test_health_check_failure(self, mock_get):
- """Test health check failure."""
- mock_get.side_effect = Exception("Connection error")
-
- provider = SelfManagedProvider()
-
- result = provider.health_check()
-
- assert result is False
-
- def test_get_supported_languages(self):
- """Test getting supported languages."""
- provider = SelfManagedProvider()
-
- languages = provider.get_supported_languages()
-
- assert "python" in languages
- assert "nodejs" in languages
- assert "javascript" in languages
-
- def test_get_config_schema(self, monkeypatch):
- """Test getting configuration schema."""
- monkeypatch.delenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", raising=False)
- schema = SelfManagedProvider.get_config_schema()
-
- assert "endpoint" in schema
- assert schema["endpoint"]["type"] == "string"
- assert schema["endpoint"]["required"] is True
- assert schema["endpoint"]["default"] == "http://sandbox-executor-manager:9385"
-
- assert "timeout" in schema
- assert schema["timeout"]["type"] == "integer"
- assert schema["timeout"]["default"] == 30
-
- # The pool size is a deployment-level fact, not a writable runtime field, so the schema
- # exposes it read-only under its real key. The default it reports is read from this
- # process's own environment and falls back to 3, which can disagree with the pool
- # sandbox-executor-manager was actually started with. Asserting a writable `pool_size`
- # pinned a shape the provider has never returned, and the assertion failed rather than
- # guarding anything.
- assert "executor_manager_pool_size" in schema
- assert schema["executor_manager_pool_size"]["type"] == "integer"
- assert schema["executor_manager_pool_size"]["scope"] == "deployment"
- assert schema["executor_manager_pool_size"]["readonly"] is True
- assert schema["executor_manager_pool_size"]["default"] == 3
- assert isinstance(schema["executor_manager_pool_size"]["default"], int)
- assert "pool_size" not in schema
-
- # `max_retries` is documented, accepted and range-checked by the provider
- # (`self_managed.py:58`, `:66`, `:386`) but get_config_schema() does not offer it, so the
- # admin form cannot set it. The assertion here used to require it and had been failing;
- # recording its absence keeps that gap visible rather than deleting the observation, and
- # turns red the moment the schema grows the field.
- assert "max_retries" not in schema
-
- monkeypatch.setenv("SANDBOX_EXECUTOR_MANAGER_POOL_SIZE", "11")
- schema = SelfManagedProvider.get_config_schema()
- assert schema["executor_manager_pool_size"]["default"] == 11
- assert isinstance(schema["executor_manager_pool_size"]["default"], int)
-
- def test_normalize_language_python(self):
- """Test normalizing Python language identifier."""
- provider = SelfManagedProvider()
-
- assert provider._normalize_language("python") == "python"
- assert provider._normalize_language("python3") == "python"
- assert provider._normalize_language("PYTHON") == "python"
- assert provider._normalize_language("Python3") == "python"
-
- def test_normalize_language_javascript(self):
- """Test normalizing JavaScript language identifier."""
- provider = SelfManagedProvider()
-
- assert provider._normalize_language("javascript") == "nodejs"
- assert provider._normalize_language("nodejs") == "nodejs"
- assert provider._normalize_language("JavaScript") == "nodejs"
- assert provider._normalize_language("NodeJS") == "nodejs"
-
- def test_normalize_language_default(self):
- """Test language normalization with empty/unknown input."""
- provider = SelfManagedProvider()
-
- assert provider._normalize_language("") == "python"
- assert provider._normalize_language(None) == "python"
- assert provider._normalize_language("unknown") == "unknown"
-
-
-class TestProviderInterface:
- """Test that providers correctly implement the interface."""
-
- def test_self_managed_provider_is_abstract(self):
- """Test that SelfManagedProvider is a SandboxProvider."""
- provider = SelfManagedProvider()
-
- assert isinstance(provider, SandboxProvider)
-
- def test_self_managed_provider_has_abstract_methods(self):
- """Test that SelfManagedProvider implements all abstract methods."""
- provider = SelfManagedProvider()
-
- # Check all abstract methods are implemented
- assert hasattr(provider, "initialize")
- assert callable(provider.initialize)
-
- assert hasattr(provider, "create_instance")
- assert callable(provider.create_instance)
-
- assert hasattr(provider, "execute_code")
- assert callable(provider.execute_code)
-
- assert hasattr(provider, "destroy_instance")
- assert callable(provider.destroy_instance)
-
- assert hasattr(provider, "health_check")
- assert callable(provider.health_check)
-
- assert hasattr(provider, "get_supported_languages")
- assert callable(provider.get_supported_languages)
diff --git a/agent/sandbox/tests/test_security.py b/agent/sandbox/tests/test_security.py
deleted file mode 100644
index 95a4ee35d4..0000000000
--- a/agent/sandbox/tests/test_security.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#
-# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-import sys
-from pathlib import Path
-
-
-EXECUTOR_MANAGER_ROOT = Path(__file__).resolve().parents[1] / "executor_manager"
-if str(EXECUTOR_MANAGER_ROOT) not in sys.path:
- sys.path.insert(0, str(EXECUTOR_MANAGER_ROOT))
-
-from models.enums import SupportLanguage # noqa: E402
-from services.security import analyze_code_security # noqa: E402
-
-
-def test_javascript_child_process_is_rejected():
- is_safe, issues = analyze_code_security(
- "const cp = require('child_process'); async function main() { return 'ok'; }",
- SupportLanguage.NODEJS,
- )
-
- assert is_safe is False
- assert any("child_process" in issue for issue, _ in issues)
-
-
-def test_javascript_eval_is_rejected():
- is_safe, issues = analyze_code_security(
- "async function main() { return eval('1+1'); }",
- SupportLanguage.NODEJS,
- )
-
- assert is_safe is False
- assert any("eval" in issue.lower() for issue, _ in issues)
-
-
-def test_javascript_child_process_template_literal_is_rejected():
- """Template literal backticks bypass single/double-quote regex patterns."""
- is_safe, issues = analyze_code_security(
- "const cp = require(`child_process`); async function main() { return 'ok'; }",
- SupportLanguage.NODEJS,
- )
-
- assert is_safe is False
- assert any("child_process" in issue for issue, _ in issues)
-
-
-def test_javascript_fs_template_literal_is_rejected():
- is_safe, issues = analyze_code_security(
- "const fs = require(`fs`); async function main() { return fs.readFileSync('/etc/passwd', 'utf8'); }",
- SupportLanguage.NODEJS,
- )
-
- assert is_safe is False
- assert any("fs" in issue for issue, _ in issues)
-
-
-def test_python_builtins_import_is_rejected():
- """builtins module gives access to eval/exec and must be blocked."""
- is_safe, issues = analyze_code_security(
- "import builtins\ndef main():\n builtins.eval('1+1')",
- SupportLanguage.PYTHON,
- )
-
- assert is_safe is False
- # Pin the specific reason: rejection must come from the new ``builtins``
- # entry in ``DANGEROUS_IMPORTS``, not from some unrelated parse error.
- assert any("builtins" in issue for issue, _ in issues), f"expected an issue mentioning 'builtins', got {issues!r}"
-
-
-def test_python_attribute_eval_call_is_rejected():
- """Attribute-style dangerous calls (builtins.eval) must be caught."""
- is_safe, issues = analyze_code_security(
- "import builtins\ndef main():\n builtins.exec('import os')",
- SupportLanguage.PYTHON,
- )
-
- assert is_safe is False
- # Pin the specific reason: rejection must come from the new
- # ``ast.Attribute`` branch in ``visit_Call`` flagging the ``exec`` call,
- # not from the ``import builtins`` line above. We assert ``exec`` is in at
- # least one finding so the test fails if visit_Call's attribute branch is
- # ever reverted.
- assert any("exec" in issue for issue, _ in issues), f"expected an issue mentioning 'exec', got {issues!r}"
-
-
-def test_javascript_safe_code_still_passes():
- is_safe, issues = analyze_code_security(
- "async function main(args) { return { answer: args.value ?? null }; }",
- SupportLanguage.NODEJS,
- )
-
- assert is_safe is True
- assert issues == []
diff --git a/agent/sandbox/tests/verify_sdk.py b/agent/sandbox/tests/verify_sdk.py
deleted file mode 100644
index e3ebf16066..0000000000
--- a/agent/sandbox/tests/verify_sdk.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#!/usr/bin/env python3
-"""
-Quick verification script for Aliyun Code Interpreter provider using official SDK.
-"""
-
-import importlib.util
-import sys
-
-sys.path.insert(0, ".")
-
-print("=" * 60)
-print("Aliyun Code Interpreter Provider - SDK Verification")
-print("=" * 60)
-
-# Test 1: Import provider
-print("\n[1/5] Testing provider import...")
-try:
- from agent.sandbox.providers.aliyun_codeinterpreter import AliyunCodeInterpreterProvider
-
- print("βœ“ Provider imported successfully")
-except ImportError as e:
- print(f"βœ— Import failed: {e}")
- sys.exit(1)
-
-# Test 2: Check provider class
-print("\n[2/5] Testing provider class...")
-provider = AliyunCodeInterpreterProvider()
-assert hasattr(provider, "initialize")
-assert hasattr(provider, "create_instance")
-assert hasattr(provider, "execute_code")
-assert hasattr(provider, "destroy_instance")
-assert hasattr(provider, "health_check")
-print("βœ“ Provider has all required methods")
-
-# Test 3: Check SDK imports
-print("\n[3/5] Testing SDK imports...")
-try:
- # Check if agentrun SDK is available using importlib
- if importlib.util.find_spec("agentrun.sandbox") is None or importlib.util.find_spec("agentrun.utils.config") is None or importlib.util.find_spec("agentrun.utils.exception") is None:
- raise ImportError("agentrun SDK not found")
-
- # Verify imports work (assign to _ to indicate they're intentionally unused)
- from agentrun.sandbox import CodeInterpreterSandbox, TemplateType, CodeLanguage
- from agentrun.utils.config import Config
- from agentrun.utils.exception import ServerError
-
- _ = (CodeInterpreterSandbox, TemplateType, CodeLanguage, Config, ServerError)
-
- print("βœ“ SDK modules imported successfully")
-except ImportError as e:
- print(f"βœ— SDK import failed: {e}")
- sys.exit(1)
-
-# Test 4: Check config schema
-print("\n[4/5] Testing configuration schema...")
-schema = AliyunCodeInterpreterProvider.get_config_schema()
-required_fields = ["access_key_id", "access_key_secret", "account_id"]
-for field in required_fields:
- assert field in schema
- assert schema[field]["required"] is True
-print(f"βœ“ All required fields present: {', '.join(required_fields)}")
-
-# Test 5: Check supported languages
-print("\n[5/5] Testing supported languages...")
-languages = provider.get_supported_languages()
-assert "python" in languages
-assert "javascript" in languages
-print(f"βœ“ Supported languages: {', '.join(languages)}")
-
-print("\n" + "=" * 60)
-print("All verification tests passed! βœ“")
-print("=" * 60)
-print("\nNote: This provider now uses the official agentrun-sdk.")
-print("SDK Documentation: https://github.com/Serverless-Devs/agentrun-sdk-python")
-print("API Documentation: https://help.aliyun.com/zh/functioncompute/fc/sandbox-sandbox-code-interepreter")
diff --git a/agent/sandbox/uv.lock b/agent/sandbox/uv.lock
deleted file mode 100644
index 3147961e93..0000000000
--- a/agent/sandbox/uv.lock
+++ /dev/null
@@ -1,396 +0,0 @@
-version = 1
-revision = 3
-requires-python = "==3.13.*"
-
-[[package]]
-name = "annotated-doc"
-version = "0.0.4"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/57/ba/046ceea27344560984e26a590f90bc7f4a75b06701f653222458922b558c/annotated_doc-0.0.4.tar.gz", hash = "sha256:fbcda96e87e9c92ad167c2e53839e57503ecfda18804ea28102353485033faa4", size = 7288, upload-time = "2025-11-10T22:07:42.062Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/1e/d3/26bf1008eb3d2daa8ef4cacc7f3bfdc11818d111f7e2d0201bc6e3b49d45/annotated_doc-0.0.4-py3-none-any.whl", hash = "sha256:571ac1dc6991c450b25a9c2d84a3705e2ae7a53467b5d111c24fa8baabbed320", size = 5303, upload-time = "2025-11-10T22:07:40.673Z" },
-]
-
-[[package]]
-name = "annotated-types"
-version = "0.7.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081, upload-time = "2024-05-20T21:33:25.928Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" },
-]
-
-[[package]]
-name = "anyio"
-version = "4.14.2"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "idna" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" },
-]
-
-[[package]]
-name = "basedpyright"
-version = "1.29.1"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "nodejs-wheel-binaries" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/b9/18/f5e488eac4960ad9a2e71b95f0d91cf93a982c7f68aa90e4e0554f0bc37e/basedpyright-1.29.1.tar.gz", hash = "sha256:06bbe6c3b50ab4af20f80e154049477a50d8b81d2522eadbc9f472f2f92cd44b", size = 21773469, upload-time = "2025-04-23T13:29:42.47Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/95/1b/1bb837bbb7e259928f33d3c105dfef4f5349ef08b3ef45576801256e3234/basedpyright-1.29.1-py3-none-any.whl", hash = "sha256:b7eb65b9d4aaeeea29a349ac494252032a75a364942d0ac466d7f07ddeacc786", size = 11397959, upload-time = "2025-04-23T13:29:38.106Z" },
-]
-
-[[package]]
-name = "certifi"
-version = "2025.4.26"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/e8/9e/c05b3920a3b7d20d3d3310465f50348e5b3694f4f88c6daf736eef3024c4/certifi-2025.4.26.tar.gz", hash = "sha256:0a816057ea3cdefcef70270d2c515e4506bbc954f417fa5ade2021213bb8f0c6", size = 160705, upload-time = "2025-04-26T02:12:29.51Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/4a/7e/3db2bd1b1f9e95f7cddca6d6e75e2f2bd9f51b1246e546d88addca0106bd/certifi-2025.4.26-py3-none-any.whl", hash = "sha256:30350364dfe371162649852c63336a15c70c6510c2ad5015b21c2345311805f3", size = 159618, upload-time = "2025-04-26T02:12:27.662Z" },
-]
-
-[[package]]
-name = "charset-normalizer"
-version = "3.4.2"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367, upload-time = "2025-05-02T08:34:42.01Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622, upload-time = "2025-05-02T08:32:56.363Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435, upload-time = "2025-05-02T08:32:58.551Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653, upload-time = "2025-05-02T08:33:00.342Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231, upload-time = "2025-05-02T08:33:02.081Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243, upload-time = "2025-05-02T08:33:04.063Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442, upload-time = "2025-05-02T08:33:06.418Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147, upload-time = "2025-05-02T08:33:08.183Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057, upload-time = "2025-05-02T08:33:09.986Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454, upload-time = "2025-05-02T08:33:11.814Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174, upload-time = "2025-05-02T08:33:13.707Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166, upload-time = "2025-05-02T08:33:15.458Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064, upload-time = "2025-05-02T08:33:17.06Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641, upload-time = "2025-05-02T08:33:18.753Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626, upload-time = "2025-05-02T08:34:40.053Z" },
-]
-
-[[package]]
-name = "click"
-version = "8.1.8"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "colorama", marker = "sys_platform == 'win32'" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/b9/2e/0090cbf739cee7d23781ad4b89a9894a41538e4fcf4c31dcdd705b78eb8b/click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a", size = 226593, upload-time = "2024-12-21T18:38:44.339Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/7e/d4/7ebdbd03970677812aac39c869717059dbb71a4cfc033ca6e5221787892c/click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2", size = 98188, upload-time = "2024-12-21T18:38:41.666Z" },
-]
-
-[[package]]
-name = "colorama"
-version = "0.4.6"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
-]
-
-[[package]]
-name = "deprecated"
-version = "1.2.18"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "wrapt" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/98/97/06afe62762c9a8a86af0cfb7bfdab22a43ad17138b07af5b1a58442690a2/deprecated-1.2.18.tar.gz", hash = "sha256:422b6f6d859da6f2ef57857761bfb392480502a64c3028ca9bbe86085d72115d", size = 2928744, upload-time = "2025-01-27T10:46:25.7Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/6e/c6/ac0b6c1e2d138f1002bcf799d330bd6d85084fece321e662a14223794041/Deprecated-1.2.18-py2.py3-none-any.whl", hash = "sha256:bd5011788200372a32418f888e326a09ff80d0214bd961147cfed01b5c018eec", size = 9998, upload-time = "2025-01-27T10:46:09.186Z" },
-]
-
-[[package]]
-name = "fastapi"
-version = "0.128.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "annotated-doc" },
- { name = "pydantic" },
- { name = "starlette" },
- { name = "typing-extensions" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/52/08/8c8508db6c7b9aae8f7175046af41baad690771c9bcde676419965e338c7/fastapi-0.128.0.tar.gz", hash = "sha256:1cc179e1cef10a6be60ffe429f79b829dce99d8de32d7acb7e6c8dfdf7f2645a", size = 365682, upload-time = "2025-12-27T15:21:13.714Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/5c/05/5cbb59154b093548acd0f4c7c474a118eda06da25aa75c616b72d8fcd92a/fastapi-0.128.0-py3-none-any.whl", hash = "sha256:aebd93f9716ee3b4f4fcfe13ffb7cf308d99c9f3ab5622d8877441072561582d", size = 103094, upload-time = "2025-12-27T15:21:12.154Z" },
-]
-
-[[package]]
-name = "gvisor-sandbox"
-version = "0.1.0"
-source = { virtual = "." }
-dependencies = [
- { name = "fastapi" },
- { name = "httpx" },
- { name = "pydantic" },
- { name = "requests" },
- { name = "slowapi" },
- { name = "uvicorn" },
-]
-
-[package.dev-dependencies]
-dev = [
- { name = "basedpyright" },
-]
-
-[package.metadata]
-requires-dist = [
- { name = "fastapi", specifier = ">=0.115.12" },
- { name = "httpx", specifier = ">=0.28.1" },
- { name = "pydantic", specifier = ">=2.11.4" },
- { name = "requests", specifier = ">=2.32.4" },
- { name = "slowapi", specifier = ">=0.1.9" },
- { name = "uvicorn", specifier = ">=0.34.2" },
-]
-
-[package.metadata.requires-dev]
-dev = [{ name = "basedpyright", specifier = ">=1.29.1" }]
-
-[[package]]
-name = "h11"
-version = "0.16.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
-]
-
-[[package]]
-name = "httpcore"
-version = "1.0.9"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "certifi" },
- { name = "h11" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
-]
-
-[[package]]
-name = "httpx"
-version = "0.28.1"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "anyio" },
- { name = "certifi" },
- { name = "httpcore" },
- { name = "idna" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" },
-]
-
-[[package]]
-name = "idna"
-version = "3.10"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490, upload-time = "2024-09-15T18:07:39.745Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442, upload-time = "2024-09-15T18:07:37.964Z" },
-]
-
-[[package]]
-name = "limits"
-version = "5.1.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "deprecated" },
- { name = "packaging" },
- { name = "typing-extensions" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/c6/94/a04e64f487a56f97aff67c53df609cc19d5c3f3e7e5697ec8a1ff8413829/limits-5.1.0.tar.gz", hash = "sha256:b298e4af0b47997da03cbeee9df027ddc2328f8630546125e81083bb56311827", size = 94655, upload-time = "2025-04-23T18:59:44.457Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/de/00/876a5ec60addda62ee13ac4b588a5afc0d1a86a431645a91711ceae834cf/limits-5.1.0-py3-none-any.whl", hash = "sha256:f368d4572ac3ef8190cb8b9911ed481175a0b4189894a63cac95cae39ebeb147", size = 60472, upload-time = "2025-04-23T18:59:42.266Z" },
-]
-
-[[package]]
-name = "nodejs-wheel-binaries"
-version = "22.15.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/45/5b/6c5f973765b96793d4e4d03684bcbd273b17e471ecc7e9bec4c32b595ebd/nodejs_wheel_binaries-22.15.0.tar.gz", hash = "sha256:ff81aa2a79db279c2266686ebcb829b6634d049a5a49fc7dc6921e4f18af9703", size = 8054, upload-time = "2025-04-23T16:57:40.338Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/d3/a8/a32e5bb99e95c536e7dac781cffab1e7e9f8661b8ee296b93df77e4df7f9/nodejs_wheel_binaries-22.15.0-py2.py3-none-macosx_11_0_arm64.whl", hash = "sha256:aa16366d48487fff89446fb237693e777aa2ecd987208db7d4e35acc40c3e1b1", size = 50514526, upload-time = "2025-04-23T16:57:07.478Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/05/e8/eb024dbb3a7d3b98c8922d1c306be989befad4d2132292954cb902f43b07/nodejs_wheel_binaries-22.15.0-py2.py3-none-macosx_11_0_x86_64.whl", hash = "sha256:a54bb3fee9170003fa8abc69572d819b2b1540344eff78505fcc2129a9175596", size = 51409179, upload-time = "2025-04-23T16:57:11.599Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/3f/0f/baa968456c3577e45c7d0e3715258bd175dcecc67b683a41a5044d5dae40/nodejs_wheel_binaries-22.15.0-py2.py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:867121ccf99d10523f6878a26db86e162c4939690e24cfb5bea56d01ea696c93", size = 57364460, upload-time = "2025-04-23T16:57:15.725Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/2f/a2/977f63cd07ed8fc27bc0d0cd72e801fc3691ffc8cd40a51496ff18a6d0a2/nodejs_wheel_binaries-22.15.0-py2.py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0ab0fbcda2ddc8aab7db1505d72cb958f99324b3834c4543541a305e02bfe860", size = 57889101, upload-time = "2025-04-23T16:57:19.643Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/67/7f/57b9c24a4f0d25490527b043146aa0fdff2d8fdc82f90667cdaf6f00cfc9/nodejs_wheel_binaries-22.15.0-py2.py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:2bde1d8e00cd955b9ce9ee9ac08309923e2778a790ee791b715e93e487e74bfd", size = 59190817, upload-time = "2025-04-23T16:57:23.875Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/fd/7f/970acbe33b81c22b3c7928f52e32347030aa46d23d779cf781cf9a9cf557/nodejs_wheel_binaries-22.15.0-py2.py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:acdd4ef73b6701aab9fbe02ac5e104f208a5e3c300402fa41ad7bc7f49499fbf", size = 60220316, upload-time = "2025-04-23T16:57:28.276Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/07/4c/030243c04bb60f0de66c2d7ee3be289c6d28ef09113c06ffa417bdfedf8f/nodejs_wheel_binaries-22.15.0-py2.py3-none-win_amd64.whl", hash = "sha256:51deaf13ee474e39684ce8c066dfe86240edb94e7241950ca789befbbbcbd23d", size = 40718853, upload-time = "2025-04-23T16:57:32.651Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/1f/49/011d472814af4fabeaab7d7ce3d5a1a635a3dadc23ae404d1f546839ecb3/nodejs_wheel_binaries-22.15.0-py2.py3-none-win_arm64.whl", hash = "sha256:01a3fe4d60477f93bf21a44219db33548c75d7fed6dc6e6f4c05cf0adf015609", size = 36436645, upload-time = "2025-04-23T16:57:36.326Z" },
-]
-
-[[package]]
-name = "packaging"
-version = "25.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727, upload-time = "2025-04-19T11:48:59.673Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469, upload-time = "2025-04-19T11:48:57.875Z" },
-]
-
-[[package]]
-name = "pydantic"
-version = "2.11.4"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "annotated-types" },
- { name = "pydantic-core" },
- { name = "typing-extensions" },
- { name = "typing-inspection" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/77/ab/5250d56ad03884ab5efd07f734203943c8a8ab40d551e208af81d0257bf2/pydantic-2.11.4.tar.gz", hash = "sha256:32738d19d63a226a52eed76645a98ee07c1f410ee41d93b4afbfa85ed8111c2d", size = 786540, upload-time = "2025-04-29T20:38:55.02Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/e7/12/46b65f3534d099349e38ef6ec98b1a5a81f42536d17e0ba382c28c67ba67/pydantic-2.11.4-py3-none-any.whl", hash = "sha256:d9615eaa9ac5a063471da949c8fc16376a84afb5024688b3ff885693506764eb", size = 443900, upload-time = "2025-04-29T20:38:52.724Z" },
-]
-
-[[package]]
-name = "pydantic-core"
-version = "2.33.2"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "typing-extensions" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ad/88/5f2260bdfae97aabf98f1778d43f69574390ad787afb646292a638c923d4/pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc", size = 435195, upload-time = "2025-04-23T18:33:52.104Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/46/8c/99040727b41f56616573a28771b1bfa08a3d3fe74d3d513f01251f79f172/pydantic_core-2.33.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:1082dd3e2d7109ad8b7da48e1d4710c8d06c253cbc4a27c1cff4fbcaa97a9e3f", size = 2015688, upload-time = "2025-04-23T18:31:53.175Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/3a/cc/5999d1eb705a6cefc31f0b4a90e9f7fc400539b1a1030529700cc1b51838/pydantic_core-2.33.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f517ca031dfc037a9c07e748cefd8d96235088b83b4f4ba8939105d20fa1dcd6", size = 1844808, upload-time = "2025-04-23T18:31:54.79Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/6f/5e/a0a7b8885c98889a18b6e376f344da1ef323d270b44edf8174d6bce4d622/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a9f2c9dd19656823cb8250b0724ee9c60a82f3cdf68a080979d13092a3b0fef", size = 1885580, upload-time = "2025-04-23T18:31:57.393Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/3b/2a/953581f343c7d11a304581156618c3f592435523dd9d79865903272c256a/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2b0a451c263b01acebe51895bfb0e1cc842a5c666efe06cdf13846c7418caa9a", size = 1973859, upload-time = "2025-04-23T18:31:59.065Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/e6/55/f1a813904771c03a3f97f676c62cca0c0a4138654107c1b61f19c644868b/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1ea40a64d23faa25e62a70ad163571c0b342b8bf66d5fa612ac0dec4f069d916", size = 2120810, upload-time = "2025-04-23T18:32:00.78Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/aa/c3/053389835a996e18853ba107a63caae0b9deb4a276c6b472931ea9ae6e48/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0fb2d542b4d66f9470e8065c5469ec676978d625a8b7a363f07d9a501a9cb36a", size = 2676498, upload-time = "2025-04-23T18:32:02.418Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/eb/3c/f4abd740877a35abade05e437245b192f9d0ffb48bbbbd708df33d3cda37/pydantic_core-2.33.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9fdac5d6ffa1b5a83bca06ffe7583f5576555e6c8b3a91fbd25ea7780f825f7d", size = 2000611, upload-time = "2025-04-23T18:32:04.152Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/59/a7/63ef2fed1837d1121a894d0ce88439fe3e3b3e48c7543b2a4479eb99c2bd/pydantic_core-2.33.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:04a1a413977ab517154eebb2d326da71638271477d6ad87a769102f7c2488c56", size = 2107924, upload-time = "2025-04-23T18:32:06.129Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/04/8f/2551964ef045669801675f1cfc3b0d74147f4901c3ffa42be2ddb1f0efc4/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c8e7af2f4e0194c22b5b37205bfb293d166a7344a5b0d0eaccebc376546d77d5", size = 2063196, upload-time = "2025-04-23T18:32:08.178Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/26/bd/d9602777e77fc6dbb0c7db9ad356e9a985825547dce5ad1d30ee04903918/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:5c92edd15cd58b3c2d34873597a1e20f13094f59cf88068adb18947df5455b4e", size = 2236389, upload-time = "2025-04-23T18:32:10.242Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/42/db/0e950daa7e2230423ab342ae918a794964b053bec24ba8af013fc7c94846/pydantic_core-2.33.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:65132b7b4a1c0beded5e057324b7e16e10910c106d43675d9bd87d4f38dde162", size = 2239223, upload-time = "2025-04-23T18:32:12.382Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/58/4d/4f937099c545a8a17eb52cb67fe0447fd9a373b348ccfa9a87f141eeb00f/pydantic_core-2.33.2-cp313-cp313-win32.whl", hash = "sha256:52fb90784e0a242bb96ec53f42196a17278855b0f31ac7c3cc6f5c1ec4811849", size = 1900473, upload-time = "2025-04-23T18:32:14.034Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a0/75/4a0a9bac998d78d889def5e4ef2b065acba8cae8c93696906c3a91f310ca/pydantic_core-2.33.2-cp313-cp313-win_amd64.whl", hash = "sha256:c083a3bdd5a93dfe480f1125926afcdbf2917ae714bdb80b36d34318b2bec5d9", size = 1955269, upload-time = "2025-04-23T18:32:15.783Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/f9/86/1beda0576969592f1497b4ce8e7bc8cbdf614c352426271b1b10d5f0aa64/pydantic_core-2.33.2-cp313-cp313-win_arm64.whl", hash = "sha256:e80b087132752f6b3d714f041ccf74403799d3b23a72722ea2e6ba2e892555b9", size = 1893921, upload-time = "2025-04-23T18:32:18.473Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a4/7d/e09391c2eebeab681df2b74bfe6c43422fffede8dc74187b2b0bf6fd7571/pydantic_core-2.33.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:61c18fba8e5e9db3ab908620af374db0ac1baa69f0f32df4f61ae23f15e586ac", size = 1806162, upload-time = "2025-04-23T18:32:20.188Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/f1/3d/847b6b1fed9f8ed3bb95a9ad04fbd0b212e832d4f0f50ff4d9ee5a9f15cf/pydantic_core-2.33.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95237e53bb015f67b63c91af7518a62a8660376a6a0db19b89acc77a4d6199f5", size = 1981560, upload-time = "2025-04-23T18:32:22.354Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/6f/9a/e73262f6c6656262b5fdd723ad90f518f579b7bc8622e43a942eec53c938/pydantic_core-2.33.2-cp313-cp313t-win_amd64.whl", hash = "sha256:c2fc0a768ef76c15ab9238afa6da7f69895bb5d1ee83aeea2e3509af4472d0b9", size = 1935777, upload-time = "2025-04-23T18:32:25.088Z" },
-]
-
-[[package]]
-name = "requests"
-version = "2.32.5"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "certifi" },
- { name = "charset-normalizer" },
- { name = "idna" },
- { name = "urllib3" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/c9/74/b3ff8e6c8446842c3f5c837e9c3dfcfe2018ea6ecef224c710c85ef728f4/requests-2.32.5.tar.gz", hash = "sha256:dbba0bac56e100853db0ea71b82b4dfd5fe2bf6d3754a8893c3af500cec7d7cf", size = 134517, upload-time = "2025-08-18T20:46:02.573Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6", size = 64738, upload-time = "2025-08-18T20:46:00.542Z" },
-]
-
-[[package]]
-name = "slowapi"
-version = "0.1.9"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "limits" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a0/99/adfc7f94ca024736f061257d39118e1542bade7a52e86415a4c4ae92d8ff/slowapi-0.1.9.tar.gz", hash = "sha256:639192d0f1ca01b1c6d95bf6c71d794c3a9ee189855337b4821f7f457dddad77", size = 14028, upload-time = "2024-02-05T12:11:52.13Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/2b/bb/f71c4b7d7e7eb3fc1e8c0458a8979b912f40b58002b9fbf37729b8cb464b/slowapi-0.1.9-py3-none-any.whl", hash = "sha256:cfad116cfb84ad9d763ee155c1e5c5cbf00b0d47399a769b227865f5df576e36", size = 14670, upload-time = "2024-02-05T12:11:50.898Z" },
-]
-
-[[package]]
-name = "starlette"
-version = "0.50.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "anyio" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ba/b8/73a0e6a6e079a9d9cfa64113d771e421640b6f679a52eeb9b32f72d871a1/starlette-0.50.0.tar.gz", hash = "sha256:a2a17b22203254bcbc2e1f926d2d55f3f9497f769416b3190768befe598fa3ca", size = 2646985, upload-time = "2025-11-01T15:25:27.516Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/d9/52/1064f510b141bd54025f9b55105e26d1fa970b9be67ad766380a3c9b74b0/starlette-0.50.0-py3-none-any.whl", hash = "sha256:9e5391843ec9b6e472eed1365a78c8098cfceb7a74bfd4d6b1c0c0095efb3bca", size = 74033, upload-time = "2025-11-01T15:25:25.461Z" },
-]
-
-[[package]]
-name = "typing-extensions"
-version = "4.13.2"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/f6/37/23083fcd6e35492953e8d2aaaa68b860eb422b34627b13f2ce3eb6106061/typing_extensions-4.13.2.tar.gz", hash = "sha256:e6c81219bd689f51865d9e372991c540bda33a0379d5573cddb9a3a23f7caaef", size = 106967, upload-time = "2025-04-10T14:19:05.416Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/8b/54/b1ae86c0973cc6f0210b53d508ca3641fb6d0c56823f288d108bc7ab3cc8/typing_extensions-4.13.2-py3-none-any.whl", hash = "sha256:a439e7c04b49fec3e5d3e2beaa21755cadbbdc391694e28ccdd36ca4a1408f8c", size = 45806, upload-time = "2025-04-10T14:19:03.967Z" },
-]
-
-[[package]]
-name = "typing-inspection"
-version = "0.4.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "typing-extensions" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/82/5c/e6082df02e215b846b4b8c0b887a64d7d08ffaba30605502639d44c06b82/typing_inspection-0.4.0.tar.gz", hash = "sha256:9765c87de36671694a67904bf2c96e395be9c6439bb6c87b5142569dcdd65122", size = 76222, upload-time = "2025-02-25T17:27:59.638Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/31/08/aa4fdfb71f7de5176385bd9e90852eaf6b5d622735020ad600f2bab54385/typing_inspection-0.4.0-py3-none-any.whl", hash = "sha256:50e72559fcd2a6367a19f7a7e610e6afcb9fac940c650290eed893d61386832f", size = 14125, upload-time = "2025-02-25T17:27:57.754Z" },
-]
-
-[[package]]
-name = "urllib3"
-version = "2.7.0"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" },
-]
-
-[[package]]
-name = "uvicorn"
-version = "0.34.2"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-dependencies = [
- { name = "click" },
- { name = "h11" },
-]
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a6/ae/9bbb19b9e1c450cf9ecaef06463e40234d98d95bf572fab11b4f19ae5ded/uvicorn-0.34.2.tar.gz", hash = "sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328", size = 76815, upload-time = "2025-04-19T06:02:50.101Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/b1/4b/4cef6ce21a2aaca9d852a6e84ef4f135d99fcd74fa75105e2fc0c8308acd/uvicorn-0.34.2-py3-none-any.whl", hash = "sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403", size = 62483, upload-time = "2025-04-19T06:02:48.42Z" },
-]
-
-[[package]]
-name = "wrapt"
-version = "1.17.2"
-source = { registry = "https://pypi.tuna.tsinghua.edu.cn/simple" }
-sdist = { url = "https://pypi.tuna.tsinghua.edu.cn/packages/c3/fc/e91cc220803d7bc4db93fb02facd8461c37364151b8494762cc88b0fbcef/wrapt-1.17.2.tar.gz", hash = "sha256:41388e9d4d1522446fe79d3213196bd9e3b301a336965b9e27ca2788ebd122f3", size = 55531, upload-time = "2025-01-14T10:35:45.465Z" }
-wheels = [
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ce/b9/0ffd557a92f3b11d4c5d5e0c5e4ad057bd9eb8586615cdaf901409920b14/wrapt-1.17.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6ed6ffac43aecfe6d86ec5b74b06a5be33d5bb9243d055141e8cabb12aa08125", size = 53800, upload-time = "2025-01-14T10:34:21.571Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/c0/ef/8be90a0b7e73c32e550c73cfb2fa09db62234227ece47b0e80a05073b375/wrapt-1.17.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:35621ae4c00e056adb0009f8e86e28eb4a41a4bfa8f9bfa9fca7d343fe94f998", size = 38824, upload-time = "2025-01-14T10:34:22.999Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/36/89/0aae34c10fe524cce30fe5fc433210376bce94cf74d05b0d68344c8ba46e/wrapt-1.17.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a604bf7a053f8362d27eb9fefd2097f82600b856d5abe996d623babd067b1ab5", size = 38920, upload-time = "2025-01-14T10:34:25.386Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/3b/24/11c4510de906d77e0cfb5197f1b1445d4fec42c9a39ea853d482698ac681/wrapt-1.17.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5cbabee4f083b6b4cd282f5b817a867cf0b1028c54d445b7ec7cfe6505057cf8", size = 88690, upload-time = "2025-01-14T10:34:28.058Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/71/d7/cfcf842291267bf455b3e266c0c29dcb675b5540ee8b50ba1699abf3af45/wrapt-1.17.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:49703ce2ddc220df165bd2962f8e03b84c89fee2d65e1c24a7defff6f988f4d6", size = 80861, upload-time = "2025-01-14T10:34:29.167Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/d5/66/5d973e9f3e7370fd686fb47a9af3319418ed925c27d72ce16b791231576d/wrapt-1.17.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8112e52c5822fc4253f3901b676c55ddf288614dc7011634e2719718eaa187dc", size = 89174, upload-time = "2025-01-14T10:34:31.702Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a7/d3/8e17bb70f6ae25dabc1aaf990f86824e4fd98ee9cadf197054e068500d27/wrapt-1.17.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9fee687dce376205d9a494e9c121e27183b2a3df18037f89d69bd7b35bcf59e2", size = 86721, upload-time = "2025-01-14T10:34:32.91Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/6f/54/f170dfb278fe1c30d0ff864513cff526d624ab8de3254b20abb9cffedc24/wrapt-1.17.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:18983c537e04d11cf027fbb60a1e8dfd5190e2b60cc27bc0808e653e7b218d1b", size = 79763, upload-time = "2025-01-14T10:34:34.903Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/4a/98/de07243751f1c4a9b15c76019250210dd3486ce098c3d80d5f729cba029c/wrapt-1.17.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:703919b1633412ab54bcf920ab388735832fdcb9f9a00ae49387f0fe67dad504", size = 87585, upload-time = "2025-01-14T10:34:36.13Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/f9/f0/13925f4bd6548013038cdeb11ee2cbd4e37c30f8bfd5db9e5a2a370d6e20/wrapt-1.17.2-cp313-cp313-win32.whl", hash = "sha256:abbb9e76177c35d4e8568e58650aa6926040d6a9f6f03435b7a522bf1c487f9a", size = 36676, upload-time = "2025-01-14T10:34:37.962Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/bf/ae/743f16ef8c2e3628df3ddfd652b7d4c555d12c84b53f3d8218498f4ade9b/wrapt-1.17.2-cp313-cp313-win_amd64.whl", hash = "sha256:69606d7bb691b50a4240ce6b22ebb319c1cfb164e5f6569835058196e0f3a845", size = 38871, upload-time = "2025-01-14T10:34:39.13Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/3d/bc/30f903f891a82d402ffb5fda27ec1d621cc97cb74c16fea0b6141f1d4e87/wrapt-1.17.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:4a721d3c943dae44f8e243b380cb645a709ba5bd35d3ad27bc2ed947e9c68192", size = 56312, upload-time = "2025-01-14T10:34:40.604Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/8a/04/c97273eb491b5f1c918857cd26f314b74fc9b29224521f5b83f872253725/wrapt-1.17.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:766d8bbefcb9e00c3ac3b000d9acc51f1b399513f44d77dfe0eb026ad7c9a19b", size = 40062, upload-time = "2025-01-14T10:34:45.011Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/4e/ca/3b7afa1eae3a9e7fefe499db9b96813f41828b9fdb016ee836c4c379dadb/wrapt-1.17.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e496a8ce2c256da1eb98bd15803a79bee00fc351f5dfb9ea82594a3f058309e0", size = 40155, upload-time = "2025-01-14T10:34:47.25Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/89/be/7c1baed43290775cb9030c774bc53c860db140397047cc49aedaf0a15477/wrapt-1.17.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40d615e4fe22f4ad3528448c193b218e077656ca9ccb22ce2cb20db730f8d306", size = 113471, upload-time = "2025-01-14T10:34:50.934Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/32/98/4ed894cf012b6d6aae5f5cc974006bdeb92f0241775addad3f8cd6ab71c8/wrapt-1.17.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a5aaeff38654462bc4b09023918b7f21790efb807f54c000a39d41d69cf552cb", size = 101208, upload-time = "2025-01-14T10:34:52.297Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/ea/fd/0c30f2301ca94e655e5e057012e83284ce8c545df7661a78d8bfca2fac7a/wrapt-1.17.2-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9a7d15bbd2bc99e92e39f49a04653062ee6085c0e18b3b7512a4f2fe91f2d681", size = 109339, upload-time = "2025-01-14T10:34:53.489Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/75/56/05d000de894c4cfcb84bcd6b1df6214297b8089a7bd324c21a4765e49b14/wrapt-1.17.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e3890b508a23299083e065f435a492b5435eba6e304a7114d2f919d400888cc6", size = 110232, upload-time = "2025-01-14T10:34:55.327Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/53/f8/c3f6b2cf9b9277fb0813418e1503e68414cd036b3b099c823379c9575e6d/wrapt-1.17.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:8c8b293cd65ad716d13d8dd3624e42e5a19cc2a2f1acc74b30c2c13f15cb61a6", size = 100476, upload-time = "2025-01-14T10:34:58.055Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/a7/b1/0bb11e29aa5139d90b770ebbfa167267b1fc548d2302c30c8f7572851738/wrapt-1.17.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c82b8785d98cdd9fed4cac84d765d234ed3251bd6afe34cb7ac523cb93e8b4f", size = 106377, upload-time = "2025-01-14T10:34:59.3Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/6a/e1/0122853035b40b3f333bbb25f1939fc1045e21dd518f7f0922b60c156f7c/wrapt-1.17.2-cp313-cp313t-win32.whl", hash = "sha256:13e6afb7fe71fe7485a4550a8844cc9ffbe263c0f1a1eea569bc7091d4898555", size = 37986, upload-time = "2025-01-14T10:35:00.498Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/09/5e/1655cf481e079c1f22d0cabdd4e51733679932718dc23bf2db175f329b76/wrapt-1.17.2-cp313-cp313t-win_amd64.whl", hash = "sha256:eaf675418ed6b3b31c7a989fd007fa7c3be66ce14e5c3b27336383604c9da85c", size = 40750, upload-time = "2025-01-14T10:35:03.378Z" },
- { url = "https://pypi.tuna.tsinghua.edu.cn/packages/2d/82/f56956041adef78f849db6b289b282e72b55ab8045a75abad81898c28d19/wrapt-1.17.2-py3-none-any.whl", hash = "sha256:b18f2d1533a71f069c7f82d524a52599053d4c7166e9dd374ae2136b7f40f7c8", size = 23594, upload-time = "2025-01-14T10:35:44.018Z" },
-]