# Python SDK

> Every public class and function of the cere Python package 0.1.7, with parameters, return values, errors and one example each.

Source: https://docs.compute.dev.ddcdragon.com/reference/python-sdk/

The `cere` Python package creates sandboxes, runs commands and agents in them, and reads their usage and egress log. This page lists everything `import cere` exports, version 0.1.7.

```sh
pip install cere
cere login
```

> Until `cere` is on PyPI, install it from the GitHub release instead (members of the Cerebellum-Network organization, with `gh` signed in): `gh release download cli/v0.1.7 -R Cerebellum-Network/ddc-node -p 'cere-*.whl' -D cere-wheels && pip install --no-index --find-links cere-wheels cere`

The SDK needs Python 3.9 or later and uses the standard library only. The same package installs the [`cere` CLI](https://docs.compute.dev.ddcdragon.com/reference/cli/); the [Quickstart](https://docs.compute.dev.ddcdragon.com/quickstart/) runs a first sandbox from both.

| Name | What |
|---|---|
| [`Sandbox`](#sandbox) | A sandbox: create, find, exec, files, logs, usage, egress, terminate. |
| [`Process`](#process) | A command running in a sandbox, returned by `Sandbox.exec`. |
| [`Allow`](#allow) | One egress rule. |
| [`Secret`](#secret) | The bucket's secrets: store, list, delete. |
| [`Agent`](#agent) | An agent definition, and its runs. |
| [`AgentResult`](#agentresult) | The result of `Agent.run`. |
| [`MissingSecretsError`](#missingsecretserror) | A run names secrets the bucket does not hold. |
| [`RunOutcome`, `run_outcome`](#runoutcome-and-run_outcome) | The result of any agent run, read from its sandbox. |
| [`Usage`](#usage) | What a sandbox used and is billed. |
| [`usage_records`](#usage_records) | The bucket's usage records. |
| [`egress_log`](#egress_log) | The egress proxy's log of the bucket's sandboxes. |
| [`Client`, `default_client`, `set_default_client`](#client) | The API client every call uses. |
| [`CereError`](#cereerror) | An error answer from the API. |
| `__version__` | The package version, `"0.1.7"`. |

## Configuration

Every call uses a [`Client`](#client). Unless you pass one, the SDK makes one on first use from the same configuration as the CLI:

1. `CERE_TOKEN` and `CERE_API_URL`, when set;
2. else what `cere login` saved, in `$CERE_CONFIG`, else `$XDG_CONFIG_HOME/cere/config.json`, else `$HOME/.config/cere/config.json`;
3. else the default API URL, `https://agent-gateway.compute.dev.ddcdragon.com` (devnet).

The S3 credential for agent definitions in the bucket comes from the same file or the `CERE_S3_*` variables ([CLI configuration](https://docs.compute.dev.ddcdragon.com/reference/cli/#environment-variables)). To set the API and token in code, make a `Client` and pass it as `client=`, or make it the default with `set_default_client`:

```python
import os, cere

cere.set_default_client(cere.Client(api_url="https://agent-gateway.compute.dev.ddcdragon.com",
                                    token=os.environ["CERE_TOKEN"]))
```

Signing in happens in the CLI only (`cere login`); see [Signing in](https://docs.compute.dev.ddcdragon.com/guides/signing-in/). [Clusters and endpoints](https://docs.compute.dev.ddcdragon.com/reference/clusters/#point-the-python-sdk-at-a-cluster) shows how to point the SDK at a cluster.

## Errors

| Exception | Raised when |
|---|---|
| [`cere.CereError`](#cereerror) | The API answers with an error, or there is no token. |
| [`cere.MissingSecretsError`](#missingsecretserror) | `Agent.run` names secrets the bucket does not hold. A subclass of `ValueError`. |
| `ValueError` | A local check fails before any call: a missing `image`, a bad secret name, an invalid agent definition, an egress rule that does not parse. |
| `TimeoutError` | `Sandbox.create`, `Sandbox.wait` or `Agent.run` waited longer than its timeout. |
| `urllib.error.URLError` | The API cannot be reached. |

### CereError

```python
class CereError(Exception):
    status: int          # the HTTP status
    message: str         # the API's message
    code: str | None     # the stable error code, when the API sent one
```

`str(e)` is `"<status> <code>: <message>"`. The codes are the API's: `not_found`, `invalid_request`, `unknown_credential`, `credential_not_bound`, `not_running`, `limit_active_sandboxes`, `file_not_found`, `file_gone`, `no_capacity`, and more; the [HTTP API](https://docs.compute.dev.ddcdragon.com/reference/http-api/#errors) lists them all. A `Client` with no token raises `CereError(401, ..., "unauthenticated")` without calling the API.

```python
try:
    cere.Sandbox.from_id("sb-00000000000000000000000000")
except cere.CereError as e:
    print(e.status, e.code, e.message)
```

```
404 not_found sandbox not found
```

## Sandbox

A sandbox. Create one with `Sandbox.create`, find one with `Sandbox.from_id` or `Sandbox.list`. [Sandboxes](https://docs.compute.dev.ddcdragon.com/guides/sandboxes/) walks through them.

```python
import cere

sb = cere.Sandbox.create(image="python:3.12-slim", timeout=300, labels={"app": "docs"})
print(sb)
p = sb.exec("python", "-c", "print(6 * 7)")
print(p.stdout.read(), end="")
sb.write_file("/workspace/out.txt", "result")
sb.terminate(retain=["/workspace/out.txt"])
print(sb.status, "|", sb.exit_reason)
print(sb.read_file("/workspace/out.txt"))
print(sb.billing())
```

```
Sandbox(sb-01m89qrf07c14jq1secqqy3n6n, running, image='python:3.12-slim')
42
terminated | terminated by API
b'result'
1.0 vCPU × 1.8 s = 1.8 CPU-s (measured 0.2), 1.0 GiB × 1.8 s = 1.8 GiB-s (measured 0.0)
```

### Sandbox.create

```python
Sandbox.create(*command: str, image: str, cpu: float = None, memory: int = None, pids: int = None,
               timeout: int = None, idle_timeout: int = None, egress: Sequence[Allow] = None,
               env: Dict[str, str] = None, labels: Dict[str, str] = None, workdir: str = None,
               wait: bool = True, wait_timeout: float = 600, client: Client = None) -> Sandbox
```

Create a gVisor sandbox and, with `wait=True`, wait until it runs.

| Parameter | Type | Default | Meaning |
|---|---|---|---|
| `*command` | `str` | `sleep infinity` | The main process. The default waits for `exec` calls. |
| `image` | `str` | required | Image from a public registry. |
| `cpu` | `float` | `1` | CPUs. |
| `memory` | `int` | `1024` | Memory in MiB, at least 128. |
| `pids` | `int` | `2048` | Process limit. |
| `timeout` | `int` | `600` | Seconds until the sandbox is terminated. |
| `idle_timeout` | `int` | off | Seconds with no exec or file call before the sandbox is terminated. |
| `egress` | list of `Allow` or rule dicts | none | The hosts the sandbox may reach, through the egress proxy. Unlike `allow` and `set_egress`, `create` does not take rule strings: a string raises `ValueError`. Pass `Allow.parse("pypi.org:GET:/pypi/")` instead. |
| `env` | `Dict[str, str]` | none | Environment variables. Not secret: keep credentials in [`Secret`](#secret). |
| `labels` | `Dict[str, str]` | none | At most 32 labels; keys of `a-z 0-9 . _ / -`, at most 63 characters; values at most 256 characters. The `cere.` prefix is reserved for agent runs. |
| `workdir` | `str` | `/workspace` | Working directory. |
| `wait` | `bool` | `True` | Wait until the sandbox runs. With `False`, return at once with status `starting`. |
| `wait_timeout` | `float` | `600` | Seconds to wait, image pull included. |
| `client` | `Client` | the default | The client to call with. |

Returns the `Sandbox`. Raises `ValueError` without `image`; `CereError` when the API refuses the sandbox (for example 400 `unknown_credential`, 409 `limit_active_sandboxes`, 503 `no_capacity`) or when it fails to start (409 `not_running`, with the exit reason in the message); `TimeoutError` when it is not running within `wait_timeout`.

### Sandbox.from_id

```python
Sandbox.from_id(sandbox_id: str, client: Client = None) -> Sandbox
```

The sandbox with this ID, in any status. Raises `CereError` 404 `not_found`, or 403 for a sandbox of another bucket.

### Sandbox.list

```python
Sandbox.list(label: str | Mapping[str, str] | Sequence[str] = None, status: str = None,
             limit: int = 100, client: Client = None) -> List[Sandbox]
```

The bucket's sandboxes, newest first.

| Parameter | Type | Default | Meaning |
|---|---|---|---|
| `label` | `"k=v"`, `"k:v"`, a dict, or a list of those | none | Only sandboxes with these labels; all must match. |
| `status` | `str` | all | `starting`, `running`, `terminated`, `failed` or `unknown`. |
| `limit` | `int` | `100` | At most this many; `None` for every one. |
| `client` | `Client` | the default | The client to call with. |

### Properties

| Property | Type | Meaning |
|---|---|---|
| `object_id`, `id` | `str` | The sandbox ID, `sb-...`. |
| `status` | `str` | `starting`, `running`, `terminated`, `failed` or `unknown`, as last read. |
| `node` | `str` | The node it runs on. |
| `exit_reason` | `str` or `None` | Why it ended: `terminated by API: <reason>`, `timeout (Ns)`, `idle_timeout (Ns)`, `oom_killed`, `exited with code N`, `failed: ...`, `lost: ...`, `token_expiry`. |
| `data` | `dict` | The sandbox as the API last reported it: every field of the [HTTP API's sandbox object](https://docs.compute.dev.ddcdragon.com/reference/http-api/#the-sandbox-object). |
| `last_usage` | [`Usage`](#usage) | The usage the API last reported with it; after `terminate()`, the final usage. |

The properties show the state as last read. `refresh()` reads it again and returns the sandbox.

### Sandbox.exec

```python
sb.exec(*command: str, timeout: int = 600, workdir: str = None, stdin: str = None,
        env: Dict[str, str] = None) -> Process
```

Run a command; its output streams into the returned [`Process`](#process). `timeout` is the seconds before the command is stopped, at most 3600 (`Process.timed_out` is then `True`); `workdir` defaults to the sandbox's; `stdin` is text sent to the command; `env` adds environment variables for this command. Raises `ValueError` without a command, `CereError` 409 `not_running` when the sandbox has ended.

### Files

```python
sb.write_file(path: str, data: bytes | str) -> None
sb.read_file(path: str) -> bytes
sb.open(path: str, mode: str = "r")
```

`write_file` writes a file, creating parent directories; at most 16 MiB. `read_file` reads a file, or a retained file after the sandbox has ended; a missing file raises `CereError` 404 `file_not_found`, a file of an ended sandbox that was not retained raises 410 `file_gone`. `open` returns a text file handle that is read on open and written back on close (modes `r`, `w`, `a` and `+`; binary modes raise `ValueError`, use `read_file` and `write_file`):

```python
with sb.open("/workspace/notes.txt", "w") as f:
    f.write("hi")
```

### Sandbox.logs

```python
sb.logs() -> Iterator[Tuple[str, str]]
```

Yield `("stdout" | "stderr", text)` from the sandbox's main process until it ends.

### Usage and billing

```python
sb.usage() -> Usage
sb.billing() -> str
```

`usage()` reads what the sandbox has used so far, live while it runs. `billing()` says what it is billed and what it measured, from its last reported usage, as the CLI prints it: `1.0 vCPU × 31.1 s = 31.1 CPU-s (measured 0.2), 1.0 GiB × 31.1 s = 31.1 GiB-s (measured 0.3)`. See [`Usage`](#usage).

### Egress

```python
sb.egress() -> List[Allow]
sb.set_egress(rules: Sequence[Allow | dict | str]) -> List[Allow]
sb.allow(*rules: Allow | dict | str) -> List[Allow]
sb.remove_egress(host: str, methods: Sequence[str] = None) -> List[Allow]
```

A rule is an [`Allow`](#allow), its JSON, or the CLI's string `host[:METHODS[:path_prefix[:credential]]]` ([syntax](https://docs.compute.dev.ddcdragon.com/reference/cli/#egress-rule-syntax)). Each method returns the rules as they are after the call.

| Method | Does |
|---|---|
| `egress()` | Read the sandbox's rules now. |
| `set_egress(rules)` | Replace all of the running sandbox's rules; `[]` removes all access. Raises `TypeError` for a single rule instead of a list. |
| `allow(*rules)` | Add rules: a rule for the same host, path prefix and credential as one the sandbox has adds its methods to that rule; any other is put first. |
| `remove_egress(host, methods)` | Remove the host's rules or, given `methods`, only those methods (a rule left with none goes). Raises `ValueError` when no rule matches. |

The egress proxy applies a change from the sandbox's next request, also inside a connection already open, and writes it to the [egress log](#egress_log) as `policy` entries. `allow` and `remove_egress` read the rules and then replace them, so a change made elsewhere in between is overwritten. All four raise `CereError` 409 `not_running` once the sandbox has ended; `set_egress` and `allow` raise 400 `unknown_credential` or `credential_not_bound` for a rule whose secret is missing or not bound to its host.

### Sandbox.terminate

```python
sb.terminate(retain: Sequence[str] = None, reason: str = None) -> Sandbox
```

End the sandbox and return it with its final usage. `retain` lists files (each up to 16 MiB) that stay readable with `read_file` afterwards; `reason` is recorded as `terminated by API: <reason>` (at most 120 characters). Terminating an ended sandbox changes nothing.

### Sandbox.poll and Sandbox.wait

```python
sb.poll() -> int | None
sb.wait(timeout: float = None, interval: float = 1.0) -> int
```

`poll()` reads the sandbox and returns `None` while it runs, else its exit code (`-1` when it has none). `wait()` polls every `interval` seconds until the sandbox ends (its command exits, it times out or is terminated) and returns the exit code; it raises `TimeoutError` after `timeout` seconds.

## Process

What `Sandbox.exec` returns. The command is already running; its output streams in as you read it.

| Attribute or method | Type | Meaning |
|---|---|---|
| `stdout`, `stderr` | stream | `read()` returns everything once the command has ended; iterating yields lines as they arrive. |
| `iter_output()` | iterator of `(str, str)` | `("stdout" \| "stderr", text)` chunks in the order they arrive, until the end. |
| `wait()` | `int` | Wait for the command to end; return its exit code. |
| `poll()` | `int` or `None` | The exit code if the command has ended (as far as has been read), else `None`. |
| `output()` | `[str, str]` | `[stdout, stderr]` once the command has ended. |
| `returncode` | `int` or `None` | The exit code, once read. |
| `duration_ms` | `int` or `None` | How long the command ran, once it has ended. |
| `timed_out` | `bool` | Whether the command was stopped at its `timeout`. |

```python
import cere

sb = cere.Sandbox.create(image="python:3.12-slim", timeout=300)
p = sb.exec("sh", "-c", "for i in 1 2 3; do echo line $i; sleep 1; done; echo oops >&2; exit 2")
for line in p.stdout:
    print("got", line, end="")
print(p.wait(), p.stderr.read(), end="")
p = sb.exec("sleep", "10", timeout=2)
print(p.wait(), p.timed_out)
sb.terminate()
```

```
got line 1
got line 2
got line 3
2 oops
124 True
```

## Allow

```python
@dataclass
class Allow:
    host: str
    methods: Sequence[str] = ["GET"]
    path_prefix: str | None = None
    credential: str | None = None
```

One egress rule: the sandbox may call `host` (exact, or `*.example.com` for any name under `example.com`, not `example.com` itself) with these methods, optionally only under `path_prefix`. `credential` names a [secret](#secret) the egress proxy adds to those requests; the sandbox never sees its value. [Egress and credentials](https://docs.compute.dev.ddcdragon.com/concepts/egress-and-credentials/) explains the rules.

| Method | Returns | Meaning |
|---|---|---|
| `Allow.parse(rule)` | `Allow` | A rule as the CLI writes it, `host[:METHODS[:path_prefix[:credential]]]`; methods are comma-separated and default to `GET`. Raises `ValueError` for a rule with no host, no methods, or a path prefix not starting with `/`. |
| `Allow.from_json(d)` | `Allow` | A rule from its JSON, as `Sandbox.data["egress"]["allow"]` holds it. |
| `to_json()` | `dict` | The rule as the API takes it, methods upper case. |

```python
print(cere.Allow.parse("api.github.com:GET,HEAD::github-readonly"))
print(cere.Allow("pypi.org", ["get"], path_prefix="/pypi/").to_json())
```

```
Allow(host='api.github.com', methods=['GET', 'HEAD'], path_prefix=None, credential='github-readonly')
{'host': 'pypi.org', 'methods': ['GET'], 'path_prefix': '/pypi/'}
```

On a running sandbox, `allow`, `remove_egress` and `set_egress` change the rules, and the egress log records each change:

```python
import cere

sb = cere.Sandbox.create(image="python:3.12-slim", timeout=300,
                         egress=[cere.Allow("pypi.org", ["GET"], path_prefix="/pypi/")])
fetch = "import urllib.request as u; print(u.urlopen('https://pypi.org/pypi/requests/json').status)"
print(sb.exec("python", "-c", fetch).stdout.read(), end="")
print(sb.allow("files.pythonhosted.org", "pypi.org:HEAD:/pypi/"))
print(sb.remove_egress("pypi.org", methods=["HEAD"]))
print(sb.set_egress([]))
print(sb.exec("python", "-c", fetch).wait())
for e in cere.egress_log(sb.object_id):
    print(e["decision"], e["method"], e["host"], e["status"], e["reason"])
sb.terminate()
```

```
200
[Allow(host='files.pythonhosted.org', methods=['GET'], path_prefix=None, credential=None), Allow(host='pypi.org', methods=['GET', 'HEAD'], path_prefix='/pypi/', credential=None)]
[Allow(host='files.pythonhosted.org', methods=['GET'], path_prefix=None, credential=None), Allow(host='pypi.org', methods=['GET'], path_prefix='/pypi/', credential=None)]
[]
1
policy GET pypi.org None rule removed
policy GET files.pythonhosted.org None rule removed
policy GET pypi.org None rule added
policy GET,HEAD pypi.org None rule removed
policy GET,HEAD pypi.org None rule added
policy GET files.pythonhosted.org None rule added
policy GET pypi.org None rule removed
allowed GET pypi.org 200 None
```

A rule whose methods change is logged as removed and added. The refused request after `set_egress([])` reaches the log a moment later.

## Secret

Secrets are held by the egress proxy, encrypted and scoped to the token's bucket. An egress rule names one (`Allow(..., credential="name")`) and the proxy sets it as a header on the requests that rule allows, and only on the hosts the secret is bound to. A value goes in and never comes out. All methods are static.

### Secret.set

```python
Secret.set(name: str, *, header: str, value: str, hosts: Sequence[str], client: Client = None) -> None
```

Store, or replace, a secret: the proxy sets `header: value` on requests to `hosts` only.

| Parameter | Type | Meaning |
|---|---|---|
| `name` | `str` | Lower-case letters, digits and `-`, at most 63 characters. |
| `header` | `str` | The request header the proxy sets, for example `Authorization`. |
| `value` | `str` | The header value, at most 8 KiB. For a bearer token, pass `"Bearer " + token`. |
| `hosts` | `Sequence[str]` | The only hosts the value is sent to: exact host names, or `"*.example.com"` for one more label. A sandbox rule naming the secret for any other host is refused at create. |
| `client` | `Client` | The client to call with. |

Storing again replaces the value and the hosts together. Raises `ValueError` for a bad name, an empty header, value or host list, or a host that is a URL.

### Secret.set_from_login

```python
Secret.set_from_login(name: str, hosts: Sequence[str] = None, client: Client = None) -> None
```

Store the token the client calls the API with as `name`: `Authorization: Bearer <token>`, bound to the cluster's inference gateway (`inference-gateway.<the API's domain>`; `hosts` overrides it). That gateway takes it as the model key for your bucket, so `cere.Secret.set_from_login("ddc-inference")` stores the example agents' model key. The secret stops working when the login expires (`cere whoami` shows when); store it again after the next `cere login`. The same as `cere secret set <name> --from-login`.

### Secret.list and Secret.delete

```python
Secret.list(client: Client = None) -> List[dict]
Secret.delete(name: str, client: Client = None) -> None
```

`list` returns `[{name, type, header, hosts, created_at, updated_at}]`, never values. `delete` removes a secret; a running sandbox whose rules name it gets `502` on that host.

```python
import secrets, cere

cere.Secret.set("docs-ref-example", header="X-Api-Key", value=secrets.token_hex(16), hosts=["api.example.com"])
for s in cere.Secret.list():
    print(s["name"], s["header"], s["hosts"])
cere.Secret.delete("docs-ref-example")
```

```
ddc-inference Authorization ['inference-gateway.compute.dev.ddcdragon.com']
docs-ref-example X-Api-Key ['api.example.com']
github-readonly Authorization ['api.github.com']
```

## Agent

An agent definition (`cere.agent/v1`). A run is a sandbox labelled `cere.kind=agent-run` that the SDK drives: it writes the definition and the input into it, runs the harness, reads `/workspace/output.json`, and terminates it, keeping the output and the transcript. [Agents](https://docs.compute.dev.ddcdragon.com/concepts/agents/) explains definitions and runs; the [Agents guide](https://docs.compute.dev.ddcdragon.com/guides/agents/) has the examples.

### Loading a definition

```python
Agent(definition: Dict[str, Any], raw: bytes = None)
Agent.from_dict(d: Dict[str, Any]) -> Agent
Agent.from_file(path: str | os.PathLike) -> Agent
Agent.from_bucket(name: str, client: Client = None) -> Agent
Agent.list_bucket(client: Client = None) -> List[str]
agent.push(client: Client = None) -> str
```

Each constructor validates the definition and raises `ValueError` listing every problem. `from_dict` copies the dict; `from_file` keeps the file's bytes, which the sandbox gets as `/workspace/agent.json`. `from_bucket` reads `cere/agents/<name>.json` from the bucket and raises `KeyError` when there is none; `list_bucket` returns the names of the definitions there; `push` stores the definition as `cere/agents/<name>.json` and returns that key. The three bucket methods need an S3 credential ([`cere login`](https://docs.compute.dev.ddcdragon.com/reference/cli/#cere-login)); without one they raise `cere._s3.NotConfigured`, and an S3 error raises `cere._s3.S3Error`.

| Attribute or method | Type | Meaning |
|---|---|---|
| `definition` | `dict` | The definition. |
| `name`, `harness` | `str` | Its `name` and `harness` (`claude-code` or `container`). |
| `json()` | `bytes` | The definition as written. |
| `needed_secrets(egress=())` | `List[str]` | The secrets a run names: the model's credential, then each egress rule's. |
| `check_secrets(egress=(), client=None)` | `None` | Raise [`MissingSecretsError`](#missingsecretserror) when the bucket lacks one of them. |
| `model_rule()` | `Allow` | The egress rule a run adds for the model: `GET` and `POST` on the model's host and path, with its credential. |
| `command()` | `List[str]` | What a run executes: the definition's `command` for the `container` harness, the agent runner for `claude-code`. |
| `create_request(run_id, egress=(), labels=None)` | `dict` | The sandbox a run asks for. |

### Agent.run

```python
agent.run(input: str, *, egress: Sequence[Allow] = (), files: Dict[str, str | bytes] = None,
          on_event: Callable[[str, Dict[str, Any]], None] = None, labels: Dict[str, str] = None,
          keep: bool = False, save_to_bucket: bool = None, start_timeout: float = 600,
          client: Client = None) -> AgentResult
```

Run the agent on `input` in a new sandbox.

| Parameter | Type | Default | Meaning |
|---|---|---|---|
| `input` | `str` | required | The input, written to `/workspace/input.txt`. |
| `egress` | list of `Allow` | none | Extra egress rules for this run. |
| `files` | `Dict[str, str \| bytes]` | none | Extra files, path → content; a relative path is under `/workspace`. |
| `on_event` | `(name, fields) -> None` | none | Receives the run's events: `sandbox`, `log`, `text`, `tool_call`, `tool_result`, `denied`, `output`, `done`. |
| `labels` | `Dict[str, str]` | none | Extra labels; the `cere.` prefix is reserved. |
| `keep` | `bool` | `False` | Leave the sandbox running after the run. |
| `save_to_bucket` | `bool` | `None` | Copy the output and transcript to `cere/runs/<sandbox-id>/` in the bucket. `None`: when an S3 credential is configured. |
| `start_timeout` | `float` | `600` | Seconds to wait for the sandbox to run. |
| `client` | `Client` | the default | The client to call with. |

The sandbox gets the definition's `resources` (default 1 CPU, 2048 MiB) and its `timeout_s` (default 900) plus 120 seconds. Unless `keep`, the run ends by terminating the sandbox, keeping `/workspace/output.json`, `output.md`, `transcript.jsonl`, `agent.json` and `input.txt`, and recording the result as its exit reason. Raises `MissingSecretsError` before creating anything when the bucket lacks a secret the run names, and `CereError` for a failure of the API; the agent's own failure is `AgentResult.error`.

`research.json` is one of the [example agents](https://docs.compute.dev.ddcdragon.com/guides/agents/#the-example-agents).

```python
import cere

agent = cere.Agent.from_file("research.json")
result = agent.run("In two sentences: how does gVisor isolate containers? Cite https://gvisor.dev/docs/",
                   on_event=lambda name, fields: print("event", name) if name in ("sandbox", "done") else None)
print(result.output)
print(repr(result.error), result.turns, result.tool_calls, result.sandbox["status"])
print(cere.run_outcome(result.sandbox))
print(len(result.transcript()), "transcript lines")
```

```
event sandbox
event done
gVisor isolates containers by replacing the host kernel's role with a per-sandbox, user-space application kernel written in Go: the Sentry intercepts and responds to the application's system calls itself rather than passing them through to the host kernel, ... (gvisor.dev docs, https://gvisor.dev/docs/, read 2026-11-25). ...
'' 2 1 terminated
RunOutcome(state='succeeded', detail='')
38 transcript lines
```

## AgentResult

What `Agent.run` returns.

| Field | Type | Meaning |
|---|---|---|
| `run_id` | `str` | The run's ID (the sandbox's `cere.run` label). |
| `sandbox_id` | `str` | The run's sandbox. |
| `agent`, `harness` | `str` | The definition's name and harness. |
| `output` | `str` | The agent's answer. |
| `turns`, `tool_calls` | `int` | How many model turns and tool calls the run took. |
| `model_usage` | `dict` | The model's token counts, as the harness reports them (`input_tokens`, `output_tokens`, ...). |
| `error` | `str` | The agent's own failure (the harness, the model, a non-zero exit); `""` when it worked. |
| `exit_code` | `int` | The harness's exit code, `-1` when it reported none. |
| `sandbox` | `dict` | The sandbox's last state: terminated with its final usage, or running with `keep=True`. |
| `bucket_keys` | `List[str]` | The keys the outputs were copied to in the bucket. |
| `store_error` | `str` | Why the outputs did not reach the bucket. |
| `duration_ms` | `int` | How long the run took. |

```python
result.transcript(client: Client = None) -> List[dict]
```

`transcript()` reads the run's transcript (`/workspace/transcript.jsonl`) from the sandbox's retained files, one dict per line.

## MissingSecretsError

```python
class MissingSecretsError(ValueError):
    missing: List[str]
```

A run names secrets the bucket does not hold. `missing` lists them, the model's first; the message says what each is for and how to store it. `Agent.run` and `Agent.check_secrets` raise it before anything is created.

```python
d = json.load(open("research.json"))
d["model"]["credential"] = "docs-model-key"
try:
    cere.Agent.from_dict(d).check_secrets()
except cere.MissingSecretsError as e:
    print(e.missing)
    print(e)
```

```
['docs-model-key']
the run needs the secret docs-model-key, which the bucket does not hold (cere.Secret.list() shows what it holds):
  docs-model-key: the model's key (glm-5.3 at https://inference-gateway.compute.dev.ddcdragon.com/anthropic); that gateway takes your login token as the key for your bucket, and the secret stops working when the token expires (cere whoami shows when)
    cere.Secret.set_from_login("docs-model-key")   (CLI: cere secret set docs-model-key --from-login)
```

## RunOutcome and run_outcome

```python
@dataclass
class RunOutcome:
    state: str
    detail: str = ""

run_outcome(sandbox: Sandbox | dict, client: Client = None) -> RunOutcome
```

The result of the run in a sandbox, whichever client started it. `state` is `running`, `succeeded`, `failed`, `stopped`, `ended` (the sandbox ended without its client recording a result) or `unknown`; `detail` says why. `sandbox` is a run's `Sandbox` or its JSON (`AgentResult.sandbox`). A run whose client recorded no result is read from its kept `output.json`.

```python
for run in cere.Sandbox.list(label="cere.kind=agent-run", limit=3):
    print(run.data["labels"]["cere.agent"], run.object_id, cere.run_outcome(run))
```

```
research sb-01m88rw1amadav638z59jzgmfv RunOutcome(state='succeeded', detail='')
sre sb-01m88qjq6jnkxe7zjm340wv5pm RunOutcome(state='succeeded', detail='')
sre sb-01m88h6p9tyv6ts6hm9v0we6xy RunOutcome(state='succeeded', detail='')
```

## Usage

```python
@dataclass
class Usage:
    wall_s: float; cpu_s: float; memory_peak_mib: float; memory_mib_s: float; ram_gib_s: float
    gpu_s: float; net_egress_bytes: int; net_ingress_bytes: int; disk_peak_mib: float
    billing_basis: str; reserved_cpu_s: float; reserved_ram_gib_s: float
    billed_cpu_s: float; billed_ram_gib_s: float
```

What a sandbox used, measured on its node, and what it is billed. `Sandbox.usage()` and `Sandbox.last_usage` return one.

| Field | Meaning |
|---|---|
| `wall_s` | Seconds the sandbox has run. |
| `cpu_s` | Measured CPU-seconds. |
| `memory_peak_mib`, `memory_mib_s`, `ram_gib_s` | Measured memory: peak in MiB, MiB-seconds and GiB-seconds. |
| `gpu_s` | GPU-seconds; sandboxes have no GPU. |
| `net_egress_bytes`, `net_ingress_bytes` | Bytes out of and into the sandbox. |
| `disk_peak_mib` | Peak size of the sandbox's writable filesystem. |
| `billing_basis` | `reserved` (the reservation for as long as the sandbox runs, or the measured amount where that is more) or `measured`. |
| `reserved_cpu_s`, `reserved_ram_gib_s` | The reservation over `wall_s`. |
| `billed_cpu_s`, `billed_ram_gib_s` | What is billed. |

`usage.billing(cpu=None, memory_mib=None)` returns the billed line the CLI prints; `cpu` and `memory_mib` are the reservation, read from the usage when left out. `str(usage)` adds the measured amounts. `Usage.from_json(d)` builds one from the API's `usage` object. [Resources and billing](https://docs.compute.dev.ddcdragon.com/concepts/resources-and-billing/) explains reserved and measured.

A sandbox whose main process prints two lines and exits; `logs()` streams them, and `last_usage` holds the final usage:

```python
import cere

sb = cere.Sandbox.create("sh", "-c", "echo ready; sleep 3; echo done", image="python:3.12-slim", timeout=60)
for stream, text in sb.logs():
    print(stream, text, end="")
print(sb.wait(), sb.exit_reason)
u = sb.refresh().last_usage
print(u.billing_basis, u.wall_s, u.billed_cpu_s, u.cpu_s)
print(u)
```

```
stdout ready
stdout done
0 exited with code 0
reserved 3.007 3.007 0.105
billed 1.0 vCPU × 3.0 s = 3.0 CPU-s (measured 0.1), 1.0 GiB × 3.0 s = 3.0 GiB-s (measured 0.0); measured wall 3.0s, cpu 0.10s, memory peak 25 MiB, 0.03 GiB-s, net out 0 B in 516 B, disk peak 0.0 MiB
```

## usage_records

```python
usage_records(sandbox_id: str = None, *, since: str | datetime = None, limit: int = 100,
              client: Client = None) -> List[dict]
```

The bucket's usage records, newest first: one per sandbox per minute plus a final one, each signed by the node that ran the sandbox. `since` is an RFC 3339 string or a `datetime` (naive means UTC); `limit=None` returns every record. Each record is a dict: `record_id`, `sandbox_id`, `period_start`, `period_end`, `final`, `exit_reason`, the measured `cpu_s`, `ram_gib_s`, `memory_peak_mib`, `net_egress_bytes`, `net_ingress_bytes`, `disk_peak_mib`, and the billing `billing_basis`, `wall_s`, `reserved_cpu`, `reserved_memory_mib`, `reserved_cpu_s`, `reserved_ram_gib_s`, `billed_cpu_s`, `billed_ram_gib_s`, `cpu_units`, `ram_units` (decimal strings: the billed amounts × 10<sup>11</sup>), `tca_id` and `dac_status` (whether the node has delivered the record). [Usage](https://docs.compute.dev.ddcdragon.com/concepts/usage/) explains the fields.

```python
for r in cere.usage_records(sandbox_id="sb-01m89a3q0xca1r5j8f54xg3zhp"):
    print(r["period_end"], r["final"], r["billing_basis"], r["billed_cpu_s"], r["cpu_s"])
```

```
2026-11-25T12:15:58.589994Z True reserved 31.098818 0.198811
```

## egress_log

```python
egress_log(sandbox_id: str = None, *, since: str | datetime = None, until: str | datetime = None,
           decision: str = None, limit: int = 100, client: Client = None) -> List[dict]
```

Every request the bucket's sandboxes made through the egress proxy, allowed or refused, newest first. Each entry is a dict: `id`, `ts`, `sandbox_id`, `host`, `method`, `path`, `status`, `decision`, `reason`, `credential`, `bytes_up`, `bytes_down`, `duration_ms`, and more. `decision` filters on `allowed`, `denied`, `error` or `policy`: a change of a sandbox's rules, one entry per rule added or removed, with `reason` `rule added` or `rule removed`. `since` and `until` are RFC 3339 strings or `datetime`s; `limit=None` returns every entry.

```python
for e in cere.egress_log(decision="denied", since="2026-11-25T00:00:00Z", limit=2):
    print(e["ts"], e["sandbox_id"], e["decision"], e["method"], e["host"], e["reason"])
```

```
2026-11-25T09:00:57.222235Z sb-01m88yzdzw0tr5s8jjefmd7vmy denied CONNECT example.com host not in the sandbox's allow-list
2026-11-25T09:00:54.642356Z sb-01m88yzdzw0tr5s8jjefmd7vmy denied CONNECT example.com host not in the sandbox's allow-list
```

## Client

```python
Client(api_url: str = None, token: str = None, timeout: float = 60.0)
default_client() -> Client
set_default_client(client: Client | None) -> None
```

`Client` calls the API with an access token. Left out, `api_url` and `token` come from the [configuration](#configuration); `timeout` is the seconds a call may take. A client with no token raises `CereError` 401 `unauthenticated`. Its attributes are `api_url`, `token`, `timeout` and `s3` (the S3 settings for agent definitions).

`default_client()` returns the client that calls given no `client=` use, made from the configuration on first use. `set_default_client(client)` replaces it; `None` makes the next call read the configuration again.

| Method | Returns | Meaning |
|---|---|---|
| `call(method, path, *, query=None, body=None, timeout=None)` | decoded JSON, `None` for 204 | A JSON request to the API, for example `call("GET", "/v1/secrets")`. |
| `get_bytes(path, *, query=None, timeout=None)` | `bytes` | A raw `GET`. |
| `put_bytes(path, data, *, query=None, timeout=None)` | `None` | A raw `PUT`. |
| `stream(method, path, *, query=None, body=None, timeout=None)` | iterator of `(event, data)` | A request whose answer is an event stream; `timeout` is the longest silence allowed. An `error` event raises `CereError`. |
| `pages(path, query=None, limit=None)` | `list` | Every item of a paged listing, following `next_cursor`, up to `limit`. |

The paths are the [HTTP API](https://docs.compute.dev.ddcdragon.com/reference/http-api/)'s.

```python
c = cere.Client(api_url="https://agent-gateway.compute.dev.ddcdragon.com")
print(c, c.timeout)
print(len(cere.Sandbox.list(limit=2, client=c)))
cere.set_default_client(c)
print(cere.default_client() is c)
```

```
Client('https://agent-gateway.compute.dev.ddcdragon.com') 60.0
2
True
```

## Related

- [Next: HTTP API](https://docs.compute.dev.ddcdragon.com/reference/http-api/)
- [CLI](https://docs.compute.dev.ddcdragon.com/reference/cli/)
- [Sandboxes guide](https://docs.compute.dev.ddcdragon.com/guides/sandboxes/)
- [Agents guide](https://docs.compute.dev.ddcdragon.com/guides/agents/)
- [Clusters and endpoints](https://docs.compute.dev.ddcdragon.com/reference/clusters/)
