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

# Serverless execution

> Run bash commands directly on an Archil file system.

Archil's serverless execution makes it simple to run untrusted code like bash, Python, and Node.js
directly on the data in your Archil file system **without** needing to manage the lifecycle of
a separate sandbox instance.

Serverless execution is built on full-featured Linux microVMs that are colocated with your
data for maximum security and performance. Each Archil disk can run many commands concurrently,
and execution is included in the per-call price. This makes them ideal for tasks such as the bash tool in an AI agent loop.

Serverless execution is available in Archil's public AWS regions and in
[BYOC deployments](https://docs.archil.com/reference/byoc.md) on any cloud (AWS, Google Cloud, or Azure) or bare
metal. See [Region availability](https://docs.archil.com/reference/regions.md#compute-availability).

If you instead need a sandbox that stays alive in-between calls for the purpose of running commands with
long startup times or network services, you can use an Archil [Persistent Sandbox](https://docs.archil.com/compute/sandboxes/introduction.md).

```typescript TypeScript theme={null}
import * as archil from "disk";

const { disk } = await archil.createDisk({ name: "agent-workspace" });
const { stdout } = await disk.exec("git clone --depth 1 https://github.com/pallets/flask.git");
```

```python Python theme={null}
import archil
from archil import S3Mount

result = archil.create_disk(name="agent-workspace")
res = result.disk.exec("git clone --depth 1 https://github.com/pallets/flask.git")
```

```bash CLI theme={null}
npx disk dsk-abc123 exec "git clone --depth 1 https://github.com/pallets/flask.git"
```

Companies are using Archil's serverless execution for:

* **Running untrusted AI-generated code** on a machine that is close to the context that the AI
  is attempting to work on, without risking that code breaking the origin server.
* **Running map-reduce style jobs across large data sets** for data analysis tasks such as full-text
  search or aggregation.
* **Using your disk from a different region** in order to avoid excessive network latency between
  your application code and the disk, and reduce the amount of data transferred out of Archil.

Each `disk.exec()` invocation at the default size counts as one serverless tool call, even when it runs several
commands. Execution is included in the per-call price. See [Pricing & Billing](https://docs.archil.com/administration/billing.md#serverless-tool-calls).

## Working directory and environment

Each command starts with the working directory set to where your Archil disk is mounted
(`/mnt/archil`). The default runtime image includes most common Unix tools. To run in a different environment,
[choose an image](#choosing-an-image), or install additional tools by directing the binaries to your disk.

## Choosing an image

By default, commands run in Archil's exec image. To run a command in your own environment, pass `baseImage`
(`base_image` in Python) with any public Linux OCI image built for `amd64`, such as `python:3.13`. Docker Hub
shorthand works, as does a full reference such as `ghcr.io/acme/agent-runtime:v2`.

```typescript TypeScript theme={null}
import * as archil from "disk";

const disk = await archil.getDisk("dsk-abc123");
const { stdout } = await disk.exec("python3 analyze.py", {
  baseImage: "python:3.13",
});
```

```python Python theme={null}
import archil

disk = archil.get_disk("dsk-abc123")
res = disk.exec("python3 analyze.py", base_image="python:3.13")
```

```bash REST theme={null}
curl --request POST \
  'https://control.green.us-east-1.aws.prod.archil.com/api/disks/dsk-abc123/exec' \
  --header "Authorization: Bearer $ARCHIL_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{"command": "python3 analyze.py", "baseImage": "python:3.13"}'
```

The first exec with a new image waits while Archil prepares it; later execs with the same image reuse it.

For a private image, or to prepare a public image before the first call, build it with the
[images API](https://docs.archil.com/compute/sandboxes/images.md) and pass the returned `imageId` (`image_id` in Python) instead. The exec runs
the image's latest successful build. An image that has not finished its first build is rejected with `409`
`image_not_ready`. `baseImage` and `imageId` are mutually exclusive.

```typescript TypeScript theme={null}
import { Archil } from "disk";

const client = new Archil({ apiKey: process.env.ARCHIL_API_KEY, region: "aws-us-east-1" });
const image = await client.images.build({
  source: "ghcr.io/acme/agent-runtime:v2",
  registryAuth: {
    username: process.env.REGISTRY_USERNAME!,
    password: process.env.REGISTRY_TOKEN!,
  },
});

const disk = await client.disks.get("dsk-abc123");
const { stdout } = await disk.exec("agent-runtime --version", { imageId: image.imageId });
```

```python Python theme={null}
import os
from archil import Archil, RegistryAuth

with Archil(region="aws-us-east-1") as client:
    image = client.images.build(
        source="ghcr.io/acme/agent-runtime:v2",
        registry_auth=RegistryAuth(
            username=os.environ["REGISTRY_USERNAME"],
            password=os.environ["REGISTRY_TOKEN"],
        ),
    )
    disk = client.disks.get("dsk-abc123")
    res = disk.exec("agent-runtime --version", image_id=image.image_id)
```

Your disks are mounted under `/mnt/archil` in every image.

## Choosing a size

Each command runs in a microVM with 2 vCPU and 4096 MiB of memory by default. Pass `vcpuCount` (1 to 32) and
`memSizeMib` (256 to 65,536) to size it for the work, such as a build or a data-processing step that needs more
memory. In Python, these are `vcpu_count` and `mem_size_mib`.

```typescript TypeScript theme={null}
const { stdout } = await disk.exec("make -j8", {
  vcpuCount: 8,
  memSizeMib: 16384,
});
```

```python Python theme={null}
res = disk.exec("make -j8", vcpu_count=8, mem_size_mib=16384)
```

A larger command bills as several calls: its size as a multiple of the default, by whichever of vCPU and memory is
the larger multiple, rounded up. The example above, 8 vCPU and 16 GiB, is four times the default and bills as four
calls. A smaller command still bills as one call. See [Pricing & Billing](https://docs.archil.com/administration/billing.md#serverless-tool-calls).

The Free plan runs every command at the default size; a larger request is rejected with `403`
`tool_call_size_limit_exceeded`.

## Restricting network access

By default, a command has unrestricted network egress. On the Developer, Team, and Enterprise plans, pass `network`
to apply the same egress rules as the [sandbox firewall](https://docs.archil.com/compute/sandboxes/firewall.md), such as denying everything but
a package registry:

```typescript TypeScript theme={null}
const { stdout } = await disk.exec("pip install -r requirements.txt && python3 train.py", {
  baseImage: "python:3.13",
  network: {
    egress: { default: "deny", allow: ["pypi.org", "files.pythonhosted.org"] },
  },
});
```

```python Python theme={null}
from archil import SandboxEgressPolicy, SandboxNetwork

res = disk.exec(
    "pip install -r requirements.txt && python3 train.py",
    base_image="python:3.13",
    network=SandboxNetwork(
        egress=SandboxEgressPolicy(default="deny", allow=["pypi.org", "files.pythonhosted.org"]),
    ),
)
```

Your mounted disks stay reachable under a deny-by-default policy. The policy applies only to that command and is not
stored. On the Free plan, a request with `network` is rejected with `403` `network_plan_required`.

`baseImage`, `imageId`, `vcpuCount`, `memSizeMib`, and `network` work the same way on multi-disk commands
[run with `archil.exec`](#composing-multiple-disks-into-a-single-command).

## Composing multiple disks into a single command

Often, users need to run commands on multiple disks at once. For example, if you're building an
AI agent which has access to a read-only customer-specific disk and a read-write session-specific
disk, and you want your agent to use documents on both disks.

To run a command against several disks, you instead pass a map of disks into `archil.exec`. Each
disk is automatically mounted to the `/mnt/archil/<key>` path inside the sandbox. For example, in the
code below, the `data` disk is mounted to `/mnt/archil/data` and the `logs` disk is mounted to `/mnt/archil/logs`.

```typescript TypeScript theme={null}
import * as archil from "disk";

const { stdout } = await archil.exec({
  disks: {
    data: "dsk-abc123",
    logs: "dsk-def456",
  },
  command: "wc -l /mnt/archil/data/*.csv > /mnt/archil/logs/lines.txt",
});
```

```python Python theme={null}
import archil

res = archil.exec(
    disks={
        "data": "dsk-abc123",
        "logs": "dsk-def456",
    },
    command="wc -l /mnt/archil/data/*.csv > /mnt/archil/logs/lines.txt",
)
```

## Specifying disk options

You may want to run a command in which some disks have reduced permissions, so the code
running cannot modify them. Serverless execution supports specifying whether or not a disk should be
marked as read-only or whether it should be limited to a subdirectory of the disk.

For example, in the code below, the `logs` disk will be mounted to `/mnt/archil/logs`. That directory
will be read-only, and code in the sandbox cannnot modify it. It will only display the contents of
the `app/logs` subdirectory of the disk.

```typescript TypeScript theme={null}
import * as archil from "disk";

const { stdout } = await archil.exec({
  disks: {
    data: "dsk-abc123",
    logs: {
      disk: "dsk-def456",
      subdirectory: "app/logs",
      readOnly: true,
    },
  },
  command: "wc -l /mnt/archil/logs/*.log",
});
```

```python Python theme={null}
import archil
from archil import ExecMountSpec

res = archil.exec(
    disks={
        "data": "dsk-abc123",
        "logs": ExecMountSpec("dsk-def456", subdirectory="app/logs", read_only=True),
    },
    command="wc -l /mnt/archil/logs/*.log",
)
```

## Consistency with other clients

Serverless execution works like other Archil clients, with the same read-after-write
consistency model. A file written to the disk by one command is immediately visible to the
next command that reads it.

By default, disks are mounted in shared mode, which means that you'll need to
take care to call `archil checkout` before mutating files on the disk. For more details on how to
checkout or checkin files in shared mode, see [Sharing disks](https://docs.archil.com/concepts/sharing-disks.md).

## Limits

| Limit | Value |
| - | - |
| Time per command | 5 minutes |
| Command length (input) | 100 KiB |
| Output returned | The first 4 MiB of stdout and the first 4 MiB of stderr |
| Resources per command | 2 vCPU and 4 GiB of memory by default, up to 32 vCPU and 64 GiB ([choosing a size](#choosing-a-size)) |

* After 5 minutes, the call returns `504` with `Exec timed out` and the command is stopped. Writes the command
  flushed with `fsync` before the timeout are durable; other writes are flushed on a best-effort basis as the command
  is stopped. For longer work, use a [persistent sandbox](https://docs.archil.com/compute/sandboxes/introduction.md), which has no per-command
  timeout.
* A command longer than 100 KiB is rejected with `400`. There is no separate stdin. To pass a larger input, write it to
  the disk first, for example with [`putObject`](https://docs.archil.com/protocols/s3-api), and have the command read the file.
* Output past 4 MiB on a stream is dropped, and the stream ends with `[output truncated]`. To keep larger output, write
  it to a file on the disk and read it with the [getObject API](https://docs.archil.com/protocols/s3-api.md).
* When a command finishes, its writes to the mounted disk are committed before the response returns. If committing fails, the
  command's exit code is non-zero and stderr says `archil: command output may not have been durably committed`.
* Users can execute hundreds of commands in parallel, contact us to have your
  limits raised to thousands.

## Latency

Each call starts a fresh microVM with your disks mounted. Every result reports `timing.queueMs`, the time from the
request arriving to the command starting, which includes booting the microVM and mounting the disks. In our
measurement from a laptop to a disk in AWS `us-west-2`, a trivial command (`true`) returned in 82 ms at the median end
to end, including about 40 ms of internet round trip, with a median `queueMs` of 37 ms. The first call on a newly
created disk took longer, 331 ms at the median. See
[How fast is a serverless tool call?](https://archil.com/article/how-fast-is-a-serverless-tool-call-for-an-ai-agent)
for the full results and a script to reproduce them.

These figures are for the default image and size, which start from a pool of ready microVMs. A command with a
different [image](#choosing-an-image) or [size](#choosing-a-size) boots its microVM on demand, so its `queueMs` is
higher.

## Next steps

* [Search files in parallel with `disk.grep`](https://docs.archil.com/compute/search-files)
* [Give an agent bash and file tools with the AI SDK](https://docs.archil.com/integrations/ai-sdk.md)
* [TypeScript SDK reference for `disk.exec`](https://docs.archil.com/sdks/typescript#executing-commands)
* [Python SDK reference for `Disk.exec`](https://docs.archil.com/sdks/python#executing-commands)
* [`disk` CLI reference](https://docs.archil.com/reference/disk-cli)


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