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

# SDK reference

> Every Megan SDK class, method, argument, and return type.

Everything is importable from the top-level package:

```python theme={null}
from cadenza_cli import (
    MeganTK, MeganSession, Anticipator,
    Decision, ProtectResult,
    MeganTKError, AuthRequired,
)
```

***

## `MeganTK`

The client, bound to one account's token. Construct once and reuse.

```python theme={null}
MeganTK(api_key=None, *, api_url=None, timeout=30.0)
```

| Argument  | Type          | Default    | Purpose                                                                                       |
| --------- | ------------- | ---------- | --------------------------------------------------------------------------------------------- |
| `api_key` | `str \| None` | resolved   | The token. If `None`, resolved from `CADENZA_API_KEY`, `CADENZA_TOKEN`, then the CLI session. |
| `api_url` | `str \| None` | hosted API | Base URL override. Falls back to `CADENZA_API_URL`, then `https://www.api.cadenzalabs.xyz`.   |
| `timeout` | `float`       | `30.0`     | Per-request timeout, seconds.                                                                 |

Raises `AuthRequired` at construction if no key can be resolved.

### Methods

| Method                                                                                       | Returns        | Description                                                                   |
| -------------------------------------------------------------------------------------------- | -------------- | ----------------------------------------------------------------------------- |
| `version()`                                                                                  | `dict`         | `{service, megantk_version, api_version}`. Open route — no auth, not metered. |
| `ping()`                                                                                     | `bool`         | `True` if the token authenticates (raises otherwise).                         |
| `usage(days=30)`                                                                             | `dict`         | Your metered consumption. See [Usage](/megantk/usage#the-rollup-fields).      |
| `session(objective, milestones, *, ring_radii=None, obstacle_block_radius=0.8, config=None)` | `MeganSession` | Open a token session.                                                         |
| `anticipator(actions=(), *, lead=1.4, guard=0.8, min_events=2)`                              | `Anticipator`  | Open a disturbance anticipator.                                               |

#### `session(...)`

| Argument                | Type                      | Default | Purpose                                                           |
| ----------------------- | ------------------------- | ------- | ----------------------------------------------------------------- |
| `objective`             | `str`                     | —       | The goal the token pursues.                                       |
| `milestones`            | `Sequence[str]`           | —       | Ordered milestone chain (at least one).                           |
| `ring_radii`            | `Sequence[float] \| None` | `None`  | One shrinking radius per milestone. Provide to enable `perceive`. |
| `obstacle_block_radius` | `float`                   | `0.8`   | How close an obstacle must be to block (perception path).         |
| `config`                | `dict \| None`            | `None`  | Optional MeganToken config overrides.                             |

#### `anticipator(...)`

| Argument     | Type            | Default | Purpose                                             |
| ------------ | --------------- | ------- | --------------------------------------------------- |
| `actions`    | `Sequence[str]` | `()`    | Protective action names to register.                |
| `lead`       | `float`         | `1.4`   | Seconds to start protecting before a predicted hit. |
| `guard`      | `float`         | `0.8`   | Seconds to keep protecting after.                   |
| `min_events` | `int`           | `2`     | Disturbances observed before the period is trusted. |

***

## `MeganSession`

A live token session. Returned by `MeganTK.session()`. A **context manager** —
`close()` runs on `__exit__`.

**Attributes:** `session_id: str`, `objective: str`, `milestones: list[str]`,
`perception: bool`.

| Method                                   | Returns    | Description                                                                                                              |
| ---------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------ |
| `step(reached=(), obstacles=())`         | `Decision` | Milestone path. `reached`: milestone indices satisfied. `obstacles`: `{"id","milestone"}` dicts or `(id, index)` tuples. |
| `perceive(position, goal, obstacles=())` | `Decision` | Perception path (session must have `ring_radii`). `obstacles`: `{"id","position"}` dicts or `(id, position)` tuples.     |
| `status()`                               | `dict`     | `{session_id, session_step, objective, perception}`.                                                                     |
| `close()`                                | `bool`     | Delete server-side. Idempotent — `True` first time, `False` after.                                                       |

***

## `Anticipator`

A live disturbance anticipator. Returned by `MeganTK.anticipator()`. A **context
manager**.

**Attributes:** `anticipator_id: str`, `actions: list[str]`.

| Method                 | Returns         | Description                                                                              |
| ---------------------- | --------------- | ---------------------------------------------------------------------------------------- |
| `disturbance(t)`       | `dict`          | Log a disturbance at time `t` (seconds). Returns `{anticipator_id, ready, best_action}`. |
| `outcome(name, saved)` | `dict`          | Record whether registered action `name` preserved the outcome.                           |
| `protect(t)`           | `ProtectResult` | Should you protect at time `t`?                                                          |
| `status()`             | `dict`          | `{anticipator_id, ready, best_action}`.                                                  |
| `close()`              | `bool`          | Delete server-side. Idempotent.                                                          |

***

## `Decision`

Frozen value object returned by `step` / `perceive`.

| Field          | Type                | Meaning                                               |
| -------------- | ------------------- | ----------------------------------------------------- |
| `route`        | `str`               | `'continue'` or `'adapt'`.                            |
| `frontier`     | `str \| None`       | The milestone attention is on (e.g. `'milestone_1'`). |
| `session_step` | `int`               | Monotonic step counter.                               |
| `adapt`        | `bool` *(property)* | `True` when `route == 'adapt'`.                       |

## `ProtectResult`

Frozen value object returned by `protect`.

| Field            | Type          | Meaning                                         |
| ---------------- | ------------- | ----------------------------------------------- |
| `should_protect` | `bool`        | Engage a protective action now?                 |
| `best_action`    | `str \| None` | Which registered action is currently best.      |
| `ready`          | `bool`        | Whether the rhythm is learned enough to act on. |

***

## Errors

```python theme={null}
from cadenza_cli import MeganTKError, AuthRequired
```

| Exception                                     | Raised when                                                                                                                                               |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AuthRequired` *(subclass of `MeganTKError`)* | No key could be resolved, or the server returned **401/403** (invalid/revoked token, deactivated account).                                                |
| `MeganTKError`                                | Any other API problem — bad request (422), rate limit (429), not found (404), or an unreachable API. The message is the server's human-readable `detail`. |

```python theme={null}
from cadenza_cli import MeganTK, AuthRequired, MeganTKError

try:
    tk = MeganTK()
    d = tk.session("goal", ["a", "b"]).step(reached=[0])
except AuthRequired as e:
    ...   # fix the key / sign in
except MeganTKError as e:
    ...   # transient / bad input — inspect str(e)
```

See [Building deep](/megantk/building-deep#error-handling) for retry and rate-limit
patterns.
