> For the list of every page, fetch /llms.txt. The API contract is the OpenAPI file linked from the API reference.

# Run a coding agent in a sandbox

This page runs Claude Code inside a sandbox, end to end. The agent works as a non-root user, can reach only Meadow, and spends from a key that allows one model and has a budget. The same steps fit any agent that speaks the OpenAI or Anthropic format.

Next step: save the Dockerfile and the script below, then run the script. It needs a key with the `admin`, `models` and `sandboxes` scopes, a stored `anthropic` key, and a stored `daytona` key.

## The image

With outbound traffic limited to Meadow, the sandbox cannot install anything at run time. So the agent, its tools, and its user go into an image. Save this as `Dockerfile`:

```dockerfile
FROM node:22-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates git python3 && rm -rf /var/lib/apt/lists/*
RUN npm install -g @anthropic-ai/claude-code
RUN useradd -m -s /bin/bash agent && mkdir -p /work && chown agent:agent /work
WORKDIR /work
CMD ["sleep", "infinity"]
```

`CMD ["sleep", "infinity"]` keeps the sandbox up on Modal, where a sandbox ends when the image's command exits. This Dockerfile copies no local files, so it needs no build context. See [Images and build contexts](/run-sandboxes/images-and-build-contexts).

## The run

Put the files the agent should work on in a folder named `task` next to the Dockerfile. Ours held one file, `calc.py`, with a bug:

```python
def add(a, b):
    return a - b
```

```bash
pip install requests
export MEADOW_BASE_URL="https://api.usemeadow.ai"
export MEADOW_API_KEY="mdw_..."
export PROJECT_ID="prj_..."
```

```python
import io
import os
import tarfile
import uuid
from datetime import datetime, timedelta, timezone
from urllib.parse import urlparse

import requests

BASE = os.environ["MEADOW_BASE_URL"]
HEADERS = {"Authorization": f"Bearer {os.environ['MEADOW_API_KEY']}"}  # admin, models and sandboxes scopes
PROJECT_ID = os.environ["PROJECT_ID"]
MODEL = "claude-haiku-5-5"
PROMPT = "Fix the bug in calc.py so that add returns the sum. Then write the single word DONE to /work/result.txt."


def call(method, path, **kwargs):
    resp = requests.request(method, f"{BASE}{path}", headers={**HEADERS, **kwargs.pop("headers", {})}, timeout=1900, **kwargs)
    if not resp.ok:
        raise RuntimeError(f"{method} {path}: {resp.status_code} {resp.text}")
    return resp


# 1. Build the image once. The same Dockerfile returns the same image on later runs.
image = call("POST", "/v1/images", params={"wait": "true"}, json={
    "name": "coding-agent",
    "dockerfile": open("Dockerfile").read(),
    "build_on": ["daytona"],
}).json()
if image["builds"][0]["status"] != "ready":
    raise RuntimeError(f"image build: {image['builds']}")
print("image", image["id"][:12], image["builds"][0]["status"])

# 2. Mint a key for this one run: one model, a request cap, a token budget, an expiry.
expires = (datetime.now(timezone.utc) + timedelta(hours=2)).strftime("%Y-%m-%dT%H:%M:%SZ")
key = call("POST", "/v1/keys", json={
    "project_id": PROJECT_ID,
    "name": "agent-run",
    "scopes": ["models"],
    "allowed_models": [MODEL],
    "max_requests": 40,
    "max_tokens": 400000,
    "expires_at": expires,
}).json()

# 3. Create the sandbox. Outbound traffic is limited to Meadow.
sandbox = call("POST", "/v1/sandboxes", params={"wait": "true"}, headers={"Idempotency-Key": str(uuid.uuid4())}, json={
    "image_id": image["id"],
    "timeout_seconds": 1800,
    "network": {"allow_domains": [urlparse(BASE).hostname]},
    "env": {
        "ANTHROPIC_BASE_URL": BASE,
        "ANTHROPIC_AUTH_TOKEN": key["secret"],
        "ANTHROPIC_MODEL": MODEL,
        "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "4096",
    },
    "provider": {"only": ["daytona"]},
}).json()
try:
    if sandbox["status"] != "running":
        raise RuntimeError(f"sandbox {sandbox['status']}: {sandbox['attempts']}")
    print("sandbox", sandbox["status"], "on", sandbox["provider"])
    url = f"/v1/sandboxes/{sandbox['id']}"

    # 4. Upload the task and hand it to the agent's user. Uploads belong to root.
    buffer = io.BytesIO()
    with tarfile.open(fileobj=buffer, mode="w") as archive:
        archive.add("task", arcname=".")
    call("PUT", f"{url}/files", params={"path": "/work", "archive": "tar"},
         headers={"Content-Type": "application/octet-stream"}, data=buffer.getvalue())
    call("POST", f"{url}/exec", json={"command": "chown -R agent:agent /work"})

    # 5. Start the agent in the background, as the non-root user, and follow its output.
    run = call("POST", f"{url}/exec", headers={"Idempotency-Key": str(uuid.uuid4())}, json={
        "command": ["claude", "-p", PROMPT, "--dangerously-skip-permissions"],
        "cwd": "/work",
        "user": "agent",
        "background": True,
        "timeout_seconds": 900,
    }).json()
    stdout_offset, stderr_offset = 0, 0
    while True:
        run = call("GET", f"{url}/execs/{run['id']}", params={
            "stdout_offset": stdout_offset, "stderr_offset": stderr_offset, "wait_seconds": 30,
        }).json()
        print(run["stdout"], end="")
        print(run["stderr"], end="")
        stdout_offset, stderr_offset = run["stdout_offset"], run["stderr_offset"]
        if run["status"] != "running" and not run["stdout"] and not run["stderr"]:
            break
    print("agent", run["status"], run["exit_code"])

    # 6. Fetch the results.
    print("result.txt:", call("GET", f"{url}/files", params={"path": "/work/result.txt"}).text.strip())
    print(call("GET", f"{url}/files", params={"path": "/work/calc.py"}).text, end="")
finally:
    call("DELETE", f"/v1/sandboxes/{sandbox['id']}")
    call("DELETE", f"/v1/keys/{key['id']}")
```

Output from a run against the hosted beta:

```text
image img_0000474a ready
sandbox running on daytona
Fixed `add` in `/work/calc.py`: it returned `a - b` and now returns `a + b`. `/work/result.txt` contains `DONE`.
I checked it with `add(2, 3)`, which returns 5. This is a plain directory, not a git repo, so there was no commit to make.
agent exited 0
result.txt: DONE
def add(a, b):
    return a + b
```

The image build took 53 seconds. With the image built, a run of the whole script took 19 seconds. The agent's own lines change from run to run.

## Why each step is there

1. The image is built once. `POST /v1/images` with the same Dockerfile returns the same image, so the script can call it on every run.
2. The key is the agent's budget. `allowed_models` stops it from calling a dearer model, `max_requests` and `max_tokens` stop a runaway loop, and `expires_at` ends the key if your cleanup never runs. The key has only the `models` scope, so the agent cannot create sandboxes or create keys. See [Authentication](/set-up-your-account/authentication#create-a-key).
3. `allow_domains` holds only the host of your base URL. The agent can call models through Meadow and nothing else. Meadow does not add its own host for you. See [Network rules](/run-sandboxes/network-rules#give-a-sandbox-access-to-meadow).
4. Claude Code reads `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, and `ANTHROPIC_MODEL` from the sandbox's `env`. `CLAUDE_CODE_MAX_OUTPUT_TOKENS` matters on a key with `max_tokens`: without it each call reserved about 145,000 tokens and the first call was rejected. See [Claude Code on a key with a token limit](/call-models/use-your-existing-tools#claude-code-on-a-key-with-a-token-limit).
5. Uploaded files do not belong to `agent`. A tar keeps the owner IDs of the machine that made it, so the script hands `/work` to `agent` with one `chown`. Without that step, a write into an uploaded folder as `agent` failed with `Permission denied`.
6. The agent runs as a background command. A blocking command is cut when your connection drops. A background command keeps running, and the loop reads its output by offset. The `Idempotency-Key` makes a retry of the start return the same command. See [Background commands](/run-sandboxes/running-commands#background-commands).
7. `--dangerously-skip-permissions` lets Claude Code edit files and run commands without asking. Claude Code rejects that flag as `root` (`--dangerously-skip-permissions cannot be used with root/sudo privileges`), which is one more reason for the `agent` user. Use it only in a sandbox like this one.
8. The `finally` block deletes the sandbox and revokes the key. Download what you need first: files and command output go with the sandbox.

## Size the key

`max_tokens` on a key is a lifetime budget of input plus output tokens. Claude Code sends about 17,000 tokens of system prompt and tools with every call, and one task takes several calls. With `CLAUDE_CODE_MAX_OUTPUT_TOKENS` set to `4096`, a one-line prompt reserved 21,099 tokens. The 400,000 token key above was enough for this task. A real task needs more. When a call no longer fits in what is left, Claude Code prints a line like this one, from a key that was too small for a single call:

```text
Failed to authenticate. API Error: 403 api key max_tokens limit would be exceeded: 0 of 1000 tokens used and 0 held by calls in flight on this key, and this request reserves 21099 tokens; lower its output token cap or shrink it
```

The key is fine. The budget is too small or spent. Read what is left with `GET /v1/key`, and raise the limit with `PATCH /v1/keys/{key_id}` or create a new key with a larger budget. See [Authentication](/set-up-your-account/authentication#read-a-key-and-its-usage). See [Token and request limits](/call-models/token-and-request-limits).

## Look inside while it runs

Add `"ssh": true` to the create request, or `"ports": [8000]`, to reach the sandbox from outside. Both worked on Daytona together with the domain allowlist: the port URL answered 200, an SSH login worked, and `example.com` was still blocked inside the SSH session. See [Files, ports, and SSH](/run-sandboxes/files-ports-and-ssh).

To follow many runs without polling, set a `webhook_url` and Meadow sends `sandbox.running` and `sandbox.terminated`. There are no events for commands. See [Webhooks](/run-sandboxes/webhooks).

## What was not run

- An interactive Claude Code session. Only print mode (`claude -p`) ran.
- Traffic other than what [Network rules](/run-sandboxes/network-rules#what-we-tried-beyond-https) lists. The allowlist is the provider's, and we tried a handful of connections.
- This flow on Modal. The pieces ran there one by one: a sandbox with a domain allowlist called Meadow, and `user` on exec worked.
- A long task. Ours took a few calls.

More in [Known limits](/reference/known-limits#running-sandboxes).

## API reference

Operations on this page: [`createImage`](/reference/api-reference#createimage), [`createKey`](/reference/api-reference#createkey), [`createSandbox`](/reference/api-reference#createsandbox), [`uploadFile`](/reference/api-reference#uploadfile), [`execInSandbox`](/reference/api-reference#execinsandbox), [`getExec`](/reference/api-reference#getexec), [`downloadFile`](/reference/api-reference#downloadfile), [`deleteSandbox`](/reference/api-reference#deletesandbox), [`revokeKey`](/reference/api-reference#revokekey).