Lightweight cross-platform sandbox with virtual and read-only filesystems for AI agents
pip install cocoon-sandbox==0.3.0 Copy PIP instructions
A featherweight, cross-platform sandbox with virtual and read-only filesystems designed for AI agents and secure code execution.
Cocoon allows AI agents, code evaluation suites, and developers to safely run untrusted scripts in Python, Node.js, Bun, Deno, Go, Java, Rust, PowerShell, Bash, Ruby, PHP, Lua, and any binary compiler without the latency or complexity of heavyweight containers or virtual machines.
👉 Installation Guide & Prerequisites | User & Agent Integration Guide | Security & Vulnerability Remediation Guide | Enterprise & Production Guide
┌────────────────────────────┐ │ AI Agent / Host App │ └─────────────┬──────────────┘ │ (CLI / Rust / Python / MCP) ┌─────────────▼──────────────┐ │ Cocoon Engine │ └─────────────┬──────────────┘ │ ┌────────────────────────┼────────────────────────┐ │ │ │ ┌────────▼─────────┐ ┌─────────▼────────┐ ┌──────────▼─────────┐ │ Linux Driver │ │ macOS Driver │ │ Windows Driver │ ├──────────────────┤ ├──────────────────┤ ├────────────────────┤ │ • User Namespaces│ │ • Apple Seatbelt │ │ • Job Objects │ │ • ro-bind mounts │ │ • SBPL Profile │ │ • UI Restrictions │ │ • tmpfs /tmp │ │ • Dynamic Sandbox│ │ • Inherited Deny │ │ • tmpfs /dev/shm │ │ • POSIX rlimits │ │ NTFS ACEs │ │ • rlimit caps │ │ • Ephemeral VFS │ │ • Scratchpad VFS │ └──────────────────┘ └──────────────────┘ └────────────────────┘ 📦 Installation Install Cocoon using your preferred package manager:
# Via Python / PyPI (Pre-compiled native binary, zero Rust toolchain needed) pip install cocoon-sandbox # Via Rust / Cargo (From Crates.io) cargo install cocoon-sandbox 🚀 Quick Start 1. Inspect System Capabilities cocoon info 2. Run Untrusted Python (Hermetic Standard Library) Mount your project directory as read-only and execute an inspection script in isolated mode (-I -S -B):
cocoon run --ro ./my_project --runtime python -c "import os; print(os.listdir('.'))" 3. Run Document Format Skills (python-skill) When running trusted format manipulation tools (e.g. openpyxl, python-docx, pandas), use the python-skill preset:
cocoon run --ro ./sheets --runtime python-skill -c "import openpyxl; print('Excel engine ready')" 4. Run Node.js with Memory & Timeout Limits cocoon run --ro ./data --runtime node -c "console.log('Processed:', 42 * 2)" --timeout 5 --mem 256 5. Run PowerShell with Isolated Desktop PowerShell automatically executes with -NoProfile -NonInteractive -ExecutionPolicy Bypass and clipboard isolation:
cocoon run --ro ./scripts --runtime pwsh -c "Get-ChildItem" 6. Dedicated Work Directory (Create & Manipulate Files) Specify an explicit workspace folder where scripts have full read-write permissions to create, manipulate, and delete files:
cocoon run --work ./agent_workspace --runtime python -c "open('report.txt', 'w').write('Analyzed')" 7. Safe Copy & Staging (Manipulate Copies While Leaving Originals Untouched) Mount sensitive files/folders as read-only (--ro), and use --copy to stage copies into the writable work folder. The sandboxed process can edit and transform the files without altering the originals:
cocoon run --ro ./repo --copy ./repo/config.json --work ./agent_workspace \ --runtime python -c "import json; d = json.load(open('config.json')); d['active'] = True; json.dump(d, open('config.json', 'w'))" 8. Structured JSON Output for AI Agents Add --json to receive structured execution telemetry:
cocoon run --ro . --runtime python -c "print('Computed:', 2**8)" --json Output:
{ "exit_code": 0, "stdout": "Computed: 256\n", "stderr": "", "duration_ms": 184.2, "timed_out": false, "oom_killed": false, "termination_reason": null, "stdout_truncated": false, "stderr_truncated": false, "peak_memory_mb": 14 } 9. Multi-Language Polyglot Pipelines (cocoon pipeline) Run sequential steps across different programming languages in the exact same virtual filesystem. Steps share the workspace and pass files between each other:
cocoon pipeline \ -s "python:open('val.txt','w').write('42')" \ -s "bun:console.log('Value read by Bun:', (await Bun.file('val.txt').text()).trim())" \ --json 10. Heavy Data & Document Processing (Pandas & Large Excel) Mount large datasets as read-only (--ro) and process millions of rows at native NVMe bus speed without risk of file corruption:
cocoon run --ro ./data --work ./output --timeout 180 --disk 2048 -r python-skill -c " import pandas as pd df = pd.read_excel('data/massive_ledger.xlsx', engine='calamine') df[df['amount'] > 50000].to_parquet('output/high_value.parquet') print(f'Processed {len(df):,} rows successfully.') " --json 11. Local SLM Inference & Fine-Tuning (GPU vs. --no-gpu) Run local Small Language Models (SLMs) such as Phi-3, Llama-3-8B, or Mistral-7B with automatic PyTorch VRAM protection:
# GPU enabled with VRAM fragmentation protection: cocoon run --ro ./models --work ./output --timeout 180 --disk 2048 -r python-skill -c " from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained('models/Phi-3-mini', device_map='auto') print('Model ready for inference.') " --json # Or run strictly on CPU with complete GPU driver detachment: cocoon run --no-gpu --ro ./models --work ./output --timeout 180 -r python-skill -c "print('CPU only')" 🔒 Security Guarantees & Built-in Invariants Default-Deny Network (allow_network: false): On Linux, network namespaces are unshared (CLONE_NEWNET), severing all sockets at the kernel level. On Windows, proxies are sinkholed to 127.0.0.1:0, blocking cooperative HTTP/HTTPS traffic. Opt-in with --allow-network. Read-Only by Default (--ro .): Even if you omit --ro, the current working directory is automatically protected as strictly read-only. On Linux, mount namespaces enforce read-only status. On Windows, NTFS Deny ACEs block write/append/delete operations on designated folders (PermissionError: Permission denied). Ambient host paths outside --ro retain standard user read access. Workspace Access Control & Ephemeral Scratchpad: Writes are confined to the designated --work directory or auto-cleaned ephemeral scratchpad. Workspace DACLs are strictly bounded to the executing user (%USERNAME%), eliminating legacy broad access (Everyone). Use --copy to stage copies of host files into the work folder and manipulate them freely without touching originals. Desktop & Clipboard Isolation: Win32 Job Object UI restrictions prevent child processes from reading the host clipboard (JOB_OBJECT_UILIMIT_READCLIPBOARD), modifying the clipboard, or sending synthetic window messages to other applications. 30-Second Execution Timeout by Default: Every execution is automatically capped at 30 seconds by default (override with --timeout ). Runaway scripts or infinite loops auto-terminate cleanly via atomic process tree termination without hanging. Active Process Cap (max_processes: 32): Mitigates fork bombs and handle exhaustion by capping active child processes to 32 by default. Storage Quota Enforcement (disk_limit_mb: 512MB): Mitigates disk exhaustion attacks by capping workspace writes at 512 MB. No Bytecode or Cache Pollution: Python bytecode caching (PYTHONPYCACHEPREFIX), pip caches (PIP_CACHE_DIR), npm caches (npm_config_cache), and cargo build artifacts are redirected to an ephemeral scratchpad that is destroyed upon exit. Universal Breakout Verification: Post-run canonicalization scans detect and reject any symlink, NTFS junction (0x400), or hardlink attempting to point outside the workspace. Hardware-Aware 95% Ceiling: Auto-detects physical RAM and clamps memory allocations to (Host Physical RAM * 0.95), mathematically preventing host paging thrashing or blue screens even if --mem is omitted. 95% CPU Rate Cap & Scheduler Lockout: Enforces NORMAL_PRIORITY_CLASS (Windows) and RLIMIT_RTPRIO=0 (Linux) to permanently block untrusted code from preempting host OS schedulers or system drivers. Clamps CPU rate to 95% MAX. GPU VRAM & Driver Isolation (--no-gpu): Strips and masks driver interfaces across NVIDIA, AMD ROCm/HIP, Intel, and OpenCL when --no-gpu is passed. Auto-injects PYTORCH_CUDA_ALLOC_CONF="max_split_size_mb:128" when GPU is enabled. Crash Core Dump Suppression: Injects RLIMIT_CORE=0 on Linux and suppresses WER crash popups on Windows, eliminating multi-gigabyte core dumps and prompt memory leakage. For a comprehensive breakdown of all threat models, CVE remediations, and OS defensive layers, see the Security & Vulnerability Remediation Guide and the Enterprise & Production Deployment Guide.
This project is licensed under the MIT License.
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Enable javascript to be able to filter the list of wheel files.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




