> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrmagent.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandbox Runtime

> Per-user persistent sandbox for code execution and tool usage.

# Sandbox Runtime

Every user gets an isolated, persistent sandbox environment that survives restarts.

## Persistence

Unlike ephemeral sandboxes, Myrm sandboxes retain:

* Installed packages and tools
* File system state
* Environment configuration
* Running processes (with auto-restart)

## Isolation

Each sandbox runs in an isolated environment with:

* Dedicated filesystem volume
* Network namespace isolation
* Resource limits (CPU, memory, disk)
* Security policies enforced at runtime
* **6-Layer Concurrency & Resource Defense**: Process-level RLIMIT enforcement (NPROC=512 anti-fork-bomb, CPU time cap, virtual memory cap, file descriptor cap, file size cap) + SubAgent fan-out limiting (max 3 delegate calls per turn) + per-type concurrency semaphores (default 5) + per-step timeout protection (300s) + memory pressure coordinated load-shedding + container-level cgroup hard caps. The `resource` Python module is blacklisted to prevent agents from escalating their own limits.
* **4-level Memory Pressure Monitor**: Real-time system memory monitoring (NORMAL → WARNING → CRITICAL → EMERGENCY) with container-aware cgroup v2 detection, hysteresis to prevent flapping, coordinated load-shedding via Pub/Sub subscribers, and automatic GC on emergency. Combined with process-level resource tracking (RSS/VMS + 512-point historical ring buffer + on-demand heap profiling), your agent self-protects before resource exhaustion becomes a problem.
* **UI Interaction Blacklisting**: For sub-agents running in the background, the sandbox blocks UI interfaces (`interactive_feedback`, `send_message`), ensuring they can never interrupt the user with popups, providing true physical isolation between background tasks and foreground user interaction.

### Native OS-Level Sandbox (No Docker Required)

For local and desktop deployments, Myrm provides **native OS-level process isolation** on all major platforms:

| Platform | Mechanism               | How It Works                                                                    |
| -------- | ----------------------- | ------------------------------------------------------------------------------- |
| macOS    | Seatbelt (sandbox-exec) | Dynamically generates SBPL profile; Zero-Trust mounts only allow explicit paths |
| Linux    | bubblewrap (bwrap)      | Kernel namespace isolation with PID/network unshare + session separation        |
| Windows  | AppContainer            | Win32 native security token with per-path ACL enforcement                       |

The sandbox provider is auto-detected at startup — no configuration needed. If the preferred provider is unavailable, the system gracefully falls back with a clear warning.

**Key advantages over Docker-based approaches:**

* No Docker Desktop dependency (reduces install friction on Windows/macOS)
* Sub-millisecond startup (no container image pull)
* Native OS security primitives (kernel-enforced, not userspace emulation)
* Works identically in Local WebUI, Tauri Desktop, and Cloud modes

## Code Execution

Agents can execute code directly in the sandbox:

* Python 3.14, Node.js 20, Bun 1.3, shell scripts
* Package installation via uv/pip, npm, apt
* File read/write operations
* Network access (configurable)

### Pre-installed Data Science Stack (70+ packages)

Your sandbox comes ready with the most commonly needed libraries — no installation wait:

| Category          | Packages                                           |
| ----------------- | -------------------------------------------------- |
| **Data Science**  | pandas, numpy, scipy, scikit-learn, statsmodels    |
| **Visualization** | matplotlib (CJK-ready), seaborn                    |
| **Excel**         | openpyxl, xlsxwriter, xlrd                         |
| **Documents**     | python-docx, python-pptx                           |
| **PDF**           | pypdf, pdfplumber, reportlab, pdf2image, pypdfium2 |
| **Image**         | Pillow                                             |
| **Big Data**      | pyarrow (Parquet/Arrow)                            |
| **Math**          | sympy, mpmath                                      |
| **Utilities**     | httpx, orjson, tqdm, pytz                          |

### Jupyter-Grade Inline Charts

Charts generated with matplotlib are automatically captured and displayed inline in the conversation — no manual file download needed. CJK fonts (Chinese, Japanese, Korean) render correctly out of the box, verified at build time.

### Smart Error Recovery

When a package is missing, the agent automatically receives an actionable diagnostic hint suggesting the exact install command, eliminating trial-and-error loops.

**Auto language routing:** One built-in execution tool detects whether input is Python or shell — no need to wrap code in `python3 -c` or pick a separate tool. Invalid Python is caught with a clear syntax error *before* running, so you spend fewer tokens on blind retries.

**vs competitors:** OpenClaw's `exec` tool is shell-only; Hermes splits shell and Python into separate tools. Myrm keeps one simple tool for GUI users and routes correctly under the hood.

## Uploaded File Access

Files you attach to a message (drag-and-drop or click-to-upload) are automatically available in the sandbox workspace:

* **Small files** (under 100 KB): content is injected directly into the LLM context for immediate analysis
* **Large files** (over 100 KB): automatically copied to the workspace `_uploaded/` directory so the agent can read them with `file_read_tool` or process them with code (e.g., `pandas.read_csv()`)

This means you can upload a 5 MB CSV and ask "analyze quarterly trends with Python" — the agent accesses the full file without any manual file transfer or path configuration.

## Workspace Sandbox (Git Worktree Isolation)

For project-level isolation, enable **Sandbox Mode** in any chat session:

* **One-click toggle**: Click the "Sandbox" button in the message input toolbar
* **Git worktree**: Creates an isolated branch where all changes are confined
* **Merge or discard**: When done, merge good changes back or discard the experiment
* **Zero risk**: Your main codebase is never modified until you explicitly merge

This is ideal for:

* Refactoring experiments ("try this approach without risk")
* Letting the agent explore multiple solutions in parallel
* Code reviews where you want to test changes before accepting

**Parallel Sub-Agent Isolation**: When running multi-agent tasks, each sub-agent gets its own Copy-on-Write workspace clone (ISOLATED\_COPY policy) with a 1 GiB safety guard. Changes are safely merged back in serial order after parallel execution — no file conflicts, no data loss.

Seven orchestration modes (Spawn / Chain / Batch / DAG / Verified / Swarm Fission / Alternatives), cascade cancellation, and delegation budgets ensure safe, cost-controlled parallel execution. 3-tier sandbox (OS namespace / Docker container / Workspace COW) starts in milliseconds without Docker dependency. **1,101 tests verify the full sub-agent & sandbox stack.**

**Robustness guarantees:**

* Locale-safe: All git commands use `LANG=C` to prevent parsing failures on non-English systems
* Auto-cleanup: On startup, stale worktrees and orphaned sandbox branches are automatically pruned
* Git-invisible: Sandbox directories are auto-excluded from `git status` via `.git/info/exclude`
* Structured errors: Failures return specific reasons (branch-exists, already-checked-out, path-exists) for clear diagnostics

Unlike Claude Code's CLI-only `--worktree` flag, Myrm's workspace sandbox is available via a GUI toggle, can be enabled/disabled mid-session, and includes a complete merge/discard workflow with pre-approval integration.

## Sleep & Wake

Sandboxes automatically sleep after configurable inactivity periods and wake on demand, preserving all state (files, processes, memory).

**Idle detection** uses two complementary signals to prevent false positives:

* **Reverse-proxy activity tracking** — every user HTTP/WebSocket request through the proxy refreshes the sandbox's activity timestamp (throttled to one DB write per 5 minutes to avoid overhead).
* **WebSocket connection guard** — if the sandbox has an active WebSocket connection to the control plane (e.g., during background deep-research or long-running tasks), the recycler skips sleep regardless of the activity timestamp.

This dual-signal approach ensures active users and background tasks are never interrupted, while genuinely idle sandboxes are reclaimed efficiently. Sleep periods incur zero WU cost.

## Enterprise Org Management & Volume Handoff

For B2B teams, the Control Plane provides full organization lifecycle management:

* **RBAC**: Owner / Admin / Member roles with atomic permission checks
* **Idempotent membership**: Adding the same user twice safely returns existing record
* **One-click offboarding**: When an employee leaves, admin freezes their sandbox, backs up the volume, and transfers it to the successor — all in one operation
* **Immutable audit trail**: Every offboarding action is logged for compliance
* **Cross-org protection**: A user cannot silently belong to two organizations

This means enterprise data never leaves with a departing employee — it stays under organizational control with full traceability.

### Zero-Secret LLM Gateway

In cloud-hosted mode, API keys never enter the sandbox:

* Real keys are stored in the Control Plane's **AES-256-GCM SecretsVault**
* Sandboxes receive signed **virtual keys** (`myrm-vk-...`) that are useless against real providers
* All LLM calls route through the CP relay, which verifies the virtual key and injects the real credential
* Request bodies are streamed byte-for-byte, preserving upstream **Prompt Prefix Cache** perfectly
* Even a fully compromised sandbox cannot exfiltrate usable API credentials

### Enterprise SSO

Enterprise deployments support OIDC single sign-on (Google Workspace, WeCom, Feishu, DingTalk, Azure AD, Okta). Employees open the app and authenticate via corporate IdP — no separate registration, no API key management.
