Skip to content

Blog

Move files in and out of agent sandboxesuploads, volumes and buckets

Upload the inputs, let the sandbox fetch big public data itself, keep reused data on a volume or in an image, and download only what changed.

· The Runtime team

10 min read

Read as Markdown

Runtime (withruntime.com) moves a folder into a sandbox as one compressed archive. The archive is unpacked as it arrives. Volumes that outlive sandboxes are billed at about $0.10 per GiB per 30-day month. A short-lived signed link brings private bucket data in, and the sandbox never holds the bucket's key. An agent's work begins with files it did not make and ends with files someone else needs. Get the transfer wrong, and the result is slow starts, a server of yours that relays gigabytes for no reason, or a results folder full of node_modules. This post sorts an agent's files by where they come from and how often they are reused. It gives each kind its own route.

Which route fits which files?

Two questions decide the route: how big are the files, and will the next sandbox need them too?

Files Route Why
A user's upload, a prompt's attachment files.write from your server Small, and already in your hands
A project folder files.uploadFolder of a tar One archive, permissions and links kept
A public dataset or a release download The sandbox fetches it itself Your server never relays the bytes
Private data already in a bucket A signed link the sandbox fetches No key inside the sandbox
Data many sandboxes read: weights, a corpus A custom image Built once, in every sandbox made from it
A cache one agent reuses run after run A read-write volume, or an image Survives the sandbox
Results someone reads files.read of what changed Only the agent's output comes back
Results other systems read Uploaded to a signed link Lands where they already look

The rest of this post covers them in the order that an agent's task uses them: in, during, and out.

How do you hand a task to the agent?

Put everything the task needs in one folder, and upload it in one call. A folder travels as one compressed archive. The sandbox's own tar unpacks it as it arrives, so a thousand small files cost about the same as one archive. A single file goes up with files.write, at any size. Pass its SHA-256 and the write is refused unless the bytes match; with offset, a dropped upload carries on from where it stopped.

Then the agent works. At the end, you want its output, not the inputs you already have. List the folder, keep the files modified after the hand-over, and bring back only those:

TypeScriptimport { execFileSync } from "node:child_process";import { mkdir, mkdtemp, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { Sandbox } from "withruntime";// The task: a folder on your machine with the inputs and the instructions.const task = await mkdtemp(join(tmpdir(), "task-"));await writeFile(join(task, "sales.csv"), "region,revenue\nnorth,1200\nsouth,950\n");await writeFile(join(task, "TASK.md"), "Summarize revenue by region in out/summary.md\n");await using sbx = await Sandbox.create({ labels: { task: "revenue-summary" } });// In: one archive, unpacked as it arrives.await sbx.files.uploadFolder("/workspace/task", execFileSync("tar", ["-czf", "-", "-C", task, "."]));const handedOver = Date.now() - 2_000; // a little slack for the two clocks// The agent works here, through exec and files calls. Its output, for example:await sbx.files.write("/workspace/task/out/summary.md", "north: 1,200\nsouth: 950\n");// Out: only what changed since the hand-over.const { items } = await sbx.files.list({ path: "/workspace/task", depth: 4 });const changed = items.filter((e) => e.type === "file" && Date.parse(e.modifiedAt ?? "") >= handedOver);for (const file of changed) {  const local = join(task, file.path.slice("/workspace/task/".length));  await mkdir(dirname(local), { recursive: true });  await writeFile(local, await sbx.files.read(file.path));  console.log("brought back", file.path, `${file.size} bytes`);}console.log(`${changed.length} of ${items.length} entries changed`);
Pythonimport ioimport osimport tarfileimport tempfileimport timefrom datetime import datetimefrom withruntime import Sandbox# The task: a folder on your machine with the inputs and the instructions.task = tempfile.mkdtemp(prefix="task-")with open(os.path.join(task, "sales.csv"), "w") as f:    f.write("region,revenue\nnorth,1200\nsouth,950\n")with open(os.path.join(task, "TASK.md"), "w") as f:    f.write("Summarize revenue by region in out/summary.md\n")with Sandbox.create(labels={"task": "revenue-summary"}) as sbx:    archive = io.BytesIO()    with tarfile.open(fileobj=archive, mode="w:gz") as tar:        tar.add(task, arcname=".")    sbx.files.upload_folder("/workspace/task", archive.getvalue())  # in: one archive, unpacked as it arrives    handed_over = time.time() - 2  # a little slack for the two clocks    # The agent works here, through exec and files calls. Its output, for example:    sbx.files.write("/workspace/task/out/summary.md", "north: 1,200\nsouth: 950\n")    # Out: only what changed since the hand-over.    entries = sbx.files.list(path="/workspace/task", depth=4).items    changed = [e for e in entries if e.type == "file" and e.modified_at               and datetime.fromisoformat(e.modified_at.replace("Z", "+00:00")).timestamp() >= handed_over]    for file in changed:        local = os.path.join(task, file.path.removeprefix("/workspace/task/"))        os.makedirs(os.path.dirname(local), exist_ok=True)        with open(local, "wb") as out:            out.write(sbx.files.read(file.path))        print("brought back", file.path, f"{file.size} bytes")    print(f"{len(changed)} of {len(entries)} entries changed")

A time check is enough when the agent writes new files. When it edits files in place, and you need to know which edits changed the content, compare content hashes instead. The recorder in see what your agent did does this. For a code task, git diff inside the sandbox is the best option: it shows the change as text, ready to review.

Should big data pass through your server?

No. If the data is on the public internet, let the sandbox download it directly. The data arrives faster, your server stays out of the path, and nothing large is held in your process's memory on the way:

TypeScriptimport { Sandbox } from "withruntime";const url = "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2024-01.parquet";await using sbx = await Sandbox.create({  diskGB: 16,  network: { allowOutbound: ["d37ci6vzurychx.cloudfront.net"] }, // this host and no other});const r = await sbx.exec(`curl -fsSL --retry 3 -o trips.parquet '${url}' && ls -l trips.parquet`, {  cwd: "/workspace",  timeoutSeconds: 600,});console.log(r.exitCode, r.stdout.trim());
Pythonfrom withruntime import NetworkRules, Sandboxurl = "https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2024-01.parquet"with Sandbox.create(disk_gb=16,                    network=NetworkRules(allow_outbound=["d37ci6vzurychx.cloudfront.net"])) as sbx:    r = sbx.exec(f"curl -fsSL --retry 3 -o trips.parquet '{url}' && ls -l trips.parquet",                 cwd="/workspace", timeout_seconds=600)    print(r.exit_code, (r.stdout or "").strip())

Two settings in that code matter. The allowOutbound list names the one host the download needs. If a model later reads instructions inside the data, it still cannot send anything to another host. The disk is sized for the data: a sandbox's default disk is 4 GB, and a large file plus its unpacked or converted copy fills that quickly (size CPU and memory).

What about private data in a bucket?

Sign a link to it. Your server holds the bucket's key and signs a URL for the one object the task needs, valid for a few minutes. The sandbox downloads the object from the bucket directly. The agent gets the data, never the key, and the link stops working on its own:

TypeScriptimport { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";import { Sandbox } from "withruntime";const s3 = new S3Client({ region: "us-east-1" }); // your server's key, never the sandbox'sconst command = new GetObjectCommand({ Bucket: "acme-research", Key: "datasets/2026-q3/sales.parquet" });const link = await getSignedUrl(s3, command, { expiresIn: 300 }); // five minutesawait using sbx = await Sandbox.create({  network: { allowOutbound: ["acme-research.s3.us-east-1.amazonaws.com"] },});const r = await sbx.exec(`mkdir -p /workspace/data && curl -fsSL -o /workspace/data/sales.parquet '${link}'`);console.log(r.exitCode, (await sbx.exec("ls -la /workspace/data")).stdout);
Pythonimport boto3from withruntime import NetworkRules, Sandboxs3 = boto3.client("s3", region_name="us-east-1")  # your server's key, never the sandbox'slink = s3.generate_presigned_url(    "get_object", Params={"Bucket": "acme-research", "Key": "datasets/2026-q3/sales.parquet"},    ExpiresIn=300)  # five minuteswith Sandbox.create(network=NetworkRules(        allow_outbound=["acme-research.s3.us-east-1.amazonaws.com"])) as sbx:    r = sbx.exec(f"mkdir -p /workspace/data && curl -fsSL -o /workspace/data/sales.parquet '{link}'")    print(r.exit_code, sbx.exec("ls -la /workspace/data").stdout)

Sign only the objects this task needs, for only as long as the download takes. The agent cannot list, delete or overwrite anything else in your bucket. For results that other systems pick up, sign an upload link (put_object) for the one output path, and have the sandbox send the file with curl -T.

When is a volume the right answer?

Use a volume when the same bytes are needed by many sandboxes, or by the next sandbox. A volume is a disk that outlives sandboxes. It has two modes:

A volume is mounted read-write in one sandbox at a time: a package cache, a database file, a model's checkpoint directory. Each run picks up where the last one stopped. When the sandbox is deleted, the volume is detached, ready for the next one. Data that many sandboxes read at once, such as model weights or a reference corpus, belongs in a custom image instead: every sandbox made from it starts with its own copy.

TypeScriptimport { Runtime } from "withruntime";const runtime = new Runtime();const cache = await runtime.volumes.create({ sizeMiB: 10_240, name: "pip-cache" });for (const run of [1, 2]) {  // One sandbox at a time: the next run attaches the volume once this one is deleted.  await using sbx = await runtime.sandboxes.create({ volumes: [{ volume: cache.id, path: "/cache" }] });  const r = await sbx.exec("echo run >> /cache/runs.log && wc -l < /cache/runs.log");  console.log(`run ${run}: the cache has seen ${r.stdout?.trim()} runs`);}
Pythonfrom withruntime import Runtime, VolumeMountruntime = Runtime()cache = runtime.volumes.create(size_mib=10_240, name="pip-cache")for run in (1, 2):    # One sandbox at a time: the next run attaches the volume once this one is deleted.    with runtime.sandboxes.create(volumes=[VolumeMount(volume=cache.id, path="/cache")]) as sbx:        r = sbx.exec("echo run >> /cache/runs.log && wc -l < /cache/runs.log")        print(f"run {run}: the cache has seen {(r.stdout or '').strip()} runs")

A volume is billed for its full size from the moment it is created, whether or not it holds data. A snapshot keeps a sandbox's own memory and disk; keep the data you may want to roll back there, and use the volume for what you keep whatever happens (an undo button for AI agents).

Volume, image or bucket?

All three keep data beyond one sandbox. The difference is how often it changes and who writes it:

Keep it in Changes Written by Read by
A custom image Rarely: when you rebuild it Your build Every sandbox made from it
A volume Every run The sandbox using it One sandbox at a time
A bucket Any time, from anywhere Any system with the key A sandbox with a signed link

Tools and libraries belong in an image. They change when you decide to rebuild, and every sandbox from the image starts with them installed. Data that one run writes and the next run reads belongs on a volume. Data that other systems also read or write belongs in a bucket.

How should the model itself find the files?

Tell it. The task message should name the input folder, the output folder, and what belongs in each: "the data is in /workspace/task, write results to /workspace/task/out, do not change the inputs". A model that has to discover the layout spends its first turns on ls and find. A model that does not know where output belongs scatters it across the disk. That defeats the download step above. An agent connected over MCP reads, writes, and lists files with runtime_machines_read, runtime_machines_write and, through runtime_call_tool, runtime_machines_list_files.

What limits should you plan around?

A few numbers save a debugging session:

  • Four folder downloads run at the same time per sandbox. Upload and download a folder rather than a thousand files one by one.
  • Writes are checked. Pass a file's SHA-256 to files.write, and bytes that differ are refused with the file left as it was.
  • A folder that fails part way comes back as an archive every tar reader refuses, never as a short one that looks whole.
  • exclude leaves folders out of a download (node_modules,.cache), so only the agent's work comes back.

In short

  • Upload a task's inputs as one folder, and bring back only the files that changed since the hand-over.
  • Let the sandbox fetch large public data itself, with an allow list naming only the source.
  • Bring private bucket data in with a short-lived signed link; the sandbox never holds the key.
  • Use a volume for state the next run reuses, one sandbox at a time, and an image for data many sandboxes read.
  • Put tools in an image, run-to-run state on a volume, and shared data in a bucket.

Run it on Runtime

Runtime costs 36% to 87% less than fourteen other sandbox providers for an agent that mostly waits on a model (compare costs). Every Runtime sandbox has a files API with checked transfers. Folder uploads travel as one archive. Network rules keep a sandbox to the hosts it needs. Volumes outlive the sandbox that uses them. Read the storage guide, then create an account at withruntime.com and hand your agent its first task folder.

Keep reading.

Cut your cloud billby 60%.

Redeem $5 free usage$0 today · 7 days free · cancel any time

7 days of Pro for $0. Billed by the second after.

Redeem $5 free usage$0 today · 7 days free · cancel any time