Skip to main content

Cocoon-Sandbox 🛡️

CI Crates.io PyPI Python Versions License Platforms Security Audit

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


⚡ Features

  • Sub-Millisecond Startup: Runs directly on native operating system primitives (< 5ms) instead of spinning up virtual machines.
  • Default-Deny Network: Outbound network is disabled by default (allow_network: false). Linux unshares network namespaces (CLONE_NEWNET) for kernel-level socket severance; Windows sinks proxies (127.0.0.1:0) to block cooperative HTTP/HTTPS clients and package tools. Use --allow-network to opt in.
  • Read-Only Host Mounts: Mount host directories with --ro where writes, overwrites, appends, and deletes are physically blocked by kernel mount namespaces on Linux and NTFS Deny ACEs on Windows.
  • Hermetic Runtimes & Dual-Mode Python: Untrusted code runs in hermetic standard-library mode (python -I -S -B, node --no-addons, ruby --disable-gems), with a dedicated python-skill preset for document processing tools (openpyxl, python-docx, pandas).
  • Desktop & Clipboard Isolation: Win32 Job Object UI restrictions prevent child processes from reading the host clipboard, injecting synthetic keystrokes, or intercepting window handles.
  • Resource & Process Caps: Hard limits on active processes (--max-procs 32), disk write quotas (--disk 512MB), memory (--mem), and execution timeouts (--timeout 30s).
  • Ephemeral Virtual Scratchpad & User Profile: Redirects caches (__pycache__, npm, cargo) and synthesizes a clean, isolated dummy user profile (USERPROFILE, HOME, APPDATA).
  • Workspace DACL Hardening: Workspace permissions are strictly bounded to the executing user (%USERNAME%), never Everyone (*S-1-1-0).
  • Universal Breakout Verification: Recursively scans workspace post-run to detect and reject symlinks, NTFS directory junctions (0x400), or hardlinks escaping the workspace root.
  • Universal Command Execution: Run any installed compiler or binary toolchain (gcc, clang, dotnet, zig, julia, etc.) by passing trailing arguments: cocoon run -- <cmd> [args...].
  • High-Throughput Heavy Data & Multimedia: Native NVMe read speeds (3–7 GB/s) with zero virtualization overhead for multi-gigabyte Excel data (Pandas/Polars), multi-hundred page PDF conversions, and video/audio processing (ffmpeg).
  • Hardware-Aware 95% Ceiling & Host Protection: Auto-detects host physical RAM and CPU cores across Windows, Linux, and macOS. Clamps resource usage to 95% MAX of physical hardware, guaranteeing the host OS never freezes, thrashes, or blue-screens.
  • GPU VRAM & Driver Isolation (--no-gpu): Multi-vendor driver detachment (NVIDIA CUDA, AMD ROCm/HIP, Intel oneAPI, OpenCL) via --no-gpu. Auto-injects PyTorch VRAM fragmentation guards (max_split_size_mb:128) when GPU is permitted for local SLMs and fine-tuning.
  • Process Priority & Core Dump Hardening: Permanently locks process priority to NORMAL_PRIORITY_CLASS (Windows) and blocks real-time elevation (RLIMIT_RTPRIO=0 on Linux) to prevent scheduler starvation. Suppresses crash core dumps (RLIMIT_CORE=0) to prevent disk flooding and prompt leaks.
  • Agent-First JSON Protocol & SIEM Logging: Emits structured output (--json) and NDJSON event logs (--log-json) with exit codes, peak memory, output truncation, and termination reasons.
  • Native Model Context Protocol (MCP) Server (cocoon mcp): Connect Cocoon directly to Claude Desktop, Cursor, and Antigravity over stdio with built-in execute_code, execute_skill, and inspect_runtimes tools.
  • Environment Diagnostic Doctor (cocoon doctor): Self-test command verifying host sandbox drivers, NTFS ACLs, user namespaces, and 12+ language runtimes.
  • Real-Time Streaming Output (--stream): Live chunked NDJSON streaming for long-running batch jobs, SLM inference, and multimedia pipelines.
  • Native Python Client SDK (import cocoon): Clean, typed 2-line integration for Python AI agent frameworks (LangChain, AutoGen, CrewAI, LlamaIndex).

🏗️ Architecture & Isolation Model

                    ┌────────────────────────────┐
                    │    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:import json; json.dump({'agent':'Cocoon','score':99}, open('data.json','w'))" \
  -s "node:const fs=require('fs'); const d=JSON.parse(fs.readFileSync('data.json')); d.score+=1; fs.writeFileSync('data.json', JSON.stringify(d));" \
  -s "bun:const d=await Bun.file('data.json').json(); console.log('Bun verified score:', d.score);" \
  -s "pwsh:Get-Content data.json"

You can also pass --json to cocoon pipeline to get a structured execution breakdown per step:

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

  1. 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.
  2. 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.
  3. 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 <path> to stage copies of host files into the work folder and manipulate them freely without touching originals.
  4. 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.
  5. 30-Second Execution Timeout by Default:
    • Every execution is automatically capped at 30 seconds by default (override with --timeout <secs>). Runaway scripts or infinite loops auto-terminate cleanly via atomic process tree termination without hanging.
  6. Active Process Cap (max_processes: 32):
    • Mitigates fork bombs and handle exhaustion by capping active child processes to 32 by default.
  7. Storage Quota Enforcement (disk_limit_mb: 512MB):
    • Mitigates disk exhaustion attacks by capping workspace writes at 512 MB.
  8. 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.
  9. Universal Breakout Verification:
    • Post-run canonicalization scans detect and reject any symlink, NTFS junction (0x400), or hardlink attempting to point outside the workspace.
  10. 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.
  11. 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.
  12. 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.
  13. 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.


📦 Project Workspace


📄 License

This project is licensed under the MIT License.

Metadata

Release files for cocoon-sandbox 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cocoon-sandbox 0.2.2
File Size Uploaded Provenance Actions
cocoon_sandbox-0.2.2.tar.gz 74.4 kB Without provenance Details for cocoon_sandbox-0.2.2.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for cocoon-sandbox 0.2.2
File Actions
cocoon_sandbox-0.2.2-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for cocoon_sandbox-0.2.2-py3-none-win_amd64.whl
cocoon_sandbox-0.2.2-py3-none-manylinux_2_39_x86_64.whl Python 3 none Linux glibc 2.39+ x86-64 Details for cocoon_sandbox-0.2.2-py3-none-manylinux_2_39_x86_64.whl
cocoon_sandbox-0.2.2-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl Python 3 none Linux glibc 2.17+ ARM64 Details for cocoon_sandbox-0.2.2-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
cocoon_sandbox-0.2.2-py3-none-macosx_11_0_arm64.whl Python 3 none macOS 11.0+ ARM64 Details for cocoon_sandbox-0.2.2-py3-none-macosx_11_0_arm64.whl
cocoon_sandbox-0.2.2-py3-none-macosx_10_12_x86_64.whl Python 3 none macOS 10.12+ x86-64 Details for cocoon_sandbox-0.2.2-py3-none-macosx_10_12_x86_64.whl

Total release size: 4.8 MB

Release files / cocoon_sandbox-0.2.2.tar.gz

Download URL cocoon_sandbox-0.2.2.tar.gz
Size 74.4 kB
Tags Source
SHA-256 checksum
How to use checksums
82414ba6c9a8b6efc0f8894615c1cc944f8129c93752563733814a42b81217d0
BLAKE2b-256 checksum
How to use checksums
55b72301500269032b15e383ecf94848ee6dc5a5c7c6f804484f12503653e021
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / cocoon_sandbox-0.2.2-py3-none-win_amd64.whl

Download URL cocoon_sandbox-0.2.2-py3-none-win_amd64.whl
Size 969.1 kB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
399164e6fab16850f1e144237e92804f6112ffad072e024ab15aad11231cd88c
BLAKE2b-256 checksum
How to use checksums
6f76fd280d9fcaa6918ab6a92458a3010e7b89ad6ded48299f3fa3da9d87fdf3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / cocoon_sandbox-0.2.2-py3-none-manylinux_2_39_x86_64.whl

Download URL cocoon_sandbox-0.2.2-py3-none-manylinux_2_39_x86_64.whl
Size 979.2 kB
Tags Linux glibc 2.39+ x86-64 Python 3
SHA-256 checksum
How to use checksums
d0c243ae2fbd8e228560f85aecfa35fc4f3d3d22c2e256a57452294814f722dc
BLAKE2b-256 checksum
How to use checksums
f0ae5c05d5bbf14bee74c185ee067788d4dab316b56c2e5e549d9c68a06e73f3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / cocoon_sandbox-0.2.2-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL cocoon_sandbox-0.2.2-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 918.8 kB
Tags Linux glibc 2.17+ ARM64 Python 3
SHA-256 checksum
How to use checksums
92d34db6bded8764c823585eb5fcbc00b716898b8babae6baecfbcce52198d72
BLAKE2b-256 checksum
How to use checksums
643d7a9d4821da7c70bd8e5e19aa7c34a045947e5c2df2db8f0942c4b2636104
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / cocoon_sandbox-0.2.2-py3-none-macosx_11_0_arm64.whl

Download URL cocoon_sandbox-0.2.2-py3-none-macosx_11_0_arm64.whl
Size 885.5 kB
Tags Python 3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
c34edb0bdef35540ef4373a51353e9a917685df010638b1c07bca0fdcdeeb439
BLAKE2b-256 checksum
How to use checksums
eecf385b47ea2d1b06b9380fe2c2872fddaec26e0d9f3a69ffca06db3e64e8ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / cocoon_sandbox-0.2.2-py3-none-macosx_10_12_x86_64.whl

Download URL cocoon_sandbox-0.2.2-py3-none-macosx_10_12_x86_64.whl
Size 944.2 kB
Tags Python 3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
d304fa68465a61bfb7f360bb4c48ea9a03313321a11520e92bd52c5d85873868
BLAKE2b-256 checksum
How to use checksums
db89eaf3c2990f92bbfe8af7d0c983267313b089fc4c401099850fad3291afc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for cocoon-sandbox 0.2.2

Provenance

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page