agentleFS
botirkhaltaevbotirkhaltaev/botir-skills/skills/modal-sandboxes/SKILL.md

modal-sandboxes

Skill4 starsChanged 3 months agoApache-2.0View on GitHub

Secure, isolated Modal Sandboxes for untrusted or agent-generated code — including snapshots, Docker-in-sandbox, VM Sandboxes, network controls, and Sandbox log/shell CLI (modal container logs sb-*, modal shell sb-*). Use when running LLM-generated code, building coding agents, snapshotting state, or executing arbitrary user code safely.

We split this skill into the rules it gives an agent

13 rules. About 0 are common, 2 are distinctive, and 11 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill when creating isolated containers for untrusted code execution, building coding agents, snapshotting sandbox state, or …

    line 13
  2. Very specific:

    Use modal.Probe.with_tcp(port) or modal.Probe.with_exec(...), then sb.wait_until_ready().

    line 101
  3. Very specific:

    Prefer sb.filesystem.* over deprecated sb.open / sb.ls / sb.mkdir / sb.rm / Sandbox.watch.

    line 125
  4. Very specific:

    Always set timeout on exec() calls

    line 173
  5. Distinctive:

    Check if the command expects stdin input

    line 174
  6. Very specific:

    Use sb.terminate(wait=True) to force-stop

    line 175
  7. Very specific:

    Use sb.filesystem.*, not volume mounts, for ad-hoc file access

    line 179
  8. Very specific:

    Ensure the file was actually created by checking with sb.exec("ls", "/path")

    line 180
  9. Very specific:

    Check block_network, CIDR/domain allowlists, or proxy/firewall

    line 184
  10. Very specific:

    Always set timeouts on exec() calls to prevent hanging

    line 327
  11. Very specific:

    Use sb.terminate(wait=True) + sb.detach() when done

    line 328
  12. Very specific:

    Prefer sb.filesystem.* over deprecated open/ls/mkdir/rm/Sandbox.watch

    line 333
  13. Very specific:

    Prefer outbound_cidr_allowlist over deprecated cidr_allowlist

    line 334

≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Modal Sandboxes

Use this skill when creating isolated containers for untrusted code execution, building coding agents, snapshotting sandbox state, or running arbitrary commands in secure environments.

When to Use This Skill

  • Executing LLM-generated code safely
  • Building coding agent infrastructure
  • Running untrusted user code in isolation
  • Creating temporary environments for testing
  • Executing git operations (clone, test, lint) in isolation
  • Snapshotting sandbox state (filesystem, directory, memory)
  • Running Docker / eBPF / systemd workloads (VM Sandboxes, Alpha)

Quick Start

import modal

app = modal.App.lookup("my-sandbox-app", create_if_missing=True)
sb = modal.Sandbox.create(app=app)

p = sb.exec("python", "-c", "print('hello')", timeout=3)
print(p.stdout.read())

sb.terminate(wait=True)
sb.detach()

No modal run needed — run directly with python script.py.

Sandbox Lifecycle

  1. Created — registered, no resources allocated yet
  2. Scheduled — worker provisioning resources
  3. Started — container running, ready for exec()
  4. Ready — readiness probe succeeded (if configured)
  5. Completed/Terminated/Error — final states
sb = modal.Sandbox.create(app=app, timeout=600, tags={"team": "agents"})

p = sb.exec("bash", "-c", "echo hello")
p.wait()

exit_code = sb.terminate(wait=True)  # block until finished; returns exit code
sb.detach()  # release client connection

Running Commands

# Simple command
p = sb.exec("python", "-c", "print(42)", timeout=5)
stdout = p.stdout.read()

# Stream output
p = sb.exec("bash", "-c", "for i in {1..5}; do echo $i; sleep 1; done")
for line in p.stdout:
    print(line, end="")

# Check exit code
p.wait()
print(p.returncode)

Logs and shells (Sandbox IDs)

Sandbox IDs (sb-*) are first-class for the container CLI:

modal container logs sb-xxxxx                 # last 100
modal container logs sb-xxxxx --all           # full history (incl. startup phase)
modal container logs sb-xxxxx -f              # follow
modal container logs sb-xxxxx --search err --source stderr --timestamps

modal shell sb-xxxxx                          # attach to running Sandbox

Stream image-build progress when creating Sandboxes:

with modal.enable_output():
    sb = modal.Sandbox.create(image=image, app=app)

Broader App/Function log debugging (filters, ap-*, Live Profiling) is modal-observability.

Readiness Probes

Use modal.Probe.with_tcp(port) or modal.Probe.with_exec(...), then sb.wait_until_ready(). There is no modal.Sandbox.ReadinessProbe.

sb = modal.Sandbox.create(
    "python3", "-m", "http.server", "8080",
    readiness_probe=modal.Probe.with_tcp(8080),
    app=app,
)
sb.wait_until_ready()  # blocks until port accepts connections

# Exec probe — succeeds when command exits 0
sb = modal.Sandbox.create(
    "bash", "-c", "sleep 2 && touch /tmp/ready && sleep 3600",
    readiness_probe=modal.Probe.with_exec(
        "sh", "-c", "test -f /tmp/ready",
        interval_ms=250,
    ),
    app=app,
)
sb.wait_until_ready()

Filesystem API

Prefer sb.filesystem.* over deprecated sb.open / sb.ls / sb.mkdir / sb.rm / Sandbox.watch.

sb.filesystem.write_text("content", "/tmp/file.txt")
text = sb.filesystem.read_text("/tmp/file.txt")
sb.filesystem.write_bytes(b"\x00\x01", "/tmp/data.bin")
data = sb.filesystem.read_bytes("/tmp/data.bin")

sb.filesystem.copy_from_local("local.txt", "/tmp/remote.txt")
sb.filesystem.copy_to_local("/tmp/remote.txt", "local-copy.txt")

entries = sb.filesystem.list_files("/tmp")
info = sb.filesystem.stat("/tmp/file.txt")
sb.filesystem.make_directory("/tmp/project")
sb.filesystem.remove("/tmp/project", recursive=True)

for event in sb.filesystem.watch("/tmp/project", recursive=True, timeout=60):
    print(event)

Configuration

sb = modal.Sandbox.create(
    app=app,
    image=modal.Image.debian_slim().pip_install("requests"),
    gpu="T4",
    cpu=2,
    memory=4096,
    timeout=300,
    tags={"env": "dev"},
    secrets=[modal.Secret.from_name("api-key")],
    volumes={"/data": modal.Volume.from_name("shared-vol")},
    region=["us-west"],
    proxy=modal.Proxy.from_name("my-proxy"),
    custom_domain="sandboxes.mydomain.com",
    include_oidc_identity_token=True,  # injects MODAL_IDENTITY_TOKEN
)
sb.reload_volumes(timeout=55)  # refresh mounted Volumes; TimeoutError if slow

Multi-Language Support

Sandboxes support Python, JavaScript/TypeScript, and Go clients.

Symptom Triage

"Sandbox command hangs"

  • Always set timeout on exec() calls
  • Check if the command expects stdin input
  • Use sb.terminate(wait=True) to force-stop
  • Inspect: modal container logs sb-… --all or modal shell sb-…

"Cannot read files from Sandbox"

  • Use sb.filesystem.*, not volume mounts, for ad-hoc file access
  • Ensure the file was actually created by checking with sb.exec("ls", "/path")

"Sandbox internet access blocked"

  • Internet access is available by default
  • Check block_network, CIDR/domain allowlists, or proxy/firewall

"NotFoundError on snapshot"

  • Filesystem/directory snapshots default to 30-day TTL in 1.5+
  • Pass ttl=None for indefinite retention, or recreate the snapshot

"No Sandbox logs"

  • modal container logs sb-… --all --timestamps
  • For create/image build noise locally: wrap Sandbox.create in modal.enable_output()

Sandbox Snapshots

Filesystem snapshot → Image

sb.exec("pip", "install", "pandas", "numpy").wait()

# Default TTL: 30 days (1.5+). Pass ttl=None for indefinite.
img = sb.snapshot_filesystem(timeout=55, ttl=30 * 24 * 3600)
# img = sb.snapshot_filesystem(ttl=None)  # retain indefinitely

sb2 = modal.Sandbox.create(image=img, app=app)

Directory snapshot + mount_image

snapshot = sb.snapshot_directory("/workspace/project", timeout=55, ttl=30 * 24 * 3600)

sb2 = modal.Sandbox.create(app=app)
try:
    sb2.mount_image("/workspace/project", snapshot)
except modal.exception.NotFoundError:
    ...  # snapshot TTL expired

sb2.unmount_image("/workspace/project")  # reveal underlying FS again

Directory snapshots are Images — can also be passed as image= to Sandbox.create(). Pair with Image.from_scratch() for lightweight mount payloads.

Memory snapshot (Beta)

sb = modal.Sandbox.create(app=app, _experimental_enable_snapshot=True)
snapshot = sb._experimental_snapshot()
sb2 = modal.Sandbox._experimental_from_snapshot(snapshot)

Retained 7 days (not configurable via ttl=).

VM Sandboxes (Alpha)

Real Linux kernel for Docker-in-sandbox, eBPF, systemd, cgroups, custom mounts — better FS I/O. Alpha; CPU only (no GPUs); memory is static (default ~1 GiB if unset).

sb = modal.Sandbox.create(
    app=app,
    cpu=2,
    memory=4096,
    experimental_options={"vm_runtime": True},
)
# CLI: modal shell --experimental-option vm_runtime=1

For Docker-in-sandbox without VM runtime, Sysbox-based images (e.g. nestybox/ubuntu-noble-systemd-docker) remain an option — also Alpha-adjacent; prefer VM runtime when you need a full kernel.

Network Controls

sb = modal.Sandbox.create(
    app=app,
    block_network=True,                                    # no internet
    outbound_domain_allowlist=["api.openai.com", "*.github.com"],  # TLS :443
    outbound_cidr_allowlist=["1.2.3.0/24"],                # whitelist outbound IPs
    inbound_cidr_allowlist=["10.0.0.0/8"],                 # whitelist inbound
    encrypted_ports=[443],
    unencrypted_ports=[8080],
    custom_domain="sandboxes.mydomain.com",
)
# Prefer outbound_cidr_allowlist — cidr_allowlist is deprecated
tunnel = sb.tunnels()[443]
print(tunnel.url)  # https://<hash>.modal.run

Go SDK

mc, _ := modal.NewClient()
app, _ := mc.Apps.FromName(ctx, "my-app", &modal.AppFromNameParams{CreateIfMissing: true})
image := mc.Images.FromRegistry("python:3.11", nil)

sb, _ := mc.Sandboxes.Create(ctx, app, image, &modal.SandboxCreateParams{
    GPU:       "T4",
    Timeout:   10 * time.Minute,
    MemoryMiB: 4096,
})
defer sb.Detach()

p, _ := sb.Exec(ctx, []string{"python", "-c", "print('hello')"}, nil)
stdout, _ := io.ReadAll(p.Stdout)
fmt.Println(string(stdout))

img, _ := sb.SnapshotFilesystem(ctx, nil)
sb.Terminate(ctx, nil)

TypeScript SDK

import { ModalClient, Probe } from "modal";
const modal = new ModalClient();

const app = await modal.apps.fromName("my-app", { createIfMissing: true });
const image = modal.images.fromRegistry("python:3.13");

const sb = await modal.sandboxes.create(app, image, {
    gpu: "T4",
    timeoutMs: 600000,
    memoryMiB: 4096,
    readinessProbe: Probe.withTcp(8080),
});

const proc = await sb.exec(["python", "-c", "print('hello')"]);
console.log(await proc.stdout.readText());

await sb.filesystem.writeText("some data", "/tmp/data.txt");
const snapshot = await sb.snapshotFilesystem();
await sb.terminate({ wait: true });
sb.detach();

Reference Map

  • references/sandbox-basics.md — creation, execution, lifecycle, tags, OIDC
  • references/sandbox-filesystem.md — filesystem API, watch, Volume mounts
  • references/sandbox-networking.md — tunnels, CIDR/domain allowlists, custom domains
  • references/sandbox-lifecycle.md — events, probes, snapshots, VM runtime, cleanup

Guardrails

  • Always set timeouts on exec() calls to prevent hanging
  • Use sb.terminate(wait=True) + sb.detach() when done
  • Sandboxes require an App (use App.lookup for standalone scripts)
  • gVisor sandboxing provides isolation; VM runtime is Alpha (real kernel)
  • Each Sandbox is a separate container with its own filesystem
  • Snapshot TTLs (1.5+): filesystem and directory snapshots default to 30 days; pass ttl=None for indefinite. Memory snapshots expire in 7 days
  • Prefer sb.filesystem.* over deprecated open/ls/mkdir/rm/Sandbox.watch
  • Prefer outbound_cidr_allowlist over deprecated cidr_allowlist
  • VM Sandboxes and Docker-in-Sandbox are Alpha — expect changes and higher resource needs

Key References

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.