---
title: "Run commands and edit files in a sandbox | Pethost Agent Sandboxes"
description: "Run shell commands in a sandbox and wait for their output or port, stream long ones, edit files by exact replacement, and move large files through links."
---

[Agent Sandboxes docs](https://pethost.dev/docs/sandboxes/) · Tasks

# Run commands and edit files in a sandbox

Updated 22 November 2026 · 9 min read

Run a command in a sandbox and get its output and exit code in one call, follow a long one as it runs, edit files by exact replacement, move files of any size through links, and open a terminal in a browser.

**In short**

- **`RunCommand`** runs `bash -lc` as `user` in `/home/user` and waits up to 45 s: its exit code and the last 32 KiB of its output, or RUNNING with its id.
- **`WatchCommand`** streams a command's output as it comes; `GetCommand` waits again and reads only what is new.
- **`WriteFiles`** writes, edits, moves and deletes files in one call, in order; an edit replaces text that occurs exactly once.
- **Links** move files of any size and open a terminal in a browser.

The examples go on from the [quickstart](https://pethost.dev/docs/sandboxes/quickstart/): `sandboxes` (`client` in Go) is a client, and the sandbox's id is at hand.

### Step 1: Run a command

A command is one string, run by `bash -lc`, so pipes, `&&` and variables work. `cwd` and `user` change where and as whom it runs; `user` is `root` or the default, `user`, who has passwordless sudo.

Python

```
command = sandboxes.run_command(sandbox_id, command="uname -r && whoami", cwd="/tmp")
print(command.exit_code)
print(command.stdout)
# 0
# 6.18.63
# user
```

TypeScript

```
const command = await sandboxes.runCommand({ sandboxId, command: "uname -r && whoami", cwd: "/tmp" });
console.log(command.exitCode);
console.log(command.stdout);
```

Go

```
command, err := client.RunCommand(ctx, &sandboxes.RunCommandRequest{SandboxID: id, Command: "uname -r && whoami", Cwd: "/tmp"})
if err != nil {
	log.Fatal(err)
}
fmt.Println(*command.ExitCode)
fmt.Println(command.Stdout)
```

Rust

```
let command = sandboxes
    .run_command(RunCommandRequest {
        sandbox_id: id.clone(),
        command: "uname -r && whoami".into(),
        cwd: "/tmp".into(),
        ..Default::default()
    })
    .await?;
println!("{:?}", command.exit_code);
println!("{}", command.stdout);
```

CLI

```
$ pethost sandbox run api-dev --cwd /tmp -- 'uname -r && whoami'
6.18.63
user
```

### Step 2: Follow a long command

With `wait_seconds` 0 the call answers as soon as the command has started. `WatchCommand` then sends its output from the last 64 KiB on, as it comes, and the command as it ended last.

Python

```
import sys

job = sandboxes.run_command(
    sandbox_id,
    command="for i in 1 2 3; do echo step $i; sleep 20; done",
    wait_seconds=0,
    timeout_seconds=600,
)
for out in sandboxes.watch_command(sandbox_id, command_id=job.command_id):
    if out.stdout is not None:
        sys.stdout.write(out.stdout.decode())
    if out.ended is not None:
        print("exit", out.ended.exit_code)
# step 1
# step 2
# step 3
# exit 0
```

TypeScript

```
const job = await sandboxes.runCommand({
  sandboxId,
  command: "for i in 1 2 3; do echo step $i; sleep 20; done",
  waitSeconds: 0,
  timeoutSeconds: 600,
});
for await (const out of sandboxes.watchCommand({ sandboxId, commandId: job.commandId })) {
  if (out.output === "stdout") process.stdout.write(out.stdout);
  if (out.output === "ended") console.log("exit", out.ended.exitCode);
}
```

Go

```
job, err := client.RunCommand(ctx, &sandboxes.RunCommandRequest{
	SandboxID:      id,
	Command:        "for i in 1 2 3; do echo step $i; sleep 20; done",
	WaitSeconds:    new(uint32(0)),
	TimeoutSeconds: 600,
})
if err != nil {
	log.Fatal(err)
}
for out, err := range client.WatchCommand(ctx, &sandboxes.WatchCommandRequest{SandboxID: id, CommandID: job.CommandID}) {
	if err != nil {
		log.Fatal(err)
	}
	switch output := out.Output.(type) {
	case sandboxes.CommandOutputStdout:
		os.Stdout.Write(output)
	case sandboxes.CommandOutputEnded:
		fmt.Println("exit", *output.ExitCode)
	}
}
```

Rust

```
let job = sandboxes
    .run_command(RunCommandRequest {
        sandbox_id: id.clone(),
        command: "for i in 1 2 3; do echo step $i; sleep 20; done".into(),
        wait_seconds: Some(0),
        timeout_seconds: 600,
        ..Default::default()
    })
    .await?;
let mut output = sandboxes.watch_command(WatchCommandRequest {
    sandbox_id: id.clone(),
    command_id: job.command_id,
});
while let Some(out) = output.next().await {
    match out?.output {
        Some(CommandOutputOutput::Stdout(bytes)) => print!("{}", String::from_utf8_lossy(&bytes)),
        Some(CommandOutputOutput::Ended(ended)) => println!("exit {:?}", ended.exit_code),
        _ => {}
    }
}
```

CLI

```
$ pethost sandbox run api-dev --timeout 10m -- 'for i in 1 2 3; do echo step $i; sleep 20; done'
step 1
step 2
step 3
```

Without a stream, `GetCommand` waits up to 45 s again. Pass the `stdout_bytes` of the answer you last read as `stdout_after_bytes`, and it sends only what came after.

### Step 3: Write, edit and read files

`WriteFiles` takes a list of changes and makes them in order: `text` or `data` writes a file whole (with `mode`, else `0644`), `edit` replaces one exact piece of a file, `move_to` moves it, `delete` deletes a file or a directory, `make_directory` makes one. Missing directories are made, and the batch stops at the first change that fails.

Python

```
from pethost.sandboxes import FileChange, TextEdit

done = sandboxes.write_files(sandbox_id, changes=[
    FileChange(path="app/run.sh", text="#!/bin/sh\necho ready\n", mode="0755"),
    FileChange(path="app/run.sh", edit=TextEdit(old_text="ready", new_text="ready to go")),
])
print(done.done_count, done.failure.name)
for entry in sandboxes.list_files(sandbox_id, path="app").files:
    print(entry.path, entry.mode, entry.size_bytes)
print(sandboxes.read_file(sandbox_id, path="app/run.sh").text)
# 2 UNSPECIFIED
# /home/user/app/run.sh 0755 27
# #!/bin/sh
# echo ready to go
```

TypeScript

```
const done = await sandboxes.writeFiles({
  sandboxId,
  changes: [
    { path: "app/run.sh", text: "#!/bin/sh\necho ready\n", mode: "0755" },
    { path: "app/run.sh", edit: { oldText: "ready", newText: "ready to go" } },
  ],
});
console.log(done.doneCount, done.failure);
const { files } = await sandboxes.listFiles({ sandboxId, path: "app" });
for (const entry of files) console.log(entry.path, entry.mode, entry.sizeBytes);
console.log((await sandboxes.readFile({ sandboxId, path: "app/run.sh" })).text);
```

Go

```
done, err := client.WriteFiles(ctx, &sandboxes.WriteFilesRequest{SandboxID: id, Changes: []sandboxes.FileChange{
	{Path: "app/run.sh", Change: sandboxes.FileChangeText("#!/bin/sh\necho ready\n"), Mode: "0755"},
	{Path: "app/run.sh", Change: sandboxes.FileChangeEdit{OldText: "ready", NewText: "ready to go"}},
}})
if err != nil {
	log.Fatal(err)
}
fmt.Println(done.DoneCount, done.Failure)
list, err := client.ListFiles(ctx, &sandboxes.ListFilesRequest{SandboxID: id, Path: "app"})
if err != nil {
	log.Fatal(err)
}
for _, entry := range list.Files {
	fmt.Println(entry.Path, entry.Mode, entry.SizeBytes)
}
```

Rust

```
let script = |change| FileChange { path: "app/run.sh".into(), change: Some(change), ..Default::default() };
let done = sandboxes
    .write_files(WriteFilesRequest {
        sandbox_id: id.clone(),
        changes: vec![
            FileChange { mode: "0755".into(), ..script(FileChangeChange::Text("#!/bin/sh\necho ready\n".into())) },
            script(FileChangeChange::Edit(TextEdit { old_text: "ready".into(), new_text: "ready to go".into() })),
        ],
    })
    .await?;
println!("{} {:?}", done.done_count, done.failure);
let list = sandboxes
    .list_files(ListFilesRequest { sandbox_id: id.clone(), path: "app".into(), ..Default::default() })
    .await?;
for entry in list.files {
    println!("{} {} {}", entry.path, entry.mode, entry.size_bytes);
}
```

### Step 4: Move a large file through a link

A call carries 1 MiB, `WriteFiles` 17 MiB and `ReadFile` 1 MiB. A file of any size moves through a link instead: `CreateLink` with `download_path` gives a URL to GET, a directory coming as a .tar; with `upload_path`, a URL to PUT the file's bytes to. Each works once, and goes straight to the sandbox's server.

Python

```
upload = sandboxes.create_link(sandbox_id, upload_path="data/train.csv")
results = sandboxes.create_link(sandbox_id, download_path="results")
print(upload.url)
print(results.url)
# https://link-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
# https://link-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
```

TypeScript

```
const upload = await sandboxes.createLink({ sandboxId, uploadPath: "data/train.csv" });
const results = await sandboxes.createLink({ sandboxId, downloadPath: "results" });
console.log(upload.url);
console.log(results.url);
```

Go

```
upload, err := client.CreateLink(ctx, &sandboxes.CreateLinkRequest{SandboxID: id, Target: sandboxes.CreateLinkUploadPath("data/train.csv")})
if err != nil {
	log.Fatal(err)
}
results, err := client.CreateLink(ctx, &sandboxes.CreateLinkRequest{SandboxID: id, Target: sandboxes.CreateLinkDownloadPath("results")})
if err != nil {
	log.Fatal(err)
}
fmt.Println(upload.URL)
fmt.Println(results.URL)
```

Rust

```
let link = |target| CreateLinkRequest { sandbox_id: id.clone(), target: Some(target), ..Default::default() };
let upload = sandboxes.create_link(link(CreateLinkRequestTarget::UploadPath("data/train.csv".into()))).await?;
let results = sandboxes.create_link(link(CreateLinkRequestTarget::DownloadPath("results".into()))).await?;
println!("{}", upload.url);
println!("{}", results.url);
```

CLI

```
$ pethost sandbox cp ./data/train.csv api-dev:data/train.csv
✓ Copied ./data/train.csv to zt01ocz93yiwpy31:data/train.csv · 22 KB in <1 s
$ pethost sandbox cp api-dev:results ./results
✓ Copied zt01ocz93yiwpy31:results to ./results · 4 KB in <1 s
```

```
curl -T train.csv "$UPLOAD_URL"
curl -o results.tar "$RESULTS_URL"
```

### Step 5: Open a terminal in a browser

`CreateLink` with `terminal` gives a page with a shell in the sandbox, for a person to type in; its `command` runs a program in place of the shell, as `claude`. A WebSocket to the same URL carries the terminal's bytes both ways, for a terminal of your own.

Python

```
from pethost.sandboxes import TerminalLink

print(sandboxes.create_link(sandbox_id, terminal=TerminalLink(), ttl_seconds=900).url)
# https://link-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
```

TypeScript

```
const terminal = await sandboxes.createLink({ sandboxId, terminal: {}, ttlSeconds: 900 });
console.log(terminal.url);
```

Go

```
terminal, err := client.CreateLink(ctx, &sandboxes.CreateLinkRequest{
	SandboxID:  id,
	Target:     sandboxes.CreateLinkTerminal{},
	TTLSeconds: 900,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(terminal.URL)
```

Rust

```
let terminal = sandboxes
    .create_link(CreateLinkRequest {
        sandbox_id: id.clone(),
        target: Some(CreateLinkRequestTarget::Terminal(TerminalLink::default())),
        ttl_seconds: 900,
    })
    .await?;
println!("{}", terminal.url);
```

CLI

```
$ pethost sandbox open api-dev --terminal
✓ Opened the terminal of e9bprbw1hovj6sw5 in your browser.
$ pethost sandbox shell api-dev
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

user@e9bprbw1hovj6sw5:~$
```

A link expires after an hour unless `ttl_seconds` says otherwise, 86,400 s at most, and holds a token in its URL: give it to the person who will use it, never to a page others read. Making one wakes nothing.

## Where a command runs

A command runs in the sandbox's VM as `user` (uid 1000, passwordless sudo, in the `docker` group) in `/home/user`, or as `root`. Its environment is the template's, with the sandbox's own variables over it (`settings.environment`). `stdin` gives it input, which then closes. A command runs until it ends, until `timeout_seconds`, or until `StopCommand`: the call's wait ends, the command does not.

A call into a paused sandbox wakes it first, in about 80 ms. A background process left running (a server started with `&`) lives on through pauses, but does not keep the sandbox awake by itself: start a long job with `keep_awake`, so the pause timer waits for it ([keep_awake](https://pethost.dev/docs/sandboxes/lifecycle/#keep-awake)).

## Output, offsets and history

An answer holds the last 32 KiB of stdout and of stderr, as UTF-8, with `output_truncated` when the beginning was cut, and `stdout_bytes` and `stderr_bytes`, all that was written. `exit_code` is the shell's: 128 plus the signal's number when a signal ended it, and absent while it runs. The sandbox keeps its last 100 ended commands for `GetCommand`. `ListCommands` lists those running now, started by the API, over SSH or in a terminal.

`StopCommand` sends SIGTERM, and SIGKILL 10 s later if the command still runs. Called for a command that has ended, it kills what that command left running in the background.

## Edits by exact replacement

An `edit` replaces `old_text` with `new_text` where `old_text` occurs exactly once in the file, of 16 MiB at most. Not there is `EDIT_NOT_FOUND`; there twice or more is `EDIT_AMBIGUOUS`, and the file is unchanged either way. It is the edit coding agents make, and it fails loudly where a line number would have gone stale. A write replaces a file whole and keeps its owner and mode; it writes through a symbolic link to its target.

`WatchFiles` streams what is created, written, removed and renamed under a directory, with `recursive` for those under it. `OVERFLOW` says events were lost: list the directory again.

## Docker in a sandbox

Every sandbox from `base` has Docker, with Compose and Buildx. Its daemon starts at the first connection to `/var/run/docker.sock` and costs nothing until then. Images and containers are on the sandbox's disk, so a stop keeps them and a template carries them. Pulls from Docker Hub go through a mirror first.

## When it does not work

- **The answer is RUNNING, with no exit code:** the command took longer than `wait_seconds` and runs on. Follow it with `WatchCommand`, or wait with `GetCommand`.
- **The sandbox paused under a long build:** nothing called it while the build ran. Start such work with `keep_awake` and a `timeout_seconds`.
- **`failure` is `EDIT_NOT_FOUND` or `EDIT_AMBIGUOUS`:** read the file again and send an `old_text` that occurs once; the changes before it in the batch were made (`done_count`).
- **`RESOURCE_EXHAUSTED` without `LimitReached`:** the request was over its bound (a file over 17 MiB: use an upload link), or the sandbox serves 64 calls at once already. End one, or wait.
- **`FAILED_PRECONDITION` with `Stopped`:** the sandbox is stopped. `ResumeSandbox` starts it, its files as it left them.
- **A command that was RUNNING is `LOST`:** the sandbox lost its memory (it stopped) while the command ran. Run it again.

## Questions

### How long can a command run?

As long as it needs: the call waits up to 45 s and the command runs on. Only `timeout_seconds` or `StopCommand` ends it early.

### Can I run commands as root?

Yes: `user` `root`, or `sudo`, which `user` has without a password.

### How do I upload a large file to a sandbox?

`CreateLink` with `upload_path` gives a URL to PUT the file to, of any size, or `pethost sandbox cp` does it for you.

### Can I run Docker inside a sandbox?

Yes. Docker, Compose and Buildx are in `base`, and the daemon starts at first use.

### Does a running background process keep the sandbox awake?

No. It survives pauses, and a request to its port wakes the sandbox, but only calls, sessions and `keep_awake` commands keep it from pausing.

[PreviousBest practices for Pethost Agent Sandboxes](https://pethost.dev/docs/sandboxes/best-practices/) [NextPorts and previews: a sandbox's URLs](https://pethost.dev/docs/sandboxes/ports-and-previews/)

## Try Pethost Agent Sandboxes

A 7-day trial with $1 of usage and 4 vCPUs, with a card. Then a plan from $20 a month, which includes as much usage.

[Start the trial](https://console.pethost.dev/)

Pethost · Stephan Gomer · NIP 1133096755

Pethost

- [Templates](https://pethost.dev/templates/)
- [About](https://pethost.dev/about/)
- [Docs](https://pethost.dev/docs/)
- [Blog](https://pethost.dev/blog/)
- [API](https://pethost.dev/docs/api/)
- [CLI](https://pethost.dev/docs/cli/)
- [Plugin](https://github.com/pethost-dev/plugin)
- [Terms](https://pethost.dev/terms/)
- [Privacy](https://pethost.dev/privacy/)
- [Refunds](https://pethost.dev/refunds/)
- [support@pethost.dev](mailto:support@pethost.dev)

Databases

- [Postgres](https://pethost.dev/postgres/)
- [Valkey](https://pethost.dev/valkey/)

Agent Sandboxes

- [Sandboxes](https://pethost.dev/sandboxes/)
- [Pricing](https://pethost.dev/sandboxes/#pricing)
- [Docs](https://pethost.dev/docs/sandboxes/)
- [API](https://pethost.dev/docs/sandboxes/api/)

Comparisons

- [Coolify vs Dokploy vs CapRover vs Dokku](https://pethost.dev/blog/coolify-vs-dokploy-vs-caprover-vs-dokku/)
- [Coolify Cloud vs Dokploy Cloud](https://pethost.dev/blog/coolify-cloud-vs-dokploy-cloud/)
- [Railway vs Render vs Fly.io pricing](https://pethost.dev/blog/railway-vs-render-vs-fly-io-pricing/)
- [Managed Docker Compose hosting](https://pethost.dev/blog/managed-docker-compose-hosting/)

Alternatives

- [Railway alternatives](https://pethost.dev/blog/railway-alternatives/)
- [Heroku alternatives](https://pethost.dev/blog/heroku-alternatives/)
- [Dokploy alternatives](https://pethost.dev/blog/dokploy-alternatives/)
- [Coolify alternatives](https://pethost.dev/blog/coolify-alternatives/)
- [Render alternatives](https://pethost.dev/blog/render-alternatives/)
- [Sliplane alternatives](https://pethost.dev/blog/sliplane-alternatives/)
