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

# Working with sandboxes

> Execute commands and exchange files in an isolated cloud sandbox.

Create a sandbox to execute commands and exchange files in one isolated running environment. Commands share its filesystem until it stops.

| Concept | What it does | Where it runs |
| - | - | - |
| **[Serverless Function](https://docs.mobilerun.ai/routines/functions.md)** | A versioned Python file with typed inputs and outputs. | An isolated cloud environment for each run. |
| **Sandbox** | A running environment where you execute shell commands and exchange files until it stops. | Mobilerun Cloud; commands share that sandbox's filesystem. |
| **[Routine](https://docs.mobilerun.ai/routines)** | A trigger plus automation steps, including functions. | Mobilerun schedules and runs the steps; device operations act on the selected phone. |

All requests below use `https://api.mobilerun.ai/v1/compute` and your [API key](https://docs.mobilerun.ai/api-keys.md). TypeScript and Python examples require SDK 6.3.0 or later.

## Serverless Functions

For saved, versioned code that runs in a fresh sandbox each time, see [Working with Serverless Functions](https://docs.mobilerun.ai/routines/functions.md). That guide covers creating functions, running them, and reading results and logs.

## Create and use a sandbox

Use the API for a standalone sandbox. Create it once, execute commands in it, then stop it when finished. This example needs no device or outbound network access.

```typescript TypeScript theme={null}
import { MobilerunSDK } from '@mobilerun/sdk';

const mobilerun = new MobilerunSDK();

const sandbox = await mobilerun.compute.sandboxes.create({
  name: 'scratch', timeoutS: 300, idleTimeoutS: 60,
}, { headers: { 'Idempotency-Key': crypto.randomUUID() } });
try {
  while (sandbox.status === 'starting') {
    await new Promise(resolve => setTimeout(resolve, 1000));
    await sandbox.refresh();
  }
  if (sandbox.status !== 'running') throw new Error('Sandbox stopped before execution');
  const executed = await sandbox.exec({
    command: 'python --version', timeoutS: 30, waitS: 30,
  }, { headers: { 'Idempotency-Key': crypto.randomUUID() } });
  console.log(executed.data);
} finally {
  await sandbox.delete();
}
```

```python Python theme={null}
import time
from uuid import uuid4
from mobilerun_sdk import MobilerunSDK

mobilerun = MobilerunSDK()

sandbox = mobilerun.compute.sandboxes.create(
    name="scratch", timeout_s=300, idle_timeout_s=60, idempotency_key=str(uuid4()),
)
try:
    while sandbox.status == "starting":
        time.sleep(1)
        sandbox.refresh()
    if sandbox.status != "running":
        raise RuntimeError("Sandbox stopped before execution")
    executed = sandbox.exec(
        command="python --version", timeout_s=30, wait_s=30, idempotency_key=str(uuid4()),
    )
    print(executed.data)
finally:
    sandbox.delete()
```

```bash cURL theme={null}
curl --fail-with-body https://api.mobilerun.ai/v1/compute/sandboxes \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"name":"scratch","timeoutS":300,"idleTimeoutS":60}' > sandbox.json
SANDBOX_ID=$(jq -er '.data.id' sandbox.json)
while [ "$(jq -r '.data.status' sandbox.json)" = starting ]; do
  sleep 1
  curl --fail-with-body "https://api.mobilerun.ai/v1/compute/sandboxes/$SANDBOX_ID" \
    -H "Authorization: Bearer $MOBILERUN_API_KEY" > sandbox.json
done
[ "$(jq -r '.data.status' sandbox.json)" = running ] || exit 1
curl --fail-with-body "https://api.mobilerun.ai/v1/compute/sandboxes/$SANDBOX_ID/exec" \
  -H "Authorization: Bearer $MOBILERUN_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"command":"python --version","timeoutS":30,"waitS":30}'
curl --fail-with-body -X DELETE \
  "https://api.mobilerun.ai/v1/compute/sandboxes/$SANDBOX_ID" \
  -H "Authorization: Bearer $MOBILERUN_API_KEY"
```

Creation returns `201`; poll its status until `running` before executing commands. Command execution returns `200` when the command exits or `202` while it continues. Save `commandId` to poll the command before stopping a sandbox that still has work to finish. Stopping returns `202`, or `204` if already stopped.

| Operation | Request |
| - | - |
| Inspect status and expiry | `GET /compute/sandboxes/{sandboxId}` |
| List commands | `GET /compute/sandboxes/{sandboxId}/commands` |
| Read command output | `GET /compute/sandboxes/{sandboxId}/commands/{commandId}?waitS=30` |
| Upload file bytes | `PUT /compute/sandboxes/{sandboxId}/files?path=/work/input.json` with `Content-Type: application/octet-stream` |
| Download file bytes | `GET /compute/sandboxes/{sandboxId}/files?path=/work/output.json` |

Use URL-encoded absolute paths within `/work` for file operations. Keep files you need by downloading them before the sandbox stops.

## Limits

| Limit | Value |
| - | - |
| Outbound requests | 100 per 10 seconds per run; excess requests receive `429` and `Retry-After: 10`. |
| Sandbox lifetime | 60–21,600 seconds, subject to available budget. |
| Sandbox idle timeout | At least 60 seconds; cannot exceed its lifetime. Default is the smaller of 900 seconds and its lifetime. |
| Command timeout | 1–21,600 seconds, within the sandbox's remaining lifetime; default 60 seconds. |
| Commands running in one sandbox | 4. |
| Sandbox file upload/download | 768 KiB per file. |
| Inline stdout/stderr | Tail of up to 16 KiB each; check `truncated`. |

Concurrency and available minutes can also prevent a sandbox from starting.

## Results and logs

Sandbox command results include `status`, `exitCode`, `timedOut`, `stdout`, `stderr`, and `truncated`. A successful HTTP response does not guarantee the command succeeded: inspect its exit code. For larger results, write a file under `/work` and download it within the file limit.

## Network access and cost

Sandbox creation accepts `allowedHosts`. External network requests must use HTTPS on the default port and match an allowed hostname exactly; redirect targets are not followed automatically. Mobilerun API access uses platform-controlled credentials and permissions. Keep secrets out of source, inputs, output, and logs.

Sandboxes consume function minutes while running, including idle time. Stop them when finished. See [Credits & usage](https://docs.mobilerun.ai/credits.md) for function minutes and concurrent-run capacity.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.