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 TCP/UDP sockets are completely blocked by default (allow_network: false) to eliminate credential exfiltration. Use --allow-network to opt in.
  • Ironclad Read-Only Protection: Mount host directories with --ro where writes, overwrites, appends, and deletes are physically blocked by kernel ACLs / namespaces.
  • 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 & Isolated User Profile: Redirects caches (__pycache__, npm, cargo) and synthesizes a clean, isolated dummy user profile (USERPROFILE, HOME, APPDATA).
  • 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.

🏗️ Architecture & Isolation Model

                    ┌────────────────────────────┐
                    │    AI Agent / Host App     │
                    └─────────────┬──────────────┘
                                  │ (CLI / Rust / JSON / SIEM)
                    ┌─────────────▼──────────────┐
                    │       Cocoon Engine        │
                    └─────────────┬──────────────┘
                                  │
         ┌────────────────────────┼────────────────────────┐
         │                        │                        │
┌────────▼─────────┐    ┌─────────▼────────┐    ┌──────────▼─────────┐
│   Linux Driver   │    │   macOS Driver   │    │   Windows Driver   │
├──────────────────┤    ├──────────────────┤    ├────────────────────┤
│ • User Namespaces│    │ • Apple Seatbelt │    │ • Job Objects      │
│ • ro-bind mounts │    │ • SBPL Profile   │    │ • UI Restrictions  │
│ • tmpfs /tmp     │    │ • Ephemeral /tmp │    │ • Inherited Deny   │
│ • tmpfs /dev/shm │    │                  │    │   NTFS ACEs        │
│ • rlimit caps    │    │                  │    │ • 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):
    • Sockets and outbound traffic are completely blocked by default. Sinks proxy variables to 127.0.0.1:0 and unshares network namespaces on Linux. 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.
    • Opening files in write mode ('w', 'a') or attempting deletions triggers immediate PermissionError / EPERM enforced at the OS kernel level.
  3. Zero Host Writes (Workdir Isolation):
    • Sandboxed processes can never write to anything other than the designated --work folder (or the auto-cleaned ephemeral scratchpad).
    • 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.0

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.0
File Size Uploaded Provenance Actions
cocoon_sandbox-0.2.0.tar.gz 59.3 kB Without provenance Details for cocoon_sandbox-0.2.0.tar.gz

Built distributions (wheels)

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

Total release size: 4.4 MB

Release files / cocoon_sandbox-0.2.0.tar.gz

Download URL cocoon_sandbox-0.2.0.tar.gz
Size 59.3 kB
Tags Source
SHA-256 checksum
How to use checksums
199ebf5e0c83bf5f827df4e4265a2cfb9df0645639ea9cd7f68f8e3060b2268b
BLAKE2b-256 checksum
How to use checksums
103bb0727095c2166f375962dec9032da4962d3fb6335d0b2f16bf2be814f74e
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.0-py3-none-win_amd64.whl

Download URL cocoon_sandbox-0.2.0-py3-none-win_amd64.whl
Size 892.1 kB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
1174866fe57a5455a89bc2ee9ff3dc4704fc6cb78326ff383077f9ca8ec40db5
BLAKE2b-256 checksum
How to use checksums
1dbd07d6d40f934c6aa7ab5feeecee1b8097e3bf2f2e12b85ba7ef15f33d6532
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.0-py3-none-manylinux_2_39_x86_64.whl

Download URL cocoon_sandbox-0.2.0-py3-none-manylinux_2_39_x86_64.whl
Size 910.6 kB
Tags Linux glibc 2.39+ x86-64 Python 3
SHA-256 checksum
How to use checksums
c90e14c8ddeed9c49095ffc38d763bd45103420472efbf63d6463559ec92eeef
BLAKE2b-256 checksum
How to use checksums
9389259af1b7c30be02321fe9eb5530cba76b0a7c09e71a6364866abd31d18c5
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.0-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL cocoon_sandbox-0.2.0-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 857.3 kB
Tags Linux glibc 2.17+ ARM64 Python 3
SHA-256 checksum
How to use checksums
fdbdae957cb0db892a04e403a81f8f14d3405ec194f8b2009ef806dcf84b8e50
BLAKE2b-256 checksum
How to use checksums
4b3e3cc3abd70f941fd2f2a67ab30983ff84906ed31a5293e5f9c515382381ab
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.0-py3-none-macosx_11_0_arm64.whl

Download URL cocoon_sandbox-0.2.0-py3-none-macosx_11_0_arm64.whl
Size 827.3 kB
Tags Python 3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
15938c04dc4b8062c00947eabcc73497aa6fd77360283c36b48cf8bb2959a1ce
BLAKE2b-256 checksum
How to use checksums
9508f7bd3d6d402c1f56b2b11d2dd1ec48407359a9050c55a2824eded9295c2c
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.0-py3-none-macosx_10_12_x86_64.whl

Download URL cocoon_sandbox-0.2.0-py3-none-macosx_10_12_x86_64.whl
Size 877.0 kB
Tags Python 3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
8e346ccdfb34e69b3b6689ee0cc652721bb228f3f164f4b9b141311125c02652
BLAKE2b-256 checksum
How to use checksums
d88bf8e9ed564145163161138a851d499fa6a2486023507b17389bc978a6304a
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.0

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