cloudflare-sandbox
Cloudflare Sandboxes SDK for secure code execution in Linux containers at edge. Use for untrusted code, Python/Node.js scripts, AI code interpreters, git operations.
What this skill does
# Cloudflare Sandboxes SDK **Status**: Production Ready (Open Beta) **Last Updated**: 2025-12-10 **Dependencies**: `cloudflare-worker-base`, `cloudflare-durable-objects` (recommended for understanding) **Latest Versions**: `@cloudflare/[email protected]`, Docker image: `cloudflare/sandbox:0.6.3-python` **⚠️ BREAKING CHANGE (v0.6.0):** Python is no longer included in the default image. Use `cloudflare/sandbox:<version>-python` for Python support (~1.3GB with data science packages). The lean variant (~600-800MB) excludes Python. --- ## Quick Start (15 Minutes) ### 1. Install SDK and Setup Wrangler ```bash bun add @cloudflare/sandbox@latest # preferred # or: bun add @cloudflare/sandbox@latest ``` **wrangler.jsonc:** ```jsonc { "name": "my-sandbox-worker", "main": "src/index.ts", "compatibility_flags": ["nodejs_compat"], "containers": [{ "class_name": "Sandbox", "image": "cloudflare/sandbox:0.6.3-python", "instance_type": "lite" }], "durable_objects": { "bindings": [{ "class_name": "Sandbox", "name": "Sandbox" }] }, "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Sandbox"] }] } ``` **Why this matters:** - `nodejs_compat` enables Node.js APIs required by SDK - `containers` defines the Ubuntu container image - `durable_objects` binding enables persistent routing - `migrations` registers the Sandbox class ### 2. Create Your First Sandbox Worker ```typescript import { getSandbox, type Sandbox } from '@cloudflare/sandbox'; export { Sandbox } from '@cloudflare/sandbox'; type Env = { Sandbox: DurableObjectNamespace<Sandbox>; }; export default { async fetch(request: Request, env: Env): Promise<Response> { // Get sandbox instance (creates if doesn't exist) const sandbox = getSandbox(env.Sandbox, 'my-first-sandbox'); // Execute Python code const result = await sandbox.exec('python3 -c "print(2 + 2)"'); return Response.json({ output: result.stdout, success: result.success, exitCode: result.exitCode }); } }; ``` **CRITICAL:** - **MUST export** `{ Sandbox }` from `@cloudflare/sandbox` in your Worker - Sandbox ID determines routing (same ID = same container) - First request creates container (~2-3 min cold start) - Subsequent requests are fast (<1s) ### 3. Deploy and Test ```bash npm run deploy curl https://your-worker.workers.dev ``` Expected output: ```json { "output": "4\n", "success": true, "exitCode": 0 } ``` ## Secure Installation Sandbox SDK packages grant container access — verify before installing to prevent unauthorized code execution. Follow supply chain security best practices: - **Block post-install scripts** — `npm config set ignore-scripts true` (or Bun: disabled by default) - **Cooldown period** — Wait 7 days for new package versions to be vetted by the community - **Audit before installing** — Run `socket package score npm <pkg>` or use `socket npm install <pkg>` to check packages Load the `dependency-upgrade` skill for full security configuration including Socket CLI integration, cooldown setup, lockfile validation, and CI enforcement. --- ## Architecture (Understanding the 3-Layer Model) ### How Sandboxes Work ``` ┌─────────────────────────────────────────┐ │ Your Worker (Layer 1) │ │ - Handles HTTP requests │ │ - Calls getSandbox() │ │ - Uses sandbox.exec(), writeFile(), etc│ └──────────────┬──────────────────────────┘ │ RPC via Durable Object ┌──────────────▼──────────────────────────┐ │ Durable Object (Layer 2) │ │ - Routes by sandbox ID │ │ - Maintains persistent identity │ │ - Geographic stickiness │ └──────────────┬──────────────────────────┘ │ Container API ┌──────────────▼──────────────────────────┐ │ Ubuntu Container (Layer 3) │ │ - Full Linux environment │ │ - Python 3.11, Node 20, Git, etc. │ │ - Filesystem: /workspace, /tmp, /home │ │ - Process isolation (VM-based) │ └─────────────────────────────────────────┘ ``` **Key Insight**: Workers handle API logic (fast), Durable Objects route requests (persistent identity), Containers execute code (full capabilities). --- ## Critical Container Lifecycle (Most Important Section!) ### Container States ``` ┌─────────┐ First request ┌────────┐ ~10 min idle ┌──────┐ │ Not │ ───────────────>│ Active │ ─────────────> │ Idle │ │ Created │ │ │ │ │ └─────────┘ └───┬────┘ └──┬───┘ │ ^ │ │ │ New request │ │ └──────────────────────┘ │ │ ▼ ▼ Files persist ALL FILES DELETED Processes run ALL PROCESSES KILLED State maintained ALL STATE RESET ``` ### The #1 Gotcha: Ephemeral by Default **While Container is Active** (~10 min after last request): - ✅ Files in `/workspace`, `/tmp`, `/home` persist - ✅ Background processes keep running - ✅ Shell environment variables remain - ✅ Session working directories preserved **When Container Goes Idle** (after inactivity): - ❌ **ALL files deleted** (entire filesystem reset) - ❌ **ALL processes terminated** - ❌ **ALL shell state lost** - ⚠️ Next request creates **fresh container from scratch** **This is NOT like a traditional server**. Sandboxes are ephemeral by design. ### Handling Persistence **For Important Data**: Use external storage ```typescript // Save to R2 before container goes idle await sandbox.writeFile('/workspace/data.txt', content); const fileData = await sandbox.readFile('/workspace/data.txt'); await env.R2.put('backup/data.txt', fileData); // Restore on next request const restored = await env.R2.get('backup/data.txt'); if (restored) { await sandbox.writeFile('/workspace/data.txt', await restored.text()); } ``` **For Build Artifacts**: Accept ephemerality or use caching ```typescript // Check if setup needed (handles cold starts) const exists = await sandbox.readdir('/workspace/project').catch(() => null); if (!exists) { await sandbox.gitCheckout(repoUrl, '/workspace/project'); await sandbox.exec('npm install', { cwd: '/workspace/project' }); } // Now safe to run build await sandbox.exec('npm run build', { cwd: '/workspace/project' }); ``` --- ## Session Management (Game-Changer for Chat Agents) ### What Are Sessions? Sessions are **bash shell contexts** within one sandbox. Think terminal tabs. **Key Properties**: - Each session has separate working directory - Sessions share same filesystem - Working directory persists across commands in same session - Perfect for multi-step workflows ### Pattern: Chat-Based Coding Agent ```typescript type ConversationState = { sandboxId: string; sessionId: string; }; // First message: Create sandbox and session const sandboxId = `user-${userId}`; const sandbox = getSandbox(env.Sandbox, sandboxId); const sessionId = await sandbox.createSession(); // Store in conversation state (database, KV, etc.) await env.KV.put(`conversation:${conversationId}`, JSON.stringify({ sandboxId, sessionId })); // Later messages: Reuse same session const state = await env.KV.get(`conversation:${conversationId}`); const { sandboxId, sessionId } = JSON.parse(state); const sandbox = getSandbox(env.Sandbox, sandboxId); // Commands run in same context await sandbox.exec('cd /workspace/project', { session: sessionId }); await sandbox.exec('ls -la', { session: sessionId }); // Still in /workspace/project await sandbox.exec('git status', { session: sessionId }); // Still in /workspace/project ``` ### Without Sessions (Common Mistake) ```typescript // ❌ WRONG: Each command r
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.