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

# Process execution

> Execute shell commands, retrieve process information, stream output, and control process lifecycle in Blaxel sandboxes using the SDK.

Execute and manage processes in your sandboxes with Blaxel SDK. Run shell commands, retrieve process information, and control process execution.

> [!TIP]
>
> Complete code examples demonstrating all operations are available on Blaxel's GitHub: [in TypeScript](https://github.com/blaxel-ai/sdk-typescript/tree/main/tests/sandbox), [in Python](https://github.com/blaxel-ai/sdk-python/tree/main/tests/integration/sandbox), and [in Go](https://github.com/blaxel-ai/sdk-go/tree/main/integration_tests).

## Execute processes and commands

> [accordion] Learn more about authentication on Blaxel
>
> The Blaxel SDK requires two environment variables to authenticate:
>
> | Variable | Description |
> | - | - |
> | `BL_WORKSPACE` | Your Blaxel workspace name |
> | `BL_API_KEY` | Your Blaxel API key |
>
> You can create an API key from the [Blaxel console](https://app.blaxel.ai/profile/security). Your workspace name is visible in the URL when you log in to the console (e.g. `app.blaxel.ai/{workspace}`).
>
> Set them as environment variables or add them to a `.env` file at the root of your project:
>
> ```bash theme={null}
> export BL_WORKSPACE=my-workspace
> export BL_API_KEY=my-api-key
> ```
>
> The Blaxel SDK does not accept credentials as constructor arguments. Credentials must come from environment variables, a `.env` file, or a local CLI login session (see below).
>
> When developing locally, you can also **log in to your workspace with Blaxel CLI** (as shown above). This allows you to run Blaxel SDK functions that will automatically connect to your workspace without additional setup. When you deploy on Blaxel, authentication is handled automatically — no environment variables needed.

### Execute command

Execute shell commands:

```typescript TypeScript theme={null}
import { SandboxInstance } from "@blaxel/core";

const sandbox = await SandboxInstance.get("my-sandbox");

// Execute command
const process = await sandbox.process.exec({
  command: "echo 'Hello, World!'"
});
```

```python Python theme={null}
from blaxel.core import SandboxInstance

sandbox = await SandboxInstance.get("my-sandbox")

# Execute command
process = await sandbox.process.exec({
  "command": "echo 'Hello, World!'"
})
```

By default, `exec` returns after starting the process without waiting for it to finish. Its output may not be available yet.

### Get command output

Set `waitForCompletion: true` (`"wait_for_completion": True` in Python) to wait for the command to finish. The result then holds its `stdout`, `stderr`, and `exitCode` (`exit_code` in Python):

```typescript TypeScript theme={null}
const result = await sandbox.process.exec({
  command: "ls /",
  waitForCompletion: true
});

console.log(result.exitCode);
console.log(result.stdout);
console.log(result.stderr);
```

```python Python theme={null}
result = await sandbox.process.exec({
  "command": "ls /",
  "wait_for_completion": True
})

print(result.exit_code)
print(result.stdout)
print(result.stderr)
```

The `logs` field holds `stdout` and `stderr` together. A command that exits with a non-zero code does not raise an error: its `status` is `failed`, so check the exit code. Set `timeout` to limit how long the command can run: if it's still running when the timeout expires, the process is killed and the call fails. For longer commands, see [Wait for process completion](#wait-for-process-completion).

Process execution logs are also visible in the Blaxel Console. Refer to the **Logs** section of the sandbox detail page, as shown below:

![process logs](https://mintcdn.com/blaxel/4l6kp8nkKF0EWNho/images/sandboxes/process-logs.webp?fit=max\&auto=format\&n=4l6kp8nkKF0EWNho\&q=85\&s=a0f49ebf4aaabb549fad28bb7f2ad128)

### Set the working directory

Set the working directory for subsequent commands:

```typescript TypeScript theme={null}
import { SandboxInstance } from "@blaxel/core";

const sandbox = await SandboxInstance.get("my-sandbox");

// Execute command
const process = await sandbox.process.exec({
  workingDir: "/app",
  command: "ls -al"
});
```

```python Python theme={null}
from blaxel.core import SandboxInstance

sandbox = await SandboxInstance.get("my-sandbox")

# Execute command
process = await sandbox.process.exec({
  "working_dir": "/app",
  "command": "ls -al"
})
```

`workingDir` is a JSON request-body field, not a URL path. Pass a normal absolute filesystem path such as `"/workspace"`; do not URL-encode it as `"%2Fworkspace"`. In Python, the equivalent field is `working_dir`.

### Use process names

When starting a process (running a command), you can specify a **process name**. This lets you interact with the process—such as retrieving logs or process information—without needing to store the process ID on your end.

```typescript TypeScript highlight={2} theme={null}
const process = await sandbox.process.exec({
  name: "hello-process",
  command: "echo 'Hello, World!'"
});
const processInfo = await sandbox.process.get("hello-process");
```

```python Python highlight={2} theme={null}
process = await sandbox.process.exec({
  "name": "hello-process",
  "command": "echo 'Hello, World!'"
})
process_info = await sandbox.process.get("hello-process")
```

You can use either the process name or the process ID to get information about the process:

```typescript TypeScript theme={null}
const completedProcess = await sandbox.process.get("hello-process");
if (completedProcess.status === "completed") {
  // ...
}
```

```python Python theme={null}
completed_process = await sandbox.process.get("hello-process")
if completed_process.status == "completed":
    # ...
```

The exit code of the process is available in the `exitCode` parameter (`exit_code` in Python) of the process execution object returned by the `process.exec` and `process.get` methods.

You can also use the process ID or name to [retrieve logs of your processes](https://docs.blaxel.ai/Sandboxes/Log-streaming.md).

### Kill process

Kill a process immediately by running:

```typescript TypeScript theme={null}
await sandbox.process.kill("test")
```

```python Python theme={null}
await sandbox.process.kill("test")
```

## Long-running processes

Blaxel Sandboxes are great for long-running processes. Processes you launch detach by design: their `stdout` and `stderr` are redirected to files and the process is monitored by background workers in the sandbox, so it survives independently of your client connection.

By default, the general [sandbox lifecycle](https://docs.blaxel.ai/Sandboxes/Overview.md#sandbox-lifecycle) rules still apply: the sandbox only stays awake while a connection is maintained and will suspend after a few seconds of inactivity. Use `keepAlive` to override this for the duration of a process.

Two independent flags let you tune how the behavior works.

* `waitForCompletion` (default: `false`) controls only whether the SDK call blocks until the process exits and returns its output. It has no effect on the process or sandbox lifetime.
* `keepAlive` (default: none) controls only whether the sandbox stays awake (auto-standby/scale-to-zero disabled) while the process runs, even with no active client connection. A counter tracks running `keepAlive` processes and is decremented automatically when each one completes, letting the sandbox return to standby on its own. See [Sandbox keep-alive](#sandbox-keep-alive) for details.

### Wait for process completion

You can wait for process completion when executing it:

```typescript TypeScript theme={null}
const process = await sandbox.process.exec({
  name: "build-process",
  command: "npm run build",
  waitForCompletion: true,
  timeout: 60 // 60 seconds
});
```

```python Python theme={null}
process = await sandbox.process.exec({
  "name": "build-process",
  "command": "npm run build",
  "wait_for_completion": True,
  "timeout": 60  # 60 seconds
})
```

When waiting for completion, the process execution object contains the command's [output](#get-command-output): `stdout`, `stderr`, and both combined in `logs`. Also, notice the `timeout` parameter which allows you to set the process timeout duration in seconds.

> [!WARNING]
>
> When using `waitForCompletion`, Blaxel enforces a **timeout limit of 60 seconds**. Don't set your timeout longer than this. For longer waiting periods, use the process-watching option described below.

> [!NOTE]
>
> `timeout` is the longest a process can run, in seconds, with or without `keepAlive`. When it expires, the process is killed and `restartOnFailure` doesn't restart it; a `waitForCompletion` call fails with a 422 error (`process timed out after N seconds`). Without `timeout`, a process runs until it exits, except `keepAlive` processes, which default to 600 seconds (see [Sandbox keep-alive](#sandbox-keep-alive)).

You can also wait for a process after it has started:

```typescript TypeScript theme={null}
await sandbox.process.exec({
  name: "long-task",
  command: "sleep 10"
});

// Wait for completion (max 10 minutes, check every 5 seconds)
await sandbox.process.wait("long-task", {
  maxWait: 600000,
  interval: 5000
});
```

```python Python theme={null}
await sandbox.process.exec({
  "name": "long-task",
  "command": "sleep 10"
})

# Wait for completion (max 10 minutes, check every 5 seconds)
await sandbox.process.wait("long-task", max_wait=600000, interval=5000)
```

Set a long completion duration if your process is expected to take longer.

### Wait for ports

In some cases, you may want to wait for a port to be opened while running — for example if you are running `npm run dev` and want to wait for port 3000 to be open. `exec` returns as soon as the ports are open, and the process keeps running in the background.

```typescript TypeScript theme={null}
const process = await sandbox.process.exec({
  name: "dev-server",
  command: "npm run dev -- --host $HOST --port 3000",
  waitForPorts: [3000]
});
```

```python Python theme={null}
process = await sandbox.process.exec({
  "name": "dev-server",
  "command": "npm run dev -- --host $HOST --port 3000",
  "wait_for_ports": [3000]
})
```

A port counts as open once the server listens on the address in `HOST` (or on all interfaces). A server bound only to `localhost` isn't reachable from outside the sandbox, so it doesn't count.

Leave `timeout` unset (or set it to `0` with `keepAlive`) for a server that should keep running. `timeout` is the process's lifetime, not just the wait, so the server is killed when it expires, even after its ports open. Without it, the call waits until the ports open. If the server takes 120 seconds or more to open them, the gateway ends the call with a 504 error, but the process keeps running: check it with `process.get` and retry until the port responds. If the process fails before its ports open (it exits with a non-zero code or is killed), the call fails right away. The error includes the exit code and the last lines of the process's output:

```typescript TypeScript theme={null}
try {
  await sandbox.process.exec({
    name: "dev-server",
    command: "npm run dev -- --host $HOST --port 3000",
    waitForPorts: [3000]
  });
} catch (error) {
  // e.g. "process exited with code 1 before ports [3000] opened; last output: ..."
  console.error(error.message);
}
```

```python Python theme={null}
try:
    await sandbox.process.exec({
        "name": "dev-server",
        "command": "npm run dev -- --host $HOST --port 3000",
        "wait_for_ports": [3000]
    })
except Exception as error:
    # e.g. "process exited with code 1 before ports [3000] opened; last output: ..."
    print(error)
```

> [!NOTE]
>
> Don't end the command with `&`. The shell exits straight away and the server it put in the background isn't tracked as part of the process, so the call waits until the gateway ends it and a startup crash isn't reported. Failing fast needs sandbox-api 0.2.62 or later; custom images pick it up when rebuilt.

## Process stdin

By default, a process has no stdin: it reads end-of-file as soon as it starts. Start it with `stdin: true` to give it a writable pipe, then send input with `writeStdin` and close the pipe with `closeStdin`. Use this to drive programs that read from stdin, such as stdio MCP servers and other JSON-RPC programs.

The pipe passes your bytes through unchanged. Unlike the [interactive terminal](https://docs.blaxel.ai/Sandboxes/Overview.md#connect-to-a-sandbox-with-an-interactive-terminal), there is no TTY in between, so nothing is echoed back or rewritten.

> [!NOTE]
>
> Process stdin needs `@blaxel/core` 0.3.19 or later in TypeScript, `blaxel` 0.4.9 or later in Python, and sandbox-api 0.2.56 or later in the sandbox. Custom images pick it up when rebuilt.

### Write to a process

Start the process with a name and `stdin: true`, write to it, then close stdin to send end-of-file:

```typescript TypeScript theme={null}
await sandbox.process.exec({
  name: "sort",
  command: "sort",
  stdin: true
});

await sandbox.process.writeStdin("sort", "cherry\napple\nbanana\n");
await sandbox.process.closeStdin("sort");

await sandbox.process.wait("sort");
const output = await sandbox.process.logs("sort", "stdout");
// "apple\nbanana\ncherry\n"
```

```python Python theme={null}
await sandbox.process.exec({
  "name": "sort",
  "command": "sort",
  "stdin": True
})

await sandbox.process.write_stdin("sort", "cherry\napple\nbanana\n")
await sandbox.process.close_stdin("sort")

await sandbox.process.wait("sort")
output = await sandbox.process.logs("sort", "stdout")
# "apple\nbanana\ncherry\n"
```

`writeStdin` (`write_stdin` in Python) takes a string or bytes and writes them as is, so include the trailing newline your program expects. `closeStdin` (`close_stdin` in Python) can be called more than once.

### Run a stdio MCP server

A stdio MCP server reads JSON-RPC messages from stdin and writes one reply per line to stdout. Send each message with `writeStdin`, and read the replies by [streaming the process's stdout](https://docs.blaxel.ai/Sandboxes/Log-streaming.md):

```typescript TypeScript theme={null}
await sandbox.process.exec({
  name: "mcp-fs",
  command: "npx -y @modelcontextprotocol/server-filesystem /tmp",
  stdin: true
});

// Each stdout line is one JSON-RPC message from the server
const pending = new Map<number, (message: any) => void>();
const stream = sandbox.process.streamLogs("mcp-fs", {
  onStdout: (line) => {
    const message = JSON.parse(line);
    pending.get(message.id)?.(message);
  }
});

const send = (message: object) =>
  sandbox.process.writeStdin("mcp-fs", JSON.stringify(message) + "\n");
const request = (id: number, method: string, params: object = {}) =>
  new Promise<any>((resolve) => {
    pending.set(id, resolve);
    void send({ jsonrpc: "2.0", id, method, params });
  });

await request(1, "initialize", {
  protocolVersion: "2025-06-18",
  capabilities: {},
  clientInfo: { name: "my-client", version: "1.0.0" }
});
await send({ jsonrpc: "2.0", method: "notifications/initialized" });
const tools = await request(2, "tools/list");

// Closing stdin shuts the server down
await sandbox.process.closeStdin("mcp-fs");
stream.close();
```

```python Python theme={null}
import asyncio
import json

await sandbox.process.exec({
  "name": "mcp-fs",
  "command": "npx -y @modelcontextprotocol/server-filesystem /tmp",
  "stdin": True
})

# Each stdout line is one JSON-RPC message from the server
pending = {}

def on_stdout(line):
    message = json.loads(line)
    reply = pending.pop(message.get("id"), None)
    if reply:
        reply.set_result(message)

stream = sandbox.process.stream_logs("mcp-fs", {"on_stdout": on_stdout})

async def send(message):
    await sandbox.process.write_stdin("mcp-fs", json.dumps(message) + "\n")

async def request(request_id, method, params=None):
    reply = asyncio.get_running_loop().create_future()
    pending[request_id] = reply
    await send({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}})
    return await reply

await request(1, "initialize", {
    "protocolVersion": "2025-06-18",
    "capabilities": {},
    "clientInfo": {"name": "my-client", "version": "1.0.0"}
})
await send({"jsonrpc": "2.0", "method": "notifications/initialized"})
tools = await request(2, "tools/list")

# Closing stdin shuts the server down
await sandbox.process.close_stdin("mcp-fs")
stream.close()
```

The first `npx` run downloads the server package, so the first reply can take several seconds.

### Stdin errors and restarts

Sequential writes keep their order, and two concurrent writes never mix inside a message. The SDK does not retry a failed write, since a duplicate would corrupt the stream. A write fails with:

* `409` if the process was started without `stdin: true`, or its stdin is closed
* `413` if the data is larger than 8 MiB
* `503` if the process stopped reading and the pipe stayed full for 10 seconds

After a `503`, part of the data may have gone through, so restart the process.

The pipe survives sandbox standby and resume. With [`restartOnFailure`](#restart-process-on-failure), each restart gets a new pipe, and data written between the failure and the restart is lost. If the sandbox API itself restarts, the process reads end-of-file and writes fail with `409`: restart the process and redo your protocol's handshake.

Over the Sandbox API, start the process with `"stdin": true` on `POST /process`, then [write to its stdin](https://docs.blaxel.ai/api-reference/process/write-to-a-processs-stdin.md) with `POST /process/{identifier}/stdin` and the raw bytes as the request body, and [close its stdin](https://docs.blaxel.ai/api-reference/process/close-a-processs-stdin.md) with `DELETE /process/{identifier}/stdin`.

## Auto-restart

### Restart process on failure

You can restart a process if it fails, up to a maximum number of restart attempts:

```typescript TypeScript theme={null}
const process = await sandbox.process.exec({
  name: "start-server",
  command: "npm run dev -- --host $HOST --port 8000",
  restartOnFailure: true,
  maxRestarts: 5
});
```

```python Python theme={null}
process = await sandbox.process.exec({
  "name": "start-server",
  "command": "uvicorn main:app --reload --host $HOST --port 8000",
  "restart_on_failure": True,
  "max_restarts": 5
})
```

## Sandbox keep-alive

By default, sandboxes automatically switch to standby when there is no active connection to save resources. However, it is possible to adjust this behavior and keep the sandbox running when you launch a process, even if there isn't an active connection to it. This is typically used to keep a long-running task actively running within the sandbox environment even when it is not serving requests.

You can include additional keep-alive metadata when launching a new process:

```typescript TypeScript theme={null}
import { SandboxInstance } from "@blaxel/core";

const sandbox = await SandboxInstance.get("my-sandbox");

// Start a dev server that keeps the sandbox awake
await sandbox.process.exec({
  name: "dev-server",
  command: "npm run dev -- --hostname $HOST --port 3000",
  keepAlive: true,        // Prevents auto-standby while the process runs
  timeout: 3600           // Auto-kill the process after 1 hour. Set 0 to not auto-kill.
});
```

```python Python theme={null}
from blaxel.core import SandboxInstance

sandbox = await SandboxInstance.get("my-sandbox")

# Start a dev server that keeps the sandbox awake
await sandbox.process.exec({
  "name": "dev-server",
  "command": "npm run dev -- --hostname $HOST --port 3000",
  "keep_alive": True,        # Prevents auto-standby
  "timeout": 3600            # Auto-kill after 1 hour
})
```

`timeout` kills any process when it expires. Only `keepAlive` processes get a default: a `keepAlive` process started without a `timeout` is killed after **600 seconds (10 minutes)**. To run a `keepAlive` process indefinitely with no auto-kill, set `timeout: 0`.

The table below summarizes how `keepAlive` and `timeout` interact:

| Configuration | Process auto-kill behavior |
| - | - |
| `keepAlive` not set (default), no `timeout` | Never auto-killed. Runs until it completes on its own. |
| `keepAlive` not set (default), `timeout: N` | Auto-killed after **N seconds**. |
| `keepAlive: true`, no `timeout` | Auto-killed after **600 seconds** (10 minutes). |
| `keepAlive: true`, `timeout: 0` | Never auto-killed. Runs until it completes on its own. |
| `keepAlive: true`, `timeout: N` | Auto-killed after **N seconds**. |

You can run multiple processes, and the sandbox will stay active until all of them complete. Here each one is killed after 1 hour:

```typescript TypeScript theme={null}
import { SandboxInstance } from "@blaxel/core";

const sandbox = await SandboxInstance.get("my-sandbox");

await sandbox.process.exec({
  name: "api-server",
  command: "npm run start:api",
  keepAlive: true,
  timeout: 3600
});

await sandbox.process.exec({
  name: "worker",
  command: "npm run start:worker",
  keepAlive: true,
  timeout: 3600
});
```

```python Python theme={null}
from blaxel.core import SandboxInstance

sandbox = await SandboxInstance.get("my-sandbox")

await sandbox.process.exec({
  "name": "api-server",
  "command": "npm run start:api",
  "keep_alive": True,
  "timeout": 3600
})

await sandbox.process.exec({
  "name": "worker",
  "command": "npm run start:worker",
  "keep_alive": True,
  "timeout": 3600
})
```

## Disable process telemetry logging

By default, process stdout and stderr are exported as structured telemetry logs (visible in external observability systems). You can disable this telemetry export by setting the `SANDBOX_DISABLE_PROCESS_LOGGING` environment variable inside the sandbox.

When set to `true` or `1`, structured telemetry output is suppressed for **all** processes. File-based logging and [real-time log streaming](https://docs.blaxel.ai/Sandboxes/Log-streaming.md) via the SDK remain fully functional and are not affected.

Set this variable in your Dockerfile or at sandbox creation time:

```dockerfile theme={null}
ENV SANDBOX_DISABLE_PROCESS_LOGGING=true
```

Alternatively, you can disable process logging for sandboxes at workspace level using the Blaxel Console, in the **Workspace settings** section.

![Disable process logging](https://mintcdn.com/blaxel/kSTOMIMV3AdaINI6/images/sandboxes/disable-process-logs.webp?fit=max\&auto=format\&n=kSTOMIMV3AdaINI6\&q=85\&s=8eaae54445e520cb89119b292c906868)

> [!NOTE]
>
> This only suppresses the structured telemetry export. You can still retrieve process logs via the SDK's `process.logs()` method and stream them in real-time.

## Process statuses

A process can have any of the following statuses:

* `running`
* `completed`
* `failed`
* `killed`
* `stopped`


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