ms-enclave


Namems-enclave JSON
Version 0.0.1 PyPI version JSON
download
home_pageNone
SummaryModularized and Stable Sandbox runtime environment.
upload_time2025-10-20 06:15:35
maintainerNone
docs_urlNone
authorModelScope team
requires_python>=3.10
licenseApache License 2.0
keywords python llm sandbox
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ms-enclave

A modular and stable sandbox runtime environment

## Overview

ms-enclave is a modular and stable sandbox runtime environment that provides a secure isolated execution environment for applications. It achieves strong isolation through Docker containers, with accompanying local/HTTP managers and an extensible tool system, enabling you to safely and efficiently execute code in a controlled environment.

- 🔒 Secure Isolation: Full isolation and resource limitation based on Docker
- 🧩 Modular: Extensible sandbox and tools (registration factory)
- ⚡ Stable Performance: Simple implementation, fast startup, lifecycle management
- 🌐 Remote Management: Built-in FastAPI service, supports HTTP management
- 🔧 Tool System: Standardized tools enabled by sandbox type (OpenAI-style schema)

## System Requirements

- Python >= 3.10
- Operating System: Linux, macOS, or Windows with Docker support
- Docker daemon running locally (Notebook sandbox requires port 8888 open)

## Installation

### Install from PyPI

```bash
pip install ms-enclave
```

### Install from Source

```bash
git clone https://github.com/modelscope/ms-enclave.git
cd ms-enclave
pip install -e .
```

## Quick Start: Minimal Example (SandboxFactory)

> Tools need to be explicitly enabled in the tools_config setting, otherwise they won't be registered.

```python
import asyncio
from ms_enclave.sandbox.boxes import SandboxFactory
from ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType

async def main():
    config = DockerSandboxConfig(
        image='python:3.11-slim',
        memory_limit='512m',
        tools_config={
            'python_executor': {},
            'file_operation': {},
            'shell_executor': {}
        }
    )

    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:
        # 1) Write a file
        await sandbox.execute_tool('file_operation', {
            'operation': 'write', 'file_path': '/sandbox/hello.txt', 'content': 'hi from enclave'
        })
        # 2) Execute Python code
        result = await sandbox.execute_tool('python_executor', {
            'code': "print('Hello from sandbox!')\nprint(open('/sandbox/hello.txt').read())"
        })
        print(result.output)

asyncio.run(main())
```

---

## Typical Usage Scenarios and Examples

- Directly using SandboxFactory: Create/destroy sandboxes in a single process—lightweight; suitable for scripts or one-off tasks
- Using LocalSandboxManager: Manage the lifecycle/cleanup of multiple sandboxes locally; suitable for service-oriented or multi-task parallel scenarios
- Using HttpSandboxManager: Unified sandbox management through remote HTTP services; suitable for cross-machine/distributed or more isolated deployments

### 1) Direct Sandbox Creation: SandboxFactory (Lightweight, Temporary)

Usage Scenarios:

- Temporarily execute code in scripts or microservices
- Fine-grained control over sandbox lifecycle (cleanup upon context exit)

Example (Docker Sandbox + Python Execution):

```python
import asyncio
from ms_enclave.sandbox.boxes import SandboxFactory
from ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType

async def main():
    cfg = DockerSandboxConfig(
        tools_config={'python_executor': {}}
    )
    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, cfg) as sb:
        r = await sb.execute_tool('python_executor', {
            'code': 'import platform; print(platform.python_version())'
        })
        print(r.output)

asyncio.run(main())
```

### 2) Local Unified Management: LocalSandboxManager (Multi-Sandbox, Lifecycle Management)

Usage Scenarios:

- Create/manage multiple sandboxes within the same process (creation, query, stop, periodic cleanup)
- Unified view for monitoring stats and health

Example:

```python
import asyncio
from ms_enclave.sandbox.manager import LocalSandboxManager
from ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType

async def main():
    async with LocalSandboxManager() as manager:
        cfg = DockerSandboxConfig(tools_config={'shell_executor': {}})
        sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, cfg)

        # Execute command
        res = await manager.execute_tool(sandbox_id, 'shell_executor', {'command': 'echo hello'})
        print(res.output.strip())  # hello

        # View list
        infos = await manager.list_sandboxes()
        print([i.id for i in infos])

        # Stop and delete
        await manager.stop_sandbox(sandbox_id)
        await manager.delete_sandbox(sandbox_id)

asyncio.run(main())
```

### 3) Remote Unified Management: HttpSandboxManager (Cross-Machine/Isolated Deployment)

Usage Scenarios:

- Run sandbox services on dedicated hosts/containers, invoke remotely via HTTP
- Share a secure controlled sandbox cluster among multiple applications

Start the service (choose one):

```bash
# Option A: Command line
ms-enclave server --host 0.0.0.0 --port 8000

# Option B: Python script
python -c "from ms_enclave.sandbox import create_server; create_server().run(host='0.0.0.0', port=8000)"
```

Client Example:

```python
import asyncio
from ms_enclave.sandbox.manager import HttpSandboxManager
from ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType

async def main():
    async with HttpSandboxManager(base_url='http://127.0.0.1:8000') as m:
        cfg = DockerSandboxConfig(tools_config={'python_executor': {}})
        sid = await m.create_sandbox(SandboxType.DOCKER, cfg)
        r = await m.execute_tool(sid, 'python_executor', {'code': 'print("Hello remote")'})
        print(r.output)
        await m.delete_sandbox(sid)

asyncio.run(main())
```

---

## Sandbox Types and Tool Support

Currently Supported Sandbox Types:

- DOCKER (General-purpose container execution)
  - Supported tools:
    - python_executor (execute Python code)
    - shell_executor (execute Shell commands)
    - file_operation (read/write/delete/list files)
  - Features: Configurable memory/CPU limits, volume mounts, network toggling, privileged mode, port mapping

- DOCKER_NOTEBOOK (Jupyter Kernel Gateway environment)
  - Supported tools:
    - notebook_executor (execute code via Jupyter Kernel, supports context saving)
  - Note: This type only loads notebook_executor; other DOCKER-specific tools won't be enabled in this sandbox.
  - Dependencies: Requires port 8888 exposed and network enabled

Tool Loading Rules:

- Tools are initialized and made available only when explicitly declared in `tools_config`.
- Tools validate `required_sandbox_type`; unmatched types will be ignored automatically.

Example:

```python
DockerSandboxConfig(tools_config={'python_executor': {}, 'shell_executor': {}, 'file_operation': {}})
DockerNotebookConfig(tools_config={'notebook_executor': {}})
```

---

## Common Configuration Options

- `image`: Docker image name (e.g., `python:3.11-slim` or `jupyter-kernel-gateway`)
- `memory_limit`: Memory limit (e.g., `512m` / `1g`)
- `cpu_limit`: CPU limit (float > 0)
- `volumes`: Volume mounts, e.g., `{host_path: {"bind": "/container/path", "mode": "rw"}}`
- `ports`: Port mappings, e.g., `{ "8888/tcp": ("127.0.0.1", 8888) }`
- `network_enabled`: Enable network (Notebook sandbox requires True)
- `remove_on_exit`: Automatically remove container on exit (default True)

---

## Error Handling and Debugging

```python
result = await sandbox.execute_tool('python_executor', {'code': 'print(1/0)'})
if result.error:
    print('Error:', result.error)
else:
    print('Output:', result.output)
```

---

## Development and Testing

```bash
# Clone the repository
git clone https://github.com/modelscope/ms-enclave.git
cd ms-enclave

# Setup virtual environment
python -m venv venv
source venv/bin/activate  # Windows: venv\Scripts\activate

# Install dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run examples (provided in the repository)
python examples/sandbox_usage_examples.py
python examples/local_manager_example.py
python examples/server_manager_example.py
```

---

## Available Tools

- `python_executor`: Execute Python code (DOCKER)
- `shell_executor`: Execute Shell commands (DOCKER)
- `file_operation`: Read/Write/Delete/List files (DOCKER)
- `notebook_executor`: Execute via Jupyter Kernel (DOCKER_NOTEBOOK)
- You can also register custom tools via the Tool factory (`@register_tool`).

---

## Contribution

We welcome contributions! Please check [CONTRIBUTING.md](CONTRIBUTING.md) for details.

### Steps to Contribute

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Develop and add tests
4. Run local tests: `pytest`
5. Commit changes: `git commit -m 'Add amazing feature'`
6. Push the branch: `git push origin feature/amazing-feature`
7. Submit a Pull Request

## License

This project is licensed under the Apache 2.0 License. See [LICENSE](LICENSE) for details.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "ms-enclave",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "python, llm, sandbox",
    "author": "ModelScope team",
    "author_email": "contact@modelscope.cn",
    "download_url": "https://files.pythonhosted.org/packages/b8/04/d70828402937c220d289adeeac8dfe413df9cdec591288886a80caf3665e/ms_enclave-0.0.1.tar.gz",
    "platform": null,
    "description": "# ms-enclave\n\nA modular and stable sandbox runtime environment\n\n## Overview\n\nms-enclave is a modular and stable sandbox runtime environment that provides a secure isolated execution environment for applications. It achieves strong isolation through Docker containers, with accompanying local/HTTP managers and an extensible tool system, enabling you to safely and efficiently execute code in a controlled environment.\n\n- \ud83d\udd12 Secure Isolation: Full isolation and resource limitation based on Docker\n- \ud83e\udde9 Modular: Extensible sandbox and tools (registration factory)\n- \u26a1 Stable Performance: Simple implementation, fast startup, lifecycle management\n- \ud83c\udf10 Remote Management: Built-in FastAPI service, supports HTTP management\n- \ud83d\udd27 Tool System: Standardized tools enabled by sandbox type (OpenAI-style schema)\n\n## System Requirements\n\n- Python >= 3.10\n- Operating System: Linux, macOS, or Windows with Docker support\n- Docker daemon running locally (Notebook sandbox requires port 8888 open)\n\n## Installation\n\n### Install from PyPI\n\n```bash\npip install ms-enclave\n```\n\n### Install from Source\n\n```bash\ngit clone https://github.com/modelscope/ms-enclave.git\ncd ms-enclave\npip install -e .\n```\n\n## Quick Start: Minimal Example (SandboxFactory)\n\n> Tools need to be explicitly enabled in the tools_config setting, otherwise they won't be registered.\n\n```python\nimport asyncio\nfrom ms_enclave.sandbox.boxes import SandboxFactory\nfrom ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType\n\nasync def main():\n    config = DockerSandboxConfig(\n        image='python:3.11-slim',\n        memory_limit='512m',\n        tools_config={\n            'python_executor': {},\n            'file_operation': {},\n            'shell_executor': {}\n        }\n    )\n\n    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, config) as sandbox:\n        # 1) Write a file\n        await sandbox.execute_tool('file_operation', {\n            'operation': 'write', 'file_path': '/sandbox/hello.txt', 'content': 'hi from enclave'\n        })\n        # 2) Execute Python code\n        result = await sandbox.execute_tool('python_executor', {\n            'code': \"print('Hello from sandbox!')\\nprint(open('/sandbox/hello.txt').read())\"\n        })\n        print(result.output)\n\nasyncio.run(main())\n```\n\n---\n\n## Typical Usage Scenarios and Examples\n\n- Directly using SandboxFactory: Create/destroy sandboxes in a single process\u2014lightweight; suitable for scripts or one-off tasks\n- Using LocalSandboxManager: Manage the lifecycle/cleanup of multiple sandboxes locally; suitable for service-oriented or multi-task parallel scenarios\n- Using HttpSandboxManager: Unified sandbox management through remote HTTP services; suitable for cross-machine/distributed or more isolated deployments\n\n### 1) Direct Sandbox Creation: SandboxFactory (Lightweight, Temporary)\n\nUsage Scenarios:\n\n- Temporarily execute code in scripts or microservices\n- Fine-grained control over sandbox lifecycle (cleanup upon context exit)\n\nExample (Docker Sandbox + Python Execution):\n\n```python\nimport asyncio\nfrom ms_enclave.sandbox.boxes import SandboxFactory\nfrom ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType\n\nasync def main():\n    cfg = DockerSandboxConfig(\n        tools_config={'python_executor': {}}\n    )\n    async with SandboxFactory.create_sandbox(SandboxType.DOCKER, cfg) as sb:\n        r = await sb.execute_tool('python_executor', {\n            'code': 'import platform; print(platform.python_version())'\n        })\n        print(r.output)\n\nasyncio.run(main())\n```\n\n### 2) Local Unified Management: LocalSandboxManager (Multi-Sandbox, Lifecycle Management)\n\nUsage Scenarios:\n\n- Create/manage multiple sandboxes within the same process (creation, query, stop, periodic cleanup)\n- Unified view for monitoring stats and health\n\nExample:\n\n```python\nimport asyncio\nfrom ms_enclave.sandbox.manager import LocalSandboxManager\nfrom ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType\n\nasync def main():\n    async with LocalSandboxManager() as manager:\n        cfg = DockerSandboxConfig(tools_config={'shell_executor': {}})\n        sandbox_id = await manager.create_sandbox(SandboxType.DOCKER, cfg)\n\n        # Execute command\n        res = await manager.execute_tool(sandbox_id, 'shell_executor', {'command': 'echo hello'})\n        print(res.output.strip())  # hello\n\n        # View list\n        infos = await manager.list_sandboxes()\n        print([i.id for i in infos])\n\n        # Stop and delete\n        await manager.stop_sandbox(sandbox_id)\n        await manager.delete_sandbox(sandbox_id)\n\nasyncio.run(main())\n```\n\n### 3) Remote Unified Management: HttpSandboxManager (Cross-Machine/Isolated Deployment)\n\nUsage Scenarios:\n\n- Run sandbox services on dedicated hosts/containers, invoke remotely via HTTP\n- Share a secure controlled sandbox cluster among multiple applications\n\nStart the service (choose one):\n\n```bash\n# Option A: Command line\nms-enclave server --host 0.0.0.0 --port 8000\n\n# Option B: Python script\npython -c \"from ms_enclave.sandbox import create_server; create_server().run(host='0.0.0.0', port=8000)\"\n```\n\nClient Example:\n\n```python\nimport asyncio\nfrom ms_enclave.sandbox.manager import HttpSandboxManager\nfrom ms_enclave.sandbox.model import DockerSandboxConfig, SandboxType\n\nasync def main():\n    async with HttpSandboxManager(base_url='http://127.0.0.1:8000') as m:\n        cfg = DockerSandboxConfig(tools_config={'python_executor': {}})\n        sid = await m.create_sandbox(SandboxType.DOCKER, cfg)\n        r = await m.execute_tool(sid, 'python_executor', {'code': 'print(\"Hello remote\")'})\n        print(r.output)\n        await m.delete_sandbox(sid)\n\nasyncio.run(main())\n```\n\n---\n\n## Sandbox Types and Tool Support\n\nCurrently Supported Sandbox Types:\n\n- DOCKER (General-purpose container execution)\n  - Supported tools:\n    - python_executor (execute Python code)\n    - shell_executor (execute Shell commands)\n    - file_operation (read/write/delete/list files)\n  - Features: Configurable memory/CPU limits, volume mounts, network toggling, privileged mode, port mapping\n\n- DOCKER_NOTEBOOK (Jupyter Kernel Gateway environment)\n  - Supported tools:\n    - notebook_executor (execute code via Jupyter Kernel, supports context saving)\n  - Note: This type only loads notebook_executor; other DOCKER-specific tools won't be enabled in this sandbox.\n  - Dependencies: Requires port 8888 exposed and network enabled\n\nTool Loading Rules:\n\n- Tools are initialized and made available only when explicitly declared in `tools_config`.\n- Tools validate `required_sandbox_type`; unmatched types will be ignored automatically.\n\nExample:\n\n```python\nDockerSandboxConfig(tools_config={'python_executor': {}, 'shell_executor': {}, 'file_operation': {}})\nDockerNotebookConfig(tools_config={'notebook_executor': {}})\n```\n\n---\n\n## Common Configuration Options\n\n- `image`: Docker image name (e.g., `python:3.11-slim` or `jupyter-kernel-gateway`)\n- `memory_limit`: Memory limit (e.g., `512m` / `1g`)\n- `cpu_limit`: CPU limit (float > 0)\n- `volumes`: Volume mounts, e.g., `{host_path: {\"bind\": \"/container/path\", \"mode\": \"rw\"}}`\n- `ports`: Port mappings, e.g., `{ \"8888/tcp\": (\"127.0.0.1\", 8888) }`\n- `network_enabled`: Enable network (Notebook sandbox requires True)\n- `remove_on_exit`: Automatically remove container on exit (default True)\n\n---\n\n## Error Handling and Debugging\n\n```python\nresult = await sandbox.execute_tool('python_executor', {'code': 'print(1/0)'})\nif result.error:\n    print('Error:', result.error)\nelse:\n    print('Output:', result.output)\n```\n\n---\n\n## Development and Testing\n\n```bash\n# Clone the repository\ngit clone https://github.com/modelscope/ms-enclave.git\ncd ms-enclave\n\n# Setup virtual environment\npython -m venv venv\nsource venv/bin/activate  # Windows: venv\\Scripts\\activate\n\n# Install dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run examples (provided in the repository)\npython examples/sandbox_usage_examples.py\npython examples/local_manager_example.py\npython examples/server_manager_example.py\n```\n\n---\n\n## Available Tools\n\n- `python_executor`: Execute Python code (DOCKER)\n- `shell_executor`: Execute Shell commands (DOCKER)\n- `file_operation`: Read/Write/Delete/List files (DOCKER)\n- `notebook_executor`: Execute via Jupyter Kernel (DOCKER_NOTEBOOK)\n- You can also register custom tools via the Tool factory (`@register_tool`).\n\n---\n\n## Contribution\n\nWe welcome contributions! Please check [CONTRIBUTING.md](CONTRIBUTING.md) for details.\n\n### Steps to Contribute\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature/amazing-feature`\n3. Develop and add tests\n4. Run local tests: `pytest`\n5. Commit changes: `git commit -m 'Add amazing feature'`\n6. Push the branch: `git push origin feature/amazing-feature`\n7. Submit a Pull Request\n\n## License\n\nThis project is licensed under the Apache 2.0 License. See [LICENSE](LICENSE) for details.\n",
    "bugtrack_url": null,
    "license": "Apache License 2.0",
    "summary": "Modularized and Stable Sandbox runtime environment.",
    "version": "0.0.1",
    "project_urls": {
        "Homepage": "https://github.com/modelscope/ms-enclave"
    },
    "split_keywords": [
        "python",
        " llm",
        " sandbox"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3f8beea3bfc63728284ca31c052d30313cfa8f6c4b893c93940130c95e0a8300",
                "md5": "6094d2c9ac302babfd2f598d48f2b800",
                "sha256": "9898b138c2942b4ff76ea18862af5aa4b8581454a75e187a1ae70486a8a2aa2f"
            },
            "downloads": -1,
            "filename": "ms_enclave-0.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6094d2c9ac302babfd2f598d48f2b800",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 47674,
            "upload_time": "2025-10-20T06:15:33",
            "upload_time_iso_8601": "2025-10-20T06:15:33.856368Z",
            "url": "https://files.pythonhosted.org/packages/3f/8b/eea3bfc63728284ca31c052d30313cfa8f6c4b893c93940130c95e0a8300/ms_enclave-0.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b804d70828402937c220d289adeeac8dfe413df9cdec591288886a80caf3665e",
                "md5": "6a1a7158135ecd46d5302ee920b59316",
                "sha256": "d833d2ff57d950450fec3a87d4e96a7526e3f4a04252708c7b6fabc60610a62d"
            },
            "downloads": -1,
            "filename": "ms_enclave-0.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "6a1a7158135ecd46d5302ee920b59316",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 41480,
            "upload_time": "2025-10-20T06:15:35",
            "upload_time_iso_8601": "2025-10-20T06:15:35.146532Z",
            "url": "https://files.pythonhosted.org/packages/b8/04/d70828402937c220d289adeeac8dfe413df9cdec591288886a80caf3665e/ms_enclave-0.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-20 06:15:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "modelscope",
    "github_project": "ms-enclave",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "ms-enclave"
}
        
Elapsed time: 1.53780s