# SDKs

> Drive sandboxes from TypeScript or Python: create, fork, run commands, run Claude Code or Codex on tasks, get preview links, start the desktop, stop and resume, and place sandboxes on your nodes.

The TypeScript and Python SDKs do what the CLI does, from code: create and fork sandboxes, run commands with their output as it comes or in the background, read and write files, get preview links, start the desktop, stop, resume and delete, place sandboxes on your [nodes](https://cloudex.build/docs/nodes.md), and manage [provider keys](https://cloudex.build/docs/keys.md). They also drive [agents](https://cloudex.build/docs/agents.md#from-code): Claude Code or Codex on a task with no terminal, which you follow, continue, interrupt and steer. Both talk to your deployment's [HTTP API](https://cloudex.build/docs/api.md).

## TypeScript

```sh
npm install cloudex
```

The `cloudex` package runs anywhere `fetch` does: Node 18 or newer, Bun, Deno and Workers. It has no dependencies. Use it from a server or a script. The API sends no CORS headers, so a web page can't call it.

```ts
import { Cloudex } from "cloudex";

const cx = new Cloudex(); // the deployment saved by the CLI
const box = await cx.create({ name: "web" });
await box.exec("git clone https://github.com/you/app && cd app && npm install");

// Ten copies of that disk, each trying something different.
const forks = await box.fork({ count: 10, name: "try" });
const results = await Promise.all(forks.map((f, i) => f.exec(["npm", "test", "--", `--shard=${i + 1}/10`])));

console.log(await forks[0]!.host(3000)); // an HTTPS link to a port
await Promise.all(forks.map((f) => f.delete()));
await box.stop(); // saves the disk; box.resume() picks up where it left off
```

### Connecting

`new Cloudex({ apiUrl, apiKey })` takes the API URL and key that `cloudex deploy` printed; `cloudex status --show-key` shows them again. Without them, it reads `$CLOUDEX_API_URL` and `$CLOUDEX_API_KEY`, then, in Node, Bun and Deno, the deployment the CLI saved. The saved key is used only with the saved URL. For any other URL, pass `apiKey` or set `$CLOUDEX_API_KEY`. In Workers, pass them in. A URL without `https://` gets it added. The key gives full control of your sandboxes, so keep it on a server.

### Calls

| Call | Does |
|---|---|
| `cx.create({ name?, size?, idleMinutes?, env?, files?, repo?, node?, cpus?, memoryMb? })` | Create a sandbox; resolves once it's running and its repo is cloned. See [Settings](https://cloudex.build/docs/settings.md). `node` runs it on that [node](https://cloudex.build/docs/nodes.md), with `cpus` and `memoryMb` as its limits there. |
| `cx.get(ref)`, `cx.list()`, `cx.health()` | Look up a sandbox by id or name, list them, check the deployment |
| `box.exec(cmd, { root?, cwd?, timeoutSec? })` | Run shell code, or an argument list, and wait; check `exitCode` |
| `box.execStream(cmd, { root?, cwd?, timeoutSec? })` | The same, as an async iterator of `stdout` and `stderr` events as they come, ending with `exit`. Leaving the loop stops the command. |
| `box.startCommand(cmd, { root?, cwd?, timeoutSec? })` | Start a [background command](https://cloudex.build/docs/commands.md#background-commands); returns a `Command` at once |
| `box.followCommand(id)`, `box.commandOutput(id, { after?, wait? })` | Iterate over its output to the end; the last piece's `command` says how it ended. Or read one piece from a byte offset. |
| `box.listCommands()`, `box.getCommand(id)`, `box.killCommand(id, signal?)`, `box.forgetCommand(id)` | The background commands; one; stop one and what it started; remove a finished one |
| `box.readFile(path)`, `box.writeFile(path, data, { mode? })` | Download a file as a `Uint8Array`; upload a string, bytes, `Blob` or stream |
| `box.stat(path)`, `box.deleteFile(path, { recursive? })` | A path's details and a directory's entries; delete |
| `box.downloadArchive(path)`, `box.uploadArchive(path, tarGz)` | A directory as a tar.gz; unpack one into a directory |
| `box.fork({ count?, name?, size?, idleMinutes?, cpus?, memoryMb? })` | Up to 10 sandboxes starting from a copy of the disk. A sandbox on a node forks on that node, with `cpus` and `memoryMb` instead of `size`. |
| `box.save(name)`, `cx.startFromSave(name, { count?, name?, size?, idleMinutes?, node?, cpus?, memoryMb? })` | Keep a copy of the disk under a [name](https://cloudex.build/docs/saves.md); start up to 10 sandboxes from it, on a node with `node` |
| `cx.listSaves()`, `cx.getSave(name)`, `cx.deleteSave(name)` | The named saves, newest first; one by name; delete one |
| `box.host(port)` | HTTPS link to a port on your preview domain; servers on localhost work too |
| `box.links()`, `box.revokeLinks(port?)` | The links that work; make one port's link, or all of them, stop working |
| `box.update({ name?, idleMinutes? })` | Rename, or change the idle time |
| `box.desktop({ size? })`, `box.stopDesktop()` | Start the desktop and get a link to it on your preview domain; stop it |
| `box.stop()`, `box.resume({ fromBackup?, size? })`, `box.delete({ force? })` | Save and stop, start again (on another size with `size`), delete; `force` deletes one whose node is offline |
| `box.refresh()` | Fetch the latest state; `box.id`, `box.name`, `box.state` and `box.info` hold it. `box.placement` says where it runs, and `box.info.isolation` how it's isolated. |
| `box.settings()`, `box.updateSettings({ env?, files? })` | The sandbox's variable names, files and repo; set values, or remove one with `null` |
| `cx.nodes.list({ live? })`, `cx.nodes.get(ref)` | The [nodes](https://cloudex.build/docs/nodes.md), with whether each is online; `live: false` answers from the deployment's index, for polling. One node, with the image it has and, for admins, a round trip to its agent. |
| `cx.nodes.add(name)`, `cx.nodes.remove(ref, { force? })` | Add a node, with the command that installs its agent; remove one. Admin only. |
| `cx.setKey(provider, key)`, `cx.listKeys()`, `cx.deleteKey(provider)` | Manage the [provider keys](https://cloudex.build/docs/keys.md) sandboxes use; `provider` is one of [those listed there](https://cloudex.build/docs/keys.md), such as `"anthropic"` or `"openrouter"` |
| `cx.me()` | Who the key belongs to: the admin key, or a token and its role |
| `cx.createToken({ name, role?, ownOnly?, expiresInSec? })`, `cx.listTokens()`, `cx.revokeToken(id)` | Manage [access tokens](https://cloudex.build/docs/tokens.md); the new token's `secret` is only in `createToken`'s answer |
| `box.prompt(prompt, { agent?, cwd?, model? })` | Start Claude Code (default) or Codex on a task; returns an `Agent` at once |
| `box.agents()`, `box.agent(id)` | The sandbox's agents, newest first; one by id |
| `agent.events({ after?, follow? })` | An async iterator over its events; follows until the agent is idle |
| `agent.send(prompt, { interrupt? })`, `agent.interrupt()`, `agent.wait()` | Continue the conversation, stop the running turn, wait until idle; `agent.lastMessage` and `agent.error` tell how the last turn went |

The file calls take `root: true` to act as root. A string passed to `exec` runs as shell code. An array is quoted for you, one argument per element. A failing command doesn't throw; check `exitCode`. Errors from the API throw `CloudexError`, with `status` and the API's message. When there was no answer, because the API can't be reached, a request timed out or a response broke off, `status` is 0 and the message starts with `can't reach` and the API URL. A call that the deployment is too old for says to update it with `cloudex deploy`.

## Python

Install it from [PyPI](https://pypi.org/project/cloudex/):

```sh
pip install cloudex
```

It needs Python 3.9 or newer and uses only the standard library.

```python
from concurrent.futures import ThreadPoolExecutor
from cloudex import Cloudex

cx = Cloudex()  # the deployment saved by the CLI
box = cx.create(name="web")
box.exec("git clone https://github.com/you/app && cd app && pip install -e .")

# Ten copies of that disk, each trying something different.
forks = box.fork(count=10, name="try")
with ThreadPoolExecutor(10) as pool:
    results = list(pool.map(lambda f: f.exec(["pytest", "-x", "app"]), forks))

print(forks[0].host(8000))  # an HTTPS link to a port
for f in forks:
    f.delete()
box.stop()  # saves the disk; box.resume() picks up where it left off
```

### Connecting

`Cloudex(api_url, api_key)` takes the API URL and key that `cloudex deploy` printed; `cloudex status --show-key` shows them again. Without them, it reads `$CLOUDEX_API_URL` and `$CLOUDEX_API_KEY`, then the deployment the CLI saved. The saved key is used only with the saved URL. For any other URL, pass `api_key` or set `$CLOUDEX_API_KEY`. A URL without `https://` gets it added. The key gives full control of your sandboxes.

### Calls

| Call | Does |
|---|---|
| `cx.create(name=, size=, idle_minutes=, env=, files=, repo=, node=, cpus=, memory_mb=)` | Create a sandbox; returns once it's running and its repo is cloned. See [Settings](https://cloudex.build/docs/settings.md). `node` runs it on that [node](https://cloudex.build/docs/nodes.md), with `cpus` and `memory_mb` as its limits there. |
| `cx.get(ref)`, `cx.list()`, `cx.health()` | Look up a sandbox by id or name, list them, check the deployment |
| `box.exec(cmd, root=, cwd=, timeout_sec=)` | Run shell code, or an argument list, and wait; check `exit_code` |
| `box.exec_stream(cmd, root=, cwd=, timeout_sec=)` | The same, as a generator of `stdout` and `stderr` events as they come, ending with `exit` |
| `box.start_command(cmd, root=, cwd=, timeout_sec=)` | Start a [background command](https://cloudex.build/docs/commands.md#background-commands); returns a `Command` at once |
| `box.follow_command(id)`, `box.command_output(id, after=, wait=)` | Iterate over its output to the end; the last piece's `command` says how it ended. Or read one piece from a byte offset. |
| `box.list_commands()`, `box.get_command(id)`, `box.kill_command(id, signal=)`, `box.forget_command(id)` | The background commands; one; stop one and what it started; remove a finished one |
| `box.read_file(path)`, `box.write_file(path, data, mode=)` | Download a file as `bytes`; upload `bytes`, a `str` or a file object |
| `box.stat(path)`, `box.delete_file(path, recursive=)` | A path's details and a directory's entries; delete |
| `box.download_archive(path)`, `box.upload_archive(path, tar_gz)` | A directory as a tar.gz; unpack one into a directory |
| `box.fork(count=, name=, size=, idle_minutes=, cpus=, memory_mb=)` | Up to 10 sandboxes starting from a copy of the disk. A sandbox on a node forks on that node, with `cpus` and `memory_mb` instead of `size`. |
| `box.save(name)`, `cx.start_from_save(save, count=, name=, size=, idle_minutes=, node=, cpus=, memory_mb=)` | Keep a copy of the disk under a [name](https://cloudex.build/docs/saves.md); start up to 10 sandboxes from it, on a node with `node` |
| `cx.list_saves()`, `cx.get_save(name)`, `cx.delete_save(name)` | The named saves, newest first, as `Save` objects; one by name; delete one |
| `box.host(port)` | HTTPS link to a port on your preview domain; servers on localhost work too |
| `box.links()`, `box.revoke_links(port=None)` | The links that work; make one port's link, or all of them, stop working |
| `box.update(name=, idle_minutes=)` | Rename, or change the idle time |
| `box.desktop(size=)`, `box.stop_desktop()` | Start the desktop and get a link to it on your preview domain; stop it |
| `box.stop()`, `box.resume(from_backup=, size=)`, `box.delete(force=)` | Save and stop, start again (on another size with `size`), delete; `force` deletes one whose node is offline |
| `box.refresh()` | Fetch the latest state; `box.id`, `box.name`, `box.state` and `box.info` hold it. `box.placement` says where it runs, and `box.isolation` how it's isolated. |
| `box.settings()`, `box.update_settings(env=, files=)` | The sandbox's variable names, files and repo; set values, or remove one with `None` |
| `cx.nodes.list(live=)`, `cx.nodes.get(ref)` | The [nodes](https://cloudex.build/docs/nodes.md), as `Node` objects; `live=False` answers from the deployment's index, for polling. One node, with the image it has and, for admins, a round trip to its agent. |
| `cx.nodes.add(name)`, `cx.nodes.remove(ref, force=)` | Add a node, as a `NewNode` with the command that installs its agent; remove one. Admin only. |
| `cx.set_key(provider, key)`, `cx.list_keys()`, `cx.delete_key(provider)` | Manage the [provider keys](https://cloudex.build/docs/keys.md) sandboxes use; `box.provider_keys` lists the ones a sandbox uses |
| `cx.me()` | Who the key belongs to: the admin key, or a token and its role |
| `cx.create_token(name, role=, own_only=, expires_in_sec=)`, `cx.list_tokens()`, `cx.revoke_token(id)` | Manage [access tokens](https://cloudex.build/docs/tokens.md); the new token's `secret` is only on `create_token`'s answer |
| `box.prompt(prompt, agent=, cwd=, model=)` | Start Claude Code (default) or Codex on a task; returns an `Agent` at once |
| `box.agents()`, `box.agent(id)` | The sandbox's agents, newest first; one by id |
| `agent.events(after=, follow=)` | Iterate over its events, as dicts; follows until the agent is idle |
| `agent.send(prompt, interrupt=)`, `agent.interrupt()`, `agent.wait()` | Continue the conversation, stop the running turn, wait until idle; `agent.last_message` and `agent.error` tell how the last turn went |

Errors from the API raise `CloudexError`, with `status` and the API's message. As in TypeScript, `status` is 0 when there was no answer, and a call that the deployment is too old for says to update it with `cloudex deploy`.

Fetching a preview link with `urllib` needs a `User-Agent` header: Cloudflare's Browser Integrity Check, on by default for your domain, answers urllib's default one with error 1010.

## Agents

`box.prompt()` starts an agent on a task and returns at once; see [Agents from code](https://cloudex.build/docs/agents.md#from-code) for how turns, events and interrupts work.

```ts
const agent = await box.prompt("make the tests pass");
for await (const e of agent.events()) console.log(e.type, e.event ?? e.text ?? "");
console.log(agent.lastMessage);
await (await agent.send("now update the docs")).wait();
```

```python
agent = box.prompt("make the tests pass")
for e in agent.events():
    print(e["type"], e.get("event") or e.get("text") or "")
print(agent.last_message)
agent.send("now update the docs").wait()
```

`events()` long-polls: each request waits up to 30 seconds (25 in Python) for new events, so a client timeout has to be longer than that.

## Waiting

`create`, `fork` and `resume` return once the sandbox is running, which can take a minute or more on a host that hasn't fetched the image yet, or for a large save. Give your HTTP client and any surrounding timeouts room for that; the CLI waits up to 20 minutes.
