> For the complete documentation index, see [llms.txt](https://docs.cloud.olakrutrim.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cloud.olakrutrim.com/basics/core-infrastructure/sandbox.md).

# Sandbox

Krutrim Cloud Sandbox provides isolated, ephemeral cloud environments for running code, testing applications, executing workloads, and supporting autonomous AI agentic workflows.

Sandboxes can be created and managed through the Krutrim Cloud Console, Python/TypeScript SDKs, direct REST API, MCP Server, and the native Hermes Agent plugin.

### Python SDK for Sandbox

Sandbox is part of the **Core Infrastructure SDK**. Install the PyPI package `krutrim-client`:

```bash
pip install krutrim-client
```

Import the client from the Python module `krutrim_client`:

```python
from krutrim_client import KrutrimClient
```

The package name uses a hyphen (`krutrim-client`); the import module uses an underscore (`krutrim_client`). The separate `krutrim-cloud` package is for AI Studio/model APIs and does not provide Sandbox APIs.

For SDK selection, installation and client setup, see the [Core Infrastructure SDK guide](https://docs.cloud.olakrutrim.com/sdk-guide/core-infra-sdk). Do not substitute AI Studio SDK examples for Sandbox calls.

***

### What You Can Do

* **Isolated Compute**: Spin up secure gVisor-isolated containers with dedicated CPU and memory in seconds.
* **Dedicated Workspace**: A persistent workspace directory at `/app` for code, artifacts, and execution state.
* **Command Execution**: Execute synchronous bash commands with stdout/stderr capture and configurable timeouts (\~60s).
* **Full Filesystem Management**: Upload, download, list, stat, move, and delete files and directories via Base64 wire protocol.
* **Port Forwarding & Web Previews**: Forward container ports (1024–65535) to public HTTPS URLs to preview web apps.
* **Environment Configuration**: Pass runtime environment variables to container processes.
* **Lifecycle & TTL Management**: Automated resource reclamation with configurable TTL from 1 minute to 7 days.

***

### Create a Sandbox

The active regions are `In-Bangalore-1` (Bangalore) and `In-Hyderabad-1` (Hyderabad).

#### Using the Console

You can create a Sandbox from the Krutrim Cloud Console by providing the required configuration:

| Setting                   | What to Configure                             | Constraints & Rules                                                                                                                                                                                               |
| ------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Sandbox Name**          | Specify a unique identifier for your Sandbox. | **1–28 characters**, lowercase letters, digits, and hyphens only. Must start with a letter and end with a letter/digit. *(Capped at 28 chars so the platform-generated DNS subdomain fits within 63 characters).* |
| **Region**                | Select the deployment region.                 | `In-Bangalore-1` & `In-Hyderabad-1`                                                                                                                                                                               |
| **Compute Flavor**        | Select CPU and RAM configuration.             | Bangalore: `sandbox-nano` to `sandbox-x-large`. Hyderabad: `sandbox-nano-hyd` to `sandbox-x-large-hyd`.                                                                                                           |
| **Expiry (TTL)**          | Maximum lifetime before auto-deletion.        | **60s to 604,800s (1 min to 7 days)**. Defaults to **3,600s (1 hour)** if omitted.                                                                                                                                |
| **Environment Variables** | Key-value pairs passed into the container.    | String-to-string dictionary.                                                                                                                                                                                      |

***

#### Compute Configuration

Choose a compute flavor based on your deployment region and workload's CPU and memory requirements. All flavors include 20 GB of ephemeral disk storage.

**Bangalore (`In-Bangalore-1`)**

| Flavor ID         | vCPU |   RAM   | Ephemeral Disk | Hourly Pricing | Recommended Workload                                      |
| ----------------- | :--: | :-----: | :------------: | :------------: | --------------------------------------------------------- |
| `sandbox-nano`    | 0.25 | 0.5 GiB |      20 GB     |   ₹1.56 / hr   | Micro-benchmarks, basic scripts, shell tests              |
| `sandbox-small`   | 0.50 | 1.0 GiB |      20 GB     |   ₹2.91 / hr   | Python scripting, code interpreters, small CLI tools      |
| `sandbox-medium`  | 1.00 | 2.0 GiB |      20 GB     |   ₹5.61 / hr   | Web servers (FastAPI/Express), data parsing, test runners |
| `sandbox-large`   | 2.00 | 4.0 GiB |      20 GB     |   ₹11.01 / hr  | Multi-threaded builds, large dependency installations     |
| `sandbox-x-large` | 4.00 | 8.0 GiB |      20 GB     |   ₹21.81 / hr  | Heavy compilation, data science, pandas/numpy pipelines   |

**Hyderabad (`In-Hyderabad-1`)**

Use the exact Hyderabad flavor name with the `-hyd` suffix when creating a Sandbox in `In-Hyderabad-1`.

| Flavor ID             | vCPU |   RAM   | Ephemeral Disk | Hourly Pricing | Recommended Workload                                      |
| --------------------- | :--: | :-----: | :------------: | :------------: | --------------------------------------------------------- |
| `sandbox-nano-hyd`    | 0.25 | 0.5 GiB |      20 GB     |   ₹1.56 / hr   | Micro-benchmarks, basic scripts, shell tests              |
| `sandbox-small-hyd`   | 0.50 | 1.0 GiB |      20 GB     |   ₹2.91 / hr   | Python scripting, code interpreters, small CLI tools      |
| `sandbox-medium-hyd`  | 1.00 | 2.0 GiB |      20 GB     |   ₹5.61 / hr   | Web servers (FastAPI/Express), data parsing, test runners |
| `sandbox-large-hyd`   | 2.00 | 4.0 GiB |      20 GB     |   ₹11.01 / hr  | Multi-threaded builds, large dependency installations     |
| `sandbox-x-large-hyd` | 4.00 | 8.0 GiB |      20 GB     |   ₹21.81 / hr  | Heavy compilation, data science, pandas/numpy pipelines   |

All five flavors in each region are listed as `active` and `Available` in the flavor API responses. Prices are in INR per hour. Check current pricing and availability before creating a Sandbox.

For the REST creation example below, set `"region": "In-Hyderabad-1"` and `"flavorName": "sandbox-small-hyd"` to use the Hyderabad small flavor. For SDK calls, use `region="In-Hyderabad-1"` and `flavor_name="sandbox-small-hyd"`.

***

### Work in Your Sandbox

#### 1. Workspace

Each Sandbox provides a clean, writable workspace root at:

```bash
/app
```

**Network Egress Posture**

Sandboxes have **unrestricted outbound internet access** (HTTP/HTTPS/TCP egress) by default. Inbound traffic is strictly restricted to user-opened ports via the Port Forwarding API.

liAll commands and filesystem operations default to `/app`. Use `/app` (or `/app/project`) to store your source code, virtual environments, configuration files, and build artifacts.

***

#### 2. Run Commands

You can execute bash commands synchronously within an active Sandbox via the API, SDK, or MCP.

```bash
POST /omni/sandbox/v1/sandbox/{sandbox_id}/commands
```

**Capabilities & Features**:

* **Real-time Output Capture**: Returns `stdout`, `stderr`, and process `exitCode`.
* **Execution Timeout**: Configurable `timeoutSeconds` between **1 and 60 seconds** (default: 30s).
* **Truncation Flags**: `stdoutTruncated` and `stderrTruncated` indicate if output exceeded buffer limits.

**Common Use Cases**:

* Running application scripts (`python3 main.py`, `npm start`)
* Installing dependencies (`pip install -r requirements.txt`, `npm install`)
* Running test suites (`pytest`, `npm test`)
* Compiling binaries and processing datasets

***

#### 3. Manage Files

The Sandbox data plane provides 7 core filesystem operations:

* **Upload File** (`POST /files`): Upload files by providing the remote path and Base64-encoded file contents (`data_base64`).
* **Download File** (`GET /files?path=...`): Download file contents. For binary files (images, PDFs, tarballs), pass `format=bytes` to receive raw Base64 data.
* **List Directory** (`GET /directory?path=...`): List directory contents with file metadata (size, permissions, modified timestamp, `is_dir`).
* **File/Directory Stat** (`GET /stat?path=...`): Retrieve metadata for a single path without reading the entire file.
* **Create Directory** (`POST /directory`): Recursively create remote directories (`mkdir -p`).
* **Move / Rename** (`POST /move`): Relocate or rename files and directories (`source` $\rightarrow$ `destination`).
* **Delete Path** (`DELETE /files?path=...`): Delete a file or recursively remove an entire directory tree.

***

#### 4. Port Forwarding & Web Previews

Access an HTTP application through the authenticated HTTPS gateway. Start the application listening on `0.0.0.0`.

* **Open:** `POST /ports` with `{"port":3000}`. Allowed range: **1024–65535**, excluding runtime-reserved ports.
* **List:** `GET /ports`. Wait until the port is `active`.
* **Preview:** Add the API host to the returned relative `url` and send `Authorization: Bearer <API key>`. The URL does not provide anonymous access.
* **Close:** `DELETE /ports/{port}`. Closing is asynchronous and does not stop the application.

This interface supports HTTP/WebSocket traffic, not general-purpose raw TCP forwarding.

***

#### 5. Environment Variables

Environment variables can be configured when creating a Sandbox. They are injected into container subshells and applications, making it easy to configure API endpoints, runtime modes, and application flags.

***

#### 6. Ephemeral Storage Notice

{% hint style="warning" %}
**Sandbox storage is ephemeral (20 GB limit).**

When a Sandbox expires or is deleted, all files, installed packages, and generated artifacts in `/app` are permanently deleted. If data or artifacts must persist, download them via the Filesystem API or store them in an external storage service (e.g. Krutrim Cloud Object Storage) before the TTL expires.Inside the container, `df` reports 8.0EB via overlayfs. However, the real disk budget is 20 GB of node ephemeral storage per pod. Exceeding 20 GB will trigger pod eviction rather than returning a `disk full` error. Download critical artifacts via the Files API before TTL expiry.
{% endhint %}

***

### Sandbox Lifecycle

A Sandbox progresses through the following deterministic lifecycle states:

```
┌─────────────┐       ┌────────────┐       ┌─────────────┐       ┌───────────┐
│  deploying  │ ───>  │   active   │ ───>  │   deleting  │ ───>  │  HTTP 404 │
└─────────────┘       └────────────┘       └─────────────┘       └───────────┘
       │
       └───> ┌───────────────┐
             │ failed_deploy │
             └───────────────┘
```

| State           | Description                                                   | Next Actions                                      |
| --------------- | ------------------------------------------------------------- | ------------------------------------------------- |
| `deploying`     | The container is provisioning and booting the runtime daemon. | Poll `GET /sandbox/{id}` until status changes.    |
| `active`        | The Sandbox is ready to accept commands and file operations.  | Execute workloads, transfer files, forward ports. |
| `deleting`      | The Sandbox is being torn down and resources reclaimed.       | Wait for completion (verified by HTTP 404).       |
| `failed_deploy` | Container provisioning timed out or failed to initialize.     | Inspect error details; delete and recreate.       |

**Pause and resume:** Sandboxes currently cannot be paused or resumed. An idle Sandbox continues billing until it expires or is deleted. Save required files externally before deleting it.

***

#### TTL (Sandbox Lifetime)

The TTL is an **absolute lifetime starting from the moment the Sandbox reaches `active` status**.

{% hint style="info" %}
**TTL is NOT an idle timeout.** Making API calls, running commands, or transferring files does **not** reset the TTL timer.
{% endhint %}

**TTL Boundaries:**

* **Minimum TTL**: `60` seconds (1 minute).
* **Maximum TTL**: `604,800` seconds (7 days).
* **Default TTL**: `3,600` seconds (1 hour) if omitted.

**Extending Lifetime:**

You can extend an active Sandbox's lifetime at any time by calling the Reset TTL endpoint:

```bash
POST /omni/sandbox/v1/sandbox/{sandbox_id}/reset-ttl
```

### Direct REST API Quickstart

#### 1. Create a Sandbox

```bash
curl -X POST "https://cloud.olakrutrim.com/omni/sandbox/v1/sandbox" \
  -H "Authorization: Bearer $KRUTRIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "sandboxName": "my-app-sandbox",
    "flavorName": "sandbox-small",
    "region": "In-Bangalore-1",
    "ttlSeconds": 3600
  }'
```

#### 2. Poll Status

```bash
curl -X GET "https://cloud.olakrutrim.com/omni/sandbox/v1/sandbox/{sandbox_id}" \
  -H "Authorization: Bearer $KRUTRIM_API_KEY"
```

#### 3. Execute a Command

```bash
curl -X POST "https://cloud.olakrutrim.com/omni/sandbox/v1/sandbox/{sandbox_id}/commands" \
  -H "Authorization: Bearer $KRUTRIM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "cmd": "python3 --version",
    "timeoutSeconds": 30,
    "cwd": "/app"
  }'
```

#### 4. Delete a Sandbox

```bash
curl -X DELETE "https://cloud.olakrutrim.com/omni/sandbox/v1/sandbox/{sandbox_id}" \
  -H "Authorization: Bearer $KRUTRIM_API_KEY"
```

***

### Best Practices

1. **Select the Right Flavor**: Use `sandbox-small` for general scripts and agents; scale up to `sandbox-large` or `sandbox-x-large` for heavy builds or data analysis.
2. **Set Intentional TTLs**: Always pass explicit `ttlSeconds` tailored to your task duration to prevent accidental compute charges.
3. `ttlSeconds` serves as the primary orphan guard. Set intentional TTL values to automatically prevent abandoned sandboxes from continuing to incur compute charges.
4. **Persist Critical Data**: Download logs, datasets, and generated artifacts before deleting the Sandbox or before the TTL expires.
5. **Explicit Teardown**: Call `DELETE /sandbox/{id}` immediately upon task completion to release resources and stop billing.
